Project NOMAD is an offline-first knowledge and education server. Wikipedia, thousands of books, courses, maps, and optional local AI, all running on hardware you own with no internet required.
TypeScript
feat(AI): add opt-in relevance check for off-topic retrieval
jakeaturnera915cdcfc9a9
diff --git a/admin/app/controllers/settings_controller.ts b/admin/app/controllers/settings_controller.tsindex 930a870a..a2e428fe 100644--- a/admin/app/controllers/settings_controller.ts+++ b/admin/app/controllers/settings_controller.ts@@ -9,6 +9,7 @@ import { inject } from '@adonisjs/core'import type { HttpContext } from '@adonisjs/core/http'import env from '#start/env'import { parseMinRelevance } from '../utils/misc.js'+import { isRelevanceCheckEnabled } from '../utils/relevance_judge.js'import { parseResponseStyle } from '../utils/sampler.js'import { RAG_MIN_FINAL_SCORE } from '../../constants/ollama.js'@@ -80,6 +81,7 @@ export default class SettingsController {const ragEnabled = await KVStore.getValue('rag.enabled')const contextWindow = await KVStore.getValue('ai.contextWindow')const minRelevance = await KVStore.getValue('rag.minRelevance')+ const relevanceCheck = await KVStore.getValue('rag.relevanceCheck')const responseStyle = await KVStore.getValue('ai.responseStyle')// Resolved window per installed model, so the setting shows what "Auto"// actually produced rather than leaving the user to guess. Best-effort:@@ -110,6 +112,7 @@ export default class SettingsController {// Sent as the resolved number so the select can match an option// without duplicating the "unset means the default" rule in the UI.minRelevance: parseMinRelevance(minRelevance, RAG_MIN_FINAL_SCORE),+ relevanceCheck: isRelevanceCheckEnabled(relevanceCheck),// Resolved rather than raw, for the same reason: unset means 'auto',// and the select shouldn't have to know that.responseStyle: parseResponseStyle(responseStyle),diff --git a/admin/app/services/eval_generation_service.ts b/admin/app/services/eval_generation_service.tsindex 98db0a28..4c64b5aa 100644--- a/admin/app/services/eval_generation_service.ts+++ b/admin/app/services/eval_generation_service.ts@@ -296,6 +296,9 @@ export class EvalGenerationService {skipQueryRewrite: options.skipQueryRewrite || isMock,// A developer's personal NOMAD.md would silently skew every score.skipNomadMd: true,+ // Pinned off rather than read from `rag.relevanceCheck`, for the same+ // reason as minFinalScore. eval:retrieval --judge-model measures it.+ relevanceCheckModel: null,}if (options.mode === 'oracle') {diff --git a/admin/app/services/eval_retrieval_service.ts b/admin/app/services/eval_retrieval_service.tsindex 112026e4..6d71100d 100644--- a/admin/app/services/eval_retrieval_service.ts+++ b/admin/app/services/eval_retrieval_service.ts@@ -1,5 +1,6 @@import { EvalCorpusService } from '#services/eval_corpus_service'import { RagService } from '#services/rag_service'+import { RelevanceJudgeService } from '#services/relevance_judge_service'import { inject } from '@adonisjs/core'import { KB_EVAL_COLLECTION } from '../../constants/kb_collections.js'import {@@ -29,6 +30,33 @@ export type RetrievalRunOptions = {kValues?: number[]/** Score the raw dense / reranked / diversified orderings separately. */ablate?: boolean+ /** Also return every golden's full pre-floor candidate pool (see RetrievalStages.candidates). */+ dump?: boolean+ /**+ * Run the relevance check on this model after the floor, as chat does when it+ * is enabled. Unset keeps this tier model-free and deterministic.+ */+ judgeModel?: string+}++/** What the relevance check cost and did, when `judgeModel` was set. */+export type JudgeStats = {+ model: string+ calls: number+ /** Calls that failed open (timeout, error, unusable verdict). */+ failures: number+ rejected: number+ meanMs: number+ maxMs: number+}++/** One golden's full candidate pool, for simulating a relevance gate offline. */+export type CandidatePool = {+ id: string+ tags: string[]+ expectRefusal: boolean+ relevantDocIds: string[]+ candidates: Array<{ docId: string | null; score: number; semanticScore: number | null }>}export type StageAblation = {@@ -48,6 +76,9 @@ export type RetrievalRunResult = {* collection filter leaked and the run is measuring the wrong corpus.*/unresolvedChunks: number+ /** Every golden's candidate pool, when `dump` was requested. */+ pools: CandidatePool[] | null+ judge: JudgeStats | null}/**@@ -69,7 +100,8 @@ export type RetrievalRunResult = {export class EvalRetrievalService {constructor(private ragService: RagService,- private corpusService: EvalCorpusService+ private corpusService: EvalCorpusService,+ private judgeService: RelevanceJudgeService) {}async run(goldens: Golden[], options: RetrievalRunOptions = {}): Promise<RetrievalRunResult> {@@ -87,19 +119,32 @@ export class EvalRetrievalService {const denseCases: RetrievalCase[] = []const rerankedCases: RetrievalCase[] = []const diversifiedCases: RetrievalCase[] = []+ const pools: CandidatePool[] = []+ const recordStages = options.ablate || options.dump+ const judgeMs: number[] = []+ let judgeFailures = 0+ let judgeRejected = 0let unresolvedChunks = 0for (const golden of goldens) {const stages: RetrievalStages = {}- const docs = await this.ragService.searchSimilarDocuments(+ let docs = await this.ragService.searchSimilarDocuments(golden.query,topK,scoreThreshold,KB_EVAL_COLLECTION,- options.ablate ? stages : undefined,+ recordStages ? stages : undefined,minFinalScore)+ if (options.judgeModel && docs.length > 0) {+ const verdict = await this.judgeService.judge(golden.query, docs, options.judgeModel)+ judgeMs.push(verdict.ms)+ if (!verdict.judged) judgeFailures+++ judgeRejected += verdict.rejected+ docs = verdict.kept+ }+const retrieved: ScoredChunk[] = docs.map((d) => {const docId = docIdFromSource(d.metadata?.source)if (!docId) unresolvedChunks++@@ -108,6 +153,20 @@ export class EvalRetrievalService {cases.push(toCase(golden, retrieved))+ if (options.dump) {+ pools.push({+ id: golden.id,+ tags: golden.tags,+ expectRefusal: golden.expectRefusal,+ relevantDocIds: golden.relevantDocIds,+ candidates: (stages.candidates ?? []).map((c) => ({+ docId: docIdFromSource(c.source),+ score: c.score,+ semanticScore: c.semanticScore ?? null,+ })),+ })+ }+if (options.ablate) {denseCases.push(toCase(golden, stageToChunks(stages.dense)))rerankedCases.push(toCase(golden, stageToChunks(stages.reranked)))@@ -133,6 +192,17 @@ export class EvalRetrievalService {}: null,unresolvedChunks,+ pools: options.dump ? pools : null,+ judge: options.judgeModel+ ? {+ model: options.judgeModel,+ calls: judgeMs.length,+ failures: judgeFailures,+ rejected: judgeRejected,+ meanMs: judgeMs.length ? judgeMs.reduce((a, b) => a + b, 0) / judgeMs.length : 0,+ maxMs: judgeMs.length ? Math.max(...judgeMs) : 0,+ }+ : null,}}diff --git a/admin/app/services/rag_pipeline_service.ts b/admin/app/services/rag_pipeline_service.tsindex 61ee1b8a..5e372135 100644--- a/admin/app/services/rag_pipeline_service.ts+++ b/admin/app/services/rag_pipeline_service.ts@@ -2,6 +2,7 @@ import { ContextWindowService } from '#services/context_window_service'import { NomadMdService } from '#services/nomad_md_service'import { OllamaService } from '#services/ollama_service'import { RagService } from '#services/rag_service'+import { RelevanceJudgeService } from '#services/relevance_judge_service'import { TokenCalibrationService } from '#services/token_calibration_service'import { inject } from '@adonisjs/core'import logger from '@adonisjs/core/services/logger'@@ -43,7 +44,8 @@ export class RagPipelineService {private ragService: RagService,private nomadMdService: NomadMdService,private contextWindowService: ContextWindowService,- private tokenCalibration: TokenCalibrationService+ private tokenCalibration: TokenCalibrationService,+ private relevanceJudge: RelevanceJudgeService) {}/**@@ -104,9 +106,11 @@ export class RagPipelineService {numCtx: undefined,numPredict: undefined,contextLimits: { maxResults: RAG_DEFAULT_TOP_K, maxTokens: 0 },- timings: { rewriteMs: 0, retrievalMs: 0 },+ timings: { rewriteMs: 0, retrievalMs: 0, relevanceCheckMs: 0 },minFinalScore: 0,chunksBelowFloor: 0,+ relevanceCheckModel: null,+ chunksRejectedByCheck: 0,}// --- Retrieval -------------------------------------------------------@@ -157,6 +161,25 @@ export class RagPipelineService {? ` (${floor.belowFloor} of ${floor.candidates} dropped below the ${minFinalScore} relevance floor)`: ''))++ // Opt-in relevance check (#1341). The floor cannot tell a coherent+ // off-topic question from a real one on a large general-prose library;+ // a model can, at ~8B. Judged against the rewritten query, which is the+ // standalone form of what the user is asking this turn.+ if (relevantDocs.length > 0) {+ const checkModel =+ opts.relevanceCheckModel !== undefined+ ? opts.relevanceCheckModel+ : await this.relevanceJudge.resolveModel(model)+ if (checkModel) {+ const verdict = await this.relevanceJudge.judge(retrievalQuery, relevantDocs, checkModel)+ relevantDocs = verdict.kept+ trace.retrieved = relevantDocs+ trace.relevanceCheckModel = checkModel+ trace.chunksRejectedByCheck = verdict.rejected+ trace.timings.relevanceCheckMs = verdict.ms+ }+ }}}diff --git a/admin/app/services/rag_service.ts b/admin/app/services/rag_service.tsindex 5ad4ebc7..c6e1be91 100644--- a/admin/app/services/rag_service.ts+++ b/admin/app/services/rag_service.ts@@ -1112,6 +1112,11 @@ export class RagService {stagesOut.diversified = diverseResults.slice(0, limit).map((r) => ({ source: r.source, score: r.finalScore }))+ stagesOut.candidates = rerankedResults.map((r) => ({+ source: r.source,+ score: r.finalScore,+ semanticScore: r.score,+ }))}// Return top N results with enhanced metadatadiff --git a/admin/app/services/relevance_judge_service.ts b/admin/app/services/relevance_judge_service.tsnew file mode 100644index 00000000..1f11fbc7--- /dev/null+++ b/admin/app/services/relevance_judge_service.ts@@ -0,0 +1,121 @@+import { OllamaService } from '#services/ollama_service'+import { inject } from '@adonisjs/core'+import logger from '@adonisjs/core/services/logger'+import KVStore from '#models/kv_store'+import { RELEVANCE_CHECK_MAX_TOKENS, SYSTEM_PROMPTS } from '../../constants/ollama.js'+import type { RetrievedChunk } from '../../types/rag.js'+import {+ buildJudgeInput,+ isRelevanceCheckEnabled,+ ON_TOPIC_SCHEMA,+ pickOnTopic,+} from '../utils/relevance_judge.js'+import { resolveStructured } from '../utils/structured_output.js'+import { resolveTasksModel } from '../utils/tasks_model.js'++export type JudgeResult = {+ /** Every chunk when the model said they fit the question, none when it said not. */+ kept: RetrievedChunk[]+ /** How many were dropped. 0 when the check failed open. */+ rejected: number+ /** False when the call failed and every chunk was kept unjudged. */+ judged: boolean+ ms: number+}++/**+ * Asks a model whether the retrieved chunks are about what the user asked, and+ * drops them all when it says no (#1341). Runs after the relevance floor, so it+ * only ever sees the few chunks that were about to be injected and cited.+ *+ * Fails open by design. The floor has already removed the noise; this removes+ * the coherent-but-off-topic remainder. A timeout or a garbled verdict costing+ * one turn that precision is a much smaller failure than an answerable question+ * losing its context because a model misbehaved.+ */+@inject()+export class RelevanceJudgeService {+ constructor(private ollamaService: OllamaService) {}++ /**+ * The model to run the check on this turn, or null to skip it. Opt-in via+ * `rag.relevanceCheck`; runs on the tasks model when one is configured and on+ * the chat model otherwise.+ */+ async resolveModel(chatModel: string): Promise<string | null> {+ try {+ if (!isRelevanceCheckEnabled(await KVStore.getValue('rag.relevanceCheck'))) return null+ } catch (error) {+ logger.warn(+ `[RAG] Failed to read rag.relevanceCheck, skipping the check: ${error instanceof Error ? error.message : error}`+ )+ return null+ }+ return resolveTasksModel(this.ollamaService, chatModel, undefined, '[RAG]')+ }++ async judge(question: string, chunks: RetrievedChunk[], model: string): Promise<JudgeResult> {+ const started = Date.now()+ const unjudged = (): JudgeResult => ({+ kept: chunks,+ rejected: 0,+ judged: false,+ ms: Date.now() - started,+ })+ if (chunks.length === 0 || !question.trim()) return unjudged()++ try {+ const thinkingCapable = await this.ollamaService.checkModelHasThinking(model)+ const response = await this.ollamaService.chat({+ model,+ messages: [+ { role: 'system', content: SYSTEM_PROMPTS.relevance_check },+ {+ role: 'user',+ content: buildJudgeInput(+ question,+ chunks.map((c) => ({+ text: c.text,+ // Titles only from content metadata. A filename is not a claim+ // about what a passage says, and in the eval corpus it would+ // hand the judge the answer ("distractor-…").+ title:+ c.metadata?.full_title || c.metadata?.article_title || c.metadata?.archive_title,+ }))+ ),+ },+ ],+ numPredict: RELEVANCE_CHECK_MAX_TOKENS,+ temperature: 0,+ think: false,+ thinkingCapable,+ format: ON_TOPIC_SCHEMA,+ })++ const verdict = resolveStructured(+ response.message.content.trim(),+ pickOnTopic,+ response.structured === true+ )+ if (!verdict.ok) {+ logger.warn(+ `[RAG] Relevance check on "${model}" returned no usable verdict (${verdict.reason}); keeping all chunks`+ )+ return unjudged()+ }++ const ms = Date.now() - started+ logger.debug(+ `[RAG] Relevance check on "${model}": ${verdict.value ? 'on topic' : 'off topic'} (${chunks.length} chunk(s), ${ms}ms)`+ )+ return verdict.value+ ? { kept: chunks, rejected: 0, judged: true, ms }+ : { kept: [], rejected: chunks.length, judged: true, ms }+ } catch (error) {+ logger.warn(+ `[RAG] Relevance check on "${model}" failed, keeping all chunks: ${error instanceof Error ? error.message : error}`+ )+ return unjudged()+ }+ }+}diff --git a/admin/app/utils/eval/retrieval_metrics.ts b/admin/app/utils/eval/retrieval_metrics.tsindex 29f5d59f..90d1459d 100644--- a/admin/app/utils/eval/retrieval_metrics.ts+++ b/admin/app/utils/eval/retrieval_metrics.ts@@ -225,6 +225,12 @@ export type RetrievalCaseResult = {reciprocalRank: number | null/** True when this case retrieved nothing at all. */empty: boolean+ /**+ * The highest-ranked chunk's scores, or null when nothing was retrieved. Shown+ * for out-of-corpus leaks: the gap between the two says how much of a false+ * positive the reranker's lexical boosts supplied.+ */+ top: { score: number; semanticScore: number | null } | null}export type RetrievalAggregate = {@@ -275,6 +281,10 @@ export function scoreCase(c: RetrievalCase, kValues: number[] = DEFAULT_K_VALUESndcg: byK((k) => ndcgAtK(c.retrieved, c.relevantDocIds, k)),reciprocalRank: reciprocalRank(c.retrieved, c.relevantDocIds),empty: c.retrieved.length === 0,+ top:+ c.retrieved.length === 0+ ? null+ : { score: c.retrieved[0].score, semanticScore: c.retrieved[0].semanticScore ?? null },}}diff --git a/admin/app/utils/relevance_judge.ts b/admin/app/utils/relevance_judge.tsnew file mode 100644index 00000000..23a7ed49--- /dev/null+++ b/admin/app/utils/relevance_judge.ts@@ -0,0 +1,107 @@+/**+ * The pure half of the retrieval relevance check (#1341): the grammar, the+ * setting, and what the judge gets to read.+ *+ * Why a model and not another threshold: on a library holding general prose+ * (Gutenberg, Wikipedia), the nearest chunk to *any* question scores as high as+ * a genuinely relevant one. Measured on the eval corpus with its distractors,+ * the weakest correct top hit scored 0.666 post-rerank while "write me a haiku+ * about autumn leaves" pulled Walden at 0.705. No cutoff on that axis separates+ * the two, so the decision has to be a judgement about the question.+ *+ * Why one verdict for the whole set rather than one per passage: asked+ * passage-by-passage, every model tried (0.5B to 8B) rejected passages that+ * were on-topic but did not spell the answer out, and cost 9-17 points of+ * recall@5. "Are these about what was asked?" is the easier question, and on an+ * 8B model it took off-topic leaks from 67% to 6% for ~5 points of recall. On a+ * 3B model it rejects most real questions, which is why the check is opt-in.+ *+ * Pure so it unit-tests under bare node; RelevanceJudgeService owns the call.+ */++/**+ * Longest excerpt of each passage the judge reads. At 700 characters the window+ * routinely stopped a sentence short of the answer (wound packing, counterpoise+ * length) and the judge rightly said the passage didn't cover it.+ */+export const JUDGE_EXCERPT_CHARS = 1500++/** Anything shorter carries no topical signal; don't let it steer the excerpt. */+const MIN_TERM_LENGTH = 4++export type JudgeablePassage = { text: string; title?: string }++export const ON_TOPIC_SCHEMA = {+ type: 'object',+ properties: { on_topic: { type: 'boolean' } },+ required: ['on_topic'],+ additionalProperties: false,+} as const++export function pickOnTopic(value: any): boolean | null {+ return typeof value?.on_topic === 'boolean' ? value.on_topic : null+}++/**+ * Interpret the stored `rag.relevanceCheck` setting. Off unless explicitly on:+ * the check costs a model call per turn and hurts recall on small models, so+ * nothing short of a deliberate choice should turn it on.+ */+export function isRelevanceCheckEnabled(raw: unknown): boolean {+ return raw === true || raw === 'true'+}++/**+ * The stretch of `text` most about the question, at most `maxChars` long.+ *+ * Chunks run ~3000 characters and the judge sees half of each, so which half+ * matters. Picks the window holding the most occurrences of the question's+ * longer terms, falling back to the start when none appear.+ */+export function excerptFor(text: string, question: string, maxChars = JUDGE_EXCERPT_CHARS): string {+ const clean = text.replace(/\s+/g, ' ').trim()+ if (clean.length <= maxChars) return clean++ const terms = [+ ...new Set(+ question+ .toLowerCase()+ .split(/[^\p{L}\p{N}]+/u)+ .filter((t) => t.length >= MIN_TERM_LENGTH)+ ),+ ]+ const lower = clean.toLowerCase()+ const hits: number[] = []+ for (const term of terms) {+ for (let at = lower.indexOf(term); at !== -1; at = lower.indexOf(term, at + term.length)) {+ hits.push(at)+ }+ }+ if (hits.length === 0) return clean.slice(0, maxChars) + '…'+ hits.sort((a, b) => a - b)++ // Densest window: two pointers over the sorted hit positions.+ let bestStart = hits[0]+ let bestCount = 0+ for (let lo = 0, hi = 0; hi < hits.length; hi++) {+ while (hits[hi] - hits[lo] > maxChars) lo+++ if (hi - lo + 1 > bestCount) {+ bestCount = hi - lo + 1+ bestStart = hits[lo]+ }+ }++ // Open a little before the first hit so the sentence it sits in reads whole.+ const start = Math.max(0, Math.min(bestStart - Math.floor(maxChars / 5), clean.length - maxChars))+ const end = start + maxChars+ return (start > 0 ? '…' : '') + clean.slice(start, end) + (end < clean.length ? '…' : '')+}++/** The user turn of the judge call: the question, then each passage. */+export function buildJudgeInput(question: string, passages: JudgeablePassage[]): string {+ const blocks = passages.map((p, i) => {+ const heading = p.title ? `p${i + 1} (from "${p.title}")` : `p${i + 1}`+ return `${heading}:\n${excerptFor(p.text, question)}`+ })+ return `Question: ${question.trim()}\n\n${blocks.join('\n\n')}`+}diff --git a/admin/commands/eval/retrieval.ts b/admin/commands/eval/retrieval.tsindex 60307eb1..2b8ddeb1 100644--- a/admin/commands/eval/retrieval.ts+++ b/admin/commands/eval/retrieval.ts@@ -33,6 +33,12 @@ export default class EvalRetrieval extends BaseCommand {})declare minFinalScore: string+ @flags.string({+ description:+ 'Run the retrieval relevance check on this model after the floor (default: off, keeping this tier model-free)',+ })+ declare judgeModel: string+@flags.boolean({ description: 'Also score the raw dense, reranked, and diversified orderings' })declare ablate: boolean@@ -55,6 +61,13 @@ export default class EvalRetrieval extends BaseCommand {@flags.boolean({ description: 'Write a JSON + Markdown report to tests/eval/reports/' })declare report: boolean+ @flags.string({+ description:+ "Write every golden's full pre-floor candidate pool (boosted + cosine scores) to this JSON path, " ++ 'for simulating a relevance gate offline',+ })+ declare dump: string+static options: CommandOptions = {startApp: true,}@@ -93,6 +106,8 @@ export default class EvalRetrieval extends BaseCommand {scoreThreshold: this.threshold ? Number.parseFloat(this.threshold) : undefined,minFinalScore: this.minFinalScore ? Number.parseFloat(this.minFinalScore) : undefined,ablate: this.ablate,+ dump: Boolean(this.dump),+ judgeModel: this.judgeModel || undefined,})const elapsed = ((Date.now() - started) / 1000).toFixed(1)@@ -100,6 +115,13 @@ export default class EvalRetrieval extends BaseCommand {`Params: topK=${result.params.topK} threshold=${result.params.scoreThreshold} ` +`minFinalScore=${result.params.minFinalScore} (${elapsed}s)`)+ if (result.judge) {+ const j = result.judge+ this.logger.info(+ `Relevance check: ${j.model} · ${j.calls} calls · rejected ${j.rejected} chunk(s) · ` ++ `${j.failures} failed open · mean ${Math.round(j.meanMs)}ms max ${Math.round(j.maxMs)}ms`+ )+ }this.logger.info('')this.printAggregate('OVERALL', result.overall, result.params.kValues)@@ -133,8 +155,12 @@ export default class EvalRetrieval extends BaseCommand {this.logger.info('=== By tag ===')for (const [tag, agg] of Object.entries(result.byTag).sort()) {const k = result.params.kValues.includes(5) ? 5 : result.params.kValues[0]+ // A refusal-only tag has no recall to report; what it has is the leak rate,+ // which is the number #1341 is about.+ const leak =+ agg.nonEmptyRateOnRefusal === null ? '' : ` leaked=${pct(agg.nonEmptyRateOnRefusal)}`this.logger.info(- ` ${tag.padEnd(20)} n=${String(agg.cases).padStart(3)} recall@${k}=${fmt(agg.recall[k])} ndcg@${k}=${fmt(agg.ndcg[k])}`+ ` ${tag.padEnd(20)} n=${String(agg.cases).padStart(3)} recall@${k}=${fmt(agg.recall[k])} ndcg@${k}=${fmt(agg.ndcg[k])}${leak}`)}@@ -155,6 +181,32 @@ export default class EvalRetrieval extends BaseCommand {this.logger.info('Re-run with --verbose to see which questions and what they retrieved.')}+ // The other failure: a question the corpus cannot answer that retrieved+ // something anyway. Each of these becomes a citation the user sees.+ const leaks = result.cases.filter((c) => c.expectRefusal && !c.empty)+ if (leaks.length > 0) {+ this.logger.info('')+ this.logger.info(`${leaks.length} out-of-corpus question(s) retrieved something anyway`)+ if (this.verbose) {+ this.logger.info('')+ this.logger.info('=== Leaks ===')+ for (const leak of leaks) {+ this.logger.info(` ${leak.id}`)+ const top = leak.top+ ? ` (top final=${leak.top.score.toFixed(3)} semantic=${leak.top.semanticScore?.toFixed(3) ?? 'n/a'})`+ : ''+ this.logger.info(` retrieved: ${leak.retrievedDocIds.join(', ')}${top}`)+ }+ }+ }++ if (this.dump && result.pools) {+ const { writeFile } = await import('node:fs/promises')+ await writeFile(this.dump, JSON.stringify({ fingerprint, params: result.params, pools: result.pools }, null, 2))+ this.logger.info('')+ this.logger.success(`Candidate pools written: ${this.dump}`)+ }+if (this.report) {const meta = await reportService.buildMeta('retrieval', fingerprint, {...result.params,diff --git a/admin/constants/kv_store.ts b/admin/constants/kv_store.tsindex 47c904c4..6953de1d 100644--- a/admin/constants/kv_store.ts+++ b/admin/constants/kv_store.ts@@ -18,6 +18,7 @@ export const SETTINGS_KEYS: KVStoreKey[] = ['rag.defaultIngestPolicy','rag.enabled','rag.minRelevance',+ 'rag.relevanceCheck','autoUpdate.enabled','autoUpdate.windowStart','autoUpdate.windowEnd',diff --git a/admin/constants/ollama.ts b/admin/constants/ollama.tsindex e35513e5..b1f7ebf0 100644--- a/admin/constants/ollama.ts+++ b/admin/constants/ollama.ts@@ -149,6 +149,24 @@ export const RAG_DEFAULT_SCORE_THRESHOLD = 0.3* So nonEmptyRateOnRefusal bottoms out at 0.6 here, and a cutoff tuned to drive* it lower is cutting real documents.*+ * What this floor cannot do (#1341). With general-prose distractors added to the+ * corpus (fingerprint b4ebe5dce8699f5d: Gutenberg excerpts, the Python tutorial,+ * MDN), the `off_topic` suite measures:+ *+ * floor core recall@5 off-topic questions that retrieve something+ * 0.62 0.991 67% (22% without the distractors)+ * 0.65 0.991 33%+ * 0.69 0.934 11%+ *+ * The weakest correct top hit scores 0.666 while "write me a haiku about autumn+ * leaves" pulls Walden at 0.705, so no value here separates the two, and a+ * better-stocked library only makes it worse. 0.65 halves the leaks at no+ * measured recall cost but sits 0.016 under that weakest hit, which is not the+ * margin this default was chosen for. The coherent-but-off-topic case is left to+ * the opt-in relevance check (app/utils/relevance_judge.ts). A cosine floor+ * alongside this one was also tried and loses recall faster than it cuts leaks:+ * the reranker's boosts lift relevant chunks more than irrelevant ones.+ ** Unset `rag.minRelevance` resolves to this value; see app/utils/rag_relevance.ts.*/export const RAG_MIN_FINAL_SCORE = 0.62@@ -211,6 +229,13 @@ export const RAG_PLACEMENT: 'tail' | 'front' = 'tail'*/export const QUERY_REWRITE_MAX_TOKENS = 160+/**+ * Token cap on the retrieval relevance check. The answer is `{"on_topic": true}`,+ * under ten tokens; the rest is headroom, since a truncated verdict is discarded+ * and the turn keeps its chunks unjudged.+ */+export const RELEVANCE_CHECK_MAX_TOKENS = 32+/*** How long Ollama keeps a chat model — and its KV cache — resident after a* request.@@ -344,6 +369,13 @@ Respond with JSON: {"suggestions": ["...", "...", "..."]}title_generation: `You are a title generator. Given the start of a conversation, generate a concise, descriptive title under 50 characters.Respond with JSON: {"title": "..."}`,+ relevance_check: `You check whether search results are about what a user asked.++Answer true if at least one passage is about the same specific subject as the question, even if it does not state the exact answer.++Answer false if the passages only share a word or a loose theme with the question. Also answer false if the user is not asking for information at all: greetings, chit-chat, or asking you to produce something new such as a poem, a joke, a translation, or a letter.++Respond with JSON: {"on_topic": true} or {"on_topic": false}`,query_rewrite: `You are a query rewriting assistant. Your task is to reformulate the user's latest question to include relevant context from the conversation history.diff --git a/admin/inertia/pages/settings/models.tsx b/admin/inertia/pages/settings/models.tsxindex 1c4258d6..df703c3f 100644--- a/admin/inertia/pages/settings/models.tsx+++ b/admin/inertia/pages/settings/models.tsx@@ -28,7 +28,7 @@ export default function ModelsPage(props: {models: {availableModels: NomadOllamaModel[]installedModels: NomadInstalledModel[]- settings: { chatSuggestionsEnabled: boolean; aiAssistantCustomName: string; remoteOllamaUrl: string; ollamaFlashAttention: boolean; autoThinking: boolean; tasksModel: string; ragEnabled: boolean; contextWindow: string; minRelevance: number; responseStyle: string }+ settings: { chatSuggestionsEnabled: boolean; aiAssistantCustomName: string; remoteOllamaUrl: string; ollamaFlashAttention: boolean; autoThinking: boolean; tasksModel: string; ragEnabled: boolean; contextWindow: string; minRelevance: number; relevanceCheck: boolean; responseStyle: string }/** Effective window per installed model, as resolved by ContextWindowService. */resolvedContextWindows?: Record<string, number>}@@ -108,6 +108,7 @@ export default function ModelsPage(props: {const [tasksModel, setTasksModel] = useState(props.models.settings.tasksModel)const [contextWindow, setContextWindow] = useState(props.models.settings.contextWindow)const [minRelevance, setMinRelevance] = useState(String(props.models.settings.minRelevance))+ const [relevanceCheck, setRelevanceCheck] = useState(props.models.settings.relevanceCheck)const [responseStyle, setResponseStyle] = useState(props.models.settings.responseStyle)const [aiAssistantCustomName, setAiAssistantCustomName] = useState(props.models.settings.aiAssistantCustomName@@ -441,6 +442,16 @@ export default function ModelsPage(props: {updateSettingMutation.mutate({ key: 'rag.minRelevance', value: newVal })}}/>+ <Switch+ checked={relevanceCheck}+ disabled={!ragEnabled}+ onChange={(newVal) => {+ setRelevanceCheck(newVal)+ updateSettingMutation.mutate({ key: 'rag.relevanceCheck', value: newVal })+ }}+ label="Double-check knowledge base matches"+ description="Before answering, ask the Tasks Model whether the passages found are actually about your question, and leave them out (and uncited) when they are not. Helps most with large libraries like Wikipedia or Project Gutenberg, where something always looks similar. Needs a capable Tasks Model (about 8B parameters or larger); smaller models reject too many good matches. Adds a short delay to every reply."+ /><Selectname="responseStyle"label="Response Style"diff --git a/admin/tests/eval/README.md b/admin/tests/eval/README.mdindex 3def872b..f6169429 100644--- a/admin/tests/eval/README.md+++ b/admin/tests/eval/README.md@@ -39,10 +39,32 @@ invalidate every committed baseline.|---|---|| `core` | The default 99 questions. Retrieval and generation quality. || `long_context` | Conversations long enough to exercise the budget planner. |+| `off_topic` | Coherent questions the corpus cannot answer, plus distractor controls (#1341). |`--suite a,b` runs several. `eval:corpus` always validates every suite, since amalformed fixture should fail validation whether or not it is in the default run.+### The `off_topic` suite++Eighteen questions no document answers (general trivia, chit-chat, requests to+write something, personal asks, and domains the corpus lacks, such as gardening)+and seven controls that the `distractor-*` documents *do* answer.++Every refusal case must retrieve **nothing**. `eval:retrieval` prints a `leaked=`+rate per tag and, with `--verbose`, each leaked question with its top chunk's+boosted and cosine scores. The controls keep a fix honest: a gate that stops the+leaks by also rejecting "how do list comprehensions work in Python?" has traded+one bug for another.++The suite exists because the relevance floor looked fine on the original 28+documents (22% of these leaked) and fails on a well-stocked library (67% leaked+once Gutenberg prose and programming docs were added). A small corpus+understates this failure, so keep the distractors in.++Retrieval-only for now. The generation tier scores `expectRefusal` as "the model+declined", and "Paris" is the right answer to the capital question as long as+nothing is cited for it.+### The `long_context` suiteFour conversations testing the two opposite ways context budgeting can fail:@@ -159,8 +181,16 @@ node ace eval:retrieval --min-final-score=0.7 # sweep the post-rerank relevancenode ace eval:retrieval --tag=multi-hopnode ace eval:retrieval --verbose # show every miss and what it retrievednode ace eval:retrieval --report # write JSON + Markdown to reports/+node ace eval:retrieval --suite=off_topic --judge-model=llama3:8b # measure the relevance check+node ace eval:retrieval --suite=core,off_topic --dump=pools.json # candidate pools for offline gate sims```+`--judge-model` runs the opt-in relevance check (`rag.relevanceCheck`) after the+floor and prints its latency and how often it failed open. It makes the run+model-dependent, so it is never part of a baseline. `--dump` writes every+golden's full pre-floor candidate pool with both scores, which lets you simulate+a new gate in a few lines of script instead of a sweep per setting.+**There are two cutoffs, on two different scores, and they do not interchange.**`--threshold` is what Qdrant applies to the raw cosine score, before reranking;`--min-final-score` (`RAG_MIN_FINAL_SCORE`) is the relevance floor applied to@@ -237,7 +267,12 @@ manufacture a regression. Re-baseline instead.## The corpus and the goldens-- `corpus/*.md` — 28 short documents across NOMAD's real domains.+- `corpus/*.md` — 28 short documents across NOMAD's real domains, plus six+ `distractor-*` documents (Project Gutenberg excerpts, the Python tutorial, MDN+ pages). The distractors stand in for a library with general prose in it, where+ something is always semantically near the question. Sources and licences are+ in each file's header: Gutenberg texts are public domain, the Python tutorial+ is PSF License v2, MDN is CC-BY-SA 2.5.- `goldens/*.jsonl` — 99 questions, one JSON object per line.The corpus is built with deliberate traps, not just easy questions:@@ -383,8 +418,8 @@ Read these before trusting a number.```tests/eval/- corpus/ 28 markdown fixtures — the frozen knowledge base- goldens/ 99 questions as JSONL+ corpus/ 34 markdown fixtures (28 domain + 6 distractor) — the frozen knowledge base+ goldens/ one JSONL file per suite (core: 99 questions)baselines/ <corpus-fingerprint>/*.json — COMMITTED; the gate compares against thesereports/ run artifacts — gitignored```diff --git a/admin/tests/eval/baselines/b4ebe5dce8699f5d/retrieval.json b/admin/tests/eval/baselines/b4ebe5dce8699f5d/retrieval.jsonnew file mode 100644index 00000000..77d0f97f--- /dev/null+++ b/admin/tests/eval/baselines/b4ebe5dce8699f5d/retrieval.json@@ -0,0 +1,4919 @@+{+ "meta": {+ "kind": "retrieval",+ "createdAt": "2026-09-23T22:08:54.308Z",+ "corpusFingerprint": "b4ebe5dce8699f5d",+ "gitSha": "b2cb1f15d70d547243447679d4c2218b097e8c9f",+ "gitBranch": "dev",+ "gitDirty": true,+ "nomadVersion": "1.35.0-rc.1",+ "platform": {+ "cpuArchitecture": "x64",+ "osName": "Linux 7.0.0-31-generic",+ "nodeVersion": "v24.15.0"+ },+ "params": {+ "topK": 5,+ "scoreThreshold": 0.3,+ "minFinalScore": 0.62,+ "kValues": [+ 1,+ 3,+ 5,+ 10+ ],+ "tag": null+ }+ },+ "metrics": {+ "recall@1": 0.9308510638297872,+ "recall@3": 0.9822695035460992,+ "recall@5": 0.9911347517730497,+ "recall@10": 0.9911347517730497,+ "hitRate@1": 0.9680851063829787,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 0.9680851063829787,+ "precision@3": 0.5407801418439718,+ "precision@5": 0.48829787234042565,+ "precision@10": 0.48829787234042565,+ "ndcg@1": 0.9680851063829787,+ "ndcg@3": 0.9750351707454068,+ "ndcg@5": 0.9799944842461846,+ "ndcg@10": 0.9799944842461846,+ "mrr": 0.9822695035460992,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": 0.6+ },+ "byTag": {+ "acronym": {+ "recall@1": 1,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.625,+ "precision@5": 0.6111111111111112,+ "precision@10": 0.6111111111111112,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "acronym-control": {+ "recall@1": 1,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.5,+ "precision@5": 0.47333333333333333,+ "precision@10": 0.47333333333333333,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "adversarial": {+ "recall@1": null,+ "recall@3": null,+ "recall@5": null,+ "recall@10": null,+ "hitRate@1": null,+ "hitRate@3": null,+ "hitRate@5": null,+ "hitRate@10": null,+ "precision@1": null,+ "precision@3": null,+ "precision@5": null,+ "precision@10": null,+ "ndcg@1": null,+ "ndcg@3": null,+ "ndcg@5": null,+ "ndcg@10": null,+ "mrr": null,+ "emptyRateOnAnswerable": null,+ "nonEmptyRateOnRefusal": 1+ },+ "chunk-boundary": {+ "recall@1": 1,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.7083333333333333,+ "precision@5": 0.7083333333333333,+ "precision@10": 0.7083333333333333,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "distractor": {+ "recall@1": 0,+ "recall@3": 0.3333333333333333,+ "recall@5": 0.6666666666666666,+ "recall@10": 0.6666666666666666,+ "hitRate@1": 0,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 0,+ "precision@3": 0.3333333333333333,+ "precision@5": 0.4,+ "precision@10": 0.4,+ "ndcg@1": 0,+ "ndcg@3": 0.2960819109658652,+ "ndcg@5": 0.49818925746641285,+ "ndcg@10": 0.49818925746641285,+ "mrr": 0.5,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "distractor-control": {+ "recall@1": 1,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.3333333333333333,+ "precision@5": 0.2,+ "precision@10": 0.2,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "fictional": {+ "recall@1": 1,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.7962962962962963,+ "precision@5": 0.787037037037037,+ "precision@10": 0.787037037037037,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "multi-hop": {+ "recall@1": 0.5,+ "recall@3": 0.8571428571428571,+ "recall@5": 0.9285714285714286,+ "recall@10": 0.9285714285714286,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.7619047619047619,+ "precision@5": 0.6714285714285714,+ "precision@10": 0.6714285714285714,+ "ndcg@1": 1,+ "ndcg@3": 0.8894706265044167,+ "ndcg@5": 0.9271946440147868,+ "ndcg@10": 0.9271946440147868,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "multi-turn": {+ "recall@1": 0.375,+ "recall@3": 0.875,+ "recall@5": 0.875,+ "recall@10": 0.875,+ "hitRate@1": 0.5,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 0.5,+ "precision@3": 0.6666666666666666,+ "precision@5": 0.6,+ "precision@10": 0.6,+ "ndcg@1": 0.5,+ "ndcg@3": 0.686019236584229,+ "ndcg@5": 0.686019236584229,+ "ndcg@10": 0.686019236584229,+ "mrr": 0.7083333333333333,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "near-miss": {+ "recall@1": 0.5,+ "recall@3": 0.5,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.3333333333333333,+ "precision@5": 0.4,+ "precision@10": 0.4,+ "ndcg@1": 1,+ "ndcg@3": 0.6131471927654584,+ "ndcg@5": 0.8772153153380493,+ "ndcg@10": 0.8772153153380493,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "numeric": {+ "recall@1": 0.9607843137254902,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.5098039215686274,+ "precision@5": 0.44673202614379076,+ "precision@10": 0.44673202614379076,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ },+ "out-of-corpus": {+ "recall@1": null,+ "recall@3": null,+ "recall@5": null,+ "recall@10": null,+ "hitRate@1": null,+ "hitRate@3": null,+ "hitRate@5": null,+ "hitRate@10": null,+ "precision@1": null,+ "precision@3": null,+ "precision@5": null,+ "precision@10": null,+ "ndcg@1": null,+ "ndcg@3": null,+ "ndcg@5": null,+ "ndcg@10": null,+ "mrr": null,+ "emptyRateOnAnswerable": null,+ "nonEmptyRateOnRefusal": 0.6+ },+ "single-hop": {+ "recall@1": 1,+ "recall@3": 1,+ "recall@5": 1,+ "recall@10": 1,+ "hitRate@1": 1,+ "hitRate@3": 1,+ "hitRate@5": 1,+ "hitRate@10": 1,+ "precision@1": 1,+ "precision@3": 0.45597484276729555,+ "precision@5": 0.38836477987421375,+ "precision@10": 0.38836477987421375,+ "ndcg@1": 1,+ "ndcg@3": 1,+ "ndcg@5": 1,+ "ndcg@10": 1,+ "mrr": 1,+ "emptyRateOnAnswerable": 0,+ "nonEmptyRateOnRefusal": null+ }+ },+ "cases": [+ {+ "id": "water-boil-time-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-boiling"+ ],+ "retrievedDocIds": [+ "water-boiling",+ "food-canning-waterbath",+ "water-chemical-treatment",+ "water-storage",+ "food-canning-pressure"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9815961793677813,+ "semanticScore": 0.84374034+ }+ },+ {+ "id": "water-boil-altitude-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-boiling"+ ],+ "retrievedDocIds": [+ "water-boiling",+ "food-canning-waterbath",+ "food-canning-pressure",+ "water-chemical-treatment",+ "regions-elevation-table"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8886211579572276,+ "semanticScore": 0.7710216+ }+ },+ {+ "id": "water-boil-altitude-threshold-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-boiling"+ ],+ "retrievedDocIds": [+ "water-boiling",+ "food-canning-pressure",+ "food-canning-waterbath",+ "regions-elevation-table",+ "distractor-gutenberg-walden"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8846119588030473,+ "semanticScore": 0.76037663+ }+ },+ {+ "id": "water-boil-taste-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-boiling"+ ],+ "retrievedDocIds": [+ "water-boiling",+ "food-canning-waterbath",+ "water-filtration",+ "water-chemical-treatment",+ "food-canning-pressure"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8557696922283238,+ "semanticScore": 0.7380408+ }+ },+ {+ "id": "water-bleach-dose-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "water-chemical-treatment"+ ],+ "retrievedDocIds": [+ "water-chemical-treatment",+ "water-storage",+ "food-canning-waterbath"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8636524329750481,+ "semanticScore": 0.7437347+ }+ },+ {+ "id": "water-bleach-cloudy-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-chemical-treatment"+ ],+ "retrievedDocIds": [+ "water-chemical-treatment",+ "water-boiling",+ "food-canning-waterbath",+ "water-storage",+ "sanitation-waste"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8749046828336395,+ "semanticScore": 0.755469+ }+ },+ {+ "id": "water-bleach-wait-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-chemical-treatment"+ ],+ "retrievedDocIds": [+ "water-chemical-treatment",+ "water-boiling",+ "water-storage",+ "food-canning-waterbath",+ "sanitation-waste"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8586794298974931,+ "semanticScore": 0.7463015+ }+ },+ {+ "id": "water-cldioxide-crypto-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "water-chemical-treatment"+ ],+ "retrievedDocIds": [+ "water-chemical-treatment",+ "water-boiling"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8430570823748271,+ "semanticScore": 0.7204655+ }+ },+ {+ "id": "water-filter-pore-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "water-filtration"+ ],+ "retrievedDocIds": [+ "water-filtration",+ "food-mylar-oxygen",+ "water-chemical-treatment"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8839381956312117,+ "semanticScore": 0.75586677+ }+ },+ {+ "id": "water-filter-virus-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-filtration"+ ],+ "retrievedDocIds": [+ "water-filtration",+ "water-boiling",+ "water-chemical-treatment",+ "sanitation-waste",+ "water-storage"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9204883406086626,+ "semanticScore": 0.7986715+ }+ },+ {+ "id": "water-filter-freeze-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-filtration"+ ],+ "retrievedDocIds": [+ "water-filtration",+ "shelter-cold-layering",+ "water-storage",+ "sanitation-waste",+ "water-boiling"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7627079824026435,+ "semanticScore": 0.67205715+ }+ },+ {+ "id": "water-storage-amount-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-storage"+ ],+ "retrievedDocIds": [+ "water-storage",+ "distractor-gutenberg-walden",+ "water-chemical-treatment",+ "food-canning-waterbath",+ "sanitation-waste"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8973458901159983,+ "semanticScore": 0.7816726+ }+ },+ {+ "id": "water-storage-rotation-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-storage"+ ],+ "retrievedDocIds": [+ "water-storage",+ "equipment-tr88-pump",+ "water-boiling",+ "food-canning-waterbath",+ "food-storage-rotation"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.856474313054675,+ "semanticScore": 0.7579396+ }+ },+ {+ "id": "water-storage-containers-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-storage"+ ],+ "retrievedDocIds": [+ "water-storage",+ "sanitation-waste",+ "food-canning-waterbath",+ "food-storage-rotation",+ "water-chemical-treatment"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8808618114191967,+ "semanticScore": 0.76681+ }+ },+ {+ "id": "food-pressure-temp-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-canning-pressure"+ ],+ "retrievedDocIds": [+ "food-canning-pressure",+ "food-canning-waterbath",+ "water-boiling",+ "food-dehydrating",+ "firstaid-hypothermia"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9813954471479394,+ "semanticScore": 0.8590077+ }+ },+ {+ "id": "food-pressure-psi-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "food-canning-pressure"+ ],+ "retrievedDocIds": [+ "food-canning-pressure",+ "food-canning-waterbath"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8249878485353306,+ "semanticScore": 0.72774994+ }+ },+ {+ "id": "food-greenbeans-method-01",+ "tags": [+ "near-miss",+ "multi-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-canning-pressure",+ "food-canning-waterbath"+ ],+ "retrievedDocIds": [+ "food-canning-waterbath",+ "water-boiling",+ "distractor-gutenberg-walden",+ "food-canning-pressure",+ "water-chemical-treatment"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 0.5,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.4,+ "10": 0.4+ },+ "ndcg": {+ "1": 1,+ "3": 0.6131471927654584,+ "5": 0.8772153153380493,+ "10": 0.8772153153380493+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8261421160519709,+ "semanticScore": 0.70916414+ }+ },+ {+ "id": "food-waterbath-ph-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-canning-waterbath"+ ],+ "retrievedDocIds": [+ "food-canning-waterbath",+ "food-canning-pressure",+ "water-boiling",+ "water-chemical-treatment",+ "water-storage"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9990537452476687,+ "semanticScore": 0.8702697+ }+ },+ {+ "id": "food-tomato-acid-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "food-canning-waterbath"+ ],+ "retrievedDocIds": [+ "food-canning-waterbath",+ "food-canning-pressure"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8219545875081886,+ "semanticScore": 0.7028638+ }+ },+ {+ "id": "food-dehydrate-veg-temp-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-dehydrating"+ ],+ "retrievedDocIds": [+ "food-dehydrating",+ "food-canning-pressure",+ "food-canning-waterbath",+ "water-boiling",+ "shelter-cold-layering"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9143909051287706,+ "semanticScore": 0.8098521+ }+ },+ {+ "id": "food-jerky-temp-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-dehydrating"+ ],+ "retrievedDocIds": [+ "food-dehydrating",+ "food-canning-pressure",+ "firstaid-hypothermia",+ "shelter-cold-layering",+ "food-canning-waterbath"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9110871322068216,+ "semanticScore": 0.8120425+ }+ },+ {+ "id": "food-conditioning-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-dehydrating"+ ],+ "retrievedDocIds": [+ "food-dehydrating",+ "food-storage-rotation",+ "food-canning-pressure",+ "food-canning-waterbath",+ "water-boiling"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8526046649195075,+ "semanticScore": 0.76138353+ }+ },+ {+ "id": "food-fifo-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "food-storage-rotation"+ ],+ "retrievedDocIds": [+ "food-storage-rotation",+ "protocol-thornfield-cache"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8022697771034744,+ "semanticScore": 0.7070433+ }+ },+ {+ "id": "food-fifo-spelled-01",+ "tags": [+ "acronym-control"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "food-storage-rotation"+ ],+ "retrievedDocIds": [+ "food-storage-rotation",+ "distractor-gutenberg-walden",+ "water-storage"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.847281259676453,+ "semanticScore": 0.7355672+ }+ },+ {+ "id": "food-brownrice-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "food-storage-rotation"+ ],+ "retrievedDocIds": [+ "food-storage-rotation",+ "water-storage",+ "food-mylar-oxygen"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.803988248754077,+ "semanticScore": 0.7034714+ }+ },+ {+ "id": "food-wheat-shelflife-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "food-storage-rotation"+ ],+ "retrievedDocIds": [+ "food-storage-rotation",+ "water-storage",+ "food-dehydrating"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8128399909827848,+ "semanticScore": 0.7093493+ }+ },+ {+ "id": "food-oxyabsorber-5gal-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "food-mylar-oxygen"+ ],+ "retrievedDocIds": [+ "food-mylar-oxygen",+ "water-storage",+ "food-canning-pressure"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9985756617677146,+ "semanticScore": 0.8614108+ }+ },+ {+ "id": "food-oxyabsorber-1gal-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "food-mylar-oxygen"+ ],+ "retrievedDocIds": [+ "food-mylar-oxygen",+ "water-storage"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9984644913412891,+ "semanticScore": 0.8613149+ }+ },+ {+ "id": "food-mylar-thickness-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-mylar-oxygen"+ ],+ "retrievedDocIds": [+ "food-mylar-oxygen",+ "food-storage-rotation",+ "water-storage",+ "food-canning-pressure",+ "gear-bug-out-bag"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9177936121453854,+ "semanticScore": 0.7878382+ }+ },+ {+ "id": "food-oxyabsorber-sugar-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "food-mylar-oxygen"+ ],+ "retrievedDocIds": [+ "food-mylar-oxygen"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.827158536589331,+ "semanticScore": 0.71003664+ }+ },+ {+ "id": "firstaid-tq-placement-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-bleeding-control"+ ],+ "retrievedDocIds": [+ "firstaid-bleeding-control",+ "firstaid-ifak-contents",+ "distractor-gutenberg-walden",+ "distractor-gutenberg-sherlock-holmes"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8767431147026937,+ "semanticScore": 0.765917+ }+ },+ {+ "id": "firstaid-tq-time-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-bleeding-control"+ ],+ "retrievedDocIds": [+ "firstaid-bleeding-control",+ "firstaid-ifak-contents",+ "distractor-gutenberg-sherlock-holmes",+ "distractor-gutenberg-pride-and-prejudice",+ "distractor-gutenberg-walden"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8139192206934482,+ "semanticScore": 0.71666646+ }+ },+ {+ "id": "firstaid-woundpack-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "firstaid-bleeding-control"+ ],+ "retrievedDocIds": [+ "firstaid-bleeding-control",+ "food-canning-pressure",+ "firstaid-burns",+ "firstaid-ifak-contents"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.25,+ "10": 0.25+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7940771832923635,+ "semanticScore": 0.6950495+ }+ },+ {+ "id": "firstaid-ifak-acronym-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "firstaid-ifak-contents"+ ],+ "retrievedDocIds": [+ "firstaid-ifak-contents",+ "gear-bug-out-bag"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9483528549696179,+ "semanticScore": 0.8466351+ }+ },+ {+ "id": "firstaid-ifak-spelled-01",+ "tags": [+ "acronym-control"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-ifak-contents"+ ],+ "retrievedDocIds": [+ "firstaid-ifak-contents",+ "gear-bug-out-bag",+ "firstaid-bleeding-control",+ "gear-edc",+ "food-mylar-oxygen"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8701354170333943,+ "semanticScore": 0.7513508+ }+ },+ {+ "id": "firstaid-ifak-carry-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "firstaid-ifak-contents"+ ],+ "retrievedDocIds": [+ "firstaid-ifak-contents",+ "gear-bug-out-bag",+ "gear-edc",+ "distractor-gutenberg-sherlock-holmes"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.25,+ "10": 0.25+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9470041287973104,+ "semanticScore": 0.81291264+ }+ },+ {+ "id": "firstaid-hypothermia-temp-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-hypothermia"+ ],+ "retrievedDocIds": [+ "firstaid-hypothermia",+ "shelter-cold-layering",+ "food-dehydrating",+ "food-canning-pressure",+ "water-boiling"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9981127319538972,+ "semanticScore": 0.8579373+ }+ },+ {+ "id": "firstaid-hypothermia-shivering-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "firstaid-hypothermia"+ ],+ "retrievedDocIds": [+ "firstaid-hypothermia",+ "shelter-cold-layering"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8273611450246979,+ "semanticScore": 0.71021056+ }+ },+ {+ "id": "firstaid-hypothermia-handling-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-hypothermia"+ ],+ "retrievedDocIds": [+ "firstaid-hypothermia",+ "distractor-gutenberg-walden",+ "shelter-cold-layering",+ "power-emp-protection",+ "food-canning-pressure"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8788057115268926,+ "semanticScore": 0.7744947+ }+ },+ {+ "id": "firstaid-burn-cooling-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-burns"+ ],+ "retrievedDocIds": [+ "firstaid-burns",+ "water-boiling",+ "shelter-cold-layering",+ "water-chemical-treatment",+ "food-canning-pressure"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8477873975707532,+ "semanticScore": 0.7396909+ }+ },+ {+ "id": "firstaid-burn-ice-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-burns"+ ],+ "retrievedDocIds": [+ "firstaid-burns",+ "water-boiling",+ "water-chemical-treatment",+ "shelter-cold-layering",+ "firstaid-hypothermia"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8737608425,+ "semanticScore": 0.7681414+ }+ },+ {+ "id": "radio-gmrs-license-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "radio-gmrs-frs"+ ],+ "retrievedDocIds": [+ "radio-gmrs-frs",+ "radio-ham-bands"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8674937135834537,+ "semanticScore": 0.77788824+ }+ },+ {+ "id": "radio-gmrs-term-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "radio-gmrs-frs"+ ],+ "retrievedDocIds": [+ "radio-gmrs-frs",+ "radio-ham-bands"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9286593710087677,+ "semanticScore": 0.8099425+ }+ },+ {+ "id": "radio-frs-power-01",+ "tags": [+ "acronym",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "radio-gmrs-frs"+ ],+ "retrievedDocIds": [+ "radio-gmrs-frs"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9047517219068886,+ "semanticScore": 0.79064566+ }+ },+ {+ "id": "radio-gmrs-power-01",+ "tags": [+ "acronym",+ "numeric"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "radio-gmrs-frs"+ ],+ "retrievedDocIds": [+ "radio-gmrs-frs",+ "radio-antenna-basics",+ "radio-ham-bands"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.25,+ "10": 0.25+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.956371181094478,+ "semanticScore": 0.831138+ }+ },+ {+ "id": "radio-frs-license-01",+ "tags": [+ "acronym-control"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "radio-gmrs-frs"+ ],+ "retrievedDocIds": [+ "radio-gmrs-frs",+ "radio-ham-bands"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8601949519648088,+ "semanticScore": 0.7463573+ }+ },+ {+ "id": "radio-tech-questions-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "radio-ham-bands"+ ],+ "retrievedDocIds": [+ "radio-ham-bands",+ "radio-gmrs-frs",+ "radio-antenna-basics"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8976950898219473,+ "semanticScore": 0.77305055+ }+ },+ {+ "id": "radio-extra-questions-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "radio-ham-bands"+ ],+ "retrievedDocIds": [+ "radio-ham-bands",+ "distractor-gutenberg-sherlock-holmes"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.25,+ "10": 0.25+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8040526197310376,+ "semanticScore": 0.69428915+ }+ },+ {+ "id": "radio-morse-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "radio-ham-bands"+ ],+ "retrievedDocIds": [+ "radio-ham-bands",+ "radio-gmrs-frs",+ "radio-antenna-basics"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9232337825190203,+ "semanticScore": 0.8170906+ }+ },+ {+ "id": "radio-counterpoise-01",+ "tags": [+ "chunk-boundary",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "radio-antenna-basics"+ ],+ "retrievedDocIds": [+ "radio-antenna-basics",+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.6887594812561,+ "semanticScore": 0.594735+ }+ },+ {+ "id": "radio-swr-threshold-01",+ "tags": [+ "chunk-boundary",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "radio-antenna-basics"+ ],+ "retrievedDocIds": [+ "radio-antenna-basics",+ "radio-gmrs-frs"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.6666666666666666,+ "5": 0.6666666666666666,+ "10": 0.6666666666666666+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8996441492678643,+ "semanticScore": 0.7777715+ }+ },+ {+ "id": "radio-swr-meaning-01",+ "tags": [+ "chunk-boundary"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "radio-antenna-basics"+ ],+ "retrievedDocIds": [+ "radio-antenna-basics",+ "radio-gmrs-frs"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.6666666666666666,+ "5": 0.6666666666666666,+ "10": 0.6666666666666666+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9697775419115846,+ "semanticScore": 0.8373905+ }+ },+ {+ "id": "radio-wavelength-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "radio-antenna-basics"+ ],+ "retrievedDocIds": [+ "radio-antenna-basics"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.6735561864496017,+ "semanticScore": 0.59360754+ }+ },+ {+ "id": "radio-height-vs-power-01",+ "tags": [+ "chunk-boundary"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "radio-antenna-basics"+ ],+ "retrievedDocIds": [+ "radio-antenna-basics"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.774340820960127,+ "semanticScore": 0.67186505+ }+ },+ {+ "id": "power-leadacid-dod-01",+ "tags": [+ "multi-hop",+ "numeric"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "power-solar-sizing",+ "power-battery-chemistry"+ ],+ "retrievedDocIds": [+ "power-battery-chemistry",+ "power-solar-sizing",+ "food-canning-pressure",+ "food-canning-waterbath"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.6666666666666666,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8356629275408575,+ "semanticScore": 0.73461556+ }+ },+ {+ "id": "power-lifepo4-dod-01",+ "tags": [+ "multi-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "power-solar-sizing",+ "power-battery-chemistry"+ ],+ "retrievedDocIds": [+ "power-battery-chemistry",+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8801602501625471,+ "semanticScore": 0.7723173+ }+ },+ {+ "id": "power-derate-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "power-solar-sizing"+ ],+ "retrievedDocIds": [+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8284260104818267,+ "semanticScore": 0.7385195+ }+ },+ {+ "id": "power-mppt-01",+ "tags": [+ "acronym",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "power-solar-sizing"+ ],+ "retrievedDocIds": [+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7269665910705577,+ "semanticScore": 0.63427526+ }+ },+ {+ "id": "power-peaksun-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "power-solar-sizing"+ ],+ "retrievedDocIds": [+ "power-solar-sizing",+ "distractor-gutenberg-walden",+ "radio-antenna-basics"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.25,+ "10": 0.25+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7173070113380687,+ "semanticScore": 0.63504803+ }+ },+ {+ "id": "power-lifepo4-cycles-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "power-battery-chemistry"+ ],+ "retrievedDocIds": [+ "power-battery-chemistry",+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.922135527213677,+ "semanticScore": 0.8156935+ }+ },+ {+ "id": "power-agm-cycles-01",+ "tags": [+ "acronym",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "power-battery-chemistry"+ ],+ "retrievedDocIds": [+ "power-battery-chemistry",+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8270568769888269,+ "semanticScore": 0.7207232+ }+ },+ {+ "id": "power-lifepo4-cold-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "power-battery-chemistry"+ ],+ "retrievedDocIds": [+ "power-battery-chemistry"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8761724121708904,+ "semanticScore": 0.74922615+ }+ },+ {+ "id": "power-usable-capacity-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "power-battery-chemistry"+ ],+ "retrievedDocIds": [+ "power-battery-chemistry",+ "power-solar-sizing"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8283468262363889,+ "semanticScore": 0.726374+ }+ },+ {+ "id": "power-emp-acronym-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "power-emp-protection"+ ],+ "retrievedDocIds": [+ "power-emp-protection"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8180948146825751,+ "semanticScore": 0.7022563+ }+ },+ {+ "id": "power-emp-spelled-01",+ "tags": [+ "acronym-control"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "power-emp-protection"+ ],+ "retrievedDocIds": [+ "power-emp-protection"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7815537727207493,+ "semanticScore": 0.6730354+ }+ },+ {+ "id": "power-faraday-ground-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "power-emp-protection"+ ],+ "retrievedDocIds": [+ "power-emp-protection"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9457987425000001,+ "semanticScore": 0.8049351+ }+ },+ {+ "id": "gear-bob-acronym-01",+ "tags": [+ "acronym",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "gear-bug-out-bag"+ ],+ "retrievedDocIds": [+ "gear-bug-out-bag",+ "food-mylar-oxygen"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9222916173124887,+ "semanticScore": 0.7998831+ }+ },+ {+ "id": "gear-bob-spelled-01",+ "tags": [+ "acronym-control",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "gear-bug-out-bag"+ ],+ "retrievedDocIds": [+ "gear-bug-out-bag",+ "food-mylar-oxygen",+ "distractor-gutenberg-walden"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9059645891985582,+ "semanticScore": 0.78572303+ }+ },+ {+ "id": "gear-bob-weight-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "gear-bug-out-bag"+ ],+ "retrievedDocIds": [+ "gear-bug-out-bag",+ "food-mylar-oxygen"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8843168902664935,+ "semanticScore": 0.76694846+ }+ },+ {+ "id": "gear-edc-acronym-01",+ "tags": [+ "acronym"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "gear-edc"+ ],+ "retrievedDocIds": [+ "gear-edc"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9546281240080038,+ "semanticScore": 0.87477267+ }+ },+ {+ "id": "shelter-cotton-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "shelter-cold-layering"+ ],+ "retrievedDocIds": [+ "shelter-cold-layering",+ "firstaid-hypothermia"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8900715224907906,+ "semanticScore": 0.7799366+ }+ },+ {+ "id": "shelter-layers-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "shelter-cold-layering"+ ],+ "retrievedDocIds": [+ "shelter-cold-layering",+ "firstaid-hypothermia"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9515753232601358,+ "semanticScore": 0.82696784+ }+ },+ {+ "id": "shelter-cold-hands-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "shelter-cold-layering"+ ],+ "retrievedDocIds": [+ "shelter-cold-layering",+ "firstaid-burns",+ "firstaid-hypothermia",+ "distractor-gutenberg-walden",+ "sanitation-waste"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8004097473015831,+ "semanticScore": 0.71227074+ }+ },+ {+ "id": "sanitation-latrine-distance-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "sanitation-waste"+ ],+ "retrievedDocIds": [+ "sanitation-waste",+ "distractor-gutenberg-walden",+ "distractor-gutenberg-sherlock-holmes",+ "water-boiling",+ "food-canning-waterbath"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7484099375158363,+ "semanticScore": 0.6521878+ }+ },+ {+ "id": "sanitation-buckets-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "sanitation-waste"+ ],+ "retrievedDocIds": [+ "sanitation-waste"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8153330972173664,+ "semanticScore": 0.7171987+ }+ },+ {+ "id": "nav-declination-01",+ "tags": [+ "single-hop"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "navigation-map-compass"+ ],+ "retrievedDocIds": [+ "navigation-map-compass"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8303358097696566,+ "semanticScore": 0.7262616+ }+ },+ {+ "id": "nav-pacecount-01",+ "tags": [+ "single-hop",+ "numeric"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "navigation-map-compass"+ ],+ "retrievedDocIds": [+ "navigation-map-compass",+ "radio-ham-bands",+ "radio-antenna-basics"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.666197416592364,+ "semanticScore": 0.58598906+ }+ },+ {+ "id": "fict-thornfield-interval-01",+ "tags": [+ "fictional",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "protocol-thornfield-cache"+ ],+ "retrievedDocIds": [+ "protocol-thornfield-cache"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9249835934834107,+ "semanticScore": 0.8060596+ }+ },+ {+ "id": "fict-thornfield-states-01",+ "tags": [+ "fictional"+ ],+ "retrievedCount": 3,+ "relevantDocIds": [+ "protocol-thornfield-cache"+ ],+ "retrievedDocIds": [+ "protocol-thornfield-cache",+ "regions-elevation-table",+ "distractor-gutenberg-walden"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.3333333333333333,+ "10": 0.3333333333333333+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.90653471802931,+ "semanticScore": 0.7806628+ }+ },+ {+ "id": "fict-thornfield-marker-01",+ "tags": [+ "fictional"+ ],+ "retrievedCount": 4,+ "relevantDocIds": [+ "protocol-thornfield-cache"+ ],+ "retrievedDocIds": [+ "protocol-thornfield-cache",+ "regions-elevation-table",+ "distractor-gutenberg-sherlock-holmes"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.25,+ "10": 0.25+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9068972627437311,+ "semanticScore": 0.77706385+ }+ },+ {+ "id": "fict-thornfield-custody-01",+ "tags": [+ "fictional"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "protocol-thornfield-cache"+ ],+ "retrievedDocIds": [+ "protocol-thornfield-cache",+ "regions-elevation-table"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9161573646346456,+ "semanticScore": 0.78406894+ }+ },+ {+ "id": "fict-tr88-flow-01",+ "tags": [+ "fictional",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "equipment-tr88-pump"+ ],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9589474281023889,+ "semanticScore": 0.82579803+ }+ },+ {+ "id": "fict-tr88-diaphragm-01",+ "tags": [+ "fictional",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "equipment-tr88-pump"+ ],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.9017118930351233,+ "semanticScore": 0.78772956+ }+ },+ {+ "id": "fict-tr88-maxtemp-01",+ "tags": [+ "fictional",+ "numeric"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "equipment-tr88-pump"+ ],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.883851612127077,+ "semanticScore": 0.77362835+ }+ },+ {+ "id": "fict-tr88-spares-01",+ "tags": [+ "fictional"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "equipment-tr88-pump"+ ],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7852771638185309,+ "semanticScore": 0.6762418+ }+ },+ {+ "id": "multihop-kestrel-boil-01",+ "tags": [+ "multi-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "regions-elevation-table",+ "water-boiling"+ ],+ "retrievedDocIds": [+ "water-boiling",+ "regions-elevation-table",+ "food-canning-waterbath",+ "food-canning-pressure",+ "water-chemical-treatment"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.6666666666666666,+ "5": 0.4,+ "10": 0.4+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7887670104112251,+ "semanticScore": 0.6977197+ }+ },+ {+ "id": "multihop-ashmere-boil-01",+ "tags": [+ "multi-hop",+ "numeric"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "regions-elevation-table",+ "water-boiling"+ ],+ "retrievedDocIds": [+ "water-boiling",+ "regions-elevation-table",+ "food-canning-waterbath",+ "food-canning-pressure",+ "water-chemical-treatment"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.6666666666666666,+ "5": 0.4,+ "10": 0.4+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7677511515734357,+ "semanticScore": 0.6791297+ }+ },+ {+ "id": "multihop-bellhollow-canning-01",+ "tags": [+ "multi-hop"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [+ "regions-elevation-table",+ "food-canning-pressure"+ ],+ "retrievedDocIds": [+ "food-canning-pressure",+ "regions-elevation-table"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.690503215451349,+ "semanticScore": 0.64038515+ }+ },+ {+ "id": "distract-river-drink-01",+ "tags": [+ "distractor"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-boiling",+ "water-filtration",+ "water-chemical-treatment"+ ],+ "retrievedDocIds": [+ "water-river-song",+ "water-boiling",+ "water-storage",+ "water-filtration",+ "distractor-gutenberg-walden"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0,+ "3": 0.3333333333333333,+ "5": 0.6666666666666666,+ "10": 0.6666666666666666+ },+ "hitRate": {+ "1": 0,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 0,+ "3": 0.3333333333333333,+ "5": 0.4,+ "10": 0.4+ },+ "ndcg": {+ "1": 0,+ "3": 0.2960819109658652,+ "5": 0.49818925746641285,+ "10": 0.49818925746641285+ },+ "reciprocalRank": 0.5,+ "empty": false,+ "top": {+ "score": 0.7787109717989457,+ "semanticScore": 0.68996376+ }+ },+ {+ "id": "distract-river-legit-01",+ "tags": [+ "distractor-control"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "water-river-song"+ ],+ "retrievedDocIds": [+ "water-river-song",+ "distractor-gutenberg-walden",+ "distractor-gutenberg-sherlock-holmes"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.8823675403166954,+ "semanticScore": 0.78150845+ }+ },+ {+ "id": "ooc-tire-pressure-01",+ "tags": [+ "out-of-corpus"+ ],+ "retrievedCount": 0,+ "relevantDocIds": [],+ "retrievedDocIds": [],+ "expectRefusal": true,+ "recall": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "hitRate": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "precision": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "ndcg": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "reciprocalRank": null,+ "empty": true,+ "top": null+ },+ {+ "id": "ooc-bgp-01",+ "tags": [+ "out-of-corpus"+ ],+ "retrievedCount": 0,+ "relevantDocIds": [],+ "retrievedDocIds": [],+ "expectRefusal": true,+ "recall": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "hitRate": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "precision": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "ndcg": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "reciprocalRank": null,+ "empty": true,+ "top": null+ },+ {+ "id": "ooc-thornfield-founded-01",+ "tags": [+ "out-of-corpus",+ "adversarial"+ ],+ "retrievedCount": 2,+ "relevantDocIds": [],+ "retrievedDocIds": [+ "protocol-thornfield-cache",+ "regions-elevation-table"+ ],+ "expectRefusal": true,+ "recall": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "hitRate": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "precision": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "ndcg": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "reciprocalRank": null,+ "empty": false,+ "top": {+ "score": 0.7221133559445054,+ "semanticScore": 0.6327611+ }+ },+ {+ "id": "ooc-tr88-warranty-01",+ "tags": [+ "out-of-corpus",+ "adversarial"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": true,+ "recall": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "hitRate": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "precision": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "ndcg": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "reciprocalRank": null,+ "empty": false,+ "top": {+ "score": 0.836970555812808,+ "semanticScore": 0.7579527+ }+ },+ {+ "id": "ooc-tr92-01",+ "tags": [+ "out-of-corpus",+ "adversarial"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": true,+ "recall": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "hitRate": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "precision": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "ndcg": {+ "1": null,+ "3": null,+ "5": null,+ "10": null+ },+ "reciprocalRank": null,+ "empty": false,+ "top": {+ "score": 0.7540597825177621,+ "semanticScore": 0.67281055+ }+ },+ {+ "id": "multiturn-canning-temp-01",+ "tags": [+ "multi-turn"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "food-canning-pressure"+ ],+ "retrievedDocIds": [+ "firstaid-hypothermia",+ "food-canning-pressure",+ "shelter-cold-layering",+ "water-boiling",+ "food-dehydrating"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 0,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 0,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 0,+ "3": 0.6309297535714575,+ "5": 0.6309297535714575,+ "10": 0.6309297535714575+ },+ "reciprocalRank": 0.5,+ "empty": false,+ "top": {+ "score": 0.7645762202981194,+ "semanticScore": 0.67382383+ }+ },+ {+ "id": "multiturn-ifak-carry-01",+ "tags": [+ "multi-turn"+ ],+ "retrievedCount": 5,+ "relevantDocIds": [+ "firstaid-ifak-contents"+ ],+ "retrievedDocIds": [+ "gear-edc",+ "distractor-gutenberg-sherlock-holmes",+ "firstaid-ifak-contents",+ "distractor-gutenberg-walden",+ "gear-bug-out-bag"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 0,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 0,+ "3": 0.3333333333333333,+ "5": 0.2,+ "10": 0.2+ },+ "ndcg": {+ "1": 0,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "reciprocalRank": 0.3333333333333333,+ "empty": false,+ "top": {+ "score": 0.7634589094965507,+ "semanticScore": 0.657453+ }+ },+ {+ "id": "multiturn-tr88-diaphragm-01",+ "tags": [+ "multi-turn",+ "fictional"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "equipment-tr88-pump"+ ],+ "retrievedDocIds": [+ "equipment-tr88-pump"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.7444315261088696,+ "semanticScore": 0.6702486+ }+ },+ {+ "id": "multiturn-boil-altitude-01",+ "tags": [+ "multi-turn",+ "multi-hop"+ ],+ "retrievedCount": 1,+ "relevantDocIds": [+ "regions-elevation-table",+ "water-boiling"+ ],+ "retrievedDocIds": [+ "regions-elevation-table"+ ],+ "expectRefusal": false,+ "recall": {+ "1": 0.5,+ "3": 0.5,+ "5": 0.5,+ "10": 0.5+ },+ "hitRate": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "precision": {+ "1": 1,+ "3": 1,+ "5": 1,+ "10": 1+ },+ "ndcg": {+ "1": 1,+ "3": 0.6131471927654584,+ "5": 0.6131471927654584,+ "10": 0.6131471927654584+ },+ "reciprocalRank": 1,+ "empty": false,+ "top": {+ "score": 0.684573435,+ "semanticScore": 0.6018228+ }+ }+ ]+}\ No newline at end of filediff --git a/admin/tests/eval/corpus/distractor-gutenberg-pride-and-prejudice.md b/admin/tests/eval/corpus/distractor-gutenberg-pride-and-prejudice.mdnew file mode 100644index 00000000..71d88f40--- /dev/null+++ b/admin/tests/eval/corpus/distractor-gutenberg-pride-and-prejudice.md@@ -0,0 +1,2499 @@+# Pride and Prejudice (chapters I-XIV), Jane Austen++Distractor document for the #1341 off-topic eval suite. Public domain text from Project Gutenberg (ebook #1342), boilerplate removed.++It is a truth universally acknowledged, that a single man in possession+of a good fortune must be in want of a wife.++However little known the feelings or views of such a man may be on his+first entering a neighbourhood, this truth is so well fixed in the minds+of the surrounding families, that he is considered as the rightful+property of some one or other of their daughters.++“My dear Mr. Bennet,” said his lady to him one day, “have you heard that+Netherfield Park is let at last?”++Mr. Bennet replied that he had not.++“But it is,” returned she; “for Mrs. Long has just been here, and she+told me all about it.”++Mr. Bennet made no answer.++“Do not you want to know who has taken it?” cried his wife, impatiently.++“_You_ want to tell me, and I have no objection to hearing it.”++[Illustration:++“He came down to see the place”++[_Copyright 1894 by George Allen._]]++This was invitation enough.++“Why, my dear, you must know, Mrs. Long says that Netherfield is taken+by a young man of large fortune from the north of England; that he came+down on Monday in a chaise and four to see the place, and was so much+delighted with it that he agreed with Mr. Morris immediately; that he is+to take possession before Michaelmas, and some of his servants are to be+in the house by the end of next week.”++“What is his name?”++“Bingley.”++“Is he married or single?”++“Oh, single, my dear, to be sure! A single man of large fortune; four or+five thousand a year. What a fine thing for our girls!”++“How so? how can it affect them?”++“My dear Mr. Bennet,” replied his wife, “how can you be so tiresome? You+must know that I am thinking of his marrying one of them.”++“Is that his design in settling here?”++“Design? Nonsense, how can you talk so! But it is very likely that he+_may_ fall in love with one of them, and therefore you must visit him as+soon as he comes.”++“I see no occasion for that. You and the girls may go--or you may send+them by themselves, which perhaps will be still better; for as you are+as handsome as any of them, Mr. Bingley might like you the best of the+party.”++“My dear, you flatter me. I certainly _have_ had my share of beauty, but+I do not pretend to be anything extraordinary now. When a woman has five+grown-up daughters, she ought to give over thinking of her own beauty.”++“In such cases, a woman has not often much beauty to think of.”++“But, my dear, you must indeed go and see Mr. Bingley when he comes into+the neighbourhood.”++“It is more than I engage for, I assure you.”++“But consider your daughters. Only think what an establishment it would+be for one of them. Sir William and Lady Lucas are determined to go,+merely on that account; for in general, you know, they visit no new+comers. Indeed you must go, for it will be impossible for _us_ to visit+him, if you do not.”++“You are over scrupulous, surely. I dare say Mr. Bingley will be very+glad to see you; and I will send a few lines by you to assure him of my+hearty consent to his marrying whichever he chooses of the girls--though+I must throw in a good word for my little Lizzy.”++“I desire you will do no such thing. Lizzy is not a bit better than the+others: and I am sure she is not half so handsome as Jane, nor half so+good-humoured as Lydia. But you are always giving _her_ the preference.”++“They have none of them much to recommend them,” replied he: “they are+all silly and ignorant like other girls; but Lizzy has something more of+quickness than her sisters.”++“Mr. Bennet, how can you abuse your own children in such a way? You take+delight in vexing me. You have no compassion on my poor nerves.”++“You mistake me, my dear. I have a high respect for your nerves. They+are my old friends. I have heard you mention them with consideration+these twenty years at least.”++“Ah, you do not know what I suffer.”++“But I hope you will get over it, and live to see many young men of four+thousand a year come into the neighbourhood.”++“It will be no use to us, if twenty such should come, since you will not+visit them.”++“Depend upon it, my dear, that when there are twenty, I will visit them+all.”++Mr. Bennet was so odd a mixture of quick parts, sarcastic humour,+reserve, and caprice, that the experience of three-and-twenty years had+been insufficient to make his wife understand his character. _Her_ mind+was less difficult to develope. She was a woman of mean understanding,+little information, and uncertain temper. When she was discontented, she+fancied herself nervous. The business of her life was to get her+daughters married: its solace was visiting and news.++[Illustration: M^{r.} & M^{rs.} Bennet++[_Copyright 1894 by George Allen._]]++[Illustration:++“I hope Mr. Bingley will like it”++[_Copyright 1894 by George Allen._]]++CHAPTER II.++[Illustration]++Mr. Bennet was among the earliest of those who waited on Mr. Bingley. He+had always intended to visit him, though to the last always assuring his+wife that he should not go; and till the evening after the visit was+paid she had no knowledge of it. It was then disclosed in the following+manner. Observing his second daughter employed in trimming a hat, he+suddenly addressed her with,--++“I hope Mr. Bingley will like it, Lizzy.”++“We are not in a way to know _what_ Mr. Bingley likes,” said her mother,+resentfully, “since we are not to visit.”++“But you forget, mamma,” said Elizabeth, “that we shall meet him at the+assemblies, and that Mrs. Long has promised to introduce him.”++“I do not believe Mrs. Long will do any such thing. She has two nieces+of her own. She is a selfish, hypocritical woman, and I have no opinion+of her.”++“No more have I,” said Mr. Bennet; “and I am glad to find that you do+not depend on her serving you.”++Mrs. Bennet deigned not to make any reply; but, unable to contain+herself, began scolding one of her daughters.++“Don’t keep coughing so, Kitty, for heaven’s sake! Have a little+compassion on my nerves. You tear them to pieces.”++“Kitty has no discretion in her coughs,” said her father; “she times+them ill.”++“I do not cough for my own amusement,” replied Kitty, fretfully. “When+is your next ball to be, Lizzy?”++“To-morrow fortnight.”++“Ay, so it is,” cried her mother, “and Mrs. Long does not come back till+the day before; so, it will be impossible for her to introduce him, for+she will not know him herself.”++“Then, my dear, you may have the advantage of your friend, and introduce+Mr. Bingley to _her_.”++“Impossible, Mr. Bennet, impossible, when I am not acquainted with him+myself; how can you be so teasing?”++“I honour your circumspection. A fortnight’s acquaintance is certainly+very little. One cannot know what a man really is by the end of a+fortnight. But if _we_ do not venture, somebody else will; and after+all, Mrs. Long and her nieces must stand their chance; and, therefore,+as she will think it an act of kindness, if you decline the office, I+will take it on myself.”++The girls stared at their father. Mrs. Bennet said only, “Nonsense,+nonsense!”++“What can be the meaning of that emphatic exclamation?” cried he. “Do+you consider the forms of introduction, and the stress that is laid on+them, as nonsense? I cannot quite agree with you _there_. What say you,+Mary? For you are a young lady of deep reflection, I know, and read+great books, and make extracts.”++Mary wished to say something very sensible, but knew not how.++“While Mary is adjusting her ideas,” he continued, “let us return to Mr.+Bingley.”++“I am sick of Mr. Bingley,” cried his wife.++“I am sorry to hear _that_; but why did you not tell me so before? If I+had known as much this morning, I certainly would not have called on+him. It is very unlucky; but as I have actually paid the visit, we+cannot escape the acquaintance now.”++The astonishment of the ladies was just what he wished--that of Mrs.+Bennet perhaps surpassing the rest; though when the first tumult of joy+was over, she began to declare that it was what she had expected all the+while.++“How good it was in you, my dear Mr. Bennet! But I knew I should+persuade you at last. I was sure you loved your girls too well to+neglect such an acquaintance. Well, how pleased I am! And it is such a+good joke, too, that you should have gone this morning, and never said a+word about it till now.”++“Now, Kitty, you may cough as much as you choose,” said Mr. Bennet; and,+as he spoke, he left the room, fatigued with the raptures of his wife.++“What an excellent father you have, girls,” said she, when the door was+shut. “I do not know how you will ever make him amends for his kindness;+or me either, for that matter. At our time of life, it is not so+pleasant, I can tell you, to be making new acquaintances every day; but+for your sakes we would do anything. Lydia, my love, though you _are_+the youngest, I dare say Mr. Bingley will dance with you at the next+ball.”++“Oh,” said Lydia, stoutly, “I am not afraid; for though I _am_ the+youngest, I’m the tallest.”++The rest of the evening was spent in conjecturing how soon he would+return Mr. Bennet’s visit, and determining when they should ask him to+dinner.++[Illustration: “I’m the tallest”]++[Illustration:++ “He rode a black horse”+]++CHAPTER III.++[Illustration]++Not all that Mrs. Bennet, however, with the assistance of her five+daughters, could ask on the subject, was sufficient to draw from her+husband any satisfactory description of Mr. Bingley. They attacked him+in various ways, with barefaced questions, ingenious suppositions, and+distant surmises; but he eluded the skill of them all; and they were at+last obliged to accept the second-hand intelligence of their neighbour,+Lady Lucas. Her report was highly favourable. Sir William had been+delighted with him. He was quite young, wonderfully handsome, extremely+agreeable, and, to crown the whole, he meant to be at the next assembly+with a large party. Nothing could be more delightful! To be fond of+dancing was a certain step towards falling in love; and very lively+hopes of Mr. Bingley’s heart were entertained.++“If I can but see one of my daughters happily settled at Netherfield,”+said Mrs. Bennet to her husband, “and all the others equally well+married, I shall have nothing to wish for.”++In a few days Mr. Bingley returned Mr. Bennet’s visit, and sat about ten+minutes with him in his library. He had entertained hopes of being+admitted to a sight of the young ladies, of whose beauty he had heard+much; but he saw only the father. The ladies were somewhat more+fortunate, for they had the advantage of ascertaining, from an upper+window, that he wore a blue coat and rode a black horse.++An invitation to dinner was soon afterwards despatched; and already had+Mrs. Bennet planned the courses that were to do credit to her+housekeeping, when an answer arrived which deferred it all. Mr. Bingley+was obliged to be in town the following day, and consequently unable to+accept the honour of their invitation, etc. Mrs. Bennet was quite+disconcerted. She could not imagine what business he could have in town+so soon after his arrival in Hertfordshire; and she began to fear that+he might always be flying about from one place to another, and never+settled at Netherfield as he ought to be. Lady Lucas quieted her fears a+little by starting the idea of his++[Illustration:++ “When the Party entered”++[_Copyright 1894 by George Allen._]]++being gone to London only to get a large party for the ball; and a+report soon followed that Mr. Bingley was to bring twelve ladies and+seven gentlemen with him to the assembly. The girls grieved over such a+number of ladies; but were comforted the day before the ball by hearing+that, instead of twelve, he had brought only six with him from London,+his five sisters and a cousin. And when the party entered the+assembly-room, it consisted of only five altogether: Mr. Bingley, his+two sisters, the husband of the eldest, and another young man.++Mr. Bingley was good-looking and gentlemanlike: he had a pleasant+countenance, and easy, unaffected manners. His sisters were fine women,+with an air of decided fashion. His brother-in-law, Mr. Hurst, merely+looked the gentleman; but his friend Mr. Darcy soon drew the attention+of the room by his fine, tall person, handsome features, noble mien, and+the report, which was in general circulation within five minutes after+his entrance, of his having ten thousand a year. The gentlemen+pronounced him to be a fine figure of a man, the ladies declared he was+much handsomer than Mr. Bingley, and he was looked at with great+admiration for about half the evening, till his manners gave a disgust+which turned the tide of his popularity; for he was discovered to be+proud, to be above his company, and above being pleased; and not all his+large estate in Derbyshire could save him from having a most forbidding,+disagreeable countenance, and being unworthy to be compared with his+friend.++Mr. Bingley had soon made himself acquainted with all the principal+people in the room: he was lively and unreserved, danced every dance,+was angry that the ball closed so early, and talked of giving one+himself at Netherfield. Such amiable qualities must speak for+themselves. What a contrast between him and his friend! Mr. Darcy danced+only once with Mrs. Hurst and once with Miss Bingley, declined being+introduced to any other lady, and spent the rest of the evening in+walking about the room, speaking occasionally to one of his own party.+His character was decided. He was the proudest, most disagreeable man in+the world, and everybody hoped that he would never come there again.+Amongst the most violent against him was Mrs. Bennet, whose dislike of+his general behaviour was sharpened into particular resentment by his+having slighted one of her daughters.++Elizabeth Bennet had been obliged, by the scarcity of gentlemen, to sit+down for two dances; and during part of that time, Mr. Darcy had been+standing near enough for her to overhear a conversation between him and+Mr. Bingley, who came from the dance for a few minutes to press his+friend to join it.++“Come, Darcy,” said he, “I must have you dance. I hate to see you+standing about by yourself in this stupid manner. You had much better+dance.”++“I certainly shall not. You know how I detest it, unless I am+particularly acquainted with my partner. At such an assembly as this, it+would be insupportable. Your sisters are engaged, and there is not+another woman in the room whom it would not be a punishment to me to+stand up with.”++“I would not be so fastidious as you are,” cried Bingley, “for a+kingdom! Upon my honour, I never met with so many pleasant girls in my+life as I have this evening; and there are several of them, you see,+uncommonly pretty.”++“_You_ are dancing with the only handsome girl in the room,” said Mr.+Darcy, looking at the eldest Miss Bennet.++“Oh, she is the most beautiful creature I ever beheld! But there is one+of her sisters sitting down just behind you, who is very pretty, and I+dare say very agreeable. Do let me ask my partner to introduce you.”++[Illustration:++“She is tolerable”++[_Copyright 1894 by George Allen._]]++“Which do you mean?” and turning round, he looked for a moment at+Elizabeth, till, catching her eye, he withdrew his own, and coldly said,+“She is tolerable: but not handsome enough to tempt _me_; and I am in no+humour at present to give consequence to young ladies who are slighted+by other men. You had better return to your partner and enjoy her+smiles, for you are wasting your time with me.”++Mr. Bingley followed his advice. Mr. Darcy walked off; and Elizabeth+remained with no very cordial feelings towards him. She told the story,+however, with great spirit among her friends; for she had a lively,+playful disposition, which delighted in anything ridiculous.++The evening altogether passed off pleasantly to the whole family. Mrs.+Bennet had seen her eldest daughter much admired by the Netherfield+party. Mr. Bingley had danced with her twice, and she had been+distinguished by his sisters. Jane was as much gratified by this as her+mother could be, though in a quieter way. Elizabeth felt Jane’s+pleasure. Mary had heard herself mentioned to Miss Bingley as the most+accomplished girl in the neighbourhood; and Catherine and Lydia had been+fortunate enough to be never without partners, which was all that they+had yet learnt to care for at a ball. They returned, therefore, in good+spirits to Longbourn, the village where they lived, and of which they+were the principal inhabitants. They found Mr. Bennet still up. With a+book, he was regardless of time; and on the present occasion he had a+good deal of curiosity as to the event of an evening which had raised+such splendid expectations. He had rather hoped that all his wife’s+views on the stranger would be disappointed; but he soon found that he+had a very different story to hear.++“Oh, my dear Mr. Bennet,” as she entered the room, “we have had a most+delightful evening, a most excellent ball. I wish you had been there.+Jane was so admired, nothing could be like it. Everybody said how well+she looked; and Mr. Bingley thought her quite beautiful, and danced with+her twice. Only think of _that_, my dear: he actually danced with her+twice; and she was the only creature in the room that he asked a second+time. First of all, he asked Miss Lucas. I was so vexed to see him stand+up with her; but, however, he did not admire her at all; indeed, nobody+can, you know; and he seemed quite struck with Jane as she was going+down the dance. So he inquired who she was, and got introduced, and+asked her for the two next. Then, the two third he danced with Miss+King, and the two fourth with Maria Lucas, and the two fifth with Jane+again, and the two sixth with Lizzy, and the _Boulanger_----”++“If he had had any compassion for _me_,” cried her husband impatiently,+“he would not have danced half so much! For God’s sake, say no more of+his partners. O that he had sprained his ancle in the first dance!”++“Oh, my dear,” continued Mrs. Bennet, “I am quite delighted with him. He+is so excessively handsome! and his sisters are charming women. I never+in my life saw anything more elegant than their dresses. I dare say the+lace upon Mrs. Hurst’s gown----”++Here she was interrupted again. Mr. Bennet protested against any+description of finery. She was therefore obliged to seek another branch+of the subject, and related, with much bitterness of spirit, and some+exaggeration, the shocking rudeness of Mr. Darcy.++“But I can assure you,” she added, “that Lizzy does not lose much by not+suiting _his_ fancy; for he is a most disagreeable, horrid man, not at+all worth pleasing. So high and so conceited, that there was no enduring+him! He walked here, and he walked there, fancying himself so very+great! Not handsome enough to dance with! I wish you had been there, my+dear, to have given him one of your set-downs. I quite detest the man.”++[Illustration]++CHAPTER IV.++[Illustration]++When Jane and Elizabeth were alone, the former, who had been cautious in+her praise of Mr. Bingley before, expressed to her sister how very much+she admired him.++“He is just what a young man ought to be,” said she, “sensible,+good-humoured, lively; and I never saw such happy manners! so much ease,+with such perfect good breeding!”++“He is also handsome,” replied Elizabeth, “which a young man ought+likewise to be if he possibly can. His character is thereby complete.”++“I was very much flattered by his asking me to dance a second time. I+did not expect such a compliment.”++“Did not you? _I_ did for you. But that is one great difference between+us. Compliments always take _you_ by surprise, and _me_ never. What+could be more natural than his asking you again? He could not help+seeing that you were about five times as pretty as every other woman in+the room. No thanks to his gallantry for that. Well, he certainly is+very agreeable, and I give you leave to like him. You have liked many a+stupider person.”++“Dear Lizzy!”++“Oh, you are a great deal too apt, you know, to like people in general.+You never see a fault in anybody. All the world are good and agreeable+in your eyes. I never heard you speak ill of a human being in my life.”++“I would wish not to be hasty in censuring anyone; but I always speak+what I think.”++“I know you do: and it is _that_ which makes the wonder. With _your_+good sense, to be so honestly blind to the follies and nonsense of+others! Affectation of candour is common enough; one meets with it+everywhere. But to be candid without ostentation or design,--to take the+good of everybody’s character and make it still better, and say nothing+of the bad,--belongs to you alone. And so, you like this man’s sisters,+too, do you? Their manners are not equal to his.”++“Certainly not, at first; but they are very pleasing women when you+converse with them. Miss Bingley is to live with her brother, and keep+his house; and I am much mistaken if we shall not find a very charming+neighbour in her.”++Elizabeth listened in silence, but was not convinced: their behaviour at+the assembly had not been calculated to please in general; and with more+quickness of observation and less pliancy of temper than her sister, and+with a judgment, too, unassailed by any attention to herself, she was+very little disposed to approve them. They were, in fact, very fine+ladies; not deficient in good-humour when they were pleased, nor in the+power of being agreeable where they chose it; but proud and conceited.+They were rather handsome; had been educated in one of the first private+seminaries in town; had a fortune of twenty thousand pounds; were in the+habit of spending more than they ought, and of associating with people+of rank; and were, therefore, in every respect entitled to think well of+themselves and meanly of others. They were of a respectable family in+the north of England; a circumstance more deeply impressed on their+memories than that their brother’s fortune and their own had been+acquired by trade.++Mr. Bingley inherited property to the amount of nearly a hundred+thousand pounds from his father, who had intended to purchase an estate,+but did not live to do it. Mr. Bingley intended it likewise, and+sometimes made choice of his county; but, as he was now provided with a+good house and the liberty of a manor, it was doubtful to many of those+who best knew the easiness of his temper, whether he might not spend the+remainder of his days at Netherfield, and leave the next generation to+purchase.++His sisters were very anxious for his having an estate of his own; but+though he was now established only as a tenant, Miss Bingley was by no+means unwilling to preside at his table; nor was Mrs. Hurst, who had+married a man of more fashion than fortune, less disposed to consider+his house as her home when it suited her. Mr. Bingley had not been of+age two years when he was tempted, by an accidental recommendation, to+look at Netherfield House. He did look at it, and into it, for half an+hour; was pleased with the situation and the principal rooms, satisfied+with what the owner said in its praise, and took it immediately.++Between him and Darcy there was a very steady friendship, in spite of a+great opposition of character. Bingley was endeared to Darcy by the+easiness, openness, and ductility of his temper, though no disposition+could offer a greater contrast to his own, and though with his own he+never appeared dissatisfied. On the strength of Darcy’s regard, Bingley+had the firmest reliance, and of his judgment the highest opinion. In+understanding, Darcy was the superior. Bingley was by no means+deficient; but Darcy was clever. He was at the same time haughty,+reserved, and fastidious; and his manners, though well bred, were not+inviting. In that respect his friend had greatly the advantage. Bingley+was sure of being liked wherever he appeared; Darcy was continually+giving offence.++The manner in which they spoke of the Meryton assembly was sufficiently+characteristic. Bingley had never met with pleasanter people or prettier+girls in his life; everybody had been most kind and attentive to him;+there had been no formality, no stiffness; he had soon felt acquainted+with all the room; and as to Miss Bennet, he could not conceive an angel+more beautiful. Darcy, on the contrary, had seen a collection of people+in whom there was little beauty and no fashion, for none of whom he had+felt the smallest interest, and from none received either attention or+pleasure. Miss Bennet he acknowledged to be pretty; but she smiled too+much.++Mrs. Hurst and her sister allowed it to be so; but still they admired+her and liked her, and pronounced her to be a sweet girl, and one whom+they should not object to know more of. Miss Bennet was therefore+established as a sweet girl; and their brother felt authorized by such+commendation to think of her as he chose.++[Illustration: [_Copyright 1894 by George Allen._]]++CHAPTER V.++[Illustration]++Within a short walk of Longbourn lived a family with whom the Bennets+were particularly intimate. Sir William Lucas had been formerly in trade+in Meryton, where he had made a tolerable fortune, and risen to the+honour of knighthood by an address to the king during his mayoralty. The+distinction had, perhaps, been felt too strongly. It had given him a+disgust to his business and to his residence in a small market town;+and, quitting them both, he had removed with his family to a house about+a mile from Meryton, denominated from that period Lucas Lodge; where he+could think with pleasure of his own importance, and, unshackled by+business, occupy himself solely in being civil to all the world. For,+though elated by his rank, it did not render him supercilious; on the+contrary, he was all attention to everybody. By nature inoffensive,+friendly, and obliging, his presentation at St. James’s had made him+courteous.++Lady Lucas was a very good kind of woman, not too clever to be a+valuable neighbour to Mrs. Bennet. They had several children. The eldest+of them, a sensible, intelligent young woman, about twenty-seven, was+Elizabeth’s intimate friend.++That the Miss Lucases and the Miss Bennets should meet to talk over a+ball was absolutely necessary; and the morning after the assembly+brought the former to Longbourn to hear and to communicate.++“_You_ began the evening well, Charlotte,” said Mrs. Bennet, with civil+self-command, to Miss Lucas. “_You_ were Mr. Bingley’s first choice.”++“Yes; but he seemed to like his second better.”++“Oh, you mean Jane, I suppose, because he danced with her twice. To be+sure that _did_ seem as if he admired her--indeed, I rather believe he+_did_--I heard something about it--but I hardly know what--something+about Mr. Robinson.”++“Perhaps you mean what I overheard between him and Mr. Robinson: did not+I mention it to you? Mr. Robinson’s asking him how he liked our Meryton+assemblies, and whether he did not think there were a great many pretty+women in the room, and _which_ he thought the prettiest? and his+answering immediately to the last question, ‘Oh, the eldest Miss Bennet,+beyond a doubt: there cannot be two opinions on that point.’”++“Upon my word! Well, that was very decided, indeed--that does seem as+if--but, however, it may all come to nothing, you know.”++“_My_ overhearings were more to the purpose than _yours_, Eliza,” said+Charlotte. “Mr. Darcy is not so well worth listening to as his friend,+is he? Poor Eliza! to be only just _tolerable_.”++“I beg you will not put it into Lizzy’s head to be vexed by his+ill-treatment, for he is such a disagreeable man that it would be quite+a misfortune to be liked by him. Mrs. Long told me last night that he+sat close to her for half an hour without once opening his lips.”++[Illustration: “Without once opening his lips”++[_Copyright 1894 by George Allen._]]++“Are you quite sure, ma’am? Is not there a little mistake?” said Jane.+“I certainly saw Mr. Darcy speaking to her.”++“Ay, because she asked him at last how he liked Netherfield, and he+could not help answering her; but she said he seemed very angry at being+spoke to.”++“Miss Bingley told me,” said Jane, “that he never speaks much unless+among his intimate acquaintance. With _them_ he is remarkably+agreeable.”++“I do not believe a word of it, my dear. If he had been so very+agreeable, he would have talked to Mrs. Long. But I can guess how it+was; everybody says that he is eat up with pride, and I dare say he had+heard somehow that Mrs. Long does not keep a carriage, and had to come+to the ball in a hack chaise.”++“I do not mind his not talking to Mrs. Long,” said Miss Lucas, “but I+wish he had danced with Eliza.”++“Another time, Lizzy,” said her mother, “I would not dance with _him_,+if I were you.”++“I believe, ma’am, I may safely promise you _never_ to dance with him.”++“His pride,” said Miss Lucas, “does not offend _me_ so much as pride+often does, because there is an excuse for it. One cannot wonder that so+very fine a young man, with family, fortune, everything in his favour,+should think highly of himself. If I may so express it, he has a _right_+to be proud.”++“That is very true,” replied Elizabeth, “and I could easily forgive+_his_ pride, if he had not mortified _mine_.”++“Pride,” observed Mary, who piqued herself upon the solidity of her+reflections, “is a very common failing, I believe. By all that I have+ever read, I am convinced that it is very common indeed; that human+nature is particularly prone to it, and that there are very few of us+who do not cherish a feeling of self-complacency on the score of some+quality or other, real or imaginary. Vanity and pride are different+things, though the words are often used synonymously. A person may be+proud without being vain. Pride relates more to our opinion of+ourselves; vanity to what we would have others think of us.”++“If I were as rich as Mr. Darcy,” cried a young Lucas, who came with his+sisters, “I should not care how proud I was. I would keep a pack of+foxhounds, and drink a bottle of wine every day.”++“Then you would drink a great deal more than you ought,” said Mrs.+Bennet; “and if I were to see you at it, I should take away your bottle+directly.”++The boy protested that she should not; she continued to declare that she+would; and the argument ended only with the visit.++[Illustration]++[Illustration]++CHAPTER VI.++[Illustration]++The ladies of Longbourn soon waited on those of Netherfield. The visit+was returned in due form. Miss Bennet’s pleasing manners grew on the+good-will of Mrs. Hurst and Miss Bingley; and though the mother was+found to be intolerable, and the younger sisters not worth speaking to,+a wish of being better acquainted with _them_ was expressed towards the+two eldest. By Jane this attention was received with the greatest+pleasure; but Elizabeth still saw superciliousness in their treatment of+everybody, hardly excepting even her sister, and could not like them;+though their kindness to Jane, such as it was, had a value, as arising,+in all probability, from the influence of their brother’s admiration. It+was generally evident, whenever they met, that he _did_ admire her; and+to _her_ it was equally evident that Jane was yielding to the preference+which she had begun to entertain for him from the first, and was in a+way to be very much in love; but she considered with pleasure that it+was not likely to be discovered by the world in general, since Jane+united with great strength of feeling, a composure of temper and an+uniform cheerfulness of manner, which would guard her from the+suspicions of the impertinent. She mentioned this to her friend, Miss+Lucas.++“It may, perhaps, be pleasant,” replied Charlotte, “to be able to impose+on the public in such a case; but it is sometimes a disadvantage to be+so very guarded. If a woman conceals her affection with the same skill+from the object of it, she may lose the opportunity of fixing him; and+it will then be but poor consolation to believe the world equally in the+dark. There is so much of gratitude or vanity in almost every+attachment, that it is not safe to leave any to itself. We can all+_begin_ freely--a slight preference is natural enough; but there are+very few of us who have heart enough to be really in love without+encouragement. In nine cases out of ten, a woman had better show _more_+affection than she feels. Bingley likes your sister undoubtedly; but he+may never do more than like her, if she does not help him on.”++“But she does help him on, as much as her nature will allow. If _I_ can+perceive her regard for him, he must be a simpleton indeed not to+discover it too.”++“Remember, Eliza, that he does not know Jane’s disposition as you do.”++“But if a woman is partial to a man, and does not endeavor to conceal+it, he must find it out.”++“Perhaps he must, if he sees enough of her. But though Bingley and Jane+meet tolerably often, it is never for many hours together; and as they+always see each other in large mixed parties, it is impossible that+every moment should be employed in conversing together. Jane should+therefore make the most of every half hour in which she can command his+attention. When she is secure of him, there will be leisure for falling+in love as much as she chooses.”++“Your plan is a good one,” replied Elizabeth, “where nothing is in+question but the desire of being well married; and if I were determined+to get a rich husband, or any husband, I dare say I should adopt it. But+these are not Jane’s feelings; she is not acting by design. As yet she+cannot even be certain of the degree of her own regard, nor of its+reasonableness. She has known him only a fortnight. She danced four+dances with him at Meryton; she saw him one morning at his own house,+and has since dined in company with him four times. This is not quite+enough to make her understand his character.”++“Not as you represent it. Had she merely _dined_ with him, she might+only have discovered whether he had a good appetite; but you must+remember that four evenings have been also spent together--and four+evenings may do a great deal.”++“Yes: these four evenings have enabled them to ascertain that they both+like Vingt-un better than Commerce, but with respect to any other+leading characteristic, I do not imagine that much has been unfolded.”++“Well,” said Charlotte, “I wish Jane success with all my heart; and if+she were married to him to-morrow, I should think she had as good a+chance of happiness as if she were to be studying his character for a+twelvemonth. Happiness in marriage is entirely a matter of chance. If+the dispositions of the parties are ever so well known to each other, or+ever so similar beforehand, it does not advance their felicity in the+least. They always continue to grow sufficiently unlike afterwards to+have their share of vexation; and it is better to know as little as+possible of the defects of the person with whom you are to pass your+life.”++“You make me laugh, Charlotte; but it is not sound. You know it is not+sound, and that you would never act in this way yourself.”++Occupied in observing Mr. Bingley’s attention to her sister, Elizabeth+was far from suspecting that she was herself becoming an object of some+interest in the eyes of his friend. Mr. Darcy had at first scarcely+allowed her to be pretty: he had looked at her without admiration at the+ball; and when they next met, he looked at her only to criticise. But no+sooner had he made it clear to himself and his friends that she had+hardly a good feature in her face, than he began to find it was rendered+uncommonly intelligent by the beautiful expression of her dark eyes. To+this discovery succeeded some others equally mortifying. Though he had+detected with a critical eye more than one failure of perfect symmetry+in her form, he was forced to acknowledge her figure to be light and+pleasing; and in spite of his asserting that her manners were not those+of the fashionable world, he was caught by their easy playfulness. Of+this she was perfectly unaware: to her he was only the man who made+himself agreeable nowhere, and who had not thought her handsome enough+to dance with.++He began to wish to know more of her; and, as a step towards conversing+with her himself, attended to her conversation with others. His doing so+drew her notice. It was at Sir William Lucas’s, where a large party were+assembled.++“What does Mr. Darcy mean,” said she to Charlotte, “by listening to my+conversation with Colonel Forster?”++“That is a question which Mr. Darcy only can answer.”++“But if he does it any more, I shall certainly let him know that I see+what he is about. He has a very satirical eye, and if I do not begin by+being impertinent myself, I shall soon grow afraid of him.”++[Illustration: “The entreaties of several” [_Copyright 1894 by George+Allen._]]++On his approaching them soon afterwards, though without seeming to have+any intention of speaking, Miss Lucas defied her friend to mention such+a subject to him, which immediately provoking Elizabeth to do it, she+turned to him and said,--++“Did not you think, Mr. Darcy, that I expressed myself uncommonly well+just now, when I was teasing Colonel Forster to give us a ball at+Meryton?”++“With great energy; but it is a subject which always makes a lady+energetic.”++“You are severe on us.”++“It will be _her_ turn soon to be teased,” said Miss Lucas. “I am going+to open the instrument, Eliza, and you know what follows.”++“You are a very strange creature by way of a friend!--always wanting me+to play and sing before anybody and everybody! If my vanity had taken a+musical turn, you would have been invaluable; but as it is, I would+really rather not sit down before those who must be in the habit of+hearing the very best performers.” On Miss Lucas’s persevering, however,+she added, “Very well; if it must be so, it must.” And gravely glancing+at Mr. Darcy, “There is a very fine old saying, which everybody here is+of course familiar with--‘Keep your breath to cool your porridge,’--and+I shall keep mine to swell my song.”++Her performance was pleasing, though by no means capital. After a song+or two, and before she could reply to the entreaties of several that she+would sing again, she was eagerly succeeded at the instrument by her+sister Mary, who having, in consequence of being the only plain one in+the family, worked hard for knowledge and accomplishments, was always+impatient for display.++Mary had neither genius nor taste; and though vanity had given her+application, it had given her likewise a pedantic air and conceited+manner, which would have injured a higher degree of excellence than she+had reached. Elizabeth, easy and unaffected, had been listened to with+much more pleasure, though not playing half so well; and Mary, at the+end of a long concerto, was glad to purchase praise and gratitude by+Scotch and Irish airs, at the request of her younger sisters, who with+some of the Lucases, and two or three officers, joined eagerly in+dancing at one end of the room.++Mr. Darcy stood near them in silent indignation at such a mode of+passing the evening, to the exclusion of all conversation, and was too+much engrossed by his own thoughts to perceive that Sir William Lucas+was his neighbour, till Sir William thus began:--++“What a charming amusement for young people this is, Mr. Darcy! There is+nothing like dancing, after all. I consider it as one of the first+refinements of polished societies.”++“Certainly, sir; and it has the advantage also of being in vogue amongst+the less polished societies of the world: every savage can dance.”++Sir William only smiled. “Your friend performs delightfully,” he+continued, after a pause, on seeing Bingley join the group; “and I doubt+not that you are an adept in the science yourself, Mr. Darcy.”++“You saw me dance at Meryton, I believe, sir.”++“Yes, indeed, and received no inconsiderable pleasure from the sight. Do+you often dance at St. James’s?”++“Never, sir.”++“Do you not think it would be a proper compliment to the place?”++“It is a compliment which I never pay to any place if I can avoid it.”++“You have a house in town, I conclude?”++Mr. Darcy bowed.++“I had once some thoughts of fixing in town myself, for I am fond of+superior society; but I did not feel quite certain that the air of+London would agree with Lady Lucas.”++He paused in hopes of an answer: but his companion was not disposed to+make any; and Elizabeth at that instant moving towards them, he was+struck with the notion of doing a very gallant thing, and called out to+her,--++“My dear Miss Eliza, why are not you dancing? Mr. Darcy, you must allow+me to present this young lady to you as a very desirable partner. You+cannot refuse to dance, I am sure, when so much beauty is before you.”+And, taking her hand, he would have given it to Mr. Darcy, who, though+extremely surprised, was not unwilling to receive it, when she instantly+drew back, and said with some discomposure to Sir William,--++“Indeed, sir, I have not the least intention of dancing. I entreat you+not to suppose that I moved this way in order to beg for a partner.”++Mr. Darcy, with grave propriety, requested to be allowed the honour of+her hand, but in vain. Elizabeth was determined; nor did Sir William at+all shake her purpose by his attempt at persuasion.++“You excel so much in the dance, Miss Eliza, that it is cruel to deny me+the happiness of seeing you; and though this gentleman dislikes the+amusement in general, he can have no objection, I am sure, to oblige us+for one half hour.”++“Mr. Darcy is all politeness,” said Elizabeth, smiling.++“He is, indeed: but considering the inducement, my dear Miss Eliza, we+cannot wonder at his complaisance; for who would object to such a+partner?”++Elizabeth looked archly, and turned away. Her resistance had not injured+her with the gentleman, and he was thinking of her with some+complacency, when thus accosted by Miss Bingley,--++“I can guess the subject of your reverie.”++“I should imagine not.”++“You are considering how insupportable it would be to pass many+evenings in this manner,--in such society; and, indeed, I am quite of+your opinion. I was never more annoyed! The insipidity, and yet the+noise--the nothingness, and yet the self-importance, of all these+people! What would I give to hear your strictures on them!”++“Your conjecture is totally wrong, I assure you. My mind was more+agreeably engaged. I have been meditating on the very great pleasure+which a pair of fine eyes in the face of a pretty woman can bestow.”++Miss Bingley immediately fixed her eyes on his face, and desired he+would tell her what lady had the credit of inspiring such reflections.+Mr. Darcy replied, with great intrepidity,--++“Miss Elizabeth Bennet.”++“Miss Elizabeth Bennet!” repeated Miss Bingley. “I am all astonishment.+How long has she been such a favourite? and pray when am I to wish you+joy?”++“That is exactly the question which I expected you to ask. A lady’s+imagination is very rapid; it jumps from admiration to love, from love+to matrimony, in a moment. I knew you would be wishing me joy.”++“Nay, if you are so serious about it, I shall consider the matter as+absolutely settled. You will have a charming mother-in-law, indeed, and+of course she will be always at Pemberley with you.”++He listened to her with perfect indifference, while she chose to+entertain herself in this manner; and as his composure convinced her+that all was safe, her wit flowed along.++[Illustration:++ “A note for Miss Bennet”++[_Copyright 1894 by George Allen._]]++CHAPTER VII.++[Illustration]++Mr. Bennet’s property consisted almost entirely in an estate of two+thousand a year, which, unfortunately for his daughters, was entailed,+in default of heirs male, on a distant relation; and their mother’s+fortune, though ample for her situation in life, could but ill supply+the deficiency of his. Her father had been an attorney in Meryton, and+had left her four thousand pounds.++She had a sister married to a Mr. Philips, who had been a clerk to their+father and succeeded him in the business, and a brother settled in+London in a respectable line of trade.++The village of Longbourn was only one mile from Meryton; a most+convenient distance for the young ladies, who were usually tempted+thither three or four times a week, to pay their duty to their aunt, and+to a milliner’s shop just over the way. The two youngest of the family,+Catherine and Lydia, were particularly frequent in these attentions:+their minds were more vacant than their sisters’, and when nothing+better offered, a walk to Meryton was necessary to amuse their morning+hours and furnish conversation for the evening; and, however bare of+news the country in general might be, they always contrived to learn+some from their aunt. At present, indeed, they were well supplied both+with news and happiness by the recent arrival of a militia regiment in+the neighbourhood; it was to remain the whole winter, and Meryton was+the head-quarters.++Their visits to Mrs. Philips were now productive of the most interesting+intelligence. Every day added something to their knowledge of the+officers’ names and connections. Their lodgings were not long a secret,+and at length they began to know the officers themselves. Mr. Philips+visited them all, and this opened to his nieces a source of felicity+unknown before. They could talk of nothing but officers; and Mr.+Bingley’s large fortune, the mention of which gave animation to their+mother, was worthless in their eyes when opposed to the regimentals of+an ensign.++After listening one morning to their effusions on this subject, Mr.+Bennet coolly observed,--++“From all that I can collect by your manner of talking, you must be two+of the silliest girls in the country. I have suspected it some time, but+I am now convinced.”++Catherine was disconcerted, and made no answer; but Lydia, with perfect+indifference, continued to express her admiration of Captain Carter, and+her hope of seeing him in the course of the day, as he was going the+next morning to London.++“I am astonished, my dear,” said Mrs. Bennet, “that you should be so+ready to think your own children silly. If I wished to think slightingly+of anybody’s children, it should not be of my own, however.”++“If my children are silly, I must hope to be always sensible of it.”++“Yes; but as it happens, they are all of them very clever.”++“This is the only point, I flatter myself, on which we do not agree. I+had hoped that our sentiments coincided in every particular, but I must+so far differ from you as to think our two youngest daughters uncommonly+foolish.”++“My dear Mr. Bennet, you must not expect such girls to have the sense of+their father and mother. When they get to our age, I dare say they will+not think about officers any more than we do. I remember the time when I+liked a red coat myself very well--and, indeed, so I do still at my+heart; and if a smart young colonel, with five or six thousand a year,+should want one of my girls, I shall not say nay to him; and I thought+Colonel Forster looked very becoming the other night at Sir William’s in+his regimentals.”++“Mamma,” cried Lydia, “my aunt says that Colonel Forster and Captain+Carter do not go so often to Miss Watson’s as they did when they first+came; she sees them now very often standing in Clarke’s library.”++Mrs. Bennet was prevented replying by the entrance of the footman with a+note for Miss Bennet; it came from Netherfield, and the servant waited+for an answer. Mrs. Bennet’s eyes sparkled with pleasure, and she was+eagerly calling out, while her daughter read,--++“Well, Jane, who is it from? What is it about? What does he say? Well,+Jane, make haste and tell us; make haste, my love.”++“It is from Miss Bingley,” said Jane, and then read it aloud.++ /* NIND “My dear friend, */++ “If you are not so compassionate as to dine to-day with Louisa and+ me, we shall be in danger of hating each other for the rest of our+ lives; for a whole day’s _tête-à-tête_ between two women can never+ end without a quarrel. Come as soon as you can on the receipt of+ this. My brother and the gentlemen are to dine with the officers.+ Yours ever,++“CAROLINE BINGLEY.”++“With the officers!” cried Lydia: “I wonder my aunt did not tell us of+_that_.”++“Dining out,” said Mrs. Bennet; “that is very unlucky.”++“Can I have the carriage?” said Jane.++“No, my dear, you had better go on horseback, because it seems likely to+rain; and then you must stay all night.”++“That would be a good scheme,” said Elizabeth, “if you were sure that+they would not offer to send her home.”++“Oh, but the gentlemen will have Mr. Bingley’s chaise to go to Meryton;+and the Hursts have no horses to theirs.”++“I had much rather go in the coach.”++“But, my dear, your father cannot spare the horses, I am sure. They are+wanted in the farm, Mr. Bennet, are not they?”++[Illustration: Cheerful prognostics]++“They are wanted in the farm much oftener than I can get them.”++“But if you have got them to-day,” said Elizabeth, “my mother’s purpose+will be answered.”++She did at last extort from her father an acknowledgment that the horses+were engaged; Jane was therefore obliged to go on horseback, and her+mother attended her to the door with many cheerful prognostics of a bad+day. Her hopes were answered; Jane had not been gone long before it+rained hard. Her sisters were uneasy for her, but her mother was+delighted. The rain continued the whole evening without intermission;+Jane certainly could not come back.++“This was a lucky idea of mine, indeed!” said Mrs. Bennet, more than+once, as if the credit of making it rain were all her own. Till the next+morning, however, she was not aware of all the felicity of her+contrivance. Breakfast was scarcely over when a servant from Netherfield+brought the following note for Elizabeth:--++ /* NIND “My dearest Lizzie, */++ “I find myself very unwell this morning, which, I suppose, is to be+ imputed to my getting wet through yesterday. My kind friends will+ not hear of my returning home till I am better. They insist also on+ my seeing Mr. Jones--therefore do not be alarmed if you should hear+ of his having been to me--and, excepting a sore throat and a+ headache, there is not much the matter with me.++“Yours, etc.”++“Well, my dear,” said Mr. Bennet, when Elizabeth had read the note+aloud, “if your daughter should have a dangerous fit of illness--if she+should die--it would be a comfort to know that it was all in pursuit of+Mr. Bingley, and under your orders.”++“Oh, I am not at all afraid of her dying. People do not die of little+trifling colds. She will be taken good care of. As long as she stays+there, it is all very well. I would go and see her if I could have the+carriage.”++Elizabeth, feeling really anxious, determined to go to her, though the+carriage was not to be had: and as she was no horsewoman, walking was+her only alternative. She declared her resolution.++“How can you be so silly,” cried her mother, “as to think of such a+thing, in all this dirt! You will not be fit to be seen when you get+there.”++“I shall be very fit to see Jane--which is all I want.”++“Is this a hint to me, Lizzy,” said her father, “to send for the+horses?”++“No, indeed. I do not wish to avoid the walk. The distance is nothing,+when one has a motive; only three miles. I shall be back by dinner.”++“I admire the activity of your benevolence,” observed Mary, “but every+impulse of feeling should be guided by reason; and, in my opinion,+exertion should always be in proportion to what is required.”++“We will go as far as Meryton with you,” said Catherine and Lydia.+Elizabeth accepted their company, and the three young ladies set off+together.++“If we make haste,” said Lydia, as they walked along, “perhaps we may+see something of Captain Carter, before he goes.”++In Meryton they parted: the two youngest repaired to the lodgings of one+of the officers’ wives, and Elizabeth continued her walk alone, crossing+field after field at a quick pace, jumping over stiles and springing+over puddles, with impatient activity, and finding herself at last+within view of the house, with weary ancles, dirty stockings, and a face+glowing with the warmth of exercise.++She was shown into the breakfast parlour, where all but Jane were+assembled, and where her appearance created a great deal of surprise.+That she should have walked three miles so early in the day in such+dirty weather, and by herself, was almost incredible to Mrs. Hurst and+Miss Bingley; and Elizabeth was convinced that they held her in contempt+for it. She was received, however, very politely by them; and in their+brother’s manners there was something better than politeness--there was+good-humour and kindness. Mr. Darcy said very little, and Mr. Hurst+nothing at all. The former was divided between admiration of the+brilliancy which exercise had given to her complexion and doubt as to+the occasion’s justifying her coming so far alone. The latter was+thinking only of his breakfast.++Her inquiries after her sister were not very favourably answered. Miss+Bennet had slept ill, and though up, was very feverish, and not well+enough to leave her room. Elizabeth was glad to be taken to her+immediately; and Jane, who had only been withheld by the fear of giving+alarm or inconvenience, from expressing in her note how much she longed+for such a visit, was delighted at her entrance. She was not equal,+however, to much conversation; and when Miss Bingley left them together,+could attempt little beside expressions of gratitude for the+extraordinary kindness she was treated with. Elizabeth silently attended+her.++When breakfast was over, they were joined by the sisters; and Elizabeth+began to like them herself, when she saw how much affection and+solicitude they showed for Jane. The apothecary came; and having+examined his patient, said, as might be supposed, that she had caught a+violent cold, and that they must endeavour to get the better of it;+advised her to return to bed, and promised her some draughts. The advice+was followed readily, for the feverish symptoms increased, and her head+ached acutely. Elizabeth did not quit her room for a moment, nor were+the other ladies often absent; the gentlemen being out, they had in fact+nothing to do elsewhere.++When the clock struck three, Elizabeth felt that she must go, and very+unwillingly said so. Miss Bingley offered her the carriage, and she only+wanted a little pressing to accept it, when Jane testified such concern+at parting with her that Miss Bingley was obliged to convert the offer+of the chaise into an invitation to remain at Netherfield for the+present. Elizabeth most thankfully consented, and a servant was+despatched to Longbourn, to acquaint the family with her stay, and bring+back a supply of clothes.++[Illustration:++“The Apothecary came”+]++[Illustration:++“covering a screen”+]++CHAPTER VIII.++[Illustration]++At five o’clock the two ladies retired to dress, and at half-past six+Elizabeth was summoned to dinner. To the civil inquiries which then+poured in, and amongst which she had the pleasure of distinguishing the+much superior solicitude of Mr. Bingley, she could not make a very+favourable answer. Jane was by no means better. The sisters, on hearing+this, repeated three or four times how much they were grieved, how+shocking it was to have a bad cold, and how excessively they disliked+being ill themselves; and then thought no more of the matter: and their+indifference towards Jane, when not immediately before them, restored+Elizabeth to the enjoyment of all her original dislike.++Their brother, indeed, was the only one of the party whom she could+regard with any complacency. His anxiety for Jane was evident, and his+attentions to herself most pleasing; and they prevented her feeling+herself so much an intruder as she believed she was considered by the+others. She had very little notice from any but him. Miss Bingley was+engrossed by Mr. Darcy, her sister scarcely less so; and as for Mr.+Hurst, by whom Elizabeth sat, he was an indolent man, who lived only to+eat, drink, and play at cards, who, when he found her prefer a plain+dish to a ragout, had nothing to say to her.++When dinner was over, she returned directly to Jane, and Miss Bingley+began abusing her as soon as she was out of the room. Her manners were+pronounced to be very bad indeed,--a mixture of pride and impertinence:+she had no conversation, no style, no taste, no beauty. Mrs. Hurst+thought the same, and added,--++“She has nothing, in short, to recommend her, but being an excellent+walker. I shall never forget her appearance this morning. She really+looked almost wild.”++“She did indeed, Louisa. I could hardly keep my countenance. Very+nonsensical to come at all! Why must _she_ be scampering about the+country, because her sister had a cold? Her hair so untidy, so blowzy!”++“Yes, and her petticoat; I hope you saw her petticoat, six inches deep+in mud, I am absolutely certain, and the gown which had been let down to+hide it not doing its office.”++“Your picture may be very exact, Louisa,” said Bingley; “but this was+all lost upon me. I thought Miss Elizabeth Bennet looked remarkably well+when she came into the room this morning. Her dirty petticoat quite+escaped my notice.”++“_You_ observed it, Mr. Darcy, I am sure,” said Miss Bingley; “and I am+inclined to think that you would not wish to see _your sister_ make such+an exhibition.”++“Certainly not.”++“To walk three miles, or four miles, or five miles, or whatever it is,+above her ancles in dirt, and alone, quite alone! what could she mean by+it? It seems to me to show an abominable sort of conceited independence,+a most country-town indifference to decorum.”++“It shows an affection for her sister that is very pleasing,” said+Bingley.++“I am afraid, Mr. Darcy,” observed Miss Bingley, in a half whisper,+“that this adventure has rather affected your admiration of her fine+eyes.”++“Not at all,” he replied: “they were brightened by the exercise.” A+short pause followed this speech, and Mrs. Hurst began again,--++“I have an excessive regard for Jane Bennet,--she is really a very sweet+girl,--and I wish with all my heart she were well settled. But with such+a father and mother, and such low connections, I am afraid there is no+chance of it.”++“I think I have heard you say that their uncle is an attorney in+Meryton?”++“Yes; and they have another, who lives somewhere near Cheapside.”++“That is capital,” added her sister; and they both laughed heartily.++“If they had uncles enough to fill _all_ Cheapside,” cried Bingley, “it+would not make them one jot less agreeable.”++“But it must very materially lessen their chance of marrying men of any+consideration in the world,” replied Darcy.++To this speech Bingley made no answer; but his sisters gave it their+hearty assent, and indulged their mirth for some time at the expense of+their dear friend’s vulgar relations.++With a renewal of tenderness, however, they repaired to her room on+leaving the dining-parlour, and sat with her till summoned to coffee.+She was still very poorly, and Elizabeth would not quit her at all, till+late in the evening, when she had the comfort of seeing her asleep, and+when it appeared to her rather right than pleasant that she should go+down stairs herself. On entering the drawing-room, she found the whole+party at loo, and was immediately invited to join them; but suspecting+them to be playing high, she declined it, and making her sister the+excuse, said she would amuse herself, for the short time she could stay+below, with a book. Mr. Hurst looked at her with astonishment.++“Do you prefer reading to cards?” said he; “that is rather singular.”++“Miss Eliza Bennet,” said Miss Bingley, “despises cards. She is a great+reader, and has no pleasure in anything else.”++“I deserve neither such praise nor such censure,” cried Elizabeth; “I+am _not_ a great reader, and I have pleasure in many things.”++“In nursing your sister I am sure you have pleasure,” said Bingley; “and+I hope it will soon be increased by seeing her quite well.”++Elizabeth thanked him from her heart, and then walked towards a table+where a few books were lying. He immediately offered to fetch her+others; all that his library afforded.++“And I wish my collection were larger for your benefit and my own+credit; but I am an idle fellow; and though I have not many, I have more+than I ever looked into.”++Elizabeth assured him that she could suit herself perfectly with those+in the room.++“I am astonished,” said Miss Bingley, “that my father should have left+so small a collection of books. What a delightful library you have at+Pemberley, Mr. Darcy!”++“It ought to be good,” he replied: “it has been the work of many+generations.”++“And then you have added so much to it yourself--you are always buying+books.”++“I cannot comprehend the neglect of a family library in such days as+these.”++“Neglect! I am sure you neglect nothing that can add to the beauties of+that noble place. Charles, when you build _your_ house, I wish it may be+half as delightful as Pemberley.”++“I wish it may.”++“But I would really advise you to make your purchase in that+neighbourhood, and take Pemberley for a kind of model. There is not a+finer county in England than Derbyshire.”++“With all my heart: I will buy Pemberley itself, if Darcy will sell it.”++“I am talking of possibilities, Charles.”++“Upon my word, Caroline, I should think it more possible to get+Pemberley by purchase than by imitation.”++Elizabeth was so much caught by what passed, as to leave her very little+attention for her book; and, soon laying it wholly aside, she drew near+the card-table, and stationed herself between Mr. Bingley and his eldest+sister, to observe the game.++“Is Miss Darcy much grown since the spring?” said Miss Bingley: “will+she be as tall as I am?”++“I think she will. She is now about Miss Elizabeth Bennet’s height, or+rather taller.”++“How I long to see her again! I never met with anybody who delighted me+so much. Such a countenance, such manners, and so extremely accomplished+for her age! Her performance on the pianoforte is exquisite.”++“It is amazing to me,” said Bingley, “how young ladies can have patience+to be so very accomplished as they all are.”++“All young ladies accomplished! My dear Charles, what do you mean?”++“Yes, all of them, I think. They all paint tables, cover screens, and+net purses. I scarcely know any one who cannot do all this; and I am+sure I never heard a young lady spoken of for the first time, without+being informed that she was very accomplished.”++“Your list of the common extent of accomplishments,” said Darcy, “has+too much truth. The word is applied to many a woman who deserves it no+otherwise than by netting a purse or covering a screen; but I am very+far from agreeing with you in your estimation of ladies in general. I+cannot boast of knowing more than half-a-dozen in the whole range of my+acquaintance that are really accomplished.”++“Nor I, I am sure,” said Miss Bingley.++“Then,” observed Elizabeth, “you must comprehend a great deal in your+idea of an accomplished woman.”++“Yes; I do comprehend a great deal in it.”++“Oh, certainly,” cried his faithful assistant, “no one can be really+esteemed accomplished who does not greatly surpass what is usually met+with. A woman must have a thorough knowledge of music, singing, drawing,+dancing, and the modern languages, to deserve the word; and, besides all+this, she must possess a certain something in her air and manner of+walking, the tone of her voice, her address and expressions, or the word+will be but half deserved.”++“All this she must possess,” added Darcy; “and to all she must yet add+something more substantial in the improvement of her mind by extensive+reading.”++“I am no longer surprised at your knowing _only_ six accomplished women.+I rather wonder now at your knowing _any_.”++“Are you so severe upon your own sex as to doubt the possibility of all+this?”++“_I_ never saw such a woman. _I_ never saw such capacity, and taste, and+application, and elegance, as you describe, united.”++Mrs. Hurst and Miss Bingley both cried out against the injustice of her+implied doubt, and were both protesting that they knew many women who+answered this description, when Mr. Hurst called them to order, with+bitter complaints of their inattention to what was going forward. As all+conversation was thereby at an end, Elizabeth soon afterwards left the+room.++“Eliza Bennet,” said Miss Bingley, when the door was closed on her, “is+one of those young ladies who seek to recommend themselves to the other+sex by undervaluing their own; and with many men, I daresay, it+succeeds; but, in my opinion, it is a paltry device, a very mean art.”++“Undoubtedly,” replied Darcy, to whom this remark was chiefly addressed,+“there is meanness in _all_ the arts which ladies sometimes condescend+to employ for captivation. Whatever bears affinity to cunning is+despicable.”++Miss Bingley was not so entirely satisfied with this reply as to+continue the subject.++Elizabeth joined them again only to say that her sister was worse, and+that she could not leave her. Bingley urged Mr. Jones’s being sent for+immediately; while his sisters, convinced that no country advice could+be of any service, recommended an express to town for one of the most+eminent physicians. This she would not hear of; but she was not so+unwilling to comply with their brother’s proposal; and it was settled+that Mr. Jones should be sent for early in the morning, if Miss Bennet+were not decidedly better. Bingley was quite uncomfortable; his sisters+declared that they were miserable. They solaced their wretchedness,+however, by duets after supper; while he could find no better relief to+his feelings than by giving his housekeeper directions that every+possible attention might be paid to the sick lady and her sister.++[Illustration:++M^{rs} Bennet and her two youngest girls++[_Copyright 1894 by George Allen._]]++CHAPTER IX.++[Illustration]++Elizabeth passed the chief of the night in her sister’s room, and in the+morning had the pleasure of being able to send a tolerable answer to the+inquiries which she very early received from Mr. Bingley by a housemaid,+and some time afterwards from the two elegant ladies who waited on his+sisters. In spite of this amendment, however, she requested to have a+note sent to Longbourn, desiring her mother to visit Jane, and form her+own judgment of her situation. The note was immediately despatched, and+its contents as quickly complied with. Mrs. Bennet, accompanied by her+two youngest girls, reached Netherfield soon after the family breakfast.++Had she found Jane in any apparent danger, Mrs. Bennet would have been+very miserable; but being satisfied on seeing her that her illness was+not alarming, she had no wish of her recovering immediately, as her+restoration to health would probably remove her from Netherfield. She+would not listen, therefore, to her daughter’s proposal of being carried+home; neither did the apothecary, who arrived about the same time, think+it at all advisable. After sitting a little while with Jane, on Miss+Bingley’s appearance and invitation, the mother and three daughters all+attended her into the breakfast parlour. Bingley met them with hopes+that Mrs. Bennet had not found Miss Bennet worse than she expected.++“Indeed I have, sir,” was her answer. “She is a great deal too ill to be+moved. Mr. Jones says we must not think of moving her. We must trespass+a little longer on your kindness.”++“Removed!” cried Bingley. “It must not be thought of. My sister, I am+sure, will not hear of her removal.”++“You may depend upon it, madam,” said Miss Bingley, with cold civility,+“that Miss Bennet shall receive every possible attention while she+remains with us.”++Mrs. Bennet was profuse in her acknowledgments.++“I am sure,” she added, “if it was not for such good friends, I do not+know what would become of her, for she is very ill indeed, and suffers a+vast deal, though with the greatest patience in the world, which is+always the way with her, for she has, without exception, the sweetest+temper I ever met with. I often tell my other girls they are nothing to+_her_. You have a sweet room here, Mr. Bingley, and a charming prospect+over that gravel walk. I do not know a place in the country that is+equal to Netherfield. You will not think of quitting it in a hurry, I+hope, though you have but a short lease.”++“Whatever I do is done in a hurry,” replied he; “and therefore if I+should resolve to quit Netherfield, I should probably be off in five+minutes. At present, however, I consider myself as quite fixed here.”++“That is exactly what I should have supposed of you,” said Elizabeth.++“You begin to comprehend me, do you?” cried he, turning towards her.++“Oh yes--I understand you perfectly.”++“I wish I might take this for a compliment; but to be so easily seen+through, I am afraid, is pitiful.”++“That is as it happens. It does not necessarily follow that a deep,+intricate character is more or less estimable than such a one as yours.”++“Lizzy,” cried her mother, “remember where you are, and do not run on in+the wild manner that you are suffered to do at home.”++“I did not know before,” continued Bingley, immediately, “that you were+a studier of character. It must be an amusing study.”++“Yes; but intricate characters are the _most_ amusing. They have at+least that advantage.”++“The country,” said Darcy, “can in general supply but few subjects for+such a study. In a country neighbourhood you move in a very confined and+unvarying society.”++“But people themselves alter so much, that there is something new to be+observed in them for ever.”++“Yes, indeed,” cried Mrs. Bennet, offended by his manner of mentioning a+country neighbourhood. “I assure you there is quite as much of _that_+going on in the country as in town.”++Everybody was surprised; and Darcy, after looking at her for a moment,+turned silently away. Mrs. Bennet, who fancied she had gained a complete+victory over him, continued her triumph,--++“I cannot see that London has any great advantage over the country, for+my part, except the shops and public places. The country is a vast deal+pleasanter, is not it, Mr. Bingley?”++“When I am in the country,” he replied, “I never wish to leave it; and+when I am in town, it is pretty much the same. They have each their+advantages, and I can be equally happy in either.”++“Ay, that is because you have the right disposition. But that+gentleman,” looking at Darcy, “seemed to think the country was nothing+at all.”++“Indeed, mamma, you are mistaken,” said Elizabeth, blushing for her+mother. “You quite mistook Mr. Darcy. He only meant that there was not+such a variety of people to be met with in the country as in town, which+you must acknowledge to be true.”++“Certainly, my dear, nobody said there were; but as to not meeting with+many people in this neighbourhood, I believe there are few+neighbourhoods larger. I know we dine with four-and-twenty families.”++Nothing but concern for Elizabeth could enable Bingley to keep his+countenance. His sister was less delicate, and directed her eye towards+Mr. Darcy with a very expressive smile. Elizabeth, for the sake of+saying something that might turn her mother’s thoughts, now asked her if+Charlotte Lucas had been at Longbourn since _her_ coming away.++“Yes, she called yesterday with her father. What an agreeable man Sir+William is, Mr. Bingley--is not he? so much the man of fashion! so+genteel and so easy! He has always something to say to everybody. _That_+is my idea of good breeding; and those persons who fancy themselves very+important and never open their mouths quite mistake the matter.”++“Did Charlotte dine with you?”++“No, she would go home. I fancy she was wanted about the mince-pies. For+my part, Mr. Bingley, _I_ always keep servants that can do their own+work; _my_ daughters are brought up differently. But everybody is to+judge for themselves, and the Lucases are a very good sort of girls, I+assure you. It is a pity they are not handsome! Not that _I_ think+Charlotte so _very_ plain; but then she is our particular friend.”++“She seems a very pleasant young woman,” said Bingley.++“Oh dear, yes; but you must own she is very plain. Lady Lucas herself+has often said so, and envied me Jane’s beauty. I do not like to boast+of my own child; but to be sure, Jane--one does not often see anybody+better looking. It is what everybody says. I do not trust my own+partiality. When she was only fifteen there was a gentleman at my+brother Gardiner’s in town so much in love with her, that my+sister-in-law was sure he would make her an offer before we came away.+But, however, he did not. Perhaps he thought her too young. However, he+wrote some verses on her, and very pretty they were.”++“And so ended his affection,” said Elizabeth, impatiently. “There has+been many a one, I fancy, overcome in the same way. I wonder who first+discovered the efficacy of poetry in driving away love!”++“I have been used to consider poetry as the _food_ of love,” said Darcy.++“Of a fine, stout, healthy love it may. Everything nourishes what is+strong already. But if it be only a slight, thin sort of inclination, I+am convinced that one good sonnet will starve it entirely away.”++Darcy only smiled; and the general pause which ensued made Elizabeth+tremble lest her mother should be exposing herself again. She longed to+speak, but could think of nothing to say; and after a short silence Mrs.+Bennet began repeating her thanks to Mr. Bingley for his kindness to+Jane, with an apology for troubling him also with Lizzy. Mr. Bingley was+unaffectedly civil in his answer, and forced his younger sister to be+civil also, and say what the occasion required. She performed her part,+indeed, without much graciousness, but Mrs. Bennet was satisfied, and+soon afterwards ordered her carriage. Upon this signal, the youngest of+her daughters put herself forward. The two girls had been whispering to+each other during the whole visit; and the result of it was, that the+youngest should tax Mr. Bingley with having promised on his first coming+into the country to give a ball at Netherfield.++Lydia was a stout, well-grown girl of fifteen, with a fine complexion+and good-humoured countenance; a favourite with her mother, whose+affection had brought her into public at an early age. She had high+animal spirits, and a sort of natural self-consequence, which the+attentions of the officers, to whom her uncle’s good dinners and her+own easy manners recommended her, had increased into assurance. She was+very equal, therefore, to address Mr. Bingley on the subject of the+ball, and abruptly reminded him of his promise; adding, that it would be+the most shameful thing in the world if he did not keep it. His answer+to this sudden attack was delightful to her mother’s ear.++“I am perfectly ready, I assure you, to keep my engagement; and, when+your sister is recovered, you shall, if you please, name the very day of+the ball. But you would not wish to be dancing while she is ill?”++Lydia declared herself satisfied. “Oh yes--it would be much better to+wait till Jane was well; and by that time, most likely, Captain Carter+would be at Meryton again. And when you have given _your_ ball,” she+added, “I shall insist on their giving one also. I shall tell Colonel+Forster it will be quite a shame if he does not.”++Mrs. Bennet and her daughters then departed, and Elizabeth returned+instantly to Jane, leaving her own and her relations’ behaviour to the+remarks of the two ladies and Mr. Darcy; the latter of whom, however,+could not be prevailed on to join in their censure of _her_, in spite of+all Miss Bingley’s witticisms on _fine eyes_.++[Illustration]++CHAPTER X.++[Illustration]++The day passed much as the day before had done. Mrs. Hurst and Miss+Bingley had spent some hours of the morning with the invalid, who+continued, though slowly, to mend; and, in the evening, Elizabeth joined+their party in the drawing-room. The loo table, however, did not appear.+Mr. Darcy was writing, and Miss Bingley, seated near him, was watching+the progress of his letter, and repeatedly calling off his attention by+messages to his sister. Mr. Hurst and Mr. Bingley were at piquet, and+Mrs. Hurst was observing their game.++Elizabeth took up some needlework, and was sufficiently amused in+attending to what passed between Darcy and his companion. The perpetual+commendations of the lady either on his hand-writing, or on the evenness+of his lines, or on the length of his letter, with the perfect unconcern+with which her praises were received, formed a curious dialogue, and was+exactly in unison with her opinion of each.++“How delighted Miss Darcy will be to receive such a letter!”++He made no answer.++“You write uncommonly fast.”++“You are mistaken. I write rather slowly.”++“How many letters you must have occasion to write in the course of a+year! Letters of business, too! How odious I should think them!”++“It is fortunate, then, that they fall to my lot instead of to yours.”++“Pray tell your sister that I long to see her.”++“I have already told her so once, by your desire.”++“I am afraid you do not like your pen. Let me mend it for you. I mend+pens remarkably well.”++“Thank you--but I always mend my own.”++“How can you contrive to write so even?”++He was silent.++“Tell your sister I am delighted to hear of her improvement on the harp,+and pray let her know that I am quite in raptures with her beautiful+little design for a table, and I think it infinitely superior to Miss+Grantley’s.”++“Will you give me leave to defer your raptures till I write again? At+present I have not room to do them justice.”++“Oh, it is of no consequence. I shall see her in January. But do you+always write such charming long letters to her, Mr. Darcy?”++“They are generally long; but whether always charming, it is not for me+to determine.”++“It is a rule with me, that a person who can write a long letter with+ease cannot write ill.”++“That will not do for a compliment to Darcy, Caroline,” cried her+brother, “because he does _not_ write with ease. He studies too much+for words of four syllables. Do not you, Darcy?”++“My style of writing is very different from yours.”++“Oh,” cried Miss Bingley, “Charles writes in the most careless way+imaginable. He leaves out half his words, and blots the rest.”++“My ideas flow so rapidly that I have not time to express them; by which+means my letters sometimes convey no ideas at all to my correspondents.”++“Your humility, Mr. Bingley,” said Elizabeth, “must disarm reproof.”++“Nothing is more deceitful,” said Darcy, “than the appearance of+humility. It is often only carelessness of opinion, and sometimes an+indirect boast.”++“And which of the two do you call _my_ little recent piece of modesty?”++“The indirect boast; for you are really proud of your defects in+writing, because you consider them as proceeding from a rapidity of+thought and carelessness of execution, which, if not estimable, you+think at least highly interesting. The power of doing anything with+quickness is always much prized by the possessor, and often without any+attention to the imperfection of the performance. When you told Mrs.+Bennet this morning, that if you ever resolved on quitting Netherfield+you should be gone in five minutes, you meant it to be a sort of+panegyric, of compliment to yourself; and yet what is there so very+laudable in a precipitance which must leave very necessary business+undone, and can be of no real advantage to yourself or anyone else?”++“Nay,” cried Bingley, “this is too much, to remember at night all the+foolish things that were said in the morning. And yet, upon my honour, I+believed what I said of myself to be true, and I believe it at this+moment. At least, therefore, I did not assume the character of needless+precipitance merely to show off before the ladies.”++“I daresay you believed it; but I am by no means convinced that you+would be gone with such celerity. Your conduct would be quite as+dependent on chance as that of any man I know; and if, as you were+mounting your horse, a friend were to say, ‘Bingley, you had better stay+till next week,’ you would probably do it--you would probably not+go--and, at another word, might stay a month.”++“You have only proved by this,” cried Elizabeth, “that Mr. Bingley did+not do justice to his own disposition. You have shown him off now much+more than he did himself.”++“I am exceedingly gratified,” said Bingley, “by your converting what my+friend says into a compliment on the sweetness of my temper. But I am+afraid you are giving it a turn which that gentleman did by no means+intend; for he would certainly think the better of me if, under such a+circumstance, I were to give a flat denial, and ride off as fast as I+could.”++“Would Mr. Darcy then consider the rashness of your original intention+as atoned for by your obstinacy in adhering to it?”++“Upon my word, I cannot exactly explain the matter--Darcy must speak for+himself.”++“You expect me to account for opinions which you choose to call mine,+but which I have never acknowledged. Allowing the case, however, to+stand according to your representation, you must remember, Miss Bennet,+that the friend who is supposed to desire his return to the house, and+the delay of his plan, has merely desired it, asked it without offering+one argument in favour of its propriety.”++“To yield readily--easily--to the _persuasion_ of a friend is no merit+with you.”++“To yield without conviction is no compliment to the understanding of+either.”++“You appear to me, Mr. Darcy, to allow nothing for the influence of+friendship and affection. A regard for the requester would often make+one readily yield to a request, without waiting for arguments to reason+one into it. I am not particularly speaking of such a case as you have+supposed about Mr. Bingley. We may as well wait, perhaps, till the+circumstance occurs, before we discuss the discretion of his behaviour+thereupon. But in general and ordinary cases, between friend and friend,+where one of them is desired by the other to change a resolution of no+very great moment, should you think ill of that person for complying+with the desire, without waiting to be argued into it?”++“Will it not be advisable, before we proceed on this subject, to arrange+with rather more precision the degree of importance which is to+appertain to this request, as well as the degree of intimacy subsisting+between the parties?”++“By all means,” cried Bingley; “let us hear all the particulars, not+forgetting their comparative height and size, for that will have more+weight in the argument, Miss Bennet, than you may be aware of. I assure+you that if Darcy were not such a great tall fellow, in comparison with+myself, I should not pay him half so much deference. I declare I do not+know a more awful object than Darcy on particular occasions, and in+particular places; at his own house especially, and of a Sunday evening,+when he has nothing to do.”++Mr. Darcy smiled; but Elizabeth thought she could perceive that he was+rather offended, and therefore checked her laugh. Miss Bingley warmly+resented the indignity he had received, in an expostulation with her+brother for talking such nonsense.++“I see your design, Bingley,” said his friend. “You dislike an argument,+and want to silence this.”++“Perhaps I do. Arguments are too much like disputes. If you and Miss+Bennet will defer yours till I am out of the room, I shall be very+thankful; and then you may say whatever you like of me.”++“What you ask,” said Elizabeth, “is no sacrifice on my side; and Mr.+Darcy had much better finish his letter.”++Mr. Darcy took her advice, and did finish his letter.++When that business was over, he applied to Miss Bingley and Elizabeth+for the indulgence of some music. Miss Bingley moved with alacrity to+the pianoforte, and after a polite request that Elizabeth would lead the+way, which the other as politely and more earnestly negatived, she+seated herself.++Mrs. Hurst sang with her sister; and while they were thus employed,+Elizabeth could not help observing, as she turned over some music-books+that lay on the instrument, how frequently Mr. Darcy’s eyes were fixed+on her. She hardly knew how to suppose that she could be an object of+admiration to so great a man, and yet that he should look at her because+he disliked her was still more strange. She could only imagine, however,+at last, that she drew his notice because there was something about her+more wrong and reprehensible, according to his ideas of right, than in+any other person present. The supposition did not pain her. She liked+him too little to care for his approbation.++After playing some Italian songs, Miss Bingley varied the charm by a+lively Scotch air; and soon afterwards Mr. Darcy, drawing near+Elizabeth, said to her,--++“Do you not feel a great inclination, Miss Bennet, to seize such an+opportunity of dancing a reel?”++She smiled, but made no answer. He repeated the question, with some+surprise at her silence.++“Oh,” said she, “I heard you before; but I could not immediately+determine what to say in reply. You wanted me, I know, to say ‘Yes,’+that you might have the pleasure of despising my taste; but I always+delight in overthrowing those kind of schemes, and cheating a person of+their premeditated contempt. I have, therefore, made up my mind to tell+you that I do not want to dance a reel at all; and now despise me if you+dare.”++“Indeed I do not dare.”++Elizabeth, having rather expected to affront him, was amazed at his+gallantry; but there was a mixture of sweetness and archness in her+manner which made it difficult for her to affront anybody, and Darcy had+never been so bewitched by any woman as he was by her. He really+believed that, were it not for the inferiority of her connections, he+should be in some danger.++Miss Bingley saw, or suspected, enough to be jealous; and her great+anxiety for the recovery of her dear friend Jane received some+assistance from her desire of getting rid of Elizabeth.++She often tried to provoke Darcy into disliking her guest, by talking of+their supposed marriage, and planning his happiness in such an alliance.++“I hope,” said she, as they were walking together in the shrubbery the+next day, “you will give your mother-in-law a few hints, when this+desirable event takes place, as to the advantage of holding her tongue;+and if you can compass it, to cure the younger girls of running after+the officers. And, if I may mention so delicate a subject, endeavour to+check that little something, bordering on conceit and impertinence,+which your lady possesses.”++[Illustration:++ “No, no; stay where you are”++[_Copyright 1894 by George Allen._]]++“Have you anything else to propose for my domestic felicity?”++“Oh yes. Do let the portraits of your uncle and aunt Philips be placed+in the gallery at Pemberley. Put them next to your great-uncle the+judge. They are in the same profession, you know, only in different+lines. As for your Elizabeth’s picture, you must not attempt to have it+taken, for what painter could do justice to those beautiful eyes?”++“It would not be easy, indeed, to catch their expression; but their+colour and shape, and the eyelashes, so remarkably fine, might be+copied.”++At that moment they were met from another walk by Mrs. Hurst and+Elizabeth herself.++“I did not know that you intended to walk,” said Miss Bingley, in some+confusion, lest they had been overheard.++“You used us abominably ill,” answered Mrs. Hurst, “running away without+telling us that you were coming out.”++Then taking the disengaged arm of Mr. Darcy, she left Elizabeth to walk+by herself. The path just admitted three. Mr. Darcy felt their rudeness,+and immediately said,--++“This walk is not wide enough for our party. We had better go into the+avenue.”++But Elizabeth, who had not the least inclination to remain with them,+laughingly answered,--++“No, no; stay where you are. You are charmingly grouped, and appear to+uncommon advantage. The picturesque would be spoilt by admitting a+fourth. Good-bye.”++She then ran gaily off, rejoicing, as she rambled about, in the hope of+being at home again in a day or two. Jane was already so much recovered+as to intend leaving her room for a couple of hours that evening.++[Illustration:++ “Piling up the fire”++[_Copyright 1894 by George Allen._]]++CHAPTER XI.++[Illustration]++When the ladies removed after dinner Elizabeth ran up to her sister, and+seeing her well guarded from cold, attended her into the drawing-room,+where she was welcomed by her two friends with many professions of+pleasure; and Elizabeth had never seen them so agreeable as they were+during the hour which passed before the gentlemen appeared. Their powers+of conversation were considerable. They could describe an entertainment+with accuracy, relate an anecdote with humour, and laugh at their+acquaintance with spirit.++But when the gentlemen entered, Jane was no longer the first object;+Miss Bingley’s eyes were instantly turned towards Darcy, and she had+something to say to him before he had advanced many steps. He addressed+himself directly to Miss Bennet with a polite congratulation; Mr. Hurst+also made her a slight bow, and said he was “very glad;” but diffuseness+and warmth remained for Bingley’s salutation. He was full of joy and+attention. The first half hour was spent in piling up the fire, lest she+should suffer from the change of room; and she removed, at his desire,+to the other side of the fireplace, that she might be farther from the+door. He then sat down by her, and talked scarcely to anyone else.+Elizabeth, at work in the opposite corner, saw it all with great+delight.++When tea was over Mr. Hurst reminded his sister-in-law of the+card-table--but in vain. She had obtained private intelligence that Mr.+Darcy did not wish for cards, and Mr. Hurst soon found even his open+petition rejected. She assured him that no one intended to play, and the+silence of the whole party on the subject seemed to justify her. Mr.+Hurst had, therefore, nothing to do but to stretch himself on one of the+sofas and go to sleep. Darcy took up a book. Miss Bingley did the same;+and Mrs. Hurst, principally occupied in playing with her bracelets and+rings, joined now and then in her brother’s conversation with Miss+Bennet.++Miss Bingley’s attention was quite as much engaged in watching Mr.+Darcy’s progress through _his_ book, as in reading her own; and she was+perpetually either making some inquiry, or looking at his page. She+could not win him, however, to any conversation; he merely answered her+question and read on. At length, quite exhausted by the attempt to be+amused with her own book, which she had only chosen because it was the+second volume of his, she gave a great yawn and said, “How pleasant it+is to spend an evening in this way! I declare, after all, there is no+enjoyment like reading! How much sooner one tires of anything than of a+book! When I have a house of my own, I shall be miserable if I have not+an excellent library.”++No one made any reply. She then yawned again, threw aside her book, and+cast her eyes round the room in quest of some amusement; when, hearing+her brother mentioning a ball to Miss Bennet, she turned suddenly+towards him and said,--++“By the bye Charles, are you really serious in meditating a dance at+Netherfield? I would advise you, before you determine on it, to consult+the wishes of the present party; I am much mistaken if there are not+some among us to whom a ball would be rather a punishment than a+pleasure.”++“If you mean Darcy,” cried her brother, “he may go to bed, if he+chooses, before it begins; but as for the ball, it is quite a settled+thing, and as soon as Nicholls has made white soup enough I shall send+round my cards.”++“I should like balls infinitely better,” she replied, “if they were+carried on in a different manner; but there is something insufferably+tedious in the usual process of such a meeting. It would surely be much+more rational if conversation instead of dancing made the order of the+day.”++“Much more rational, my dear Caroline, I dare say; but it would not be+near so much like a ball.”++Miss Bingley made no answer, and soon afterwards got up and walked about+the room. Her figure was elegant, and she walked well; but Darcy, at+whom it was all aimed, was still inflexibly studious. In the+desperation of her feelings, she resolved on one effort more; and,+turning to Elizabeth, said,--++“Miss Eliza Bennet, let me persuade you to follow my example, and take a+turn about the room. I assure you it is very refreshing after sitting so+long in one attitude.”++Elizabeth was surprised, but agreed to it immediately. Miss Bingley+succeeded no less in the real object of her civility: Mr. Darcy looked+up. He was as much awake to the novelty of attention in that quarter as+Elizabeth herself could be, and unconsciously closed his book. He was+directly invited to join their party, but he declined it, observing that+he could imagine but two motives for their choosing to walk up and down+the room together, with either of which motives his joining them would+interfere. What could he mean? She was dying to know what could be his+meaning--and asked Elizabeth whether she could at all understand him.++“Not at all,” was her answer; “but, depend upon it, he means to be+severe on us, and our surest way of disappointing him will be to ask+nothing about it.”++Miss Bingley, however, was incapable of disappointing Mr. Darcy in+anything, and persevered, therefore, in requiring an explanation of his+two motives.++“I have not the smallest objection to explaining them,” said he, as soon+as she allowed him to speak. “You either choose this method of passing+the evening because you are in each other’s confidence, and have secret+affairs to discuss, or because you are conscious that your figures+appear to the greatest advantage in walking: if the first, I should be+completely in your way; and if the second, I can admire you much better+as I sit by the fire.”++“Oh, shocking!” cried Miss Bingley. “I never heard anything so+abominable. How shall we punish him for such a speech?”++“Nothing so easy, if you have but the inclination,” said Elizabeth. “We+can all plague and punish one another. Tease him--laugh at him. Intimate+as you are, you must know how it is to be done.”++“But upon my honour I do _not_. I do assure you that my intimacy has not+yet taught me _that_. Tease calmness of temper and presence of mind! No,+no; I feel he may defy us there. And as to laughter, we will not expose+ourselves, if you please, by attempting to laugh without a subject. Mr.+Darcy may hug himself.”++“Mr. Darcy is not to be laughed at!” cried Elizabeth. “That is an+uncommon advantage, and uncommon I hope it will continue, for it would+be a great loss to _me_ to have many such acquaintance. I dearly love a+laugh.”++“Miss Bingley,” said he, “has given me credit for more than can be. The+wisest and best of men,--nay, the wisest and best of their actions,--may+be rendered ridiculous by a person whose first object in life is a+joke.”++“Certainly,” replied Elizabeth, “there are such people, but I hope I am+not one of _them_. I hope I never ridicule what is wise or good. Follies+and nonsense, whims and inconsistencies, _do_ divert me, I own, and I+laugh at them whenever I can. But these, I suppose, are precisely what+you are without.”++“Perhaps that is not possible for anyone. But it has been the study of+my life to avoid those weaknesses which often expose a strong+understanding to ridicule.”++“Such as vanity and pride.”++“Yes, vanity is a weakness indeed. But pride--where there is a real+superiority of mind--pride will be always under good regulation.”++Elizabeth turned away to hide a smile.++“Your examination of Mr. Darcy is over, I presume,” said Miss Bingley;+“and pray what is the result?”++“I am perfectly convinced by it that Mr. Darcy has no defect. He owns it+himself without disguise.”++“No,” said Darcy, “I have made no such pretension. I have faults enough,+but they are not, I hope, of understanding. My temper I dare not vouch+for. It is, I believe, too little yielding; certainly too little for the+convenience of the world. I cannot forget the follies and vices of+others so soon as I ought, nor their offences against myself. My+feelings are not puffed about with every attempt to move them. My temper+would perhaps be called resentful. My good opinion once lost is lost for+ever.”++“_That_ is a failing, indeed!” cried Elizabeth. “Implacable resentment+_is_ a shade in a character. But you have chosen your fault well. I+really cannot _laugh_ at it. You are safe from me.”++“There is, I believe, in every disposition a tendency to some particular+evil, a natural defect, which not even the best education can overcome.”++“And _your_ defect is a propensity to hate everybody.”++“And yours,” he replied, with a smile, “is wilfully to misunderstand+them.”++“Do let us have a little music,” cried Miss Bingley, tired of a+conversation in which she had no share. “Louisa, you will not mind my+waking Mr. Hurst.”++Her sister made not the smallest objection, and the pianoforte was+opened; and Darcy, after a few moments’ recollection, was not sorry for+it. He began to feel the danger of paying Elizabeth too much attention.++[Illustration]++CHAPTER XII.++[Illustration]++In consequence of an agreement between the sisters, Elizabeth wrote the+next morning to her mother, to beg that the carriage might be sent for+them in the course of the day. But Mrs. Bennet, who had calculated on+her daughters remaining at Netherfield till the following Tuesday, which+would exactly finish Jane’s week, could not bring herself to receive+them with pleasure before. Her answer, therefore, was not propitious, at+least not to Elizabeth’s wishes, for she was impatient to get home. Mrs.+Bennet sent them word that they could not possibly have the carriage+before Tuesday; and in her postscript it was added, that if Mr. Bingley+and his sister pressed them to stay longer, she could spare them very+well. Against staying longer, however, Elizabeth was positively+resolved--nor did she much expect it would be asked; and fearful, on the+contrary, of being considered as intruding themselves needlessly long,+she urged Jane to borrow Mr. Bingley’s carriage immediately, and at+length it was settled that their original design of leaving Netherfield+that morning should be mentioned, and the request made.++The communication excited many professions of concern; and enough was+said of wishing them to stay at least till the following day to work on+Jane; and till the morrow their going was deferred. Miss Bingley was+then sorry that she had proposed the delay; for her jealousy and dislike+of one sister much exceeded her affection for the other.++The master of the house heard with real sorrow that they were to go so+soon, and repeatedly tried to persuade Miss Bennet that it would not be+safe for her--that she was not enough recovered; but Jane was firm where+she felt herself to be right.++To Mr. Darcy it was welcome intelligence: Elizabeth had been at+Netherfield long enough. She attracted him more than he liked; and Miss+Bingley was uncivil to _her_ and more teasing than usual to himself. He+wisely resolved to be particularly careful that no sign of admiration+should _now_ escape him--nothing that could elevate her with the hope of+influencing his felicity; sensible that, if such an idea had been+suggested, his behaviour during the last day must have material weight+in confirming or crushing it. Steady to his purpose, he scarcely spoke+ten words to her through the whole of Saturday: and though they were at+one time left by themselves for half an hour, he adhered most+conscientiously to his book, and would not even look at her.++On Sunday, after morning service, the separation, so agreeable to almost+all, took place. Miss Bingley’s civility to Elizabeth increased at last+very rapidly, as well as her affection for Jane; and when they parted,+after assuring the latter of the pleasure it would always give her to+see her either at Longbourn or Netherfield, and embracing her most+tenderly, she even shook hands with the former. Elizabeth took leave of+the whole party in the liveliest spirits.++They were not welcomed home very cordially by their mother. Mrs. Bennet+wondered at their coming, and thought them very wrong to give so much+trouble, and was sure Jane would have caught cold again. But their+father, though very laconic in his expressions of pleasure, was really+glad to see them; he had felt their importance in the family circle. The+evening conversation, when they were all assembled, had lost much of its+animation, and almost all its sense, by the absence of Jane and+Elizabeth.++They found Mary, as usual, deep in the study of thorough bass and human+nature; and had some new extracts to admire and some new observations of+threadbare morality to listen to. Catherine and Lydia had information+for them of a different sort. Much had been done, and much had been said+in the regiment since the preceding Wednesday; several of the officers+had dined lately with their uncle; a private had been flogged; and it+had actually been hinted that Colonel Forster was going to be married.++[Illustration]++CHAPTER XIII++[Illustration]++“I hope, my dear,” said Mr. Bennet to his wife, as they were at+breakfast the next morning, “that you have ordered a good dinner to-day,+because I have reason to expect an addition to our family party.”++“Who do you mean, my dear? I know of nobody that is coming, I am sure,+unless Charlotte Lucas should happen to call in; and I hope _my_ dinners+are good enough for her. I do not believe she often sees such at home.”++“The person of whom I speak is a gentleman and a stranger.”++Mrs. Bennet’s eyes sparkled. “A gentleman and a stranger! It is Mr.+Bingley, I am sure. Why, Jane--you never dropped a word of this--you sly+thing! Well, I am sure I shall be extremely glad to see Mr. Bingley.+But--good Lord! how unlucky! there is not a bit of fish to be got+to-day. Lydia, my love, ring the bell. I must speak to Hill this+moment.”++“It is _not_ Mr. Bingley,” said her husband; “it is a person whom I+never saw in the whole course of my life.”++This roused a general astonishment; and he had the pleasure of being+eagerly questioned by his wife and five daughters at once.++After amusing himself some time with their curiosity, he thus+explained:--“About a month ago I received this letter, and about a+fortnight ago I answered it; for I thought it a case of some delicacy,+and requiring early attention. It is from my cousin, Mr. Collins, who,+when I am dead, may turn you all out of this house as soon as he+pleases.”++“Oh, my dear,” cried his wife, “I cannot bear to hear that mentioned.+Pray do not talk of that odious man. I do think it is the hardest thing+in the world, that your estate should be entailed away from your own+children; and I am sure, if I had been you, I should have tried long ago+to do something or other about it.”++Jane and Elizabeth attempted to explain to her the nature of an entail.+They had often attempted it before: but it was a subject on which Mrs.+Bennet was beyond the reach of reason; and she continued to rail+bitterly against the cruelty of settling an estate away from a family of+five daughters, in favour of a man whom nobody cared anything about.++“It certainly is a most iniquitous affair,” said Mr. Bennet; “and+nothing can clear Mr. Collins from the guilt of inheriting Longbourn.+But if you will listen to his letter, you may, perhaps, be a little+softened by his manner of expressing himself.”++“No, that I am sure I shall not: and I think it was very impertinent of+him to write to you at all, and very hypocritical. I hate such false+friends. Why could not he keep on quarrelling with you, as his father+did before him?”++“Why, indeed, he does seem to have had some filial scruples on that+head, as you will hear.”++ /* RIGHT “Hunsford, near Westerham, Kent, _15th October_. */++“Dear Sir,++ “The disagreement subsisting between yourself and my late honoured+ father always gave me much uneasiness; and, since I have had the+ misfortune to lose him, I have frequently wished to heal the+ breach: but, for some time, I was kept back by my own doubts,+ fearing lest it might seem disrespectful to his memory for me to be+ on good terms with anyone with whom it had always pleased him to be+ at variance.”--‘There, Mrs. Bennet.’--“My mind, however, is now+ made up on the subject; for, having received ordination at Easter,+ I have been so fortunate as to be distinguished by the patronage of+ the Right Honourable Lady Catherine de Bourgh, widow of Sir Lewis+ de Bourgh, whose bounty and beneficence has preferred me to the+ valuable rectory of this parish, where it shall be my earnest+ endeavour to demean myself with grateful respect towards her+ Ladyship, and be ever ready to perform those rites and ceremonies+ which are instituted by the Church of England. As a clergyman,+ moreover, I feel it my duty to promote and establish the blessing+ of peace in all families within the reach of my influence; and on+ these grounds I flatter myself that my present overtures of+ good-will are highly commendable, and that the circumstance of my+ being next in the entail of Longbourn estate will be kindly+ overlooked on your side, and not lead you to reject the offered+ olive branch. I cannot be otherwise than concerned at being the+ means of injuring your amiable daughters, and beg leave to+ apologize for it, as well as to assure you of my readiness to make+ them every possible amends; but of this hereafter. If you should+ have no objection to receive me into your house, I propose myself+ the satisfaction of waiting on you and your family, Monday,+ November 18th, by four o’clock, and shall probably trespass on your+ hospitality till the Saturday se’nnight following, which I can do+ without any inconvenience, as Lady Catherine is far from objecting+ to my occasional absence on a Sunday, provided that some other+ clergyman is engaged to do the duty of the day. I remain, dear sir,+ with respectful compliments to your lady and daughters, your+ well-wisher and friend,++“WILLIAM COLLINS.”++“At four o’clock, therefore, we may expect this peace-making gentleman,”+said Mr. Bennet, as he folded up the letter. “He seems to be a most+conscientious and polite young man, upon my word; and, I doubt not, will+prove a valuable acquaintance, especially if Lady Catherine should be so+indulgent as to let him come to us again.”++“There is some sense in what he says about the girls, however; and, if+he is disposed to make them any amends, I shall not be the person to+discourage him.”++“Though it is difficult,” said Jane, “to guess in what way he can mean+to make us the atonement he thinks our due, the wish is certainly to his+credit.”++Elizabeth was chiefly struck with his extraordinary deference for Lady+Catherine, and his kind intention of christening, marrying, and burying+his parishioners whenever it were required.++“He must be an oddity, I think,” said she. “I cannot make him out. There+is something very pompous in his style. And what can he mean by+apologizing for being next in the entail? We cannot suppose he would+help it, if he could. Can he be a sensible man, sir?”++“No, my dear; I think not. I have great hopes of finding him quite the+reverse. There is a mixture of servility and self-importance in his+letter which promises well. I am impatient to see him.”++“In point of composition,” said Mary, “his letter does not seem+defective. The idea of the olive branch perhaps is not wholly new, yet I+think it is well expressed.”++To Catherine and Lydia neither the letter nor its writer were in any+degree interesting. It was next to impossible that their cousin should+come in a scarlet coat, and it was now some weeks since they had+received pleasure from the society of a man in any other colour. As for+their mother, Mr. Collins’s letter had done away much of her ill-will,+and she was preparing to see him with a degree of composure which+astonished her husband and daughters.++Mr. Collins was punctual to his time, and was received with great+politeness by the whole family. Mr. Bennet indeed said little; but the+ladies were ready enough to talk, and Mr. Collins seemed neither in need+of encouragement, nor inclined to be silent himself. He was a tall,+heavy-looking young man of five-and-twenty. His air was grave and+stately, and his manners were very formal. He had not been long seated+before he complimented Mrs. Bennet on having so fine a family of+daughters, said he had heard much of their beauty, but that, in this+instance, fame had fallen short of the truth; and added, that he did not+doubt her seeing them all in due time well disposed of in marriage. This+gallantry was not much to the taste of some of his hearers; but Mrs.+Bennet, who quarrelled with no compliments, answered most readily,--++“You are very kind, sir, I am sure; and I wish with all my heart it may+prove so; for else they will be destitute enough. Things are settled so+oddly.”++“You allude, perhaps, to the entail of this estate.”++“Ah, sir, I do indeed. It is a grievous affair to my poor girls, you+must confess. Not that I mean to find fault with _you_, for such things,+I know, are all chance in this world. There is no knowing how estates+will go when once they come to be entailed.”++“I am very sensible, madam, of the hardship to my fair cousins, and+could say much on the subject, but that I am cautious of appearing+forward and precipitate. But I can assure the young ladies that I come+prepared to admire them. At present I will not say more, but, perhaps,+when we are better acquainted----”++He was interrupted by a summons to dinner; and the girls smiled on each+other. They were not the only objects of Mr. Collins’s admiration. The+hall, the dining-room, and all its furniture, were examined and praised;+and his commendation of everything would have touched Mrs. Bennet’s+heart, but for the mortifying supposition of his viewing it all as his+own future property. The dinner, too, in its turn, was highly admired;+and he begged to know to which of his fair cousins the excellence of its+cookery was owing. But here he was set right by Mrs. Bennet, who assured+him, with some asperity, that they were very well able to keep a good+cook, and that her daughters had nothing to do in the kitchen. He begged+pardon for having displeased her. In a softened tone she declared+herself not at all offended; but he continued to apologize for about a+quarter of an hour.++[Illustration]++CHAPTER XIV++[Illustration]++During dinner, Mr. Bennet scarcely spoke at all; but when the servants+were withdrawn, he thought it time to have some conversation with his+guest, and therefore started a subject in which he expected him to+shine, by observing that he seemed very fortunate in his patroness. Lady+Catherine de Bourgh’s attention to his wishes, and consideration for his+comfort, appeared very remarkable. Mr. Bennet could not have chosen+better. Mr. Collins was eloquent in her praise. The subject elevated him+to more than usual solemnity of manner; and with a most important aspect+he protested that he had never in his life witnessed such behaviour in a+person of rank--such affability and condescension, as he had himself+experienced from Lady Catherine. She had been graciously pleased to+approve of both the discourses which he had already had the honour of+preaching before her. She had also asked him twice to dine at Rosings,+and had sent for him only the Saturday before, to make up her pool of+quadrille in the evening. Lady Catherine was reckoned proud by many+people, he knew, but _he_ had never seen anything but affability in her.+She had always spoken to him as she would to any other gentleman; she+made not the smallest objection to his joining in the society of the+neighbourhood, nor to his leaving his parish occasionally for a week or+two to visit his relations. She had even condescended to advise him to+marry as soon as he could, provided he chose with discretion; and had+once paid him a visit in his humble parsonage, where she had perfectly+approved all the alterations he had been making, and had even vouchsafed+to suggest some herself,--some shelves in the closets upstairs.++“That is all very proper and civil, I am sure,” said Mrs. Bennet, “and I+dare say she is a very agreeable woman. It is a pity that great ladies+in general are not more like her. Does she live near you, sir?”++“The garden in which stands my humble abode is separated only by a lane+from Rosings Park, her Ladyship’s residence.”++“I think you said she was a widow, sir? has she any family?”++“She has one only daughter, the heiress of Rosings, and of very+extensive property.”++“Ah,” cried Mrs. Bennet, shaking her head, “then she is better off than+many girls. And what sort of young lady is she? Is she handsome?”++“She is a most charming young lady, indeed. Lady Catherine herself says+that, in point of true beauty, Miss de Bourgh is far superior to the+handsomest of her sex; because there is that in her features which marks+the young woman of distinguished birth. She is unfortunately of a sickly+constitution, which has prevented her making that progress in many+accomplishments which she could not otherwise have failed of, as I am+informed by the lady who superintended her education, and who still+resides with them. But she is perfectly amiable, and often condescends+to drive by my humble abode in her little phaeton and ponies.”++“Has she been presented? I do not remember her name among the ladies at+court.”++“Her indifferent state of health unhappily prevents her being in town;+and by that means, as I told Lady Catherine myself one day, has deprived+the British Court of its brightest ornament. Her Ladyship seemed pleased+with the idea; and you may imagine that I am happy on every occasion to+offer those little delicate compliments which are always acceptable to+ladies. I have more than once observed to Lady Catherine, that her+charming daughter seemed born to be a duchess; and that the most+elevated rank, instead of giving her consequence, would be adorned by+her. These are the kind of little things which please her Ladyship, and+it is a sort of attention which I conceive myself peculiarly bound to+pay.”++“You judge very properly,” said Mr. Bennet; “and it is happy for you+that you possess the talent of flattering with delicacy. May I ask+whether these pleasing attentions proceed from the impulse of the+moment, or are the result of previous study?”++“They arise chiefly from what is passing at the time; and though I+sometimes amuse myself with suggesting and arranging such little elegant+compliments as may be adapted to ordinary occasions, I always wish to+give them as unstudied an air as possible.”++Mr. Bennet’s expectations were fully answered. His cousin was as absurd+as he had hoped; and he listened to him with the keenest enjoyment,+maintaining at the same time the most resolute composure of countenance,+and, except in an occasional glance at Elizabeth, requiring no partner+in his pleasure.++By tea-time, however, the dose had been enough, and Mr. Bennet was glad+to take his guest into the drawing-room again, and when tea was over,+glad to invite him++[Illustration:++“Protested+that he never read novels” H.T Feb 94+]++to read aloud to the ladies. Mr. Collins readily assented, and a book+was produced; but on beholding it (for everything announced it to be+from a circulating library) he started back, and, begging pardon,+protested that he never read novels. Kitty stared at him, and Lydia+exclaimed. Other books were produced, and after some deliberation he+chose “Fordyce’s Sermons.” Lydia gaped as he opened the volume; and+before he had, with very monotonous solemnity, read three pages, she+interrupted him with,--++“Do you know, mamma, that my uncle Philips talks of turning away+Richard? and if he does, Colonel Forster will hire him. My aunt told me+so herself on Saturday. I shall walk to Meryton to-morrow to hear more+about it, and to ask when Mr. Denny comes back from town.”++Lydia was bid by her two eldest sisters to hold her tongue; but Mr.+Collins, much offended, laid aside his book, and said,--++“I have often observed how little young ladies are interested by books+of a serious stamp, though written solely for their benefit. It amazes+me, I confess; for certainly there can be nothing so advantageous to+them as instruction. But I will no longer importune my young cousin.”++Then, turning to Mr. Bennet, he offered himself as his antagonist at+backgammon. Mr. Bennet accepted the challenge, observing that he acted+very wisely in leaving the girls to their own trifling amusements. Mrs.+Bennet and her daughters apologized most civilly for Lydia’s+interruption, and promised that it should not occur again, if he would+resume his book; but Mr. Collins, after assuring them that he bore his+young cousin no ill-will, and should never resent her behaviour as any+affront, seated himself at another table with Mr. Bennet, and prepared+for backgammon.++[Illustration]diff --git a/admin/tests/eval/corpus/distractor-gutenberg-sherlock-holmes.md b/admin/tests/eval/corpus/distractor-gutenberg-sherlock-holmes.mdnew file mode 100644index 00000000..8960cf58--- /dev/null+++ b/admin/tests/eval/corpus/distractor-gutenberg-sherlock-holmes.md@@ -0,0 +1,3902 @@+# The Adventures of Sherlock Holmes (stories I-IV), Arthur Conan Doyle++Distractor document for the #1341 off-topic eval suite. Public domain text from Project Gutenberg (ebook #1661), boilerplate removed.++I. A SCANDAL IN BOHEMIA++I.++To Sherlock Holmes she is always _the_ woman. I have seldom heard him+mention her under any other name. In his eyes she eclipses and+predominates the whole of her sex. It was not that he felt any emotion+akin to love for Irene Adler. All emotions, and that one particularly,+were abhorrent to his cold, precise but admirably balanced mind. He+was, I take it, the most perfect reasoning and observing machine that+the world has seen, but as a lover he would have placed himself in a+false position. He never spoke of the softer passions, save with a gibe+and a sneer. They were admirable things for the observer—excellent for+drawing the veil from men’s motives and actions. But for the trained+reasoner to admit such intrusions into his own delicate and finely+adjusted temperament was to introduce a distracting factor which might+throw a doubt upon all his mental results. Grit in a sensitive+instrument, or a crack in one of his own high-power lenses, would not+be more disturbing than a strong emotion in a nature such as his. And+yet there was but one woman to him, and that woman was the late Irene+Adler, of dubious and questionable memory.++I had seen little of Holmes lately. My marriage had drifted us away+from each other. My own complete happiness, and the home-centred+interests which rise up around the man who first finds himself master+of his own establishment, were sufficient to absorb all my attention,+while Holmes, who loathed every form of society with his whole Bohemian+soul, remained in our lodgings in Baker Street, buried among his old+books, and alternating from week to week between cocaine and ambition,+the drowsiness of the drug, and the fierce energy of his own keen+nature. He was still, as ever, deeply attracted by the study of crime,+and occupied his immense faculties and extraordinary powers of+observation in following out those clues, and clearing up those+mysteries which had been abandoned as hopeless by the official police.+From time to time I heard some vague account of his doings: of his+summons to Odessa in the case of the Trepoff murder, of his clearing up+of the singular tragedy of the Atkinson brothers at Trincomalee, and+finally of the mission which he had accomplished so delicately and+successfully for the reigning family of Holland. Beyond these signs of+his activity, however, which I merely shared with all the readers of+the daily press, I knew little of my former friend and companion.++One night—it was on the twentieth of March, 1888—I was returning from a+journey to a patient (for I had now returned to civil practice), when+my way led me through Baker Street. As I passed the well-remembered+door, which must always be associated in my mind with my wooing, and+with the dark incidents of the Study in Scarlet, I was seized with a+keen desire to see Holmes again, and to know how he was employing his+extraordinary powers. His rooms were brilliantly lit, and, even as I+looked up, I saw his tall, spare figure pass twice in a dark silhouette+against the blind. He was pacing the room swiftly, eagerly, with his+head sunk upon his chest and his hands clasped behind him. To me, who+knew his every mood and habit, his attitude and manner told their own+story. He was at work again. He had risen out of his drug-created+dreams and was hot upon the scent of some new problem. I rang the bell+and was shown up to the chamber which had formerly been in part my own.++His manner was not effusive. It seldom was; but he was glad, I think,+to see me. With hardly a word spoken, but with a kindly eye, he waved+me to an armchair, threw across his case of cigars, and indicated a+spirit case and a gasogene in the corner. Then he stood before the fire+and looked me over in his singular introspective fashion.++“Wedlock suits you,” he remarked. “I think, Watson, that you have put+on seven and a half pounds since I saw you.”++“Seven!” I answered.++“Indeed, I should have thought a little more. Just a trifle more, I+fancy, Watson. And in practice again, I observe. You did not tell me+that you intended to go into harness.”++“Then, how do you know?”++“I see it, I deduce it. How do I know that you have been getting+yourself very wet lately, and that you have a most clumsy and careless+servant girl?”++“My dear Holmes,” said I, “this is too much. You would certainly have+been burned, had you lived a few centuries ago. It is true that I had a+country walk on Thursday and came home in a dreadful mess, but as I+have changed my clothes I can’t imagine how you deduce it. As to Mary+Jane, she is incorrigible, and my wife has given her notice, but there,+again, I fail to see how you work it out.”++He chuckled to himself and rubbed his long, nervous hands together.++“It is simplicity itself,” said he; “my eyes tell me that on the inside+of your left shoe, just where the firelight strikes it, the leather is+scored by six almost parallel cuts. Obviously they have been caused by+someone who has very carelessly scraped round the edges of the sole in+order to remove crusted mud from it. Hence, you see, my double+deduction that you had been out in vile weather, and that you had a+particularly malignant boot-slitting specimen of the London slavey. As+to your practice, if a gentleman walks into my rooms smelling of+iodoform, with a black mark of nitrate of silver upon his right+forefinger, and a bulge on the right side of his top-hat to show where+he has secreted his stethoscope, I must be dull, indeed, if I do not+pronounce him to be an active member of the medical profession.”++I could not help laughing at the ease with which he explained his+process of deduction. “When I hear you give your reasons,” I remarked,+“the thing always appears to me to be so ridiculously simple that I+could easily do it myself, though at each successive instance of your+reasoning I am baffled until you explain your process. And yet I+believe that my eyes are as good as yours.”++“Quite so,” he answered, lighting a cigarette, and throwing himself+down into an armchair. “You see, but you do not observe. The+distinction is clear. For example, you have frequently seen the steps+which lead up from the hall to this room.”++“Frequently.”++“How often?”++“Well, some hundreds of times.”++“Then how many are there?”++“How many? I don’t know.”++“Quite so! You have not observed. And yet you have seen. That is just+my point. Now, I know that there are seventeen steps, because I have+both seen and observed. By the way, since you are interested in these+little problems, and since you are good enough to chronicle one or two+of my trifling experiences, you may be interested in this.” He threw+over a sheet of thick, pink-tinted notepaper which had been lying open+upon the table. “It came by the last post,” said he. “Read it aloud.”++The note was undated, and without either signature or address.++“There will call upon you to-night, at a quarter to eight o’clock,” it+said, “a gentleman who desires to consult you upon a matter of the very+deepest moment. Your recent services to one of the royal houses of+Europe have shown that you are one who may safely be trusted with+matters which are of an importance which can hardly be exaggerated.+This account of you we have from all quarters received. Be in your+chamber then at that hour, and do not take it amiss if your visitor+wear a mask.”++“This is indeed a mystery,” I remarked. “What do you imagine that it+means?”++“I have no data yet. It is a capital mistake to theorise before one has+data. Insensibly one begins to twist facts to suit theories, instead of+theories to suit facts. But the note itself. What do you deduce from+it?”++I carefully examined the writing, and the paper upon which it was+written.++“The man who wrote it was presumably well to do,” I remarked,+endeavouring to imitate my companion’s processes. “Such paper could not+be bought under half a crown a packet. It is peculiarly strong and+stiff.”++“Peculiar—that is the very word,” said Holmes. “It is not an English+paper at all. Hold it up to the light.”++I did so, and saw a large “E” with a small “g,” a “P,” and a large “G”+with a small “t” woven into the texture of the paper.++“What do you make of that?” asked Holmes.++“The name of the maker, no doubt; or his monogram, rather.”++“Not at all. The ‘G’ with the small ‘t’ stands for ‘Gesellschaft,’+which is the German for ‘Company.’ It is a customary contraction like+our ‘Co.’ ‘P,’ of course, stands for ‘Papier.’ Now for the ‘Eg.’ Let us+glance at our Continental Gazetteer.” He took down a heavy brown volume+from his shelves. “Eglow, Eglonitz—here we are, Egria. It is in a+German-speaking country—in Bohemia, not far from Carlsbad. ‘Remarkable+as being the scene of the death of Wallenstein, and for its numerous+glass-factories and paper-mills.’ Ha, ha, my boy, what do you make of+that?” His eyes sparkled, and he sent up a great blue triumphant cloud+from his cigarette.++“The paper was made in Bohemia,” I said.++“Precisely. And the man who wrote the note is a German. Do you note the+peculiar construction of the sentence—‘This account of you we have from+all quarters received.’ A Frenchman or Russian could not have written+that. It is the German who is so uncourteous to his verbs. It only+remains, therefore, to discover what is wanted by this German who+writes upon Bohemian paper and prefers wearing a mask to showing his+face. And here he comes, if I am not mistaken, to resolve all our+doubts.”++As he spoke there was the sharp sound of horses’ hoofs and grating+wheels against the curb, followed by a sharp pull at the bell. Holmes+whistled.++“A pair, by the sound,” said he. “Yes,” he continued, glancing out of+the window. “A nice little brougham and a pair of beauties. A hundred+and fifty guineas apiece. There’s money in this case, Watson, if there+is nothing else.”++“I think that I had better go, Holmes.”++“Not a bit, Doctor. Stay where you are. I am lost without my Boswell.+And this promises to be interesting. It would be a pity to miss it.”++“But your client—”++“Never mind him. I may want your help, and so may he. Here he comes.+Sit down in that armchair, Doctor, and give us your best attention.”++A slow and heavy step, which had been heard upon the stairs and in the+passage, paused immediately outside the door. Then there was a loud and+authoritative tap.++“Come in!” said Holmes.++A man entered who could hardly have been less than six feet six inches+in height, with the chest and limbs of a Hercules. His dress was rich+with a richness which would, in England, be looked upon as akin to bad+taste. Heavy bands of astrakhan were slashed across the sleeves and+fronts of his double-breasted coat, while the deep blue cloak which was+thrown over his shoulders was lined with flame-coloured silk and+secured at the neck with a brooch which consisted of a single flaming+beryl. Boots which extended halfway up his calves, and which were+trimmed at the tops with rich brown fur, completed the impression of+barbaric opulence which was suggested by his whole appearance. He+carried a broad-brimmed hat in his hand, while he wore across the upper+part of his face, extending down past the cheekbones, a black vizard+mask, which he had apparently adjusted that very moment, for his hand+was still raised to it as he entered. From the lower part of the face+he appeared to be a man of strong character, with a thick, hanging lip,+and a long, straight chin suggestive of resolution pushed to the length+of obstinacy.++“You had my note?” he asked with a deep harsh voice and a strongly+marked German accent. “I told you that I would call.” He looked from+one to the other of us, as if uncertain which to address.++“Pray take a seat,” said Holmes. “This is my friend and colleague, Dr.+Watson, who is occasionally good enough to help me in my cases. Whom+have I the honour to address?”++“You may address me as the Count Von Kramm, a Bohemian nobleman. I+understand that this gentleman, your friend, is a man of honour and+discretion, whom I may trust with a matter of the most extreme+importance. If not, I should much prefer to communicate with you+alone.”++I rose to go, but Holmes caught me by the wrist and pushed me back into+my chair. “It is both, or none,” said he. “You may say before this+gentleman anything which you may say to me.”++The Count shrugged his broad shoulders. “Then I must begin,” said he,+“by binding you both to absolute secrecy for two years; at the end of+that time the matter will be of no importance. At present it is not too+much to say that it is of such weight it may have an influence upon+European history.”++“I promise,” said Holmes.++“And I.”++“You will excuse this mask,” continued our strange visitor. “The august+person who employs me wishes his agent to be unknown to you, and I may+confess at once that the title by which I have just called myself is+not exactly my own.”++“I was aware of it,” said Holmes dryly.++“The circumstances are of great delicacy, and every precaution has to+be taken to quench what might grow to be an immense scandal and+seriously compromise one of the reigning families of Europe. To speak+plainly, the matter implicates the great House of Ormstein, hereditary+kings of Bohemia.”++“I was also aware of that,” murmured Holmes, settling himself down in+his armchair and closing his eyes.++Our visitor glanced with some apparent surprise at the languid,+lounging figure of the man who had been no doubt depicted to him as the+most incisive reasoner and most energetic agent in Europe. Holmes+slowly reopened his eyes and looked impatiently at his gigantic client.++“If your Majesty would condescend to state your case,” he remarked, “I+should be better able to advise you.”++The man sprang from his chair and paced up and down the room in+uncontrollable agitation. Then, with a gesture of desperation, he tore+the mask from his face and hurled it upon the ground. “You are right,”+he cried; “I am the King. Why should I attempt to conceal it?”++“Why, indeed?” murmured Holmes. “Your Majesty had not spoken before I+was aware that I was addressing Wilhelm Gottsreich Sigismond von+Ormstein, Grand Duke of Cassel-Felstein, and hereditary King of+Bohemia.”++“But you can understand,” said our strange visitor, sitting down once+more and passing his hand over his high white forehead, “you can+understand that I am not accustomed to doing such business in my own+person. Yet the matter was so delicate that I could not confide it to+an agent without putting myself in his power. I have come _incognito_+from Prague for the purpose of consulting you.”++“Then, pray consult,” said Holmes, shutting his eyes once more.++“The facts are briefly these: Some five years ago, during a lengthy+visit to Warsaw, I made the acquaintance of the well-known adventuress,+Irene Adler. The name is no doubt familiar to you.”++“Kindly look her up in my index, Doctor,” murmured Holmes without+opening his eyes. For many years he had adopted a system of docketing+all paragraphs concerning men and things, so that it was difficult to+name a subject or a person on which he could not at once furnish+information. In this case I found her biography sandwiched in between+that of a Hebrew rabbi and that of a staff-commander who had written a+monograph upon the deep-sea fishes.++“Let me see!” said Holmes. “Hum! Born in New Jersey in the year 1858.+Contralto—hum! La Scala, hum! Prima donna Imperial Opera of Warsaw—yes!+Retired from operatic stage—ha! Living in London—quite so! Your+Majesty, as I understand, became entangled with this young person,+wrote her some compromising letters, and is now desirous of getting+those letters back.”++“Precisely so. But how—”++“Was there a secret marriage?”++“None.”++“No legal papers or certificates?”++“None.”++“Then I fail to follow your Majesty. If this young person should+produce her letters for blackmailing or other purposes, how is she to+prove their authenticity?”++“There is the writing.”++“Pooh, pooh! Forgery.”++“My private note-paper.”++“Stolen.”++“My own seal.”++“Imitated.”++“My photograph.”++“Bought.”++“We were both in the photograph.”++“Oh, dear! That is very bad! Your Majesty has indeed committed an+indiscretion.”++“I was mad—insane.”++“You have compromised yourself seriously.”++“I was only Crown Prince then. I was young. I am but thirty now.”++“It must be recovered.”++“We have tried and failed.”++“Your Majesty must pay. It must be bought.”++“She will not sell.”++“Stolen, then.”++“Five attempts have been made. Twice burglars in my pay ransacked her+house. Once we diverted her luggage when she travelled. Twice she has+been waylaid. There has been no result.”++“No sign of it?”++“Absolutely none.”++Holmes laughed. “It is quite a pretty little problem,” said he.++“But a very serious one to me,” returned the King reproachfully.++“Very, indeed. And what does she propose to do with the photograph?”++“To ruin me.”++“But how?”++“I am about to be married.”++“So I have heard.”++“To Clotilde Lothman von Saxe-Meningen, second daughter of the King of+Scandinavia. You may know the strict principles of her family. She is+herself the very soul of delicacy. A shadow of a doubt as to my conduct+would bring the matter to an end.”++“And Irene Adler?”++“Threatens to send them the photograph. And she will do it. I know that+she will do it. You do not know her, but she has a soul of steel. She+has the face of the most beautiful of women, and the mind of the most+resolute of men. Rather than I should marry another woman, there are no+lengths to which she would not go—none.”++“You are sure that she has not sent it yet?”++“I am sure.”++“And why?”++“Because she has said that she would send it on the day when the+betrothal was publicly proclaimed. That will be next Monday.”++“Oh, then we have three days yet,” said Holmes with a yawn. “That is+very fortunate, as I have one or two matters of importance to look into+just at present. Your Majesty will, of course, stay in London for the+present?”++“Certainly. You will find me at the Langham under the name of the Count+Von Kramm.”++“Then I shall drop you a line to let you know how we progress.”++“Pray do so. I shall be all anxiety.”++“Then, as to money?”++“You have _carte blanche_.”++“Absolutely?”++“I tell you that I would give one of the provinces of my kingdom to+have that photograph.”++“And for present expenses?”++The King took a heavy chamois leather bag from under his cloak and laid+it on the table.++“There are three hundred pounds in gold and seven hundred in notes,” he+said.++Holmes scribbled a receipt upon a sheet of his note-book and handed it+to him.++“And Mademoiselle’s address?” he asked.++“Is Briony Lodge, Serpentine Avenue, St. John’s Wood.”++Holmes took a note of it. “One other question,” said he. “Was the+photograph a cabinet?”++“It was.”++“Then, good-night, your Majesty, and I trust that we shall soon have+some good news for you. And good-night, Watson,” he added, as the+wheels of the royal brougham rolled down the street. “If you will be+good enough to call to-morrow afternoon at three o’clock I should like+to chat this little matter over with you.”++II.++At three o’clock precisely I was at Baker Street, but Holmes had not+yet returned. The landlady informed me that he had left the house+shortly after eight o’clock in the morning. I sat down beside the fire,+however, with the intention of awaiting him, however long he might be.+I was already deeply interested in his inquiry, for, though it was+surrounded by none of the grim and strange features which were+associated with the two crimes which I have already recorded, still,+the nature of the case and the exalted station of his client gave it a+character of its own. Indeed, apart from the nature of the+investigation which my friend had on hand, there was something in his+masterly grasp of a situation, and his keen, incisive reasoning, which+made it a pleasure to me to study his system of work, and to follow the+quick, subtle methods by which he disentangled the most inextricable+mysteries. So accustomed was I to his invariable success that the very+possibility of his failing had ceased to enter into my head.++It was close upon four before the door opened, and a drunken-looking+groom, ill-kempt and side-whiskered, with an inflamed face and+disreputable clothes, walked into the room. Accustomed as I was to my+friend’s amazing powers in the use of disguises, I had to look three+times before I was certain that it was indeed he. With a nod he+vanished into the bedroom, whence he emerged in five minutes+tweed-suited and respectable, as of old. Putting his hands into his+pockets, he stretched out his legs in front of the fire and laughed+heartily for some minutes.++“Well, really!” he cried, and then he choked and laughed again until he+was obliged to lie back, limp and helpless, in the chair.++“What is it?”++“It’s quite too funny. I am sure you could never guess how I employed+my morning, or what I ended by doing.”++“I can’t imagine. I suppose that you have been watching the habits, and+perhaps the house, of Miss Irene Adler.”++“Quite so; but the sequel was rather unusual. I will tell you, however.+I left the house a little after eight o’clock this morning in the+character of a groom out of work. There is a wonderful sympathy and+freemasonry among horsey men. Be one of them, and you will know all+that there is to know. I soon found Briony Lodge. It is a _bijou_+villa, with a garden at the back, but built out in front right up to+the road, two stories. Chubb lock to the door. Large sitting-room on+the right side, well furnished, with long windows almost to the floor,+and those preposterous English window fasteners which a child could+open. Behind there was nothing remarkable, save that the passage window+could be reached from the top of the coach-house. I walked round it and+examined it closely from every point of view, but without noting+anything else of interest.++“I then lounged down the street and found, as I expected, that there+was a mews in a lane which runs down by one wall of the garden. I lent+the ostlers a hand in rubbing down their horses, and received in+exchange twopence, a glass of half-and-half, two fills of shag tobacco,+and as much information as I could desire about Miss Adler, to say+nothing of half a dozen other people in the neighbourhood in whom I was+not in the least interested, but whose biographies I was compelled to+listen to.”++“And what of Irene Adler?” I asked.++“Oh, she has turned all the men’s heads down in that part. She is the+daintiest thing under a bonnet on this planet. So say the+Serpentine-mews, to a man. She lives quietly, sings at concerts, drives+out at five every day, and returns at seven sharp for dinner. Seldom+goes out at other times, except when she sings. Has only one male+visitor, but a good deal of him. He is dark, handsome, and dashing,+never calls less than once a day, and often twice. He is a Mr. Godfrey+Norton, of the Inner Temple. See the advantages of a cabman as a+confidant. They had driven him home a dozen times from Serpentine-mews,+and knew all about him. When I had listened to all they had to tell, I+began to walk up and down near Briony Lodge once more, and to think+over my plan of campaign.++“This Godfrey Norton was evidently an important factor in the matter.+He was a lawyer. That sounded ominous. What was the relation between+them, and what the object of his repeated visits? Was she his client,+his friend, or his mistress? If the former, she had probably+transferred the photograph to his keeping. If the latter, it was less+likely. On the issue of this question depended whether I should+continue my work at Briony Lodge, or turn my attention to the+gentleman’s chambers in the Temple. It was a delicate point, and it+widened the field of my inquiry. I fear that I bore you with these+details, but I have to let you see my little difficulties, if you are+to understand the situation.”++“I am following you closely,” I answered.++“I was still balancing the matter in my mind when a hansom cab drove up+to Briony Lodge, and a gentleman sprang out. He was a remarkably+handsome man, dark, aquiline, and moustached—evidently the man of whom+I had heard. He appeared to be in a great hurry, shouted to the cabman+to wait, and brushed past the maid who opened the door with the air of+a man who was thoroughly at home.++“He was in the house about half an hour, and I could catch glimpses of+him in the windows of the sitting-room, pacing up and down, talking+excitedly, and waving his arms. Of her I could see nothing. Presently+he emerged, looking even more flurried than before. As he stepped up to+the cab, he pulled a gold watch from his pocket and looked at it+earnestly, ‘Drive like the devil,’ he shouted, ‘first to Gross &+Hankey’s in Regent Street, and then to the Church of St. Monica in the+Edgeware Road. Half a guinea if you do it in twenty minutes!’++“Away they went, and I was just wondering whether I should not do well+to follow them when up the lane came a neat little landau, the coachman+with his coat only half-buttoned, and his tie under his ear, while all+the tags of his harness were sticking out of the buckles. It hadn’t+pulled up before she shot out of the hall door and into it. I only+caught a glimpse of her at the moment, but she was a lovely woman, with+a face that a man might die for.++“‘The Church of St. Monica, John,’ she cried, ‘and half a sovereign if+you reach it in twenty minutes.’++“This was quite too good to lose, Watson. I was just balancing whether+I should run for it, or whether I should perch behind her landau when a+cab came through the street. The driver looked twice at such a shabby+fare, but I jumped in before he could object. ‘The Church of St.+Monica,’ said I, ‘and half a sovereign if you reach it in twenty+minutes.’ It was twenty-five minutes to twelve, and of course it was+clear enough what was in the wind.++“My cabby drove fast. I don’t think I ever drove faster, but the others+were there before us. The cab and the landau with their steaming horses+were in front of the door when I arrived. I paid the man and hurried+into the church. There was not a soul there save the two whom I had+followed and a surpliced clergyman, who seemed to be expostulating with+them. They were all three standing in a knot in front of the altar. I+lounged up the side aisle like any other idler who has dropped into a+church. Suddenly, to my surprise, the three at the altar faced round to+me, and Godfrey Norton came running as hard as he could towards me.++“‘Thank God,’ he cried. ‘You’ll do. Come! Come!’++“‘What then?’ I asked.++“‘Come, man, come, only three minutes, or it won’t be legal.’++“I was half-dragged up to the altar, and before I knew where I was I+found myself mumbling responses which were whispered in my ear, and+vouching for things of which I knew nothing, and generally assisting in+the secure tying up of Irene Adler, spinster, to Godfrey Norton,+bachelor. It was all done in an instant, and there was the gentleman+thanking me on the one side and the lady on the other, while the+clergyman beamed on me in front. It was the most preposterous position+in which I ever found myself in my life, and it was the thought of it+that started me laughing just now. It seems that there had been some+informality about their license, that the clergyman absolutely refused+to marry them without a witness of some sort, and that my lucky+appearance saved the bridegroom from having to sally out into the+streets in search of a best man. The bride gave me a sovereign, and I+mean to wear it on my watch chain in memory of the occasion.”++“This is a very unexpected turn of affairs,” said I; “and what then?”++“Well, I found my plans very seriously menaced. It looked as if the+pair might take an immediate departure, and so necessitate very prompt+and energetic measures on my part. At the church door, however, they+separated, he driving back to the Temple, and she to her own house. ‘I+shall drive out in the park at five as usual,’ she said as she left+him. I heard no more. They drove away in different directions, and I+went off to make my own arrangements.”++“Which are?”++“Some cold beef and a glass of beer,” he answered, ringing the bell. “I+have been too busy to think of food, and I am likely to be busier still+this evening. By the way, Doctor, I shall want your co-operation.”++“I shall be delighted.”++“You don’t mind breaking the law?”++“Not in the least.”++“Nor running a chance of arrest?”++“Not in a good cause.”++“Oh, the cause is excellent!”++“Then I am your man.”++“I was sure that I might rely on you.”++“But what is it you wish?”++“When Mrs. Turner has brought in the tray I will make it clear to you.+Now,” he said as he turned hungrily on the simple fare that our+landlady had provided, “I must discuss it while I eat, for I have not+much time. It is nearly five now. In two hours we must be on the scene+of action. Miss Irene, or Madame, rather, returns from her drive at+seven. We must be at Briony Lodge to meet her.”++“And what then?”++“You must leave that to me. I have already arranged what is to occur.+There is only one point on which I must insist. You must not interfere,+come what may. You understand?”++“I am to be neutral?”++“To do nothing whatever. There will probably be some small+unpleasantness. Do not join in it. It will end in my being conveyed+into the house. Four or five minutes afterwards the sitting-room window+will open. You are to station yourself close to that open window.”++“Yes.”++“You are to watch me, for I will be visible to you.”++“Yes.”++“And when I raise my hand—so—you will throw into the room what I give+you to throw, and will, at the same time, raise the cry of fire. You+quite follow me?”++“Entirely.”++“It is nothing very formidable,” he said, taking a long cigar-shaped+roll from his pocket. “It is an ordinary plumber’s smoke-rocket, fitted+with a cap at either end to make it self-lighting. Your task is+confined to that. When you raise your cry of fire, it will be taken up+by quite a number of people. You may then walk to the end of the+street, and I will rejoin you in ten minutes. I hope that I have made+myself clear?”++“I am to remain neutral, to get near the window, to watch you, and at+the signal to throw in this object, then to raise the cry of fire, and+to wait you at the corner of the street.”++“Precisely.”++“Then you may entirely rely on me.”++“That is excellent. I think, perhaps, it is almost time that I prepare+for the new role I have to play.”++He disappeared into his bedroom and returned in a few minutes in the+character of an amiable and simple-minded Nonconformist clergyman. His+broad black hat, his baggy trousers, his white tie, his sympathetic+smile, and general look of peering and benevolent curiosity were such+as Mr. John Hare alone could have equalled. It was not merely that+Holmes changed his costume. His expression, his manner, his very soul+seemed to vary with every fresh part that he assumed. The stage lost a+fine actor, even as science lost an acute reasoner, when he became a+specialist in crime.++It was a quarter past six when we left Baker Street, and it still+wanted ten minutes to the hour when we found ourselves in Serpentine+Avenue. It was already dusk, and the lamps were just being lighted as+we paced up and down in front of Briony Lodge, waiting for the coming+of its occupant. The house was just such as I had pictured it from+Sherlock Holmes’ succinct description, but the locality appeared to be+less private than I expected. On the contrary, for a small street in a+quiet neighbourhood, it was remarkably animated. There was a group of+shabbily dressed men smoking and laughing in a corner, a+scissors-grinder with his wheel, two guardsmen who were flirting with a+nurse-girl, and several well-dressed young men who were lounging up and+down with cigars in their mouths.++“You see,” remarked Holmes, as we paced to and fro in front of the+house, “this marriage rather simplifies matters. The photograph becomes+a double-edged weapon now. The chances are that she would be as averse+to its being seen by Mr. Godfrey Norton, as our client is to its coming+to the eyes of his princess. Now the question is, Where are we to find+the photograph?”++“Where, indeed?”++“It is most unlikely that she carries it about with her. It is cabinet+size. Too large for easy concealment about a woman’s dress. She knows+that the King is capable of having her waylaid and searched. Two+attempts of the sort have already been made. We may take it, then, that+she does not carry it about with her.”++“Where, then?”++“Her banker or her lawyer. There is that double possibility. But I am+inclined to think neither. Women are naturally secretive, and they like+to do their own secreting. Why should she hand it over to anyone else?+She could trust her own guardianship, but she could not tell what+indirect or political influence might be brought to bear upon a+business man. Besides, remember that she had resolved to use it within+a few days. It must be where she can lay her hands upon it. It must be+in her own house.”++“But it has twice been burgled.”++“Pshaw! They did not know how to look.”++“But how will you look?”++“I will not look.”++“What then?”++“I will get her to show me.”++“But she will refuse.”++“She will not be able to. But I hear the rumble of wheels. It is her+carriage. Now carry out my orders to the letter.”++As he spoke the gleam of the sidelights of a carriage came round the+curve of the avenue. It was a smart little landau which rattled up to+the door of Briony Lodge. As it pulled up, one of the loafing men at+the corner dashed forward to open the door in the hope of earning a+copper, but was elbowed away by another loafer, who had rushed up with+the same intention. A fierce quarrel broke out, which was increased by+the two guardsmen, who took sides with one of the loungers, and by the+scissors-grinder, who was equally hot upon the other side. A blow was+struck, and in an instant the lady, who had stepped from her carriage,+was the centre of a little knot of flushed and struggling men, who+struck savagely at each other with their fists and sticks. Holmes+dashed into the crowd to protect the lady; but, just as he reached her,+he gave a cry and dropped to the ground, with the blood running freely+down his face. At his fall the guardsmen took to their heels in one+direction and the loungers in the other, while a number of better+dressed people, who had watched the scuffle without taking part in it,+crowded in to help the lady and to attend to the injured man. Irene+Adler, as I will still call her, had hurried up the steps; but she+stood at the top with her superb figure outlined against the lights of+the hall, looking back into the street.++“Is the poor gentleman much hurt?” she asked.++“He is dead,” cried several voices.++“No, no, there’s life in him!” shouted another. “But he’ll be gone+before you can get him to hospital.”++“He’s a brave fellow,” said a woman. “They would have had the lady’s+purse and watch if it hadn’t been for him. They were a gang, and a+rough one, too. Ah, he’s breathing now.”++“He can’t lie in the street. May we bring him in, marm?”++“Surely. Bring him into the sitting-room. There is a comfortable sofa.+This way, please!”++Slowly and solemnly he was borne into Briony Lodge and laid out in the+principal room, while I still observed the proceedings from my post by+the window. The lamps had been lit, but the blinds had not been drawn,+so that I could see Holmes as he lay upon the couch. I do not know+whether he was seized with compunction at that moment for the part he+was playing, but I know that I never felt more heartily ashamed of+myself in my life than when I saw the beautiful creature against whom I+was conspiring, or the grace and kindliness with which she waited upon+the injured man. And yet it would be the blackest treachery to Holmes+to draw back now from the part which he had intrusted to me. I hardened+my heart, and took the smoke-rocket from under my ulster. After all, I+thought, we are not injuring her. We are but preventing her from+injuring another.++Holmes had sat up upon the couch, and I saw him motion like a man who+is in need of air. A maid rushed across and threw open the window. At+the same instant I saw him raise his hand and at the signal I tossed my+rocket into the room with a cry of “Fire!” The word was no sooner out+of my mouth than the whole crowd of spectators, well dressed and+ill—gentlemen, ostlers, and servant maids—joined in a general shriek of+“Fire!” Thick clouds of smoke curled through the room and out at the+open window. I caught a glimpse of rushing figures, and a moment later+the voice of Holmes from within assuring them that it was a false+alarm. Slipping through the shouting crowd I made my way to the corner+of the street, and in ten minutes was rejoiced to find my friend’s arm+in mine, and to get away from the scene of uproar. He walked swiftly+and in silence for some few minutes until we had turned down one of the+quiet streets which lead towards the Edgeware Road.++“You did it very nicely, Doctor,” he remarked. “Nothing could have been+better. It is all right.”++“You have the photograph?”++“I know where it is.”++“And how did you find out?”++“She showed me, as I told you she would.”++“I am still in the dark.”++“I do not wish to make a mystery,” said he, laughing. “The matter was+perfectly simple. You, of course, saw that everyone in the street was+an accomplice. They were all engaged for the evening.”++“I guessed as much.”++“Then, when the row broke out, I had a little moist red paint in the+palm of my hand. I rushed forward, fell down, clapped my hand to my+face, and became a piteous spectacle. It is an old trick.”++“That also I could fathom.”++“Then they carried me in. She was bound to have me in. What else could+she do? And into her sitting-room, which was the very room which I+suspected. It lay between that and her bedroom, and I was determined to+see which. They laid me on a couch, I motioned for air, they were+compelled to open the window, and you had your chance.”++“How did that help you?”++“It was all-important. When a woman thinks that her house is on fire,+her instinct is at once to rush to the thing which she values most. It+is a perfectly overpowering impulse, and I have more than once taken+advantage of it. In the case of the Darlington Substitution Scandal it+was of use to me, and also in the Arnsworth Castle business. A married+woman grabs at her baby; an unmarried one reaches for her jewel-box.+Now it was clear to me that our lady of to-day had nothing in the house+more precious to her than what we are in quest of. She would rush to+secure it. The alarm of fire was admirably done. The smoke and shouting+were enough to shake nerves of steel. She responded beautifully. The+photograph is in a recess behind a sliding panel just above the right+bell-pull. She was there in an instant, and I caught a glimpse of it as+she half drew it out. When I cried out that it was a false alarm, she+replaced it, glanced at the rocket, rushed from the room, and I have+not seen her since. I rose, and, making my excuses, escaped from the+house. I hesitated whether to attempt to secure the photograph at once;+but the coachman had come in, and as he was watching me narrowly, it+seemed safer to wait. A little over-precipitance may ruin all.”++“And now?” I asked.++“Our quest is practically finished. I shall call with the King+to-morrow, and with you, if you care to come with us. We will be shown+into the sitting-room to wait for the lady, but it is probable that+when she comes she may find neither us nor the photograph. It might be+a satisfaction to his Majesty to regain it with his own hands.”++“And when will you call?”++“At eight in the morning. She will not be up, so that we shall have a+clear field. Besides, we must be prompt, for this marriage may mean a+complete change in her life and habits. I must wire to the King without+delay.”++We had reached Baker Street and had stopped at the door. He was+searching his pockets for the key when someone passing said:++“Good-night, Mister Sherlock Holmes.”++There were several people on the pavement at the time, but the greeting+appeared to come from a slim youth in an ulster who had hurried by.++“I’ve heard that voice before,” said Holmes, staring down the dimly lit+street. “Now, I wonder who the deuce that could have been.”++III.++I slept at Baker Street that night, and we were engaged upon our toast+and coffee in the morning when the King of Bohemia rushed into the+room.++“You have really got it!” he cried, grasping Sherlock Holmes by either+shoulder and looking eagerly into his face.++“Not yet.”++“But you have hopes?”++“I have hopes.”++“Then, come. I am all impatience to be gone.”++“We must have a cab.”++“No, my brougham is waiting.”++“Then that will simplify matters.” We descended and started off once+more for Briony Lodge.++“Irene Adler is married,” remarked Holmes.++“Married! When?”++“Yesterday.”++“But to whom?”++“To an English lawyer named Norton.”++“But she could not love him.”++“I am in hopes that she does.”++“And why in hopes?”++“Because it would spare your Majesty all fear of future annoyance. If+the lady loves her husband, she does not love your Majesty. If she does+not love your Majesty, there is no reason why she should interfere with+your Majesty’s plan.”++“It is true. And yet—! Well! I wish she had been of my own station!+What a queen she would have made!” He relapsed into a moody silence,+which was not broken until we drew up in Serpentine Avenue.++The door of Briony Lodge was open, and an elderly woman stood upon the+steps. She watched us with a sardonic eye as we stepped from the+brougham.++“Mr. Sherlock Holmes, I believe?” said she.++“I am Mr. Holmes,” answered my companion, looking at her with a+questioning and rather startled gaze.++“Indeed! My mistress told me that you were likely to call. She left+this morning with her husband by the 5:15 train from Charing Cross for+the Continent.”++“What!” Sherlock Holmes staggered back, white with chagrin and+surprise. “Do you mean that she has left England?”++“Never to return.”++“And the papers?” asked the King hoarsely. “All is lost.”++“We shall see.” He pushed past the servant and rushed into the+drawing-room, followed by the King and myself. The furniture was+scattered about in every direction, with dismantled shelves and open+drawers, as if the lady had hurriedly ransacked them before her flight.+Holmes rushed at the bell-pull, tore back a small sliding shutter, and,+plunging in his hand, pulled out a photograph and a letter. The+photograph was of Irene Adler herself in evening dress, the letter was+superscribed to “Sherlock Holmes, Esq. To be left till called for.” My+friend tore it open, and we all three read it together. It was dated at+midnight of the preceding night and ran in this way:++ “MY DEAR MR. SHERLOCK HOLMES,—You really did it very well. You took+ me in completely. Until after the alarm of fire, I had not a+ suspicion. But then, when I found how I had betrayed myself, I+ began to think. I had been warned against you months ago. I had+ been told that, if the King employed an agent, it would certainly+ be you. And your address had been given me. Yet, with all this, you+ made me reveal what you wanted to know. Even after I became+ suspicious, I found it hard to think evil of such a dear, kind old+ clergyman. But, you know, I have been trained as an actress myself.+ Male costume is nothing new to me. I often take advantage of the+ freedom which it gives. I sent John, the coachman, to watch you,+ ran upstairs, got into my walking clothes, as I call them, and came+ down just as you departed.++ “Well, I followed you to your door, and so made sure that I was+ really an object of interest to the celebrated Mr. Sherlock Holmes.+ Then I, rather imprudently, wished you good-night, and started for+ the Temple to see my husband.++ “We both thought the best resource was flight, when pursued by so+ formidable an antagonist; so you will find the nest empty when you+ call to-morrow. As to the photograph, your client may rest in+ peace. I love and am loved by a better man than he. The King may do+ what he will without hindrance from one whom he has cruelly+ wronged. I keep it only to safeguard myself, and to preserve a+ weapon which will always secure me from any steps which he might+ take in the future. I leave a photograph which he might care to+ possess; and I remain, dear Mr. Sherlock Holmes,++ “Very truly yours,++ “IRENE NORTON, _née_ ADLER.”++“What a woman—oh, what a woman!” cried the King of Bohemia, when we had+all three read this epistle. “Did I not tell you how quick and resolute+she was? Would she not have made an admirable queen? Is it not a pity+that she was not on my level?”++“From what I have seen of the lady, she seems, indeed, to be on a very+different level to your Majesty,” said Holmes coldly. “I am sorry that+I have not been able to bring your Majesty’s business to a more+successful conclusion.”++“On the contrary, my dear sir,” cried the King; “nothing could be more+successful. I know that her word is inviolate. The photograph is now as+safe as if it were in the fire.”++“I am glad to hear your Majesty say so.”++“I am immensely indebted to you. Pray tell me in what way I can reward+you. This ring—” He slipped an emerald snake ring from his finger and+held it out upon the palm of his hand.++“Your Majesty has something which I should value even more highly,”+said Holmes.++“You have but to name it.”++“This photograph!”++The King stared at him in amazement.++“Irene’s photograph!” he cried. “Certainly, if you wish it.”++“I thank your Majesty. Then there is no more to be done in the matter.+I have the honour to wish you a very good morning.” He bowed, and,+turning away without observing the hand which the King had stretched+out to him, he set off in my company for his chambers.++And that was how a great scandal threatened to affect the kingdom of+Bohemia, and how the best plans of Mr. Sherlock Holmes were beaten by a+woman’s wit. He used to make merry over the cleverness of women, but I+have not heard him do it of late. And when he speaks of Irene Adler, or+when he refers to her photograph, it is always under the honourable+title of _the_ woman.++II. THE RED-HEADED LEAGUE++ I had called upon my friend, Mr. Sherlock Holmes, one day in the+ autumn of last year and found him in deep conversation with a very+ stout, florid-faced, elderly gentleman with fiery red hair. With an+ apology for my intrusion, I was about to withdraw when Holmes pulled+ me abruptly into the room and closed the door behind me.++“You could not possibly have come at a better time, my dear Watson,” he+said cordially.++“I was afraid that you were engaged.”++“So I am. Very much so.”++“Then I can wait in the next room.”++“Not at all. This gentleman, Mr. Wilson, has been my partner and helper+in many of my most successful cases, and I have no doubt that he will+be of the utmost use to me in yours also.”++The stout gentleman half rose from his chair and gave a bob of+greeting, with a quick little questioning glance from his small+fat-encircled eyes.++“Try the settee,” said Holmes, relapsing into his armchair and putting+his fingertips together, as was his custom when in judicial moods. “I+know, my dear Watson, that you share my love of all that is bizarre and+outside the conventions and humdrum routine of everyday life. You have+shown your relish for it by the enthusiasm which has prompted you to+chronicle, and, if you will excuse my saying so, somewhat to embellish+so many of my own little adventures.”++“Your cases have indeed been of the greatest interest to me,” I+observed.++“You will remember that I remarked the other day, just before we went+into the very simple problem presented by Miss Mary Sutherland, that+for strange effects and extraordinary combinations we must go to life+itself, which is always far more daring than any effort of the+imagination.”++“A proposition which I took the liberty of doubting.”++“You did, Doctor, but none the less you must come round to my view, for+otherwise I shall keep on piling fact upon fact on you until your+reason breaks down under them and acknowledges me to be right. Now, Mr.+Jabez Wilson here has been good enough to call upon me this morning,+and to begin a narrative which promises to be one of the most singular+which I have listened to for some time. You have heard me remark that+the strangest and most unique things are very often connected not with+the larger but with the smaller crimes, and occasionally, indeed, where+there is room for doubt whether any positive crime has been committed.+As far as I have heard, it is impossible for me to say whether the+present case is an instance of crime or not, but the course of events+is certainly among the most singular that I have ever listened to.+Perhaps, Mr. Wilson, you would have the great kindness to recommence+your narrative. I ask you not merely because my friend Dr. Watson has+not heard the opening part but also because the peculiar nature of the+story makes me anxious to have every possible detail from your lips. As+a rule, when I have heard some slight indication of the course of+events, I am able to guide myself by the thousands of other similar+cases which occur to my memory. In the present instance I am forced to+admit that the facts are, to the best of my belief, unique.”++The portly client puffed out his chest with an appearance of some+little pride and pulled a dirty and wrinkled newspaper from the inside+pocket of his greatcoat. As he glanced down the advertisement column,+with his head thrust forward and the paper flattened out upon his knee,+I took a good look at the man and endeavoured, after the fashion of my+companion, to read the indications which might be presented by his+dress or appearance.++I did not gain very much, however, by my inspection. Our visitor bore+every mark of being an average commonplace British tradesman, obese,+pompous, and slow. He wore rather baggy grey shepherd’s check trousers,+a not over-clean black frock-coat, unbuttoned in the front, and a drab+waistcoat with a heavy brassy Albert chain, and a square pierced bit of+metal dangling down as an ornament. A frayed top-hat and a faded brown+overcoat with a wrinkled velvet collar lay upon a chair beside him.+Altogether, look as I would, there was nothing remarkable about the man+save his blazing red head, and the expression of extreme chagrin and+discontent upon his features.++Sherlock Holmes’ quick eye took in my occupation, and he shook his head+with a smile as he noticed my questioning glances. “Beyond the obvious+facts that he has at some time done manual labour, that he takes snuff,+that he is a Freemason, that he has been in China, and that he has done+a considerable amount of writing lately, I can deduce nothing else.”++Mr. Jabez Wilson started up in his chair, with his forefinger upon the+paper, but his eyes upon my companion.++“How, in the name of good-fortune, did you know all that, Mr. Holmes?”+he asked. “How did you know, for example, that I did manual labour.+It’s as true as gospel, for I began as a ship’s carpenter.”++“Your hands, my dear sir. Your right hand is quite a size larger than+your left. You have worked with it, and the muscles are more+developed.”++“Well, the snuff, then, and the Freemasonry?”++“I won’t insult your intelligence by telling you how I read that,+especially as, rather against the strict rules of your order, you use+an arc-and-compass breastpin.”++“Ah, of course, I forgot that. But the writing?”++“What else can be indicated by that right cuff so very shiny for five+inches, and the left one with the smooth patch near the elbow where you+rest it upon the desk?”++“Well, but China?”++“The fish that you have tattooed immediately above your right wrist+could only have been done in China. I have made a small study of tattoo+marks and have even contributed to the literature of the subject. That+trick of staining the fishes’ scales of a delicate pink is quite+peculiar to China. When, in addition, I see a Chinese coin hanging from+your watch-chain, the matter becomes even more simple.”++Mr. Jabez Wilson laughed heavily. “Well, I never!” said he. “I thought+at first that you had done something clever, but I see that there was+nothing in it after all.”++“I begin to think, Watson,” said Holmes, “that I make a mistake in+explaining. ‘_Omne ignotum pro magnifico_,’ you know, and my poor+little reputation, such as it is, will suffer shipwreck if I am so+candid. Can you not find the advertisement, Mr. Wilson?”++“Yes, I have got it now,” he answered with his thick red finger planted+halfway down the column. “Here it is. This is what began it all. You+just read it for yourself, sir.”++I took the paper from him and read as follows:++“TO THE RED-HEADED LEAGUE: On account of the bequest of the late+Ezekiah Hopkins, of Lebanon, Pennsylvania, U.S.A., there is now another+vacancy open which entitles a member of the League to a salary of £ 4 a+week for purely nominal services. All red-headed men who are sound in+body and mind and above the age of twenty-one years, are eligible.+Apply in person on Monday, at eleven o’clock, to Duncan Ross, at the+offices of the League, 7 Pope’s Court, Fleet Street.”++“What on earth does this mean?” I ejaculated after I had twice read+over the extraordinary announcement.++Holmes chuckled and wriggled in his chair, as was his habit when in+high spirits. “It is a little off the beaten track, isn’t it?” said he.+“And now, Mr. Wilson, off you go at scratch and tell us all about+yourself, your household, and the effect which this advertisement had+upon your fortunes. You will first make a note, Doctor, of the paper+and the date.”++“It is _The Morning Chronicle_ of April 27, 1890. Just two months ago.”++“Very good. Now, Mr. Wilson?”++“Well, it is just as I have been telling you, Mr. Sherlock Holmes,”+said Jabez Wilson, mopping his forehead; “I have a small pawnbroker’s+business at Coburg Square, near the City. It’s not a very large affair,+and of late years it has not done more than just give me a living. I+used to be able to keep two assistants, but now I only keep one; and I+would have a job to pay him but that he is willing to come for half+wages so as to learn the business.”++“What is the name of this obliging youth?” asked Sherlock Holmes.++“His name is Vincent Spaulding, and he’s not such a youth, either. It’s+hard to say his age. I should not wish a smarter assistant, Mr. Holmes;+and I know very well that he could better himself and earn twice what I+am able to give him. But, after all, if he is satisfied, why should I+put ideas in his head?”++“Why, indeed? You seem most fortunate in having an _employé_ who comes+under the full market price. It is not a common experience among+employers in this age. I don’t know that your assistant is not as+remarkable as your advertisement.”++“Oh, he has his faults, too,” said Mr. Wilson. “Never was such a fellow+for photography. Snapping away with a camera when he ought to be+improving his mind, and then diving down into the cellar like a rabbit+into its hole to develop his pictures. That is his main fault, but on+the whole he’s a good worker. There’s no vice in him.”++“He is still with you, I presume?”++“Yes, sir. He and a girl of fourteen, who does a bit of simple cooking+and keeps the place clean—that’s all I have in the house, for I am a+widower and never had any family. We live very quietly, sir, the three+of us; and we keep a roof over our heads and pay our debts, if we do+nothing more.++“The first thing that put us out was that advertisement. Spaulding, he+came down into the office just this day eight weeks, with this very+paper in his hand, and he says:++“‘I wish to the Lord, Mr. Wilson, that I was a red-headed man.’++“‘Why that?’ I asks.++“‘Why,’ says he, ‘here’s another vacancy on the League of the+Red-headed Men. It’s worth quite a little fortune to any man who gets+it, and I understand that there are more vacancies than there are men,+so that the trustees are at their wits’ end what to do with the money.+If my hair would only change colour, here’s a nice little crib all+ready for me to step into.’++“‘Why, what is it, then?’ I asked. You see, Mr. Holmes, I am a very+stay-at-home man, and as my business came to me instead of my having to+go to it, I was often weeks on end without putting my foot over the+door-mat. In that way I didn’t know much of what was going on outside,+and I was always glad of a bit of news.++“‘Have you never heard of the League of the Red-headed Men?’ he asked+with his eyes open.++“‘Never.’++“‘Why, I wonder at that, for you are eligible yourself for one of the+vacancies.’++“‘And what are they worth?’ I asked.++“‘Oh, merely a couple of hundred a year, but the work is slight, and it+need not interfere very much with one’s other occupations.’++“Well, you can easily think that that made me prick up my ears, for the+business has not been over good for some years, and an extra couple of+hundred would have been very handy.++“‘Tell me all about it,’ said I.++“‘Well,’ said he, showing me the advertisement, ‘you can see for+yourself that the League has a vacancy, and there is the address where+you should apply for particulars. As far as I can make out, the League+was founded by an American millionaire, Ezekiah Hopkins, who was very+peculiar in his ways. He was himself red-headed, and he had a great+sympathy for all red-headed men; so, when he died, it was found that he+had left his enormous fortune in the hands of trustees, with+instructions to apply the interest to the providing of easy berths to+men whose hair is of that colour. From all I hear it is splendid pay+and very little to do.’++“‘But,’ said I, ‘there would be millions of red-headed men who would+apply.’++“‘Not so many as you might think,’ he answered. ‘You see it is really+confined to Londoners, and to grown men. This American had started from+London when he was young, and he wanted to do the old town a good turn.+Then, again, I have heard it is no use your applying if your hair is+light red, or dark red, or anything but real bright, blazing, fiery+red. Now, if you cared to apply, Mr. Wilson, you would just walk in;+but perhaps it would hardly be worth your while to put yourself out of+the way for the sake of a few hundred pounds.’++“Now, it is a fact, gentlemen, as you may see for yourselves, that my+hair is of a very full and rich tint, so that it seemed to me that if+there was to be any competition in the matter I stood as good a chance+as any man that I had ever met. Vincent Spaulding seemed to know so+much about it that I thought he might prove useful, so I just ordered+him to put up the shutters for the day and to come right away with me.+He was very willing to have a holiday, so we shut the business up and+started off for the address that was given us in the advertisement.++“I never hope to see such a sight as that again, Mr. Holmes. From+north, south, east, and west every man who had a shade of red in his+hair had tramped into the city to answer the advertisement. Fleet+Street was choked with red-headed folk, and Pope’s Court looked like a+coster’s orange barrow. I should not have thought there were so many in+the whole country as were brought together by that single+advertisement. Every shade of colour they were—straw, lemon, orange,+brick, Irish-setter, liver, clay; but, as Spaulding said, there were+not many who had the real vivid flame-coloured tint. When I saw how+many were waiting, I would have given it up in despair; but Spaulding+would not hear of it. How he did it I could not imagine, but he pushed+and pulled and butted until he got me through the crowd, and right up+to the steps which led to the office. There was a double stream upon+the stair, some going up in hope, and some coming back dejected; but we+wedged in as well as we could and soon found ourselves in the office.”++“Your experience has been a most entertaining one,” remarked Holmes as+his client paused and refreshed his memory with a huge pinch of snuff.+“Pray continue your very interesting statement.”++“There was nothing in the office but a couple of wooden chairs and a+deal table, behind which sat a small man with a head that was even+redder than mine. He said a few words to each candidate as he came up,+and then he always managed to find some fault in them which would+disqualify them. Getting a vacancy did not seem to be such a very easy+matter, after all. However, when our turn came the little man was much+more favourable to me than to any of the others, and he closed the door+as we entered, so that he might have a private word with us.++“‘This is Mr. Jabez Wilson,’ said my assistant, ‘and he is willing to+fill a vacancy in the League.’++“‘And he is admirably suited for it,’ the other answered. ‘He has every+requirement. I cannot recall when I have seen anything so fine.’ He+took a step backward, cocked his head on one side, and gazed at my hair+until I felt quite bashful. Then suddenly he plunged forward, wrung my+hand, and congratulated me warmly on my success.++“‘It would be injustice to hesitate,’ said he. ‘You will, however, I am+sure, excuse me for taking an obvious precaution.’ With that he seized+my hair in both his hands, and tugged until I yelled with the pain.+‘There is water in your eyes,’ said he as he released me. ‘I perceive+that all is as it should be. But we have to be careful, for we have+twice been deceived by wigs and once by paint. I could tell you tales+of cobbler’s wax which would disgust you with human nature.’ He stepped+over to the window and shouted through it at the top of his voice that+the vacancy was filled. A groan of disappointment came up from below,+and the folk all trooped away in different directions until there was+not a red-head to be seen except my own and that of the manager.++“‘My name,’ said he, ‘is Mr. Duncan Ross, and I am myself one of the+pensioners upon the fund left by our noble benefactor. Are you a+married man, Mr. Wilson? Have you a family?’++“I answered that I had not.++“His face fell immediately.++“‘Dear me!’ he said gravely, ‘that is very serious indeed! I am sorry+to hear you say that. The fund was, of course, for the propagation and+spread of the red-heads as well as for their maintenance. It is+exceedingly unfortunate that you should be a bachelor.’++“My face lengthened at this, Mr. Holmes, for I thought that I was not+to have the vacancy after all; but after thinking it over for a few+minutes he said that it would be all right.++“‘In the case of another,’ said he, ‘the objection might be fatal, but+we must stretch a point in favour of a man with such a head of hair as+yours. When shall you be able to enter upon your new duties?’++“‘Well, it is a little awkward, for I have a business already,’ said I.++“‘Oh, never mind about that, Mr. Wilson!’ said Vincent Spaulding. ‘I+should be able to look after that for you.’++“‘What would be the hours?’ I asked.++“‘Ten to two.’++“Now a pawnbroker’s business is mostly done of an evening, Mr. Holmes,+especially Thursday and Friday evening, which is just before pay-day;+so it would suit me very well to earn a little in the mornings.+Besides, I knew that my assistant was a good man, and that he would see+to anything that turned up.++“‘That would suit me very well,’ said I. ‘And the pay?’++“‘Is £ 4 a week.’++“‘And the work?’++“‘Is purely nominal.’++“‘What do you call purely nominal?’++“‘Well, you have to be in the office, or at least in the building, the+whole time. If you leave, you forfeit your whole position forever. The+will is very clear upon that point. You don’t comply with the+conditions if you budge from the office during that time.’++“‘It’s only four hours a day, and I should not think of leaving,’ said+I.++“‘No excuse will avail,’ said Mr. Duncan Ross; ‘neither sickness nor+business nor anything else. There you must stay, or you lose your+billet.’++“‘And the work?’++“‘Is to copy out the _Encyclopædia Britannica_. There is the first+volume of it in that press. You must find your own ink, pens, and+blotting-paper, but we provide this table and chair. Will you be ready+to-morrow?’++“‘Certainly,’ I answered.++“‘Then, good-bye, Mr. Jabez Wilson, and let me congratulate you once+more on the important position which you have been fortunate enough to+gain.’ He bowed me out of the room and I went home with my assistant,+hardly knowing what to say or do, I was so pleased at my own good+fortune.++“Well, I thought over the matter all day, and by evening I was in low+spirits again; for I had quite persuaded myself that the whole affair+must be some great hoax or fraud, though what its object might be I+could not imagine. It seemed altogether past belief that anyone could+make such a will, or that they would pay such a sum for doing anything+so simple as copying out the _Encyclopædia Britannica_. Vincent+Spaulding did what he could to cheer me up, but by bedtime I had+reasoned myself out of the whole thing. However, in the morning I+determined to have a look at it anyhow, so I bought a penny bottle of+ink, and with a quill-pen, and seven sheets of foolscap paper, I+started off for Pope’s Court.++“Well, to my surprise and delight, everything was as right as possible.+The table was set out ready for me, and Mr. Duncan Ross was there to+see that I got fairly to work. He started me off upon the letter A, and+then he left me; but he would drop in from time to time to see that all+was right with me. At two o’clock he bade me good-day, complimented me+upon the amount that I had written, and locked the door of the office+after me.++“This went on day after day, Mr. Holmes, and on Saturday the manager+came in and planked down four golden sovereigns for my week’s work. It+was the same next week, and the same the week after. Every morning I+was there at ten, and every afternoon I left at two. By degrees Mr.+Duncan Ross took to coming in only once of a morning, and then, after a+time, he did not come in at all. Still, of course, I never dared to+leave the room for an instant, for I was not sure when he might come,+and the billet was such a good one, and suited me so well, that I would+not risk the loss of it.++“Eight weeks passed away like this, and I had written about Abbots and+Archery and Armour and Architecture and Attica, and hoped with+diligence that I might get on to the B’s before very long. It cost me+something in foolscap, and I had pretty nearly filled a shelf with my+writings. And then suddenly the whole business came to an end.”++“To an end?”++“Yes, sir. And no later than this morning. I went to my work as usual+at ten o’clock, but the door was shut and locked, with a little square+of cardboard hammered on to the middle of the panel with a tack. Here+it is, and you can read for yourself.”++He held up a piece of white cardboard about the size of a sheet of+note-paper. It read in this fashion:++“THE RED-HEADED LEAGUE IS DISSOLVED. October 9, 1890.”++Sherlock Holmes and I surveyed this curt announcement and the rueful+face behind it, until the comical side of the affair so completely+overtopped every other consideration that we both burst out into a roar+of laughter.++“I cannot see that there is anything very funny,” cried our client,+flushing up to the roots of his flaming head. “If you can do nothing+better than laugh at me, I can go elsewhere.”++“No, no,” cried Holmes, shoving him back into the chair from which he+had half risen. “I really wouldn’t miss your case for the world. It is+most refreshingly unusual. But there is, if you will excuse my saying+so, something just a little funny about it. Pray what steps did you+take when you found the card upon the door?”++“I was staggered, sir. I did not know what to do. Then I called at the+offices round, but none of them seemed to know anything about it.+Finally, I went to the landlord, who is an accountant living on the+ground floor, and I asked him if he could tell me what had become of+the Red-headed League. He said that he had never heard of any such+body. Then I asked him who Mr. Duncan Ross was. He answered that the+name was new to him.++“‘Well,’ said I, ‘the gentleman at No. 4.’++“‘What, the red-headed man?’++“‘Yes.’++“‘Oh,’ said he, ‘his name was William Morris. He was a solicitor and+was using my room as a temporary convenience until his new premises+were ready. He moved out yesterday.’++“‘Where could I find him?’++“‘Oh, at his new offices. He did tell me the address. Yes, 17 King+Edward Street, near St. Paul’s.’++“I started off, Mr. Holmes, but when I got to that address it was a+manufactory of artificial knee-caps, and no one in it had ever heard of+either Mr. William Morris or Mr. Duncan Ross.”++“And what did you do then?” asked Holmes.++“I went home to Saxe-Coburg Square, and I took the advice of my+assistant. But he could not help me in any way. He could only say that+if I waited I should hear by post. But that was not quite good enough,+Mr. Holmes. I did not wish to lose such a place without a struggle, so,+as I had heard that you were good enough to give advice to poor folk+who were in need of it, I came right away to you.”++“And you did very wisely,” said Holmes. “Your case is an exceedingly+remarkable one, and I shall be happy to look into it. From what you+have told me I think that it is possible that graver issues hang from+it than might at first sight appear.”++“Grave enough!” said Mr. Jabez Wilson. “Why, I have lost four pound a+week.”++“As far as you are personally concerned,” remarked Holmes, “I do not+see that you have any grievance against this extraordinary league. On+the contrary, you are, as I understand, richer by some £ 30, to say+nothing of the minute knowledge which you have gained on every subject+which comes under the letter A. You have lost nothing by them.”++“No, sir. But I want to find out about them, and who they are, and what+their object was in playing this prank—if it was a prank—upon me. It+was a pretty expensive joke for them, for it cost them two and thirty+pounds.”++“We shall endeavour to clear up these points for you. And, first, one+or two questions, Mr. Wilson. This assistant of yours who first called+your attention to the advertisement—how long had he been with you?”++“About a month then.”++“How did he come?”++“In answer to an advertisement.”++“Was he the only applicant?”++“No, I had a dozen.”++“Why did you pick him?”++“Because he was handy and would come cheap.”++“At half wages, in fact.”++“Yes.”++“What is he like, this Vincent Spaulding?”++“Small, stout-built, very quick in his ways, no hair on his face,+though he’s not short of thirty. Has a white splash of acid upon his+forehead.”++Holmes sat up in his chair in considerable excitement. “I thought as+much,” said he. “Have you ever observed that his ears are pierced for+earrings?”++“Yes, sir. He told me that a gipsy had done it for him when he was a+lad.”++“Hum!” said Holmes, sinking back in deep thought. “He is still with+you?”++“Oh, yes, sir; I have only just left him.”++“And has your business been attended to in your absence?”++“Nothing to complain of, sir. There’s never very much to do of a+morning.”++“That will do, Mr. Wilson. I shall be happy to give you an opinion upon+the subject in the course of a day or two. To-day is Saturday, and I+hope that by Monday we may come to a conclusion.”++“Well, Watson,” said Holmes when our visitor had left us, “what do you+make of it all?”++“I make nothing of it,” I answered frankly. “It is a most mysterious+business.”++“As a rule,” said Holmes, “the more bizarre a thing is the less+mysterious it proves to be. It is your commonplace, featureless crimes+which are really puzzling, just as a commonplace face is the most+difficult to identify. But I must be prompt over this matter.”++“What are you going to do, then?” I asked.++“To smoke,” he answered. “It is quite a three pipe problem, and I beg+that you won’t speak to me for fifty minutes.” He curled himself up in+his chair, with his thin knees drawn up to his hawk-like nose, and+there he sat with his eyes closed and his black clay pipe thrusting out+like the bill of some strange bird. I had come to the conclusion that+he had dropped asleep, and indeed was nodding myself, when he suddenly+sprang out of his chair with the gesture of a man who has made up his+mind and put his pipe down upon the mantelpiece.++“Sarasate plays at the St. James’s Hall this afternoon,” he remarked.+“What do you think, Watson? Could your patients spare you for a few+hours?”++“I have nothing to do to-day. My practice is never very absorbing.”++“Then put on your hat and come. I am going through the City first, and+we can have some lunch on the way. I observe that there is a good deal+of German music on the programme, which is rather more to my taste than+Italian or French. It is introspective, and I want to introspect. Come+along!”++We travelled by the Underground as far as Aldersgate; and a short walk+took us to Saxe-Coburg Square, the scene of the singular story which we+had listened to in the morning. It was a poky, little, shabby-genteel+place, where four lines of dingy two-storied brick houses looked out+into a small railed-in enclosure, where a lawn of weedy grass and a few+clumps of faded laurel bushes made a hard fight against a smoke-laden+and uncongenial atmosphere. Three gilt balls and a brown board with+“JABEZ WILSON” in white letters, upon a corner house, announced the+place where our red-headed client carried on his business. Sherlock+Holmes stopped in front of it with his head on one side and looked it+all over, with his eyes shining brightly between puckered lids. Then he+walked slowly up the street, and then down again to the corner, still+looking keenly at the houses. Finally he returned to the pawnbroker’s,+and, having thumped vigorously upon the pavement with his stick two or+three times, he went up to the door and knocked. It was instantly+opened by a bright-looking, clean-shaven young fellow, who asked him to+step in.++“Thank you,” said Holmes, “I only wished to ask you how you would go+from here to the Strand.”++“Third right, fourth left,” answered the assistant promptly, closing+the door.++“Smart fellow, that,” observed Holmes as we walked away. “He is, in my+judgment, the fourth smartest man in London, and for daring I am not+sure that he has not a claim to be third. I have known something of him+before.”++“Evidently,” said I, “Mr. Wilson’s assistant counts for a good deal in+this mystery of the Red-headed League. I am sure that you inquired your+way merely in order that you might see him.”++“Not him.”++“What then?”++“The knees of his trousers.”++“And what did you see?”++“What I expected to see.”++“Why did you beat the pavement?”++“My dear doctor, this is a time for observation, not for talk. We are+spies in an enemy’s country. We know something of Saxe-Coburg Square.+Let us now explore the parts which lie behind it.”++The road in which we found ourselves as we turned round the corner from+the retired Saxe-Coburg Square presented as great a contrast to it as+the front of a picture does to the back. It was one of the main+arteries which conveyed the traffic of the City to the north and west.+The roadway was blocked with the immense stream of commerce flowing in+a double tide inward and outward, while the footpaths were black with+the hurrying swarm of pedestrians. It was difficult to realise as we+looked at the line of fine shops and stately business premises that+they really abutted on the other side upon the faded and stagnant+square which we had just quitted.++“Let me see,” said Holmes, standing at the corner and glancing along+the line, “I should like just to remember the order of the houses here.+It is a hobby of mine to have an exact knowledge of London. There is+Mortimer’s, the tobacconist, the little newspaper shop, the Coburg+branch of the City and Suburban Bank, the Vegetarian Restaurant, and+McFarlane’s carriage-building depot. That carries us right on to the+other block. And now, Doctor, we’ve done our work, so it’s time we had+some play. A sandwich and a cup of coffee, and then off to violin-land,+where all is sweetness and delicacy and harmony, and there are no+red-headed clients to vex us with their conundrums.”++My friend was an enthusiastic musician, being himself not only a very+capable performer but a composer of no ordinary merit. All the+afternoon he sat in the stalls wrapped in the most perfect happiness,+gently waving his long, thin fingers in time to the music, while his+gently smiling face and his languid, dreamy eyes were as unlike those+of Holmes the sleuth-hound, Holmes the relentless, keen-witted,+ready-handed criminal agent, as it was possible to conceive. In his+singular character the dual nature alternately asserted itself, and his+extreme exactness and astuteness represented, as I have often thought,+the reaction against the poetic and contemplative mood which+occasionally predominated in him. The swing of his nature took him from+extreme languor to devouring energy; and, as I knew well, he was never+so truly formidable as when, for days on end, he had been lounging in+his armchair amid his improvisations and his black-letter editions.+Then it was that the lust of the chase would suddenly come upon him,+and that his brilliant reasoning power would rise to the level of+intuition, until those who were unacquainted with his methods would+look askance at him as on a man whose knowledge was not that of other+mortals. When I saw him that afternoon so enwrapped in the music at St.+James’s Hall I felt that an evil time might be coming upon those whom+he had set himself to hunt down.++“You want to go home, no doubt, Doctor,” he remarked as we emerged.++“Yes, it would be as well.”++“And I have some business to do which will take some hours. This+business at Coburg Square is serious.”++“Why serious?”++“A considerable crime is in contemplation. I have every reason to+believe that we shall be in time to stop it. But to-day being Saturday+rather complicates matters. I shall want your help to-night.”++“At what time?”++“Ten will be early enough.”++“I shall be at Baker Street at ten.”++“Very well. And, I say, Doctor, there may be some little danger, so+kindly put your army revolver in your pocket.” He waved his hand,+turned on his heel, and disappeared in an instant among the crowd.++I trust that I am not more dense than my neighbours, but I was always+oppressed with a sense of my own stupidity in my dealings with Sherlock+Holmes. Here I had heard what he had heard, I had seen what he had+seen, and yet from his words it was evident that he saw clearly not+only what had happened but what was about to happen, while to me the+whole business was still confused and grotesque. As I drove home to my+house in Kensington I thought over it all, from the extraordinary story+of the red-headed copier of the _Encyclopædia_ down to the visit to+Saxe-Coburg Square, and the ominous words with which he had parted from+me. What was this nocturnal expedition, and why should I go armed?+Where were we going, and what were we to do? I had the hint from Holmes+that this smooth-faced pawnbroker’s assistant was a formidable man—a+man who might play a deep game. I tried to puzzle it out, but gave it+up in despair and set the matter aside until night should bring an+explanation.++It was a quarter-past nine when I started from home and made my way+across the Park, and so through Oxford Street to Baker Street. Two+hansoms were standing at the door, and as I entered the passage I heard+the sound of voices from above. On entering his room, I found Holmes in+animated conversation with two men, one of whom I recognised as Peter+Jones, the official police agent, while the other was a long, thin,+sad-faced man, with a very shiny hat and oppressively respectable+frock-coat.++“Ha! Our party is complete,” said Holmes, buttoning up his pea-jacket+and taking his heavy hunting crop from the rack. “Watson, I think you+know Mr. Jones, of Scotland Yard? Let me introduce you to Mr.+Merryweather, who is to be our companion in to-night’s adventure.”++“We’re hunting in couples again, Doctor, you see,” said Jones in his+consequential way. “Our friend here is a wonderful man for starting a+chase. All he wants is an old dog to help him to do the running down.”++“I hope a wild goose may not prove to be the end of our chase,”+observed Mr. Merryweather gloomily.++“You may place considerable confidence in Mr. Holmes, sir,” said the+police agent loftily. “He has his own little methods, which are, if he+won’t mind my saying so, just a little too theoretical and fantastic,+but he has the makings of a detective in him. It is not too much to say+that once or twice, as in that business of the Sholto murder and the+Agra treasure, he has been more nearly correct than the official+force.”++“Oh, if you say so, Mr. Jones, it is all right,” said the stranger with+deference. “Still, I confess that I miss my rubber. It is the first+Saturday night for seven-and-twenty years that I have not had my+rubber.”++“I think you will find,” said Sherlock Holmes, “that you will play for+a higher stake to-night than you have ever done yet, and that the play+will be more exciting. For you, Mr. Merryweather, the stake will be+some £ 30,000; and for you, Jones, it will be the man upon whom you+wish to lay your hands.”++“John Clay, the murderer, thief, smasher, and forger. He’s a young man,+Mr. Merryweather, but he is at the head of his profession, and I would+rather have my bracelets on him than on any criminal in London. He’s a+remarkable man, is young John Clay. His grandfather was a royal duke,+and he himself has been to Eton and Oxford. His brain is as cunning as+his fingers, and though we meet signs of him at every turn, we never+know where to find the man himself. He’ll crack a crib in Scotland one+week, and be raising money to build an orphanage in Cornwall the next.+I’ve been on his track for years and have never set eyes on him yet.”++“I hope that I may have the pleasure of introducing you to-night. I’ve+had one or two little turns also with Mr. John Clay, and I agree with+you that he is at the head of his profession. It is past ten, however,+and quite time that we started. If you two will take the first hansom,+Watson and I will follow in the second.”++Sherlock Holmes was not very communicative during the long drive and+lay back in the cab humming the tunes which he had heard in the+afternoon. We rattled through an endless labyrinth of gas-lit streets+until we emerged into Farrington Street.++“We are close there now,” my friend remarked. “This fellow Merryweather+is a bank director, and personally interested in the matter. I thought+it as well to have Jones with us also. He is not a bad fellow, though+an absolute imbecile in his profession. He has one positive virtue. He+is as brave as a bulldog and as tenacious as a lobster if he gets his+claws upon anyone. Here we are, and they are waiting for us.”++We had reached the same crowded thoroughfare in which we had found+ourselves in the morning. Our cabs were dismissed, and, following the+guidance of Mr. Merryweather, we passed down a narrow passage and+through a side door, which he opened for us. Within there was a small+corridor, which ended in a very massive iron gate. This also was+opened, and led down a flight of winding stone steps, which terminated+at another formidable gate. Mr. Merryweather stopped to light a+lantern, and then conducted us down a dark, earth-smelling passage, and+so, after opening a third door, into a huge vault or cellar, which was+piled all round with crates and massive boxes.++“You are not very vulnerable from above,” Holmes remarked as he held up+the lantern and gazed about him.++“Nor from below,” said Mr. Merryweather, striking his stick upon the+flags which lined the floor. “Why, dear me, it sounds quite hollow!” he+remarked, looking up in surprise.++“I must really ask you to be a little more quiet!” said Holmes+severely. “You have already imperilled the whole success of our+expedition. Might I beg that you would have the goodness to sit down+upon one of those boxes, and not to interfere?”++The solemn Mr. Merryweather perched himself upon a crate, with a very+injured expression upon his face, while Holmes fell upon his knees upon+the floor and, with the lantern and a magnifying lens, began to examine+minutely the cracks between the stones. A few seconds sufficed to+satisfy him, for he sprang to his feet again and put his glass in his+pocket.++“We have at least an hour before us,” he remarked, “for they can hardly+take any steps until the good pawnbroker is safely in bed. Then they+will not lose a minute, for the sooner they do their work the longer+time they will have for their escape. We are at present, Doctor—as no+doubt you have divined—in the cellar of the City branch of one of the+principal London banks. Mr. Merryweather is the chairman of directors,+and he will explain to you that there are reasons why the more daring+criminals of London should take a considerable interest in this cellar+at present.”++“It is our French gold,” whispered the director. “We have had several+warnings that an attempt might be made upon it.”++“Your French gold?”++“Yes. We had occasion some months ago to strengthen our resources and+borrowed for that purpose 30,000 napoleons from the Bank of France. It+has become known that we have never had occasion to unpack the money,+and that it is still lying in our cellar. The crate upon which I sit+contains 2,000 napoleons packed between layers of lead foil. Our+reserve of bullion is much larger at present than is usually kept in a+single branch office, and the directors have had misgivings upon the+subject.”++“Which were very well justified,” observed Holmes. “And now it is time+that we arranged our little plans. I expect that within an hour matters+will come to a head. In the meantime Mr. Merryweather, we must put the+screen over that dark lantern.”++“And sit in the dark?”++“I am afraid so. I had brought a pack of cards in my pocket, and I+thought that, as we were a _partie carrée_, you might have your rubber+after all. But I see that the enemy’s preparations have gone so far+that we cannot risk the presence of a light. And, first of all, we must+choose our positions. These are daring men, and though we shall take+them at a disadvantage, they may do us some harm unless we are careful.+I shall stand behind this crate, and do you conceal yourselves behind+those. Then, when I flash a light upon them, close in swiftly. If they+fire, Watson, have no compunction about shooting them down.”++I placed my revolver, cocked, upon the top of the wooden case behind+which I crouched. Holmes shot the slide across the front of his lantern+and left us in pitch darkness—such an absolute darkness as I have never+before experienced. The smell of hot metal remained to assure us that+the light was still there, ready to flash out at a moment’s notice. To+me, with my nerves worked up to a pitch of expectancy, there was+something depressing and subduing in the sudden gloom, and in the cold+dank air of the vault.++“They have but one retreat,” whispered Holmes. “That is back through+the house into Saxe-Coburg Square. I hope that you have done what I+asked you, Jones?”++“I have an inspector and two officers waiting at the front door.”++“Then we have stopped all the holes. And now we must be silent and+wait.”++What a time it seemed! From comparing notes afterwards it was but an+hour and a quarter, yet it appeared to me that the night must have+almost gone, and the dawn be breaking above us. My limbs were weary and+stiff, for I feared to change my position; yet my nerves were worked up+to the highest pitch of tension, and my hearing was so acute that I+could not only hear the gentle breathing of my companions, but I could+distinguish the deeper, heavier in-breath of the bulky Jones from the+thin, sighing note of the bank director. From my position I could look+over the case in the direction of the floor. Suddenly my eyes caught+the glint of a light.++At first it was but a lurid spark upon the stone pavement. Then it+lengthened out until it became a yellow line, and then, without any+warning or sound, a gash seemed to open and a hand appeared, a white,+almost womanly hand, which felt about in the centre of the little area+of light. For a minute or more the hand, with its writhing fingers,+protruded out of the floor. Then it was withdrawn as suddenly as it+appeared, and all was dark again save the single lurid spark which+marked a chink between the stones.++Its disappearance, however, was but momentary. With a rending, tearing+sound, one of the broad, white stones turned over upon its side and+left a square, gaping hole, through which streamed the light of a+lantern. Over the edge there peeped a clean-cut, boyish face, which+looked keenly about it, and then, with a hand on either side of the+aperture, drew itself shoulder-high and waist-high, until one knee+rested upon the edge. In another instant he stood at the side of the+hole and was hauling after him a companion, lithe and small like+himself, with a pale face and a shock of very red hair.++“It’s all clear,” he whispered. “Have you the chisel and the bags?+Great Scott! Jump, Archie, jump, and I’ll swing for it!”++Sherlock Holmes had sprung out and seized the intruder by the collar.+The other dived down the hole, and I heard the sound of rending cloth+as Jones clutched at his skirts. The light flashed upon the barrel of a+revolver, but Holmes’ hunting crop came down on the man’s wrist, and+the pistol clinked upon the stone floor.++“It’s no use, John Clay,” said Holmes blandly. “You have no chance at+all.”++“So I see,” the other answered with the utmost coolness. “I fancy that+my pal is all right, though I see you have got his coat-tails.”++“There are three men waiting for him at the door,” said Holmes.++“Oh, indeed! You seem to have done the thing very completely. I must+compliment you.”++“And I you,” Holmes answered. “Your red-headed idea was very new and+effective.”++“You’ll see your pal again presently,” said Jones. “He’s quicker at+climbing down holes than I am. Just hold out while I fix the derbies.”++“I beg that you will not touch me with your filthy hands,” remarked our+prisoner as the handcuffs clattered upon his wrists. “You may not be+aware that I have royal blood in my veins. Have the goodness, also,+when you address me always to say ‘sir’ and ‘please.’”++“All right,” said Jones with a stare and a snigger. “Well, would you+please, sir, march upstairs, where we can get a cab to carry your+Highness to the police-station?”++“That is better,” said John Clay serenely. He made a sweeping bow to+the three of us and walked quietly off in the custody of the detective.++“Really, Mr. Holmes,” said Mr. Merryweather as we followed them from+the cellar, “I do not know how the bank can thank you or repay you.+There is no doubt that you have detected and defeated in the most+complete manner one of the most determined attempts at bank robbery+that have ever come within my experience.”++“I have had one or two little scores of my own to settle with Mr. John+Clay,” said Holmes. “I have been at some small expense over this+matter, which I shall expect the bank to refund, but beyond that I am+amply repaid by having had an experience which is in many ways unique,+and by hearing the very remarkable narrative of the Red-headed League.”++“You see, Watson,” he explained in the early hours of the morning as we+sat over a glass of whisky and soda in Baker Street, “it was perfectly+obvious from the first that the only possible object of this rather+fantastic business of the advertisement of the League, and the copying+of the _Encyclopædia_, must be to get this not over-bright pawnbroker+out of the way for a number of hours every day. It was a curious way of+managing it, but, really, it would be difficult to suggest a better.+The method was no doubt suggested to Clay’s ingenious mind by the+colour of his accomplice’s hair. The £ 4 a week was a lure which must+draw him, and what was it to them, who were playing for thousands? They+put in the advertisement, one rogue has the temporary office, the other+rogue incites the man to apply for it, and together they manage to+secure his absence every morning in the week. From the time that I+heard of the assistant having come for half wages, it was obvious to me+that he had some strong motive for securing the situation.”++“But how could you guess what the motive was?”++“Had there been women in the house, I should have suspected a mere+vulgar intrigue. That, however, was out of the question. The man’s+business was a small one, and there was nothing in his house which+could account for such elaborate preparations, and such an expenditure+as they were at. It must, then, be something out of the house. What+could it be? I thought of the assistant’s fondness for photography, and+his trick of vanishing into the cellar. The cellar! There was the end+of this tangled clue. Then I made inquiries as to this mysterious+assistant and found that I had to deal with one of the coolest and most+daring criminals in London. He was doing something in the+cellar—something which took many hours a day for months on end. What+could it be, once more? I could think of nothing save that he was+running a tunnel to some other building.++“So far I had got when we went to visit the scene of action. I+surprised you by beating upon the pavement with my stick. I was+ascertaining whether the cellar stretched out in front or behind. It+was not in front. Then I rang the bell, and, as I hoped, the assistant+answered it. We have had some skirmishes, but we had never set eyes+upon each other before. I hardly looked at his face. His knees were+what I wished to see. You must yourself have remarked how worn,+wrinkled, and stained they were. They spoke of those hours of+burrowing. The only remaining point was what they were burrowing for. I+walked round the corner, saw the City and Suburban Bank abutted on our+friend’s premises, and felt that I had solved my problem. When you+drove home after the concert I called upon Scotland Yard and upon the+chairman of the bank directors, with the result that you have seen.”++“And how could you tell that they would make their attempt to-night?” I+asked.++“Well, when they closed their League offices that was a sign that they+cared no longer about Mr. Jabez Wilson’s presence—in other words, that+they had completed their tunnel. But it was essential that they should+use it soon, as it might be discovered, or the bullion might be+removed. Saturday would suit them better than any other day, as it+would give them two days for their escape. For all these reasons I+expected them to come to-night.”++“You reasoned it out beautifully,” I exclaimed in unfeigned admiration.+“It is so long a chain, and yet every link rings true.”++“It saved me from ennui,” he answered, yawning. “Alas! I already feel+it closing in upon me. My life is spent in one long effort to escape+from the commonplaces of existence. These little problems help me to do+so.”++“And you are a benefactor of the race,” said I.++He shrugged his shoulders. “Well, perhaps, after all, it is of some+little use,” he remarked. “‘_L’homme c’est rien—l’œuvre c’est tout_,’+as Gustave Flaubert wrote to George Sand.”++III. A CASE OF IDENTITY++“My dear fellow,” said Sherlock Holmes as we sat on either side of the+fire in his lodgings at Baker Street, “life is infinitely stranger than+anything which the mind of man could invent. We would not dare to+conceive the things which are really mere commonplaces of existence. If+we could fly out of that window hand in hand, hover over this great+city, gently remove the roofs, and peep in at the queer things which+are going on, the strange coincidences, the plannings, the+cross-purposes, the wonderful chains of events, working through+generations, and leading to the most _outré_ results, it would make all+fiction with its conventionalities and foreseen conclusions most stale+and unprofitable.”++“And yet I am not convinced of it,” I answered. “The cases which come+to light in the papers are, as a rule, bald enough, and vulgar enough.+We have in our police reports realism pushed to its extreme limits, and+yet the result is, it must be confessed, neither fascinating nor+artistic.”++“A certain selection and discretion must be used in producing a+realistic effect,” remarked Holmes. “This is wanting in the police+report, where more stress is laid, perhaps, upon the platitudes of the+magistrate than upon the details, which to an observer contain the+vital essence of the whole matter. Depend upon it, there is nothing so+unnatural as the commonplace.”++I smiled and shook my head. “I can quite understand your thinking so,”+I said. “Of course, in your position of unofficial adviser and helper+to everybody who is absolutely puzzled, throughout three continents,+you are brought in contact with all that is strange and bizarre. But+here”—I picked up the morning paper from the ground—“let us put it to a+practical test. Here is the first heading upon which I come. ‘A+husband’s cruelty to his wife.’ There is half a column of print, but I+know without reading it that it is all perfectly familiar to me. There+is, of course, the other woman, the drink, the push, the blow, the+bruise, the sympathetic sister or landlady. The crudest of writers+could invent nothing more crude.”++“Indeed, your example is an unfortunate one for your argument,” said+Holmes, taking the paper and glancing his eye down it. “This is the+Dundas separation case, and, as it happens, I was engaged in clearing+up some small points in connection with it. The husband was a+teetotaler, there was no other woman, and the conduct complained of was+that he had drifted into the habit of winding up every meal by taking+out his false teeth and hurling them at his wife, which, you will+allow, is not an action likely to occur to the imagination of the+average story-teller. Take a pinch of snuff, Doctor, and acknowledge+that I have scored over you in your example.”++He held out his snuffbox of old gold, with a great amethyst in the+centre of the lid. Its splendour was in such contrast to his homely+ways and simple life that I could not help commenting upon it.++“Ah,” said he, “I forgot that I had not seen you for some weeks. It is+a little souvenir from the King of Bohemia in return for my assistance+in the case of the Irene Adler papers.”++“And the ring?” I asked, glancing at a remarkable brilliant which+sparkled upon his finger.++“It was from the reigning family of Holland, though the matter in which+I served them was of such delicacy that I cannot confide it even to+you, who have been good enough to chronicle one or two of my little+problems.”++“And have you any on hand just now?” I asked with interest.++“Some ten or twelve, but none which present any feature of interest.+They are important, you understand, without being interesting. Indeed,+I have found that it is usually in unimportant matters that there is a+field for the observation, and for the quick analysis of cause and+effect which gives the charm to an investigation. The larger crimes are+apt to be the simpler, for the bigger the crime the more obvious, as a+rule, is the motive. In these cases, save for one rather intricate+matter which has been referred to me from Marseilles, there is nothing+which presents any features of interest. It is possible, however, that+I may have something better before very many minutes are over, for this+is one of my clients, or I am much mistaken.”++He had risen from his chair and was standing between the parted blinds+gazing down into the dull neutral-tinted London street. Looking over+his shoulder, I saw that on the pavement opposite there stood a large+woman with a heavy fur boa round her neck, and a large curling red+feather in a broad-brimmed hat which was tilted in a coquettish Duchess+of Devonshire fashion over her ear. From under this great panoply she+peeped up in a nervous, hesitating fashion at our windows, while her+body oscillated backward and forward, and her fingers fidgeted with her+glove buttons. Suddenly, with a plunge, as of the swimmer who leaves+the bank, she hurried across the road, and we heard the sharp clang of+the bell.++“I have seen those symptoms before,” said Holmes, throwing his+cigarette into the fire. “Oscillation upon the pavement always means an+_affaire de cœur_. She would like advice, but is not sure that the+matter is not too delicate for communication. And yet even here we may+discriminate. When a woman has been seriously wronged by a man she no+longer oscillates, and the usual symptom is a broken bell wire. Here we+may take it that there is a love matter, but that the maiden is not so+much angry as perplexed, or grieved. But here she comes in person to+resolve our doubts.”++As he spoke there was a tap at the door, and the boy in buttons entered+to announce Miss Mary Sutherland, while the lady herself loomed behind+his small black figure like a full-sailed merchant-man behind a tiny+pilot boat. Sherlock Holmes welcomed her with the easy courtesy for+which he was remarkable, and, having closed the door and bowed her into+an armchair, he looked her over in the minute and yet abstracted+fashion which was peculiar to him.++“Do you not find,” he said, “that with your short sight it is a little+trying to do so much typewriting?”++“I did at first,” she answered, “but now I know where the letters are+without looking.” Then, suddenly realising the full purport of his+words, she gave a violent start and looked up, with fear and+astonishment upon her broad, good-humoured face. “You’ve heard about+me, Mr. Holmes,” she cried, “else how could you know all that?”++“Never mind,” said Holmes, laughing; “it is my business to know things.+Perhaps I have trained myself to see what others overlook. If not, why+should you come to consult me?”++“I came to you, sir, because I heard of you from Mrs. Etherege, whose+husband you found so easy when the police and everyone had given him up+for dead. Oh, Mr. Holmes, I wish you would do as much for me. I’m not+rich, but still I have a hundred a year in my own right, besides the+little that I make by the machine, and I would give it all to know what+has become of Mr. Hosmer Angel.”++“Why did you come away to consult me in such a hurry?” asked Sherlock+Holmes, with his finger-tips together and his eyes to the ceiling.++Again a startled look came over the somewhat vacuous face of Miss Mary+Sutherland. “Yes, I did bang out of the house,” she said, “for it made+me angry to see the easy way in which Mr. Windibank—that is, my+father—took it all. He would not go to the police, and he would not go+to you, and so at last, as he would do nothing and kept on saying that+there was no harm done, it made me mad, and I just on with my things+and came right away to you.”++“Your father,” said Holmes, “your stepfather, surely, since the name is+different.”++“Yes, my stepfather. I call him father, though it sounds funny, too,+for he is only five years and two months older than myself.”++“And your mother is alive?”++“Oh, yes, mother is alive and well. I wasn’t best pleased, Mr. Holmes,+when she married again so soon after father’s death, and a man who was+nearly fifteen years younger than herself. Father was a plumber in the+Tottenham Court Road, and he left a tidy business behind him, which+mother carried on with Mr. Hardy, the foreman; but when Mr. Windibank+came he made her sell the business, for he was very superior, being a+traveller in wines. They got £ 4700 for the goodwill and interest,+which wasn’t near as much as father could have got if he had been+alive.”++I had expected to see Sherlock Holmes impatient under this rambling and+inconsequential narrative, but, on the contrary, he had listened with+the greatest concentration of attention.++“Your own little income,” he asked, “does it come out of the business?”++“Oh, no, sir. It is quite separate and was left me by my uncle Ned in+Auckland. It is in New Zealand stock, paying 4½ per cent. Two thousand+five hundred pounds was the amount, but I can only touch the interest.”++“You interest me extremely,” said Holmes. “And since you draw so large+a sum as a hundred a year, with what you earn into the bargain, you no+doubt travel a little and indulge yourself in every way. I believe that+a single lady can get on very nicely upon an income of about £ 60.”++“I could do with much less than that, Mr. Holmes, but you understand+that as long as I live at home I don’t wish to be a burden to them, and+so they have the use of the money just while I am staying with them. Of+course, that is only just for the time. Mr. Windibank draws my interest+every quarter and pays it over to mother, and I find that I can do+pretty well with what I earn at typewriting. It brings me twopence a+sheet, and I can often do from fifteen to twenty sheets in a day.”++“You have made your position very clear to me,” said Holmes. “This is+my friend, Dr. Watson, before whom you can speak as freely as before+myself. Kindly tell us now all about your connection with Mr. Hosmer+Angel.”++A flush stole over Miss Sutherland’s face, and she picked nervously at+the fringe of her jacket. “I met him first at the gasfitters’ ball,”+she said. “They used to send father tickets when he was alive, and then+afterwards they remembered us, and sent them to mother. Mr. Windibank+did not wish us to go. He never did wish us to go anywhere. He would+get quite mad if I wanted so much as to join a Sunday-school treat. But+this time I was set on going, and I would go; for what right had he to+prevent? He said the folk were not fit for us to know, when all+father’s friends were to be there. And he said that I had nothing fit+to wear, when I had my purple plush that I had never so much as taken+out of the drawer. At last, when nothing else would do, he went off to+France upon the business of the firm, but we went, mother and I, with+Mr. Hardy, who used to be our foreman, and it was there I met Mr.+Hosmer Angel.”++“I suppose,” said Holmes, “that when Mr. Windibank came back from+France he was very annoyed at your having gone to the ball.”++“Oh, well, he was very good about it. He laughed, I remember, and+shrugged his shoulders, and said there was no use denying anything to a+woman, for she would have her way.”++“I see. Then at the gasfitters’ ball you met, as I understand, a+gentleman called Mr. Hosmer Angel.”++“Yes, sir. I met him that night, and he called next day to ask if we+had got home all safe, and after that we met him—that is to say, Mr.+Holmes, I met him twice for walks, but after that father came back+again, and Mr. Hosmer Angel could not come to the house any more.”++“No?”++“Well, you know father didn’t like anything of the sort. He wouldn’t+have any visitors if he could help it, and he used to say that a woman+should be happy in her own family circle. But then, as I used to say to+mother, a woman wants her own circle to begin with, and I had not got+mine yet.”++“But how about Mr. Hosmer Angel? Did he make no attempt to see you?”++“Well, father was going off to France again in a week, and Hosmer wrote+and said that it would be safer and better not to see each other until+he had gone. We could write in the meantime, and he used to write every+day. I took the letters in in the morning, so there was no need for+father to know.”++“Were you engaged to the gentleman at this time?”++“Oh, yes, Mr. Holmes. We were engaged after the first walk that we+took. Hosmer—Mr. Angel—was a cashier in an office in Leadenhall+Street—and—”++“What office?”++“That’s the worst of it, Mr. Holmes, I don’t know.”++“Where did he live, then?”++“He slept on the premises.”++“And you don’t know his address?”++“No—except that it was Leadenhall Street.”++“Where did you address your letters, then?”++“To the Leadenhall Street Post Office, to be left till called for. He+said that if they were sent to the office he would be chaffed by all+the other clerks about having letters from a lady, so I offered to+typewrite them, like he did his, but he wouldn’t have that, for he said+that when I wrote them they seemed to come from me, but when they were+typewritten he always felt that the machine had come between us. That+will just show you how fond he was of me, Mr. Holmes, and the little+things that he would think of.”++“It was most suggestive,” said Holmes. “It has long been an axiom of+mine that the little things are infinitely the most important. Can you+remember any other little things about Mr. Hosmer Angel?”++“He was a very shy man, Mr. Holmes. He would rather walk with me in the+evening than in the daylight, for he said that he hated to be+conspicuous. Very retiring and gentlemanly he was. Even his voice was+gentle. He’d had the quinsy and swollen glands when he was young, he+told me, and it had left him with a weak throat, and a hesitating,+whispering fashion of speech. He was always well dressed, very neat and+plain, but his eyes were weak, just as mine are, and he wore tinted+glasses against the glare.”++“Well, and what happened when Mr. Windibank, your stepfather, returned+to France?”++“Mr. Hosmer Angel came to the house again and proposed that we should+marry before father came back. He was in dreadful earnest and made me+swear, with my hands on the Testament, that whatever happened I would+always be true to him. Mother said he was quite right to make me swear,+and that it was a sign of his passion. Mother was all in his favour+from the first and was even fonder of him than I was. Then, when they+talked of marrying within the week, I began to ask about father; but+they both said never to mind about father, but just to tell him+afterwards, and mother said she would make it all right with him. I+didn’t quite like that, Mr. Holmes. It seemed funny that I should ask+his leave, as he was only a few years older than me; but I didn’t want+to do anything on the sly, so I wrote to father at Bordeaux, where the+company has its French offices, but the letter came back to me on the+very morning of the wedding.”++“It missed him, then?”++“Yes, sir; for he had started to England just before it arrived.”++“Ha! that was unfortunate. Your wedding was arranged, then, for the+Friday. Was it to be in church?”++“Yes, sir, but very quietly. It was to be at St. Saviour’s, near King’s+Cross, and we were to have breakfast afterwards at the St. Pancras+Hotel. Hosmer came for us in a hansom, but as there were two of us he+put us both into it and stepped himself into a four-wheeler, which+happened to be the only other cab in the street. We got to the church+first, and when the four-wheeler drove up we waited for him to step+out, but he never did, and when the cabman got down from the box and+looked there was no one there! The cabman said that he could not+imagine what had become of him, for he had seen him get in with his own+eyes. That was last Friday, Mr. Holmes, and I have never seen or heard+anything since then to throw any light upon what became of him.”++“It seems to me that you have been very shamefully treated,” said+Holmes.++“Oh, no, sir! He was too good and kind to leave me so. Why, all the+morning he was saying to me that, whatever happened, I was to be true;+and that even if something quite unforeseen occurred to separate us, I+was always to remember that I was pledged to him, and that he would+claim his pledge sooner or later. It seemed strange talk for a+wedding-morning, but what has happened since gives a meaning to it.”++“Most certainly it does. Your own opinion is, then, that some+unforeseen catastrophe has occurred to him?”++“Yes, sir. I believe that he foresaw some danger, or else he would not+have talked so. And then I think that what he foresaw happened.”++“But you have no notion as to what it could have been?”++“None.”++“One more question. How did your mother take the matter?”++“She was angry, and said that I was never to speak of the matter+again.”++“And your father? Did you tell him?”++“Yes; and he seemed to think, with me, that something had happened, and+that I should hear of Hosmer again. As he said, what interest could+anyone have in bringing me to the doors of the church, and then leaving+me? Now, if he had borrowed my money, or if he had married me and got+my money settled on him, there might be some reason, but Hosmer was+very independent about money and never would look at a shilling of+mine. And yet, what could have happened? And why could he not write?+Oh, it drives me half-mad to think of it, and I can’t sleep a wink at+night.” She pulled a little handkerchief out of her muff and began to+sob heavily into it.++“I shall glance into the case for you,” said Holmes, rising, “and I+have no doubt that we shall reach some definite result. Let the weight+of the matter rest upon me now, and do not let your mind dwell upon it+further. Above all, try to let Mr. Hosmer Angel vanish from your+memory, as he has done from your life.”++“Then you don’t think I’ll see him again?”++“I fear not.”++“Then what has happened to him?”++“You will leave that question in my hands. I should like an accurate+description of him and any letters of his which you can spare.”++“I advertised for him in last Saturday’s _Chronicle_,” said she. “Here+is the slip and here are four letters from him.”++“Thank you. And your address?”++“No. 31 Lyon Place, Camberwell.”++“Mr. Angel’s address you never had, I understand. Where is your+father’s place of business?”++“He travels for Westhouse & Marbank, the great claret importers of+Fenchurch Street.”++“Thank you. You have made your statement very clearly. You will leave+the papers here, and remember the advice which I have given you. Let+the whole incident be a sealed book, and do not allow it to affect your+life.”++“You are very kind, Mr. Holmes, but I cannot do that. I shall be true+to Hosmer. He shall find me ready when he comes back.”++For all the preposterous hat and the vacuous face, there was something+noble in the simple faith of our visitor which compelled our respect.+She laid her little bundle of papers upon the table and went her way,+with a promise to come again whenever she might be summoned.++Sherlock Holmes sat silent for a few minutes with his fingertips still+pressed together, his legs stretched out in front of him, and his gaze+directed upward to the ceiling. Then he took down from the rack the old+and oily clay pipe, which was to him as a counsellor, and, having lit+it, he leaned back in his chair, with the thick blue cloud-wreaths+spinning up from him, and a look of infinite languor in his face.++“Quite an interesting study, that maiden,” he observed. “I found her+more interesting than her little problem, which, by the way, is rather+a trite one. You will find parallel cases, if you consult my index, in+Andover in ’77, and there was something of the sort at The Hague last+year. Old as is the idea, however, there were one or two details which+were new to me. But the maiden herself was most instructive.”++“You appeared to read a good deal upon her which was quite invisible to+me,” I remarked.++“Not invisible but unnoticed, Watson. You did not know where to look,+and so you missed all that was important. I can never bring you to+realise the importance of sleeves, the suggestiveness of thumb-nails,+or the great issues that may hang from a boot-lace. Now, what did you+gather from that woman’s appearance? Describe it.”++“Well, she had a slate-coloured, broad-brimmed straw hat, with a+feather of a brickish red. Her jacket was black, with black beads sewn+upon it, and a fringe of little black jet ornaments. Her dress was+brown, rather darker than coffee colour, with a little purple plush at+the neck and sleeves. Her gloves were greyish and were worn through at+the right forefinger. Her boots I didn’t observe. She had small round,+hanging gold earrings, and a general air of being fairly well-to-do in+a vulgar, comfortable, easy-going way.”++Sherlock Holmes clapped his hands softly together and chuckled.++“’Pon my word, Watson, you are coming along wonderfully. You have+really done very well indeed. It is true that you have missed+everything of importance, but you have hit upon the method, and you+have a quick eye for colour. Never trust to general impressions, my+boy, but concentrate yourself upon details. My first glance is always+at a woman’s sleeve. In a man it is perhaps better first to take the+knee of the trouser. As you observe, this woman had plush upon her+sleeves, which is a most useful material for showing traces. The double+line a little above the wrist, where the typewritist presses against+the table, was beautifully defined. The sewing-machine, of the hand+type, leaves a similar mark, but only on the left arm, and on the side+of it farthest from the thumb, instead of being right across the+broadest part, as this was. I then glanced at her face, and, observing+the dint of a pince-nez at either side of her nose, I ventured a remark+upon short sight and typewriting, which seemed to surprise her.”++“It surprised me.”++“But, surely, it was obvious. I was then much surprised and interested+on glancing down to observe that, though the boots which she was+wearing were not unlike each other, they were really odd ones; the one+having a slightly decorated toe-cap, and the other a plain one. One was+buttoned only in the two lower buttons out of five, and the other at+the first, third, and fifth. Now, when you see that a young lady,+otherwise neatly dressed, has come away from home with odd boots,+half-buttoned, it is no great deduction to say that she came away in a+hurry.”++“And what else?” I asked, keenly interested, as I always was, by my+friend’s incisive reasoning.++“I noted, in passing, that she had written a note before leaving home+but after being fully dressed. You observed that her right glove was+torn at the forefinger, but you did not apparently see that both glove+and finger were stained with violet ink. She had written in a hurry and+dipped her pen too deep. It must have been this morning, or the mark+would not remain clear upon the finger. All this is amusing, though+rather elementary, but I must go back to business, Watson. Would you+mind reading me the advertised description of Mr. Hosmer Angel?”++I held the little printed slip to the light. “Missing,” it said, “on+the morning of the fourteenth, a gentleman named Hosmer Angel. About+five ft. seven in. in height; strongly built, sallow complexion, black+hair, a little bald in the centre, bushy, black side-whiskers and+moustache; tinted glasses, slight infirmity of speech. Was dressed,+when last seen, in black frock-coat faced with silk, black waistcoat,+gold Albert chain, and grey Harris tweed trousers, with brown gaiters+over elastic-sided boots. Known to have been employed in an office in+Leadenhall Street. Anybody bringing,” &c, &c.++“That will do,” said Holmes. “As to the letters,” he continued,+glancing over them, “they are very commonplace. Absolutely no clue in+them to Mr. Angel, save that he quotes Balzac once. There is one+remarkable point, however, which will no doubt strike you.”++“They are typewritten,” I remarked.++“Not only that, but the signature is typewritten. Look at the neat+little ‘Hosmer Angel’ at the bottom. There is a date, you see, but no+superscription except Leadenhall Street, which is rather vague. The+point about the signature is very suggestive—in fact, we may call it+conclusive.”++“Of what?”++“My dear fellow, is it possible you do not see how strongly it bears+upon the case?”++“I cannot say that I do unless it were that he wished to be able to+deny his signature if an action for breach of promise were instituted.”++“No, that was not the point. However, I shall write two letters, which+should settle the matter. One is to a firm in the City, the other is to+the young lady’s stepfather, Mr. Windibank, asking him whether he could+meet us here at six o’clock to-morrow evening. It is just as well that+we should do business with the male relatives. And now, Doctor, we can+do nothing until the answers to those letters come, so we may put our+little problem upon the shelf for the interim.”++I had had so many reasons to believe in my friend’s subtle powers of+reasoning and extraordinary energy in action that I felt that he must+have some solid grounds for the assured and easy demeanour with which+he treated the singular mystery which he had been called upon to+fathom. Once only had I known him to fail, in the case of the King of+Bohemia and of the Irene Adler photograph; but when I looked back to+the weird business of the Sign of Four, and the extraordinary+circumstances connected with the Study in Scarlet, I felt that it would+be a strange tangle indeed which he could not unravel.++I left him then, still puffing at his black clay pipe, with the+conviction that when I came again on the next evening I would find that+he held in his hands all the clues which would lead up to the identity+of the disappearing bridegroom of Miss Mary Sutherland.++A professional case of great gravity was engaging my own attention at+the time, and the whole of next day I was busy at the bedside of the+sufferer. It was not until close upon six o’clock that I found myself+free and was able to spring into a hansom and drive to Baker Street,+half afraid that I might be too late to assist at the _dénouement_ of+the little mystery. I found Sherlock Holmes alone, however, half+asleep, with his long, thin form curled up in the recesses of his+armchair. A formidable array of bottles and test-tubes, with the+pungent cleanly smell of hydrochloric acid, told me that he had spent+his day in the chemical work which was so dear to him.++“Well, have you solved it?” I asked as I entered.++“Yes. It was the bisulphate of baryta.”++“No, no, the mystery!” I cried.++“Oh, that! I thought of the salt that I have been working upon. There+was never any mystery in the matter, though, as I said yesterday, some+of the details are of interest. The only drawback is that there is no+law, I fear, that can touch the scoundrel.”++“Who was he, then, and what was his object in deserting Miss+Sutherland?”++The question was hardly out of my mouth, and Holmes had not yet opened+his lips to reply, when we heard a heavy footfall in the passage and a+tap at the door.++“This is the girl’s stepfather, Mr. James Windibank,” said Holmes. “He+has written to me to say that he would be here at six. Come in!”++The man who entered was a sturdy, middle-sized fellow, some thirty+years of age, clean-shaven, and sallow-skinned, with a bland,+insinuating manner, and a pair of wonderfully sharp and penetrating+grey eyes. He shot a questioning glance at each of us, placed his shiny+top-hat upon the sideboard, and with a slight bow sidled down into the+nearest chair.++“Good-evening, Mr. James Windibank,” said Holmes. “I think that this+typewritten letter is from you, in which you made an appointment with+me for six o’clock?”++“Yes, sir. I am afraid that I am a little late, but I am not quite my+own master, you know. I am sorry that Miss Sutherland has troubled you+about this little matter, for I think it is far better not to wash+linen of the sort in public. It was quite against my wishes that she+came, but she is a very excitable, impulsive girl, as you may have+noticed, and she is not easily controlled when she has made up her mind+on a point. Of course, I did not mind you so much, as you are not+connected with the official police, but it is not pleasant to have a+family misfortune like this noised abroad. Besides, it is a useless+expense, for how could you possibly find this Hosmer Angel?”++“On the contrary,” said Holmes quietly; “I have every reason to believe+that I will succeed in discovering Mr. Hosmer Angel.”++Mr. Windibank gave a violent start and dropped his gloves. “I am+delighted to hear it,” he said.++“It is a curious thing,” remarked Holmes, “that a typewriter has really+quite as much individuality as a man’s handwriting. Unless they are+quite new, no two of them write exactly alike. Some letters get more+worn than others, and some wear only on one side. Now, you remark in+this note of yours, Mr. Windibank, that in every case there is some+little slurring over of the ‘e,’ and a slight defect in the tail of the+‘r.’ There are fourteen other characteristics, but those are the more+obvious.”++“We do all our correspondence with this machine at the office, and no+doubt it is a little worn,” our visitor answered, glancing keenly at+Holmes with his bright little eyes.++“And now I will show you what is really a very interesting study, Mr.+Windibank,” Holmes continued. “I think of writing another little+monograph some of these days on the typewriter and its relation to+crime. It is a subject to which I have devoted some little attention. I+have here four letters which purport to come from the missing man. They+are all typewritten. In each case, not only are the ‘e’s’ slurred and+the ‘r’s’ tailless, but you will observe, if you care to use my+magnifying lens, that the fourteen other characteristics to which I+have alluded are there as well.”++Mr. Windibank sprang out of his chair and picked up his hat. “I cannot+waste time over this sort of fantastic talk, Mr. Holmes,” he said. “If+you can catch the man, catch him, and let me know when you have done+it.”++“Certainly,” said Holmes, stepping over and turning the key in the+door. “I let you know, then, that I have caught him!”++“What! where?” shouted Mr. Windibank, turning white to his lips and+glancing about him like a rat in a trap.++“Oh, it won’t do—really it won’t,” said Holmes suavely. “There is no+possible getting out of it, Mr. Windibank. It is quite too transparent,+and it was a very bad compliment when you said that it was impossible+for me to solve so simple a question. That’s right! Sit down and let us+talk it over.”++Our visitor collapsed into a chair, with a ghastly face and a glitter+of moisture on his brow. “It—it’s not actionable,” he stammered.++“I am very much afraid that it is not. But between ourselves,+Windibank, it was as cruel and selfish and heartless a trick in a petty+way as ever came before me. Now, let me just run over the course of+events, and you will contradict me if I go wrong.”++The man sat huddled up in his chair, with his head sunk upon his+breast, like one who is utterly crushed. Holmes stuck his feet up on+the corner of the mantelpiece and, leaning back with his hands in his+pockets, began talking, rather to himself, as it seemed, than to us.++“The man married a woman very much older than himself for her money,”+said he, “and he enjoyed the use of the money of the daughter as long+as she lived with them. It was a considerable sum, for people in their+position, and the loss of it would have made a serious difference. It+was worth an effort to preserve it. The daughter was of a good, amiable+disposition, but affectionate and warm-hearted in her ways, so that it+was evident that with her fair personal advantages, and her little+income, she would not be allowed to remain single long. Now her+marriage would mean, of course, the loss of a hundred a year, so what+does her stepfather do to prevent it? He takes the obvious course of+keeping her at home and forbidding her to seek the company of people of+her own age. But soon he found that that would not answer forever. She+became restive, insisted upon her rights, and finally announced her+positive intention of going to a certain ball. What does her clever+stepfather do then? He conceives an idea more creditable to his head+than to his heart. With the connivance and assistance of his wife he+disguised himself, covered those keen eyes with tinted glasses, masked+the face with a moustache and a pair of bushy whiskers, sunk that clear+voice into an insinuating whisper, and doubly secure on account of the+girl’s short sight, he appears as Mr. Hosmer Angel, and keeps off other+lovers by making love himself.”++“It was only a joke at first,” groaned our visitor. “We never thought+that she would have been so carried away.”++“Very likely not. However that may be, the young lady was very+decidedly carried away, and, having quite made up her mind that her+stepfather was in France, the suspicion of treachery never for an+instant entered her mind. She was flattered by the gentleman’s+attentions, and the effect was increased by the loudly expressed+admiration of her mother. Then Mr. Angel began to call, for it was+obvious that the matter should be pushed as far as it would go if a+real effect were to be produced. There were meetings, and an+engagement, which would finally secure the girl’s affections from+turning towards anyone else. But the deception could not be kept up+forever. These pretended journeys to France were rather cumbrous. The+thing to do was clearly to bring the business to an end in such a+dramatic manner that it would leave a permanent impression upon the+young lady’s mind and prevent her from looking upon any other suitor+for some time to come. Hence those vows of fidelity exacted upon a+Testament, and hence also the allusions to a possibility of something+happening on the very morning of the wedding. James Windibank wished+Miss Sutherland to be so bound to Hosmer Angel, and so uncertain as to+his fate, that for ten years to come, at any rate, she would not listen+to another man. As far as the church door he brought her, and then, as+he could go no farther, he conveniently vanished away by the old trick+of stepping in at one door of a four-wheeler and out at the other. I+think that was the chain of events, Mr. Windibank!”++Our visitor had recovered something of his assurance while Holmes had+been talking, and he rose from his chair now with a cold sneer upon his+pale face.++“It may be so, or it may not, Mr. Holmes,” said he, “but if you are so+very sharp you ought to be sharp enough to know that it is you who are+breaking the law now, and not me. I have done nothing actionable from+the first, but as long as you keep that door locked you lay yourself+open to an action for assault and illegal constraint.”++“The law cannot, as you say, touch you,” said Holmes, unlocking and+throwing open the door, “yet there never was a man who deserved+punishment more. If the young lady has a brother or a friend, he ought+to lay a whip across your shoulders. By Jove!” he continued, flushing+up at the sight of the bitter sneer upon the man’s face, “it is not+part of my duties to my client, but here’s a hunting crop handy, and I+think I shall just treat myself to—” He took two swift steps to the+whip, but before he could grasp it there was a wild clatter of steps+upon the stairs, the heavy hall door banged, and from the window we+could see Mr. James Windibank running at the top of his speed down the+road.++“There’s a cold-blooded scoundrel!” said Holmes, laughing, as he threw+himself down into his chair once more. “That fellow will rise from+crime to crime until he does something very bad, and ends on a gallows.+The case has, in some respects, been not entirely devoid of interest.”++“I cannot now entirely see all the steps of your reasoning,” I+remarked.++“Well, of course it was obvious from the first that this Mr. Hosmer+Angel must have some strong object for his curious conduct, and it was+equally clear that the only man who really profited by the incident, as+far as we could see, was the stepfather. Then the fact that the two men+were never together, but that the one always appeared when the other+was away, was suggestive. So were the tinted spectacles and the curious+voice, which both hinted at a disguise, as did the bushy whiskers. My+suspicions were all confirmed by his peculiar action in typewriting his+signature, which, of course, inferred that his handwriting was so+familiar to her that she would recognise even the smallest sample of+it. You see all these isolated facts, together with many minor ones,+all pointed in the same direction.”++“And how did you verify them?”++“Having once spotted my man, it was easy to get corroboration. I knew+the firm for which this man worked. Having taken the printed+description. I eliminated everything from it which could be the result+of a disguise—the whiskers, the glasses, the voice, and I sent it to+the firm, with a request that they would inform me whether it answered+to the description of any of their travellers. I had already noticed+the peculiarities of the typewriter, and I wrote to the man himself at+his business address asking him if he would come here. As I expected,+his reply was typewritten and revealed the same trivial but+characteristic defects. The same post brought me a letter from+Westhouse & Marbank, of Fenchurch Street, to say that the description+tallied in every respect with that of their employé, James Windibank.+_Voilà tout_!”++“And Miss Sutherland?”++“If I tell her she will not believe me. You may remember the old+Persian saying, ‘There is danger for him who taketh the tiger cub, and+danger also for whoso snatches a delusion from a woman.’ There is as+much sense in Hafiz as in Horace, and as much knowledge of the world.”++IV. THE BOSCOMBE VALLEY MYSTERY++We were seated at breakfast one morning, my wife and I, when the maid+brought in a telegram. It was from Sherlock Holmes and ran in this way:++“Have you a couple of days to spare? Have just been wired for from the+west of England in connection with Boscombe Valley tragedy. Shall be+glad if you will come with me. Air and scenery perfect. Leave+Paddington by the 11:15.”++“What do you say, dear?” said my wife, looking across at me. “Will you+go?”++“I really don’t know what to say. I have a fairly long list at+present.”++“Oh, Anstruther would do your work for you. You have been looking a+little pale lately. I think that the change would do you good, and you+are always so interested in Mr. Sherlock Holmes’ cases.”++“I should be ungrateful if I were not, seeing what I gained through one+of them,” I answered. “But if I am to go, I must pack at once, for I+have only half an hour.”++My experience of camp life in Afghanistan had at least had the effect+of making me a prompt and ready traveller. My wants were few and+simple, so that in less than the time stated I was in a cab with my+valise, rattling away to Paddington Station. Sherlock Holmes was pacing+up and down the platform, his tall, gaunt figure made even gaunter and+taller by his long grey travelling-cloak and close-fitting cloth cap.++“It is really very good of you to come, Watson,” said he. “It makes a+considerable difference to me, having someone with me on whom I can+thoroughly rely. Local aid is always either worthless or else biassed.+If you will keep the two corner seats I shall get the tickets.”++We had the carriage to ourselves save for an immense litter of papers+which Holmes had brought with him. Among these he rummaged and read,+with intervals of note-taking and of meditation, until we were past+Reading. Then he suddenly rolled them all into a gigantic ball and+tossed them up onto the rack.++“Have you heard anything of the case?” he asked.++“Not a word. I have not seen a paper for some days.”++“The London press has not had very full accounts. I have just been+looking through all the recent papers in order to master the+particulars. It seems, from what I gather, to be one of those simple+cases which are so extremely difficult.”++“That sounds a little paradoxical.”++“But it is profoundly true. Singularity is almost invariably a clue.+The more featureless and commonplace a crime is, the more difficult it+is to bring it home. In this case, however, they have established a+very serious case against the son of the murdered man.”++“It is a murder, then?”++“Well, it is conjectured to be so. I shall take nothing for granted+until I have the opportunity of looking personally into it. I will+explain the state of things to you, as far as I have been able to+understand it, in a very few words.++“Boscombe Valley is a country district not very far from Ross, in+Herefordshire. The largest landed proprietor in that part is a Mr. John+Turner, who made his money in Australia and returned some years ago to+the old country. One of the farms which he held, that of Hatherley, was+let to Mr. Charles McCarthy, who was also an ex-Australian. The men had+known each other in the colonies, so that it was not unnatural that+when they came to settle down they should do so as near each other as+possible. Turner was apparently the richer man, so McCarthy became his+tenant but still remained, it seems, upon terms of perfect equality, as+they were frequently together. McCarthy had one son, a lad of eighteen,+and Turner had an only daughter of the same age, but neither of them+had wives living. They appear to have avoided the society of the+neighbouring English families and to have led retired lives, though+both the McCarthys were fond of sport and were frequently seen at the+race-meetings of the neighbourhood. McCarthy kept two servants—a man+and a girl. Turner had a considerable household, some half-dozen at the+least. That is as much as I have been able to gather about the+families. Now for the facts.++“On June 3rd, that is, on Monday last, McCarthy left his house at+Hatherley about three in the afternoon and walked down to the Boscombe+Pool, which is a small lake formed by the spreading out of the stream+which runs down the Boscombe Valley. He had been out with his+serving-man in the morning at Ross, and he had told the man that he+must hurry, as he had an appointment of importance to keep at three.+From that appointment he never came back alive.++“From Hatherley Farmhouse to the Boscombe Pool is a quarter of a mile,+and two people saw him as he passed over this ground. One was an old+woman, whose name is not mentioned, and the other was William Crowder,+a game-keeper in the employ of Mr. Turner. Both these witnesses depose+that Mr. McCarthy was walking alone. The game-keeper adds that within a+few minutes of his seeing Mr. McCarthy pass he had seen his son, Mr.+James McCarthy, going the same way with a gun under his arm. To the+best of his belief, the father was actually in sight at the time, and+the son was following him. He thought no more of the matter until he+heard in the evening of the tragedy that had occurred.++“The two McCarthys were seen after the time when William Crowder, the+game-keeper, lost sight of them. The Boscombe Pool is thickly wooded+round, with just a fringe of grass and of reeds round the edge. A girl+of fourteen, Patience Moran, who is the daughter of the lodge-keeper of+the Boscombe Valley estate, was in one of the woods picking flowers.+She states that while she was there she saw, at the border of the wood+and close by the lake, Mr. McCarthy and his son, and that they appeared+to be having a violent quarrel. She heard Mr. McCarthy the elder using+very strong language to his son, and she saw the latter raise up his+hand as if to strike his father. She was so frightened by their+violence that she ran away and told her mother when she reached home+that she had left the two McCarthys quarrelling near Boscombe Pool, and+that she was afraid that they were going to fight. She had hardly said+the words when young Mr. McCarthy came running up to the lodge to say+that he had found his father dead in the wood, and to ask for the help+of the lodge-keeper. He was much excited, without either his gun or his+hat, and his right hand and sleeve were observed to be stained with+fresh blood. On following him they found the dead body stretched out+upon the grass beside the pool. The head had been beaten in by repeated+blows of some heavy and blunt weapon. The injuries were such as might+very well have been inflicted by the butt-end of his son’s gun, which+was found lying on the grass within a few paces of the body. Under+these circumstances the young man was instantly arrested, and a verdict+of ‘wilful murder’ having been returned at the inquest on Tuesday, he+was on Wednesday brought before the magistrates at Ross, who have+referred the case to the next Assizes. Those are the main facts of the+case as they came out before the coroner and the police-court.”++“I could hardly imagine a more damning case,” I remarked. “If ever+circumstantial evidence pointed to a criminal it does so here.”++“Circumstantial evidence is a very tricky thing,” answered Holmes+thoughtfully. “It may seem to point very straight to one thing, but if+you shift your own point of view a little, you may find it pointing in+an equally uncompromising manner to something entirely different. It+must be confessed, however, that the case looks exceedingly grave+against the young man, and it is very possible that he is indeed the+culprit. There are several people in the neighbourhood, however, and+among them Miss Turner, the daughter of the neighbouring landowner, who+believe in his innocence, and who have retained Lestrade, whom you may+recollect in connection with the Study in Scarlet, to work out the case+in his interest. Lestrade, being rather puzzled, has referred the case+to me, and hence it is that two middle-aged gentlemen are flying+westward at fifty miles an hour instead of quietly digesting their+breakfasts at home.”++“I am afraid,” said I, “that the facts are so obvious that you will+find little credit to be gained out of this case.”++“There is nothing more deceptive than an obvious fact,” he answered,+laughing. “Besides, we may chance to hit upon some other obvious facts+which may have been by no means obvious to Mr. Lestrade. You know me+too well to think that I am boasting when I say that I shall either+confirm or destroy his theory by means which he is quite incapable of+employing, or even of understanding. To take the first example to hand,+I very clearly perceive that in your bedroom the window is upon the+right-hand side, and yet I question whether Mr. Lestrade would have+noted even so self-evident a thing as that.”++“How on earth—”++“My dear fellow, I know you well. I know the military neatness which+characterises you. You shave every morning, and in this season you+shave by the sunlight; but since your shaving is less and less complete+as we get farther back on the left side, until it becomes positively+slovenly as we get round the angle of the jaw, it is surely very clear+that that side is less illuminated than the other. I could not imagine+a man of your habits looking at himself in an equal light and being+satisfied with such a result. I only quote this as a trivial example of+observation and inference. Therein lies my _métier_, and it is just+possible that it may be of some service in the investigation which lies+before us. There are one or two minor points which were brought out in+the inquest, and which are worth considering.”++“What are they?”++“It appears that his arrest did not take place at once, but after the+return to Hatherley Farm. On the inspector of constabulary informing+him that he was a prisoner, he remarked that he was not surprised to+hear it, and that it was no more than his deserts. This observation of+his had the natural effect of removing any traces of doubt which might+have remained in the minds of the coroner’s jury.”++“It was a confession,” I ejaculated.++“No, for it was followed by a protestation of innocence.”++“Coming on the top of such a damning series of events, it was at least+a most suspicious remark.”++“On the contrary,” said Holmes, “it is the brightest rift which I can+at present see in the clouds. However innocent he might be, he could+not be such an absolute imbecile as not to see that the circumstances+were very black against him. Had he appeared surprised at his own+arrest, or feigned indignation at it, I should have looked upon it as+highly suspicious, because such surprise or anger would not be natural+under the circumstances, and yet might appear to be the best policy to+a scheming man. His frank acceptance of the situation marks him as+either an innocent man, or else as a man of considerable self-restraint+and firmness. As to his remark about his deserts, it was also not+unnatural if you consider that he stood beside the dead body of his+father, and that there is no doubt that he had that very day so far+forgotten his filial duty as to bandy words with him, and even,+according to the little girl whose evidence is so important, to raise+his hand as if to strike him. The self-reproach and contrition which+are displayed in his remark appear to me to be the signs of a healthy+mind rather than of a guilty one.”++I shook my head. “Many men have been hanged on far slighter evidence,”+I remarked.++“So they have. And many men have been wrongfully hanged.”++“What is the young man’s own account of the matter?”++“It is, I am afraid, not very encouraging to his supporters, though+there are one or two points in it which are suggestive. You will find+it here, and may read it for yourself.”++He picked out from his bundle a copy of the local Herefordshire paper,+and having turned down the sheet he pointed out the paragraph in which+the unfortunate young man had given his own statement of what had+occurred. I settled myself down in the corner of the carriage and read+it very carefully. It ran in this way:++“Mr. James McCarthy, the only son of the deceased, was then called and+gave evidence as follows: ‘I had been away from home for three days at+Bristol, and had only just returned upon the morning of last Monday,+the 3rd. My father was absent from home at the time of my arrival, and+I was informed by the maid that he had driven over to Ross with John+Cobb, the groom. Shortly after my return I heard the wheels of his trap+in the yard, and, looking out of my window, I saw him get out and walk+rapidly out of the yard, though I was not aware in which direction he+was going. I then took my gun and strolled out in the direction of the+Boscombe Pool, with the intention of visiting the rabbit warren which+is upon the other side. On my way I saw William Crowder, the+game-keeper, as he had stated in his evidence; but he is mistaken in+thinking that I was following my father. I had no idea that he was in+front of me. When about a hundred yards from the pool I heard a cry of+“Cooee!” which was a usual signal between my father and myself. I then+hurried forward, and found him standing by the pool. He appeared to be+much surprised at seeing me and asked me rather roughly what I was+doing there. A conversation ensued which led to high words and almost+to blows, for my father was a man of a very violent temper. Seeing that+his passion was becoming ungovernable, I left him and returned towards+Hatherley Farm. I had not gone more than 150 yards, however, when I+heard a hideous outcry behind me, which caused me to run back again. I+found my father expiring upon the ground, with his head terribly+injured. I dropped my gun and held him in my arms, but he almost+instantly expired. I knelt beside him for some minutes, and then made+my way to Mr. Turner’s lodge-keeper, his house being the nearest, to+ask for assistance. I saw no one near my father when I returned, and I+have no idea how he came by his injuries. He was not a popular man,+being somewhat cold and forbidding in his manners, but he had, as far+as I know, no active enemies. I know nothing further of the matter.’++“The Coroner: Did your father make any statement to you before he died?++“Witness: He mumbled a few words, but I could only catch some allusion+to a rat.++“The Coroner: What did you understand by that?++“Witness: It conveyed no meaning to me. I thought that he was+delirious.++“The Coroner: What was the point upon which you and your father had+this final quarrel?++“Witness: I should prefer not to answer.++“The Coroner: I am afraid that I must press it.++“Witness: It is really impossible for me to tell you. I can assure you+that it has nothing to do with the sad tragedy which followed.++“The Coroner: That is for the court to decide. I need not point out to+you that your refusal to answer will prejudice your case considerably+in any future proceedings which may arise.++“Witness: I must still refuse.++“The Coroner: I understand that the cry of ‘Cooee’ was a common signal+between you and your father?++“Witness: It was.++“The Coroner: How was it, then, that he uttered it before he saw you,+and before he even knew that you had returned from Bristol?++“Witness (with considerable confusion): I do not know.++“A Juryman: Did you see nothing which aroused your suspicions when you+returned on hearing the cry and found your father fatally injured?++“Witness: Nothing definite.++“The Coroner: What do you mean?++“Witness: I was so disturbed and excited as I rushed out into the open,+that I could think of nothing except of my father. Yet I have a vague+impression that as I ran forward something lay upon the ground to the+left of me. It seemed to me to be something grey in colour, a coat of+some sort, or a plaid perhaps. When I rose from my father I looked+round for it, but it was gone.++“‘Do you mean that it disappeared before you went for help?’++“‘Yes, it was gone.’++“‘You cannot say what it was?’++“‘No, I had a feeling something was there.’++“‘How far from the body?’++“‘A dozen yards or so.’++“‘And how far from the edge of the wood?’++“‘About the same.’++“‘Then if it was removed it was while you were within a dozen yards of+it?’++“‘Yes, but with my back towards it.’++“This concluded the examination of the witness.”++“I see,” said I as I glanced down the column, “that the coroner in his+concluding remarks was rather severe upon young McCarthy. He calls+attention, and with reason, to the discrepancy about his father having+signalled to him before seeing him, also to his refusal to give details+of his conversation with his father, and his singular account of his+father’s dying words. They are all, as he remarks, very much against+the son.”++Holmes laughed softly to himself and stretched himself out upon the+cushioned seat. “Both you and the coroner have been at some pains,”+said he, “to single out the very strongest points in the young man’s+favour. Don’t you see that you alternately give him credit for having+too much imagination and too little? Too little, if he could not invent+a cause of quarrel which would give him the sympathy of the jury; too+much, if he evolved from his own inner consciousness anything so+_outré_ as a dying reference to a rat, and the incident of the+vanishing cloth. No, sir, I shall approach this case from the point of+view that what this young man says is true, and we shall see whither+that hypothesis will lead us. And now here is my pocket Petrarch, and+not another word shall I say of this case until we are on the scene of+action. We lunch at Swindon, and I see that we shall be there in twenty+minutes.”++It was nearly four o’clock when we at last, after passing through the+beautiful Stroud Valley, and over the broad gleaming Severn, found+ourselves at the pretty little country-town of Ross. A lean,+ferret-like man, furtive and sly-looking, was waiting for us upon the+platform. In spite of the light brown dustcoat and leather-leggings+which he wore in deference to his rustic surroundings, I had no+difficulty in recognising Lestrade, of Scotland Yard. With him we drove+to the Hereford Arms where a room had already been engaged for us.++“I have ordered a carriage,” said Lestrade as we sat over a cup of tea.+“I knew your energetic nature, and that you would not be happy until+you had been on the scene of the crime.”++“It was very nice and complimentary of you,” Holmes answered. “It is+entirely a question of barometric pressure.”++Lestrade looked startled. “I do not quite follow,” he said.++“How is the glass? Twenty-nine, I see. No wind, and not a cloud in the+sky. I have a caseful of cigarettes here which need smoking, and the+sofa is very much superior to the usual country hotel abomination. I do+not think that it is probable that I shall use the carriage to-night.”++Lestrade laughed indulgently. “You have, no doubt, already formed your+conclusions from the newspapers,” he said. “The case is as plain as a+pikestaff, and the more one goes into it the plainer it becomes. Still,+of course, one can’t refuse a lady, and such a very positive one, too.+She has heard of you, and would have your opinion, though I repeatedly+told her that there was nothing which you could do which I had not+already done. Why, bless my soul! here is her carriage at the door.”++He had hardly spoken before there rushed into the room one of the most+lovely young women that I have ever seen in my life. Her violet eyes+shining, her lips parted, a pink flush upon her cheeks, all thought of+her natural reserve lost in her overpowering excitement and concern.++“Oh, Mr. Sherlock Holmes!” she cried, glancing from one to the other of+us, and finally, with a woman’s quick intuition, fastening upon my+companion, “I am so glad that you have come. I have driven down to tell+you so. I know that James didn’t do it. I know it, and I want you to+start upon your work knowing it, too. Never let yourself doubt upon+that point. We have known each other since we were little children, and+I know his faults as no one else does; but he is too tender-hearted to+hurt a fly. Such a charge is absurd to anyone who really knows him.”++“I hope we may clear him, Miss Turner,” said Sherlock Holmes. “You may+rely upon my doing all that I can.”++“But you have read the evidence. You have formed some conclusion? Do+you not see some loophole, some flaw? Do you not yourself think that he+is innocent?”++“I think that it is very probable.”++“There, now!” she cried, throwing back her head and looking defiantly+at Lestrade. “You hear! He gives me hopes.”++Lestrade shrugged his shoulders. “I am afraid that my colleague has+been a little quick in forming his conclusions,” he said.++“But he is right. Oh! I know that he is right. James never did it. And+about his quarrel with his father, I am sure that the reason why he+would not speak about it to the coroner was because I was concerned in+it.”++“In what way?” asked Holmes.++“It is no time for me to hide anything. James and his father had many+disagreements about me. Mr. McCarthy was very anxious that there should+be a marriage between us. James and I have always loved each other as+brother and sister; but of course he is young and has seen very little+of life yet, and—and—well, he naturally did not wish to do anything+like that yet. So there were quarrels, and this, I am sure, was one of+them.”++“And your father?” asked Holmes. “Was he in favour of such a union?”++“No, he was averse to it also. No one but Mr. McCarthy was in favour of+it.” A quick blush passed over her fresh young face as Holmes shot one+of his keen, questioning glances at her.++“Thank you for this information,” said he. “May I see your father if I+call to-morrow?”++“I am afraid the doctor won’t allow it.”++“The doctor?”++“Yes, have you not heard? Poor father has never been strong for years+back, but this has broken him down completely. He has taken to his bed,+and Dr. Willows says that he is a wreck and that his nervous system is+shattered. Mr. McCarthy was the only man alive who had known dad in the+old days in Victoria.”++“Ha! In Victoria! That is important.”++“Yes, at the mines.”++“Quite so; at the gold-mines, where, as I understand, Mr. Turner made+his money.”++“Yes, certainly.”++“Thank you, Miss Turner. You have been of material assistance to me.”++“You will tell me if you have any news to-morrow. No doubt you will go+to the prison to see James. Oh, if you do, Mr. Holmes, do tell him that+I know him to be innocent.”++“I will, Miss Turner.”++“I must go home now, for dad is very ill, and he misses me so if I+leave him. Good-bye, and God help you in your undertaking.” She hurried+from the room as impulsively as she had entered, and we heard the+wheels of her carriage rattle off down the street.++“I am ashamed of you, Holmes,” said Lestrade with dignity after a few+minutes’ silence. “Why should you raise up hopes which you are bound to+disappoint? I am not over-tender of heart, but I call it cruel.”++“I think that I see my way to clearing James McCarthy,” said Holmes.+“Have you an order to see him in prison?”++“Yes, but only for you and me.”++“Then I shall reconsider my resolution about going out. We have still+time to take a train to Hereford and see him to-night?”++“Ample.”++“Then let us do so. Watson, I fear that you will find it very slow, but+I shall only be away a couple of hours.”++I walked down to the station with them, and then wandered through the+streets of the little town, finally returning to the hotel, where I lay+upon the sofa and tried to interest myself in a yellow-backed novel.+The puny plot of the story was so thin, however, when compared to the+deep mystery through which we were groping, and I found my attention+wander so continually from the action to the fact, that I at last flung+it across the room and gave myself up entirely to a consideration of+the events of the day. Supposing that this unhappy young man’s story+were absolutely true, then what hellish thing, what absolutely+unforeseen and extraordinary calamity could have occurred between the+time when he parted from his father, and the moment when, drawn back by+his screams, he rushed into the glade? It was something terrible and+deadly. What could it be? Might not the nature of the injuries reveal+something to my medical instincts? I rang the bell and called for the+weekly county paper, which contained a verbatim account of the inquest.+In the surgeon’s deposition it was stated that the posterior third of+the left parietal bone and the left half of the occipital bone had been+shattered by a heavy blow from a blunt weapon. I marked the spot upon+my own head. Clearly such a blow must have been struck from behind.+That was to some extent in favour of the accused, as when seen+quarrelling he was face to face with his father. Still, it did not go+for very much, for the older man might have turned his back before the+blow fell. Still, it might be worth while to call Holmes’ attention to+it. Then there was the peculiar dying reference to a rat. What could+that mean? It could not be delirium. A man dying from a sudden blow+does not commonly become delirious. No, it was more likely to be an+attempt to explain how he met his fate. But what could it indicate? I+cudgelled my brains to find some possible explanation. And then the+incident of the grey cloth seen by young McCarthy. If that were true+the murderer must have dropped some part of his dress, presumably his+overcoat, in his flight, and must have had the hardihood to return and+to carry it away at the instant when the son was kneeling with his back+turned not a dozen paces off. What a tissue of mysteries and+improbabilities the whole thing was! I did not wonder at Lestrade’s+opinion, and yet I had so much faith in Sherlock Holmes’ insight that I+could not lose hope as long as every fresh fact seemed to strengthen+his conviction of young McCarthy’s innocence.++It was late before Sherlock Holmes returned. He came back alone, for+Lestrade was staying in lodgings in the town.++“The glass still keeps very high,” he remarked as he sat down. “It is+of importance that it should not rain before we are able to go over the+ground. On the other hand, a man should be at his very best and keenest+for such nice work as that, and I did not wish to do it when fagged by+a long journey. I have seen young McCarthy.”++“And what did you learn from him?”++“Nothing.”++“Could he throw no light?”++“None at all. I was inclined to think at one time that he knew who had+done it and was screening him or her, but I am convinced now that he is+as puzzled as everyone else. He is not a very quick-witted youth,+though comely to look at and, I should think, sound at heart.”++“I cannot admire his taste,” I remarked, “if it is indeed a fact that+he was averse to a marriage with so charming a young lady as this Miss+Turner.”++“Ah, thereby hangs a rather painful tale. This fellow is madly,+insanely, in love with her, but some two years ago, when he was only a+lad, and before he really knew her, for she had been away five years at+a boarding-school, what does the idiot do but get into the clutches of+a barmaid in Bristol and marry her at a registry office? No one knows a+word of the matter, but you can imagine how maddening it must be to him+to be upbraided for not doing what he would give his very eyes to do,+but what he knows to be absolutely impossible. It was sheer frenzy of+this sort which made him throw his hands up into the air when his+father, at their last interview, was goading him on to propose to Miss+Turner. On the other hand, he had no means of supporting himself, and+his father, who was by all accounts a very hard man, would have thrown+him over utterly had he known the truth. It was with his barmaid wife+that he had spent the last three days in Bristol, and his father did+not know where he was. Mark that point. It is of importance. Good has+come out of evil, however, for the barmaid, finding from the papers+that he is in serious trouble and likely to be hanged, has thrown him+over utterly and has written to him to say that she has a husband+already in the Bermuda Dockyard, so that there is really no tie between+them. I think that that bit of news has consoled young McCarthy for all+that he has suffered.”++“But if he is innocent, who has done it?”++“Ah! who? I would call your attention very particularly to two points.+One is that the murdered man had an appointment with someone at the+pool, and that the someone could not have been his son, for his son was+away, and he did not know when he would return. The second is that the+murdered man was heard to cry ‘Cooee!’ before he knew that his son had+returned. Those are the crucial points upon which the case depends. And+now let us talk about George Meredith, if you please, and we shall+leave all minor matters until to-morrow.”++There was no rain, as Holmes had foretold, and the morning broke bright+and cloudless. At nine o’clock Lestrade called for us with the+carriage, and we set off for Hatherley Farm and the Boscombe Pool.++“There is serious news this morning,” Lestrade observed. “It is said+that Mr. Turner, of the Hall, is so ill that his life is despaired of.”++“An elderly man, I presume?” said Holmes.++“About sixty; but his constitution has been shattered by his life+abroad, and he has been in failing health for some time. This business+has had a very bad effect upon him. He was an old friend of McCarthy’s,+and, I may add, a great benefactor to him, for I have learned that he+gave him Hatherley Farm rent free.”++“Indeed! That is interesting,” said Holmes.++“Oh, yes! In a hundred other ways he has helped him. Everybody about+here speaks of his kindness to him.”++“Really! Does it not strike you as a little singular that this+McCarthy, who appears to have had little of his own, and to have been+under such obligations to Turner, should still talk of marrying his son+to Turner’s daughter, who is, presumably, heiress to the estate, and+that in such a very cocksure manner, as if it were merely a case of a+proposal and all else would follow? It is the more strange, since we+know that Turner himself was averse to the idea. The daughter told us+as much. Do you not deduce something from that?”++“We have got to the deductions and the inferences,” said Lestrade,+winking at me. “I find it hard enough to tackle facts, Holmes, without+flying away after theories and fancies.”++“You are right,” said Holmes demurely; “you do find it very hard to+tackle the facts.”++“Anyhow, I have grasped one fact which you seem to find it difficult to+get hold of,” replied Lestrade with some warmth.++“And that is—”++“That McCarthy senior met his death from McCarthy junior and that all+theories to the contrary are the merest moonshine.”++“Well, moonshine is a brighter thing than fog,” said Holmes, laughing.+“But I am very much mistaken if this is not Hatherley Farm upon the+left.”++“Yes, that is it.” It was a widespread, comfortable-looking building,+two-storied, slate-roofed, with great yellow blotches of lichen upon+the grey walls. The drawn blinds and the smokeless chimneys, however,+gave it a stricken look, as though the weight of this horror still lay+heavy upon it. We called at the door, when the maid, at Holmes’+request, showed us the boots which her master wore at the time of his+death, and also a pair of the son’s, though not the pair which he had+then had. Having measured these very carefully from seven or eight+different points, Holmes desired to be led to the court-yard, from+which we all followed the winding track which led to Boscombe Pool.++Sherlock Holmes was transformed when he was hot upon such a scent as+this. Men who had only known the quiet thinker and logician of Baker+Street would have failed to recognise him. His face flushed and+darkened. His brows were drawn into two hard black lines, while his+eyes shone out from beneath them with a steely glitter. His face was+bent downward, his shoulders bowed, his lips compressed, and the veins+stood out like whipcord in his long, sinewy neck. His nostrils seemed+to dilate with a purely animal lust for the chase, and his mind was so+absolutely concentrated upon the matter before him that a question or+remark fell unheeded upon his ears, or, at the most, only provoked a+quick, impatient snarl in reply. Swiftly and silently he made his way+along the track which ran through the meadows, and so by way of the+woods to the Boscombe Pool. It was damp, marshy ground, as is all that+district, and there were marks of many feet, both upon the path and+amid the short grass which bounded it on either side. Sometimes Holmes+would hurry on, sometimes stop dead, and once he made quite a little+detour into the meadow. Lestrade and I walked behind him, the detective+indifferent and contemptuous, while I watched my friend with the+interest which sprang from the conviction that every one of his actions+was directed towards a definite end.++The Boscombe Pool, which is a little reed-girt sheet of water some+fifty yards across, is situated at the boundary between the Hatherley+Farm and the private park of the wealthy Mr. Turner. Above the woods+which lined it upon the farther side we could see the red, jutting+pinnacles which marked the site of the rich landowner’s dwelling. On+the Hatherley side of the pool the woods grew very thick, and there was+a narrow belt of sodden grass twenty paces across between the edge of+the trees and the reeds which lined the lake. Lestrade showed us the+exact spot at which the body had been found, and, indeed, so moist was+the ground, that I could plainly see the traces which had been left by+the fall of the stricken man. To Holmes, as I could see by his eager+face and peering eyes, very many other things were to be read upon the+trampled grass. He ran round, like a dog who is picking up a scent, and+then turned upon my companion.++“What did you go into the pool for?” he asked.++“I fished about with a rake. I thought there might be some weapon or+other trace. But how on earth—”++“Oh, tut, tut! I have no time! That left foot of yours with its inward+twist is all over the place. A mole could trace it, and there it+vanishes among the reeds. Oh, how simple it would all have been had I+been here before they came like a herd of buffalo and wallowed all over+it. Here is where the party with the lodge-keeper came, and they have+covered all tracks for six or eight feet round the body. But here are+three separate tracks of the same feet.” He drew out a lens and lay+down upon his waterproof to have a better view, talking all the time+rather to himself than to us. “These are young McCarthy’s feet. Twice+he was walking, and once he ran swiftly, so that the soles are deeply+marked and the heels hardly visible. That bears out his story. He ran+when he saw his father on the ground. Then here are the father’s feet+as he paced up and down. What is this, then? It is the butt-end of the+gun as the son stood listening. And this? Ha, ha! What have we here?+Tiptoes! tiptoes! Square, too, quite unusual boots! They come, they go,+they come again—of course that was for the cloak. Now where did they+come from?” He ran up and down, sometimes losing, sometimes finding the+track until we were well within the edge of the wood and under the+shadow of a great beech, the largest tree in the neighbourhood. Holmes+traced his way to the farther side of this and lay down once more upon+his face with a little cry of satisfaction. For a long time he remained+there, turning over the leaves and dried sticks, gathering up what+seemed to me to be dust into an envelope and examining with his lens+not only the ground but even the bark of the tree as far as he could+reach. A jagged stone was lying among the moss, and this also he+carefully examined and retained. Then he followed a pathway through the+wood until he came to the high road, where all traces were lost.++“It has been a case of considerable interest,” he remarked, returning+to his natural manner. “I fancy that this grey house on the right must+be the lodge. I think that I will go in and have a word with Moran, and+perhaps write a little note. Having done that, we may drive back to our+luncheon. You may walk to the cab, and I shall be with you presently.”++It was about ten minutes before we regained our cab and drove back into+Ross, Holmes still carrying with him the stone which he had picked up+in the wood.++“This may interest you, Lestrade,” he remarked, holding it out. “The+murder was done with it.”++“I see no marks.”++“There are none.”++“How do you know, then?”++“The grass was growing under it. It had only lain there a few days.+There was no sign of a place whence it had been taken. It corresponds+with the injuries. There is no sign of any other weapon.”++“And the murderer?”++“Is a tall man, left-handed, limps with the right leg, wears+thick-soled shooting-boots and a grey cloak, smokes Indian cigars, uses+a cigar-holder, and carries a blunt pen-knife in his pocket. There are+several other indications, but these may be enough to aid us in our+search.”++Lestrade laughed. “I am afraid that I am still a sceptic,” he said.+“Theories are all very well, but we have to deal with a hard-headed+British jury.”++“_Nous verrons_,” answered Holmes calmly. “You work your own method,+and I shall work mine. I shall be busy this afternoon, and shall+probably return to London by the evening train.”++“And leave your case unfinished?”++“No, finished.”++“But the mystery?”++“It is solved.”++“Who was the criminal, then?”++“The gentleman I describe.”++“But who is he?”++“Surely it would not be difficult to find out. This is not such a+populous neighbourhood.”++Lestrade shrugged his shoulders. “I am a practical man,” he said, “and+I really cannot undertake to go about the country looking for a+left-handed gentleman with a game leg. I should become the+laughing-stock of Scotland Yard.”++“All right,” said Holmes quietly. “I have given you the chance. Here+are your lodgings. Good-bye. I shall drop you a line before I leave.”++Having left Lestrade at his rooms, we drove to our hotel, where we+found lunch upon the table. Holmes was silent and buried in thought+with a pained expression upon his face, as one who finds himself in a+perplexing position.++“Look here, Watson,” he said when the cloth was cleared “just sit down+in this chair and let me preach to you for a little. I don’t know quite+what to do, and I should value your advice. Light a cigar and let me+expound.”++ “Pray do so.”++“Well, now, in considering this case there are two points about young+McCarthy’s narrative which struck us both instantly, although they+impressed me in his favour and you against him. One was the fact that+his father should, according to his account, cry ‘Cooee!’ before seeing+him. The other was his singular dying reference to a rat. He mumbled+several words, you understand, but that was all that caught the son’s+ear. Now from this double point our research must commence, and we will+begin it by presuming that what the lad says is absolutely true.”++“What of this ‘Cooee!’ then?”++“Well, obviously it could not have been meant for the son. The son, as+far as he knew, was in Bristol. It was mere chance that he was within+earshot. The ‘Cooee!’ was meant to attract the attention of whoever it+was that he had the appointment with. But ‘Cooee’ is a distinctly+Australian cry, and one which is used between Australians. There is a+strong presumption that the person whom McCarthy expected to meet him+at Boscombe Pool was someone who had been in Australia.”++“What of the rat, then?”++Sherlock Holmes took a folded paper from his pocket and flattened it+out on the table. “This is a map of the Colony of Victoria,” he said.+“I wired to Bristol for it last night.” He put his hand over part of+the map. “What do you read?”++“ARAT,” I read.++“And now?” He raised his hand.++“BALLARAT.”++“Quite so. That was the word the man uttered, and of which his son only+caught the last two syllables. He was trying to utter the name of his+murderer. So and so, of Ballarat.”++“It is wonderful!” I exclaimed.++“It is obvious. And now, you see, I had narrowed the field down+considerably. The possession of a grey garment was a third point which,+granting the son’s statement to be correct, was a certainty. We have+come now out of mere vagueness to the definite conception of an+Australian from Ballarat with a grey cloak.”++“Certainly.”++“And one who was at home in the district, for the pool can only be+approached by the farm or by the estate, where strangers could hardly+wander.”++“Quite so.”++“Then comes our expedition of to-day. By an examination of the ground I+gained the trifling details which I gave to that imbecile Lestrade, as+to the personality of the criminal.”++“But how did you gain them?”++“You know my method. It is founded upon the observation of trifles.”++“His height I know that you might roughly judge from the length of his+stride. His boots, too, might be told from their traces.”++“Yes, they were peculiar boots.”++“But his lameness?”++“The impression of his right foot was always less distinct than his+left. He put less weight upon it. Why? Because he limped—he was lame.”++“But his left-handedness.”++“You were yourself struck by the nature of the injury as recorded by+the surgeon at the inquest. The blow was struck from immediately+behind, and yet was upon the left side. Now, how can that be unless it+were by a left-handed man? He had stood behind that tree during the+interview between the father and son. He had even smoked there. I found+the ash of a cigar, which my special knowledge of tobacco ashes enables+me to pronounce as an Indian cigar. I have, as you know, devoted some+attention to this, and written a little monograph on the ashes of 140+different varieties of pipe, cigar, and cigarette tobacco. Having found+the ash, I then looked round and discovered the stump among the moss+where he had tossed it. It was an Indian cigar, of the variety which+are rolled in Rotterdam.”++“And the cigar-holder?”++“I could see that the end had not been in his mouth. Therefore he used+a holder. The tip had been cut off, not bitten off, but the cut was not+a clean one, so I deduced a blunt pen-knife.”++“Holmes,” I said, “you have drawn a net round this man from which he+cannot escape, and you have saved an innocent human life as truly as if+you had cut the cord which was hanging him. I see the direction in+which all this points. The culprit is—”++“Mr. John Turner,” cried the hotel waiter, opening the door of our+sitting-room, and ushering in a visitor.++The man who entered was a strange and impressive figure. His slow,+limping step and bowed shoulders gave the appearance of decrepitude,+and yet his hard, deep-lined, craggy features, and his enormous limbs+showed that he was possessed of unusual strength of body and of+character. His tangled beard, grizzled hair, and outstanding, drooping+eyebrows combined to give an air of dignity and power to his+appearance, but his face was of an ashen white, while his lips and the+corners of his nostrils were tinged with a shade of blue. It was clear+to me at a glance that he was in the grip of some deadly and chronic+disease.++“Pray sit down on the sofa,” said Holmes gently. “You had my note?”++“Yes, the lodge-keeper brought it up. You said that you wished to see+me here to avoid scandal.”++“I thought people would talk if I went to the Hall.”++“And why did you wish to see me?” He looked across at my companion with+despair in his weary eyes, as though his question was already answered.++“Yes,” said Holmes, answering the look rather than the words. “It is+so. I know all about McCarthy.”++The old man sank his face in his hands. “God help me!” he cried. “But I+would not have let the young man come to harm. I give you my word that+I would have spoken out if it went against him at the Assizes.”++“I am glad to hear you say so,” said Holmes gravely.++“I would have spoken now had it not been for my dear girl. It would+break her heart—it will break her heart when she hears that I am+arrested.”++“It may not come to that,” said Holmes.++“What?”++“I am no official agent. I understand that it was your daughter who+required my presence here, and I am acting in her interests. Young+McCarthy must be got off, however.”++“I am a dying man,” said old Turner. “I have had diabetes for years. My+doctor says it is a question whether I shall live a month. Yet I would+rather die under my own roof than in a gaol.”++Holmes rose and sat down at the table with his pen in his hand and a+bundle of paper before him. “Just tell us the truth,” he said. “I shall+jot down the facts. You will sign it, and Watson here can witness it.+Then I could produce your confession at the last extremity to save+young McCarthy. I promise you that I shall not use it unless it is+absolutely needed.”++“It’s as well,” said the old man; “it’s a question whether I shall live+to the Assizes, so it matters little to me, but I should wish to spare+Alice the shock. And now I will make the thing clear to you; it has+been a long time in the acting, but will not take me long to tell.++“You didn’t know this dead man, McCarthy. He was a devil incarnate. I+tell you that. God keep you out of the clutches of such a man as he.+His grip has been upon me these twenty years, and he has blasted my+life. I’ll tell you first how I came to be in his power.++“It was in the early ’60’s at the diggings. I was a young chap then,+hot-blooded and reckless, ready to turn my hand at anything; I got+among bad companions, took to drink, had no luck with my claim, took to+the bush, and in a word became what you would call over here a highway+robber. There were six of us, and we had a wild, free life of it,+sticking up a station from time to time, or stopping the wagons on the+road to the diggings. Black Jack of Ballarat was the name I went under,+and our party is still remembered in the colony as the Ballarat Gang.++“One day a gold convoy came down from Ballarat to Melbourne, and we lay+in wait for it and attacked it. There were six troopers and six of us,+so it was a close thing, but we emptied four of their saddles at the+first volley. Three of our boys were killed, however, before we got the+swag. I put my pistol to the head of the wagon-driver, who was this+very man McCarthy. I wish to the Lord that I had shot him then, but I+spared him, though I saw his wicked little eyes fixed on my face, as+though to remember every feature. We got away with the gold, became+wealthy men, and made our way over to England without being suspected.+There I parted from my old pals and determined to settle down to a+quiet and respectable life. I bought this estate, which chanced to be+in the market, and I set myself to do a little good with my money, to+make up for the way in which I had earned it. I married, too, and+though my wife died young she left me my dear little Alice. Even when+she was just a baby her wee hand seemed to lead me down the right path+as nothing else had ever done. In a word, I turned over a new leaf and+did my best to make up for the past. All was going well when McCarthy+laid his grip upon me.++“I had gone up to town about an investment, and I met him in Regent+Street with hardly a coat to his back or a boot to his foot.++“‘Here we are, Jack,’ says he, touching me on the arm; ‘we’ll be as+good as a family to you. There’s two of us, me and my son, and you can+have the keeping of us. If you don’t—it’s a fine, law-abiding country+is England, and there’s always a policeman within hail.’++“Well, down they came to the west country, there was no shaking them+off, and there they have lived rent free on my best land ever since.+There was no rest for me, no peace, no forgetfulness; turn where I+would, there was his cunning, grinning face at my elbow. It grew worse+as Alice grew up, for he soon saw I was more afraid of her knowing my+past than of the police. Whatever he wanted he must have, and whatever+it was I gave him without question, land, money, houses, until at last+he asked a thing which I could not give. He asked for Alice.++“His son, you see, had grown up, and so had my girl, and as I was known+to be in weak health, it seemed a fine stroke to him that his lad+should step into the whole property. But there I was firm. I would not+have his cursed stock mixed with mine; not that I had any dislike to+the lad, but his blood was in him, and that was enough. I stood firm.+McCarthy threatened. I braved him to do his worst. We were to meet at+the pool midway between our houses to talk it over.++“When I went down there I found him talking with his son, so I smoked a+cigar and waited behind a tree until he should be alone. But as I+listened to his talk all that was black and bitter in me seemed to come+uppermost. He was urging his son to marry my daughter with as little+regard for what she might think as if she were a slut from off the+streets. It drove me mad to think that I and all that I held most dear+should be in the power of such a man as this. Could I not snap the+bond? I was already a dying and a desperate man. Though clear of mind+and fairly strong of limb, I knew that my own fate was sealed. But my+memory and my girl! Both could be saved if I could but silence that+foul tongue. I did it, Mr. Holmes. I would do it again. Deeply as I+have sinned, I have led a life of martyrdom to atone for it. But that+my girl should be entangled in the same meshes which held me was more+than I could suffer. I struck him down with no more compunction than if+he had been some foul and venomous beast. His cry brought back his son;+but I had gained the cover of the wood, though I was forced to go back+to fetch the cloak which I had dropped in my flight. That is the true+story, gentlemen, of all that occurred.”++“Well, it is not for me to judge you,” said Holmes as the old man+signed the statement which had been drawn out. “I pray that we may+never be exposed to such a temptation.”++“I pray not, sir. And what do you intend to do?”++“In view of your health, nothing. You are yourself aware that you will+soon have to answer for your deed at a higher court than the Assizes. I+will keep your confession, and if McCarthy is condemned I shall be+forced to use it. If not, it shall never be seen by mortal eye; and+your secret, whether you be alive or dead, shall be safe with us.”++“Farewell, then,” said the old man solemnly. “Your own deathbeds, when+they come, will be the easier for the thought of the peace which you+have given to mine.” Tottering and shaking in all his giant frame, he+stumbled slowly from the room.++“God help us!” said Holmes after a long silence. “Why does fate play+such tricks with poor, helpless worms? I never hear of such a case as+this that I do not think of Baxter’s words, and say, ‘There, but for+the grace of God, goes Sherlock Holmes.’”++James McCarthy was acquitted at the Assizes on the strength of a number+of objections which had been drawn out by Holmes and submitted to the+defending counsel. Old Turner lived for seven months after our+interview, but he is now dead; and there is every prospect that the son+and daughter may come to live happily together in ignorance of the+black cloud which rests upon their past.diff --git a/admin/tests/eval/corpus/distractor-gutenberg-walden.md b/admin/tests/eval/corpus/distractor-gutenberg-walden.mdnew file mode 100644index 00000000..8ffb543a--- /dev/null+++ b/admin/tests/eval/corpus/distractor-gutenberg-walden.md@@ -0,0 +1,2410 @@+# Walden (excerpt), Henry David Thoreau++Distractor document for the #1341 off-topic eval suite. Public domain text from Project Gutenberg (ebook #205), boilerplate removed.++Where I Lived, and What I Lived For++At a certain season of our life we are accustomed to consider every+spot as the possible site of a house. I have thus surveyed the country+on every side within a dozen miles of where I live. In imagination I+have bought all the farms in succession, for all were to be bought, and+I knew their price. I walked over each farmer’s premises, tasted his+wild apples, discoursed on husbandry with him, took his farm at his+price, at any price, mortgaging it to him in my mind; even put a higher+price on it,—took everything but a deed of it,—took his word for his+deed, for I dearly love to talk,—cultivated it, and him too to some+extent, I trust, and withdrew when I had enjoyed it long enough,+leaving him to carry it on. This experience entitled me to be regarded+as a sort of real-estate broker by my friends. Wherever I sat, there I+might live, and the landscape radiated from me accordingly. What is a+house but a _sedes_, a seat?—better if a country seat. I discovered+many a site for a house not likely to be soon improved, which some+might have thought too far from the village, but to my eyes the village+was too far from it. Well, there I might live, I said; and there I did+live, for an hour, a summer and a winter life; saw how I could let the+years run off, buffet the winter through, and see the spring come in.+The future inhabitants of this region, wherever they may place their+houses, may be sure that they have been anticipated. An afternoon+sufficed to lay out the land into orchard, woodlot, and pasture, and to+decide what fine oaks or pines should be left to stand before the door,+and whence each blasted tree could be seen to the best advantage; and+then I let it lie, fallow perchance, for a man is rich in proportion to+the number of things which he can afford to let alone.++My imagination carried me so far that I even had the refusal of several+farms,—the refusal was all I wanted,—but I never got my fingers burned+by actual possession. The nearest that I came to actual possession was+when I bought the Hollowell place, and had begun to sort my seeds, and+collected materials with which to make a wheelbarrow to carry it on or+off with; but before the owner gave me a deed of it, his wife—every man+has such a wife—changed her mind and wished to keep it, and he offered+me ten dollars to release him. Now, to speak the truth, I had but ten+cents in the world, and it surpassed my arithmetic to tell, if I was+that man who had ten cents, or who had a farm, or ten dollars, or all+together. However, I let him keep the ten dollars and the farm too, for+I had carried it far enough; or rather, to be generous, I sold him the+farm for just what I gave for it, and, as he was not a rich man, made+him a present of ten dollars, and still had my ten cents, and seeds,+and materials for a wheelbarrow left. I found thus that I had been a+rich man without any damage to my poverty. But I retained the+landscape, and I have since annually carried off what it yielded+without a wheelbarrow. With respect to landscapes,—++ “I am monarch of all I _survey_,+ My right there is none to dispute.”++I have frequently seen a poet withdraw, having enjoyed the most+valuable part of a farm, while the crusty farmer supposed that he had+got a few wild apples only. Why, the owner does not know it for many+years when a poet has put his farm in rhyme, the most admirable kind of+invisible fence, has fairly impounded it, milked it, skimmed it, and+got all the cream, and left the farmer only the skimmed milk.++The real attractions of the Hollowell farm, to me, were; its complete+retirement, being, about two miles from the village, half a mile from+the nearest neighbor, and separated from the highway by a broad field;+its bounding on the river, which the owner said protected it by its+fogs from frosts in the spring, though that was nothing to me; the gray+color and ruinous state of the house and barn, and the dilapidated+fences, which put such an interval between me and the last occupant;+the hollow and lichen-covered apple trees, gnawed by rabbits, showing+what kind of neighbors I should have; but above all, the recollection I+had of it from my earliest voyages up the river, when the house was+concealed behind a dense grove of red maples, through which I heard the+house-dog bark. I was in haste to buy it, before the proprietor+finished getting out some rocks, cutting down the hollow apple trees,+and grubbing up some young birches which had sprung up in the pasture,+or, in short, had made any more of his improvements. To enjoy these+advantages I was ready to carry it on; like Atlas, to take the world on+my shoulders,—I never heard what compensation he received for that,—and+do all those things which had no other motive or excuse but that I+might pay for it and be unmolested in my possession of it; for I knew+all the while that it would yield the most abundant crop of the kind I+wanted if I could only afford to let it alone. But it turned out as I+have said.++All that I could say, then, with respect to farming on a large scale,+(I have always cultivated a garden,) was, that I had had my seeds+ready. Many think that seeds improve with age. I have no doubt that+time discriminates between the good and the bad; and when at last I+shall plant, I shall be less likely to be disappointed. But I would say+to my fellows, once for all, As long as possible live free and+uncommitted. It makes but little difference whether you are committed+to a farm or the county jail.++Old Cato, whose “De Re Rusticâ” is my “Cultivator,” says, and the only+translation I have seen makes sheer nonsense of the passage, “When you+think of getting a farm, turn it thus in your mind, not to buy+greedily; nor spare your pains to look at it, and do not think it+enough to go round it once. The oftener you go there the more it will+please you, if it is good.” I think I shall not buy greedily, but go+round and round it as long as I live, and be buried in it first, that+it may please me the more at last.++The present was my next experiment of this kind, which I purpose to+describe more at length; for convenience, putting the experience of two+years into one. As I have said, I do not propose to write an ode to+dejection, but to brag as lustily as chanticleer in the morning,+standing on his roost, if only to wake my neighbors up.++When first I took up my abode in the woods, that is, began to spend my+nights as well as days there, which, by accident, was on Independence+Day, or the Fourth of July, 1845, my house was not finished for winter,+but was merely a defence against the rain, without plastering or+chimney, the walls being of rough, weather-stained boards, with wide+chinks, which made it cool at night. The upright white hewn studs and+freshly planed door and window casings gave it a clean and airy look,+especially in the morning, when its timbers were saturated with dew, so+that I fancied that by noon some sweet gum would exude from them. To my+imagination it retained throughout the day more or less of this auroral+character, reminding me of a certain house on a mountain which I had+visited the year before. This was an airy and unplastered cabin, fit to+entertain a travelling god, and where a goddess might trail her+garments. The winds which passed over my dwelling were such as sweep+over the ridges of mountains, bearing the broken strains, or celestial+parts only, of terrestrial music. The morning wind forever blows, the+poem of creation is uninterrupted; but few are the ears that hear it.+Olympus is but the outside of the earth every where.++The only house I had been the owner of before, if I except a boat, was+a tent, which I used occasionally when making excursions in the summer,+and this is still rolled up in my garret; but the boat, after passing+from hand to hand, has gone down the stream of time. With this more+substantial shelter about me, I had made some progress toward settling+in the world. This frame, so slightly clad, was a sort of+crystallization around me, and reacted on the builder. It was+suggestive somewhat as a picture in outlines. I did not need to go+outdoors to take the air, for the atmosphere within had lost none of+its freshness. It was not so much within doors as behind a door where I+sat, even in the rainiest weather. The Harivansa says, “An abode+without birds is like a meat without seasoning.” Such was not my abode,+for I found myself suddenly neighbor to the birds; not by having+imprisoned one, but having caged myself near them. I was not only+nearer to some of those which commonly frequent the garden and the+orchard, but to those wilder and more thrilling songsters of the forest+which never, or rarely, serenade a villager,—the wood-thrush, the+veery, the scarlet tanager, the field-sparrow, the whippoorwill, and+many others.++I was seated by the shore of a small pond, about a mile and a half+south of the village of Concord and somewhat higher than it, in the+midst of an extensive wood between that town and Lincoln, and about two+miles south of that our only field known to fame, Concord Battle+Ground; but I was so low in the woods that the opposite shore, half a+mile off, like the rest, covered with wood, was my most distant+horizon. For the first week, whenever I looked out on the pond it+impressed me like a tarn high up on the side of a mountain, its bottom+far above the surface of other lakes, and, as the sun arose, I saw it+throwing off its nightly clothing of mist, and here and there, by+degrees, its soft ripples or its smooth reflecting surface was+revealed, while the mists, like ghosts, were stealthily withdrawing in+every direction into the woods, as at the breaking up of some nocturnal+conventicle. The very dew seemed to hang upon the trees later into the+day than usual, as on the sides of mountains.++This small lake was of most value as a neighbor in the intervals of a+gentle rain storm in August, when, both air and water being perfectly+still, but the sky overcast, mid-afternoon had all the serenity of+evening, and the wood-thrush sang around, and was heard from shore to+shore. A lake like this is never smoother than at such a time; and the+clear portion of the air above it being shallow and darkened by clouds,+the water, full of light and reflections, becomes a lower heaven itself+so much the more important. From a hill top near by, where the wood had+been recently cut off, there was a pleasing vista southward across the+pond, through a wide indentation in the hills which form the shore+there, where their opposite sides sloping toward each other suggested a+stream flowing out in that direction through a wooded valley, but+stream there was none. That way I looked between and over the near+green hills to some distant and higher ones in the horizon, tinged with+blue. Indeed, by standing on tiptoe I could catch a glimpse of some of+the peaks of the still bluer and more distant mountain ranges in the+north-west, those true-blue coins from heaven’s own mint, and also of+some portion of the village. But in other directions, even from this+point, I could not see over or beyond the woods which surrounded me. It+is well to have some water in your neighborhood, to give buoyancy to+and float the earth. One value even of the smallest well is, that when+you look into it you see that earth is not continent but insular. This+is as important as that it keeps butter cool. When I looked across the+pond from this peak toward the Sudbury meadows, which in time of flood+I distinguished elevated perhaps by a mirage in their seething valley,+like a coin in a basin, all the earth beyond the pond appeared like a+thin crust insulated and floated even by this small sheet of+interverting water, and I was reminded that this on which I dwelt was+but _dry land_.++Though the view from my door was still more contracted, I did not feel+crowded or confined in the least. There was pasture enough for my+imagination. The low shrub-oak plateau to which the opposite shore+arose, stretched away toward the prairies of the West and the steppes+of Tartary, affording ample room for all the roving families of men.+“There are none happy in the world but beings who enjoy freely a vast+horizon,”—said Damodara, when his herds required new and larger+pastures.++Both place and time were changed, and I dwelt nearer to those parts of+the universe and to those eras in history which had most attracted me.+Where I lived was as far off as many a region viewed nightly by+astronomers. We are wont to imagine rare and delectable places in some+remote and more celestial corner of the system, behind the+constellation of Cassiopeia’s Chair, far from noise and disturbance. I+discovered that my house actually had its site in such a withdrawn, but+forever new and unprofaned, part of the universe. If it were worth the+while to settle in those parts near to the Pleiades or the Hyades, to+Aldebaran or Altair, then I was really there, or at an equal remoteness+from the life which I had left behind, dwindled and twinkling with as+fine a ray to my nearest neighbor, and to be seen only in moonless+nights by him. Such was that part of creation where I had squatted;—++ “There was a shepherd that did live,+ And held his thoughts as high+ As were the mounts whereon his flocks+ Did hourly feed him by.”++What should we think of the shepherd’s life if his flocks always+wandered to higher pastures than his thoughts?++Every morning was a cheerful invitation to make my life of equal+simplicity, and I may say innocence, with Nature herself. I have been+as sincere a worshipper of Aurora as the Greeks. I got up early and+bathed in the pond; that was a religious exercise, and one of the best+things which I did. They say that characters were engraven on the+bathing tub of king Tching-thang to this effect: “Renew thyself+completely each day; do it again, and again, and forever again.” I can+understand that. Morning brings back the heroic ages. I was as much+affected by the faint hum of a mosquito making its invisible and+unimaginable tour through my apartment at earliest dawn, when I was+sitting with door and windows open, as I could be by any trumpet that+ever sang of fame. It was Homer’s requiem; itself an Iliad and Odyssey+in the air, singing its own wrath and wanderings. There was something+cosmical about it; a standing advertisement, till forbidden, of the+everlasting vigor and fertility of the world. The morning, which is the+most memorable season of the day, is the awakening hour. Then there is+least somnolence in us; and for an hour, at least, some part of us+awakes which slumbers all the rest of the day and night. Little is to+be expected of that day, if it can be called a day, to which we are not+awakened by our Genius, but by the mechanical nudgings of some+servitor, are not awakened by our own newly-acquired force and+aspirations from within, accompanied by the undulations of celestial+music, instead of factory bells, and a fragrance filling the air—to a+higher life than we fell asleep from; and thus the darkness bear its+fruit, and prove itself to be good, no less than the light. That man+who does not believe that each day contains an earlier, more sacred,+and auroral hour than he has yet profaned, has despaired of life, and+is pursuing a descending and darkening way. After a partial cessation+of his sensuous life, the soul of man, or its organs rather, are+reinvigorated each day, and his Genius tries again what noble life it+can make. All memorable events, I should say, transpire in morning time+and in a morning atmosphere. The Vedas say, “All intelligences awake+with the morning.” Poetry and art, and the fairest and most memorable+of the actions of men, date from such an hour. All poets and heroes,+like Memnon, are the children of Aurora, and emit their music at+sunrise. To him whose elastic and vigorous thought keeps pace with the+sun, the day is a perpetual morning. It matters not what the clocks say+or the attitudes and labors of men. Morning is when I am awake and+there is a dawn in me. Moral reform is the effort to throw off sleep.+Why is it that men give so poor an account of their day if they have+not been slumbering? They are not such poor calculators. If they had+not been overcome with drowsiness, they would have performed something.+The millions are awake enough for physical labor; but only one in a+million is awake enough for effective intellectual exertion, only one+in a hundred millions to a poetic or divine life. To be awake is to be+alive. I have never yet met a man who was quite awake. How could I have+looked him in the face?++We must learn to reawaken and keep ourselves awake, not by mechanical+aids, but by an infinite expectation of the dawn, which does not+forsake us in our soundest sleep. I know of no more encouraging fact+than the unquestionable ability of man to elevate his life by a+conscious endeavor. It is something to be able to paint a particular+picture, or to carve a statue, and so to make a few objects beautiful;+but it is far more glorious to carve and paint the very atmosphere and+medium through which we look, which morally we can do. To affect the+quality of the day, that is the highest of arts. Every man is tasked to+make his life, even in its details, worthy of the contemplation of his+most elevated and critical hour. If we refused, or rather used up, such+paltry information as we get, the oracles would distinctly inform us+how this might be done.++I went to the woods because I wished to live deliberately, to front+only the essential facts of life, and see if I could not learn what it+had to teach, and not, when I came to die, discover that I had not+lived. I did not wish to live what was not life, living is so dear; nor+did I wish to practise resignation, unless it was quite necessary. I+wanted to live deep and suck out all the marrow of life, to live so+sturdily and Spartan-like as to put to rout all that was not life, to+cut a broad swath and shave close, to drive life into a corner, and+reduce it to its lowest terms, and, if it proved to be mean, why then+to get the whole and genuine meanness of it, and publish its meanness+to the world; or if it were sublime, to know it by experience, and be+able to give a true account of it in my next excursion. For most men,+it appears to me, are in a strange uncertainty about it, whether it is+of the devil or of God, and have _somewhat hastily_ concluded that it+is the chief end of man here to “glorify God and enjoy him forever.”++Still we live meanly, like ants; though the fable tells us that we were+long ago changed into men; like pygmies we fight with cranes; it is+error upon error, and clout upon clout, and our best virtue has for its+occasion a superfluous and evitable wretchedness. Our life is frittered+away by detail. An honest man has hardly need to count more than his+ten fingers, or in extreme cases he may add his ten toes, and lump the+rest. Simplicity, simplicity, simplicity! I say, let your affairs be as+two or three, and not a hundred or a thousand; instead of a million+count half a dozen, and keep your accounts on your thumb nail. In the+midst of this chopping sea of civilized life, such are the clouds and+storms and quicksands and thousand-and-one items to be allowed for,+that a man has to live, if he would not founder and go to the bottom+and not make his port at all, by dead reckoning, and he must be a great+calculator indeed who succeeds. Simplify, simplify. Instead of three+meals a day, if it be necessary eat but one; instead of a hundred+dishes, five; and reduce other things in proportion. Our life is like a+German Confederacy, made up of petty states, with its boundary forever+fluctuating, so that even a German cannot tell you how it is bounded at+any moment. The nation itself, with all its so called internal+improvements, which, by the way, are all external and superficial, is+just such an unwieldy and overgrown establishment, cluttered with+furniture and tripped up by its own traps, ruined by luxury and+heedless expense, by want of calculation and a worthy aim, as the+million households in the land; and the only cure for it as for them is+in a rigid economy, a stern and more than Spartan simplicity of life+and elevation of purpose. It lives too fast. Men think that it is+essential that the _Nation_ have commerce, and export ice, and talk+through a telegraph, and ride thirty miles an hour, without a doubt,+whether _they_ do or not; but whether we should live like baboons or+like men, is a little uncertain. If we do not get out sleepers, and+forge rails, and devote days and nights to the work, but go to+tinkering upon our _lives_ to improve _them_, who will build railroads?+And if railroads are not built, how shall we get to heaven in season?+But if we stay at home and mind our business, who will want railroads?+We do not ride on the railroad; it rides upon us. Did you ever think+what those sleepers are that underlie the railroad? Each one is a man,+an Irish-man, or a Yankee man. The rails are laid on them, and they are+covered with sand, and the cars run smoothly over them. They are sound+sleepers, I assure you. And every few years a new lot is laid down and+run over; so that, if some have the pleasure of riding on a rail,+others have the misfortune to be ridden upon. And when they run over a+man that is walking in his sleep, a supernumerary sleeper in the wrong+position, and wake him up, they suddenly stop the cars, and make a hue+and cry about it, as if this were an exception. I am glad to know that+it takes a gang of men for every five miles to keep the sleepers down+and level in their beds as it is, for this is a sign that they may+sometime get up again.++Why should we live with such hurry and waste of life? We are determined+to be starved before we are hungry. Men say that a stitch in time saves+nine, and so they take a thousand stitches to-day to save nine+to-morrow. As for _work_, we haven’t any of any consequence. We have+the Saint Vitus’ dance, and cannot possibly keep our heads still. If I+should only give a few pulls at the parish bell-rope, as for a fire,+that is, without setting the bell, there is hardly a man on his farm in+the outskirts of Concord, notwithstanding that press of engagements+which was his excuse so many times this morning, nor a boy, nor a+woman, I might almost say, but would forsake all and follow that sound,+not mainly to save property from the flames, but, if we will confess+the truth, much more to see it burn, since burn it must, and we, be it+known, did not set it on fire,—or to see it put out, and have a hand in+it, if that is done as handsomely; yes, even if it were the parish+church itself. Hardly a man takes a half hour’s nap after dinner, but+when he wakes he holds up his head and asks, “What’s the news?” as if+the rest of mankind had stood his sentinels. Some give directions to be+waked every half hour, doubtless for no other purpose; and then, to pay+for it, they tell what they have dreamed. After a night’s sleep the+news is as indispensable as the breakfast. “Pray tell me any thing new+that has happened to a man any where on this globe,”—and he reads it+over his coffee and rolls, that a man has had his eyes gouged out this+morning on the Wachito River; never dreaming the while that he lives in+the dark unfathomed mammoth cave of this world, and has but the+rudiment of an eye himself.++For my part, I could easily do without the post-office. I think that+there are very few important communications made through it. To speak+critically, I never received more than one or two letters in my life—I+wrote this some years ago—that were worth the postage. The penny-post+is, commonly, an institution through which you seriously offer a man+that penny for his thoughts which is so often safely offered in jest.+And I am sure that I never read any memorable news in a newspaper. If+we read of one man robbed, or murdered, or killed by accident, or one+house burned, or one vessel wrecked, or one steamboat blown up, or one+cow run over on the Western Railroad, or one mad dog killed, or one lot+of grasshoppers in the winter,—we never need read of another. One is+enough. If you are acquainted with the principle, what do you care for+a myriad instances and applications? To a philosopher all _news_, as it+is called, is gossip, and they who edit and read it are old women over+their tea. Yet not a few are greedy after this gossip. There was such a+rush, as I hear, the other day at one of the offices to learn the+foreign news by the last arrival, that several large squares of plate+glass belonging to the establishment were broken by the pressure,—news+which I seriously think a ready wit might write a twelve-month, or+twelve years, beforehand with sufficient accuracy. As for Spain, for+instance, if you know how to throw in Don Carlos and the Infanta, and+Don Pedro and Seville and Granada, from time to time in the right+proportions,—they may have changed the names a little since I saw the+papers,—and serve up a bull-fight when other entertainments fail, it+will be true to the letter, and give us as good an idea of the exact+state or ruin of things in Spain as the most succinct and lucid reports+under this head in the newspapers: and as for England, almost the last+significant scrap of news from that quarter was the revolution of 1649;+and if you have learned the history of her crops for an average year,+you never need attend to that thing again, unless your speculations are+of a merely pecuniary character. If one may judge who rarely looks into+the newspapers, nothing new does ever happen in foreign parts, a French+revolution not excepted.++What news! how much more important to know what that is which was never+old! “Kieou-he-yu (great dignitary of the state of Wei) sent a man to+Khoung-tseu to know his news. Khoung-tseu caused the messenger to be+seated near him, and questioned him in these terms: What is your master+doing? The messenger answered with respect: My master desires to+diminish the number of his faults, but he cannot come to the end of+them. The messenger being gone, the philosopher remarked: What a worthy+messenger! What a worthy messenger!” The preacher, instead of vexing+the ears of drowsy farmers on their day of rest at the end of the+week,—for Sunday is the fit conclusion of an ill-spent week, and not+the fresh and brave beginning of a new one,—with this one other+draggle-tail of a sermon, should shout with thundering voice, “Pause!+Avast! Why so seeming fast, but deadly slow?”++Shams and delusions are esteemed for soundest truths, while reality is+fabulous. If men would steadily observe realities only, and not allow+themselves to be deluded, life, to compare it with such things as we+know, would be like a fairy tale and the Arabian Nights’+Entertainments. If we respected only what is inevitable and has a right+to be, music and poetry would resound along the streets. When we are+unhurried and wise, we perceive that only great and worthy things have+any permanent and absolute existence,—that petty fears and petty+pleasures are but the shadow of the reality. This is always+exhilarating and sublime. By closing the eyes and slumbering, and+consenting to be deceived by shows, men establish and confirm their+daily life of routine and habit everywhere, which still is built on+purely illusory foundations. Children, who play life, discern its true+law and relations more clearly than men, who fail to live it worthily,+but who think that they are wiser by experience, that is, by failure. I+have read in a Hindoo book, that “there was a king’s son, who, being+expelled in infancy from his native city, was brought up by a forester,+and, growing up to maturity in that state, imagined himself to belong+to the barbarous race with which he lived. One of his father’s+ministers having discovered him, revealed to him what he was, and the+misconception of his character was removed, and he knew himself to be a+prince. So soul,” continues the Hindoo philosopher, “from the+circumstances in which it is placed, mistakes its own character, until+the truth is revealed to it by some holy teacher, and then it knows+itself to be _Brahme_.” I perceive that we inhabitants of New England+live this mean life that we do because our vision does not penetrate+the surface of things. We think that that _is_ which _appears_ to be.+If a man should walk through this town and see only the reality, where,+think you, would the “Mill-dam” go to? If he should give us an account+of the realities he beheld there, we should not recognize the place in+his description. Look at a meeting-house, or a court-house, or a jail,+or a shop, or a dwelling-house, and say what that thing really is+before a true gaze, and they would all go to pieces in your account of+them. Men esteem truth remote, in the outskirts of the system, behind+the farthest star, before Adam and after the last man. In eternity+there is indeed something true and sublime. But all these times and+places and occasions are now and here. God himself culminates in the+present moment, and will never be more divine in the lapse of all the+ages. And we are enabled to apprehend at all what is sublime and noble+only by the perpetual instilling and drenching of the reality that+surrounds us. The universe constantly and obediently answers to our+conceptions; whether we travel fast or slow, the track is laid for us.+Let us spend our lives in conceiving then. The poet or the artist never+yet had so fair and noble a design but some of his posterity at least+could accomplish it.++Let us spend one day as deliberately as Nature, and not be thrown off+the track by every nutshell and mosquito’s wing that falls on the+rails. Let us rise early and fast, or break fast, gently and without+perturbation; let company come and let company go, let the bells ring+and the children cry,—determined to make a day of it. Why should we+knock under and go with the stream? Let us not be upset and overwhelmed+in that terrible rapid and whirlpool called a dinner, situated in the+meridian shallows. Weather this danger and you are safe, for the rest+of the way is down hill. With unrelaxed nerves, with morning vigor,+sail by it, looking another way, tied to the mast like Ulysses. If the+engine whistles, let it whistle till it is hoarse for its pains. If the+bell rings, why should we run? We will consider what kind of music they+are like. Let us settle ourselves, and work and wedge our feet downward+through the mud and slush of opinion, and prejudice, and tradition, and+delusion, and appearance, that alluvion which covers the globe, through+Paris and London, through New York and Boston and Concord, through+church and state, through poetry and philosophy and religion, till we+come to a hard bottom and rocks in place, which we can call _reality_,+and say, This is, and no mistake; and then begin, having a _point+d’appui_, below freshet and frost and fire, a place where you might+found a wall or a state, or set a lamp-post safely, or perhaps a gauge,+not a Nilometer, but a Realometer, that future ages might know how deep+a freshet of shams and appearances had gathered from time to time. If+you stand right fronting and face to face to a fact, you will see the+sun glimmer on both its surfaces, as if it were a cimeter, and feel its+sweet edge dividing you through the heart and marrow, and so you will+happily conclude your mortal career. Be it life or death, we crave only+reality. If we are really dying, let us hear the rattle in our throats+and feel cold in the extremities; if we are alive, let us go about our+business.++Time is but the stream I go a-fishing in. I drink at it; but while I+drink I see the sandy bottom and detect how shallow it is. Its thin+current slides away, but eternity remains. I would drink deeper; fish+in the sky, whose bottom is pebbly with stars. I cannot count one. I+know not the first letter of the alphabet. I have always been+regretting that I was not as wise as the day I was born. The intellect+is a cleaver; it discerns and rifts its way into the secret of things.+I do not wish to be any more busy with my hands than is necessary. My+head is hands and feet. I feel all my best faculties concentrated in+it. My instinct tells me that my head is an organ for burrowing, as+some creatures use their snout and fore-paws, and with it I would mine+and burrow my way through these hills. I think that the richest vein is+somewhere hereabouts; so by the divining-rod and thin rising vapors I+judge; and here I will begin to mine.++Reading++With a little more deliberation in the choice of their pursuits, all+men would perhaps become essentially students and observers, for+certainly their nature and destiny are interesting to all alike. In+accumulating property for ourselves or our posterity, in founding a+family or a state, or acquiring fame even, we are mortal; but in+dealing with truth we are immortal, and need fear no change nor+accident. The oldest Egyptian or Hindoo philosopher raised a corner of+the veil from the statue of the divinity; and still the trembling robe+remains raised, and I gaze upon as fresh a glory as he did, since it+was I in him that was then so bold, and it is he in me that now reviews+the vision. No dust has settled on that robe; no time has elapsed since+that divinity was revealed. That time which we really improve, or which+is improvable, is neither past, present, nor future.++My residence was more favorable, not only to thought, but to serious+reading, than a university; and though I was beyond the range of the+ordinary circulating library, I had more than ever come within the+influence of those books which circulate round the world, whose+sentences were first written on bark, and are now merely copied from+time to time on to linen paper. Says the poet Mîr Camar Uddîn Mast,+“Being seated to run through the region of the spiritual world; I have+had this advantage in books. To be intoxicated by a single glass of+wine; I have experienced this pleasure when I have drunk the liquor of+the esoteric doctrines.” I kept Homer’s Iliad on my table through the+summer, though I looked at his page only now and then. Incessant labor+with my hands, at first, for I had my house to finish and my beans to+hoe at the same time, made more study impossible. Yet I sustained+myself by the prospect of such reading in future. I read one or two+shallow books of travel in the intervals of my work, till that+employment made me ashamed of myself, and I asked where it was then+that _I_ lived.++The student may read Homer or Æschylus in the Greek without danger of+dissipation or luxuriousness, for it implies that he in some measure+emulate their heroes, and consecrate morning hours to their pages. The+heroic books, even if printed in the character of our mother tongue,+will always be in a language dead to degenerate times; and we must+laboriously seek the meaning of each word and line, conjecturing a+larger sense than common use permits out of what wisdom and valor and+generosity we have. The modern cheap and fertile press, with all its+translations, has done little to bring us nearer to the heroic writers+of antiquity. They seem as solitary, and the letter in which they are+printed as rare and curious, as ever. It is worth the expense of+youthful days and costly hours, if you learn only some words of an+ancient language, which are raised out of the trivialness of the+street, to be perpetual suggestions and provocations. It is not in vain+that the farmer remembers and repeats the few Latin words which he has+heard. Men sometimes speak as if the study of the classics would at+length make way for more modern and practical studies; but the+adventurous student will always study classics, in whatever language+they may be written and however ancient they may be. For what are the+classics but the noblest recorded thoughts of man? They are the only+oracles which are not decayed, and there are such answers to the most+modern inquiry in them as Delphi and Dodona never gave. We might as+well omit to study Nature because she is old. To read well, that is, to+read true books in a true spirit, is a noble exercise, and one that+will task the reader more than any exercise which the customs of the+day esteem. It requires a training such as the athletes underwent, the+steady intention almost of the whole life to this object. Books must be+read as deliberately and reservedly as they were written. It is not+enough even to be able to speak the language of that nation by which+they are written, for there is a memorable interval between the spoken+and the written language, the language heard and the language read. The+one is commonly transitory, a sound, a tongue, a dialect merely, almost+brutish, and we learn it unconsciously, like the brutes, of our+mothers. The other is the maturity and experience of that; if that is+our mother tongue, this is our father tongue, a reserved and select+expression, too significant to be heard by the ear, which we must be+born again in order to speak. The crowds of men who merely _spoke_ the+Greek and Latin tongues in the middle ages were not entitled by the+accident of birth to _read_ the works of genius written in those+languages; for these were not written in that Greek or Latin which they+knew, but in the select language of literature. They had not learned+the nobler dialects of Greece and Rome, but the very materials on which+they were written were waste paper to them, and they prized instead a+cheap contemporary literature. But when the several nations of Europe+had acquired distinct though rude written languages of their own,+sufficient for the purposes of their rising literatures, then first+learning revived, and scholars were enabled to discern from that+remoteness the treasures of antiquity. What the Roman and Grecian+multitude could not _hear_, after the lapse of ages a few scholars+_read_, and a few scholars only are still reading it.++However much we may admire the orator’s occasional bursts of eloquence,+the noblest written words are commonly as far behind or above the+fleeting spoken language as the firmament with its stars is behind the+clouds. _There_ are the stars, and they who can may read them. The+astronomers forever comment on and observe them. They are not+exhalations like our daily colloquies and vaporous breath. What is+called eloquence in the forum is commonly found to be rhetoric in the+study. The orator yields to the inspiration of a transient occasion,+and speaks to the mob before him, to those who can _hear_ him; but the+writer, whose more equable life is his occasion, and who would be+distracted by the event and the crowd which inspire the orator, speaks+to the intellect and health of mankind, to all in any age who can+_understand_ him.++No wonder that Alexander carried the Iliad with him on his expeditions+in a precious casket. A written word is the choicest of relics. It is+something at once more intimate with us and more universal than any+other work of art. It is the work of art nearest to life itself. It may+be translated into every language, and not only be read but actually+breathed from all human lips;—not be represented on canvas or in marble+only, but be carved out of the breath of life itself. The symbol of an+ancient man’s thought becomes a modern man’s speech. Two thousand+summers have imparted to the monuments of Grecian literature, as to her+marbles, only a maturer golden and autumnal tint, for they have carried+their own serene and celestial atmosphere into all lands to protect+them against the corrosion of time. Books are the treasured wealth of+the world and the fit inheritance of generations and nations. Books,+the oldest and the best, stand naturally and rightfully on the shelves+of every cottage. They have no cause of their own to plead, but while+they enlighten and sustain the reader his common sense will not refuse+them. Their authors are a natural and irresistible aristocracy in every+society, and, more than kings or emperors, exert an influence on+mankind. When the illiterate and perhaps scornful trader has earned by+enterprise and industry his coveted leisure and independence, and is+admitted to the circles of wealth and fashion, he turns inevitably at+last to those still higher but yet inaccessible circles of intellect+and genius, and is sensible only of the imperfection of his culture and+the vanity and insufficiency of all his riches, and further proves his+good sense by the pains which he takes to secure for his children that+intellectual culture whose want he so keenly feels; and thus it is that+he becomes the founder of a family.++Those who have not learned to read the ancient classics in the language+in which they were written must have a very imperfect knowledge of the+history of the human race; for it is remarkable that no transcript of+them has ever been made into any modern tongue, unless our civilization+itself may be regarded as such a transcript. Homer has never yet been+printed in English, nor Æschylus, nor Virgil even—works as refined, as+solidly done, and as beautiful almost as the morning itself; for later+writers, say what we will of their genius, have rarely, if ever,+equalled the elaborate beauty and finish and the lifelong and heroic+literary labors of the ancients. They only talk of forgetting them who+never knew them. It will be soon enough to forget them when we have the+learning and the genius which will enable us to attend to and+appreciate them. That age will be rich indeed when those relics which+we call Classics, and the still older and more than classic but even+less known Scriptures of the nations, shall have still further+accumulated, when the Vaticans shall be filled with Vedas and+Zendavestas and Bibles, with Homers and Dantes and Shakespeares, and+all the centuries to come shall have successively deposited their+trophies in the forum of the world. By such a pile we may hope to scale+heaven at last.++The works of the great poets have never yet been read by mankind, for+only great poets can read them. They have only been read as the+multitude read the stars, at most astrologically, not astronomically.+Most men have learned to read to serve a paltry convenience, as they+have learned to cipher in order to keep accounts and not be cheated in+trade; but of reading as a noble intellectual exercise they know little+or nothing; yet this only is reading, in a high sense, not that which+lulls us as a luxury and suffers the nobler faculties to sleep the+while, but what we have to stand on tip-toe to read and devote our most+alert and wakeful hours to.++I think that having learned our letters we should read the best that is+in literature, and not be forever repeating our a b abs, and words of+one syllable, in the fourth or fifth classes, sitting on the lowest and+foremost form all our lives. Most men are satisfied if they read or+hear read, and perchance have been convicted by the wisdom of one good+book, the Bible, and for the rest of their lives vegetate and dissipate+their faculties in what is called easy reading. There is a work in+several volumes in our Circulating Library entitled Little Reading,+which I thought referred to a town of that name which I had not been+to. There are those who, like cormorants and ostriches, can digest all+sorts of this, even after the fullest dinner of meats and vegetables,+for they suffer nothing to be wasted. If others are the machines to+provide this provender, they are the machines to read it. They read the+nine thousandth tale about Zebulon and Sephronia, and how they loved as+none had ever loved before, and neither did the course of their true+love run smooth,—at any rate, how it did run and stumble, and get up+again and go on! how some poor unfortunate got up on to a steeple, who+had better never have gone up as far as the belfry; and then, having+needlessly got him up there, the happy novelist rings the bell for all+the world to come together and hear, O dear! how he did get down again!+For my part, I think that they had better metamorphose all such+aspiring heroes of universal noveldom into man weathercocks, as they+used to put heroes among the constellations, and let them swing round+there till they are rusty, and not come down at all to bother honest+men with their pranks. The next time the novelist rings the bell I will+not stir though the meeting-house burn down. “The Skip of the+Tip-Toe-Hop, a Romance of the Middle Ages, by the celebrated author of+‘Tittle-Tol-Tan,’ to appear in monthly parts; a great rush; don’t all+come together.” All this they read with saucer eyes, and erect and+primitive curiosity, and with unwearied gizzard, whose corrugations+even yet need no sharpening, just as some little four-year-old bencher+his two-cent gilt-covered edition of Cinderella,—without any+improvement, that I can see, in the pronunciation, or accent, or+emphasis, or any more skill in extracting or inserting the moral. The+result is dulness of sight, a stagnation of the vital circulations, and+a general deliquium and sloughing off of all the intellectual+faculties. This sort of gingerbread is baked daily and more sedulously+than pure wheat or rye-and-Indian in almost every oven, and finds a+surer market.++The best books are not read even by those who are called good readers.+What does our Concord culture amount to? There is in this town, with a+very few exceptions, no taste for the best or for very good books even+in English literature, whose words all can read and spell. Even the+college-bred and so called liberally educated men here and elsewhere+have really little or no acquaintance with the English classics; and as+for the recorded wisdom of mankind, the ancient classics and Bibles,+which are accessible to all who will know of them, there are the+feeblest efforts any where made to become acquainted with them. I know+a woodchopper, of middle age, who takes a French paper, not for news as+he says, for he is above that, but to “keep himself in practice,” he+being a Canadian by birth; and when I ask him what he considers the+best thing he can do in this world, he says, beside this, to keep up+and add to his English. This is about as much as the college bred+generally do or aspire to do, and they take an English paper for the+purpose. One who has just come from reading perhaps one of the best+English books will find how many with whom he can converse about it? Or+suppose he comes from reading a Greek or Latin classic in the original,+whose praises are familiar even to the so called illiterate; he will+find nobody at all to speak to, but must keep silence about it. Indeed,+there is hardly the professor in our colleges, who, if he has mastered+the difficulties of the language, has proportionally mastered the+difficulties of the wit and poetry of a Greek poet, and has any+sympathy to impart to the alert and heroic reader; and as for the+sacred Scriptures, or Bibles of mankind, who in this town can tell me+even their titles? Most men do not know that any nation but the Hebrews+have had a scripture. A man, any man, will go considerably out of his+way to pick up a silver dollar; but here are golden words, which the+wisest men of antiquity have uttered, and whose worth the wise of every+succeeding age have assured us of;—and yet we learn to read only as far+as Easy Reading, the primers and class-books, and when we leave school,+the “Little Reading,” and story books, which are for boys and+beginners; and our reading, our conversation and thinking, are all on a+very low level, worthy only of pygmies and manikins.++I aspire to be acquainted with wiser men than this our Concord soil has+produced, whose names are hardly known here. Or shall I hear the name+of Plato and never read his book? As if Plato were my townsman and I+never saw him,—my next neighbor and I never heard him speak or attended+to the wisdom of his words. But how actually is it? His Dialogues,+which contain what was immortal in him, lie on the next shelf, and yet+I never read them. We are underbred and low-lived and illiterate; and+in this respect I confess I do not make any very broad distinction+between the illiterateness of my townsman who cannot read at all, and+the illiterateness of him who has learned to read only what is for+children and feeble intellects. We should be as good as the worthies of+antiquity, but partly by first knowing how good they were. We are a+race of tit-men, and soar but little higher in our intellectual flights+than the columns of the daily paper.++It is not all books that are as dull as their readers. There are+probably words addressed to our condition exactly, which, if we could+really hear and understand, would be more salutary than the morning or+the spring to our lives, and possibly put a new aspect on the face of+things for us. How many a man has dated a new era in his life from the+reading of a book. The book exists for us perchance which will explain+our miracles and reveal new ones. The at present unutterable things we+may find somewhere uttered. These same questions that disturb and+puzzle and confound us have in their turn occurred to all the wise men;+not one has been omitted; and each has answered them, according to his+ability, by his words and his life. Moreover, with wisdom we shall+learn liberality. The solitary hired man on a farm in the outskirts of+Concord, who has had his second birth and peculiar religious+experience, and is driven as he believes into the silent gravity and+exclusiveness by his faith, may think it is not true; but Zoroaster,+thousands of years ago, travelled the same road and had the same+experience; but he, being wise, knew it to be universal, and treated+his neighbors accordingly, and is even said to have invented and+established worship among men. Let him humbly commune with Zoroaster+then, and through the liberalizing influence of all the worthies, with+Jesus Christ himself, and let “our church” go by the board.++We boast that we belong to the nineteenth century and are making the+most rapid strides of any nation. But consider how little this village+does for its own culture. I do not wish to flatter my townsmen, nor to+be flattered by them, for that will not advance either of us. We need+to be provoked,—goaded like oxen, as we are, into a trot. We have a+comparatively decent system of common schools, schools for infants+only; but excepting the half-starved Lyceum in the winter, and latterly+the puny beginning of a library suggested by the state, no school for+ourselves. We spend more on almost any article of bodily aliment or+ailment than on our mental aliment. It is time that we had uncommon+schools, that we did not leave off our education when we begin to be+men and women. It is time that villages were universities, and their+elder inhabitants the fellows of universities, with leisure—if they are+indeed so well off—to pursue liberal studies the rest of their lives.+Shall the world be confined to one Paris or one Oxford forever? Cannot+students be boarded here and get a liberal education under the skies of+Concord? Can we not hire some Abelard to lecture to us? Alas! what with+foddering the cattle and tending the store, we are kept from school too+long, and our education is sadly neglected. In this country, the+village should in some respects take the place of the nobleman of+Europe. It should be the patron of the fine arts. It is rich enough. It+wants only the magnanimity and refinement. It can spend money enough on+such things as farmers and traders value, but it is thought Utopian to+propose spending money for things which more intelligent men know to be+of far more worth. This town has spent seventeen thousand dollars on a+town-house, thank fortune or politics, but probably it will not spend+so much on living wit, the true meat to put into that shell, in a+hundred years. The one hundred and twenty-five dollars annually+subscribed for a Lyceum in the winter is better spent than any other+equal sum raised in the town. If we live in the nineteenth century, why+should we not enjoy the advantages which the nineteenth century offers?+Why should our life be in any respect provincial? If we will read+newspapers, why not skip the gossip of Boston and take the best+newspaper in the world at once?—not be sucking the pap of “neutral+family” papers, or browsing “Olive-Branches” here in New England. Let+the reports of all the learned societies come to us, and we will see if+they know any thing. Why should we leave it to Harper & Brothers and+Redding & Co. to select our reading? As the nobleman of cultivated+taste surrounds himself with whatever conduces to his+culture,—genius—learning—wit—books—paintings—statuary—music—+philosophical instruments, and the like; so let the village do,—not+stop short at a pedagogue, a parson, a sexton, a parish library, and+three selectmen, because our pilgrim forefathers got through a cold+winter once on a bleak rock with these. To act collectively is+according to the spirit of our institutions; and I am confident that,+as our circumstances are more flourishing, our means are greater than+the nobleman’s. New England can hire all the wise men in the world to+come and teach her, and board them round the while, and not be+provincial at all. That is the _uncommon_ school we want. Instead of+noblemen, let us have noble villages of men. If it is necessary, omit+one bridge over the river, go round a little there, and throw one arch+at least over the darker gulf of ignorance which surrounds us.++Sounds++But while we are confined to books, though the most select and classic,+and read only particular written languages, which are themselves but+dialects and provincial, we are in danger of forgetting the language+which all things and events speak without metaphor, which alone is+copious and standard. Much is published, but little printed. The rays+which stream through the shutter will be no longer remembered when the+shutter is wholly removed. No method nor discipline can supersede the+necessity of being forever on the alert. What is a course of history,+or philosophy, or poetry, no matter how well selected, or the best+society, or the most admirable routine of life, compared with the+discipline of looking always at what is to be seen? Will you be a+reader, a student merely, or a seer? Read your fate, see what is before+you, and walk on into futurity.++I did not read books the first summer; I hoed beans. Nay, I often did+better than this. There were times when I could not afford to sacrifice+the bloom of the present moment to any work, whether of the head or+hands. I love a broad margin to my life. Sometimes, in a summer+morning, having taken my accustomed bath, I sat in my sunny doorway+from sunrise till noon, rapt in a revery, amidst the pines and+hickories and sumachs, in undisturbed solitude and stillness, while the+birds sing around or flitted noiseless through the house, until by the+sun falling in at my west window, or the noise of some traveller’s+wagon on the distant highway, I was reminded of the lapse of time. I+grew in those seasons like corn in the night, and they were far better+than any work of the hands would have been. They were not time+subtracted from my life, but so much over and above my usual allowance.+I realized what the Orientals mean by contemplation and the forsaking+of works. For the most part, I minded not how the hours went. The day+advanced as if to light some work of mine; it was morning, and lo, now+it is evening, and nothing memorable is accomplished. Instead of+singing like the birds, I silently smiled at my incessant good fortune.+As the sparrow had its trill, sitting on the hickory before my door, so+had I my chuckle or suppressed warble which he might hear out of my+nest. My days were not days of the week, bearing the stamp of any+heathen deity, nor were they minced into hours and fretted by the+ticking of a clock; for I lived like the Puri Indians, of whom it is+said that “for yesterday, to-day, and to-morrow they have only one+word, and they express the variety of meaning by pointing backward for+yesterday, forward for to-morrow, and overhead for the passing day.”+This was sheer idleness to my fellow-townsmen, no doubt; but if the+birds and flowers had tried me by their standard, I should not have+been found wanting. A man must find his occasions in himself, it is+true. The natural day is very calm, and will hardly reprove his+indolence.++I had this advantage, at least, in my mode of life, over those who were+obliged to look abroad for amusement, to society and the theatre, that+my life itself was become my amusement and never ceased to be novel. It+was a drama of many scenes and without an end. If we were always indeed+getting our living, and regulating our lives according to the last and+best mode we had learned, we should never be troubled with ennui.+Follow your genius closely enough, and it will not fail to show you a+fresh prospect every hour. Housework was a pleasant pastime. When my+floor was dirty, I rose early, and, setting all my furniture out of+doors on the grass, bed and bedstead making but one budget, dashed+water on the floor, and sprinkled white sand from the pond on it, and+then with a broom scrubbed it clean and white; and by the time the+villagers had broken their fast the morning sun had dried my house+sufficiently to allow me to move in again, and my meditations were+almost uninterupted. It was pleasant to see my whole household effects+out on the grass, making a little pile like a gypsy’s pack, and my+three-legged table, from which I did not remove the books and pen and+ink, standing amid the pines and hickories. They seemed glad to get out+themselves, and as if unwilling to be brought in. I was sometimes+tempted to stretch an awning over them and take my seat there. It was+worth the while to see the sun shine on these things, and hear the free+wind blow on them; so much more interesting most familiar objects look+out of doors than in the house. A bird sits on the next bough,+life-everlasting grows under the table, and blackberry vines run round+its legs; pine cones, chestnut burs, and strawberry leaves are strewn+about. It looked as if this was the way these forms came to be+transferred to our furniture, to tables, chairs, and bedsteads,—because+they once stood in their midst.++My house was on the side of a hill, immediately on the edge of the+larger wood, in the midst of a young forest of pitch pines and+hickories, and half a dozen rods from the pond, to which a narrow+footpath led down the hill. In my front yard grew the strawberry,+blackberry, and life-everlasting, johnswort and goldenrod, shrub-oaks+and sand-cherry, blueberry and groundnut. Near the end of May, the+sand-cherry (_Cerasus pumila_,) adorned the sides of the path with its+delicate flowers arranged in umbels cylindrically about its short+stems, which last, in the fall, weighed down with good sized and+handsome cherries, fell over in wreaths like rays on every side. I+tasted them out of compliment to Nature, though they were scarcely+palatable. The sumach (_Rhus glabra_,) grew luxuriantly about the+house, pushing up through the embankment which I had made, and growing+five or six feet the first season. Its broad pinnate tropical leaf was+pleasant though strange to look on. The large buds, suddenly pushing+out late in the spring from dry sticks which had seemed to be dead,+developed themselves as by magic into graceful green and tender boughs,+an inch in diameter; and sometimes, as I sat at my window, so+heedlessly did they grow and tax their weak joints, I heard a fresh and+tender bough suddenly fall like a fan to the ground, when there was not+a breath of air stirring, broken off by its own weight. In August, the+large masses of berries, which, when in flower, had attracted many wild+bees, gradually assumed their bright velvety crimson hue, and by their+weight again bent down and broke the tender limbs.++As I sit at my window this summer afternoon, hawks are circling about+my clearing; the tantivy of wild pigeons, flying by twos and threes+athwart my view, or perching restless on the white-pine boughs behind+my house, gives a voice to the air; a fishhawk dimples the glassy+surface of the pond and brings up a fish; a mink steals out of the+marsh before my door and seizes a frog by the shore; the sedge is+bending under the weight of the reed-birds flitting hither and thither;+and for the last half hour I have heard the rattle of railroad cars,+now dying away and then reviving like the beat of a partridge,+conveying travellers from Boston to the country. For I did not live so+out of the world as that boy who, as I hear, was put out to a farmer in+the east part of the town, but ere long ran away and came home again,+quite down at the heel and homesick. He had never seen such a dull and+out-of-the-way place; the folks were all gone off; why, you couldn’t+even hear the whistle! I doubt if there is such a place in+Massachusetts now:—++ “In truth, our village has become a butt+ For one of those fleet railroad shafts, and o’er+ Our peaceful plain its soothing sound is—Concord.”++The Fitchburg Railroad touches the pond about a hundred rods south of+where I dwell. I usually go to the village along its causeway, and am,+as it were, related to society by this link. The men on the freight+trains, who go over the whole length of the road, bow to me as to an+old acquaintance, they pass me so often, and apparently they take me+for an employee; and so I am. I too would fain be a track-repairer+somewhere in the orbit of the earth.++The whistle of the locomotive penetrates my woods summer and winter,+sounding like the scream of a hawk sailing over some farmer’s yard,+informing me that many restless city merchants are arriving within the+circle of the town, or adventurous country traders from the other side.+As they come under one horizon, they shout their warning to get off the+track to the other, heard sometimes through the circles of two towns.+Here come your groceries, country; your rations, countrymen! Nor is+there any man so independent on his farm that he can say them nay. And+here’s your pay for them! screams the countryman’s whistle; timber like+long battering rams going twenty miles an hour against the city’s+walls, and chairs enough to seat all the weary and heavy laden that+dwell within them. With such huge and lumbering civility the country+hands a chair to the city. All the Indian huckleberry hills are+stripped, all the cranberry meadows are raked into the city. Up comes+the cotton, down goes the woven cloth; up comes the silk, down goes the+woollen; up come the books, but down goes the wit that writes them.++When I meet the engine with its train of cars moving off with planetary+motion,—or, rather, like a comet, for the beholder knows not if with+that velocity and with that direction it will ever revisit this system,+since its orbit does not look like a returning curve,—with its steam+cloud like a banner streaming behind in golden and silver wreaths, like+many a downy cloud which I have seen, high in the heavens, unfolding+its masses to the light,—as if this travelling demigod, this+cloud-compeller, would ere long take the sunset sky for the livery of+his train; when I hear the iron horse make the hills echo with his+snort like thunder, shaking the earth with his feet, and breathing fire+and smoke from his nostrils, (what kind of winged horse or fiery dragon+they will put into the new Mythology I don’t know), it seems as if the+earth had got a race now worthy to inhabit it. If all were as it seems,+and men made the elements their servants for noble ends! If the cloud+that hangs over the engine were the perspiration of heroic deeds, or as+beneficent as that which floats over the farmer’s fields, then the+elements and Nature herself would cheerfully accompany men on their+errands and be their escort.++I watch the passage of the morning cars with the same feeling that I do+the rising of the sun, which is hardly more regular. Their train of+clouds stretching far behind and rising higher and higher, going to+heaven while the cars are going to Boston, conceals the sun for a+minute and casts my distant field into the shade, a celestial train+beside which the petty train of cars which hugs the earth is but the+barb of the spear. The stabler of the iron horse was up early this+winter morning by the light of the stars amid the mountains, to fodder+and harness his steed. Fire, too, was awakened thus early to put the+vital heat in him and get him off. If the enterprise were as innocent+as it is early! If the snow lies deep, they strap on his snow-shoes,+and with the giant plow, plow a furrow from the mountains to the+seaboard, in which the cars, like a following drill-barrow, sprinkle+all the restless men and floating merchandise in the country for seed.+All day the fire-steed flies over the country, stopping only that his+master may rest, and I am awakened by his tramp and defiant snort at+midnight, when in some remote glen in the woods he fronts the elements+incased in ice and snow; and he will reach his stall only with the+morning star, to start once more on his travels without rest or+slumber. Or perchance, at evening, I hear him in his stable blowing off+the superfluous energy of the day, that he may calm his nerves and cool+his liver and brain for a few hours of iron slumber. If the enterprise+were as heroic and commanding as it is protracted and unwearied!++Far through unfrequented woods on the confines of towns, where once+only the hunter penetrated by day, in the darkest night dart these+bright saloons without the knowledge of their inhabitants; this moment+stopping at some brilliant station-house in town or city, where a+social crowd is gathered, the next in the Dismal Swamp, scaring the owl+and fox. The startings and arrivals of the cars are now the epochs in+the village day. They go and come with such regularity and precision,+and their whistle can be heard so far, that the farmers set their+clocks by them, and thus one well conducted institution regulates a+whole country. Have not men improved somewhat in punctuality since the+railroad was invented? Do they not talk and think faster in the depot+than they did in the stage-office? There is something electrifying in+the atmosphere of the former place. I have been astonished at the+miracles it has wrought; that some of my neighbors, who, I should have+prophesied, once for all, would never get to Boston by so prompt a+conveyance, are on hand when the bell rings. To do things “railroad+fashion” is now the by-word; and it is worth the while to be warned so+often and so sincerely by any power to get off its track. There is no+stopping to read the riot act, no firing over the heads of the mob, in+this case. We have constructed a fate, an _Atropos_, that never turns+aside. (Let that be the name of your engine.) Men are advertised that+at a certain hour and minute these bolts will be shot toward particular+points of the compass; yet it interferes with no man’s business, and+the children go to school on the other track. We live the steadier for+it. We are all educated thus to be sons of Tell. The air is full of+invisible bolts. Every path but your own is the path of fate. Keep on+your own track, then.++What recommends commerce to me is its enterprise and bravery. It does+not clasp its hands and pray to Jupiter. I see these men every day go+about their business with more or less courage and content, doing more+even than they suspect, and perchance better employed than they could+have consciously devised. I am less affected by their heroism who stood+up for half an hour in the front line at Buena Vista, than by the+steady and cheerful valor of the men who inhabit the snow-plough for+their winter quarters; who have not merely the three-o’-clock in the+morning courage, which Bonaparte thought was the rarest, but whose+courage does not go to rest so early, who go to sleep only when the+storm sleeps or the sinews of their iron steed are frozen. On this+morning of the Great Snow, perchance, which is still raging and+chilling men’s blood, I hear the muffled tone of their engine bell from+out the fog bank of their chilled breath, which announces that the cars+_are coming_, without long delay, notwithstanding the veto of a New+England north-east snow storm, and I behold the ploughmen covered with+snow and rime, their heads peering, above the mould-board which is+turning down other than daisies and the nests of field-mice, like+bowlders of the Sierra Nevada, that occupy an outside place in the+universe.++Commerce is unexpectedly confident and serene, alert, adventurous, and+unwearied. It is very natural in its methods withal, far more so than+many fantastic enterprises and sentimental experiments, and hence its+singular success. I am refreshed and expanded when the freight train+rattles past me, and I smell the stores which go dispensing their odors+all the way from Long Wharf to Lake Champlain, reminding me of foreign+parts, of coral reefs, and Indian oceans, and tropical climes, and the+extent of the globe. I feel more like a citizen of the world at the+sight of the palm-leaf which will cover so many flaxen New England+heads the next summer, the Manilla hemp and cocoa-nut husks, the old+junk, gunny bags, scrap iron, and rusty nails. This car-load of torn+sails is more legible and interesting now than if they should be+wrought into paper and printed books. Who can write so graphically the+history of the storms they have weathered as these rents have done?+They are proof-sheets which need no correction. Here goes lumber from+the Maine woods, which did not go out to sea in the last freshet, risen+four dollars on the thousand because of what did go out or was split+up; pine, spruce, cedar,—first, second, third, and fourth qualities, so+lately all of one quality, to wave over the bear, and moose, and+caribou. Next rolls Thomaston lime, a prime lot, which will get far+among the hills before it gets slacked. These rags in bales, of all+hues and qualities, the lowest condition to which cotton and linen+descend, the final result of dress,—of patterns which are now no longer+cried up, unless it be in Milwaukie, as those splendid articles,+English, French, or American prints, ginghams, muslins, &c., gathered+from all quarters both of fashion and poverty, going to become paper of+one color or a few shades only, on which forsooth will be written tales+of real life, high and low, and founded on fact! This closed car smells+of salt fish, the strong New England and commercial scent, reminding me+of the Grand Banks and the fisheries. Who has not seen a salt fish,+thoroughly cured for this world, so that nothing can spoil it, and+putting the perseverance of the saints to the blush? with which you may+sweep or pave the streets, and split your kindlings, and the teamster+shelter himself and his lading against sun wind and rain behind it,—and+the trader, as a Concord trader once did, hang it up by his door for a+sign when he commences business, until at last his oldest customer+cannot tell surely whether it be animal, vegetable, or mineral, and yet+it shall be as pure as a snowflake, and if it be put into a pot and+boiled, will come out an excellent dun fish for a Saturday’s dinner.+Next Spanish hides, with the tails still preserving their twist and the+angle of elevation they had when the oxen that wore them were careering+over the pampas of the Spanish main,—a type of all obstinacy, and+evincing how almost hopeless and incurable are all constitutional+vices. I confess, that practically speaking, when I have learned a+man’s real disposition, I have no hopes of changing it for the better+or worse in this state of existence. As the Orientals say, “A cur’s+tail may be warmed, and pressed, and bound round with ligatures, and+after a twelve years’ labor bestowed upon it, still it will retain its+natural form.” The only effectual cure for such inveteracies as these+tails exhibit is to make glue of them, which I believe is what is+usually done with them, and then they will stay put and stick. Here is+a hogshead of molasses or of brandy directed to John Smith,+Cuttingsville, Vermont, some trader among the Green Mountains, who+imports for the farmers near his clearing, and now perchance stands+over his bulk-head and thinks of the last arrivals on the coast, how+they may affect the price for him, telling his customers this moment,+as he has told them twenty times before this morning, that he expects+some by the next train of prime quality. It is advertised in the+Cuttingsville Times.++While these things go up other things come down. Warned by the whizzing+sound, I look up from my book and see some tall pine, hewn on far+northern hills, which has winged its way over the Green Mountains and+the Connecticut, shot like an arrow through the township within ten+minutes, and scarce another eye beholds it; going++ “to be the mast+ Of some great ammiral.”++And hark! here comes the cattle-train bearing the cattle of a thousand+hills, sheepcots, stables, and cow-yards in the air, drovers with their+sticks, and shepherd boys in the midst of their flocks, all but the+mountain pastures, whirled along like leaves blown from the mountains+by the September gales. The air is filled with the bleating of calves+and sheep, and the hustling of oxen, as if a pastoral valley were going+by. When the old bell-wether at the head rattles his bell, the+mountains do indeed skip like rams and the little hills like lambs. A+car-load of drovers, too, in the midst, on a level with their droves+now, their vocation gone, but still clinging to their useless sticks as+their badge of office. But their dogs, where are they? It is a stampede+to them; they are quite thrown out; they have lost the scent. Methinks+I hear them barking behind the Peterboro’ Hills, or panting up the+western slope of the Green Mountains. They will not be in at the death.+Their vocation, too, is gone. Their fidelity and sagacity are below par+now. They will slink back to their kennels in disgrace, or perchance+run wild and strike a league with the wolf and the fox. So is your+pastoral life whirled past and away. But the bell rings, and I must get+off the track and let the cars go by;—++ What’s the railroad to me?+ I never go to see+ Where it ends.+ It fills a few hollows,+ And makes banks for the swallows,+ It sets the sand a-blowing,+ And the blackberries a-growing,++but I cross it like a cart-path in the woods. I will not have my eyes+put out and my ears spoiled by its smoke and steam and hissing.++Now that the cars are gone by and all the restless world with them, and+the fishes in the pond no longer feel their rumbling, I am more alone+than ever. For the rest of the long afternoon, perhaps, my meditations+are interrupted only by the faint rattle of a carriage or team along+the distant highway.++Sometimes, on Sundays, I heard the bells, the Lincoln, Acton, Bedford,+or Concord bell, when the wind was favorable, a faint, sweet, and, as+it were, natural melody, worth importing into the wilderness. At a+sufficient distance over the woods this sound acquires a certain+vibratory hum, as if the pine needles in the horizon were the strings+of a harp which it swept. All sound heard at the greatest possible+distance produces one and the same effect, a vibration of the universal+lyre, just as the intervening atmosphere makes a distant ridge of earth+interesting to our eyes by the azure tint it imparts to it. There came+to me in this case a melody which the air had strained, and which had+conversed with every leaf and needle of the wood, that portion of the+sound which the elements had taken up and modulated and echoed from+vale to vale. The echo is, to some extent, an original sound, and+therein is the magic and charm of it. It is not merely a repetition of+what was worth repeating in the bell, but partly the voice of the wood;+the same trivial words and notes sung by a wood-nymph.++At evening, the distant lowing of some cow in the horizon beyond the+woods sounded sweet and melodious, and at first I would mistake it for+the voices of certain minstrels by whom I was sometimes serenaded, who+might be straying over hill and dale; but soon I was not unpleasantly+disappointed when it was prolonged into the cheap and natural music of+the cow. I do not mean to be satirical, but to express my appreciation+of those youths’ singing, when I state that I perceived clearly that it+was akin to the music of the cow, and they were at length one+articulation of Nature.++Regularly at half past seven, in one part of the summer, after the+evening train had gone by, the whippoorwills chanted their vespers for+half an hour, sitting on a stump by my door, or upon the ridge pole of+the house. They would begin to sing almost with as much precision as a+clock, within five minutes of a particular time, referred to the+setting of the sun, every evening. I had a rare opportunity to become+acquainted with their habits. Sometimes I heard four or five at once in+different parts of the wood, by accident one a bar behind another, and+so near me that I distinguished not only the cluck after each note, but+often that singular buzzing sound like a fly in a spider’s web, only+proportionally louder. Sometimes one would circle round and round me in+the woods a few feet distant as if tethered by a string, when probably+I was near its eggs. They sang at intervals throughout the night, and+were again as musical as ever just before and about dawn.++When other birds are still the screech owls take up the strain, like+mourning women their ancient u-lu-lu. Their dismal scream is truly Ben+Jonsonian. Wise midnight hags! It is no honest and blunt tu-whit tu-who+of the poets, but, without jesting, a most solemn graveyard ditty, the+mutual consolations of suicide lovers remembering the pangs and the+delights of supernal love in the infernal groves. Yet I love to hear+their wailing, their doleful responses, trilled along the wood-side;+reminding me sometimes of music and singing birds; as if it were the+dark and tearful side of music, the regrets and sighs that would fain+be sung. They are the spirits, the low spirits and melancholy+forebodings, of fallen souls that once in human shape night-walked the+earth and did the deeds of darkness, now expiating their sins with+their wailing hymns or threnodies in the scenery of their+transgressions. They give me a new sense of the variety and capacity of+that nature which is our common dwelling. _Oh-o-o-o-o that I never had+been bor-r-r-r-n!_ sighs one on this side of the pond, and circles with+the restlessness of despair to some new perch on the gray oaks.+Then—_that I never had been bor-r-r-r-n!_ echoes another on the farther+side with tremulous sincerity, and—_bor-r-r-r-n!_ comes faintly from+far in the Lincoln woods.++I was also serenaded by a hooting owl. Near at hand you could fancy it+the most melancholy sound in Nature, as if she meant by this to+stereotype and make permanent in her choir the dying moans of a human+being,—some poor weak relic of mortality who has left hope behind, and+howls like an animal, yet with human sobs, on entering the dark valley,+made more awful by a certain gurgling melodiousness,—I find myself+beginning with the letters gl when I try to imitate it,—expressive of a+mind which has reached the gelatinous mildewy stage in the+mortification of all healthy and courageous thought. It reminded me of+ghouls and idiots and insane howlings. But now one answers from far+woods in a strain made really melodious by distance,—_Hoo hoo hoo,+hoorer hoo_; and indeed for the most part it suggested only pleasing+associations, whether heard by day or night, summer or winter.++I rejoice that there are owls. Let them do the idiotic and maniacal+hooting for men. It is a sound admirably suited to swamps and twilight+woods which no day illustrates, suggesting a vast and undeveloped+nature which men have not recognized. They represent the stark twilight+and unsatisfied thoughts which all have. All day the sun has shone on+the surface of some savage swamp, where the single spruce stands hung+with usnea lichens, and small hawks circulate above, and the chickadee+lisps amid the evergreens, and the partridge and rabbit skulk beneath;+but now a more dismal and fitting day dawns, and a different race of+creatures awakes to express the meaning of Nature there.++Late in the evening I heard the distant rumbling of wagons over+bridges,—a sound heard farther than almost any other at night,—the+baying of dogs, and sometimes again the lowing of some disconsolate cow+in a distant barn-yard. In the mean while all the shore rang with the+trump of bullfrogs, the sturdy spirits of ancient wine-bibbers and+wassailers, still unrepentant, trying to sing a catch in their Stygian+lake,—if the Walden nymphs will pardon the comparison, for though there+are almost no weeds, there are frogs there,—who would fain keep up the+hilarious rules of their old festal tables, though their voices have+waxed hoarse and solemnly grave, mocking at mirth, and the wine has+lost its flavor, and become only liquor to distend their paunches, and+sweet intoxication never comes to drown the memory of the past, but+mere saturation and waterloggedness and distention. The most+aldermanic, with his chin upon a heart-leaf, which serves for a napkin+to his drooling chaps, under this northern shore quaffs a deep draught+of the once scorned water, and passes round the cup with the+ejaculation _tr-r-r-oonk, tr-r-r-oonk, tr-r-r-oonk!_ and straightway+comes over the water from some distant cove the same password repeated,+where the next in seniority and girth has gulped down to his mark; and+when this observance has made the circuit of the shores, then+ejaculates the master of ceremonies, with satisfaction, _tr-r-r-oonk!_+and each in his turn repeats the same down to the least distended,+leakiest, and flabbiest paunched, that there be no mistake; and then+the bowl goes round again and again, until the sun disperses the+morning mist, and only the patriarch is not under the pond, but vainly+bellowing _troonk_ from time to time, and pausing for a reply.++I am not sure that I ever heard the sound of cock-crowing from my+clearing, and I thought that it might be worth the while to keep a+cockerel for his music merely, as a singing bird. The note of this once+wild Indian pheasant is certainly the most remarkable of any bird’s,+and if they could be naturalized without being domesticated, it would+soon become the most famous sound in our woods, surpassing the clangor+of the goose and the hooting of the owl; and then imagine the cackling+of the hens to fill the pauses when their lords’ clarions rested! No+wonder that man added this bird to his tame stock,—to say nothing of+the eggs and drumsticks. To walk in a winter morning in a wood where+these birds abounded, their native woods, and hear the wild cockerels+crow on the trees, clear and shrill for miles over the resounding+earth, drowning the feebler notes of other birds,—think of it! It would+put nations on the alert. Who would not be early to rise, and rise+earlier and earlier every successive day of his life, till he became+unspeakably healthy, wealthy, and wise? This foreign bird’s note is+celebrated by the poets of all countries along with the notes of their+native songsters. All climates agree with brave Chanticleer. He is more+indigenous even than the natives. His health is ever good, his lungs+are sound, his spirits never flag. Even the sailor on the Atlantic and+Pacific is awakened by his voice; but its shrill sound never roused me+from my slumbers. I kept neither dog, cat, cow, pig, nor hens, so that+you would have said there was a deficiency of domestic sounds; neither+the churn, nor the spinning wheel, nor even the singing of the kettle,+nor the hissing of the urn, nor children crying, to comfort one. An+old-fashioned man would have lost his senses or died of ennui before+this. Not even rats in the wall, for they were starved out, or rather+were never baited in,—only squirrels on the roof and under the floor, a+whippoorwill on the ridge pole, a blue-jay screaming beneath the+window, a hare or woodchuck under the house, a screech-owl or a cat-owl+behind it, a flock of wild geese or a laughing loon on the pond, and a+fox to bark in the night. Not even a lark or an oriole, those mild+plantation birds, ever visited my clearing. No cockerels to crow nor+hens to cackle in the yard. No yard! but unfenced Nature reaching up to+your very sills. A young forest growing up under your meadows, and wild+sumachs and blackberry vines breaking through into your cellar; sturdy+pitch pines rubbing and creaking against the shingles for want of room,+their roots reaching quite under the house. Instead of a scuttle or a+blind blown off in the gale,—a pine tree snapped off or torn up by the+roots behind your house for fuel. Instead of no path to the front-yard+gate in the Great Snow,—no gate,—no front-yard,—and no path to the+civilized world!++Solitude++This is a delicious evening, when the whole body is one sense, and+imbibes delight through every pore. I go and come with a strange+liberty in Nature, a part of herself. As I walk along the stony shore+of the pond in my shirt sleeves, though it is cool as well as cloudy+and windy, and I see nothing special to attract me, all the elements+are unusually congenial to me. The bullfrogs trump to usher in the+night, and the note of the whippoorwill is borne on the rippling wind+from over the water. Sympathy with the fluttering alder and poplar+leaves almost takes away my breath; yet, like the lake, my serenity is+rippled but not ruffled. These small waves raised by the evening wind+are as remote from storm as the smooth reflecting surface. Though it is+now dark, the wind still blows and roars in the wood, the waves still+dash, and some creatures lull the rest with their notes. The repose is+never complete. The wildest animals do not repose, but seek their prey+now; the fox, and skunk, and rabbit, now roam the fields and woods+without fear. They are Nature’s watchmen,—links which connect the days+of animated life.++When I return to my house I find that visitors have been there and left+their cards, either a bunch of flowers, or a wreath of evergreen, or a+name in pencil on a yellow walnut leaf or a chip. They who come rarely+to the woods take some little piece of the forest into their hands to+play with by the way, which they leave, either intentionally or+accidentally. One has peeled a willow wand, woven it into a ring, and+dropped it on my table. I could always tell if visitors had called in+my absence, either by the bended twigs or grass, or the print of their+shoes, and generally of what sex or age or quality they were by some+slight trace left, as a flower dropped, or a bunch of grass plucked and+thrown away, even as far off as the railroad, half a mile distant, or+by the lingering odor of a cigar or pipe. Nay, I was frequently+notified of the passage of a traveller along the highway sixty rods off+by the scent of his pipe.++There is commonly sufficient space about us. Our horizon is never quite+at our elbows. The thick wood is not just at our door, nor the pond,+but somewhat is always clearing, familiar and worn by us, appropriated+and fenced in some way, and reclaimed from Nature. For what reason have+I this vast range and circuit, some square miles of unfrequented+forest, for my privacy, abandoned to me by men? My nearest neighbor is+a mile distant, and no house is visible from any place but the+hill-tops within half a mile of my own. I have my horizon bounded by+woods all to myself; a distant view of the railroad where it touches+the pond on the one hand, and of the fence which skirts the woodland+road on the other. But for the most part it is as solitary where I live+as on the prairies. It is as much Asia or Africa as New England. I+have, as it were, my own sun and moon and stars, and a little world all+to myself. At night there was never a traveller passed my house, or+knocked at my door, more than if I were the first or last man; unless+it were in the spring, when at long intervals some came from the+village to fish for pouts,—they plainly fished much more in the Walden+Pond of their own natures, and baited their hooks with darkness,—but+they soon retreated, usually with light baskets, and left “the world to+darkness and to me,” and the black kernel of the night was never+profaned by any human neighborhood. I believe that men are generally+still a little afraid of the dark, though the witches are all hung, and+Christianity and candles have been introduced.++Yet I experienced sometimes that the most sweet and tender, the most+innocent and encouraging society may be found in any natural object,+even for the poor misanthrope and most melancholy man. There can be no+very black melancholy to him who lives in the midst of Nature and has+his senses still. There was never yet such a storm but it was Æolian+music to a healthy and innocent ear. Nothing can rightly compel a+simple and brave man to a vulgar sadness. While I enjoy the friendship+of the seasons I trust that nothing can make life a burden to me. The+gentle rain which waters my beans and keeps me in the house to-day is+not drear and melancholy, but good for me too. Though it prevents my+hoeing them, it is of far more worth than my hoeing. If it should+continue so long as to cause the seeds to rot in the ground and destroy+the potatoes in the low lands, it would still be good for the grass on+the uplands, and, being good for the grass, it would be good for me.+Sometimes, when I compare myself with other men, it seems as if I were+more favored by the gods than they, beyond any deserts that I am+conscious of; as if I had a warrant and surety at their hands which my+fellows have not, and were especially guided and guarded. I do not+flatter myself, but if it be possible they flatter me. I have never+felt lonesome, or in the least oppressed by a sense of solitude, but+once, and that was a few weeks after I came to the woods, when, for an+hour, I doubted if the near neighborhood of man was not essential to a+serene and healthy life. To be alone was something unpleasant. But I+was at the same time conscious of a slight insanity in my mood, and+seemed to foresee my recovery. In the midst of a gentle rain while+these thoughts prevailed, I was suddenly sensible of such sweet and+beneficent society in Nature, in the very pattering of the drops, and+in every sound and sight around my house, an infinite and unaccountable+friendliness all at once like an atmosphere sustaining me, as made the+fancied advantages of human neighborhood insignificant, and I have+never thought of them since. Every little pine needle expanded and+swelled with sympathy and befriended me. I was so distinctly made aware+of the presence of something kindred to me, even in scenes which we are+accustomed to call wild and dreary, and also that the nearest of blood+to me and humanest was not a person nor a villager, that I thought no+place could ever be strange to me again.—++ “Mourning untimely consumes the sad;+ Few are their days in the land of the living,+ Beautiful daughter of Toscar.”++Some of my pleasantest hours were during the long rain storms in the+spring or fall, which confined me to the house for the afternoon as+well as the forenoon, soothed by their ceaseless roar and pelting; when+an early twilight ushered in a long evening in which many thoughts had+time to take root and unfold themselves. In those driving north-east+rains which tried the village houses so, when the maids stood ready+with mop and pail in front entries to keep the deluge out, I sat behind+my door in my little house, which was all entry, and thoroughly enjoyed+its protection. In one heavy thunder shower the lightning struck a+large pitch-pine across the pond, making a very conspicuous and+perfectly regular spiral groove from top to bottom, an inch or more+deep, and four or five inches wide, as you would groove a+walking-stick. I passed it again the other day, and was struck with awe+on looking up and beholding that mark, now more distinct than ever,+where a terrific and resistless bolt came down out of the harmless sky+eight years ago. Men frequently say to me, “I should think you would+feel lonesome down there, and want to be nearer to folks, rainy and+snowy days and nights especially.” I am tempted to reply to such,—This+whole earth which we inhabit is but a point in space. How far apart,+think you, dwell the two most distant inhabitants of yonder star, the+breadth of whose disk cannot be appreciated by our instruments? Why+should I feel lonely? is not our planet in the Milky Way? This which+you put seems to me not to be the most important question. What sort of+space is that which separates a man from his fellows and makes him+solitary? I have found that no exertion of the legs can bring two minds+much nearer to one another. What do we want most to dwell near to? Not+to many men surely, the depot, the post-office, the bar-room, the+meeting-house, the school-house, the grocery, Beacon Hill, or the Five+Points, where men most congregate, but to the perennial source of our+life, whence in all our experience we have found that to issue, as the+willow stands near the water and sends out its roots in that direction.+This will vary with different natures, but this is the place where a+wise man will dig his cellar.... I one evening overtook one of my+townsmen, who has accumulated what is called “a handsome+property,”—though I never got a _fair_ view of it,—on the Walden road,+driving a pair of cattle to market, who inquired of me how I could+bring my mind to give up so many of the comforts of life. I answered+that I was very sure I liked it passably well; I was not joking. And so+I went home to my bed, and left him to pick his way through the+darkness and the mud to Brighton,—or Bright-town,—which place he would+reach some time in the morning.++Any prospect of awakening or coming to life to a dead man makes+indifferent all times and places. The place where that may occur is+always the same, and indescribably pleasant to all our senses. For the+most part we allow only outlying and transient circumstances to make+our occasions. They are, in fact, the cause of our distraction. Nearest+to all things is that power which fashions their being. _Next_ to us+the grandest laws are continually being executed. _Next_ to us is not+the workman whom we have hired, with whom we love so well to talk, but+the workman whose work we are.++“How vast and profound is the influence of the subtile powers of Heaven+and of Earth!”++“We seek to perceive them, and we do not see them; we seek to hear+them, and we do not hear them; identified with the substance of things,+they cannot be separated from them.”++“They cause that in all the universe men purify and sanctify their+hearts, and clothe themselves in their holiday garments to offer+sacrifices and oblations to their ancestors. It is an ocean of subtile+intelligences. They are every where, above us, on our left, on our+right; they environ us on all sides.”++We are the subjects of an experiment which is not a little interesting+to me. Can we not do without the society of our gossips a little while+under these circumstances,—have our own thoughts to cheer us? Confucius+says truly, “Virtue does not remain as an abandoned orphan; it must of+necessity have neighbors.”++With thinking we may be beside ourselves in a sane sense. By a+conscious effort of the mind we can stand aloof from actions and their+consequences; and all things, good and bad, go by us like a torrent. We+are not wholly involved in Nature. I may be either the drift-wood in+the stream, or Indra in the sky looking down on it. I _may_ be affected+by a theatrical exhibition; on the other hand, I _may not_ be affected+by an actual event which appears to concern me much more. I only know+myself as a human entity; the scene, so to speak, of thoughts and+affections; and am sensible of a certain doubleness by which I can+stand as remote from myself as from another. However intense my+experience, I am conscious of the presence and criticism of a part of+me, which, as it were, is not a part of me, but spectator, sharing no+experience, but taking note of it; and that is no more I than it is+you. When the play, it may be the tragedy, of life is over, the+spectator goes his way. It was a kind of fiction, a work of the+imagination only, so far as he was concerned. This doubleness may+easily make us poor neighbors and friends sometimes.++I find it wholesome to be alone the greater part of the time. To be in+company, even with the best, is soon wearisome and dissipating. I love+to be alone. I never found the companion that was so companionable as+solitude. We are for the most part more lonely when we go abroad among+men than when we stay in our chambers. A man thinking or working is+always alone, let him be where he will. Solitude is not measured by the+miles of space that intervene between a man and his fellows. The really+diligent student in one of the crowded hives of Cambridge College is as+solitary as a dervish in the desert. The farmer can work alone in the+field or the woods all day, hoeing or chopping, and not feel lonesome,+because he is employed; but when he comes home at night he cannot sit+down in a room alone, at the mercy of his thoughts, but must be where+he can “see the folks,” and recreate, and as he thinks remunerate+himself for his day’s solitude; and hence he wonders how the student+can sit alone in the house all night and most of the day without ennui+and “the blues;” but he does not realize that the student, though in+the house, is still at work in _his_ field, and chopping in _his_+woods, as the farmer in his, and in turn seeks the same recreation and+society that the latter does, though it may be a more condensed form of+it.++Society is commonly too cheap. We meet at very short intervals, not+having had time to acquire any new value for each other. We meet at+meals three times a day, and give each other a new taste of that old+musty cheese that we are. We have had to agree on a certain set of+rules, called etiquette and politeness, to make this frequent meeting+tolerable and that we need not come to open war. We meet at the+post-office, and at the sociable, and about the fireside every night;+we live thick and are in each other’s way, and stumble over one+another, and I think that we thus lose some respect for one another.+Certainly less frequency would suffice for all important and hearty+communications. Consider the girls in a factory,—never alone, hardly in+their dreams. It would be better if there were but one inhabitant to a+square mile, as where I live. The value of a man is not in his skin,+that we should touch him.++I have heard of a man lost in the woods and dying of famine and+exhaustion at the foot of a tree, whose loneliness was relieved by the+grotesque visions with which, owing to bodily weakness, his diseased+imagination surrounded him, and which he believed to be real. So also,+owing to bodily and mental health and strength, we may be continually+cheered by a like but more normal and natural society, and come to know+that we are never alone.++I have a great deal of company in my house; especially in the morning,+when nobody calls. Let me suggest a few comparisons, that some one may+convey an idea of my situation. I am no more lonely than the loon in+the pond that laughs so loud, or than Walden Pond itself. What company+has that lonely lake, I pray? And yet it has not the blue devils, but+the blue angels in it, in the azure tint of its waters. The sun is+alone, except in thick weather, when there sometimes appear to be two,+but one is a mock sun. God is alone,—but the devil, he is far from+being alone; he sees a great deal of company; he is legion. I am no+more lonely than a single mullein or dandelion in a pasture, or a bean+leaf, or sorrel, or a horse-fly, or a bumble-bee. I am no more lonely+than the Mill Brook, or a weathercock, or the north star, or the south+wind, or an April shower, or a January thaw, or the first spider in a+new house.++I have occasional visits in the long winter evenings, when the snow+falls fast and the wind howls in the wood, from an old settler and+original proprietor, who is reported to have dug Walden Pond, and+stoned it, and fringed it with pine woods; who tells me stories of old+time and of new eternity; and between us we manage to pass a cheerful+evening with social mirth and pleasant views of things, even without+apples or cider,—a most wise and humorous friend, whom I love much, who+keeps himself more secret than ever did Goffe or Whalley; and though he+is thought to be dead, none can show where he is buried. An elderly+dame, too, dwells in my neighborhood, invisible to most persons, in+whose odorous herb garden I love to stroll sometimes, gathering simples+and listening to her fables; for she has a genius of unequalled+fertility, and her memory runs back farther than mythology, and she can+tell me the original of every fable, and on what fact every one is+founded, for the incidents occurred when she was young. A ruddy and+lusty old dame, who delights in all weathers and seasons, and is likely+to outlive all her children yet.++The indescribable innocence and beneficence of Nature,—of sun and wind+and rain, of summer and winter,—such health, such cheer, they afford+forever! and such sympathy have they ever with our race, that all+Nature would be affected, and the sun’s brightness fade, and the winds+would sigh humanely, and the clouds rain tears, and the woods shed+their leaves and put on mourning in midsummer, if any man should ever+for a just cause grieve. Shall I not have intelligence with the earth?+Am I not partly leaves and vegetable mould myself?++What is the pill which will keep us well, serene, contented? Not my or+thy great-grandfather’s, but our great-grandmother Nature’s universal,+vegetable, botanic medicines, by which she has kept herself young+always, outlived so many old Parrs in her day, and fed her health with+their decaying fatness. For my panacea, instead of one of those quack+vials of a mixture dipped from Acheron and the Dead Sea, which come out+of those long shallow black-schooner looking wagons which we sometimes+see made to carry bottles, let me have a draught of undiluted morning+air. Morning air! If men will not drink of this at the fountain-head of+the day, why, then, we must even bottle up some and sell it in the+shops, for the benefit of those who have lost their subscription ticket+to morning time in this world. But remember, it will not keep quite+till noon-day even in the coolest cellar, but drive out the stopples+long ere that and follow westward the steps of Aurora. I am no+worshipper of Hygeia, who was the daughter of that old herb-doctor+Æsculapius, and who is represented on monuments holding a serpent in+one hand, and in the other a cup out of which the serpent sometimes+drinks; but rather of Hebe, cupbearer to Jupiter, who was the daughter+of Juno and wild lettuce, and who had the power of restoring gods and+men to the vigor of youth. She was probably the only thoroughly+sound-conditioned, healthy, and robust young lady that ever walked the+globe, and wherever she came it was spring.++Visitors++I think that I love society as much as most, and am ready enough to+fasten myself like a bloodsucker for the time to any full-blooded man+that comes in my way. I am naturally no hermit, but might possibly sit+out the sturdiest frequenter of the bar-room, if my business called me+thither.++I had three chairs in my house; one for solitude, two for friendship,+three for society. When visitors came in larger and unexpected numbers+there was but the third chair for them all, but they generally+economized the room by standing up. It is surprising how many great men+and women a small house will contain. I have had twenty-five or thirty+souls, with their bodies, at once under my roof, and yet we often+parted without being aware that we had come very near to one another.+Many of our houses, both public and private, with their almost+innumerable apartments, their huge halls and their cellars for the+storage of wines and other munitions of peace, appear to me+extravagantly large for their inhabitants. They are so vast and+magnificent that the latter seem to be only vermin which infest them. I+am surprised when the herald blows his summons before some Tremont or+Astor or Middlesex House, to see come creeping out over the piazza for+all inhabitants a ridiculous mouse, which soon again slinks into some+hole in the pavement.++One inconvenience I sometimes experienced in so small a house, the+difficulty of getting to a sufficient distance from my guest when we+began to utter the big thoughts in big words. You want room for your+thoughts to get into sailing trim and run a course or two before they+make their port. The bullet of your thought must have overcome its+lateral and ricochet motion and fallen into its last and steady course+before it reaches the ear of the hearer, else it may plough out again+through the side of his head. Also, our sentences wanted room to unfold+and form their columns in the interval. Individuals, like nations, must+have suitable broad and natural boundaries, even a considerable neutral+ground, between them. I have found it a singular luxury to talk across+the pond to a companion on the opposite side. In my house we were so+near that we could not begin to hear,—we could not speak low enough to+be heard; as when you throw two stones into calm water so near that+they break each other’s undulations. If we are merely loquacious and+loud talkers, then we can afford to stand very near together, cheek by+jowl, and feel each other’s breath; but if we speak reservedly and+thoughtfully, we want to be farther apart, that all animal heat and+moisture may have a chance to evaporate. If we would enjoy the most+intimate society with that in each of us which is without, or above,+being spoken to, we must not only be silent, but commonly so far apart+bodily that we cannot possibly hear each other’s voice in any case.+Referred to this standard, speech is for the convenience of those who+are hard of hearing; but there are many fine things which we cannot say+if we have to shout. As the conversation began to assume a loftier and+grander tone, we gradually shoved our chairs farther apart till they+touched the wall in opposite corners, and then commonly there was not+room enough.++My “best” room, however, my withdrawing room, always ready for company,+on whose carpet the sun rarely fell, was the pine wood behind my house.+Thither in summer days, when distinguished guests came, I took them,+and a priceless domestic swept the floor and dusted the furniture and+kept the things in order.++If one guest came he sometimes partook of my frugal meal, and it was no+interruption to conversation to be stirring a hasty-pudding, or+watching the rising and maturing of a loaf of bread in the ashes, in+the mean while. But if twenty came and sat in my house there was+nothing said about dinner, though there might be bread enough for two,+more than if eating were a forsaken habit; but we naturally practised+abstinence; and this was never felt to be an offence against+hospitality, but the most proper and considerate course. The waste and+decay of physical life, which so often needs repair, seemed+miraculously retarded in such a case, and the vital vigor stood its+ground. I could entertain thus a thousand as well as twenty; and if any+ever went away disappointed or hungry from my house when they found me+at home, they may depend upon it that I sympathized with them at least.+So easy is it, though many housekeepers doubt it, to establish new and+better customs in the place of the old. You need not rest your+reputation on the dinners you give. For my own part, I was never so+effectually deterred from frequenting a man’s house, by any kind of+Cerberus whatever, as by the parade one made about dining me, which I+took to be a very polite and roundabout hint never to trouble him so+again. I think I shall never revisit those scenes. I should be proud to+have for the motto of my cabin those lines of Spenser which one of my+visitors inscribed on a yellow walnut leaf for a card:—++ “Arrivéd there, the little house they fill,+ Ne looke for entertainment where none was;+ Rest is their feast, and all things at their will:+ The noblest mind the best contentment has.”++When Winslow, afterward governor of the Plymouth Colony, went with a+companion on a visit of ceremony to Massasoit on foot through the+woods, and arrived tired and hungry at his lodge, they were well+received by the king, but nothing was said about eating that day. When+the night arrived, to quote their own words,—“He laid us on the bed+with himself and his wife, they at the one end and we at the other, it+being only planks laid a foot from the ground, and a thin mat upon+them. Two more of his chief men, for want of room, pressed by and upon+us; so that we were worse weary of our lodging than of our journey.” At+one o’clock the next day Massasoit “brought two fishes that he had+shot,” about thrice as big as a bream; “these being boiled, there were+at least forty looked for a share in them. The most ate of them. This+meal only we had in two nights and a day; and had not one of us bought+a partridge, we had taken our journey fasting.” Fearing that they would+be light-headed for want of food and also sleep, owing to “the savages’+barbarous singing, (for they used to sing themselves asleep,)” and that+they might get home while they had strength to travel, they departed.+As for lodging, it is true they were but poorly entertained, though+what they found an inconvenience was no doubt intended for an honor;+but as far as eating was concerned, I do not see how the Indians could+have done better. They had nothing to eat themselves, and they were+wiser than to think that apologies could supply the place of food to+their guests; so they drew their belts tighter and said nothing about+it. Another time when Winslow visited them, it being a season of plenty+with them, there was no deficiency in this respect.++As for men, they will hardly fail one any where. I had more visitors+while I lived in the woods than at any other period in my life; I mean+that I had some. I met several there under more favorable circumstances+than I could any where else. But fewer came to see me on trivial+business. In this respect, my company was winnowed by my mere distance+from town. I had withdrawn so far within the great ocean of solitude,+into which the rivers of society empty, that for the most part, so far+as my needs were concerned, only the finest sediment was deposited+around me. Beside, there were wafted to me evidences of unexplored and+uncultivated continents on the other side.++Who should come to my lodge this morning but a true Homeric or+Paphlagonian man,—he had so suitable and poetic a name that I am sorry+I cannot print it here,—a Canadian, a woodchopper and post-maker, who+can hole fifty posts in a day, who made his last supper on a woodchuck+which his dog caught. He, too, has heard of Homer, and, “if it were not+for books,” would “not know what to do rainy days,” though perhaps he+has not read one wholly through for many rainy seasons. Some priest who+could pronounce the Greek itself taught him to read his verse in the+testament in his native parish far away; and now I must translate to+him, while he holds the book, Achilles’ reproof to Patroclus for his+sad countenance.—“Why are you in tears, Patroclus, like a young girl?”—++ “Or have you alone heard some news from Phthia?+ They say that Menœtius lives yet, son of Actor,+ And Peleus lives, son of Æacus, among the Myrmidons,+ Either of whom having died, we should greatly grieve.”++He says, “That’s good.” He has a great bundle of white-oak bark under+his arm for a sick man, gathered this Sunday morning. “I suppose+there’s no harm in going after such a thing to-day,” says he. To him+Homer was a great writer, though what his writing was about he did not+know. A more simple and natural man it would be hard to find. Vice and+disease, which cast such a sombre moral hue over the world, seemed to+have hardly any existence for him. He was about twenty-eight years old,+and had left Canada and his father’s house a dozen years before to work+in the States, and earn money to buy a farm with at last, perhaps in+his native country. He was cast in the coarsest mould; a stout but+sluggish body, yet gracefully carried, with a thick sunburnt neck, dark+bushy hair, and dull sleepy blue eyes, which were occasionally lit up+with expression. He wore a flat gray cloth cap, a dingy wool-colored+greatcoat, and cowhide boots. He was a great consumer of meat, usually+carrying his dinner to his work a couple of miles past my house,—for he+chopped all summer,—in a tin pail; cold meats, often cold woodchucks,+and coffee in a stone bottle which dangled by a string from his belt;+and sometimes he offered me a drink. He came along early, crossing my+bean-field, though without anxiety or haste to get to his work, such as+Yankees exhibit. He wasn’t a-going to hurt himself. He didn’t care if+he only earned his board. Frequently he would leave his dinner in the+bushes, when his dog had caught a woodchuck by the way, and go back a+mile and a half to dress it and leave it in the cellar of the house+where he boarded, after deliberating first for half an hour whether he+could not sink it in the pond safely till nightfall,—loving to dwell+long upon these themes. He would say, as he went by in the morning,+“How thick the pigeons are! If working every day were not my trade, I+could get all the meat I should want by hunting,—pigeons, woodchucks,+rabbits, partridges,—by gosh! I could get all I should want for a week+in one day.”++He was a skilful chopper, and indulged in some flourishes and ornaments+in his art. He cut his trees level and close to the ground, that the+sprouts which came up afterward might be more vigorous and a sled might+slide over the stumps; and instead of leaving a whole tree to support+his corded wood, he would pare it away to a slender stake or splinter+which you could break off with your hand at last.++He interested me because he was so quiet and solitary and so happy+withal; a well of good humor and contentment which overflowed at his+eyes. His mirth was without alloy. Sometimes I saw him at his work in+the woods, felling trees, and he would greet me with a laugh of+inexpressible satisfaction, and a salutation in Canadian French, though+he spoke English as well. When I approached him he would suspend his+work, and with half-suppressed mirth lie along the trunk of a pine+which he had felled, and, peeling off the inner bark, roll it up into a+ball and chew it while he laughed and talked. Such an exuberance of+animal spirits had he that he sometimes tumbled down and rolled on the+ground with laughter at any thing which made him think and tickled him.+Looking round upon the trees he would exclaim,—“By George! I can enjoy+myself well enough here chopping; I want no better sport.” Sometimes,+when at leisure, he amused himself all day in the woods with a pocket+pistol, firing salutes to himself at regular intervals as he walked. In+the winter he had a fire by which at noon he warmed his coffee in a+kettle; and as he sat on a log to eat his dinner the chickadees would+sometimes come round and alight on his arm and peck at the potato in+his fingers; and he said that he “liked to have the little _fellers_+about him.”++In him the animal man chiefly was developed. In physical endurance and+contentment he was cousin to the pine and the rock. I asked him once if+he was not sometimes tired at night, after working all day; and he+answered, with a sincere and serious look, “Gorrappit, I never was+tired in my life.” But the intellectual and what is called spiritual+man in him were slumbering as in an infant. He had been instructed only+in that innocent and ineffectual way in which the Catholic priests+teach the aborigines, by which the pupil is never educated to the+degree of consciousness, but only to the degree of trust and reverence,+and a child is not made a man, but kept a child. When Nature made him,+she gave him a strong body and contentment for his portion, and propped+him on every side with reverence and reliance, that he might live out+his threescore years and ten a child. He was so genuine and+unsophisticated that no introduction would serve to introduce him, more+than if you introduced a woodchuck to your neighbor. He had got to find+him out as you did. He would not play any part. Men paid him wages for+work, and so helped to feed and clothe him; but he never exchanged+opinions with them. He was so simply and naturally humble—if he can be+called humble who never aspires—that humility was no distinct quality+in him, nor could he conceive of it. Wiser men were demigods to him. If+you told him that such a one was coming, he did as if he thought that+any thing so grand would expect nothing of himself, but take all the+responsibility on itself, and let him be forgotten still. He never+heard the sound of praise. He particularly reverenced the writer and+the preacher. Their performances were miracles. When I told him that I+wrote considerably, he thought for a long time that it was merely the+handwriting which I meant, for he could write a remarkably good hand+himself. I sometimes found the name of his native parish handsomely+written in the snow by the highway, with the proper French accent, and+knew that he had passed. I asked him if he ever wished to write his+thoughts. He said that he had read and written letters for those who+could not, but he never tried to write thoughts,—no, he could not, he+could not tell what to put first, it would kill him, and then there was+spelling to be attended to at the same time!++I heard that a distinguished wise man and reformer asked him if he did+not want the world to be changed; but he answered with a chuckle of+surprise in his Canadian accent, not knowing that the question had ever+been entertained before, “No, I like it well enough.” It would have+suggested many things to a philosopher to have dealings with him. To a+stranger he appeared to know nothing of things in general; yet I+sometimes saw in him a man whom I had not seen before, and I did not+know whether he was as wise as Shakespeare or as simply ignorant as a+child, whether to suspect him of a fine poetic consciousness or of+stupidity. A townsman told me that when he met him sauntering through+the village in his small close-fitting cap, and whistling to himself,+he reminded him of a prince in disguise.++His only books were an almanac and an arithmetic, in which last he was+considerably expert. The former was a sort of cyclopædia to him, which+he supposed to contain an abstract of human knowledge, as indeed it+does to a considerable extent. I loved to sound him on the various+reforms of the day, and he never failed to look at them in the most+simple and practical light. He had never heard of such things before.+Could he do without factories? I asked. He had worn the home-made+Vermont gray, he said, and that was good. Could he dispense with tea+and coffee? Did this country afford any beverage beside water? He had+soaked hemlock leaves in water and drank it, and thought that was+better than water in warm weather. When I asked him if he could do+without money, he showed the convenience of money in such a way as to+suggest and coincide with the most philosophical accounts of the origin+of this institution, and the very derivation of the word _pecunia_. If+an ox were his property, and he wished to get needles and thread at the+store, he thought it would be inconvenient and impossible soon to go on+mortgaging some portion of the creature each time to that amount. He+could defend many institutions better than any philosopher, because, in+describing them as they concerned him, he gave the true reason for+their prevalence, and speculation had not suggested to him any other.+At another time, hearing Plato’s definition of a man,—a biped without+feathers,—and that one exhibited a cock plucked and called it Plato’s+man, he thought it an important difference that the _knees_ bent the+wrong way. He would sometimes exclaim, “How I love to talk! By George,+I could talk all day!” I asked him once, when I had not seen him for+many months, if he had got a new idea this summer. “Good Lord,” said+he, “a man that has to work as I do, if he does not forget the ideas he+has had, he will do well. May be the man you hoe with is inclined to+race; then, by gorry, your mind must be there; you think of weeds.” He+would sometimes ask me first on such occasions, if I had made any+improvement. One winter day I asked him if he was always satisfied with+himself, wishing to suggest a substitute within him for the priest+without, and some higher motive for living. “Satisfied!” said he; “some+men are satisfied with one thing, and some with another. One man,+perhaps, if he has got enough, will be satisfied to sit all day with+his back to the fire and his belly to the table, by George!” Yet I+never, by any manœuvring, could get him to take the spiritual view of+things; the highest that he appeared to conceive of was a simple+expediency, such as you might expect an animal to appreciate; and this,+practically, is true of most men. If I suggested any improvement in his+mode of life, he merely answered, without expressing any regret, that+it was too late. Yet he thoroughly believed in honesty and the like+virtues.++There was a certain positive originality, however slight, to be+detected in him, and I occasionally observed that he was thinking for+himself and expressing his own opinion, a phenomenon so rare that I+would any day walk ten miles to observe it, and it amounted to the+re-origination of many of the institutions of society. Though he+hesitated, and perhaps failed to express himself distinctly, he always+had a presentable thought behind. Yet his thinking was so primitive and+immersed in his animal life, that, though more promising than a merely+learned man’s, it rarely ripened to any thing which can be reported. He+suggested that there might be men of genius in the lowest grades of+life, however permanently humble and illiterate, who take their own+view always, or do not pretend to see at all; who are as bottomless+even as Walden Pond was thought to be, though they may be dark and+muddy.++Many a traveller came out of his way to see me and the inside of my+house, and, as an excuse for calling, asked for a glass of water. I+told them that I drank at the pond, and pointed thither, offering to+lend them a dipper. Far off as I lived, I was not exempted from the+annual visitation which occurs, methinks, about the first of April,+when every body is on the move; and I had my share of good luck, though+there were some curious specimens among my visitors. Half-witted men+from the almshouse and elsewhere came to see me; but I endeavored to+make them exercise all the wit they had, and make their confessions to+me; in such cases making wit the theme of our conversation; and so was+compensated. Indeed, I found some of them to be wiser than the so+called _overseers_ of the poor and selectmen of the town, and thought+it was time that the tables were turned. With respect to wit, I learned+that there was not much difference between the half and the whole. One+day, in particular, an inoffensive, simple-minded pauper, whom with+others I had often seen used as fencing stuff, standing or sitting on a+bushel in the fields to keep cattle and himself from straying, visited+me, and expressed a wish to live as I did. He told me, with the utmost+simplicity and truth, quite superior, or rather _inferior_, to any+thing that is called humility, that he was “deficient in intellect.”+These were his words. The Lord had made him so, yet he supposed the+Lord cared as much for him as for another. “I have always been so,”+said he, “from my childhood; I never had much mind; I was not like+other children; I am weak in the head. It was the Lord’s will, I+suppose.” And there he was to prove the truth of his words. He was a+metaphysical puzzle to me. I have rarely met a fellow-man on such+promising ground,—it was so simple and sincere and so true all that he+said. And, true enough, in proportion as he appeared to humble himself+was he exalted. I did not know at first but it was the result of a wise+policy. It seemed that from such a basis of truth and frankness as the+poor weak-headed pauper had laid, our intercourse might go forward to+something better than the intercourse of sages.++I had some guests from those not reckoned commonly among the town’s+poor, but who should be; who are among the world’s poor, at any rate;+guests who appeal, not to your hospitality, but to your+_hospitalality_; who earnestly wish to be helped, and preface their+appeal with the information that they are resolved, for one thing,+never to help themselves. I require of a visitor that he be not+actually starving, though he may have the very best appetite in the+world, however he got it. Objects of charity are not guests. Men who+did not know when their visit had terminated, though I went about my+business again, answering them from greater and greater remoteness. Men+of almost every degree of wit called on me in the migrating season.+Some who had more wits than they knew what to do with; runaway slaves+with plantation manners, who listened from time to time, like the fox+in the fable, as if they heard the hounds a-baying on their track, and+looked at me beseechingly, as much as to say,—++ “O Christian, will you send me back?”++One real runaway slave, among the rest, whom I helped to forward toward+the northstar. Men of one idea, like a hen with one chicken, and that a+duckling; men of a thousand ideas, and unkempt heads, like those hens+which are made to take charge of a hundred chickens, all in pursuit of+one bug, a score of them lost in every morning’s dew,—and become+frizzled and mangy in consequence; men of ideas instead of legs, a sort+of intellectual centipede that made you crawl all over. One man+proposed a book in which visitors should write their names, as at the+White Mountains; but, alas! I have too good a memory to make that+necessary.++I could not but notice some of the peculiarities of my visitors. Girls+and boys and young women generally seemed glad to be in the woods. They+looked in the pond and at the flowers, and improved their time. Men of+business, even farmers, thought only of solitude and employment, and of+the great distance at which I dwelt from something or other; and though+they said that they loved a ramble in the woods occasionally, it was+obvious that they did not. Restless committed men, whose time was all+taken up in getting a living or keeping it; ministers who spoke of God+as if they enjoyed a monopoly of the subject, who could not bear all+kinds of opinions; doctors, lawyers, uneasy housekeepers who pried into+my cupboard and bed when I was out,—how came Mrs. —— to know that my+sheets were not as clean as hers?—young men who had ceased to be young,+and had concluded that it was safest to follow the beaten track of the+professions,—all these generally said that it was not possible to do so+much good in my position. Ay! there was the rub. The old and infirm and+the timid, of whatever age or sex, thought most of sickness, and sudden+accident and death; to them life seemed full of danger,—what danger is+there if you don’t think of any?—and they thought that a prudent man+would carefully select the safest position, where Dr. B. might be on+hand at a moment’s warning. To them the village was literally a+_com-munity_, a league for mutual defence, and you would suppose that+they would not go a-huckleberrying without a medicine chest. The amount+of it is, if a man is alive, there is always _danger_ that he may die,+though the danger must be allowed to be less in proportion as he is+dead-and-alive to begin with. A man sits as many risks as he runs.+Finally, there were the self-styled reformers, the greatest bores of+all, who thought that I was forever singing,—++ This is the house that I built;+ This is the man that lives in the house that I built;++but they did not know that the third line was,—++ These are the folks that worry the man+ That lives in the house that I built.++I did not fear the hen-harriers, for I kept no chickens; but I feared+the men-harriers rather.++I had more cheering visitors than the last. Children come a-berrying,+railroad men taking a Sunday morning walk in clean shirts, fishermen+and hunters, poets and philosophers; in short, all honest pilgrims, who+came out to the woods for freedom’s sake, and really left the village+behind, I was ready to greet with,—“Welcome, Englishmen! welcome,+Englishmen!” for I had had communication with that race.++The Bean-Field++Meanwhile my beans, the length of whose rows, added together, was seven+miles already planted, were impatient to be hoed, for the earliest had+grown considerably before the latest were in the ground; indeed they+were not easily to be put off. What was the meaning of this so steady+and self-respecting, this small Herculean labor, I knew not. I came to+love my rows, my beans, though so many more than I wanted. They+attached me to the earth, and so I got strength like Antæus. But why+should I raise them? Only Heaven knows. This was my curious labor all+summer,—to make this portion of the earth’s surface, which had yielded+only cinquefoil, blackberries, johnswort, and the like, before, sweet+wild fruits and pleasant flowers, produce instead this pulse. What+shall I learn of beans or beans of me? I cherish them, I hoe them,+early and late I have an eye to them; and this is my day’s work. It is+a fine broad leaf to look on. My auxiliaries are the dews and rains+which water this dry soil, and what fertility is in the soil itself,+which for the most part is lean and effete. My enemies are worms, cool+days, and most of all woodchucks. The last have nibbled for me a+quarter of an acre clean. But what right had I to oust johnswort and+the rest, and break up their ancient herb garden? Soon, however, the+remaining beans will be too tough for them, and go forward to meet new+foes.++When I was four years old, as I well remember, I was brought from+Boston to this my native town, through these very woods and this field,+to the pond. It is one of the oldest scenes stamped on my memory. And+now to-night my flute has waked the echoes over that very water. The+pines still stand here older than I; or, if some have fallen, I have+cooked my supper with their stumps, and a new growth is rising all+around, preparing another aspect for new infant eyes. Almost the same+johnswort springs from the same perennial root in this pasture, and+even I have at length helped to clothe that fabulous landscape of my+infant dreams, and one of the results of my presence and influence is+seen in these bean leaves, corn blades, and potato vines.++I planted about two acres and a half of upland; and as it was only+about fifteen years since the land was cleared, and I myself had got+out two or three cords of stumps, I did not give it any manure; but in+the course of the summer it appeared by the arrowheads which I turned+up in hoeing, that an extinct nation had anciently dwelt here and+planted corn and beans ere white men came to clear the land, and so, to+some extent, had exhausted the soil for this very crop.++Before yet any woodchuck or squirrel had run across the road, or the+sun had got above the shrub oaks, while all the dew was on, though the+farmers warned me against it,—I would advise you to do all your work if+possible while the dew is on,—I began to level the ranks of haughty+weeds in my bean-field and throw dust upon their heads. Early in the+morning I worked barefooted, dabbling like a plastic artist in the dewy+and crumbling sand, but later in the day the sun blistered my feet.+There the sun lighted me to hoe beans, pacing slowly backward and+forward over that yellow gravelly upland, between the long green rows,+fifteen rods, the one end terminating in a shrub oak copse where I+could rest in the shade, the other in a blackberry field where the+green berries deepened their tints by the time I had made another bout.+Removing the weeds, putting fresh soil about the bean stems, and+encouraging this weed which I had sown, making the yellow soil express+its summer thought in bean leaves and blossoms rather than in wormwood+and piper and millet grass, making the earth say beans instead of+grass,—this was my daily work. As I had little aid from horses or+cattle, or hired men or boys, or improved implements of husbandry, I+was much slower, and became much more intimate with my beans than+usual. But labor of the hands, even when pursued to the verge of+drudgery, is perhaps never the worst form of idleness. It has a+constant and imperishable moral, and to the scholar it yields a classic+result. A very _agricola laboriosus_ was I to travellers bound westward+through Lincoln and Wayland to nobody knows where; they sitting at+their ease in gigs, with elbows on knees, and reins loosely hanging in+festoons; I the home-staying, laborious native of the soil. But soon my+homestead was out of their sight and thought. It was the only open and+cultivated field for a great distance on either side of the road; so+they made the most of it; and sometimes the man in the field heard more+of travellers’ gossip and comment than was meant for his ear: “Beans so+late! peas so late!”—for I continued to plant when others had begun to+hoe,—the ministerial husbandman had not suspected it. “Corn, my boy,+for fodder; corn for fodder.” “Does he _live_ there?” asks the black+bonnet of the gray coat; and the hard-featured farmer reins up his+grateful dobbin to inquire what you are doing where he sees no manure+in the furrow, and recommends a little chip dirt, or any little waste+stuff, or it may be ashes or plaster. But here were two acres and a+half of furrows, and only a hoe for cart and two hands to draw+it,—there being an aversion to other carts and horses,—and chip dirt+far away. Fellow-travellers as they rattled by compared it aloud with+the fields which they had passed, so that I came to know how I stood in+the agricultural world. This was one field not in Mr. Coleman’s report.+And, by the way, who estimates the value of the crop which nature+yields in the still wilder fields unimproved by man? The crop of+_English_ hay is carefully weighed, the moisture calculated, the+silicates and the potash; but in all dells and pond holes in the woods+and pastures and swamps grows a rich and various crop only unreaped by+man. Mine was, as it were, the connecting link between wild and+cultivated fields; as some states are civilized, and others+half-civilized, and others savage or barbarous, so my field was, though+not in a bad sense, a half-cultivated field. They were beans cheerfully+returning to their wild and primitive state that I cultivated, and my+hoe played the _Ranz des Vaches_ for them.++Near at hand, upon the topmost spray of a birch, sings the+brown-thrasher—or red mavis, as some love to call him—all the morning,+glad of your society, that would find out another farmer’s field if+yours were not here. While you are planting the seed, he cries,—“Drop+it, drop it,—cover it up, cover it up,—pull it up, pull it up, pull it+up.” But this was not corn, and so it was safe from such enemies as he.+You may wonder what his rigmarole, his amateur Paganini performances on+one string or on twenty, have to do with your planting, and yet prefer+it to leached ashes or plaster. It was a cheap sort of top dressing in+which I had entire faith.++As I drew a still fresher soil about the rows with my hoe, I disturbed+the ashes of unchronicled nations who in primeval years lived under+these heavens, and their small implements of war and hunting were+brought to the light of this modern day. They lay mingled with other+natural stones, some of which bore the marks of having been burned by+Indian fires, and some by the sun, and also bits of pottery and glass+brought hither by the recent cultivators of the soil. When my hoe+tinkled against the stones, that music echoed to the woods and the sky,+and was an accompaniment to my labor which yielded an instant and+immeasurable crop. It was no longer beans that I hoed, nor I that hoed+beans; and I remembered with as much pity as pride, if I remembered at+all, my acquaintances who had gone to the city to attend the oratorios.+The night-hawk circled overhead in the sunny afternoons—for I sometimes+made a day of it—like a mote in the eye, or in heaven’s eye, falling+from time to time with a swoop and a sound as if the heavens were rent,+torn at last to very rags and tatters, and yet a seamless cope+remained; small imps that fill the air and lay their eggs on the ground+on bare sand or rocks on the tops of hills, where few have found them;+graceful and slender like ripples caught up from the pond, as leaves+are raised by the wind to float in the heavens; such kindredship is in+Nature. The hawk is aerial brother of the wave which he sails over and+surveys, those his perfect air-inflated wings answering to the+elemental unfledged pinions of the sea. Or sometimes I watched a pair+of hen-hawks circling high in the sky, alternately soaring and+descending, approaching, and leaving one another, as if they were the+embodiment of my own thoughts. Or I was attracted by the passage of+wild pigeons from this wood to that, with a slight quivering winnowing+sound and carrier haste; or from under a rotten stump my hoe turned up+a sluggish portentous and outlandish spotted salamander, a trace of+Egypt and the Nile, yet our contemporary. When I paused to lean on my+hoe, these sounds and sights I heard and saw anywhere in the row, a+part of the inexhaustible entertainment which the country offers.++On gala days the town fires its great guns, which echo like popguns to+these woods, and some waifs of martial music occasionally penetrate+thus far. To me, away there in my bean-field at the other end of the+town, the big guns sounded as if a puffball had burst; and when there+was a military turnout of which I was ignorant, I have sometimes had a+vague sense all the day of some sort of itching and disease in the+horizon, as if some eruption would break out there soon, either+scarlatina or canker-rash, until at length some more favorable puff of+wind, making haste over the fields and up the Wayland road, brought me+information of the “trainers.” It seemed by the distant hum as if+somebody’s bees had swarmed, and that the neighbors, according to+Virgil’s advice, by a faint _tintinnabulum_ upon the most sonorous of+their domestic utensils, were endeavoring to call them down into the+hive again. And when the sound died quite away, and the hum had ceased,+and the most favorable breezes told no tale, I knew that they had got+the last drone of them all safely into the Middlesex hive, and that now+their minds were bent on the honey with which it was smeared.++I felt proud to know that the liberties of Massachusetts and of our+fatherland were in such safe keeping; and as I turned to my hoeing+again I was filled with an inexpressible confidence, and pursued my+labor cheerfully with a calm trust in the future.++When there were several bands of musicians, it sounded as if all the+village was a vast bellows, and all the buildings expanded and+collapsed alternately with a din. But sometimes it was a really noble+and inspiring strain that reached these woods, and the trumpet that+sings of fame, and I felt as if I could spit a Mexican with a good+relish,—for why should we always stand for trifles?—and looked round+for a woodchuck or a skunk to exercise my chivalry upon. These martial+strains seemed as far away as Palestine, and reminded me of a march of+crusaders in the horizon, with a slight tantivy and tremulous motion of+the elm-tree tops which overhang the village. This was one of the+_great_ days; though the sky had from my clearing only the same+everlastingly great look that it wears daily, and I saw no difference+in it.++It was a singular experience that long acquaintance which I cultivated+with beans, what with planting, and hoeing, and harvesting, and+threshing, and picking over and selling them,—the last was the hardest+of all,—I might add eating, for I did taste. I was determined to know+beans. When they were growing, I used to hoe from five o’clock in the+morning till noon, and commonly spent the rest of the day about other+affairs. Consider the intimate and curious acquaintance one makes with+various kinds of weeds,—it will bear some iteration in the account, for+there was no little iteration in the labor,—disturbing their delicate+organizations so ruthlessly, and making such invidious distinctions+with his hoe, levelling whole ranks of one species, and sedulously+cultivating another. That’s Roman wormwood,—that’s pigweed,—that’s+sorrel,—that’s piper-grass,—have at him, chop him up, turn his roots+upward to the sun, don’t let him have a fibre in the shade, if you do+he’ll turn himself t’other side up and be as green as a leek in two+days. A long war, not with cranes, but with weeds, those Trojans who+had sun and rain and dews on their side. Daily the beans saw me come to+their rescue armed with a hoe, and thin the ranks of their enemies,+filling up the trenches with weedy dead. Many a lusty crest-waving+Hector, that towered a whole foot above his crowding comrades, fell+before my weapon and rolled in the dust.++Those summer days which some of my contemporaries devoted to the fine+arts in Boston or Rome, and others to contemplation in India, and+others to trade in London or New York, I thus, with the other farmers+of New England, devoted to husbandry. Not that I wanted beans to eat,+for I am by nature a Pythagorean, so far as beans are concerned,+whether they mean porridge or voting, and exchanged them for rice; but,+perchance, as some must work in fields if only for the sake of tropes+and expression, to serve a parable-maker one day. It was on the whole a+rare amusement, which, continued too long, might have become a+dissipation. Though I gave them no manure, and did not hoe them all+once, I hoed them unusually well as far as I went, and was paid for it+in the end, “there being in truth,” as Evelyn says, “no compost or+lætation whatsoever comparable to this continual motion, repastination,+and turning of the mould with the spade.” “The earth,” he adds+elsewhere, “especially if fresh, has a certain magnetism in it, by+which it attracts the salt, power, or virtue (call it either) which+gives it life, and is the logic of all the labor and stir we keep about+it, to sustain us; all dungings and other sordid temperings being but+the vicars succedaneous to this improvement.” Moreover, this being one+of those “worn-out and exhausted lay fields which enjoy their sabbath,”+had perchance, as Sir Kenelm Digby thinks likely, attracted “vital+spirits” from the air. I harvested twelve bushels of beans.++But to be more particular, for it is complained that Mr. Coleman has+reported chiefly the expensive experiments of gentlemen farmers, my+outgoes were,—++ For a hoe,.................................. $ 0.54+ Ploughing, harrowing, and furrowing,......... 7.50 Too much.+ Beans for seed,.............................. 3.12½+ Potatoes for seed,........................... 1.33+ Peas for seed,............................... 0.40+ Turnip seed,................................. 0.06+ White line for crow fence,................... 0.02+ Horse cultivator and boy three hours,........ 1.00+ Horse and cart to get crop,.................. 0.75+ ————+ In all,................................. $14.72½++My income was (patrem familias vendacem, non emacem esse oportet),+from++ Nine bushels and twelve quarts of beans sold,. $16.94+ Five " large potatoes,.................... 2.50+ Nine " small,............................. 2.25+ Grass,.......................................... 1.00+ Stalks,......................................... 0.75+ ————+ In all,................................... $23.44+ Leaving a pecuniary profit,+ as I have elsewhere said, of.............. $8.71½.++This is the result of my experience in raising beans. Plant the common+small white bush bean about the first of June, in rows three feet by+eighteen inches apart, being careful to select fresh round and unmixed+seed. First look out for worms, and supply vacancies by planting anew.+Then look out for woodchucks, if it is an exposed place, for they will+nibble off the earliest tender leaves almost clean as they go; and+again, when the young tendrils make their appearance, they have notice+of it, and will shear them off with both buds and young pods, sitting+erect like a squirrel. But above all harvest as early as possible, if+you would escape frosts and have a fair and salable crop; you may save+much loss by this means.++This further experience also I gained. I said to myself, I will not+plant beans and corn with so much industry another summer, but such+seeds, if the seed is not lost, as sincerity, truth, simplicity, faith,+innocence, and the like, and see if they will not grow in this soil,+even with less toil and manurance, and sustain me, for surely it has+not been exhausted for these crops. Alas! I said this to myself; but+now another summer is gone, and another, and another, and I am obliged+to say to you, Reader, that the seeds which I planted, if indeed they+_were_ the seeds of those virtues, were wormeaten or had lost their+vitality, and so did not come up. Commonly men will only be brave as+their fathers were brave, or timid. This generation is very sure to+plant corn and beans each new year precisely as the Indians did+centuries ago and taught the first settlers to do, as if there were a+fate in it. I saw an old man the other day, to my astonishment, making+the holes with a hoe for the seventieth time at least, and not for+himself to lie down in! But why should not the New Englander try new+adventures, and not lay so much stress on his grain, his potato and+grass crop, and his orchards,—raise other crops than these? Why concern+ourselves so much about our beans for seed, and not be concerned at all+about a new generation of men? We should really be fed and cheered if+when we met a man we were sure to see that some of the qualities which+I have named, which we all prize more than those other productions, but+which are for the most part broadcast and floating in the air, had+taken root and grown in him. Here comes such a subtile and ineffable+quality, for instance, as truth or justice, though the slightest amount+or new variety of it, along the road. Our ambassadors should be+instructed to send home such seeds as these, and Congress help to+distribute them over all the land. We should never stand upon ceremony+with sincerity. We should never cheat and insult and banish one another+by our meanness, if there were present the kernel of worth and+friendliness. We should not meet thus in haste. Most men I do not meet+at all, for they seem not to have time; they are busy about their+beans. We would not deal with a man thus plodding ever, leaning on a+hoe or a spade as a staff between his work, not as a mushroom, but+partially risen out of the earth, something more than erect, like+swallows alighted and walking on the ground:—++ “And as he spake, his wings would now and then+ Spread, as he meant to fly, then close again,”++so that we should suspect that we might be conversing with an angel.+Bread may not always nourish us; but it always does us good, it even+takes stiffness out of our joints, and makes us supple and buoyant,+when we knew not what ailed us, to recognize any generosity in man or+Nature, to share any unmixed and heroic joy.++Ancient poetry and mythology suggest, at least, that husbandry was once+a sacred art; but it is pursued with irreverent haste and heedlessness+by us, our object being to have large farms and large crops merely. We+have no festival, nor procession, nor ceremony, not excepting our+Cattle-shows and so called Thanksgivings, by which the farmer expresses+a sense of the sacredness of his calling, or is reminded of its sacred+origin. It is the premium and the feast which tempt him. He sacrifices+not to Ceres and the Terrestrial Jove, but to the infernal Plutus+rather. By avarice and selfishness, and a grovelling habit, from which+none of us is free, of regarding the soil as property, or the means of+acquiring property chiefly, the landscape is deformed, husbandry is+degraded with us, and the farmer leads the meanest of lives. He knows+Nature but as a robber. Cato says that the profits of agriculture are+particularly pious or just, (_maximeque pius quæstus_), and according+to Varro the old Romans “called the same earth Mother and Ceres, and+thought that they who cultivated it led a pious and useful life, and+that they alone were left of the race of King Saturn.”++We are wont to forget that the sun looks on our cultivated fields and+on the prairies and forests without distinction. They all reflect and+absorb his rays alike, and the former make but a small part of the+glorious picture which he beholds in his daily course. In his view the+earth is all equally cultivated like a garden. Therefore we should+receive the benefit of his light and heat with a corresponding trust+and magnanimity. What though I value the seed of these beans, and+harvest that in the fall of the year? This broad field which I have+looked at so long looks not to me as the principal cultivator, but away+from me to influences more genial to it, which water and make it green.+These beans have results which are not harvested by me. Do they not+grow for woodchucks partly? The ear of wheat (in Latin _spica_,+obsoletely _speca_, from _spe_, hope) should not be the only hope of+the husbandman; its kernel or grain (_granum_ from _gerendo_, bearing)+is not all that it bears. How, then, can our harvest fail? Shall I not+rejoice also at the abundance of the weeds whose seeds are the granary+of the birds? It matters little comparatively whether the fields fill+the farmer’s barns. The true husbandman will cease from anxiety, as the+squirrels manifest no concern whether the woods will bear chestnuts+this year or not, and finish his labor with every day, relinquishing+all claim to the produce of his fields, and sacrificing in his mind not+only his first but his last fruits also.diff --git a/admin/tests/eval/corpus/distractor-mdn-css-flexbox.md b/admin/tests/eval/corpus/distractor-mdn-css-flexbox.mdnew file mode 100644index 00000000..225ba435--- /dev/null+++ b/admin/tests/eval/corpus/distractor-mdn-css-flexbox.md@@ -0,0 +1,438 @@+# MDN: Basic concepts of flexbox++Distractor document for the #1341 off-topic eval suite. From MDN Web Docs (github.com/mdn/content), by Mozilla Contributors, CC-BY-SA 2.5.++The [flexible box layout](/en-US/docs/Web/CSS/Guides/Flexible_box_layout) module (usually referred to as flexbox) is a one-dimensional layout model for distributing space between items and includes numerous alignment capabilities. This article gives an outline of the main features of flexbox, which we will explore in more detail in the rest of these guides.++When we describe flexbox as being one-dimensional we are describing the fact that flexbox deals with layout in one dimension at a time — either as a row or as a column. This can be contrasted with the two-dimensional model of [CSS Grid Layout](/en-US/docs/Web/CSS/Guides/Grid_layout), which controls columns and rows together.++## The two axes of flexbox++When working with flexbox you need to think in terms of two axes — the _main axis_ and the _cross axis_. The [main axis](#the_main_axis) is defined by the {{cssxref("flex-direction")}} property, and the [cross axis](#the_cross_axis) runs perpendicular to it. Everything we do with flexbox refers back to these axes, so it is worth understanding how they work from the outset.++### The main axis++The {{glossary("main axis")}} is defined by `flex-direction`, which has four possible values:++- `row`+- `row-reverse`+- `column`+- `column-reverse`++Should you choose `row` or `row-reverse`, your main axis will run along the row in the **inline direction**.++++Choose `column` or `column-reverse` and your main axis will run in the **block direction**, from the top of the page to the bottom.++++### The cross axis++The {{glossary("cross axis")}} runs perpendicular to the main axis. Therefore, if your `flex-direction` (main axis) is set to `row` or `row-reverse` the cross axis runs down the columns.++++If your main axis is `column` or `column-reverse` then the cross axis runs along the rows.++++## Start and end lines++Another vital area of understanding is how flexbox makes no assumption about the writing mode of the document. Flexbox doesn't just assume that all lines of text start at the top left of a document and run towards the right-hand side, with new lines appearing one under the other. Rather, it supports all writing modes, like other [logical properties and values](/en-US/docs/Web/CSS/Guides/Logical_properties_and_values).++You can [read more about the relationship between flexbox and writing modes](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Relationship_with_other_layout_methods#writing_modes) in a later article; however, the following description should help explain why we do not talk about left and right and top and bottom when we describe the direction that our flex items flow in.++If the `flex-direction` is `row` and I am working in English, then the start edge of the main axis will be on the left, the end edge on the right.++++If I were to work in Arabic, then the start edge of my main axis would be on the right and the end edge on the left.++++In both cases the start edge of the cross-axis is at the top of the flex container and the end edge at the bottom, as both languages have a horizontal writing mode.++After a while, thinking about start and end rather than left and right becomes natural, and will be useful to you when dealing with other layout methods such as CSS Grid Layout which follow the same patterns.++## The flex container++An area of a document that is laid out using flexbox is called a **flex container**. To create a {{glossary("flex container")}}, set the area's {{cssxref("display")}} property to `flex`. When we do this, the direct children of that container become **flex items**. You can explicitly control whether the container itself is displayed inline or in block formatting context using `inline flex` or `inline-flex` for inline flex containers or `block flex` or `flex` for block level flex containers.++### Initial values++As with all properties in CSS, some initial values are defined, so the contents of a new flex container will behave in the following way:++- Items display in a row (the {{cssxref("flex-direction")}} property's default value is `row`).+- The items start from the start edge of the main axis.+- The items do not stretch on the main dimension but can shrink (a flex-item's {{cssxref("flex-grow")}} property's default value is `0` and its {{cssxref("flex-shrink")}} property's default value is `1`).+- The items will stretch to fill the size of the cross-axis (the {{cssxref("align-items")}} property's default value is `stretch`).+- The flex-item's {{cssxref("flex-basis")}} property's default value is `auto`. This means that, in each case, it will be equal to the flex item {{cssxref("width")}} in horizontal writing mode, and the flex item {{cssxref("height")}} in vertical writing mode. If the corresponding `width`/`height` is also set to `auto`, the `flex-basis` `content` value is used instead.+- All the items will be in a single row (the {{cssxref("flex-wrap")}} property's default value is `nowrap`), overflowing their container if their combined `width`/`height` exceeds the containing element `width`/`height`.++The result of this is that your items will all line up in a row, using the size of the content as their size in the main axis. If there are more items than can fit in the container, they will not wrap but will instead overflow. If some items are taller than others, all items will stretch along the full length of the cross-axis.++You can see in the live sample below how this looks. Click "Play" to open the example in the MDN Playground and edit the items or add new items to try out the initial behavior of flexbox:++```html live-sample___the-flex-container+<div class="box">+ <div>One</div>+ <div>Two</div>+ <div>Three <br />has <br />extra <br />text</div>+</div>+```++```css live-sample___the-flex-container+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+}++.box {+ border: 2px dotted rgb(96 139 168);+ display: flex;+}+```++{{EmbedLiveSample("the-flex-container")}}++### Changing flex-direction++Adding the {{cssxref("flex-direction")}} property to the flex container allows us to change the direction in which our flex items display. Setting `flex-direction: row-reverse` will keep the items displaying along the row, however the start and end lines are switched.++If we change `flex-direction` to `column` the main axis switches and our items now display in a column. Set `column-reverse` and the start and end lines are again switched.++The live sample below has `flex-direction` set to `row-reverse`. Try the other values — `row`, `column` and `column-reverse` — to see what happens to the content.++```html live-sample___flex-direction+<div class="box">+ <div>One</div>+ <div>Two</div>+ <div>Three</div>+</div>+```++```css live-sample___flex-direction+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+}++.box {+ border: 2px dotted rgb(96 139 168);+ display: flex;+ flex-direction: row-reverse;+}+```++{{EmbedLiveSample("flex-direction")}}++## Multi-line flex containers with flex-wrap++While flexbox is a one dimensional model, it is possible to make flex items wrap across multiple lines. If you do this, you should consider each line as a new flex container. Any space distribution will happen across each line, without reference to the previous or subsequent lines.++To cause wrapping behavior add the property {{cssxref("flex-wrap")}} with a value of `wrap`. Now, if your items are too large to all display in one line, they will wrap onto another line. The live sample below contains items that have been given a `width`. The total width of the items is too wide for the flex container. As `flex-wrap` is set to `wrap`, the items wrap across multiple lines. If you set it to `nowrap`, which is the initial value, they will shrink to fit the container. They shrink because they are using initial flexbox values, including `flex-shrink: 1`, that allows items to shrink. Using `nowrap` would cause an [overflow](/en-US/docs/Learn_web_development/Core/Styling_basics/Overflow) if the items were not able to shrink, or could not shrink small enough to fit.++```html live-sample___flex-wrap+<div class="box">+ <div>One</div>+ <div>Two</div>+ <div>Three</div>+</div>+```++```css live-sample___flex-wrap+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+ width: 200px;+}++.box {+ width: 500px;+ border: 2px dotted rgb(96 139 168);+ display: flex;+ flex-wrap: wrap;+}+```++{{EmbedLiveSample("flex-wrap")}}++Find out more about wrapping flex items in the guide [Mastering wrapping of flex items](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Wrapping_items).++## The flex-flow shorthand++You can combine the two properties `flex-direction` and `flex-wrap` into the {{cssxref("flex-flow")}} shorthand.++In the live sample below, try changing the first value to one of the allowable values for `flex-direction` - `row`, `row-reverse`, `column` or `column-reverse`, and also change the second to `wrap` and `nowrap`.++```html live-sample___flex-flow+<div class="box">+ <div>One</div>+ <div>Two</div>+ <div>Three</div>+</div>+```++```css live-sample___flex-flow+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+ width: 200px;+}++.box {+ width: 500px;+ border: 2px dotted rgb(96 139 168);+ display: flex;+ flex-flow: row wrap;+}+```++{{EmbedLiveSample("flex-flow")}}++## Properties applied to flex items++To control the inline-size of each flex item, we target them directly via three properties:++- {{cssxref("flex-grow")}}+- {{cssxref("flex-shrink")}}+- {{cssxref("flex-basis")}}++We will take a brief look at these properties below, but if you want more comprehensive information, take a look at the [Controlling ratios of flex items on the main axis](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Controlling_flex_item_ratios) guide.++Before we can make sense of these properties we need to consider the concept of **available space**. What we are doing when we change the value of these flex properties is to change the way that available space is distributed among our items. This concept of available space is also important when we come to look at aligning items.++If we have three 100 pixel-wide items in a container which is 500 pixels wide, then the space we need to lay out our items is 300 pixels. This leaves 200 pixels of available space. If we don't change the initial values then flexbox will put that space after the last item.++++If we instead would like the items to grow and fill the space, then we need to have a method of distributing the leftover space between the items. The `flex` properties that we apply to the items themselves, enable dictating how that available space should be distributed among the sibling flex items.++### The flex-basis property++The `flex-basis` is what defines the size of that item in terms of the space it leaves as available space. The initial value of this property is `auto` — in this case the browser looks to see if the item has a size. In the example above, all of the items have a width of 100 pixels. This is used as the `flex-basis`.++If the items don't have a size then the content's size is used as the flex-basis. This is why when we just declare `display: flex` on the parent to create flex items, the items all move into a row and take only as much space as they need to display their contents.++### The flex-grow property++With the `flex-grow` property set to a positive integer, if there is available space, the flex item can grow along the main axis from its `flex-basis`. Whether the item stretches to take up all the available space on that axis, or just a portion of the available space depends on if the other items are allowed to grow too and the value of their `flex-grow` properties.++Each item with a positive value consumes a portion of any available space based on their `flex-grow` value. If we gave all of our items in the example above a `flex-grow` value of 1 then the available space in the flex container would be equally shared between our items and they would stretch to fill the container on the main axis. If we give our first item a `flex-grow` value of 2, and the other items a value of 1 each, there are a total of 4 parts; 2 parts of the available space will be given to the first item (100px out of 200px in the case of the example above) and 1 part each the other two (50px each out of the 200px total).++### The flex-shrink property++Where the `flex-grow` property deals with adding space in the main axis, the `flex-shrink` property controls how it is taken away. If we do not have enough space in the container to lay out our items, and `flex-shrink` is set to a positive integer, then the item can become smaller than the `flex-basis`. As with `flex-grow`, different values can be assigned in order to cause one item to shrink faster than others — an item with a higher value set for `flex-shrink` will shrink faster than its siblings that have lower values.++An item can shrink down to its {{cssxref("min-content")}} size. This minimum size is taken into account while working out the actual amount of shrinkage that will happen, which means that `flex-shrink` has the potential to appear less consistent than `flex-grow` in behavior. We'll therefore take a more detailed look at how this algorithm works in the article [Controlling ratios of items along the main axis](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Controlling_flex_item_ratios).++> [!NOTE]+> These values for `flex-grow` and `flex-shrink` are proportions. Typically if we had all of our items set to `flex: 1 1 200px` and then wanted one item to grow at twice the rate, we would set that item to `flex: 2 1 200px`. However you could also use `flex: 10 1 200px` and `flex: 20 1 200px` if you wanted.++### Shorthand values for the flex properties++You will very rarely see the `flex-grow`, `flex-shrink`, and `flex-basis` properties used individually; instead they are combined into the {{cssxref("flex")}} shorthand. The `flex` shorthand allows you to set the three values in this order — `flex-grow`, `flex-shrink`, `flex-basis`.++The live sample below allows you to test out the different values of the flex shorthand; remember that the first value is `flex-grow`. Giving this a positive value means the item can grow. The second is `flex-shrink` — with a positive value the items can shrink, but only if their total values overflow the main axis. The final value is `flex-basis`; this is the value the items are using as their base value to grow and shrink from.++```html live-sample___flex-properties+<div class="box">+ <div class="one">One</div>+ <div class="two">Two</div>+ <div class="three">Three</div>+</div>+```++```css live-sample___flex-properties+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+}++.box {+ border: 2px dotted rgb(96 139 168);+ display: flex;+}++.one {+ flex: 1 1 auto;+}++.two {+ flex: 1 1 auto;+}++.three {+ flex: 1 1 auto;+}+```++{{EmbedLiveSample("flex-properties")}}++There are also some predefined shorthand values which cover most of the use cases. You will often see these used in tutorials, and in many cases these are all you will need to use. The predefined values are as follows:++- `flex: initial`+- `flex: auto`+- `flex: none`+- `flex: <positive-number>`++The `initial` value is a [CSS-wide keyword](/en-US/docs/Web/CSS/Reference/Values/Data_types#css-wide_keywords) that represents the initial value for a property. Setting `flex: initial` resets the item to the [initial values](#initial_values) of the three longhand properties, which is the same as `flex: 0 1 auto`. The initial value of `flex-grow` is `0`, so items will not grow larger than their `flex-basis` size. The initial value of `flex-shrink` is `1`, so items can shrink if they need to rather than overflowing. The initial value of `flex-basis` is `auto`. Items will either use any size set on the item in the main dimension, or they will get their size from the content size.++Using `flex: auto` is the same as using `flex: 1 1 auto`; this is similar to `flex: initial`, except that the items can grow and fill the container as well as shrink if needed.++Using `flex: none` will create fully inflexible flex items. It is as if you wrote `flex: 0 0 auto`. The items cannot grow or shrink and will be laid out using flexbox with a `flex-basis` of `auto`.++The shorthand you often see in tutorials is `flex: 1` or `flex: 2` and so on. This is the same as writing `flex: 1 1 0` or `flex: 2 1 0` and so on, respectively. The items get minimum size due to `flex-basis: 0` and then proportionally grow to fill the available space. In this case, the `flex-shrink` value of `1` is redundant because the items start with minimum size — they're not given any size that could cause them to overflow the flex container.++Try these shorthand values in the live sample below.++```html live-sample___flex-shorthands+<div class="box">+ <div class="one">One</div>+ <div class="two">Two</div>+ <div class="three">Three</div>+</div>+```++```css live-sample___flex-shorthands+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+}++.box {+ border: 2px dotted rgb(96 139 168);+ display: flex;+}++.one {+ flex: 1;+}++.two {+ flex: 1;+}++.three {+ flex: 1;+}+```++{{EmbedLiveSample("flex-shorthands")}}++## Alignment, justification and distribution of free space between items++A key feature of flexbox is the ability to align and justify items on the main- and cross-axes, and to distribute space between flex items. Note that these properties are set on the flex container, not on the items themselves.++### align-items++The {{cssxref("align-items")}} property aligns all the flex items on the cross axis.++The initial value for this property is `stretch` and is why flex items stretch to the height of the flex container by default (or the width if `flex-direction` is set to `column` or `column-reverse`). This height may come from the tallest item in the container or the size set on the flex container itself.++You could instead set `align-items` to `flex-start`, or simply `start`, in order to make the items line up at the start of the flex container, `flex-end`, or just `end`, to align them to the end, or `center` to align them in the center. Try this in the live sample — I have given the flex container a height in order that you can see how the items can be moved around inside the container. See what happens if you set the value of align-items to:++- `stretch`+- `flex-start`+- `flex-end`+- `start`+- `end`+- `center`+- `baseline`+- `last baseline`++```html live-sample___align-items+<div class="box">+ <div>One</div>+ <div>Two</div>+ <div>Three <br />has <br />extra <br />text</div>+</div>+```++```css live-sample___align-items+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+}++.box {+ width: 500px;+ height: 130px;+ border: 2px dotted rgb(96 139 168);+ display: flex;+ align-items: flex-start;+}+```++{{EmbedLiveSample("align-items")}}++The `align-items` is set on the flex container and impacts all the flex items. If you want to align a flex item differently from others, you can set the {{cssxref("align-self")}} on the flex item.++### justify-content++The {{cssxref("justify-content")}} property is used to align the items on the main axis, the direction in which `flex-direction` has set the flow. The initial value is `flex-start` which will line the items up at the start edge of the container, but you could also set the value to `flex-end` to line them up at the end, or `center` to line them up in the center.++You can also use the value `space-between` to take all the spare space after the items have been laid out, and share it out evenly between the items so there will be an equal amount of space between each item. To cause an equal amount of space on the right and left (or top and bottom for columns) of each item use the value `space-around`. With `space-around`, items have a half-size space on either end. Or, to cause items to have equal space around them use the value `space-evenly`. With `space-evenly`, items have a full-size space on either end.++Try the following values of `justify-content` in the live sample:++- `start`+- `end`+- `left`+- `right`+- `normal`+- `flex-start`+- `flex-end`+- `center`+- `space-around`+- `space-between`+- `space-evenly`+- `stretch`++```html live-sample___justify-content+<div class="box">+ <div>One</div>+ <div>Two</div>+ <div>Three</div>+</div>+```++```css live-sample___justify-content+.box > * {+ border: 2px solid rgb(96 139 168);+ border-radius: 5px;+ background-color: rgb(96 139 168 / 0.2);+}++.box {+ border: 2px dotted rgb(96 139 168);+ display: flex;+ justify-content: flex-start;+}+```++{{EmbedLiveSample("justify-content")}}++The article [Aligning items in a flex container](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Aligning_items) explores these properties in more depth, in order to have a better understanding of how they work. These basic examples, however, are useful in the majority of use cases.++### justify-items++The {{cssxref("justify-items")}} property is ignored in flexbox layouts.++### place-items and place-content++The {{cssxref("place-items")}} property is a shorthand property for `align-items` and `justify-items`. If set on a flex container, it will set the alignment but not the justification, as `justify-items` is ignored in flexbox.++There is another shorthand property, {{cssxref("place-content")}}, that defines the {{cssxref("align-content")}} and `justify-content` properties. The `align-content` property only affects flex containers that wrap, and is discussed in [Aligning items in a flex container](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Aligning_items).++## Next steps++After reading this article you should have an understanding of the basic features of flexbox. In the next article, we will look at [how this specification relates to other parts of CSS](/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Relationship_with_other_layout_methods).diff --git a/admin/tests/eval/corpus/distractor-mdn-javascript-guide.md b/admin/tests/eval/corpus/distractor-mdn-javascript-guide.mdnew file mode 100644index 00000000..22a80cb2--- /dev/null+++ b/admin/tests/eval/corpus/distractor-mdn-javascript-guide.md@@ -0,0 +1,2615 @@+# MDN JavaScript Guide (excerpt)++Distractor document for the #1341 off-topic eval suite. From MDN Web Docs (github.com/mdn/content), by Mozilla Contributors, CC-BY-SA 2.5.++{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_operators")}}++Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.++See also the [exhaustive reference chapter about JavaScript functions](/en-US/docs/Web/JavaScript/Reference/Functions) to get to know the details.++## Defining functions++### Function declarations++A **function definition** (also called a **function declaration**, or **function statement**) consists of the [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function) keyword, followed by:++- The name of the function.+- A list of parameters to the function, enclosed in parentheses and separated by commas.+- The JavaScript statements that define the function, enclosed in curly braces, `{ /* … */ }`.++For example, the following code defines a function named `square`:++```js+function square(number) {+ return number * number;+}+```++The function `square` takes one parameter, called `number`. The function consists of one statement that says to return the parameter of the function (that is, `number`) multiplied by itself. The [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement specifies the value returned by the function, which is `number * number`.++Parameters are essentially passed to functions **by value** — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, **the change is not reflected globally or in the code which called that function**.++When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:++```js+function myFunc(theObject) {+ theObject.make = "Toyota";+}++const myCar = {+ make: "Honda",+ model: "Accord",+ year: 1998,+};++console.log(myCar.make); // "Honda"+myFunc(myCar);+console.log(myCar.make); // "Toyota"+```++When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:++```js+function myFunc(theArr) {+ theArr[0] = 30;+}++const arr = [45];++console.log(arr[0]); // 45+myFunc(arr);+console.log(arr[0]); // 30+```++Function declarations and expressions can be nested, which forms a _scope chain_. For example:++```js+function addSquares(a, b) {+ function square(x) {+ return x * x;+ }+ return square(a) + square(b);+}+```++See [function scopes and closures](#function_scopes_and_closures) for more information.++### Function expressions++While the function declaration above is syntactically a statement, functions can also be created by a [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function).++Such a function can be **anonymous**; it does not have to have a name. For example, the function `square` could have been defined as:++```js+const square = function (number) {+ return number * number;+};++console.log(square(4)); // 16+```++However, a name _can_ be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:++```js+const factorial = function fac(n) {+ return n < 2 ? 1 : n * fac(n - 1);+};++console.log(factorial(3)); // 6+```++Function expressions are convenient when passing a function as an argument to another function. The following example defines a `map` function that should receive a function as first argument and an array as second argument. Then, it is called with a function defined by a function expression:++```js+function map(f, a) {+ const result = new Array(a.length);+ for (let i = 0; i < a.length; i++) {+ result[i] = f(a[i]);+ }+ return result;+}++const numbers = [0, 1, 2, 5, 10];+const cubedNumbers = map(function (x) {+ return x * x * x;+}, numbers);+console.log(cubedNumbers); // [0, 1, 8, 125, 1000]+```++In JavaScript, a function can be defined based on a condition. For example, the following function definition defines `myFunc` only if `num` equals `0`:++```js+let myFunc;+if (num === 0) {+ myFunc = function (theObject) {+ theObject.make = "Toyota";+ };+}+```++In addition to defining functions as described here, you can also use the {{jsxref("Function")}} constructor to create functions from a string at runtime, much like {{jsxref("Global_Objects/eval", "eval()")}}.++A **method** is a function that is a property of an object. Read more about objects and methods in [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects).++## Calling functions++_Defining_ a function does not _execute_ it. Defining it names the function and specifies what to do when the function is called.++**Calling** the function actually performs the specified actions with the indicated parameters. For example, if you define the function `square`, you could call it as follows:++```js+square(5);+```++The preceding statement calls the function with an argument of `5`. The function executes its statements and returns the value `25`.++Functions must be _in scope_ when they are called, but the function declaration can be [hoisted](#function_hoisting) (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).++The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The `showProps()` function (defined in [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#objects_and_properties)) is an example of a function that takes an object as an argument.++A function can call itself. For example, here is a function that computes factorials recursively:++```js+function factorial(n) {+ if (n === 0 || n === 1) {+ return 1;+ }+ return n * factorial(n - 1);+}+```++You could then compute the factorials of `1` through `5` as follows:++```js+console.log(factorial(1)); // 1+console.log(factorial(2)); // 2+console.log(factorial(3)); // 6+console.log(factorial(4)); // 24+console.log(factorial(5)); // 120+```++There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.++It turns out that _functions are themselves objects_ — and in turn, these objects have methods. (See the {{jsxref("Function")}} object.) The [`call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and [`apply()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) methods can be used to achieve this goal.++### Function hoisting++Consider the example below:++```js+console.log(square(5)); // 25++function square(n) {+ return n * n;+}+```++This code runs without any error, despite the `square()` function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to:++```js+// All function declarations are effectively at the top of the scope+function square(n) {+ return n * n;+}++console.log(square(5)); // 25+```++Function hoisting only works with function _declarations_ — not with function _expressions_. The following code will not work:++```js example-bad+console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization+const square = function (n) {+ return n * n;+};+```++### Recursion++A function can refer to and call itself. It can be referred to either by the function expression or declaration's name, or via any in-scope variable that refers to the function object. For example, consider the following function definition:++```js+const foo = function bar() {+ // statements go here+};+```++Within the function body, you can refer to the function itself either as `bar` or `foo`, and call itself using `bar()` or `foo()`.++A function that calls itself is called a _recursive function_. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).++For example, consider the following loop:++```js+let x = 0;+// "x < 10" is the loop condition+while (x < 10) {+ // do stuff+ x++;+}+```++It can be converted into a recursive function declaration, followed by a call to that function:++```js+function loop(x) {+ // "x >= 10" is the exit condition (equivalent to "!(x < 10)")+ if (x >= 10) {+ return;+ }+ // do stuff+ loop(x + 1); // the recursive call+}+loop(0);+```++However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the [DOM](/en-US/docs/Web/API/Document_Object_Model)) is easier via recursion:++```js+function walkTree(node) {+ if (node === null) {+ return;+ }+ // do something with node+ for (const child of node.childNodes) {+ walkTree(child);+ }+}+```++Compared to the function `loop`, each recursive call itself makes many recursive calls here.++It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.++In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:++```js+function foo(i) {+ if (i < 0) {+ return;+ }+ console.log(`begin: ${i}`);+ foo(i - 1);+ console.log(`end: ${i}`);+}+foo(3);++// Logs:+// begin: 3+// begin: 2+// begin: 1+// begin: 0+// end: 0+// end: 1+// end: 2+// end: 3+```++### Immediately Invoked Function Expressions (IIFE)++An [Immediately Invoked Function Expression (IIFE)](/en-US/docs/Glossary/IIFE) is a code pattern that directly calls a function defined as an expression. It looks like this:++```js+(function () {+ // Do something+})();++const value = (function () {+ // Do something+ return someValue;+})();+```++Instead of saving the function in a variable, the function is immediately invoked. This is almost equivalent to just writing the function body, but there are a few unique benefits:++- It creates an extra [scope](#function_scopes_and_closures) of variables, which helps to confine variables to the place where they are useful.+- It is now an _expression_ instead of a sequence of _statements_. This allows you to write complex computation logic when initializing variables.++For more information, see the [IIFE](/en-US/docs/Glossary/IIFE) glossary entry.++## Function scopes and closures++Functions form a [scope](/en-US/docs/Glossary/Scope) for variables—this means variables defined inside a function cannot be accessed from anywhere outside the function. The function scope inherits from all the upper scopes. For example, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. On the other hand, the parent function (and any other parent scope) does _not_ have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables in the inner function.++```js+// The following variables are defined in the global scope+const num1 = 20;+const num2 = 3;+const name = "Chamakh";++// This function is defined in the global scope+function multiply() {+ return num1 * num2;+}++console.log(multiply()); // 60++// A nested function example+function getScore() {+ const num1 = 2;+ const num2 = 3;++ function add() {+ return `${name} scored ${num1 + num2}`;+ }++ return add();+}++console.log(getScore()); // "Chamakh scored 5"+```++### Closures++We also refer to the function body as a _closure_. A closure is any piece of source code (most commonly, a function) that refers to some variables, and the closure "remembers" these variables even when the scope in which these variables were declared has exited.++Closures are usually illustrated with nested functions to show that they remember variables beyond the lifetime of its parent scope; but in fact, nested functions are unnecessary. Technically speaking, all functions in JavaScript form closures—some just don't capture anything, and closures don't even have to be functions. The key ingredients for a _useful_ closure are the following:++- A parent scope that defines some variables or functions. It should have a clear lifetime, which means it should finish execution at some point. Any scope that's not the global scope satisfies this requirement; this includes blocks, functions, modules, and more.+- An inner scope defined within the parent scope, which refers to some variables or functions defined in the parent scope.+- The inner scope manages to survive beyond the lifetime of the parent scope. For example, it is saved to a variable that's defined outside the parent scope, or it's returned from the parent scope (if the parent scope is a function).+- Then, when you call the function outside of the parent scope, you can still access the variables or functions that were defined in the parent scope, even though the parent scope has finished execution.++The following is a typical example of a closure:++```js+// The outer function defines a variable called "name"+const pet = function (name) {+ const getName = function () {+ // The inner function has access to the "name" variable of the outer function+ return name;+ };+ return getName; // Return the inner function, thereby exposing it to outer scopes+};+const myPet = pet("Vivie");++console.log(myPet()); // "Vivie"+```++It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.++```js+const createPet = function (name) {+ let sex;++ const pet = {+ // setName(newName) is equivalent to setName: function (newName)+ // in this context+ setName(newName) {+ name = newName;+ },++ getName() {+ return name;+ },++ getSex() {+ return sex;+ },++ setSex(newSex) {+ if (+ typeof newSex === "string" &&+ (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")+ ) {+ sex = newSex;+ }+ },+ };++ return pet;+};++const pet = createPet("Vivie");+console.log(pet.getName()); // Vivie++pet.setName("Oliver");+pet.setSex("male");+console.log(pet.getSex()); // male+console.log(pet.getName()); // Oliver+```++In the code above, the `name` variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.++```js+const getCode = (function () {+ const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify…++ return function () {+ return apiCode;+ };+})();++console.log(getCode()); // "0]Eal(eh&2"+```++In the code above, we use the [IIFE](#immediately_invoked_function_expressions_iife) pattern. Within this IIFE scope, two values exist: a variable `apiCode` and an unnamed function that gets returned and gets assigned to the variable `getCode`. `apiCode` is in the scope of the returned unnamed function but not in the scope of any other part of the program, so there is no way for reading the value of `apiCode` apart from via the `getCode` function.++### Multiply-nested functions++Functions can be multiply-nested. For example:++- A function (`A`) contains a function (`B`), which itself contains a function (`C`).+- Both functions `B` and `C` form closures here. So, `B` can access `A`, and `C` can access `B`.+- In addition, since `C` can access `B` which can access `A`, `C` can also access `A`.++Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called _scope chaining_. Consider the following example:++```js+function A(x) {+ function B(y) {+ function C(z) {+ console.log(x + y + z);+ }+ C(3);+ }+ B(2);+}+A(1); // Logs 6 (which is 1 + 2 + 3)+```++In this example, `C` accesses `B`'s `y` and `A`'s `x`. This can be done because:++1. `B` forms a closure including `A` (i.e., `B` can access `A`'s arguments and variables).+2. `C` forms a closure including `B`.+3. Because `C`'s closure includes `B` and `B`'s closure includes `A`, then `C`'s closure also includes `A`. This means `C` can access _both_ `B` _and_ `A`'s arguments and variables. In other words, `C` _chains_ the scopes of `B` and `A`, _in that order_.++The reverse, however, is not true. `A` cannot access `C`, because `A` cannot access any argument or variable of `B`, which `C` is a variable of. Thus, `C` remains private to only `B`.++### Name conflicts++When two arguments or variables in the scopes of a closure have the same name, there is a _name conflict_. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:++```js+function outside() {+ const x = 5;+ function inside(x) {+ return x * 2;+ }+ return inside;+}++console.log(outside()(10)); // 20 (instead of 10)+```++The name conflict happens at the statement `return x * 2` and is between `inside`'s parameter `x` and `outside`'s variable `x`. The scope chain here is `inside` => `outside` => global object. Therefore, `inside`'s `x` takes precedences over `outside`'s `x`, and `20` (`inside`'s `x`) is returned instead of `10` (`outside`'s `x`).++## Using the arguments object++The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:++```js+arguments[i];+```++where `i` is the ordinal number of the argument, starting at `0`. So, the first argument passed to a function would be `arguments[0]`. The total number of arguments is indicated by `arguments.length`.++Using the `arguments` object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use `arguments.length` to determine the number of arguments actually passed to the function, and then access each argument using the `arguments` object.++For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:++```js+function myConcat(separator) {+ let result = ""; // initialize list+ // iterate through arguments+ for (let i = 1; i < arguments.length; i++) {+ result += arguments[i] + separator;+ }+ return result;+}+```++You can pass any number of arguments to this function, and it concatenates each argument into a string "list":++```js+console.log(myConcat(", ", "red", "orange", "blue"));+// "red, orange, blue, "++console.log(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));+// "elephant; giraffe; lion; cheetah; "++console.log(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));+// "sage. basil. oregano. pepper. parsley. "+```++> [!NOTE]+> The `arguments` variable is "array-like", but not an array. It is array-like in that it has a numbered index and a `length` property. However, it does _not_ possess all of the array-manipulation methods.++See the {{jsxref("Function")}} object in the JavaScript reference for more information.++## Function parameters++There are two special kinds of parameter syntax: _default parameters_ and _rest parameters_.++### Default parameters++In JavaScript, parameters of functions default to `undefined`. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.++In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are `undefined`.++In the following example, if no value is provided for `b`, its value would be `undefined` when evaluating `a*b`, and a call to `multiply` would normally have returned `NaN`. However, this is prevented by the second line in this example:++```js+function multiply(a, b) {+ b = typeof b !== "undefined" ? b : 1;+ return a * b;+}++console.log(multiply(5)); // 5+```++With _default parameters_, a manual check in the function body is no longer necessary. You can put `1` as the default value for `b` in the function head:++```js+function multiply(a, b = 1) {+ return a * b;+}++console.log(multiply(5)); // 5+```++For more details, see [default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) in the reference.++### Rest parameters++The [rest parameter](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) syntax allows us to represent an indefinite number of arguments as an array.++In the following example, the function `multiply` uses _rest parameters_ to collect arguments from the second one to the end. The function then multiplies these by the first argument.++```js+function multiply(multiplier, ...theArgs) {+ return theArgs.map((x) => multiplier * x);+}++const arr = multiply(2, 1, 2, 3);+console.log(arr); // [2, 4, 6]+```++## Arrow functions++An [arrow function expression](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) (also called a _fat arrow_ to distinguish from a hypothetical `->` syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments), [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super), or [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target). Arrow functions are always anonymous.++Two factors influenced the introduction of arrow functions: _shorter functions_ and _non-binding_ of `this`.++### Shorter functions++In some functional patterns, shorter functions are welcome. Compare:++```js+const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];++const a2 = a.map(function (s) {+ return s.length;+});++console.log(a2); // [8, 6, 7, 9]++const a3 = a.map((s) => s.length);++console.log(a3); // [8, 6, 7, 9]+```++### No separate this++Until arrow functions, every new function defined its own [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) value (a new object in the case of a constructor, undefined in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.++```js+function Person() {+ // The Person() constructor defines `this` as itself.+ this.age = 0;++ setInterval(function growUp() {+ // In nonstrict mode, the growUp() function defines `this`+ // as the global object, which is different from the `this`+ // defined by the Person() constructor.+ this.age++;+ }, 1000);+}++const p = new Person();+```++In ECMAScript 3/5, this issue was fixed by assigning the value in `this` to a variable that could be closed over.++```js+function Person() {+ // Some choose `that` instead of `self`.+ // Choose one and be consistent.+ const self = this;+ self.age = 0;++ setInterval(function growUp() {+ // The callback refers to the `self` variable of which+ // the value is the expected object.+ self.age++;+ }, 1000);+}+```++Alternatively, a [bound function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) could be created so that the proper `this` value would be passed to the `growUp()` function.++An arrow function does not have its own `this`; the `this` value of the enclosing execution context is used. Thus, in the following code, the `this` within the function that is passed to `setInterval` has the same value as `this` in the enclosing function:++```js+function Person() {+ this.age = 0;++ setInterval(() => {+ this.age++; // `this` properly refers to the person object+ }, 1000);+}++const p = new Person();+```++{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_operators")}}++{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}++Loops offer a quick and easy way to do something repeatedly. This+chapter of the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide)+introduces the different iteration statements available to JavaScript.++You can think of a loop as a computerized version of the game where you tell someone to+take _X_ steps in one direction, then _Y_ steps in another. For example,+the idea "Go five steps to the east" could be expressed this way as a loop:++```js+for (let step = 0; step < 5; step++) {+ // Runs 5 times, with values of step 0 through 4.+ console.log("Walking east one step");+}+```++There are many different kinds of loops, but they all essentially do the same thing:+they repeat an action some number of times. (Note that it's possible that number could+be zero!)++The various loop mechanisms offer different ways to determine the start and end points+of the loop. There are various situations that are more easily served by one type of+loop over the others.++The statements for loops provided in JavaScript are:++- [for statement](#for_statement)+- [do...while statement](#do...while_statement)+- [while statement](#while_statement)+- [labeled statement](#labeled_statement)+- [break statement](#break_statement)+- [continue statement](#continue_statement)+- [for...in statement](#for...in_statement)+- [for...of statement](#for...of_statement)++## for statement++A {{jsxref("Statements/for", "for")}} loop repeats until a specified condition evaluates to false. The JavaScript `for` loop is similar to the Java and C `for` loop.++A `for` statement looks as follows:++```js-nolint+for (initialization; condition; afterthought)+ statement+```++When a `for` loop executes, the following occurs:++1. The initializing expression `initialization`, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.+2. The `condition` expression is evaluated. If the value of `condition` is true, the loop statements execute. Otherwise, the `for` loop terminates. (If the `condition` expression is omitted entirely, the condition is assumed to be true.)+3. The `statement` executes. To execute multiple statements, use a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block) (`{ }`) to group those statements.+4. If present, the update expression `afterthought` is executed.+5. Control returns to Step 2.++### Example++In the example below, the function contains a `for` statement that counts+the number of selected options in a scrolling list (a [`<select>`](/en-US/docs/Web/HTML/Reference/Elements/select)+element that allows multiple selections).++#### HTML++```html+<form name="selectForm">+ <label for="musicTypes"+ >Choose some music types, then click the button below:</label+ >+ <select id="musicTypes" name="musicTypes" multiple>+ <option selected>R&B</option>+ <option>Jazz</option>+ <option>Blues</option>+ <option>New Age</option>+ <option>Classical</option>+ <option>Opera</option>+ </select>+ <button id="btn" type="button">How many are selected?</button>+</form>+```++#### JavaScript++Here, the `for` statement declares the variable `i` and initializes it to `0`. It checks that `i` is less than the number of options in the `<select>` element, performs the succeeding `if` statement, and increments `i` by 1 after each pass through the loop.++```js+function countSelected(selectObject) {+ let numberSelected = 0;+ for (let i = 0; i < selectObject.options.length; i++) {+ if (selectObject.options[i].selected) {+ numberSelected++;+ }+ }+ return numberSelected;+}++const btn = document.getElementById("btn");++btn.addEventListener("click", () => {+ const musicTypes = document.selectForm.musicTypes;+ console.log(`You have selected ${countSelected(musicTypes)} option(s).`);+});+```++## do...while statement++The {{jsxref("Statements/do...while", "do...while")}} statement repeats until a+specified condition evaluates to false.++A `do...while` statement looks as follows:++```js-nolint+do+ statement+while (condition);+```++`statement` is always executed once before the condition is+checked. (To execute multiple statements, use a block statement (`{ }`)+to group those statements.)++If `condition` is `true`, the statement executes again. At the+end of every execution, the condition is checked. When the condition is+`false`, execution stops, and control passes to the statement following+`do...while`.++### Example++In the following example, the `do` loop iterates at least once and+reiterates until `i` is no longer less than `5`.++```js+let i = 0;+do {+ i += 1;+ console.log(i);+} while (i < 5);+```++## while statement++A {{jsxref("Statements/while", "while")}} statement executes its statements as long as a+specified condition evaluates to `true`. A `while` statement looks+as follows:++```js-nolint+while (condition)+ statement+```++If the `condition` becomes `false`,+`statement` within the loop stops executing and control passes to the+statement following the loop.++The condition test occurs _before_ `statement` in the loop is+executed. If the condition returns `true`, `statement` is executed+and the `condition` is tested again. If the condition returns+`false`, execution stops, and control is passed to the statement following+`while`.++To execute multiple statements, use a block statement (`{ }`) to group+those statements.++### Example 1++The following `while` loop iterates as long as `n` is+less than `3`:++```js+let n = 0;+let x = 0;+while (n < 3) {+ n++;+ x += n;+}+```++With each iteration, the loop increments `n` and adds that value to+`x`. Therefore, `x` and `n` take on the following+values:++- After the first pass: `n` = `1` and `x` =+ `1`+- After the second pass: `n` = `2` and `x` =+ `3`+- After the third pass: `n` = `3` and `x` =+ `6`++After completing the third pass, the condition `n < 3` is no longer+`true`, so the loop terminates.++### Example 2++Avoid infinite loops. Make sure the condition in a loop eventually becomes+`false`—otherwise, the loop will never terminate! The statements in the+following `while` loop execute forever because the condition never becomes+`false`:++```js example-bad+// Infinite loops are bad!+while (true) {+ console.log("Hello, world!");+}+```++## labeled statement++A {{jsxref("Statements/label", "label")}} provides a statement with an identifier that+lets you refer to it elsewhere in your program. For example, you can use a label to+identify a loop, and then use the `break` or `continue` statements+to indicate whether a program should interrupt the loop or continue its execution.++The syntax of the labeled statement looks like the following:++```js-nolint+label:+ statement+```++The value of `label` may be any JavaScript identifier that is not a+reserved word. The `statement` that you identify with a label may be+any statement. For examples of using labeled statements, see the examples of `break` and `continue` below.++## break statement++Use the {{jsxref("Statements/break", "break")}} statement to terminate a loop,+`switch`, or in conjunction with a labeled statement.++- When you use `break` without a label, it terminates the innermost+ enclosing `while`, `do-while`, `for`, or+ `switch` immediately and transfers control to the following statement.+- When you use `break` with a label, it terminates the specified labeled+ statement.++The syntax of the `break` statement looks like this:++```js-nolint+break;+break label;+```++1. The first form of the syntax terminates the innermost enclosing loop or `switch`.+2. The second form of the syntax terminates the specified enclosing labeled statement.++### Example 1++The following example iterates through the elements in an array until it finds the+index of an element whose value is `theValue`:++```js+for (let i = 0; i < a.length; i++) {+ if (a[i] === theValue) {+ break;+ }+}+```++### Example 2: Breaking to a label++```js+let x = 0;+let z = 0;+labelCancelLoops: while (true) {+ console.log("Outer loops:", x);+ x += 1;+ z = 1;+ while (true) {+ console.log("Inner loops:", z);+ z += 1;+ if (z === 10 && x === 10) {+ break labelCancelLoops;+ } else if (z === 10) {+ break;+ }+ }+}+```++## continue statement++The {{jsxref("Statements/continue", "continue")}} statement can be used to restart a+`while`, `do-while`, `for`, or `label`+statement.++- When you use `continue` without a label, it terminates the current+ iteration of the innermost enclosing `while`, `do-while`, or+ `for` statement and continues execution of the loop with the next+ iteration. In contrast to the `break` statement, `continue` does+ not terminate the execution of the loop entirely. In a `while` loop, it+ jumps back to the condition. In a `for` loop, it jumps to the+ `increment-expression`.+- When you use `continue` with a label, it applies to the looping statement+ identified with that label.++The syntax of the `continue` statement looks like the following:++```js-nolint+continue;+continue label;+```++### Example 1++The following example shows a `while` loop with a `continue`+statement that executes when the value of `i` is `3`. Thus,+`n` takes on the values `1`, `3`, `7`, and+`12`.++```js+let i = 0;+let n = 0;+while (i < 5) {+ i++;+ if (i === 3) {+ continue;+ }+ n += i;+ console.log(n);+}+// Logs:+// 1 3 7 12+```++If you comment out the `continue;`, the loop would run till the end and you would see `1,3,6,10,15`.++### Example 2++A statement labeled `checkIandJ` contains a statement labeled+`checkJ`. If `continue` is encountered, the program+terminates the current iteration of `checkJ` and begins the next+iteration. Each time `continue` is encountered, `checkJ`+reiterates until its condition returns `false`. When `false` is+returned, the remainder of the `checkIandJ` statement is completed,+and `checkIandJ` reiterates until its condition returns+`false`. When `false` is returned, the program continues at the+statement following `checkIandJ`.++If `continue` had a label of `checkIandJ`, the program+would continue at the top of the `checkIandJ` statement.++```js+let i = 0;+let j = 10;+checkIandJ: while (i < 4) {+ console.log(i);+ i += 1;+ checkJ: while (j > 4) {+ console.log(j);+ j -= 1;+ if (j % 2 === 0) {+ continue;+ }+ console.log(j, "is odd.");+ }+ console.log("i =", i);+ console.log("j =", j);+}+```++## for...in statement++The {{jsxref("Statements/for...in", "for...in")}} statement iterates a specified+variable over all the enumerable properties of an object. For each distinct property,+JavaScript executes the specified statements. A `for...in` statement looks as+follows:++```js-nolint+for (variable in object)+ statement+```++### Example++The following function takes as its argument an object and the object's name. It then+iterates over all the object's properties and returns a string that lists the property+names and their values.++```js+function dumpProps(obj, objName) {+ let result = "";+ for (const i in obj) {+ result += `${objName}.${i} = ${obj[i]}<br>`;+ }+ result += "<hr>";+ return result;+}+```++For an object `car` with properties `make` and `model`, `result` would be:++```plain+car.make = Ford+car.model = Mustang+```++### Arrays++Although it may be tempting to use this as a way to iterate over {{jsxref("Array")}}+elements, the `for...in` statement will return the name of your user-defined+properties in addition to the numeric indexes.++Therefore, it is better to use a traditional {{jsxref("Statements/for", "for")}} loop+with a numeric index when iterating over arrays, because the `for...in`+statement iterates over user-defined properties in addition to the array elements, if+you modify the Array object (such as adding custom properties or methods).++## for...of statement++The {{jsxref("Statements/for...of", "for...of")}} statement creates a loop Iterating+over [iterable objects](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) (including+{{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}},+{{jsxref("Functions/arguments", "arguments")}} object and so on), invoking a custom+iteration hook with statements to be executed for the value of each distinct property.++```js-nolint+for (variable of iterable)+ statement+```++The following example shows the difference between a `for...of` loop and a+{{jsxref("Statements/for...in", "for...in")}} loop. While `for...in` iterates+over property names, `for...of` iterates over property values:++```js+const arr = [3, 5, 7];+arr.foo = "hello";++for (const i in arr) {+ console.log(i);+}+// "0" "1" "2" "foo"++for (const i of arr) {+ console.log(i);+}+// Logs: 3 5 7+```++The `for...of` and `for...in` statements can also be used with [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring). For example, you can simultaneously loop over the keys and values of an object using {{jsxref("Object.entries()")}}.++```js+const obj = { foo: 1, bar: 2 };++for (const [key, val] of Object.entries(obj)) {+ console.log(key, val);+}+// "foo" 1+// "bar" 2+```++{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}++{{PreviousNext("Web/JavaScript/Guide/Keyed_collections", "Web/JavaScript/Guide/Using_classes")}}++JavaScript is designed on an object-based paradigm. An object is a collection of [properties](/en-US/docs/Glossary/Property/JavaScript), and a property is an association between a name (or _key_) and a value. A property's value can be a function, in which case the property is known as a [method](/en-US/docs/Glossary/Method).++Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object with properties. A cup has a color, a design, weight, a material it is made of, etc. In the same way, JavaScript objects can have properties, which define their characteristics.++In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, and methods, and how to create your own objects.++## Creating new objects++You can create an object using an [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). Alternatively, you can first create a constructor function and then instantiate an object by invoking that function with the `new` operator.++### Using object initializers++Object initializers are also called _object literals_. "Object initializer" is consistent with the terminology used by C++.++The syntax for an object using an object initializer is:++```js+const obj = {+ property1: value1, // property name may be an identifier+ 2: value2, // or a number+ "property n": value3, // or a string+};+```++Each property name before the colon is either an identifier, a number literal, or a string literal, and each `valueN` is an expression whose value is assigned to the property name. The property name can also be an expression; computed keys need to be wrapped in square brackets. The [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) reference contains a more detailed explanation of the syntax.++In this example, the newly created object is assigned to a variable `obj` — this is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)++Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that do not compare to each other as equal.++The following statement creates an object and assigns it to the variable `x` if and only if the expression `cond` is true:++```js+let x;+if (cond) {+ x = { greeting: "hi there" };+}+```++The following example creates `myHonda` with three properties. Note that the `engine` property is also an object with its own properties.++```js+const myHonda = {+ color: "red",+ wheels: 4,+ engine: { cylinders: 4, size: 2.2 },+};+```++Objects created with initializers are called _plain objects_, because they are instances of {{jsxref("Object")}}, but not any other object type. Some object types have special initializer syntaxes — for example, [array initializers](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) and [regex literals](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#creating_a_regular_expression).++### Using a constructor function++Alternatively, you can create an object with these two steps:++1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.+2. Create an instance of the object with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new).++To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called `Car`, and you want it to have properties for make, model, and year. To do this, you would write the following function:++```js+function Car(make, model, year) {+ this.make = make;+ this.model = model;+ this.year = year;+}+```++Notice the use of `this` to assign values to the object's properties based on the values passed to the function.++Now you can create an object called `myCar` as follows:++```js+const myCar = new Car("Eagle", "Talon TSi", 1993);+```++This statement creates `myCar` and assigns it the specified values for its properties. Then the value of `myCar.make` is the string `"Eagle"`, `myCar.model` is the string `"Talon TSi"`, `myCar.year` is the integer `1993`, and so on. The order of arguments and parameters should be the same.++You can create any number of `Car` objects by calls to `new`. For example,++```js+const randCar = new Car("Nissan", "300ZX", 1992);+const kenCar = new Car("Mazda", "Miata", 1990);+```++An object can have a property that is itself another object. For example, suppose you define an object called `Person` as follows:++```js+function Person(name, age, sex) {+ this.name = name;+ this.age = age;+ this.sex = sex;+}+```++and then instantiate two new `Person` objects as follows:++```js+const rand = new Person("Rand McKinnon", 33, "M");+const ken = new Person("Ken Jones", 39, "M");+```++Then, you can rewrite the definition of `Car` to include an `owner` property that takes a `Person` object, as follows:++```js+function Car(make, model, year, owner) {+ this.make = make;+ this.model = model;+ this.year = year;+ this.owner = owner;+}+```++To instantiate the new objects, you then use the following:++```js+const car1 = new Car("Eagle", "Talon TSi", 1993, rand);+const car2 = new Car("Nissan", "300ZX", 1992, ken);+```++Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects `rand` and `ken` as the arguments for the owners. Then if you want to find out the name of the owner of `car2`, you can access the following property:++```js+car2.owner.name;+```++You can always add a property to a previously defined object. For example, the statement++```js+car1.color = "black";+```++adds a property `color` to `car1`, and assigns it a value of `"black"`. However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the `Car` object type.++You can also use the [`class`](/en-US/docs/Web/JavaScript/Reference/Classes) syntax instead of the `function` syntax to define a constructor function. For more information, see the [class guide](/en-US/docs/Web/JavaScript/Guide/Using_classes).++### Using the Object.create() method++Objects can also be created using the {{jsxref("Object.create()")}} method. This method can be very useful, because it allows you to choose the [prototype](/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain) object for the object you want to create, without having to define a constructor function.++```js+// Animal properties and method encapsulation+const animalProto = {+ type: "Invertebrates", // Default value of properties+ displayType() {+ // Method which will display the type of animal+ console.log(this.type);+ },+};++// Create a new animal type called `animal`+const animal = Object.create(animalProto);+animal.displayType(); // Logs: Invertebrates++// Create a new animal type called fish+const fish = Object.create(animalProto);+fish.type = "Fishes";+fish.displayType(); // Logs: Fishes+```++## Objects and properties++A JavaScript object has properties associated with it. Object properties are basically the same as variables, except that they are associated with objects, not [scopes](/en-US/docs/Glossary/Scope). The properties of an object define the characteristics of the object.++For example, this example creates an object named `myCar`, with properties named `make`, `model`, and `year`, with their values set to `"Ford"`, `"Mustang"`, and `1969`:++```js+const myCar = {+ make: "Ford",+ model: "Mustang",+ year: 1969,+};+```++Like JavaScript variables, property names are case sensitive. Property names can only be strings or Symbols — all keys are [converted to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) unless they are Symbols. [Array indices](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices) are, in fact, properties with string keys that contain integers.++### Accessing properties++You can access a property of an object by its property name. [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) come in two syntaxes: _dot notation_ and _bracket notation_. For example, you could access the properties of the `myCar` object as follows:++```js+// Dot notation+myCar.make = "Ford";+myCar.model = "Mustang";+myCar.year = 1969;++// Bracket notation+myCar["make"] = "Ford";+myCar["model"] = "Mustang";+myCar["year"] = 1969;+```++An object property name can be any JavaScript string or [symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), including an empty string. However, you cannot use dot notation to access a property whose name is not a valid JavaScript identifier. For example, a property name that has a space or a hyphen, that starts with a number, or that is held inside a variable can only be accessed using the bracket notation. This notation is also very useful when property names are to be dynamically determined, i.e., not determinable until runtime. Examples are as follows:++```js+const myObj = {};+const str = "myString";+const rand = Math.random();+const anotherObj = {};++// Create additional properties on myObj+myObj.type = "Dot syntax for a key named type";+myObj["date created"] = "This key has a space";+myObj[str] = "This key is in variable str";+myObj[rand] = "A random number is the key here";+myObj[anotherObj] = "This key is object anotherObj";+myObj[""] = "This key is an empty string";++console.log(myObj);+// {+// type: 'Dot syntax for a key named type',+// 'date created': 'This key has a space',+// myString: 'This key is in variable str',+// '0.6398914448618778': 'A random number is the key here',+// '[object Object]': 'This key is object anotherObj',+// '': 'This key is an empty string'+// }+console.log(myObj.myString); // 'This key is in variable str'+```++In the above code, the key `anotherObj` is an object, which is neither a string nor a symbol. When it is added to the `myObj`, JavaScript calls the {{jsxref("Object/toString", "toString()")}} method of `anotherObj`, and use the resulting string as the new key.++You can also access properties with a string value stored in a variable. The variable must be passed in bracket notation. In the example above, the variable `str` held `"myString"` and it is `"myString"` that is the property name. Therefore, `myObj.str` will return as undefined.++```js+str = "myString";+myObj[str] = "This key is in variable str";++console.log(myObj.str); // undefined++console.log(myObj[str]); // 'This key is in variable str'+console.log(myObj.myString); // 'This key is in variable str'+```++This allows accessing any property as determined at runtime:++```js+let propertyName = "make";+myCar[propertyName] = "Ford";++// access different properties by changing the contents of the variable+propertyName = "model";+myCar[propertyName] = "Mustang";++console.log(myCar); // { make: 'Ford', model: 'Mustang' }+```++However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to [object injection attacks](https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md).++Nonexistent properties of an object have the value {{jsxref("undefined")}} (and not [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)).++```js+myCar.nonexistentProperty; // undefined+```++### Enumerating properties++There are three native ways to list/traverse object properties:++- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops. This method traverses all of the enumerable string properties of an object as well as its prototype chain.+- {{jsxref("Object.keys()")}}. This method returns an array with only the enumerable own string property names ("keys") in the object `myObj`, but not those in the prototype chain.+- {{jsxref("Object.getOwnPropertyNames()")}}. This method returns an array containing all the own string property names in the object `myObj`, regardless of if they are enumerable or not.++You can use the bracket notation with [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:++```js+function showProps(obj, objName) {+ let result = "";+ for (const i in obj) {+ // Object.hasOwn() is used to exclude properties from the object's+ // prototype chain and only show "own properties"+ if (Object.hasOwn(obj, i)) {+ result += `${objName}.${i} = ${obj[i]}\n`;+ }+ }+ console.log(result);+}+```++The term "own property" refers to the properties of the object, but excluding those of the prototype chain. So, the function call `showProps(myCar, 'myCar')` would print the following:++```plain+myCar.make = Ford+myCar.model = Mustang+myCar.year = 1969+```++The above is equivalent to:++```js+function showProps(obj, objName) {+ let result = "";+ Object.keys(obj).forEach((i) => {+ result += `${objName}.${i} = ${obj[i]}\n`;+ });+ console.log(result);+}+```++There is no native way to list all inherited properties, including non-enumerable ones. However, this can be achieved with the following function:++```js+function listAllProperties(myObj) {+ let objectToInspect = myObj;+ let result = [];++ while (objectToInspect !== null) {+ result = result.concat(Object.getOwnPropertyNames(objectToInspect));+ objectToInspect = Object.getPrototypeOf(objectToInspect);+ }++ return result;+}+```++For more information, see [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Guide/Enumerability_and_ownership_of_properties).++### Deleting properties++You can remove a non-inherited property using the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator. The following code shows how to remove a property.++```js+// Creates a new object, myObj, with two properties, a and b.+const myObj = { a: 5, b: 12 };++// Removes the a property, leaving myObj with only the b property.+delete myObj.a;+console.log("a" in myObj); // false+```++## Inheritance++All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the `prototype` object of the constructor. See [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain) for more information.++### Defining properties for all objects of one type++You can add a property to all objects created through a certain [constructor](#using_a_constructor_function) using the [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a `color` property to all objects of type `Car`, and then reads the property's value from an instance `car1`.++```js+Car.prototype.color = "red";+console.log(car1.color); // "red"+```++## Defining methods++A _method_ is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also [method definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) for more details. An example is:++```js+objectName.methodName = functionName;++const myObj = {+ myMethod: function (params) {+ // do something+ },++ // this works too!+ myOtherMethod(params) {+ // do something else+ },+};+```++where `objectName` is an existing object, `methodName` is the name you are assigning to the method, and `functionName` is the name of the function.++You can then call the method in the context of the object as follows:++```js+objectName.methodName(params);+```++Methods are typically defined on the `prototype` object of the constructor, so that all objects of the same type share the same method. For example, you can define a function that formats and displays the properties of the previously-defined `Car` objects.++```js+Car.prototype.displayCar = function () {+ const result = `A Beautiful ${this.year} ${this.make} ${this.model}`;+ console.log(result);+};+```++Notice the use of `this` to refer to the object to which the method belongs. Then you can call the `displayCar` method for each of the objects as follows:++```js+car1.displayCar();+car2.displayCar();+```++### Using this for object references++JavaScript has a special keyword, [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), that you can use within a method to refer to the current object. For example, suppose you have 2 objects, `manager` and `intern`. Each object has its own `name`, `age` and `job`. In the function `sayHi()`, notice the use of `this.name`. When added to the 2 objects, the same function will print the message with the name of the respective object it's attached to.++```js+const manager = {+ name: "Karina",+ age: 27,+ job: "Software Engineer",+};+const intern = {+ name: "Tyrone",+ age: 21,+ job: "Software Engineer Intern",+};++function sayHi() {+ console.log(`Hello, my name is ${this.name}`);+}++// Add sayHi function to both objects+manager.sayHi = sayHi;+intern.sayHi = sayHi;++manager.sayHi(); // Hello, my name is Karina+intern.sayHi(); // Hello, my name is Tyrone+```++`this` is a "hidden parameter" of a function call that's passed in by specifying the object before the function that was called. For example, in `manager.sayHi()`, `this` is the `manager` object, because `manager` comes before the function `sayHi()`. If you access the same function from another object, `this` will change as well. If you use other methods to call the function, like {{jsxref("Function.prototype.call()")}} or {{jsxref("Reflect.apply()")}}, you can explicitly pass the value of `this` as an argument.++## Defining getters and setters++A [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) is a function associated with a property that gets the value of a specific property. A [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) is a function associated with a property that sets the value of a specific property. Together, they can indirectly represent the value of a property.++Getters and setters can be either++- defined within [object initializers](#using_object_initializers), or+- added later to any existing object.++Within [object initializers](#using_object_initializers), getters and setters are defined like regular [methods](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions), but prefixed with the keywords `get` or `set`. The getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:++```js+const myObj = {+ a: 7,+ get b() {+ return this.a + 1;+ },+ set c(x) {+ this.a = x / 2;+ },+};++console.log(myObj.a); // 7+console.log(myObj.b); // 8, returned from the get b() method+myObj.c = 50; // Calls the set c(x) method+console.log(myObj.a); // 25+```++The `myObj` object's properties are:++- `myObj.a` — a number+- `myObj.b` — a getter that returns `myObj.a` plus 1+- `myObj.c` — a setter that sets the value of `myObj.a` to half of the value `myObj.c` is being set to++Getters and setters can also be added to an object at any time after creation using the {{jsxref("Object.defineProperties()")}} method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:++```js+const myObj = { a: 0 };++Object.defineProperties(myObj, {+ b: {+ get() {+ return this.a + 1;+ },+ },+ c: {+ set(x) {+ this.a = x / 2;+ },+ },+});++myObj.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property+console.log(myObj.b); // Runs the getter, which yields a + 1 or 6+```++Which of the two forms to choose depends on your programming style and task at hand. If you can change the definition of the original object, you will probably define getters and setters through the original initializer. This form is more compact and natural. However, if you need to add getters and setters later — maybe because you did not write the particular object — then the second form is the only possible form. The second form better represents the dynamic nature of JavaScript, but it can make the code hard to read and understand.++## Comparing objects++In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.++```js+// Two variables, two distinct objects with the same properties+const fruit = { name: "apple" };+const anotherFruit = { name: "apple" };++fruit == anotherFruit; // return false+fruit === anotherFruit; // return false+```++```js+// Two variables, a single object+const fruit = { name: "apple" };+const anotherFruit = fruit; // Assign fruit object reference to anotherFruit++// Here fruit and anotherFruit are pointing to same object+fruit == anotherFruit; // return true+fruit === anotherFruit; // return true++fruit.name = "grape";+console.log(anotherFruit); // { name: "grape" }; not { name: "apple" }+```++For more information about comparison operators, see [equality operators](/en-US/docs/Web/JavaScript/Reference/Operators#equality_operators).++## See also++- [Inheritance and the prototype chain](/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain)+- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)++{{PreviousNext("Web/JavaScript/Guide/Regular_expressions", "Web/JavaScript/Guide/Using_classes")}}++{{PreviousNext("Web/JavaScript/Guide/Using_classes", "Web/JavaScript/Guide/Typed_arrays")}}++A {{jsxref("Promise")}} is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.++Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Imagine a function, `createAudioFileAsync()`, which asynchronously generates a sound file given a configuration record and two callback functions: one called if the audio file is successfully created, and the other called if an error occurs.++Here's some code that uses `createAudioFileAsync()`:++```js+function successCallback(result) {+ console.log(`Audio file ready at URL: ${result}`);+}++function failureCallback(error) {+ console.error(`Error generating audio file: ${error}`);+}++createAudioFileAsync(audioSettings, successCallback, failureCallback);+```++If `createAudioFileAsync()` were rewritten to return a promise, you would attach your callbacks to it instead:++```js+createAudioFileAsync(audioSettings).then(successCallback, failureCallback);+```++This convention has several advantages. We will explore each one.++## Chaining++A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. In the old days, doing several asynchronous operations in a row would lead to the classic [callback hell](https://medium.com/@raihan_tazdid/callback-hell-in-javascript-all-you-need-to-know-296f7f5d3c1):++```js-nolint+doSomething(function (result) {+ doSomethingElse(result, function (newResult) {+ doThirdThing(newResult, function (finalResult) {+ console.log(`Got the final result: ${finalResult}`);+ }, failureCallback);+ }, failureCallback);+}, failureCallback);+```++With promises, we accomplish this by creating a promise chain. The API design of promises makes this great, because callbacks are attached to the returned promise object, instead of being passed into a function.++Here's the magic: the `then()` function returns a **new promise**, different from the original:++```js+const promise = doSomething();+const promise2 = promise.then(successCallback, failureCallback);+```++This second promise (`promise2`) represents the completion not just of `doSomething()`, but also of the `successCallback` or `failureCallback` you passed in — which can be other asynchronous functions returning a promise. When that's the case, any callbacks added to `promise2` get queued behind the promise returned by either `successCallback` or `failureCallback`.++> [!NOTE]+> If you want a working example to play with, you can use the following template to create any function returning a promise:+>+> ```js+> function doSomething() {+> return new Promise((resolve) => {+> setTimeout(() => {+> // Other things to do before completion of the promise+> console.log("Did something");+> // The fulfillment value of the promise+> resolve("https://example.com/");+> }, 200);+> });+> }+> ```+>+> The implementation is discussed in the [Creating a Promise around an old callback API](#creating_a_promise_around_an_old_callback_api) section below.++With this pattern, you can create longer chains of processing, where each promise represents the completion of one asynchronous step in the chain. In addition, the arguments to `then` are optional, and `catch(failureCallback)` is short for `then(null, failureCallback)` — so if your error handling code is the same for all steps, you can attach it to the end of the chain:++```js+doSomething()+ .then(function (result) {+ return doSomethingElse(result);+ })+ .then(function (newResult) {+ return doThirdThing(newResult);+ })+ .then(function (finalResult) {+ console.log(`Got the final result: ${finalResult}`);+ })+ .catch(failureCallback);+```++You might see this expressed with [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) instead:++```js+doSomething()+ .then((result) => doSomethingElse(result))+ .then((newResult) => doThirdThing(newResult))+ .then((finalResult) => {+ console.log(`Got the final result: ${finalResult}`);+ })+ .catch(failureCallback);+```++> [!NOTE]+> Arrow function expressions can have an [implicit return](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#function_body); so, `() => x` is short for `() => { return x; }`.++`doSomethingElse` and `doThirdThing` can return any value — if they return promises, that promise is first waited until it settles, and the next callback receives the fulfillment value, not the promise itself. It is important to always return promises from `then` callbacks, even if the promise always resolves to `undefined`. If the previous handler started a promise but did not return it, there's no way to track its settlement anymore, and the promise is said to be "floating".++```js example-bad+doSomething()+ .then((url) => {+ // Missing `return` keyword in front of fetch(url).+ fetch(url);+ })+ .then((result) => {+ // result is undefined, because nothing is returned from the previous+ // handler. There's no way to know the return value of the fetch()+ // call anymore, or whether it succeeded at all.+ });+```++By returning the result of the `fetch` call (which is a promise), we can both track its completion and receive its value when it completes.++```js example-good+doSomething()+ .then((url) => {+ // `return` keyword added+ return fetch(url);+ })+ .then((result) => {+ // result is a Response object+ });+```++Floating promises could be worse if you have race conditions — if the promise from the last handler is not returned, the next `then` handler will be called early, and any value it reads may be incomplete.++```js example-bad+const listOfIngredients = [];++doSomething()+ .then((url) => {+ // Missing `return` keyword in front of fetch(url).+ fetch(url)+ .then((res) => res.json())+ .then((data) => {+ listOfIngredients.push(data);+ });+ })+ .then(() => {+ console.log(listOfIngredients);+ // listOfIngredients will always be [], because the fetch request hasn't completed yet.+ });+```++Therefore, as a rule of thumb, whenever your operation encounters a promise, return it and defer its handling to the next `then` handler.++```js example-good+const listOfIngredients = [];++doSomething()+ .then((url) => {+ // `return` keyword now included in front of fetch call.+ return fetch(url)+ .then((res) => res.json())+ .then((data) => {+ listOfIngredients.push(data);+ });+ })+ .then(() => {+ console.log(listOfIngredients);+ // listOfIngredients will now contain data from fetch call.+ });+```++Even better, you can flatten the nested chain into a single chain, which is simpler and makes error handling easier. The details are discussed in the [Nesting](#nesting) section below.++```js+doSomething()+ .then((url) => fetch(url))+ .then((res) => res.json())+ .then((data) => {+ listOfIngredients.push(data);+ })+ .then(() => {+ console.log(listOfIngredients);+ });+```++Using [`async`/`await`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) can help you write code that's more intuitive and resembles synchronous code. Below is the same example using `async`/`await`:++```js+async function logIngredients() {+ const url = await doSomething();+ const res = await fetch(url);+ const data = await res.json();+ listOfIngredients.push(data);+ console.log(listOfIngredients);+}+```++Note how the code looks exactly like synchronous code, except for the `await` keywords in front of promises. One of the only tradeoffs is that it may be easy to forget the [`await`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) keyword, which can only be fixed when there's a type mismatch (e.g., trying to use a promise as a value).++`async`/`await` builds on promises — for example, `doSomething()` is the same function as before, so there's minimal refactoring needed to change from promises to `async`/`await`. You can read more about the `async`/`await` syntax in the [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) references.++> [!NOTE]+> `async`/`await` has the same concurrency semantics as normal promise chains. `await` within one async function does not stop the entire program, only the parts that depend on its value, so other async jobs can still run while the `await` is pending.++## Error handling++You might recall seeing `failureCallback` three times in the pyramid of doom earlier, compared to only once at the end of the promise chain:++```js+doSomething()+ .then((result) => doSomethingElse(result))+ .then((newResult) => doThirdThing(newResult))+ .then((finalResult) => console.log(`Got the final result: ${finalResult}`))+ .catch(failureCallback);+```++If there's an exception, the browser will look down the chain for `.catch()` handlers or `onRejected`. This is very much modeled after how synchronous code works:++```js+try {+ const result = syncDoSomething();+ const newResult = syncDoSomethingElse(result);+ const finalResult = syncDoThirdThing(newResult);+ console.log(`Got the final result: ${finalResult}`);+} catch (error) {+ failureCallback(error);+}+```++This symmetry with asynchronous code culminates in the `async`/`await` syntax:++```js+async function foo() {+ try {+ const result = await doSomething();+ const newResult = await doSomethingElse(result);+ const finalResult = await doThirdThing(newResult);+ console.log(`Got the final result: ${finalResult}`);+ } catch (error) {+ failureCallback(error);+ }+}+```++Promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. This is essential for functional composition of asynchronous operations. All errors are now handled by the [`catch()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) method at the end of the chain, and you should almost never need to use `try`/`catch` without using `async`/`await`.++### Nesting++In the examples above involving `listOfIngredients`, the first one has one promise chain nested in the return value of another `then()` handler, while the second one uses an entirely flat chain. Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition.++Nesting is a control structure to limit the scope of `catch` statements. Specifically, a nested `catch` only catches failures in its scope and below, not errors higher up in the chain outside the nested scope. When used correctly, this gives greater precision in error recovery:++```js+doSomethingCritical()+ .then((result) =>+ doSomethingOptional(result)+ .then((optionalResult) => doSomethingExtraNice(optionalResult))+ .catch((e) => {}),+ ) // Ignore if optional stuff fails; proceed.+ .then(() => moreCriticalStuff())+ .catch((e) => console.error(`Critical failure: ${e.message}`));+```++Note that the optional steps here are nested — with the nesting caused not by the indentation, but by the placement of the outer `(` and `)` parentheses around the steps.++The inner error-silencing `catch` handler only catches failures from `doSomethingOptional()` and `doSomethingExtraNice()`, after which the code resumes with `moreCriticalStuff()`. Importantly, if `doSomethingCritical()` fails, its error is caught by the final (outer) `catch` only, and does not get swallowed by the inner `catch` handler.++In `async`/`await`, this code looks like:++```js+async function main() {+ try {+ const result = await doSomethingCritical();+ try {+ const optionalResult = await doSomethingOptional(result);+ await doSomethingExtraNice(optionalResult);+ } catch (e) {+ // Ignore failures in optional steps and proceed.+ }+ await moreCriticalStuff();+ } catch (e) {+ console.error(`Critical failure: ${e.message}`);+ }+}+```++> [!NOTE]+> If you don't have sophisticated error handling, you very likely don't need nested `then` handlers. Instead, use a flat chain and put the error handling logic at the end.++### Chaining after a catch++It's possible to chain _after_ a failure, i.e., a `catch`, which is useful to accomplish new actions even after an action failed in the chain. Read the following example:++```js+doSomething()+ .then(() => {+ throw new Error("Something failed");++ console.log("Do this");+ })+ .catch(() => {+ console.error("Do that");+ })+ .then(() => {+ console.log("Do this, no matter what happened before");+ });+```++This will output the following text:++```plain+Do that+Do this, no matter what happened before+```++> [!NOTE]+> The text "Do this" is not displayed because the "Something failed" error caused a rejection.++In `async`/`await`, this code looks like:++```js+async function main() {+ try {+ await doSomething();+ throw new Error("Something failed");+ console.log("Do this");+ } catch (e) {+ console.error("Do that");+ }+ console.log("Do this, no matter what happened before");+}+```++### Promise rejection events++If a promise rejection event is not handled by any handler, it bubbles to the top of the call stack, and the host needs to surface it. On the web, whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the [`window`](/en-US/docs/Web/API/Window) or, if being used in a web worker, it's the [`Worker`](/en-US/docs/Web/API/Worker) or other worker-based interface). The two events are:++- [`unhandledrejection`](/en-US/docs/Web/API/Window/unhandledrejection_event)+ - : Sent when a promise is rejected but there is no rejection handler available.+- [`rejectionhandled`](/en-US/docs/Web/API/Window/rejectionhandled_event)+ - : Sent when a handler is attached to a rejected promise that has already caused an `unhandledrejection` event.++In both cases, the event (of type [`PromiseRejectionEvent`](/en-US/docs/Web/API/PromiseRejectionEvent)) has as members a [`promise`](/en-US/docs/Web/API/PromiseRejectionEvent/promise) property indicating the promise that was rejected, and a [`reason`](/en-US/docs/Web/API/PromiseRejectionEvent/reason) property that provides the reason given for the promise to be rejected.++These make it possible to offer fallback error handling for promises, as well as to help debug issues with your promise management. These handlers are global per context, so all errors will go to the same event handlers, regardless of source.++In [Node.js](/en-US/docs/Glossary/Node.js), handling promise rejection is slightly different. You capture unhandled rejections by adding a handler for the Node.js `unhandledRejection` event (notice the difference in capitalization of the name), like this:++```js+process.on("unhandledRejection", (reason, promise) => {+ // Add code here to examine the "promise" and "reason" values+});+```++For Node.js, to prevent the error from being logged to the console (the default action that would otherwise occur), adding that `process.on()` listener is all that's necessary; there's no need for an equivalent of the browser runtime's [`preventDefault()`](/en-US/docs/Web/API/Event/preventDefault) method.++However, if you add that `process.on` listener but don't also have code within it to handle rejected promises, they will just be dropped on the floor and silently ignored. So ideally, you should add code within that listener to examine each rejected promise and make sure it was not caused by an actual code bug.++## Composition++There are four [composition tools](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) for running asynchronous operations concurrently: {{jsxref("Promise.all()")}}, {{jsxref("Promise.allSettled()")}}, {{jsxref("Promise.any()")}}, and {{jsxref("Promise.race()")}}.++We can start operations at the same time and wait for them all to finish like this:++```js+Promise.all([func1(), func2(), func3()]).then(([result1, result2, result3]) => {+ // use result1, result2 and result3+});+```++If one of the promises in the array rejects, `Promise.all()` immediately rejects the returned promise. The other operations continue to run, but their outcomes are not available via the return value of `Promise.all()`. This may cause unexpected state or behavior. {{jsxref("Promise.allSettled()")}} is another composition tool that ensures all operations are complete before resolving.++These methods all run promises concurrently — a sequence of promises are started simultaneously and do not wait for each other. Sequential composition is possible using some clever JavaScript:++```js+[func1, func2, func3]+ .reduce((p, f) => p.then(f), Promise.resolve())+ .then((result3) => {+ /* use result3 */+ });+```++In this example, we [reduce](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) an array of asynchronous functions down to a promise chain. The code above is equivalent to:++```js+Promise.resolve()+ .then(func1)+ .then(func2)+ .then(func3)+ .then((result3) => {+ /* use result3 */+ });+```++This can be made into a reusable compose function, which is common in functional programming:++```js+const applyAsync = (acc, val) => acc.then(val);+const composeAsync =+ (...funcs) =>+ (x) =>+ funcs.reduce(applyAsync, Promise.resolve(x));+```++The `composeAsync()` function accepts any number of functions as arguments and returns a new function that accepts an initial value to be passed through the composition pipeline:++```js+const transformData = composeAsync(func1, func2, func3);+const result3 = transformData(data);+```++Sequential composition can also be done more succinctly with async/await:++```js+let result;+for (const f of [func1, func2, func3]) {+ result = await f(result);+}+/* use last result (i.e. result3) */+```++However, before you compose promises sequentially, consider if it's really necessary — it's always better to run promises concurrently so that they don't unnecessarily block each other unless one promise's execution depends on another's result.++## Cancellation++`Promise` itself has no first-class protocol for cancellation, but you may be able to directly cancel the underlying asynchronous operation, typically using [`AbortController`](/en-US/docs/Web/API/AbortController).++## Creating a Promise around an old callback API++A {{jsxref("Promise")}} can be created from scratch using its [constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise). This should be needed only to wrap old APIs.++In an ideal world, all asynchronous functions would already return promises. Unfortunately, some APIs still expect success and/or failure callbacks to be passed in the old way. The most obvious example is the {{domxref("Window.setTimeout", "setTimeout()")}} function:++```js+setTimeout(() => saySomething("10 seconds passed"), 10 * 1000);+```++Mixing old-style callbacks and promises is problematic. If `saySomething()` fails or contains a programming error, nothing catches it. This is intrinsic to the design of `setTimeout()`.++Luckily we can wrap `setTimeout()` in a promise. The best practice is to wrap the callback-accepting functions at the lowest possible level, and then never call them directly again:++```js+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++wait(10 * 1000)+ .then(() => saySomething("10 seconds"))+ .catch(failureCallback);+```++The promise constructor takes an executor function that lets us resolve or reject a promise manually. Since `setTimeout()` doesn't really fail, we left out reject in this case. For more information on how the executor function works, see the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) reference.++## Timing++Lastly, we will look into the more technical details, about when the registered callbacks get called.++### Guarantees++In the callback-based API, when and how the callback gets called depends on the API implementor. For example, the callback may be called synchronously or asynchronously:++```js example-bad+function doSomething(callback) {+ if (Math.random() > 0.5) {+ callback();+ } else {+ setTimeout(() => callback(), 1000);+ }+}+```++The above design is strongly discouraged because it leads to the so-called "state of Zalgo". In the context of designing asynchronous APIs, this means a callback is called synchronously in some cases but asynchronously in other cases, creating ambiguity for the caller. For further background, see the article [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony/), where the term was first formally presented. This API design makes side effects hard to analyze:++```js+let value = 1;+doSomething(() => {+ value = 2;+});+console.log(value); // 1 or 2?+```++On the other hand, promises are a form of [inversion of control](https://en.wikipedia.org/wiki/Inversion_of_control) — the API implementor does not control when the callback gets called. Instead, the job of maintaining the callback queue and deciding when to call the callbacks is delegated to the promise implementation, and both the API user and API developer automatically get strong semantic guarantees, including:++- Callbacks added with [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) will never be invoked before the [completion of the current run](/en-US/docs/Web/JavaScript/Reference/Execution_model#run-to-completion) of the JavaScript event loop.+- These callbacks will be invoked even if they were added _after_ the success or failure of the asynchronous operation that the promise represents.+- Multiple callbacks may be added by calling [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) several times. They will be invoked one after another, in the order in which they were inserted.++To avoid surprises, functions passed to [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) will never be called synchronously, even with an already-resolved promise:++```js+Promise.resolve().then(() => console.log(2));+console.log(1);+// Logs: 1, 2+```++Instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later (only after the function which created it exits, and when the JavaScript execution stack is empty), just before control is returned to the event loop; i.e., pretty soon:++```js+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++wait(0).then(() => console.log(4));+Promise.resolve()+ .then(() => console.log(2))+ .then(() => console.log(3));+console.log(1); // 1, 2, 3, 4+```++### Task queues vs. microtasks++Promise callbacks are handled as a [microtask](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) whereas {{domxref("Window.setTimeout", "setTimeout()")}} callbacks are handled as task queues.++```js+const promise = new Promise((resolve, reject) => {+ console.log("Promise callback");+ resolve();+}).then((result) => {+ console.log("Promise callback (.then)");+});++setTimeout(() => {+ console.log("event-loop cycle: Promise (fulfilled)", promise);+}, 0);++console.log("Promise (pending)", promise);+```++The code above will output:++```plain+Promise callback+Promise (pending) Promise {<pending>}+Promise callback (.then)+event-loop cycle: Promise (fulfilled) Promise {<fulfilled>}+```++For more details, refer to [Tasks vs. microtasks](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth#tasks_vs._microtasks).++### When promises and tasks collide++If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally.++If you think microtasks may help solve this problem, see the [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) to learn more about how to use {{domxref("Window.queueMicrotask()", "queueMicrotask()")}} to enqueue a function as a microtask.++## See also++- {{jsxref("Promise")}}+- {{jsxref("Statements/async_function", "async function")}}+- {{jsxref("Operators/await", "await")}}+- [Promises/A+ specification](https://promisesaplus.com/)+- [We have a problem with promises](https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html) on pouchdb.com (2015)++{{PreviousNext("Web/JavaScript/Guide/Using_classes", "Web/JavaScript/Guide/Typed_arrays")}}++{{PreviousNext("Web/JavaScript/Guide/Representing_dates_times", "Web/JavaScript/Guide/Indexed_collections")}}++Regular expressions are patterns used to match character combinations in strings.+In JavaScript, regular expressions are also objects. These patterns are used with the {{jsxref("RegExp/exec", "exec()")}} and {{jsxref("RegExp/test", "test()")}} methods of {{jsxref("RegExp")}}, and with the {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}}, {{jsxref("String/search", "search()")}}, and {{jsxref("String/split", "split()")}} methods of {{jsxref("String")}}.+This chapter describes JavaScript regular expressions. It provides a brief overview of each syntax element. For a detailed explanation of each one's semantics, read the [regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions) reference.++## Creating a regular expression++You construct a regular expression in one of two ways:++- Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:++ ```js+ const re = /ab+c/;+ ```++ Regular expression literals provide compilation of the regular expression when the script is loaded.+ If the regular expression remains constant, using this can improve performance.++- Or calling the constructor function of the {{jsxref("RegExp")}} object, as follows:++ ```js+ const re = new RegExp("ab+c");+ ```++ Using the constructor function provides runtime compilation of the regular expression.+ Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.++## Writing a regular expression pattern++A regular expression pattern is composed of simple characters, such as `/abc/`, or a combination of simple and special characters, such as `/ab*c/` or `/Chapter (\d+)\.\d*/`.+The last example includes parentheses, which are used as a memory device.+The match made with this part of the pattern is remembered for later use, as described in [Using groups](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences#using_groups).++### Using simple patterns++Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern `/abc/` matches character combinations in strings only when the exact sequence `"abc"` occurs (all characters together and in that order).+Such a match would succeed in the strings `"Hi, do you know your abc's?"` and `"The latest airplane designs evolved from slabcraft."`.+In both cases the match is with the substring `"abc"`.+There is no match in the string `"Grab crab"` because while it contains the substring `"ab c"`, it does not contain the exact substring `"abc"`.++### Using special characters++When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern.+For example, to match _a single `"a"` followed by zero or more `"b"`s followed by `"c"`_, you'd use the pattern `/ab*c/`: the `*` after `"b"` means "0 or more occurrences of the preceding item."+In the string `"cbbabbbbcdebc"`, this pattern will match the substring `"abbbbc"`.++The following pages provide lists of the different special characters that fit into each category, along with descriptions and examples.++- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide+ - : Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).+- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide+ - : Distinguish different types of characters. For example, distinguishing between letters and digits.+- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide+ - : Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.+- [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) guide+ - : Indicate numbers of characters or expressions to match.++If you want to look at all the special characters that can be used in regular expressions in a single table, see the following:++<table class="standard-table">+ <caption>+ Special characters in regular expressions.+ </caption>+ <thead>+ <tr>+ <th scope="col">Characters / constructs</th>+ <th scope="col">Corresponding article</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>+ <code>[xyz]</code>, <code>[^xyz]</code>, <code>.</code>,+ <code>\d</code>, <code>\D</code>, <code>\w</code>, <code>\W</code>,+ <code>\s</code>, <code>\S</code>, <code>\t</code>, <code>\r</code>,+ <code>\n</code>, <code>\v</code>, <code>\f</code>, <code>[\b]</code>,+ <code>\0</code>, <code>\c<em>X</em></code>, <code>\x<em>HH</em></code>,+ <code>\u<em>HHHH</em></code>, <code>\u<em>{H…H}</em></code>,+ <code><em>x</em>|<em>y</em></code>+ </td>+ <td>+ <p>+ <a+ href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes"+ >Character classes</a+ >+ </p>+ </td>+ </tr>+ <tr>+ <td>+ <code>^</code>, <code>$</code>, <code>\b</code>, <code>\B</code>,+ <code>x(?=y)</code>, <code>x(?!y)</code>, <code>(?<=y)x</code>,+ <code>(?<!y)x</code>+ </td>+ <td>+ <p>+ <a+ href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"+ >Assertions</a+ >+ </p>+ </td>+ </tr>+ <tr>+ <td>+ <code>(<em>x</em>)</code>, <code>(?<Name>x)</code>, <code>(?:<em>x</em>)</code>,+ <code>\<em>n</em></code>, <code>\k<Name></code>+ </td>+ <td>+ <p>+ <a+ href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences"+ >Groups and backreferences</a+ >+ </p>+ </td>+ </tr>+ <tr>+ <td>+ <code><em>x</em>*</code>, <code><em>x</em>+</code>, <code><em>x</em>?</code>,+ <code><em>x</em>{<em>n</em>}</code>, <code><em>x</em>{<em>n</em>,}</code>,+ <code><em>x</em>{<em>n</em>,<em>m</em>}</code>+ </td>+ <td>+ <p>+ <a+ href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers"+ >Quantifiers</a+ >+ </p>+ </td>+ </tr>+ </tbody>+</table>++> [!NOTE]+> [A larger cheat sheet is also available](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet) (only aggregating parts of those individual articles).++### Escaping++If you need to use any of the special characters literally (actually searching for a `"*"`, for instance), you should escape it by putting a backslash in front of it. For instance, to search for `"a"` followed by `"*"` followed by `"b"`, you'd use `/a\*b/` — the backslash "escapes" the `"*"`, making it literal instead of special.++> [!NOTE]+> In many cases, when trying match a special character, you can wrap it in a [character class](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) as an alternative to escaping, for example `/a[*]b/`.++Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern).+For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use `/\/example\/[a-z]+/i`—the backslashes before each slash make them literal.++To match a literal backslash, you need to escape the backslash.+For instance, to match the string "C:\\" where "C" can be any letter, you'd use `/[A-Z]:\\/` — the first backslash escapes the one after it, so the expression searches for a single literal backslash.++If using the `RegExp` constructor with a string literal, remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level.+`/a\*b/` and `new RegExp("a\\*b")` create the same expression, which searches for "a" followed by a literal "\*" followed by "b".++The {{jsxref("RegExp.escape()")}} function returns a new string where all special characters in regex syntax are escaped. This allows you to do `new RegExp(RegExp.escape("a*b"))` to create a regular expression that matches only the string `"a*b"`.++### Using parentheses++Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered.+Once remembered, the substring can be recalled for other use. See [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences#using_groups) for more details.++## Using regular expressions in JavaScript++Regular expressions are used with the {{jsxref("RegExp")}} methods {{jsxref("RegExp/test", "test()")}} and {{jsxref("RegExp/exec", "exec()")}} and with the {{jsxref("String")}} methods {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}}, {{jsxref("String/search", "search()")}}, and {{jsxref("String/split", "split()")}}.++| Method | Description |+| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |+| {{jsxref("RegExp/exec", "exec()")}} | Executes a search for a match in a string. It returns an array of information or `null` on a mismatch. |+| {{jsxref("RegExp/test", "test()")}} | Tests for a match in a string. It returns `true` or `false`. |+| {{jsxref("String/match", "match()")}} | Returns an array containing all of the matches, including capturing groups, or `null` if no match is found. |+| {{jsxref("String/matchAll", "matchAll()")}} | Returns an iterator containing all of the matches, including capturing groups. |+| {{jsxref("String/search", "search()")}} | Tests for a match in a string. It returns the index of the match, or `-1` if the search fails. |+| {{jsxref("String/replace", "replace()")}} | Executes a search for a match in a string, and replaces the matched substring with a replacement substring. |+| {{jsxref("String/replaceAll", "replaceAll()")}} | Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring. |+| {{jsxref("String/split", "split()")}} | Uses a regular expression or a fixed string to break a string into an array of substrings. |++When you want to know whether a pattern is found in a string, use the `test()` or `search()` methods; for more information (but slower execution) use the `exec()` or `match()` methods.+If you use `exec()` or `match()` and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, `RegExp`.+If the match fails, the `exec()` method returns `null` (which coerces to `false`).++In the following example, the script uses the `exec()` method to find a match in a string.++```js+const myRe = /d(b+)d/g;+const myArray = myRe.exec("cdbbdbsbz");+```++If you do not need to access the properties of the regular expression, an alternative way of creating `myArray` is with this script:++```js+const myArray = /d(b+)d/g.exec("cdbbdbsbz");+// similar to 'cdbbdbsbz'.match(/d(b+)d/g); however,+// 'cdbbdbsbz'.match(/d(b+)d/g) outputs [ "dbbd" ]+// while /d(b+)d/g.exec('cdbbdbsbz') outputs [ 'dbbd', 'bb', index: 1, input: 'cdbbdbsbz' ]+```++(See [Using the global search flag with `exec()`](#using_the_global_search_flag_with_exec) for further info about the different behaviors.)++If you want to construct the regular expression from a string, yet another alternative is this script:++```js+const myRe = new RegExp("d(b+)d", "g");+const myArray = myRe.exec("cdbbdbsbz");+```++With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.++<table class="standard-table">+ <caption>+ Results of regular expression execution.+ </caption>+ <thead>+ <tr>+ <th scope="col">Object</th>+ <th scope="col">Property or index</th>+ <th scope="col">Description</th>+ <th scope="col">In this example</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td rowspan="4"><code>myArray</code></td>+ <td></td>+ <td>The matched string and all remembered substrings.</td>+ <td><code>['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']</code></td>+ </tr>+ <tr>+ <td><code>index</code></td>+ <td>The 0-based index of the match in the input string.</td>+ <td><code>1</code></td>+ </tr>+ <tr>+ <td><code>input</code></td>+ <td>The original string.</td>+ <td><code>'cdbbdbsbz'</code></td>+ </tr>+ <tr>+ <td><code>[0]</code></td>+ <td>The last matched characters.</td>+ <td><code>'dbbd'</code></td>+ </tr>+ <tr>+ <td rowspan="2"><code>myRe</code></td>+ <td><code>lastIndex</code></td>+ <td>The index at which to start the next match.+ (This property is set only if the regular expression uses the g option, described in+ <a href="#advanced_searching_with_flags">Advanced Searching With Flags</a>.)+ </td>+ <td><code>5</code></td>+ </tr>+ <tr>+ <td><code>source</code></td>+ <td>+ The text of the pattern. Updated at the time that the regular expression is created, not executed.+ </td>+ <td><code>'d(b+)d'</code></td>+ </tr>+ </tbody>+</table>++As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable.+If you do, however, every occurrence is a new regular expression.+For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression.+For example, assume you have this script:++```js+const myRe = /d(b+)d/g;+const myArray = myRe.exec("cdbbdbsbz");+console.log(`The value of lastIndex is ${myRe.lastIndex}`);++// "The value of lastIndex is 5"+```++However, if you have this script:++```js+const myArray = /d(b+)d/g.exec("cdbbdbsbz");+console.log(`The value of lastIndex is ${/d(b+)d/g.lastIndex}`);++// "The value of lastIndex is 0"+```++The occurrences of `/d(b+)d/g` in the two statements are different regular expression objects and hence have different values for their `lastIndex` property.+If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.++### Advanced searching with flags++Regular expressions have optional flags that allow for functionality like global searching and case-insensitive searching.+These flags can be used separately or together in any order, and are included as part of the regular expression.++| Flag | Description | Corresponding property |+| ---- | --------------------------------------------------------------------------------------------- | ----------------------------------------------- |+| `d` | Generate indices for substring matches. | {{jsxref("RegExp/hasIndices", "hasIndices")}} |+| `g` | Global search. | {{jsxref("RegExp/global", "global")}} |+| `i` | Case-insensitive search. | {{jsxref("RegExp/ignoreCase", "ignoreCase")}} |+| `m` | Makes `^` and `$` match the start and end of each line instead of those of the entire string. | {{jsxref("RegExp/multiline", "multiline")}} |+| `s` | Allows `.` to match newline characters. | {{jsxref("RegExp/dotAll", "dotAll")}} |+| `u` | "Unicode"; treat a pattern as a sequence of Unicode code points. | {{jsxref("RegExp/unicode", "unicode")}} |+| `v` | An upgrade to the `u` mode with more Unicode features. | {{jsxref("RegExp/unicodeSets", "unicodeSets")}} |+| `y` | Perform a "sticky" search that matches starting at the current position in the target string. | {{jsxref("RegExp/sticky", "sticky")}} |++To include a flag with the regular expression, use this syntax:++```js+const re = /pattern/flags;+```++or++```js+const re = new RegExp("pattern", "flags");+```++Note that the flags are an integral part of a regular expression. They cannot be added or removed later.++For example, `re = /\w+\s/g` creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.++```js+const re = /\w+\s/g;+const str = "fee fi fo fum";+const myArray = str.match(re);+console.log(myArray);++// ["fee ", "fi ", "fo "]+```++You could replace the line:++```js+const re = /\w+\s/g;+```++with:++```js+const re = new RegExp("\\w+\\s", "g");+```++and get the same result.++The `m` flag is used to specify that a multiline input string should be treated as multiple lines.+If the `m` flag is used, `^` and `$` match at the start or end of any line within the input string instead of the start or end of the entire string.++The `i`, `m`, and `s` flags can be enabled or disabled for specific parts of a regex using the [modifier](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Modifier) syntax.++#### Using the global search flag with exec()++{{jsxref("RegExp.prototype.exec()")}} method with the `g` flag returns each match and its position iteratively.++```js+const str = "fee fi fo fum";+const re = /\w+\s/g;++console.log(re.exec(str)); // ["fee ", index: 0, input: "fee fi fo fum"]+console.log(re.exec(str)); // ["fi ", index: 4, input: "fee fi fo fum"]+console.log(re.exec(str)); // ["fo ", index: 7, input: "fee fi fo fum"]+console.log(re.exec(str)); // null+```++In contrast, {{jsxref("String.prototype.match()")}} method returns all matches at once, but without their position.++```js+console.log(str.match(re)); // ["fee ", "fi ", "fo "]+```++#### Using unicode regular expressions++The `u` flag is used to create "unicode" regular expressions; that is, regular expressions which support matching against unicode text. An important feature that's enabled in unicode mode is [Unicode property escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape). For example, the following regular expression might be used to match against an arbitrary unicode "word":++```js+/\p{L}*/u;+```++Unicode regular expressions have different execution behavior as well. [`RegExp.prototype.unicode`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode) contains more explanation about this.++## Examples++> [!NOTE]+> Several examples are also available in:+>+> - The reference pages for {{jsxref("RegExp/exec", "exec()")}}, {{jsxref("RegExp/test", "test()")}}, {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/search", "search()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/split", "split()")}}+> - The guide articles: [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes), [assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions), [groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences), [quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers)++### Using special characters to verify input++In the following example, the user is expected to enter a phone number.+When the user presses the "Check" button, the script checks the validity of the number.+If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number.+If the number is invalid, the script informs the user that the phone number is not valid.++The regular expression looks for:++1. the beginning of the line of data: `^`+2. followed by three numeric characters `\d{3}` OR `|` a left parenthesis `\(`, followed by three digits `\d{3}`, followed by a close parenthesis `\)`, in a non-capturing group `(?:)`+3. followed by one dash, forward slash, or decimal point in a capturing group `()`+4. followed by three digits `\d{3}`+5. followed by the match remembered in the (first) captured group `\1`+6. followed by four digits `\d{4}`+7. followed by the end of the line of data: `$`++#### HTML++```html+<p>+ Enter your phone number (with area code) and then click "Check".+ <br />+ The expected format is like ###-###-####.+</p>+<form id="form">+ <input id="phone" />+ <button type="submit">Check</button>+</form>+<p id="output"></p>+```++#### JavaScript++```js+const form = document.querySelector("#form");+const input = document.querySelector("#phone");+const output = document.querySelector("#output");++const re = /^(?:\d{3}|\(\d{3}\))([-/.])\d{3}\1\d{4}$/;++function testInfo(phoneInput) {+ const ok = re.exec(phoneInput.value);++ output.textContent = ok+ ? `Thanks, your phone number is ${ok[0]}`+ : `${phoneInput.value} isn't a phone number with area code!`;+}++form.addEventListener("submit", (event) => {+ event.preventDefault();+ testInfo(input);+});+```++#### Result++{{EmbedLiveSample("Using_special_characters_to_verify_input")}}++## Tools++- [RegExr](https://regexr.com/)+ - : An online tool to learn, build, & test Regular Expressions.+- [Regex tester](https://regex101.com/)+ - : An online regex builder/debugger+- [Regex interactive tutorial](https://regexlearn.com/)+ - : An online interactive tutorials, Cheat sheet, & Playground.+- [Regex visualizer](https://extendsclass.com/regex-tester.html)+ - : An online visual regex tester.++{{PreviousNext("Web/JavaScript/Guide/Representing_dates_times", "Web/JavaScript/Guide/Indexed_collections")}}diff --git a/admin/tests/eval/corpus/distractor-python-tutorial.md b/admin/tests/eval/corpus/distractor-python-tutorial.mdnew file mode 100644index 00000000..7e568c71--- /dev/null+++ b/admin/tests/eval/corpus/distractor-python-tutorial.md@@ -0,0 +1,4099 @@+# Python Tutorial (excerpt)++Distractor document for the #1341 off-topic eval suite. From the CPython documentation, Doc/tutorial/*.rst, (c) Python Software Foundation, PSF License Version 2.++.. _tut-morecontrol:++***********************+More Control Flow Tools+***********************++As well as the :keyword:`while` statement just introduced, Python uses a few more+that we will encounter in this chapter.++.. _tut-if:++:keyword:`!if` Statements+=========================++Perhaps the most well-known statement type is the :keyword:`if` statement. For+example::++ >>> x = int(input("Please enter an integer: "))+ Please enter an integer: 42+ >>> if x < 0:+ ... x = 0+ ... print('Negative changed to zero')+ ... elif x == 0:+ ... print('Zero')+ ... elif x == 1:+ ... print('Single')+ ... else:+ ... print('More')+ ...+ More++There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is+optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful+to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ...+:keyword:`!elif` ... sequence is a substitute for the ``switch`` or+``case`` statements found in other languages.++If you're comparing the same value to several constants, or checking for specific types or+attributes, you may also find the :keyword:`!match` statement useful. For more+details see :ref:`tut-match`.++.. _tut-for:++:keyword:`!for` Statements+==========================++.. index::+ pair: statement; for++The :keyword:`for` statement in Python differs a bit from what you may be used+to in C or Pascal. Rather than always iterating over an arithmetic progression+of numbers (like in Pascal), or giving the user the ability to define both the+iteration step and halting condition (as C), Python's :keyword:`!for` statement+iterates over the items of any sequence (a list or a string), in the order that+they appear in the sequence. For example (no pun intended):++.. One suggestion was to give a real C example here, but that may only serve to+ confuse non-C programmers.++::++ >>> # Measure some strings:+ >>> words = ['cat', 'window', 'defenestrate']+ >>> for w in words:+ ... print(w, len(w))+ ...+ cat 3+ window 6+ defenestrate 12++Code that modifies a collection while iterating over that same collection can+be tricky to get right. Instead, it is usually more straight-forward to loop+over a copy of the collection or to create a new collection::++ # Create a sample collection+ users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}++ # Strategy: Iterate over a copy+ for user, status in users.copy().items():+ if status == 'inactive':+ del users[user]++ # Strategy: Create a new collection+ active_users = {}+ for user, status in users.items():+ if status == 'active':+ active_users[user] = status++.. _tut-range:++The :func:`range` Function+==========================++If you do need to iterate over a sequence of numbers, the built-in function+:func:`range` comes in handy. It generates arithmetic progressions::++ >>> for i in range(5):+ ... print(i)+ ...+ 0+ 1+ 2+ 3+ 4++The given end point is never part of the generated sequence; ``range(10)`` generates+10 values, the legal indices for items of a sequence of length 10. It+is possible to let the range start at another number, or to specify a different+increment (even negative; sometimes this is called the 'step')::++ >>> list(range(5, 10))+ [5, 6, 7, 8, 9]++ >>> list(range(0, 10, 3))+ [0, 3, 6, 9]++ >>> list(range(-10, -100, -30))+ [-10, -40, -70]++To iterate over the indices of a sequence, you can combine :func:`range` and+:func:`len` as follows::++ >>> a = ['Mary', 'had', 'a', 'little', 'lamb']+ >>> for i in range(len(a)):+ ... print(i, a[i])+ ...+ 0 Mary+ 1 had+ 2 a+ 3 little+ 4 lamb++In most such cases, however, it is convenient to use the :func:`enumerate`+function, see :ref:`tut-loopidioms`.++A strange thing happens if you just print a range::++ >>> range(10)+ range(0, 10)++In many ways the object returned by :func:`range` behaves as if it is a list,+but in fact it isn't. It is an object which returns the successive items of+the desired sequence when you iterate over it, but it doesn't really make+the list, thus saving space.++We say such an object is :term:`iterable`, that is, suitable as a target for+functions and constructs that expect something from which they can+obtain successive items until the supply is :term:`exhausted`. We have seen that+the :keyword:`for` statement is such a construct, while an example of a function+that takes an iterable is :func:`sum`::++ >>> sum(range(4)) # 0 + 1 + 2 + 3+ 6++Later we will see more functions that return iterables and take iterables as+arguments. In chapter :ref:`tut-structures`, we will discuss :func:`list` in more+detail.++.. _tut-break:++:keyword:`!break` and :keyword:`!continue` Statements+=====================================================++The :keyword:`break` statement breaks out of the innermost enclosing+:keyword:`for` or :keyword:`while` loop::++ >>> for n in range(2, 10):+ ... for x in range(2, n):+ ... if n % x == 0:+ ... print(f"{n} equals {x} * {n//x}")+ ... break+ ...+ 4 equals 2 * 2+ 6 equals 2 * 3+ 8 equals 2 * 4+ 9 equals 3 * 3++The :keyword:`continue` statement continues with the next+iteration of the loop::++ >>> for num in range(2, 10):+ ... if num % 2 == 0:+ ... print(f"Found an even number {num}")+ ... continue+ ... print(f"Found an odd number {num}")+ ...+ Found an even number 2+ Found an odd number 3+ Found an even number 4+ Found an odd number 5+ Found an even number 6+ Found an odd number 7+ Found an even number 8+ Found an odd number 9++.. _tut-for-else:+.. _break-and-continue-statements-and-else-clauses-on-loops:++:keyword:`!else` Clauses on Loops+=================================++In a :keyword:`!for` or :keyword:`!while` loop the :keyword:`!break` statement+may be paired with an :keyword:`!else` clause. If the loop finishes without+executing the :keyword:`!break`, the :keyword:`!else` clause executes.++In a :keyword:`for` loop, the :keyword:`!else` clause is executed+after the loop finishes its final iteration, that is, if no break occurred.++In a :keyword:`while` loop, it's executed after the loop's condition becomes false.++In either kind of loop, the :keyword:`!else` clause is **not** executed if the+loop was terminated by a :keyword:`break`. Of course, other ways of ending the+loop early, such as a :keyword:`return` or a raised exception, will also skip+execution of the :keyword:`else` clause.++This is exemplified in the following :keyword:`!for` loop,+which searches for prime numbers::++ >>> for n in range(2, 10):+ ... for x in range(2, n):+ ... if n % x == 0:+ ... print(n, 'equals', x, '*', n//x)+ ... break+ ... else:+ ... # loop fell through without finding a factor+ ... print(n, 'is a prime number')+ ...+ 2 is a prime number+ 3 is a prime number+ 4 equals 2 * 2+ 5 is a prime number+ 6 equals 2 * 3+ 7 is a prime number+ 8 equals 2 * 4+ 9 equals 3 * 3++(Yes, this is the correct code. Look closely: the ``else`` clause belongs to+the ``for`` loop, **not** the ``if`` statement.)++One way to think of the else clause is to imagine it paired with the ``if``+inside the loop. As the loop executes, it will run a sequence like+if/if/if/else. The ``if`` is inside the loop, encountered a number of times. If+the condition is ever true, a ``break`` will happen. If the condition is never+true, the ``else`` clause outside the loop will execute.++When used with a loop, the ``else`` clause has more in common with the ``else``+clause of a :keyword:`try` statement than it does with that of ``if``+statements: a ``try`` statement's ``else`` clause runs when no exception+occurs, and a loop's ``else`` clause runs when no ``break`` occurs. For more on+the ``try`` statement and exceptions, see :ref:`tut-handling`.++.. index:: single: ...; ellipsis literal+.. _tut-pass:++:keyword:`!pass` Statements+===========================++The :keyword:`pass` statement does nothing. It can be used when a statement is+required syntactically but the program requires no action. For example::++ >>> while True:+ ... pass # Busy-wait for keyboard interrupt (Ctrl+C)+ ...++This is commonly used for creating minimal classes::++ >>> class MyEmptyClass:+ ... pass+ ...++Another place :keyword:`pass` can be used is as a place-holder for a function or+conditional body when you are working on new code, allowing you to keep thinking+at a more abstract level. The :keyword:`!pass` is silently ignored::++ >>> def initlog(*args):+ ... pass # Remember to implement this!+ ...++For this last case, many people use the ellipsis literal :code:`...` instead of+:code:`pass`. This use has no special meaning to Python, and is not part of+the language definition (you could use any constant expression here), but+:code:`...` is used conventionally as a placeholder body as well.+See :ref:`bltin-ellipsis-object`.++.. _tut-match:++:keyword:`!match` Statements+============================++A :keyword:`match` statement takes an expression and compares its value to successive+patterns given as one or more case blocks. This is superficially+similar to a switch statement in C, Java or JavaScript (and many+other languages), but it's more similar to pattern matching in+languages like Rust or Haskell. Only the first pattern that matches+gets executed and it can also extract components (sequence elements+or object attributes) from the value into variables. If no case matches,+none of the branches is executed.++The simplest form compares a subject value against one or more literals::++ def http_error(status):+ match status:+ case 400:+ return "Bad request"+ case 404:+ return "Not found"+ case 418:+ return "I'm a teapot"+ case _:+ return "Something's wrong with the internet"++Note the last block: the "variable name" ``_`` acts as a *wildcard* and+never fails to match.++You can combine several literals in a single pattern using ``|`` ("or")::++ case 401 | 403 | 404:+ return "Not allowed"++Patterns can look like unpacking assignments, and can be used to bind+variables::++ # point is an (x, y) tuple+ match point:+ case (0, 0):+ print("Origin")+ case (0, y):+ print(f"Y={y}")+ case (x, 0):+ print(f"X={x}")+ case (x, y):+ print(f"X={x}, Y={y}")+ case _:+ raise ValueError("Not a point")++Study that one carefully! The first pattern has two literals, and can+be thought of as an extension of the literal pattern shown above. But+the next two patterns combine a literal and a variable, and the+variable *binds* a value from the subject (``point``). The fourth+pattern captures two values, which makes it conceptually similar to+the unpacking assignment ``(x, y) = point``.++If you are using classes to structure your data+you can use the class name followed by an argument list resembling a+constructor, but with the ability to capture attributes into variables::++ class Point:+ def __init__(self, x, y):+ self.x = x+ self.y = y++ def where_is(point):+ match point:+ case Point(x=0, y=0):+ print("Origin")+ case Point(x=0, y=y):+ print(f"Y={y}")+ case Point(x=x, y=0):+ print(f"X={x}")+ case Point():+ print("Somewhere else")+ case _:+ print("Not a point")++You can use positional parameters with some builtin classes that provide an+ordering for their attributes (e.g. dataclasses). You can also define a specific+position for attributes in patterns by setting the ``__match_args__`` special+attribute in your classes. If it's set to ("x", "y"), the following patterns are all+equivalent (and all bind the ``y`` attribute to the ``var`` variable)::++ Point(1, var)+ Point(1, y=var)+ Point(x=1, y=var)+ Point(y=var, x=1)++A recommended way to read patterns is to look at them as an extended form of what you+would put on the left of an assignment, to understand which variables would be set to+what.+Only the standalone names (like ``var`` above) are assigned to by a match statement.+Dotted names (like ``foo.bar``), attribute names (the ``x=`` and ``y=`` above) or class names+(recognized by the "(...)" next to them like ``Point`` above) are never assigned to.++Patterns can be arbitrarily nested. For example, if we have a short+list of Points, with ``__match_args__`` added, we could match it like this::++ class Point:+ __match_args__ = ('x', 'y')+ def __init__(self, x, y):+ self.x = x+ self.y = y++ match points:+ case []:+ print("No points")+ case [Point(0, 0)]:+ print("The origin")+ case [Point(x, y)]:+ print(f"Single point {x}, {y}")+ case [Point(0, y1), Point(0, y2)]:+ print(f"Two on the Y axis at {y1}, {y2}")+ case _:+ print("Something else")++We can add an ``if`` clause to a pattern, known as a "guard". If the+guard is false, ``match`` goes on to try the next case block. Note+that value capture happens before the guard is evaluated::++ match point:+ case Point(x, y) if x == y:+ print(f"Y=X at {x}")+ case Point(x, y):+ print(f"Not on the diagonal")++Several other key features of this statement:++- Like unpacking assignments, tuple and list patterns have exactly the+ same meaning and actually match arbitrary sequences. An important+ exception is that they don't match iterators or strings.++- Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y,+ *rest)`` work similar to unpacking assignments. The+ name after ``*`` may also be ``_``, so ``(x, y, *_)`` matches a sequence+ of at least two items without binding the remaining items.++- Mapping patterns: ``{"bandwidth": b, "latency": l}`` captures the+ ``"bandwidth"`` and ``"latency"`` values from a dictionary. Unlike sequence+ patterns, extra keys are ignored. An unpacking like ``**rest`` is also+ supported. (But ``**_`` would be redundant, so it is not allowed.)++- Subpatterns may be captured using the ``as`` keyword::++ case (Point(x1, y1), Point(x2, y2) as p2): ...++ will capture the second element of the input as ``p2`` (as long as the input is+ a sequence of two points)++- Most literals are compared by equality, however the singletons ``True``,+ ``False`` and ``None`` are compared by identity.++- Patterns may use named constants. These must be dotted names+ to prevent them from being interpreted as capture variables::++ from enum import Enum+ class Color(Enum):+ RED = 'red'+ GREEN = 'green'+ BLUE = 'blue'++ color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))++ match color:+ case Color.RED:+ print("I see red!")+ case Color.GREEN:+ print("Grass is green")+ case Color.BLUE:+ print("I'm feeling the blues :(")++For a more detailed explanation and additional examples, you can look into+:pep:`636` which is written in a tutorial format.++.. _tut-functions:++Defining Functions+==================++We can create a function that writes the Fibonacci series to an arbitrary+boundary::++ >>> def fib(n): # write Fibonacci series less than n+ ... """Print a Fibonacci series less than n."""+ ... a, b = 0, 1+ ... while a < n:+ ... print(a, end=' ')+ ... a, b = b, a+b+ ... print()+ ...+ >>> # Now call the function we just defined:+ >>> fib(2000)+ 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597++.. index::+ single: documentation strings+ single: docstrings+ single: strings, documentation++The keyword :keyword:`def` introduces a function *definition*. It must be+followed by the function name and the parenthesized list of formal parameters.+The statements that form the body of the function start at the next line, and+must be indented.++The first statement of the function body can optionally be a string literal;+this string literal is the function's documentation string, or :dfn:`docstring`.+(More about docstrings can be found in the section :ref:`tut-docstrings`.)+There are tools which use docstrings to automatically produce online or printed+documentation, or to let the user interactively browse through code; it's good+practice to include docstrings in code that you write, so make a habit of it.++The *execution* of a function introduces a new symbol table used for the local+variables of the function. More precisely, all variable assignments in a+function store the value in the local symbol table; whereas variable references+first look in the local symbol table, then in the local symbol tables of+enclosing functions, then in the global symbol table, and finally in the table+of built-in names. Thus, global variables and variables of enclosing functions+cannot be directly assigned a value within a function (unless, for global+variables, named in a :keyword:`global` statement, or, for variables of enclosing+functions, named in a :keyword:`nonlocal` statement), although they may be+referenced.++The actual parameters (arguments) to a function call are introduced in the local+symbol table of the called function when it is called; thus, arguments are+passed using *call by value* (where the *value* is always an object *reference*,+not the value of the object). [#]_ When a function calls another function,+or calls itself recursively, a new+local symbol table is created for that call.++A function definition associates the function name with the function object in+the current symbol table. The interpreter recognizes the object pointed to by+that name as a user-defined function. Other names can also point to that same+function object and can also be used to access the function::++ >>> fib+ <function fib at 10042ed0>+ >>> f = fib+ >>> f(100)+ 0 1 1 2 3 5 8 13 21 34 55 89++Coming from other languages, you might object that ``fib`` is not a function but+a procedure since it doesn't return a value. In fact, even functions without a+:keyword:`return` statement do return a value, albeit a rather boring one. This+value is called ``None`` (it's a built-in name). Writing the value ``None`` is+normally suppressed by the interpreter if it would be the only value written.+You can see it if you really want to using :func:`print`::++ >>> fib(0)+ >>> print(fib(0))+ None++It is simple to write a function that returns a list of the numbers of the+Fibonacci series, instead of printing it::++ >>> def fib2(n): # return Fibonacci series up to n+ ... """Return a list containing the Fibonacci series up to n."""+ ... result = []+ ... a, b = 0, 1+ ... while a < n:+ ... result.append(a) # see below+ ... a, b = b, a+b+ ... return result+ ...+ >>> f100 = fib2(100) # call it+ >>> f100 # write the result+ [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]++This example, as usual, demonstrates some new Python features:++* The :keyword:`return` statement returns with a value from a function.+ :keyword:`!return` without an expression argument returns ``None``. Falling off+ the end of a function also returns ``None``.++* The statement ``result.append(a)`` calls a *method* of the list object+ ``result``. A method is a function that 'belongs' to an object and is named+ ``obj.methodname``, where ``obj`` is some object (this may be an expression),+ and ``methodname`` is the name of a method that is defined by the object's type.+ Different types define different methods. Methods of different types may have+ the same name without causing ambiguity. (It is possible to define your own+ object types and methods, using *classes*, see :ref:`tut-classes`)+ The method :meth:`~list.append` shown in the example is defined for list objects; it+ adds a new element at the end of the list. In this example it is equivalent to+ ``result = result + [a]``, but more efficient.++.. _tut-defining:++More on Defining Functions+==========================++It is also possible to define functions with a variable number of arguments.+There are three forms, which can be combined.++.. _tut-defaultargs:++Default Argument Values+-----------------------++The most useful form is to specify a default value for one or more arguments.+This creates a function that can be called with fewer arguments than it is+defined to allow. For example::++ def ask_ok(prompt, retries=4, reminder='Please try again!'):+ while True:+ reply = input(prompt)+ if reply in {'y', 'ye', 'yes'}:+ return True+ if reply in {'n', 'no', 'nop', 'nope'}:+ return False+ retries = retries - 1+ if retries < 0:+ raise ValueError('invalid user response')+ print(reminder)++This function can be called in several ways:++* giving only the mandatory argument:+ ``ask_ok('Do you really want to quit?')``+* giving one of the optional arguments:+ ``ask_ok('OK to overwrite the file?', 2)``+* or even giving all arguments:+ ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``++This example also introduces the :keyword:`in` keyword. This tests whether or+not a sequence contains a certain value.++The default values are evaluated at the point of function definition in the+*defining* scope, so that ::++ i = 5++ def f(arg=i):+ print(arg)++ i = 6+ f()++will print ``5``.++**Important warning:** The default value is evaluated only once. This makes a+difference when the default is a mutable object such as a list, dictionary, or+instances of most classes. For example, the following function accumulates the+arguments passed to it on subsequent calls::++ def f(a, L=[]):+ L.append(a)+ return L++ print(f(1))+ print(f(2))+ print(f(3))++This will print ::++ [1]+ [1, 2]+ [1, 2, 3]++If you don't want the default to be shared between subsequent calls, you can+write the function like this instead::++ def f(a, L=None):+ if L is None:+ L = []+ L.append(a)+ return L++.. _tut-keywordargs:++Keyword Arguments+-----------------++Functions can also be called using :term:`keyword arguments <keyword argument>`+of the form ``kwarg=value``. For instance, the following function::++ def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):+ print("-- This parrot wouldn't", action, end=' ')+ print("if you put", voltage, "volts through it.")+ print("-- Lovely plumage, the", type)+ print("-- It's", state, "!")++accepts one required argument (``voltage``) and three optional arguments+(``state``, ``action``, and ``type``). This function can be called in any+of the following ways::++ parrot(1000) # 1 positional argument+ parrot(voltage=1000) # 1 keyword argument+ parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments+ parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments+ parrot('a million', 'bereft of life', 'jump') # 3 positional arguments+ parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword++but all the following calls would be invalid::++ parrot() # required argument missing+ parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument+ parrot(110, voltage=220) # duplicate value for the same argument+ parrot(actor='John Cleese') # unknown keyword argument++In a function call, keyword arguments must follow positional arguments.+All the keyword arguments passed must match one of the arguments+accepted by the function (e.g. ``actor`` is not a valid argument for the+``parrot`` function), and their order is not important. This also includes+non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).+No argument may receive a value more than once.+Here's an example that fails due to this restriction::++ >>> def function(a):+ ... pass+ ...+ >>> function(0, a=0)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: function() got multiple values for argument 'a'++When a final formal parameter of the form ``**name`` is present, it receives a+dictionary (see :ref:`typesmapping`) containing all keyword arguments except for+those corresponding to a formal parameter. This may be combined with a formal+parameter of the form ``*name`` (described in the next subsection) which+receives a :ref:`tuple <tut-tuples>` containing the positional+arguments beyond the formal parameter list. (``*name`` must occur+before ``**name``.) For example, if we define a function like this::++ def cheeseshop(kind, *arguments, **keywords):+ print("-- Do you have any", kind, "?")+ print("-- I'm sorry, we're all out of", kind)+ for arg in arguments:+ print(arg)+ print("-" * 40)+ for kw in keywords:+ print(kw, ":", keywords[kw])++It could be called like this::++ cheeseshop("Limburger", "It's very runny, sir.",+ "It's really very, VERY runny, sir.",+ shopkeeper="Michael Palin",+ client="John Cleese",+ sketch="Cheese Shop Sketch")++and of course it would print:++.. code-block:: none++ -- Do you have any Limburger ?+ -- I'm sorry, we're all out of Limburger+ It's very runny, sir.+ It's really very, VERY runny, sir.+ ----------------------------------------+ shopkeeper : Michael Palin+ client : John Cleese+ sketch : Cheese Shop Sketch++Note that the order in which the keyword arguments are printed is guaranteed+to match the order in which they were provided in the function call.++Special parameters+------------------++By default, arguments may be passed to a Python function either by position+or explicitly by keyword. For readability and performance, it makes sense to+restrict the way arguments can be passed so that a developer need only look+at the function definition to determine if items are passed by position, by+position or keyword, or by keyword.++A function definition may look like:++.. code-block:: none++ def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):+ ----------- ---------- ----------+ | | |+ | Positional or keyword |+ | - Keyword only+ -- Positional only++where ``/`` and ``*`` are optional. If used, these symbols indicate the kind of+parameter by how the arguments may be passed to the function:+positional-only, positional-or-keyword, and keyword-only. Keyword parameters+are also referred to as named parameters.++-------------------------------+Positional-or-Keyword Arguments+-------------------------------++If ``/`` and ``*`` are not present in the function definition, arguments may+be passed to a function by position or by keyword.++--------------------------+Positional-Only Parameters+--------------------------++Looking at this in a bit more detail, it is possible to mark certain parameters+as *positional-only*. If *positional-only*, the parameters' order matters, and+the parameters cannot be passed by keyword. Positional-only parameters are+placed before a ``/`` (forward-slash). The ``/`` is used to logically+separate the positional-only parameters from the rest of the parameters.+If there is no ``/`` in the function definition, there are no positional-only+parameters.++Parameters following the ``/`` may be *positional-or-keyword* or *keyword-only*.++----------------------+Keyword-Only Arguments+----------------------++To mark parameters as *keyword-only*, indicating the parameters must be passed+by keyword argument, place an ``*`` in the arguments list just before the first+*keyword-only* parameter.++-----------------+Function Examples+-----------------++Consider the following example function definitions paying close attention to the+markers ``/`` and ``*``::++ >>> def standard_arg(arg):+ ... print(arg)+ ...+ >>> def pos_only_arg(arg, /):+ ... print(arg)+ ...+ >>> def kwd_only_arg(*, arg):+ ... print(arg)+ ...+ >>> def combined_example(pos_only, /, standard, *, kwd_only):+ ... print(pos_only, standard, kwd_only)++The first function definition, ``standard_arg``, the most familiar form,+places no restrictions on the calling convention and arguments may be+passed by position or keyword::++ >>> standard_arg(2)+ 2++ >>> standard_arg(arg=2)+ 2++The second function ``pos_only_arg`` is restricted to only use positional+parameters as there is a ``/`` in the function definition::++ >>> pos_only_arg(1)+ 1++ >>> pos_only_arg(arg=1)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'++The third function ``kwd_only_arg`` only allows keyword arguments as indicated+by a ``*`` in the function definition::++ >>> kwd_only_arg(3)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given++ >>> kwd_only_arg(arg=3)+ 3++And the last uses all three calling conventions in the same function+definition::++ >>> combined_example(1, 2, 3)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: combined_example() takes 2 positional arguments but 3 were given++ >>> combined_example(1, 2, kwd_only=3)+ 1 2 3++ >>> combined_example(1, standard=2, kwd_only=3)+ 1 2 3++ >>> combined_example(pos_only=1, standard=2, kwd_only=3)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'++Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key::++ def foo(name, **kwds):+ return 'name' in kwds++There is no possible call that will make it return ``True`` as the keyword ``'name'``+will always bind to the first parameter. For example::++ >>> foo(1, **{'name': 2})+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: foo() got multiple values for argument 'name'+ >>>++But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments::++ >>> def foo(name, /, **kwds):+ ... return 'name' in kwds+ ...+ >>> foo(1, **{'name': 2})+ True++In other words, the names of positional-only parameters can be used in+``**kwds`` without ambiguity.++-----+Recap+-----++The use case will determine which parameters to use in the function definition::++ def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):++As guidance:++* Use positional-only if you want the name of the parameters to not be+ available to the user. This is useful when parameter names have no real+ meaning, if you want to enforce the order of the arguments when the function+ is called or if you need to take some positional parameters and arbitrary+ keywords.+* Use keyword-only when names have meaning and the function definition is+ more understandable by being explicit with names or you want to prevent+ users relying on the position of the argument being passed.+* For an API, use positional-only to prevent breaking API changes+ if the parameter's name is modified in the future.++.. _tut-arbitraryargs:++Arbitrary Argument Lists+------------------------++.. index::+ single: * (asterisk); in function calls++Finally, the least frequently used option is to specify that a function can be+called with an arbitrary number of arguments. These arguments will be wrapped+up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,+zero or more normal arguments may occur. ::++ def write_multiple_items(file, separator, *args):+ file.write(separator.join(args))++Normally, these *variadic* arguments will be last in the list of formal+parameters, because they scoop up all remaining input arguments that are+passed to the function. Any formal parameters which occur after the ``*args``+parameter are 'keyword-only' arguments, meaning that they can only be used as+keywords rather than positional arguments. ::++ >>> def concat(*args, sep="/"):+ ... return sep.join(args)+ ...+ >>> concat("earth", "mars", "venus")+ 'earth/mars/venus'+ >>> concat("earth", "mars", "venus", sep=".")+ 'earth.mars.venus'++.. _tut-unpacking-arguments:++Unpacking Argument Lists+------------------------++The reverse situation occurs when the arguments are already in a list or tuple+but need to be unpacked for a function call requiring separate positional+arguments. For instance, the built-in :func:`range` function expects separate+*start* and *stop* arguments. If they are not available separately, write the+function call with the ``*``\ -operator to unpack the arguments out of a list+or tuple::++ >>> list(range(3, 6)) # normal call with separate arguments+ [3, 4, 5]+ >>> args = [3, 6]+ >>> list(range(*args)) # call with arguments unpacked from a list+ [3, 4, 5]++.. index::+ single: **; in function calls++In the same fashion, dictionaries can deliver keyword arguments with the+``**``\ -operator::++ >>> def parrot(voltage, state='a stiff', action='voom'):+ ... print("-- This parrot wouldn't", action, end=' ')+ ... print("if you put", voltage, "volts through it.", end=' ')+ ... print("E's", state, "!")+ ...+ >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}+ >>> parrot(**d)+ -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !++.. _tut-lambda:++Lambda Expressions+------------------++Small anonymous functions can be created with the :keyword:`lambda` keyword.+This function returns the sum of its two arguments: ``lambda a, b: a+b``.+Lambda functions can be used wherever function objects are required. They are+syntactically restricted to a single expression. Semantically, they are just+syntactic sugar for a normal function definition. Like nested function+definitions, lambda functions can reference variables from the containing+scope::++ >>> def make_incrementor(n):+ ... return lambda x: x + n+ ...+ >>> f = make_incrementor(42)+ >>> f(0)+ 42+ >>> f(1)+ 43++The above example uses a lambda expression to return a function. Another use+is to pass a small function as an argument. For instance, :meth:`list.sort`+takes a sorting key function *key* which can be a lambda function::++ >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]+ >>> pairs.sort(key=lambda pair: pair[1])+ >>> pairs+ [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]++.. _tut-docstrings:++Documentation Strings+---------------------++.. index::+ single: docstrings+ single: documentation strings+ single: strings, documentation++Here are some conventions about the content and formatting of documentation+strings.++The first line should always be a short, concise summary of the object's+purpose. For brevity, it should not explicitly state the object's name or type,+since these are available by other means (except if the name happens to be a+verb describing a function's operation). This line should begin with a capital+letter and end with a period.++If there are more lines in the documentation string, the second line should be+blank, visually separating the summary from the rest of the description. The+following lines should be one or more paragraphs describing the object's calling+conventions, its side effects, etc.++The Python parser strips indentation from multi-line string literals when they+serve as module, class, or function docstrings.++Here is an example of a multi-line docstring::++ >>> def my_function():+ ... """Do nothing, but document it.+ ...+ ... No, really, it doesn't do anything:+ ...+ ... >>> my_function()+ ... >>>+ ... """+ ... pass+ ...+ >>> print(my_function.__doc__)+ Do nothing, but document it.++ No, really, it doesn't do anything:++ >>> my_function()+ >>>++.. _tut-annotations:++Function Annotations+--------------------++.. index::+ pair: function; annotations+ single: ->; function annotations+ single: : (colon); function annotations++:ref:`Function annotations <function>` are completely optional metadata+information about the types used by user-defined functions (see :pep:`3107` and+:pep:`484` for more information).++:term:`Annotations <function annotation>` are stored in the :attr:`~object.__annotations__`+attribute of the function as a dictionary and have no effect on any other part of the+function. Parameter annotations are defined by a colon after the parameter name, followed+by an expression evaluating to the value of the annotation. Return annotations are+defined by a literal ``->``, followed by an expression, between the parameter+list and the colon denoting the end of the :keyword:`def` statement. The+following example has a required argument, an optional argument, and the return+value annotated::++ >>> def f(ham: str, eggs: str = 'eggs') -> str:+ ... print("Annotations:", f.__annotations__)+ ... print("Arguments:", ham, eggs)+ ... return ham + ' and ' + eggs+ ...+ >>> f('spam')+ Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}+ Arguments: spam eggs+ 'spam and eggs'++.. _tut-codingstyle:++Intermezzo: Coding Style+========================++.. index:: pair: coding; style++Now that you are about to write longer, more complex pieces of Python, it is a+good time to talk about *coding style*. Most languages can be written (or more+concisely, *formatted*) in different styles; some are more readable than others.+Making it easy for others to read your code is always a good idea, and adopting+a nice coding style helps tremendously for that.++For Python, :pep:`8` has emerged as the style guide that most projects adhere to;+it promotes a very readable and eye-pleasing coding style. Every Python+developer should read it at some point; here are the most important points+extracted for you:++* Use 4-space indentation, and no tabs.++ 4 spaces are a good compromise between small indentation (allows greater+ nesting depth) and large indentation (easier to read). Tabs introduce+ confusion, and are best left out.++* Wrap lines so that they don't exceed 79 characters.++ This helps users with small displays and makes it possible to have several+ code files side-by-side on larger displays.++* Use blank lines to separate functions and classes, and larger blocks of+ code inside functions.++* When possible, put comments on a line of their own.++* Use docstrings.++* Use spaces around operators and after commas, but not directly inside+ bracketing constructs: ``a = f(1, 2) + g(3, 4)``.++* Name your classes and functions consistently; the convention is to use+ ``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for functions+ and methods. Always use ``self`` as the name for the first method argument+ (see :ref:`tut-firstclasses` for more on classes and methods).++* Don't use fancy encodings if your code is meant to be used in international+ environments. Python's default, UTF-8, or even plain ASCII work best in any+ case.++* Likewise, don't use non-ASCII characters in identifiers if there is only the+ slightest chance people speaking a different language will read or maintain+ the code.++.. rubric:: Footnotes++.. [#] Actually, *call by object reference* would be a better description,+ since if a mutable object is passed, the caller will see any changes the+ callee makes to it (items inserted into a list).++.. _tut-structures:++***************+Data Structures+***************++This chapter describes some things you've learned about already in more detail,+and adds some new things as well.++.. _tut-morelists:++More on Lists+=============++The :ref:`list <typesseq-list>` data type has some more methods. Here are all+of the methods of list objects:++.. method:: list.append(value, /)+ :noindex:++ Add an item to the end of the list. Similar to ``a[len(a):] = [x]``.++.. method:: list.extend(iterable, /)+ :noindex:++ Extend the list by appending all the items from the iterable. Similar to+ ``a[len(a):] = iterable``.++.. method:: list.insert(index, value, /)+ :noindex:++ Insert an item at a given position. The first argument is the index of the+ element before which to insert, so ``a.insert(0, x)`` inserts at the front of+ the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.++.. method:: list.remove(value, /)+ :noindex:++ Remove the first item from the list whose value is equal to *value*. It raises a+ :exc:`ValueError` if there is no such item.++.. method:: list.pop(index=-1, /)+ :noindex:++ Remove the item at the given position in the list, and return it. If no index+ is specified, ``a.pop()`` removes and returns the last item in the list.+ It raises an :exc:`IndexError` if the list is empty or the index is+ outside the list range.++.. method:: list.clear()+ :noindex:++ Remove all items from the list. Similar to ``del a[:]``.++.. method:: list.index(value[, start[, stop]])+ :noindex:++ Return zero-based index of the first occurrence of *value* in the list.+ Raises a :exc:`ValueError` if there is no such item.++ The optional arguments *start* and *end* are interpreted as in the slice+ notation and are used to limit the search to a particular subsequence of+ the list. The returned index is computed relative to the beginning of the full+ sequence rather than the *start* argument.++.. method:: list.count(value, /)+ :noindex:++ Return the number of times *value* appears in the list.++.. method:: list.sort(*, key=None, reverse=False)+ :noindex:++ Sort the items of the list in place (the arguments can be used for sort+ customization, see :func:`sorted` for their explanation).++.. method:: list.reverse()+ :noindex:++ Reverse the elements of the list in place.++.. method:: list.copy()+ :noindex:++ Return a shallow copy of the list. Similar to ``a[:]``.++An example that uses most of the list methods::++ >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']+ >>> fruits.count('apple')+ 2+ >>> fruits.count('tangerine')+ 0+ >>> fruits.index('banana')+ 3+ >>> fruits.index('banana', 4) # Find next banana starting at position 4+ 6+ >>> fruits.reverse()+ >>> fruits+ ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']+ >>> fruits.append('grape')+ >>> fruits+ ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']+ >>> fruits.sort()+ >>> fruits+ ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']+ >>> fruits.pop()+ 'pear'++You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that+only modify the list have no return value printed -- they return the default+``None``. [#]_ This is a design principle for all mutable data structures in+Python.++Another thing you might notice is that not all data can be sorted or+compared. For instance, ``[None, 'hello', 10]`` doesn't sort because+integers can't be compared to strings and ``None`` can't be compared to+other types. Also, there are some types that don't have a defined+ordering relation. For example, ``3+4j < 5+7j`` isn't a valid+comparison.++.. _tut-lists-as-stacks:++Using Lists as Stacks+---------------------++The list methods make it very easy to use a list as a stack, where the last+element added is the first element retrieved ("last-in, first-out"). To add an+item to the top of the stack, use :meth:`~list.append`. To retrieve an item from the+top of the stack, use :meth:`~list.pop` without an explicit index. For example::++ >>> stack = [3, 4, 5]+ >>> stack.append(6)+ >>> stack.append(7)+ >>> stack+ [3, 4, 5, 6, 7]+ >>> stack.pop()+ 7+ >>> stack+ [3, 4, 5, 6]+ >>> stack.pop()+ 6+ >>> stack.pop()+ 5+ >>> stack+ [3, 4]++.. _tut-lists-as-queues:++Using Lists as Queues+---------------------++It is also possible to use a list as a queue, where the first element added is+the first element retrieved ("first-in, first-out"); however, lists are not+efficient for this purpose. While appends and pops from the end of list are+fast, doing inserts or pops from the beginning of a list is slow (because all+of the other elements have to be shifted by one). See+:ref:`time-complexity` for more information.++To implement a queue, use :class:`collections.deque` which was designed to+have fast appends and pops from both ends. For example::++ >>> from collections import deque+ >>> queue = deque(["Eric", "John", "Michael"])+ >>> queue.append("Terry") # Terry arrives+ >>> queue.append("Graham") # Graham arrives+ >>> queue.popleft() # The first to arrive now leaves+ 'Eric'+ >>> queue.popleft() # The second to arrive now leaves+ 'John'+ >>> queue # Remaining queue in order of arrival+ deque(['Michael', 'Terry', 'Graham'])++.. _tut-listcomps:++List Comprehensions+-------------------++List comprehensions provide a concise way to create lists.+Common applications are to make new lists where each element is the result of+some operations applied to each member of another sequence or iterable, or to+create a subsequence of those elements that satisfy a certain condition.++For example, assume we want to create a list of squares, like::++ >>> squares = []+ >>> for x in range(10):+ ... squares.append(x**2)+ ...+ >>> squares+ [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]++Note that this creates (or overwrites) a variable named ``x`` that still exists+after the loop completes. We can calculate the list of squares without any+side effects using::++ squares = list(map(lambda x: x**2, range(10)))++or, equivalently::++ squares = [x**2 for x in range(10)]++which is more concise and readable.++A list comprehension consists of brackets containing an expression followed+by a :keyword:`!for` clause, then zero or more :keyword:`!for` or :keyword:`!if`+clauses. The result will be a new list resulting from evaluating the expression+in the context of the :keyword:`!for` and :keyword:`!if` clauses which follow it.+For example, this listcomp combines the elements of two lists if they are not+equal::++ >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]+ [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]++and it's equivalent to::++ >>> combs = []+ >>> for x in [1,2,3]:+ ... for y in [3,1,4]:+ ... if x != y:+ ... combs.append((x, y))+ ...+ >>> combs+ [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]++Note how the order of the :keyword:`for` and :keyword:`if` statements is the+same in both these snippets.++If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),+it must be parenthesized. ::++ >>> vec = [-4, -2, 0, 2, 4]+ >>> # create a new list with the values doubled+ >>> [x*2 for x in vec]+ [-8, -4, 0, 4, 8]+ >>> # filter the list to exclude negative numbers+ >>> [x for x in vec if x >= 0]+ [0, 2, 4]+ >>> # apply a function to all the elements+ >>> [abs(x) for x in vec]+ [4, 2, 0, 2, 4]+ >>> # call a method on each element+ >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']+ >>> [weapon.strip() for weapon in freshfruit]+ ['banana', 'loganberry', 'passion fruit']+ >>> # create a list of 2-tuples like (number, square)+ >>> [(x, x**2) for x in range(6)]+ [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]+ >>> # the tuple must be parenthesized, otherwise an error is raised+ >>> [x, x**2 for x in range(6)]+ File "<stdin>", line 1+ [x, x**2 for x in range(6)]+ ^^^^^^^+ SyntaxError: did you forget parentheses around the comprehension target?+ >>> # flatten a list using a listcomp with two 'for'+ >>> vec = [[1,2,3], [4,5,6], [7,8,9]]+ >>> [num for elem in vec for num in elem]+ [1, 2, 3, 4, 5, 6, 7, 8, 9]++List comprehensions can contain complex expressions and nested functions::++ >>> from math import pi+ >>> [str(round(pi, i)) for i in range(1, 6)]+ ['3.1', '3.14', '3.142', '3.1416', '3.14159']++Nested List Comprehensions+--------------------------++The initial expression in a list comprehension can be any arbitrary expression,+including another list comprehension.++Consider the following example of a 3x4 matrix implemented as a list of+3 lists of length 4::++ >>> matrix = [+ ... [1, 2, 3, 4],+ ... [5, 6, 7, 8],+ ... [9, 10, 11, 12],+ ... ]++The following list comprehension will transpose rows and columns::++ >>> [[row[i] for row in matrix] for i in range(4)]+ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]++As we saw in the previous section, the inner list comprehension is evaluated in+the context of the :keyword:`for` that follows it, so this example is+equivalent to::++ >>> transposed = []+ >>> for i in range(4):+ ... transposed.append([row[i] for row in matrix])+ ...+ >>> transposed+ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]++which, in turn, is the same as::++ >>> transposed = []+ >>> for i in range(4):+ ... # the following 3 lines implement the nested listcomp+ ... transposed_row = []+ ... for row in matrix:+ ... transposed_row.append(row[i])+ ... transposed.append(transposed_row)+ ...+ >>> transposed+ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]++In the real world, you should prefer built-in functions to complex flow statements.+The :func:`zip` function would do a great job for this use case::++ >>> list(zip(*matrix))+ [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]++See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.++Unpacking in Lists and List Comprehensions+------------------------------------------++The section on :ref:`tut-unpacking-arguments` describes the use of ``*`` to+"unpack" the elements of an iterable object, providing each one separately as+an argument to a function. Unpacking can also be used in other contexts, for+example, when creating lists. When specifying elements of a list, prefixing an+expression by a ``*`` will unpack the result of that expression, adding each of+its elements to the list we're creating::++ >>> x = [1, 2, 3]+ >>> [0, *x, 4, 5, 6]+ [0, 1, 2, 3, 4, 5, 6]++This only works if the expression following the ``*`` evaluates to an iterable+object; trying to unpack a non-iterable object will raise an exception::++ >>> x = 1+ >>> [0, *x, 2, 3, 4]+ Traceback (most recent call last):+ File "<python-input-1>", line 1, in <module>+ [0, *x, 2, 3, 4]+ TypeError: Value after * must be an iterable, not int++Unpacking can also be used in list comprehensions, as a way to build a new list+representing the concatenation of an arbitrary number of iterables::++ >>> x = [[1, 2, 3], [4, 5, 6], [], [7], [8, 9]]+ >>> [*element for element in x]+ [1, 2, 3, 4, 5, 6, 7, 8, 9]++Note that the effect is that each element from ``x`` is unpacked. This works+for arbitrary iterable objects, not just lists::++ >>> x = [[1, 2, 3], 'cat', {'spam': 'eggs'}]+ >>> [*element for element in x]+ [1, 2, 3, 'c', 'a', 't', 'spam']++But if the objects in ``x`` are not iterable, this expression would again raise+an exception.++.. _tut-del:++The :keyword:`!del` statement+=============================++There is a way to remove an item from a list given its index instead of its+value: the :keyword:`del` statement. This differs from the :meth:`~list.pop` method+which returns a value. The :keyword:`!del` statement can also be used to remove+slices from a list or clear the entire list (which we did earlier by assignment+of an empty list to the slice). For example::++ >>> a = [-1, 1, 66.25, 333, 333, 1234.5]+ >>> del a[0]+ >>> a+ [1, 66.25, 333, 333, 1234.5]+ >>> del a[2:4]+ >>> a+ [1, 66.25, 1234.5]+ >>> del a[:]+ >>> a+ []++:keyword:`del` can also be used to delete entire variables::++ >>> del a++Referencing the name ``a`` hereafter is an error (at least until another value+is assigned to it). We'll find other uses for :keyword:`del` later.++.. _tut-tuples:++Tuples and Sequences+====================++We saw that lists and strings have many common properties, such as indexing and+slicing operations. They are two examples of *sequence* data types (see+:ref:`typesseq`). Since Python is an evolving language, other sequence data+types may be added. There is also another standard sequence data type: the+*tuple*.++A tuple consists of a number of values separated by commas, for instance::++ >>> t = 12345, 54321, 'hello!'+ >>> t[0]+ 12345+ >>> t+ (12345, 54321, 'hello!')+ >>> # Tuples may be nested:+ >>> u = t, (1, 2, 3, 4, 5)+ >>> u+ ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))+ >>> # Tuples are immutable:+ >>> t[0] = 88888+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ TypeError: 'tuple' object does not support item assignment+ >>> # but they can contain mutable objects:+ >>> v = ([1, 2, 3], [3, 2, 1])+ >>> v+ ([1, 2, 3], [3, 2, 1])+ >>> # they support unpacking just like lists:+ >>> x = [1, 2, 3]+ >>> 0, *x, 4+ (0, 1, 2, 3, 4)++As you see, on output tuples are always enclosed in parentheses, so that nested+tuples are interpreted correctly; they may be input with or without surrounding+parentheses, although often parentheses are necessary anyway (if the tuple is+part of a larger expression). It is not possible to assign to the individual+items of a tuple, however it is possible to create tuples which contain mutable+objects, such as lists.++Though tuples may seem similar to lists, they are often used in different+situations and for different purposes.+Tuples are :term:`immutable`, and usually contain a heterogeneous sequence of+elements that are accessed via unpacking (see later in this section) or indexing+(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).+Lists are :term:`mutable`, and their elements are usually homogeneous and are+accessed by iterating over the list.++A special problem is the construction of tuples containing 0 or 1 items: the+syntax has some extra quirks to accommodate these. Empty tuples are constructed+by an empty pair of parentheses; a tuple with one item is constructed by+following a value with a comma (it is not sufficient to enclose a single value+in parentheses). Ugly, but effective. For example::++ >>> empty = ()+ >>> singleton = 'hello', # <-- note trailing comma+ >>> len(empty)+ 0+ >>> len(singleton)+ 1+ >>> singleton+ ('hello',)++The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:+the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.+The reverse operation is also possible::++ >>> x, y, z = t++This is called, appropriately enough, *sequence unpacking* and works for any+sequence on the right-hand side. Sequence unpacking requires that there are as+many variables on the left side of the equals sign as there are elements in the+sequence. Note that multiple assignment is really just a combination of tuple+packing and sequence unpacking.++.. _tut-sets:++Sets+====++Python also includes a data type for :ref:`sets <types-set>`. A set is+an unordered collection with no duplicate elements. Basic uses include+membership testing and eliminating duplicate entries. Set objects also+support mathematical operations like union, intersection, difference, and+symmetric difference.++Curly braces or the :func:`set` function can be used to create sets. Note: to+create an empty set you have to use ``set()``, not ``{}``; the latter creates an+empty dictionary, a data structure that we discuss in the next section.++Because sets are unordered, iterating over them or printing them can+produce the elements in a different order than you expect.++Here is a brief demonstration::++ >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}+ >>> print(basket) # show that duplicates have been removed+ {'orange', 'banana', 'pear', 'apple'}+ >>> 'orange' in basket # fast membership testing+ True+ >>> 'crabgrass' in basket+ False++ >>> # Demonstrate set operations on unique letters from two words+ >>>+ >>> a = set('abracadabra')+ >>> b = set('alacazam')+ >>> a # unique letters in a+ {'a', 'r', 'b', 'c', 'd'}+ >>> a - b # letters in a but not in b+ {'r', 'd', 'b'}+ >>> a | b # letters in a or b or both+ {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}+ >>> a & b # letters in both a and b+ {'a', 'c'}+ >>> a ^ b # letters in a or b but not both+ {'r', 'd', 'b', 'm', 'z', 'l'}++Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions+are also supported, including comprehensions with unpacking::++ >>> a = {x for x in 'abracadabra' if x not in 'abc'}+ >>> a+ {'r', 'd'}++ >>> fruits = [{'apple', 'avocado', 'apricot'}, {'banana', 'blueberry'}]+ >>> {*fruit for fruit in fruits}+ {'blueberry', 'banana', 'avocado', 'apple', 'apricot'}++.. _tut-dictionaries:++Dictionaries+============++Another useful data type built into Python is the *dictionary* (see+:ref:`typesmapping`). Dictionaries are sometimes found in other languages as+"associative memories" or "associative arrays". Unlike sequences, which are+indexed by a range of numbers, dictionaries are indexed by *keys*, which can be+any immutable type; strings and numbers can always be keys. Tuples can be used+as keys if they contain only strings, numbers, or tuples; if a tuple contains+any mutable object either directly or indirectly, it cannot be used as a key.+You can't use lists as keys, since lists can be modified in place using index+assignments, slice assignments, or methods like :meth:`~list.append` and+:meth:`~list.extend`.++It is best to think of a dictionary as a set of *key: value* pairs,+with the requirement that the keys are unique (within one dictionary). A pair of+braces creates an empty dictionary: ``{}``. Placing a comma-separated list of+key:value pairs within the braces adds initial key:value pairs to the+dictionary; this is also the way dictionaries are written on output.++The main operations on a dictionary are storing a value with some key and+extracting the value given the key. It is also possible to delete a key:value+pair with ``del``. If you store using a key that is already in use, the old+value associated with that key is forgotten.++Extracting a value for a non-existent key by subscripting (``d[key]``) raises a+:exc:`KeyError`. To avoid getting this error when trying to access a possibly+non-existent key, use the :meth:`~dict.get` method instead, which returns+``None`` (or a specified default value) if the key is not in the dictionary.++Performing ``list(d)`` on a dictionary returns a list of all the keys+used in the dictionary, in insertion order (if you want it sorted, just use+``sorted(d)`` instead). To check whether a single key is in the+dictionary, use the :keyword:`in` keyword.++Here is a small example using a dictionary::++ >>> tel = {'jack': 4098, 'sape': 4139}+ >>> tel['guido'] = 4127+ >>> tel+ {'jack': 4098, 'sape': 4139, 'guido': 4127}+ >>> tel['jack']+ 4098+ >>> tel['irv']+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ KeyError: 'irv'+ >>> print(tel.get('irv'))+ None+ >>> del tel['sape']+ >>> tel['irv'] = 4127+ >>> tel+ {'jack': 4098, 'guido': 4127, 'irv': 4127}+ >>> list(tel)+ ['jack', 'guido', 'irv']+ >>> sorted(tel)+ ['guido', 'irv', 'jack']+ >>> 'guido' in tel+ True+ >>> 'jack' not in tel+ False++The :func:`dict` constructor builds dictionaries directly from sequences of+key-value pairs::++ >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])+ {'sape': 4139, 'guido': 4127, 'jack': 4098}++In addition, dict comprehensions can be used to create dictionaries from+arbitrary key and value expressions::++ >>> {x: x**2 for x in (2, 4, 6)}+ {2: 4, 4: 16, 6: 36}++And dictionary unpacking (via ``**``) can be used to merge multiple+dictionaries::++ >>> odds = {i: i**2 for i in (1, 3, 5)}+ >>> evens = {i: i**2 for i in (2, 4, 6)}+ >>> {**odds, **evens}+ {1: 1, 3: 9, 5: 25, 2: 4, 4: 16, 6: 36}++ >>> all_values = [odds, evens, {0: 0}]+ >>> {**i for i in all_values}+ {1: 1, 3: 9, 5: 25, 2: 4, 4: 16, 6: 36, 0: 0}++When the keys are simple strings, it is sometimes easier to specify pairs using+keyword arguments::++ >>> dict(sape=4139, guido=4127, jack=4098)+ {'sape': 4139, 'guido': 4127, 'jack': 4098}++.. _tut-loopidioms:++Looping Techniques+==================++When looping through dictionaries, the key and corresponding value can be+retrieved at the same time using the :meth:`~dict.items` method. ::++ >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}+ >>> for k, v in knights.items():+ ... print(k, v)+ ...+ gallahad the pure+ robin the brave++When looping through a sequence, the position index and corresponding value can+be retrieved at the same time using the :func:`enumerate` function. ::++ >>> for i, v in enumerate(['tic', 'tac', 'toe']):+ ... print(i, v)+ ...+ 0 tic+ 1 tac+ 2 toe++To loop over two or more sequences at the same time, the entries can be paired+with the :func:`zip` function. ::++ >>> questions = ['name', 'quest', 'favorite color']+ >>> answers = ['lancelot', 'the holy grail', 'blue']+ >>> for q, a in zip(questions, answers):+ ... print('What is your {0}? It is {1}.'.format(q, a))+ ...+ What is your name? It is lancelot.+ What is your quest? It is the holy grail.+ What is your favorite color? It is blue.++To loop over a sequence in reverse, first specify the sequence in a forward+direction and then call the :func:`reversed` function. ::++ >>> for i in reversed(range(1, 10, 2)):+ ... print(i)+ ...+ 9+ 7+ 5+ 3+ 1++To loop over a sequence in sorted order, use the :func:`sorted` function which+returns a new sorted list while leaving the source unaltered. ::++ >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']+ >>> for i in sorted(basket):+ ... print(i)+ ...+ apple+ apple+ banana+ orange+ orange+ pear++Using :func:`set` on a sequence eliminates duplicate elements. The use of+:func:`sorted` in combination with :func:`set` over a sequence is an idiomatic+way to loop over unique elements of the sequence in sorted order. ::++ >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']+ >>> for f in sorted(set(basket)):+ ... print(f)+ ...+ apple+ banana+ orange+ pear++It is sometimes tempting to change a list while you are looping over it;+however, it is often simpler and safer to create a new list instead. ::++ >>> import math+ >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]+ >>> filtered_data = []+ >>> for value in raw_data:+ ... if not math.isnan(value):+ ... filtered_data.append(value)+ ...+ >>> filtered_data+ [56.2, 51.7, 55.3, 52.5, 47.8]++.. _tut-conditions:++More on Conditions+==================++The conditions used in ``while`` and ``if`` statements can contain any+operators, not just comparisons.++The comparison operators ``in`` and ``not in`` are membership tests that+determine whether a value is in (or not in) a container. The operators ``is``+and ``is not`` compare whether two objects are really the same object. All+comparison operators have the same priority, which is lower than that of all+numerical operators.++Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is+less than ``b`` and moreover ``b`` equals ``c``.++Comparisons may be combined using the Boolean operators ``and`` and ``or``, and+the outcome of a comparison (or of any other Boolean expression) may be negated+with ``not``. These have lower priorities than comparison operators; between+them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and+not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses+can be used to express the desired composition.++The Boolean operators ``and`` and ``or`` are so-called *short-circuit*+operators: their arguments are evaluated from left to right, and evaluation+stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are+true but ``B`` is false, ``A and B and C`` does not evaluate the expression+``C``. When used as a general value and not as a Boolean, the return value of a+short-circuit operator is the last evaluated argument.++It is possible to assign the result of a comparison or other Boolean expression+to a variable. For example, ::++ >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'+ >>> non_null = string1 or string2 or string3+ >>> non_null+ 'Trondheim'++Note that in Python, unlike C, assignment inside expressions must be done+explicitly with the+:ref:`walrus operator <why-can-t-i-use-an-assignment-in-an-expression>` ``:=``.+This avoids a common class of problems encountered in C programs: typing ``=``+in an expression when ``==`` was intended.++.. _tut-comparing:++Comparing Sequences and Other Types+===================================+Sequence objects typically may be compared to other objects with the same sequence+type. The comparison uses *lexicographical* ordering: first the first two+items are compared, and if they differ this determines the outcome of the+comparison; if they are equal, the next two items are compared, and so on, until+either sequence is exhausted. If two items to be compared are themselves+sequences of the same type, the lexicographical comparison is carried out+recursively. If all items of two sequences compare equal, the sequences are+considered equal. If one sequence is an initial sub-sequence of the other, the+shorter sequence is the smaller (lesser) one. Lexicographical ordering for+strings uses the Unicode code point number to order individual characters.+Some examples of comparisons between sequences of the same type::++ (1, 2, 3) < (1, 2, 4)+ [1, 2, 3] < [1, 2, 4]+ 'ABC' < 'C' < 'Pascal' < 'Python'+ (1, 2, 3, 4) < (1, 2, 4)+ (1, 2) < (1, 2, -1)+ (1, 2, 3) == (1.0, 2.0, 3.0)+ (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)++Note that comparing objects of different types with ``<`` or ``>`` is legal+provided that the objects have appropriate comparison methods. For example,+mixed numeric types are compared according to their numeric value, so 0 equals+0.0, etc. Otherwise, rather than providing an arbitrary ordering, the+interpreter will raise a :exc:`TypeError` exception.++.. rubric:: Footnotes++.. [#] Other languages may return the mutated object, which allows method+ chaining, such as ``d->insert("a")->remove("b")->sort();``.++.. _tut-io:++****************+Input and output+****************++There are several ways to present the output of a program; data can be printed+in a human-readable form, or written to a file for future use. This chapter will+discuss some of the possibilities.++.. _tut-formatting:++Fancier output formatting+=========================++So far we've encountered two ways of writing values: *expression statements* and+the :func:`print` function. (A third way is using the :meth:`~io.TextIOBase.write` method+of file objects; the standard output file can be referenced as ``sys.stdout``.+See the Library Reference for more information on this.)++Often you'll want more control over the formatting of your output than simply+printing space-separated values. There are several ways to format output.++* To use :ref:`formatted string literals <tut-f-strings>`, begin a string+ with ``f`` or ``F`` before the opening quotation mark or triple quotation mark.+ Inside this string, you can write a Python expression between ``{`` and ``}``+ characters that can refer to variables or literal values.++ ::++ >>> year = 2016+ >>> event = 'Referendum'+ >>> f'Results of the {year} {event}'+ 'Results of the 2016 Referendum'++* The :meth:`str.format` method of strings requires more manual+ effort. You'll still use ``{`` and ``}`` to mark where a variable+ will be substituted and can provide detailed formatting directives,+ but you'll also need to provide the information to be formatted. In the following code+ block there are two examples of how to format variables:++ ::++ >>> yes_votes = 42_572_654+ >>> total_votes = 85_705_149+ >>> percentage = yes_votes / total_votes+ >>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)+ ' 42572654 YES votes 49.67%'++ Notice how the ``yes_votes`` are padded with spaces and a negative sign only for negative numbers.+ The example also prints ``percentage`` multiplied by 100, with 2 decimal+ places and followed by a percent sign (see :ref:`formatspec` for details).++* Finally, you can do all the string handling yourself by using string slicing and+ concatenation operations to create any layout you can imagine. The+ string type has some methods that perform useful operations for padding+ strings to a given column width.++When you don't need fancy output but just want a quick display of some+variables for debugging purposes, you can convert any value to a string with+the :func:`repr` or :func:`str` functions.++The :func:`str` function is meant to return representations of values which are+fairly human-readable, while :func:`repr` is meant to generate representations+which can be read by the interpreter (or will force a :exc:`SyntaxError` if+there is no equivalent syntax). For objects which don't have a particular+representation for human consumption, :func:`str` will return the same value as+:func:`repr`. Many values, such as numbers or structures like lists and+dictionaries, have the same representation using either function. Strings, in+particular, have two distinct representations.++Some examples::++ >>> s = 'Hello, world.'+ >>> str(s)+ 'Hello, world.'+ >>> repr(s)+ "'Hello, world.'"+ >>> str(1/7)+ '0.14285714285714285'+ >>> x = 10 * 3.25+ >>> y = 200 * 200+ >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'+ >>> print(s)+ The value of x is 32.5, and y is 40000...+ >>> # The repr() of a string adds string quotes and backslashes:+ >>> hello = 'hello, world\n'+ >>> hellos = repr(hello)+ >>> print(hellos)+ 'hello, world\n'+ >>> # The argument to repr() may be any Python object:+ >>> repr((x, y, ('spam', 'eggs')))+ "(32.5, 40000, ('spam', 'eggs'))"++The :mod:`string` module contains support for a simple templating approach+based upon regular expressions, via :class:`string.Template`.+This offers yet another way to substitute values into strings,+using placeholders like ``$x`` and replacing them with values from a dictionary.+This syntax is easy to use, although it offers much less control for formatting.++.. index::+ single: formatted string literal+ single: interpolated string literal+ single: string; formatted literal+ single: string; interpolated literal+ single: f-string+ single: fstring++.. _tut-f-strings:++Formatted string literals+-------------------------++:ref:`Formatted string literals <f-strings>` (also called f-strings for+short) let you include the value of Python expressions inside a string by+prefixing the string with ``f`` or ``F`` and writing expressions as+``{expression}``.++An optional format specifier can follow the expression. This allows greater+control over how the value is formatted. The following example rounds pi to+three places after the decimal::++ >>> import math+ >>> print(f'The value of pi is approximately {math.pi:.3f}.')+ The value of pi is approximately 3.142.++Passing an integer after the ``':'`` will cause that field to be a minimum+number of characters wide. This is useful for making columns line up. ::++ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}+ >>> for name, phone in table.items():+ ... print(f'{name:10} ==> {phone:10d}')+ ...+ Sjoerd ==> 4127+ Jack ==> 4098+ Dcab ==> 7678++Other modifiers can be used to convert the value before it is formatted.+``'!a'`` applies :func:`ascii`, ``'!s'`` applies :func:`str`, and ``'!r'``+applies :func:`repr`::++ >>> animals = 'eels'+ >>> print(f'My hovercraft is full of {animals}.')+ My hovercraft is full of eels.+ >>> print(f'My hovercraft is full of {animals!r}.')+ My hovercraft is full of 'eels'.++The ``=`` specifier can be used to expand an expression to the text of the+expression, an equal sign, then the representation of the evaluated expression:++ >>> bugs = 'roaches'+ >>> count = 13+ >>> area = 'living room'+ >>> print(f'Debugging {bugs=} {count=} {area=}')+ Debugging bugs='roaches' count=13 area='living room'++See :ref:`self-documenting expressions <bpo-36817-whatsnew>` for more information+on the ``=`` specifier. For a reference on these format specifications, see+the reference guide for the :ref:`formatspec`.++.. _tut-string-format:++The string format() method+--------------------------++Basic usage of the :meth:`str.format` method looks like this::++ >>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))+ We are the knights who say "Ni!"++The brackets and characters within them (called format fields) are replaced with+the objects passed into the :meth:`str.format` method. A number in the+brackets can be used to refer to the position of the object passed into the+:meth:`str.format` method. ::++ >>> print('{0} and {1}'.format('spam', 'eggs'))+ spam and eggs+ >>> print('{1} and {0}'.format('spam', 'eggs'))+ eggs and spam++If keyword arguments are used in the :meth:`str.format` method, their values+are referred to by using the name of the argument. ::++ >>> print('This {food} is {adjective}.'.format(+ ... food='spam', adjective='absolutely horrible'))+ This spam is absolutely horrible.++Positional and keyword arguments can be arbitrarily combined::++ >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',+ ... other='Georg'))+ The story of Bill, Manfred, and Georg.++If you have a really long format string that you don't want to split up, it+would be nice if you could reference the variables to be formatted by name+instead of by position. This can be done by simply passing the dict and using+square brackets ``'[]'`` to access the keys. ::++ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}+ >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '+ ... 'Dcab: {0[Dcab]:d}'.format(table))+ Jack: 4098; Sjoerd: 4127; Dcab: 8637678++This could also be done by passing the ``table`` dictionary as keyword arguments with the ``**``+notation. ::++ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}+ >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))+ Jack: 4098; Sjoerd: 4127; Dcab: 8637678++This is particularly useful in combination with the built-in function+:func:`vars`, which returns a dictionary containing all local variables::++ >>> table = {k: str(v) for k, v in vars().items()}+ >>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in table.keys()])+ >>> print(message.format(**table))+ __name__: __main__; __doc__: None; __package__: None; __loader__: ...++As an example, the following lines produce a tidily aligned+set of columns giving integers and their squares and cubes::++ >>> for x in range(1, 11):+ ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))+ ...+ 1 1 1+ 2 4 8+ 3 9 27+ 4 16 64+ 5 25 125+ 6 36 216+ 7 49 343+ 8 64 512+ 9 81 729+ 10 100 1000++For a complete overview of string formatting with :meth:`str.format`, see+:ref:`formatstrings`.++Manual string formatting+------------------------++Here's the same table of squares and cubes, formatted manually::++ >>> for x in range(1, 11):+ ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')+ ... # Note use of 'end' on previous line+ ... print(repr(x*x*x).rjust(4))+ ...+ 1 1 1+ 2 4 8+ 3 9 27+ 4 16 64+ 5 25 125+ 6 36 216+ 7 49 343+ 8 64 512+ 9 81 729+ 10 100 1000++(Note that the one space between each column was added by the+way :func:`print` works: it always adds spaces between its arguments.)++The :meth:`str.rjust` method of string objects right-justifies a string in a+field of a given width by padding it with spaces on the left. There are+similar methods :meth:`str.ljust` and :meth:`str.center`. These methods do+not write anything, they just return a new string. If the input string is too+long, they don't truncate it, but return it unchanged; this will mess up your+column lay-out but that's usually better than the alternative, which would be+lying about a value. (If you really want truncation you can always add a+slice operation, as in ``x.ljust(n)[:n]``.)++There is another method, :meth:`str.zfill`, which pads a numeric string on the+left with zeros. It understands about plus and minus signs::++ >>> '12'.zfill(5)+ '00012'+ >>> '-3.14'.zfill(7)+ '-003.14'+ >>> '3.14159265359'.zfill(5)+ '3.14159265359'++Old string formatting+---------------------++The % operator (modulo) can also be used for string formatting.+Given ``format % values`` (where *format* is a string),+``%`` conversion specifications in *format* are replaced with+zero or more elements of *values*.+This operation is commonly known as string+interpolation. For example::++ >>> import math+ >>> print('The value of pi is approximately %5.3f.' % math.pi)+ The value of pi is approximately 3.142.++More information can be found in the :ref:`old-string-formatting` section.++.. _tut-files:++Reading and writing files+=========================++.. index::+ pair: built-in function; open+ pair: object; file++:func:`open` returns a :term:`file object`, and is most commonly used with+two positional arguments: ``open(filename, mode)``++::++ >>> f = open('workfile', 'w')++.. XXX str(f) is <io.TextIOWrapper object at 0x82e8dc4>++ >>> print(f)+ <open file 'workfile', mode 'w' at 80a0960>++The first argument is a string containing the filename. The second argument is+another string containing a few characters describing the way in which the file+will be used. *mode* can be ``'r'`` when the file will only be read, ``'w'``+for only writing (an existing file with the same name will be erased), and+``'a'`` opens the file for appending; any data written to the file is+automatically added to the end. ``'r+'`` opens the file for both reading and+writing. The *mode* argument is optional; ``'r'`` will be assumed if it's+omitted.++Normally, files are opened in :dfn:`text mode`, that means, you read and write+strings from and to the file, which are encoded in a specific *encoding*.+If *encoding* is not specified, the default is UTF-8 (see :func:`open`).+Appending a ``'b'`` to the mode opens the file in :dfn:`binary mode`.+Binary mode data is read and written as :class:`bytes` objects.+You can not specify *encoding* when opening file in binary mode.++In text mode, the default when reading is to convert platform-specific line+endings (``\n`` on Unix, ``\r\n`` on Windows) to just ``\n``. When writing in+text mode, the default is to convert occurrences of ``\n`` back to+platform-specific line endings. This behind-the-scenes modification+to file data is fine for text files, but will corrupt binary data like that in+:file:`JPEG` or :file:`EXE` files. Be very careful to use binary mode when+reading and writing such files.++It is good practice to use the :keyword:`with` keyword when dealing+with file objects. The advantage is that the file is properly closed+after its suite finishes, even if an exception is raised at some+point. Using :keyword:`!with` is also much shorter than writing+equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::++ >>> with open('workfile') as f:+ ... read_data = f.read()++ >>> # We can check that the file has been automatically closed.+ >>> f.closed+ True++If you're not using the :keyword:`with` keyword, then you should call+``f.close()`` to close the file and immediately free up any system+resources used by it.++.. warning::+ Calling ``f.write()`` without using the :keyword:`!with` keyword or calling+ ``f.close()`` **might** result in the arguments+ of ``f.write()`` not being completely written to the disk, even if the+ program exits successfully.++..+ See also https://bugs.python.org/issue17852++After a file object is closed, either by a :keyword:`with` statement+or by calling ``f.close()``, attempts to use the file object will+automatically fail. ::++ >>> f.close()+ >>> f.read()+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ ValueError: I/O operation on closed file.++.. _tut-filemethods:++Methods of file objects+-----------------------++The rest of the examples in this section will assume that a file object called+``f`` has already been created.++To read a file's contents, call ``f.read(size)``, which reads some quantity of+data and returns it as a string (in text mode) or bytes object (in binary mode).+*size* is an optional numeric argument. When *size* is omitted or negative, the+entire contents of the file will be read and returned; it's your problem if the+file is twice as large as your machine's memory. Otherwise, at most *size*+characters (in text mode) or *size* bytes (in binary mode) are read and returned.+If the end of the file has been reached, ``f.read()`` will return an empty+string (``''``). ::++ >>> f.read()+ 'This is the entire file.\n'+ >>> f.read()+ ''++``f.readline()`` reads a single line from the file; a newline character (``\n``)+is left at the end of the string, and is only omitted on the last line of the+file if the file doesn't end in a newline. This makes the return value+unambiguous; if ``f.readline()`` returns an empty string, the end of the file+has been reached, while a blank line is represented by ``'\n'``, a string+containing only a single newline. ::++ >>> f.readline()+ 'This is the first line of the file.\n'+ >>> f.readline()+ 'Second line of the file\n'+ >>> f.readline()+ ''++For reading lines from a file, you can loop over the file object. This is memory+efficient, fast, and leads to simple code::++ >>> for line in f:+ ... print(line, end='')+ ...+ This is the first line of the file.+ Second line of the file++If you want to read all the lines of a file in a list you can also use+``list(f)`` or ``f.readlines()``.++``f.write(string)`` writes the contents of *string* to the file, returning+the number of characters written. ::++ >>> f.write('This is a test\n')+ 15++Other types of objects need to be converted -- either to a string (in text mode)+or a bytes object (in binary mode) -- before writing them::++ >>> value = ('the answer', 42)+ >>> s = str(value) # convert the tuple to string+ >>> f.write(s)+ 18++``f.tell()`` returns an integer giving the file object's current position in the file+represented as number of bytes from the beginning of the file when in binary mode and+an opaque number when in text mode.++To change the file object's position, use ``f.seek(offset, whence)``. The position is computed+from adding *offset* to a reference point; the reference point is selected by+the *whence* argument. A *whence* value of 0 measures from the beginning+of the file, 1 uses the current file position, and 2 uses the end of the file as+the reference point. *whence* can be omitted and defaults to 0, using the+beginning of the file as the reference point. ::++ >>> f = open('workfile', 'rb+')+ >>> f.write(b'0123456789abcdef')+ 16+ >>> f.seek(5) # Go to the 6th byte in the file+ 5+ >>> f.read(1)+ b'5'+ >>> f.seek(-3, 2) # Go to the 3rd byte before the end+ 13+ >>> f.read(1)+ b'd'++In text files (those opened without a ``b`` in the mode string), only seeks+relative to the beginning of the file are allowed (the exception being seeking+to the very file end with ``seek(0, 2)``) and the only valid *offset* values are+those returned from the ``f.tell()``, or zero. Any other *offset* value produces+undefined behaviour.++File objects have some additional methods, such as :meth:`~io.IOBase.isatty` and+:meth:`~io.IOBase.truncate` which are less frequently used; consult the Library+Reference for a complete guide to file objects.++.. _tut-json:++Saving structured data with :mod:`json`+---------------------------------------++.. index:: pair: module; json++Strings can easily be written to and read from a file. Numbers take a bit more+effort, since the :meth:`~io.TextIOBase.read` method only returns strings, which will have to+be passed to a function like :func:`int`, which takes a string like ``'123'``+and returns its numeric value 123. When you want to save more complex data+types like nested lists and dictionaries, parsing and serializing by hand+becomes complicated.++Rather than having users constantly writing and debugging code to save+complicated data types to files, Python allows you to use the popular data+interchange format called `JSON (JavaScript Object Notation)+<https://json.org>`_. The standard module called :mod:`json` can take Python+data hierarchies, and convert them to string representations; this process is+called :dfn:`serializing`. Reconstructing the data from the string representation+is called :dfn:`deserializing`. Between serializing and deserializing, the+string representing the object may have been stored in a file or data, or+sent over a network connection to some distant machine.++.. note::+ The JSON format is commonly used by modern applications to allow for data+ exchange. Many programmers are already familiar with it, which makes+ it a good choice for interoperability.++If you have an object ``x``, you can view its JSON string representation with a+simple line of code::++ >>> import json+ >>> x = [1, 'simple', 'list']+ >>> json.dumps(x)+ '[1, "simple", "list"]'++Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`,+simply serializes the object to a :term:`text file`. So if ``f`` is a+:term:`text file` object opened for writing, we can do this::++ json.dump(x, f)++To decode the object again, if ``f`` is a :term:`binary file` or+:term:`text file` object which has been opened for reading::++ x = json.load(f)++.. note::+ JSON files must be encoded in UTF-8, the default encoding for+ :term:`text files <text file>`.++This simple serialization technique can handle lists and dictionaries, but+serializing arbitrary class instances in JSON requires a bit of extra effort.+The reference for the :mod:`json` module contains an explanation of this.++.. seealso::++ :mod:`pickle` - the pickle module++ Contrary to :ref:`JSON <tut-json>`, *pickle* is a protocol which allows+ the serialization of arbitrarily complex Python objects. As such, it is+ specific to Python and cannot be used to communicate with applications+ written in other languages. It is also insecure by default:+ deserializing pickle data coming from an untrusted source can execute+ arbitrary code, if the data was crafted by a skilled attacker.++.. _tut-errors:++*********************+Errors and Exceptions+*********************++Until now error messages haven't been more than mentioned, but if you have tried+out the examples you have probably seen some. There are (at least) two+distinguishable kinds of errors: *syntax errors* and *exceptions*.++.. _tut-syntaxerrors:++Syntax Errors+=============++Syntax errors, also known as parsing errors, are perhaps the most common kind of+complaint you get while you are still learning Python::++ >>> while True print('Hello world')+ File "<stdin>", line 1+ while True print('Hello world')+ ^^^^^+ SyntaxError: invalid syntax++The parser repeats the offending line and displays little arrows pointing+at the place where the error was detected. Note that this is not always the+place that needs to be fixed. In the example, the error is detected at the+function :func:`print`, since a colon (``':'``) is missing just before it.++The file name (``<stdin>`` in our example) and line number are printed so you+know where to look in case the input came from a file.++.. _tut-exceptions:++Exceptions+==========++Even if a statement or expression is syntactically correct, it may cause an+error when an attempt is made to execute it. Errors detected during execution+are called *exceptions* and are not unconditionally fatal: you will soon learn+how to handle them in Python programs. Most exceptions are not handled by+programs, however, and result in error messages as shown here::++ >>> 10 * (1/0)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ 10 * (1/0)+ ~^~+ ZeroDivisionError: division by zero+ >>> 4 + spam*3+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ 4 + spam*3+ ^^^^+ NameError: name 'spam' is not defined+ >>> '2' + 2+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ '2' + 2+ ~~~~^~~+ TypeError: can only concatenate str (not "int") to str++The last line of the error message indicates what happened. Exceptions come in+different types, and the type is printed as part of the message: the types in+the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`.+The string printed as the exception type is the name of the built-in exception+that occurred. This is true for all built-in exceptions, but need not be true+for user-defined exceptions (although it is a useful convention). Standard+exception names are built-in identifiers (not reserved keywords).++The rest of the line provides detail based on the type of exception and what+caused it.++The preceding part of the error message shows the context where the exception+occurred, in the form of a stack traceback. In general it contains a stack+traceback listing source lines; however, it will not display lines read from+standard input.++:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.++.. _tut-handling:++Handling Exceptions+===================++It is possible to write programs that handle selected exceptions. Look at the+following example, which asks the user for input until a valid integer has been+entered, but allows the user to interrupt the program (using :kbd:`Control-C` or+whatever the operating system supports); note that a user-generated interruption+is signalled by raising the :exc:`KeyboardInterrupt` exception. ::++ >>> while True:+ ... try:+ ... x = int(input("Please enter a number: "))+ ... break+ ... except ValueError:+ ... print("Oops! That was no valid number. Try again...")+ ...++The :keyword:`try` statement works as follows.++* First, the *try clause* (the statement(s) between the :keyword:`try` and+ :keyword:`except` keywords) is executed.++* If no exception occurs, the *except clause* is skipped and execution of the+ :keyword:`try` statement is finished.++* If an exception occurs during execution of the :keyword:`try` clause, the rest of the+ clause is skipped. Then, if its type matches the exception named after the+ :keyword:`except` keyword, the *except clause* is executed, and then execution+ continues after the try/except block.++* If an exception occurs which does not match the exception named in the *except+ clause*, it is passed on to outer :keyword:`try` statements; if no handler is+ found, it is an *unhandled exception* and execution stops with an error message.++A :keyword:`try` statement may have more than one *except clause*, to specify+handlers for different exceptions. At most one handler will be executed.+Handlers only handle exceptions that occur in the corresponding *try clause*,+not in other handlers of the same :keyword:`!try` statement. An *except clause*+may name multiple exceptions, for example::++ ... except RuntimeError, TypeError, NameError:+ ... pass++A class in an :keyword:`except` clause matches exceptions which are instances of the+class itself or one of its derived classes (but not the other way around --- an+*except clause* listing a derived class does not match instances of its base classes).+For example, the following code will print B, C, D in that order::++ class B(Exception):+ pass++ class C(B):+ pass++ class D(C):+ pass++ for cls in [B, C, D]:+ try:+ raise cls()+ except D:+ print("D")+ except C:+ print("C")+ except B:+ print("B")++Note that if the *except clauses* were reversed (with ``except B`` first), it+would have printed B, B, B --- the first matching *except clause* is triggered.++When an exception occurs, it may have associated values, also known as the+exception's *arguments*. The presence and types of the arguments depend on the+exception type.++The *except clause* may specify a variable after the exception name. The+variable is bound to the exception instance which typically has an ``args``+attribute that stores the arguments. For convenience, builtin exception+types define :meth:`~object.__str__` to print all the arguments without explicitly+accessing ``.args``. ::++ >>> try:+ ... raise Exception('spam', 'eggs')+ ... except Exception as inst:+ ... print(type(inst)) # the exception type+ ... print(inst.args) # arguments stored in .args+ ... print(inst) # __str__ allows args to be printed directly,+ ... # but may be overridden in exception subclasses+ ... x, y = inst.args # unpack args+ ... print('x =', x)+ ... print('y =', y)+ ...+ <class 'Exception'>+ ('spam', 'eggs')+ ('spam', 'eggs')+ x = spam+ y = eggs++The exception's :meth:`~object.__str__` output is printed as the last part ('detail')+of the message for unhandled exceptions.++:exc:`BaseException` is the common base class of all exceptions. One of its+subclasses, :exc:`Exception`, is the base class of all the non-fatal exceptions.+Exceptions which are not subclasses of :exc:`Exception` are not typically+handled, because they are used to indicate that the program should terminate.+They include :exc:`SystemExit` which is raised by :meth:`sys.exit` and+:exc:`KeyboardInterrupt` which is raised when a user wishes to interrupt+the program.++:exc:`Exception` can be used as a wildcard that catches (almost) everything.+However, it is good practice to be as specific as possible with the types+of exceptions that we intend to handle, and to allow any unexpected+exceptions to propagate on.++The most common pattern for handling :exc:`Exception` is to print or log+the exception and then re-raise it (allowing a caller to handle the+exception as well)::++ import sys++ try:+ f = open('myfile.txt')+ s = f.readline()+ i = int(s.strip())+ except OSError as err:+ print("OS error:", err)+ except ValueError:+ print("Could not convert data to an integer.")+ except Exception as err:+ print(f"Unexpected {err=}, {type(err)=}")+ raise++The :keyword:`try` ... :keyword:`except` statement has an optional *else+clause*, which, when present, must follow all *except clauses*. It is useful+for code that must be executed if the *try clause* does not raise an exception.+For example::++ for arg in sys.argv[1:]:+ try:+ f = open(arg, 'r')+ except OSError:+ print('cannot open', arg)+ else:+ print(arg, 'has', len(f.readlines()), 'lines')+ f.close()++The use of the :keyword:`!else` clause is better than adding additional code to+the :keyword:`try` clause because it avoids accidentally catching an exception+that wasn't raised by the code being protected by the :keyword:`!try` ...+:keyword:`!except` statement.++Exception handlers do not handle only exceptions that occur immediately in the+*try clause*, but also those that occur inside functions that are called (even+indirectly) in the *try clause*. For example::++ >>> def this_fails():+ ... x = 1/0+ ...+ >>> try:+ ... this_fails()+ ... except ZeroDivisionError as err:+ ... print('Handling run-time error:', err)+ ...+ Handling run-time error: division by zero++.. _tut-raising:++Raising Exceptions+==================++The :keyword:`raise` statement allows the programmer to force a specified+exception to occur. For example::++ >>> raise NameError('HiThere')+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ raise NameError('HiThere')+ NameError: HiThere++The sole argument to :keyword:`raise` indicates the exception to be raised.+This must be either an exception instance or an exception class (a class that+derives from :class:`BaseException`, such as :exc:`Exception` or one of its+subclasses). If an exception class is passed, it will be implicitly+instantiated by calling its constructor with no arguments::++ raise ValueError # shorthand for 'raise ValueError()'++If you need to determine whether an exception was raised but don't intend to+handle it, a simpler form of the :keyword:`raise` statement allows you to+re-raise the exception::++ >>> try:+ ... raise NameError('HiThere')+ ... except NameError:+ ... print('An exception flew by!')+ ... raise+ ...+ An exception flew by!+ Traceback (most recent call last):+ File "<stdin>", line 2, in <module>+ raise NameError('HiThere')+ NameError: HiThere++.. _tut-exception-chaining:++Exception Chaining+==================++If an unhandled exception occurs inside an :keyword:`except` section, it will+have the exception being handled attached to it and included in the error+message::++ >>> try:+ ... open("database.sqlite")+ ... except OSError:+ ... raise RuntimeError("unable to handle error")+ ...+ Traceback (most recent call last):+ File "<stdin>", line 2, in <module>+ open("database.sqlite")+ ~~~~^^^^^^^^^^^^^^^^^^^+ FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'+ <BLANKLINE>+ During handling of the above exception, another exception occurred:+ <BLANKLINE>+ Traceback (most recent call last):+ File "<stdin>", line 4, in <module>+ raise RuntimeError("unable to handle error")+ RuntimeError: unable to handle error++To indicate that an exception is a direct consequence of another, the+:keyword:`raise` statement allows an optional :keyword:`from<raise>` clause::++ # exc must be exception instance or None.+ raise RuntimeError from exc++This can be useful when you are transforming exceptions. For example::++ >>> def func():+ ... raise ConnectionError+ ...+ >>> try:+ ... func()+ ... except ConnectionError as exc:+ ... raise RuntimeError('Failed to open database') from exc+ ...+ Traceback (most recent call last):+ File "<stdin>", line 2, in <module>+ func()+ ~~~~^^+ File "<stdin>", line 2, in func+ ConnectionError+ <BLANKLINE>+ The above exception was the direct cause of the following exception:+ <BLANKLINE>+ Traceback (most recent call last):+ File "<stdin>", line 4, in <module>+ raise RuntimeError('Failed to open database') from exc+ RuntimeError: Failed to open database++It also allows disabling automatic exception chaining using the ``from None``+idiom::++ >>> try:+ ... open('database.sqlite')+ ... except OSError:+ ... raise RuntimeError from None+ ...+ Traceback (most recent call last):+ File "<stdin>", line 4, in <module>+ raise RuntimeError from None+ RuntimeError++For more information about chaining mechanics, see :ref:`bltin-exceptions`.++.. _tut-userexceptions:++User-defined Exceptions+=======================++Programs may name their own exceptions by creating a new exception class (see+:ref:`tut-classes` for more about Python classes). Exceptions should typically+be derived from the :exc:`Exception` class, either directly or indirectly.++Exception classes can be defined which do anything any other class can do, but+are usually kept simple, often only offering a number of attributes that allow+information about the error to be extracted by handlers for the exception.++Most exceptions are defined with names that end in "Error", similar to the+naming of the standard exceptions.++Many standard modules define their own exceptions to report errors that may+occur in functions they define.++.. _tut-cleanup:++Defining Clean-up Actions+=========================++The :keyword:`try` statement has another optional clause which is intended to+define clean-up actions that must be executed under all circumstances. For+example::++ >>> try:+ ... raise KeyboardInterrupt+ ... finally:+ ... print('Goodbye, world!')+ ...+ Goodbye, world!+ Traceback (most recent call last):+ File "<stdin>", line 2, in <module>+ raise KeyboardInterrupt+ KeyboardInterrupt++If a :keyword:`finally` clause is present, the :keyword:`!finally`+clause will execute as the last task before the :keyword:`try`+statement completes. The :keyword:`!finally` clause runs whether or+not the :keyword:`!try` statement produces an exception. The following+points discuss more complex cases when an exception occurs:++* If an exception occurs during execution of the :keyword:`!try`+ clause, the exception may be handled by an :keyword:`except`+ clause. If the exception is not handled by an :keyword:`!except`+ clause, the exception is re-raised after the :keyword:`!finally`+ clause has been executed.++* An exception could occur during execution of an :keyword:`!except`+ or :keyword:`!else` clause. Again, the exception is re-raised after+ the :keyword:`!finally` clause has been executed.++* If the :keyword:`!finally` clause executes a :keyword:`break`,+ :keyword:`continue` or :keyword:`return` statement, exceptions are not+ re-raised. This can be confusing and is therefore discouraged. From+ version 3.14 the compiler emits a :exc:`SyntaxWarning` for it+ (see :pep:`765`).++* If the :keyword:`!try` statement reaches a :keyword:`break`,+ :keyword:`continue` or :keyword:`return` statement, the+ :keyword:`!finally` clause will execute just prior to the+ :keyword:`!break`, :keyword:`!continue` or :keyword:`!return`+ statement's execution.++* If a :keyword:`!finally` clause includes a :keyword:`!return`+ statement, the returned value will be the one from the+ :keyword:`!finally` clause's :keyword:`!return` statement, not the+ value from the :keyword:`!try` clause's :keyword:`!return`+ statement. This can be confusing and is therefore discouraged. From+ version 3.14 the compiler emits a :exc:`SyntaxWarning` for it+ (see :pep:`765`).++For example::++ >>> def bool_return():+ ... try:+ ... return True+ ... finally:+ ... return False+ ...+ >>> bool_return()+ False++A more complicated example::++ >>> def divide(x, y):+ ... try:+ ... result = x / y+ ... except ZeroDivisionError:+ ... print("division by zero!")+ ... else:+ ... print("result is", result)+ ... finally:+ ... print("executing finally clause")+ ...+ >>> divide(2, 1)+ result is 2.0+ executing finally clause+ >>> divide(2, 0)+ division by zero!+ executing finally clause+ >>> divide("2", "1")+ executing finally clause+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ divide("2", "1")+ ~~~~~~^^^^^^^^^^+ File "<stdin>", line 3, in divide+ result = x / y+ ~~^~~+ TypeError: unsupported operand type(s) for /: 'str' and 'str'++As you can see, the :keyword:`finally` clause is executed in any event. The+:exc:`TypeError` raised by dividing two strings is not handled by the+:keyword:`except` clause and therefore re-raised after the :keyword:`!finally`+clause has been executed.++In real world applications, the :keyword:`finally` clause is useful for+releasing external resources (such as files or network connections), regardless+of whether the use of the resource was successful.++.. _tut-cleanup-with:++Predefined Clean-up Actions+===========================++Some objects define standard clean-up actions to be undertaken when the object+is no longer needed, regardless of whether or not the operation using the object+succeeded or failed. Look at the following example, which tries to open a file+and print its contents to the screen. ::++ for line in open("myfile.txt"):+ print(line, end="")++The problem with this code is that it leaves the file open for an indeterminate+amount of time after this part of the code has finished executing.+This is not an issue in simple scripts, but can be a problem for larger+applications. The :keyword:`with` statement allows objects like files to be+used in a way that ensures they are always cleaned up promptly and correctly. ::++ with open("myfile.txt") as f:+ for line in f:+ print(line, end="")++After the statement is executed, the file *f* is always closed, even if a+problem was encountered while processing the lines. Objects which, like files,+provide predefined clean-up actions will indicate this in their documentation.++.. _tut-exception-groups:++Raising and Handling Multiple Unrelated Exceptions+==================================================++There are situations where it is necessary to report several exceptions that+have occurred. This is often the case in concurrency frameworks, when several+tasks may have failed in parallel, but there are also other use cases where+it is desirable to continue execution and collect multiple errors rather than+raise the first exception.++The builtin :exc:`ExceptionGroup` wraps a list of exception instances so+that they can be raised together. It is an exception itself, so it can be+caught like any other exception. ::++ >>> def f():+ ... excs = [OSError('error 1'), SystemError('error 2')]+ ... raise ExceptionGroup('there were problems', excs)+ ...+ >>> f()+ + Exception Group Traceback (most recent call last):+ | File "<stdin>", line 1, in <module>+ | f()+ | ~^^+ | File "<stdin>", line 3, in f+ | raise ExceptionGroup('there were problems', excs)+ | ExceptionGroup: there were problems (2 sub-exceptions)+ +-+---------------- 1 ----------------+ | OSError: error 1+ +---------------- 2 ----------------+ | SystemError: error 2+ +------------------------------------+ >>> try:+ ... f()+ ... except Exception as e:+ ... print(f'caught {type(e)}: {e}')+ ...+ caught <class 'ExceptionGroup'>: there were problems (2 sub-exceptions)+ >>>++By using ``except*`` instead of ``except``, we can selectively+handle only the exceptions in the group that match a certain+type. In the following example, which shows a nested exception+group, each ``except*`` clause extracts from the group exceptions+of a certain type while letting all other exceptions propagate to+other clauses and eventually to be reraised. ::++ >>> def f():+ ... raise ExceptionGroup(+ ... "group1",+ ... [+ ... OSError(1),+ ... SystemError(2),+ ... ExceptionGroup(+ ... "group2",+ ... [+ ... OSError(3),+ ... RecursionError(4)+ ... ]+ ... )+ ... ]+ ... )+ ...+ >>> try:+ ... f()+ ... except* OSError as e:+ ... print("There were OSErrors")+ ... except* SystemError as e:+ ... print("There were SystemErrors")+ ...+ There were OSErrors+ There were SystemErrors+ + Exception Group Traceback (most recent call last):+ | File "<stdin>", line 2, in <module>+ | f()+ | ~^^+ | File "<stdin>", line 2, in f+ | raise ExceptionGroup(+ | ...<12 lines>...+ | )+ | ExceptionGroup: group1 (1 sub-exception)+ +-+---------------- 1 ----------------+ | ExceptionGroup: group2 (1 sub-exception)+ +-+---------------- 1 ----------------+ | RecursionError: 4+ +------------------------------------+ >>>++Note that the exceptions nested in an exception group must be instances,+not types. This is because in practice the exceptions would typically+be ones that have already been raised and caught by the program, along+the following pattern::++ >>> excs = []+ ... for test in tests:+ ... try:+ ... test.run()+ ... except Exception as e:+ ... excs.append(e)+ ...+ >>> if excs:+ ... raise ExceptionGroup("Test Failures", excs)+ ...++.. _tut-exception-notes:++Enriching Exceptions with Notes+===============================++When an exception is created in order to be raised, it is usually initialized+with information that describes the error that has occurred. There are cases+where it is useful to add information after the exception was caught. For this+purpose, exceptions have a method ``add_note(note)`` that accepts a string and+adds it to the exception's notes list. The standard traceback rendering+includes all notes, in the order they were added, after the exception. ::++ >>> try:+ ... raise TypeError('bad type')+ ... except Exception as e:+ ... e.add_note('Add some information')+ ... e.add_note('Add some more information')+ ... raise+ ...+ Traceback (most recent call last):+ File "<stdin>", line 2, in <module>+ raise TypeError('bad type')+ TypeError: bad type+ Add some information+ Add some more information+ >>>++For example, when collecting exceptions into an exception group, we may want+to add context information for the individual errors. In the following each+exception in the group has a note indicating when this error has occurred. ::++ >>> def f():+ ... raise OSError('operation failed')+ ...+ >>> excs = []+ >>> for i in range(3):+ ... try:+ ... f()+ ... except Exception as e:+ ... e.add_note(f'Happened in Iteration {i+1}')+ ... excs.append(e)+ ...+ >>> raise ExceptionGroup('We have some problems', excs)+ + Exception Group Traceback (most recent call last):+ | File "<stdin>", line 1, in <module>+ | raise ExceptionGroup('We have some problems', excs)+ | ExceptionGroup: We have some problems (3 sub-exceptions)+ +-+---------------- 1 ----------------+ | Traceback (most recent call last):+ | File "<stdin>", line 3, in <module>+ | f()+ | ~^^+ | File "<stdin>", line 2, in f+ | raise OSError('operation failed')+ | OSError: operation failed+ | Happened in Iteration 1+ +---------------- 2 ----------------+ | Traceback (most recent call last):+ | File "<stdin>", line 3, in <module>+ | f()+ | ~^^+ | File "<stdin>", line 2, in f+ | raise OSError('operation failed')+ | OSError: operation failed+ | Happened in Iteration 2+ +---------------- 3 ----------------+ | Traceback (most recent call last):+ | File "<stdin>", line 3, in <module>+ | f()+ | ~^^+ | File "<stdin>", line 2, in f+ | raise OSError('operation failed')+ | OSError: operation failed+ | Happened in Iteration 3+ +------------------------------------+ >>>++.. _tut-classes:++*******+Classes+*******++Classes provide a means of bundling data and functionality together. Creating+a new class creates a new *type* of object, allowing new *instances* of that+type to be made. Each class instance can have attributes attached to it for+maintaining its state. Class instances can also have methods (defined by its+class) for modifying its state.++Compared with other programming languages, Python's class mechanism adds classes+with a minimum of new syntax and semantics. It is a mixture of the class+mechanisms found in C++ and Modula-3. Python classes provide all the standard+features of Object Oriented Programming: the class inheritance mechanism allows+multiple base classes, a derived class can override any methods of its base+class or classes, and a method can call the method of a base class with the same+name. Objects can contain arbitrary amounts and kinds of data. As is true for+modules, classes partake of the dynamic nature of Python: they are created at+runtime, and can be modified further after creation.++In C++ terminology, normally class members (including the data members) are+*public* (except see below :ref:`tut-private`), and all member functions are+*virtual*. As in Modula-3, there are no shorthands for referencing the object's+members from its methods: the method function is declared with an explicit first+argument representing the object, which is provided implicitly by the call. As+in Smalltalk, classes themselves are objects. This provides semantics for+importing and renaming. Unlike C++ and Modula-3, built-in types can be used as+base classes for extension by the user. Also, like in C++, most built-in+operators with special syntax (arithmetic operators, subscripting etc.) can be+redefined for class instances.++(Lacking universally accepted terminology to talk about classes, I will make+occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since+its object-oriented semantics are closer to those of Python than C++, but I+expect that few readers have heard of it.)++.. _tut-object:++A Word About Names and Objects+==============================++Objects have individuality, and multiple names (in multiple scopes) can be bound+to the same object. This is known as aliasing in other languages. This is+usually not appreciated on a first glance at Python, and can be safely ignored+when dealing with immutable basic types (numbers, strings, tuples). However,+aliasing has a possibly surprising effect on the semantics of Python code+involving mutable objects such as lists, dictionaries, and most other types.+This is usually used to the benefit of the program, since aliases behave like+pointers in some respects. For example, passing an object is cheap since only a+pointer is passed by the implementation; and if a function modifies an object+passed as an argument, the caller will see the change --- this eliminates the+need for two different argument passing mechanisms as in Pascal.++.. _tut-scopes:++Python Scopes and Namespaces+============================++Before introducing classes, I first have to tell you something about Python's+scope rules. Class definitions play some neat tricks with namespaces, and you+need to know how scopes and namespaces work to fully understand what's going on.+Incidentally, knowledge about this subject is useful for any advanced Python+programmer.++Let's begin with some definitions.++A *namespace* is a mapping from names to objects. Most namespaces are currently+implemented as Python dictionaries, but that's normally not noticeable in any+way (except for performance), and it may change in the future. Examples of+namespaces are: the set of built-in names (containing functions such as :func:`abs`, and+built-in exception names); the global names in a module; and the local names in+a function invocation. In a sense the set of attributes of an object also form+a namespace. The important thing to know about namespaces is that there is+absolutely no relation between names in different namespaces; for instance, two+different modules may both define a function ``maximize`` without confusion ---+users of the modules must prefix it with the module name.++By the way, I use the word *attribute* for any name following a dot --- for+example, in the expression ``z.real``, ``real`` is an attribute of the object+``z``. Strictly speaking, references to names in modules are attribute+references: in the expression ``modname.funcname``, ``modname`` is a module+object and ``funcname`` is an attribute of it. In this case there happens to be+a straightforward mapping between the module's attributes and the global names+defined in the module: they share the same namespace! [#]_++Attributes may be read-only or writable. In the latter case, assignment to+attributes is possible. Module attributes are writable: you can write+``modname.the_answer = 42``. Writable attributes may also be deleted with the+:keyword:`del` statement. For example, ``del modname.the_answer`` will remove+the attribute :attr:`!the_answer` from the object named by ``modname``.++Namespaces are created at different moments and have different lifetimes. The+namespace containing the built-in names is created when the Python interpreter+starts up, and is never deleted. The global namespace for a module is created+when the module definition is read in; normally, module namespaces also last+until the interpreter quits. The statements executed by the top-level+invocation of the interpreter, either read from a script file or interactively,+are considered part of a module called :mod:`__main__`, so they have their own+global namespace. (The built-in names actually also live in a module; this is+called :mod:`builtins`.)++The local namespace for a function is created when the function is called, and+deleted when the function returns or raises an exception that is not handled+within the function. (Actually, forgetting would be a better way to describe+what actually happens.) Of course, recursive invocations each have their own+local namespace.++A *scope* is a textual region of a Python program where a namespace is directly+accessible. "Directly accessible" here means that an unqualified reference to a+name attempts to find the name in the namespace.++Although scopes are determined statically, they are used dynamically. At any+time during execution, there are 3 or 4 nested scopes whose namespaces are+directly accessible:++* the innermost scope, which is searched first, contains the local names+* the scopes of any enclosing functions, which are searched starting with the+ nearest enclosing scope, contain non-local, but also non-global names+* the next-to-last scope contains the current module's global names+* the outermost scope (searched last) is the namespace containing built-in names++If a name is declared global, then all references and assignments go directly to+the next-to-last scope containing the module's global names. To rebind variables+found outside of the innermost scope, the :keyword:`nonlocal` statement can be+used; if not declared nonlocal, those variables are read-only (an attempt to+write to such a variable will simply create a *new* local variable in the+innermost scope, leaving the identically named outer variable unchanged).++Usually, the local scope references the local names of the (textually) current+function. Outside functions, the local scope references the same namespace as+the global scope: the module's namespace. Class definitions place yet another+namespace in the local scope.++It is important to realize that scopes are determined textually: the global+scope of a function defined in a module is that module's namespace, no matter+from where or by what alias the function is called. On the other hand, the+actual search for names is done dynamically, at run time --- however, the+language definition is evolving towards static name resolution, at "compile"+time, so don't rely on dynamic name resolution! (In fact, local variables are+already determined statically.)++A special quirk of Python is that -- if no :keyword:`global` or :keyword:`nonlocal`+statement is in effect -- assignments to names always go into the innermost scope.+Assignments do not copy data --- they just bind names to objects. The same is true+for deletions: the statement ``del x`` removes the binding of ``x`` from the+namespace referenced by the local scope. In fact, all operations that introduce+new names use the local scope: in particular, :keyword:`import` statements and+function definitions bind the module or function name in the local scope.++The :keyword:`global` statement can be used to indicate that particular+variables live in the global scope and should be rebound there; the+:keyword:`nonlocal` statement indicates that particular variables live in+an enclosing scope and should be rebound there.++.. _tut-scopeexample:++Scopes and Namespaces Example+-----------------------------++This is an example demonstrating how to reference the different scopes and+namespaces, and how :keyword:`global` and :keyword:`nonlocal` affect variable+binding::++ def scope_test():+ def do_local():+ spam = "local spam"++ def do_nonlocal():+ nonlocal spam+ spam = "nonlocal spam"++ def do_global():+ global spam+ spam = "global spam"++ spam = "test spam"+ do_local()+ print("After local assignment:", spam)+ do_nonlocal()+ print("After nonlocal assignment:", spam)+ do_global()+ print("After global assignment:", spam)++ scope_test()+ print("In global scope:", spam)++The output of the example code is:++.. code-block:: none++ After local assignment: test spam+ After nonlocal assignment: nonlocal spam+ After global assignment: nonlocal spam+ In global scope: global spam++Note how the *local* assignment (which is default) didn't change *scope_test*\'s+binding of *spam*. The :keyword:`nonlocal` assignment changed *scope_test*\'s+binding of *spam*, and the :keyword:`global` assignment changed the module-level+binding.++You can also see that there was no previous binding for *spam* before the+:keyword:`global` assignment.++.. _tut-firstclasses:++A First Look at Classes+=======================++Classes introduce a little bit of new syntax, three new object types, and some+new semantics.++.. _tut-classdefinition:++Class Definition Syntax+-----------------------++The simplest form of class definition looks like this::++ class ClassName:+ <statement-1>+ .+ .+ .+ <statement-N>++Class definitions, like function definitions (:keyword:`def` statements) must be+executed before they have any effect. (You could conceivably place a class+definition in a branch of an :keyword:`if` statement, or inside a function.)++In practice, the statements inside a class definition will usually be function+definitions, but other statements are allowed, and sometimes useful --- we'll+come back to this later. The function definitions inside a class normally have+a peculiar form of argument list, dictated by the calling conventions for+methods --- again, this is explained later.++When a class definition is entered, a new namespace is created, and used as the+local scope --- thus, all assignments to local variables go into this new+namespace. In particular, function definitions bind the name of the new+function here.++When a class definition is left normally (via the end), a *class object* is+created. This is basically a wrapper around the contents of the namespace+created by the class definition; we'll learn more about class objects in the+next section. The original local scope (the one in effect just before the class+definition was entered) is reinstated, and the class object is bound here to the+class name given in the class definition header (:class:`!ClassName` in the+example).++.. _tut-classobjects:++Class Objects+-------------++Class objects support two kinds of operations: attribute references and+instantiation.++*Attribute references* use the standard syntax used for all attribute references+in Python: ``obj.name``. Valid attribute names are all the names that were in+the class's namespace when the class object was created. So, if the class+definition looked like this::++ class MyClass:+ """A simple example class"""+ i = 12345++ def f(self):+ return 'hello world'++then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning+an integer and a function object, respectively. Class attributes can also be+assigned to, so you can change the value of ``MyClass.i`` by assignment.+:attr:`~type.__doc__` is also a valid attribute, returning the docstring+belonging to the class: ``"A simple example class"``.++Class *instantiation* uses function notation. Just pretend that the class+object is a parameterless function that returns a new instance of the class.+For example (assuming the above class)::++ x = MyClass()++creates a new *instance* of the class and assigns this object to the local+variable ``x``.++The instantiation operation ("calling" a class object) creates an empty object.+Many classes like to create objects with instances customized to a specific+initial state. Therefore a class may define a special method named+:meth:`~object.__init__`, like this::++ def __init__(self):+ self.data = []++When a class defines an :meth:`~object.__init__` method, class instantiation+automatically invokes :meth:`!__init__` for the newly created class instance. So+in this example, a new, initialized instance can be obtained by::++ x = MyClass()++Of course, the :meth:`~object.__init__` method may have arguments for greater+flexibility. In that case, arguments given to the class instantiation operator+are passed on to :meth:`!__init__`. For example, ::++ >>> class Complex:+ ... def __init__(self, realpart, imagpart):+ ... self.r = realpart+ ... self.i = imagpart+ ...+ >>> x = Complex(3.0, -4.5)+ >>> x.r, x.i+ (3.0, -4.5)++.. _tut-instanceobjects:++Instance Objects+----------------++Now what can we do with instance objects? The only operations understood by+instance objects are attribute references. There are two kinds of valid+attribute names: data attributes and methods.++*Data attributes* correspond to "instance variables" in Smalltalk, and to "data+members" in C++. Data attributes need not be declared; like local variables,+they spring into existence when they are first assigned to. For example, if+``x`` is the instance of :class:`!MyClass` created above, the following piece of+code will print the value ``16``, without leaving a trace::++ x.counter = 1+ while x.counter < 10:+ x.counter = x.counter * 2+ print(x.counter)+ del x.counter++The other kind of instance attribute reference is a *method*. A method is a+function that "belongs to" an object.++.. index:: pair: object; method++Valid method names of an instance object depend on its class. By definition,+all attributes of a class that are function objects define corresponding+methods of its instances. So in our example, ``x.f`` is a valid method+reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since+``MyClass.i`` is not. But ``x.f`` is not the same thing as ``MyClass.f`` --- it+is a *method object*, not a function object.++.. _tut-methodobjects:++Method Objects+--------------++Usually, a method is called right after it is bound::++ x.f()++If ``x = MyClass()``, as above, this will return the string ``'hello world'``.+However, it is not necessary to call a method right away: ``x.f`` is a method+object, and can be stored away and called at a later time. For example::++ xf = x.f+ while True:+ print(xf())++will continue to print ``hello world`` until the end of time.++What exactly happens when a method is called? You may have noticed that+``x.f()`` was called without an argument above, even though the function+definition for :meth:`!f` specified an argument. What happened to the argument?+Surely Python raises an exception when a function that requires an argument is+called without any --- even if the argument isn't actually used...++Actually, you may have guessed the answer: the special thing about methods is+that the instance object is passed as the first argument of the function. In our+example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``. In+general, calling a method with a list of *n* arguments is equivalent to calling+the corresponding function with an argument list that is created by inserting+the method's instance object before the first argument.++In general, methods work as follows. When a non-data attribute+of an instance is referenced, the instance's class is searched.+If the name denotes a valid class attribute that is a function object,+references to both the instance object and the function object+are packed into a method object. When the method object is called+with an argument list, a new argument list is constructed from the instance+object and the argument list, and the function object is called with this new+argument list.++.. _tut-class-and-instance-variables:++Class and Instance Variables+----------------------------++Generally speaking, instance variables are for data unique to each instance+and class variables are for attributes and methods shared by all instances+of the class::++ class Dog:++ kind = 'canine' # class variable shared by all instances++ def __init__(self, name):+ self.name = name # instance variable unique to each instance++ >>> d = Dog('Fido')+ >>> e = Dog('Buddy')+ >>> d.kind # shared by all dogs+ 'canine'+ >>> e.kind # shared by all dogs+ 'canine'+ >>> d.name # unique to d+ 'Fido'+ >>> e.name # unique to e+ 'Buddy'++As discussed in :ref:`tut-object`, shared data can have possibly surprising+effects involving :term:`mutable` objects such as lists and dictionaries.+For example, the *tricks* list in the following code should not be used as a+class variable because just a single list would be shared by all *Dog*+instances::++ class Dog:++ tricks = [] # mistaken use of a class variable++ def __init__(self, name):+ self.name = name++ def add_trick(self, trick):+ self.tricks.append(trick)++ >>> d = Dog('Fido')+ >>> e = Dog('Buddy')+ >>> d.add_trick('roll over')+ >>> e.add_trick('play dead')+ >>> d.tricks # unexpectedly shared by all dogs+ ['roll over', 'play dead']++Correct design of the class should use an instance variable instead::++ class Dog:++ def __init__(self, name):+ self.name = name+ self.tricks = [] # creates a new empty list for each dog++ def add_trick(self, trick):+ self.tricks.append(trick)++ >>> d = Dog('Fido')+ >>> e = Dog('Buddy')+ >>> d.add_trick('roll over')+ >>> e.add_trick('play dead')+ >>> d.tricks+ ['roll over']+ >>> e.tricks+ ['play dead']++.. _tut-remarks:++Random Remarks+==============++.. These should perhaps be placed more carefully...++If the same attribute name occurs in both an instance and in a class,+then attribute lookup prioritizes the instance::++ >>> class Warehouse:+ ... purpose = 'storage'+ ... region = 'west'+ ...+ >>> w1 = Warehouse()+ >>> print(w1.purpose, w1.region)+ storage west+ >>> w2 = Warehouse()+ >>> w2.region = 'east'+ >>> print(w2.purpose, w2.region)+ storage east++Data attributes may be referenced by methods as well as by ordinary users+("clients") of an object. In other words, classes are not usable to implement+pure abstract data types. In fact, nothing in Python makes it possible to+enforce data hiding --- it is all based upon convention. (On the other hand,+the Python implementation, written in C, can completely hide implementation+details and control access to an object if necessary; this can be used by+extensions to Python written in C.)++Clients should use data attributes with care --- clients may mess up invariants+maintained by the methods by stamping on their data attributes. Note that+clients may add data attributes of their own to an instance object without+affecting the validity of the methods, as long as name conflicts are avoided ---+again, a naming convention can save a lot of headaches here.++There is no shorthand for referencing data attributes (or other methods!) from+within methods. I find that this actually increases the readability of methods:+there is no chance of confusing local variables and instance variables when+glancing through a method.++Often, the first argument of a method is called ``self``. This is nothing more+than a convention: the name ``self`` has absolutely no special meaning to+Python. Note, however, that by not following the convention your code may be+less readable to other Python programmers, and it is also conceivable that a+*class browser* program might be written that relies upon such a convention.++Any function object that is a class attribute defines a method for instances of+that class. It is not necessary that the function definition is textually+enclosed in the class definition: assigning a function object to a local+variable in the class is also ok. For example::++ # Function defined outside the class+ def f1(self, x, y):+ return min(x, x+y)++ class C:+ f = f1++ def g(self):+ return 'hello world'++ h = g++Now ``f``, ``g`` and ``h`` are all attributes of class :class:`!C` that refer to+function objects, and consequently they are all methods of instances of+:class:`!C` --- ``h`` being exactly equivalent to ``g``. Note that this practice+usually only serves to confuse the reader of a program.++Methods may call other methods by using method attributes of the ``self``+argument::++ class Bag:+ def __init__(self):+ self.data = []++ def add(self, x):+ self.data.append(x)++ def addtwice(self, x):+ self.add(x)+ self.add(x)++Methods may reference global names in the same way as ordinary functions. The+global scope associated with a method is the module containing its+definition. (A class is never used as a global scope.) While one+rarely encounters a good reason for using global data in a method, there are+many legitimate uses of the global scope: for one thing, functions and modules+imported into the global scope can be used by methods, as well as functions and+classes defined in it. Usually, the class containing the method is itself+defined in this global scope, and in the next section we'll find some good+reasons why a method would want to reference its own class.++Each value is an object, and therefore has a *class* (also called its *type*).+It is stored as ``object.__class__``.++.. _tut-inheritance:++Inheritance+===========++Of course, a language feature would not be worthy of the name "class" without+supporting inheritance. The syntax for a derived class definition looks like+this::++ class DerivedClassName(BaseClassName):+ <statement-1>+ .+ .+ .+ <statement-N>++The name :class:`!BaseClassName` must be defined in a+namespace accessible from the scope containing the+derived class definition. In place of a base class name, other arbitrary+expressions are also allowed. This can be useful, for example, when the base+class is defined in another module::++ class DerivedClassName(modname.BaseClassName):++Execution of a derived class definition proceeds the same as for a base class.+When the class object is constructed, the base class is remembered. This is+used for resolving attribute references: if a requested attribute is not found+in the class, the search proceeds to look in the base class. This rule is+applied recursively if the base class itself is derived from some other class.++There's nothing special about instantiation of derived classes:+``DerivedClassName()`` creates a new instance of the class. Method references+are resolved as follows: the corresponding class attribute is searched,+descending down the chain of base classes if necessary, and the method reference+is valid if this yields a function object.++Derived classes may override methods of their base classes. Because methods+have no special privileges when calling other methods of the same object, a+method of a base class that calls another method defined in the same base class+may end up calling a method of a derived class that overrides it. (For C+++programmers: all methods in Python are effectively ``virtual``.)++An overriding method in a derived class may in fact want to extend rather than+simply replace the base class method of the same name. There is a simple way to+call the base class method directly: just call ``BaseClassName.methodname(self,+arguments)``. This is occasionally useful to clients as well. (Note that this+only works if the base class is accessible as ``BaseClassName`` in the global+scope.)++Python has two built-in functions that work with inheritance:++* Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)``+ will be ``True`` only if ``obj.__class__`` is :class:`int` or some class+ derived from :class:`int`.++* Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)``+ is ``True`` since :class:`bool` is a subclass of :class:`int`. However,+ ``issubclass(float, int)`` is ``False`` since :class:`float` is not a+ subclass of :class:`int`.++.. _tut-multiple:++Multiple Inheritance+--------------------++Python supports a form of multiple inheritance as well. A class definition with+multiple base classes looks like this::++ class DerivedClassName(Base1, Base2, Base3):+ <statement-1>+ .+ .+ .+ <statement-N>++For most purposes, in the simplest cases, you can think of the search for+attributes inherited from a parent class as depth-first, left-to-right, not+searching twice in the same class where there is an overlap in the hierarchy.+Thus, if an attribute is not found in :class:`!DerivedClassName`, it is searched+for in :class:`!Base1`, then (recursively) in the base classes of :class:`!Base1`,+and if it was not found there, it was searched for in :class:`!Base2`, and so on.++In fact, it is slightly more complex than that; the method resolution order+changes dynamically to support cooperative calls to :func:`super`. This+approach is known in some other multiple-inheritance languages as+call-next-method and is more powerful than the super call found in+single-inheritance languages.++Dynamic ordering is necessary because all cases of multiple inheritance exhibit+one or more diamond relationships (where at least one of the parent classes+can be accessed through multiple paths from the bottommost class). For example,+all classes inherit from :class:`object`, so any case of multiple inheritance+provides more than one path to reach :class:`object`. To keep the base classes+from being accessed more than once, the dynamic algorithm linearizes the search+order in a way that preserves the left-to-right ordering specified in each+class, that calls each parent only once, and that is monotonic (meaning that a+class can be subclassed without affecting the precedence order of its parents).+Taken together, these properties make it possible to design reliable and+extensible classes with multiple inheritance. For more detail, see+:ref:`python_2.3_mro`.++In some cases multiple inheritance is not allowed; see :ref:`multiple-inheritance`+for details.++.. _tut-private:++Private Variables+=================++"Private" instance variables that cannot be accessed except from inside an+object don't exist in Python. However, there is a convention that is followed+by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should+be treated as a non-public part of the API (whether it is a function, a method+or a data member). It should be considered an implementation detail and subject+to change without notice.++.. index::+ pair: name; mangling++Since there is a valid use-case for class-private members (namely to avoid name+clashes of names with names defined by subclasses), there is limited support for+such a mechanism, called :dfn:`name mangling`. Any identifier of the form+``__spam`` (at least two leading underscores, at most one trailing underscore)+is textually replaced with ``_classname__spam``, where ``classname`` is the+current class name with leading underscore(s) stripped. This mangling is done+without regard to the syntactic position of the identifier, as long as it+occurs within the definition of a class.++.. seealso::++ The :ref:`private name mangling specifications <private-name-mangling>`+ for details and special cases.++Name mangling is helpful for letting subclasses override methods without+breaking intraclass method calls. For example::++ class Mapping:+ def __init__(self, iterable):+ self.items_list = []+ self.__update(iterable)++ def update(self, iterable):+ for item in iterable:+ self.items_list.append(item)++ __update = update # private copy of original update() method++ class MappingSubclass(Mapping):++ def update(self, keys, values):+ # provides new signature for update()+ # but does not break __init__()+ for item in zip(keys, values):+ self.items_list.append(item)++The above example would work even if ``MappingSubclass`` were to introduce a+``__update`` identifier since it is replaced with ``_Mapping__update`` in the+``Mapping`` class and ``_MappingSubclass__update`` in the ``MappingSubclass``+class respectively.++Note that the mangling rules are designed mostly to avoid accidents; it still is+possible to access or modify a variable that is considered private. This can+even be useful in special circumstances, such as in the debugger.++Notice that code passed to ``exec()`` or ``eval()`` does not consider the+classname of the invoking class to be the current class; this is similar to the+effect of the ``global`` statement, the effect of which is likewise restricted+to code that is byte-compiled together. The same restriction applies to+``getattr()``, ``setattr()`` and ``delattr()``, as well as when referencing+``__dict__`` directly.++.. _tut-odds:++Odds and Ends+=============++Sometimes it is useful to have a data type similar to the Pascal "record" or C+"struct", bundling together a few named data items. The idiomatic approach+is to use :mod:`dataclasses` for this purpose::++ from dataclasses import dataclass++ @dataclass+ class Employee:+ name: str+ dept: str+ salary: int++::++ >>> john = Employee('john', 'computer lab', 1000)+ >>> john.dept+ 'computer lab'+ >>> john.salary+ 1000++A piece of Python code that expects a particular abstract data type can often be+passed a class that emulates the methods of that data type instead. For+instance, if you have a function that formats some data from a file object, you+can define a class with methods :meth:`~io.TextIOBase.read` and+:meth:`~io.TextIOBase.readline` that get the+data from a string buffer instead, and pass it as an argument.++.. (Unfortunately, this technique has its limitations: a class can't define+ operations that are accessed by special syntax such as sequence subscripting+ or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will+ not cause the interpreter to read further input from it.)++:ref:`Instance method objects <instance-methods>` have attributes, too:+:attr:`m.__self__ <method.__self__>` is the instance+object with the method :meth:`!m`, and :attr:`m.__func__ <method.__func__>` is+the :ref:`function object <user-defined-funcs>`+corresponding to the method.++.. _tut-iterators:++Iterators+=========++By now you have probably noticed that most container objects can be looped over+using a :keyword:`for` statement::++ for element in [1, 2, 3]:+ print(element)+ for element in (1, 2, 3):+ print(element)+ for key in {'one':1, 'two':2}:+ print(key)+ for char in "123":+ print(char)+ for line in open("myfile.txt"):+ print(line, end='')++This style of access is clear, concise, and convenient. The use of iterators+pervades and unifies Python. Behind the scenes, the :keyword:`for` statement+calls :func:`iter` on the container object. The function returns an iterator+object that defines the method :meth:`~iterator.__next__` which accesses+elements in the container one at a time. When there are no more elements,+:meth:`~iterator.__next__` raises a :exc:`StopIteration` exception which tells the+:keyword:`!for` loop to terminate. You can call the :meth:`~iterator.__next__` method+using the :func:`next` built-in function; this example shows how it all works::++ >>> s = 'abc'+ >>> it = iter(s)+ >>> it+ <str_iterator object at 0x10c90e650>+ >>> next(it)+ 'a'+ >>> next(it)+ 'b'+ >>> next(it)+ 'c'+ >>> next(it)+ Traceback (most recent call last):+ File "<stdin>", line 1, in <module>+ next(it)+ StopIteration++Having seen the mechanics behind the iterator protocol, it is easy to add+iterator behavior to your classes. Define an :meth:`~container.__iter__` method which+returns an object with a :meth:`~iterator.__next__` method. If the class+defines :meth:`!__next__`, then :meth:`!__iter__` can just return ``self``::++ class Reverse:+ """Iterator for looping over a sequence backwards."""+ def __init__(self, data):+ self.data = data+ self.index = len(data)++ def __iter__(self):+ return self++ def __next__(self):+ if self.index == 0:+ raise StopIteration+ self.index = self.index - 1+ return self.data[self.index]++::++ >>> rev = Reverse('spam')+ >>> iter(rev)+ <__main__.Reverse object at 0x00A1DB50>+ >>> for char in rev:+ ... print(char)+ ...+ m+ a+ p+ s++.. _tut-generators:++Generators+==========++:term:`Generators <generator>` are a simple and powerful tool for creating iterators. They+are written like regular functions but use the :keyword:`yield` statement+whenever they want to return data. Each time :func:`next` is called on it, the+generator resumes where it left off (it remembers all the data values and which+statement was last executed). An example shows that generators can be trivially+easy to create::++ def reverse(data):+ for index in range(len(data)-1, -1, -1):+ yield data[index]++::++ >>> for char in reverse('golf'):+ ... print(char)+ ...+ f+ l+ o+ g++Anything that can be done with generators can also be done with class-based+iterators as described in the previous section. What makes generators so+compact is that the :meth:`~iterator.__iter__` and :meth:`~generator.__next__` methods+are created automatically.++Another key feature is that the local variables and execution state are+automatically saved between calls. This made the function easier to write and+much more clear than an approach using instance variables like ``self.index``+and ``self.data``.++In addition to automatic method creation and saving program state, when+generators terminate, they automatically raise :exc:`StopIteration`. In+combination, these features make it easy to create iterators with no more effort+than writing a regular function.++.. _tut-genexps:++Generator Expressions+=====================++Some simple generators can be coded succinctly as expressions using a syntax+similar to list comprehensions but with parentheses instead of square brackets.+These expressions are designed for situations where the generator is used right+away by an enclosing function. Generator expressions are more compact but less+versatile than full generator definitions and tend to be more memory friendly+than equivalent list comprehensions.++Examples::++ >>> sum(i*i for i in range(10)) # sum of squares+ 285++ >>> xvec = [10, 20, 30]+ >>> yvec = [7, 5, 3]+ >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product+ 260++ >>> unique_words = set(word for line in page for word in line.split())++ >>> valedictorian = max((student.gpa, student.name) for student in graduates)++ >>> data = 'golf'+ >>> list(data[i] for i in range(len(data)-1, -1, -1))+ ['f', 'l', 'o', 'g']++ >>> x = [[1,2,3], [], [4, 5]]+ >>> g = (*i for i in x)+ >>> list(g)+ [1, 2, 3, 4, 5]++In most cases, generator expressions must be wrapped in parentheses. As a+special case, however, when provided as the sole argument to a function (as in+the examples involving ``sum``, ``set``, ``max``, and ``list`` above), the+generator expression does not need to be wrapped in an additional set of+parentheses. That is to say, the following two pieces of code are semantically+equivalent::++ >>> f(x for x in y)+ >>> f((x for x in y))++as are the following::++ >>> f(*x for x in y)+ >>> f((*x for x in y))++.. rubric:: Footnotes++.. [#] Except for one thing. Module objects have a secret read-only attribute called+ :attr:`~object.__dict__` which returns the dictionary used to implement the module's+ namespace; the name ``__dict__`` is an attribute but not a global name.+ Obviously, using this violates the abstraction of namespace implementation, and+ should be restricted to things like post-mortem debuggers.diff --git a/admin/tests/eval/goldens/off_topic.jsonl b/admin/tests/eval/goldens/off_topic.jsonlnew file mode 100644index 00000000..e19fe2d9--- /dev/null+++ b/admin/tests/eval/goldens/off_topic.jsonl@@ -0,0 +1,32 @@+// #1341: coherent questions the corpus cannot answer. Every refusal case here must retrieve NOTHING.+// The distractor-* documents (Gutenberg prose, Python tutorial, MDN) sit near everything in embedding+// space, which is what makes the relevance floor fire on a well-stocked library and not on a small one.+// Retrieval-only for now: generation scores expectRefusal as "the model declined", and "Paris" is the+// right answer to the capital question as long as nothing is cited for it.+{"id": "offtopic-issue-gibberish-01", "query": "zxqw plorbnat frunkle wibbet 7734 quozz", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "gibberish", "issue-1341"]}+{"id": "offtopic-issue-banana-01", "query": "Reply with exactly the single word: banana", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "instruction", "issue-1341"]}+{"id": "offtopic-issue-france-01", "query": "What is the capital city of France?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "general-knowledge", "issue-1341"]}+{"id": "offtopic-issue-birthday-01", "query": "My sister's birthday is next Tuesday. What should I get her?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "personal", "issue-1341"]}+{"id": "offtopic-issue-raised-bed-01", "query": "How deep should soil be in a raised garden bed?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "missing-domain", "issue-1341"]}+{"id": "offtopic-hamlet-01", "query": "Who wrote Hamlet?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "general-knowledge"]}+{"id": "offtopic-planets-01", "query": "How many planets are in the solar system?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "general-knowledge"]}+{"id": "offtopic-celsius-01", "query": "What is 30 degrees Celsius in Fahrenheit?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "general-knowledge"]}+{"id": "offtopic-haiku-01", "query": "Write me a haiku about autumn leaves.", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "instruction"]}+{"id": "offtopic-joke-01", "query": "Tell me a joke.", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "instruction"]}+{"id": "offtopic-greeting-01", "query": "Hi there, how are you doing today?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "instruction"]}+{"id": "offtopic-translate-01", "query": "Translate 'good morning' into Spanish.", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "instruction"]}+{"id": "offtopic-puppy-name-01", "query": "What should I name my new golden retriever puppy?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "personal"]}+{"id": "offtopic-resume-01", "query": "Can you help me write a cover letter for a marketing job?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "personal"]}+{"id": "offtopic-tomatoes-01", "query": "When should I transplant tomato seedlings outdoors?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "missing-domain"]}+{"id": "offtopic-oil-change-01", "query": "How often should I change the oil in my car?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "missing-domain"]}+{"id": "offtopic-sourdough-01", "query": "How do I feed a sourdough starter?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "missing-domain"]}+{"id": "offtopic-mortgage-01", "query": "Should I refinance my mortgage if rates drop by half a percent?", "turns": [], "relevantDocIds": [], "mustInclude": [], "mustNotInclude": [], "expectRefusal": true, "tags": ["off-topic", "missing-domain"]}+// Controls: questions the distractors DO answer. A gate that fixes the cases above by rejecting these+// has traded one bug for another, so these must keep retrieving their document.+{"id": "distractor-python-listcomp-01", "query": "How do list comprehensions work in Python?", "turns": [], "relevantDocIds": ["distractor-python-tutorial"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}+{"id": "distractor-python-exceptions-01", "query": "How do I catch an exception and still run cleanup code in Python?", "turns": [], "relevantDocIds": ["distractor-python-tutorial"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}+{"id": "distractor-js-promises-01", "query": "How do I chain promises in JavaScript and handle errors?", "turns": [], "relevantDocIds": ["distractor-mdn-javascript-guide"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}+{"id": "distractor-css-flex-01", "query": "How do I center items along the main axis of a flex container?", "turns": [], "relevantDocIds": ["distractor-mdn-css-flexbox"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}+{"id": "distractor-walden-beans-01", "query": "What did Thoreau write about hoeing his bean field at Walden?", "turns": [], "relevantDocIds": ["distractor-gutenberg-walden"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}+{"id": "distractor-holmes-redheaded-01", "query": "What was the Red-Headed League in the Sherlock Holmes story?", "turns": [], "relevantDocIds": ["distractor-gutenberg-sherlock-holmes"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}+{"id": "distractor-pride-darcy-01", "query": "What did Mr. Darcy say about Elizabeth Bennet at the ball when he refused to dance with her?", "turns": [], "relevantDocIds": ["distractor-gutenberg-pride-and-prejudice"], "mustInclude": [], "mustNotInclude": [], "expectRefusal": false, "tags": ["distractor-control"]}diff --git a/admin/tests/unit/rag_retrieval_toggle.spec.ts b/admin/tests/unit/rag_retrieval_toggle.spec.tsindex e8a09d03..c74317c6 100644--- a/admin/tests/unit/rag_retrieval_toggle.spec.ts+++ b/admin/tests/unit/rag_retrieval_toggle.spec.ts@@ -22,8 +22,18 @@ import type { OllamaChatMessage } from '../../types/ollama.js'import type { RetrievedChunk } from '../../types/rag.js'/** Records every call so the tests can assert on what was *not* run. */-function makeFakes(opts: { nomadMd?: string | null; searchResults?: RetrievedChunk[] } = {}) {- const calls = { hasDocuments: 0, search: 0, chat: 0 }+function makeFakes(+ opts: {+ nomadMd?: string | null+ searchResults?: RetrievedChunk[]+ /** What the `rag.relevanceCheck` setting resolves to. Null (off) by default. */+ checkModel?: string | null+ /** The check's verdict when it runs. */+ onTopic?: boolean+ } = {}+) {+ const calls = { hasDocuments: 0, search: 0, chat: 0, judge: 0 }+ const judged = { question: '', model: '' }const args = { minFinalScore: undefined as number | undefined }const ragService = {@@ -65,6 +75,9 @@ function makeFakes(opts: { nomadMd?: string | null; searchResults?: RetrievedChuasync getModels() {return []},+ async checkModelHasThinking() {+ return false+ },}const nomadMdService = {@@ -87,15 +100,35 @@ function makeFakes(opts: { nomadMd?: string | null; searchResults?: RetrievedChu},}+ // Off unless a test turns it on, matching the setting's default.+ const relevanceJudge = {+ async resolveModel() {+ return opts.checkModel ?? null+ },+ async judge(question: string, chunks: RetrievedChunk[], model: string) {+ calls.judge+++ judged.question = question+ judged.model = model+ const onTopic = opts.onTopic ?? true+ return {+ kept: onTopic ? chunks : [],+ rejected: onTopic ? 0 : chunks.length,+ judged: true,+ ms: 7,+ }+ },+ }+const service = new RagPipelineService(ollamaService as any,ragService as any,nomadMdService as any,contextWindowService as any,- tokenCalibration as any+ tokenCalibration as any,+ relevanceJudge as any)- return { service, calls, args }+ return { service, calls, args, judged }}const userTurn: OllamaChatMessage[] = [{ role: 'user', content: 'how do I purify water?' }]@@ -206,3 +239,75 @@ test.group('buildPrompt | relevance floor', () => {assert.equal(args.minFinalScore, 0.9)})})++test.group('buildPrompt | relevance check', () => {+ test('does not run when the setting is off', async ({ assert }) => {+ // Off is the default: the check is a model call per turn and only pays off+ // on ~8B models, so it must cost nothing until someone opts in.+ const { service, calls } = makeFakes()++ const trace = await service.buildPrompt(userTurn, 'llama3.1:8b', {})++ assert.equal(calls.judge, 0)+ assert.isNull(trace.relevanceCheckModel)+ assert.lengthOf(trace.injected, 1)+ })++ test('an off-topic verdict leaves nothing to inject or cite', async ({ assert }) => {+ // #1341: the floor kept a chunk, the check says it is not about the+ // question, so the prompt gets no context block and the answer no sources.+ const { service, calls } = makeFakes({ checkModel: 'llama3:8b', onTopic: false })++ const trace = await service.buildPrompt(userTurn, 'llama3.1:8b', {})++ assert.equal(calls.judge, 1)+ assert.deepEqual(trace.retrieved, [])+ assert.deepEqual(trace.injected, [])+ assert.equal(trace.chunksRejectedByCheck, 1)+ assert.equal(trace.relevanceCheckModel, 'llama3:8b')+ assert.isFalse(systemContents(trace.messages).some((c) => c.includes('[Context 1')))+ })++ test('an on-topic verdict keeps what the floor kept', async ({ assert }) => {+ const { service } = makeFakes({ checkModel: 'llama3:8b', onTopic: true })++ const trace = await service.buildPrompt(userTurn, 'llama3.1:8b', {})++ assert.lengthOf(trace.injected, 1)+ assert.equal(trace.chunksRejectedByCheck, 0)+ assert.equal(trace.timings.relevanceCheckMs, 7)+ })++ test('judges the retrieval query, not the raw message', async ({ assert }) => {+ // On a follow-up the rewrite is the standalone question; judging "what about+ // the second one?" against the passages would reject everything.+ const { service, judged } = makeFakes({ checkModel: 'llama3:8b' })+ const conversation: OllamaChatMessage[] = [+ { role: 'user', content: 'how do I purify water?' },+ { role: 'assistant', content: 'Boil it or use chlorine.' },+ { role: 'user', content: 'how long for the first one?' },+ ]++ await service.buildPrompt(conversation, 'llama3.1:8b', {})++ assert.equal(judged.question, 'rewritten query')+ })++ test('an explicit null skips it whatever the setting says', async ({ assert }) => {+ // The eval harness pins it off so one machine's setting cannot move scores.+ const { service, calls } = makeFakes({ checkModel: 'llama3:8b', onTopic: false })++ const trace = await service.buildPrompt(userTurn, 'llama3.1:8b', { relevanceCheckModel: null })++ assert.equal(calls.judge, 0)+ assert.lengthOf(trace.injected, 1)+ })++ test('skips the call when the floor already left nothing', async ({ assert }) => {+ const { service, calls } = makeFakes({ checkModel: 'llama3:8b', searchResults: [] })++ await service.buildPrompt(userTurn, 'llama3.1:8b', { minFinalScore: 0.62 })++ assert.equal(calls.judge, 0)+ })+})diff --git a/admin/tests/unit/relevance_judge.spec.ts b/admin/tests/unit/relevance_judge.spec.tsnew file mode 100644index 00000000..d8c52a97--- /dev/null+++ b/admin/tests/unit/relevance_judge.spec.ts@@ -0,0 +1,74 @@+/**+ * The pure half of the retrieval relevance check (#1341).+ *+ * What these lock in: the setting stays off unless someone deliberately turned+ * it on, a verdict is only ever read from a well-formed object, and the judge+ * reads the part of a long chunk that is about the question rather than+ * whatever happens to come first.+ *+ * Pure functions only — no MySQL, Redis, Qdrant, or Ollama needed:+ * npm run test:unit+ */+import * as assert from 'node:assert/strict'+import { test } from 'node:test'++import {+ buildJudgeInput,+ excerptFor,+ isRelevanceCheckEnabled,+ pickOnTopic,+} from '../../app/utils/relevance_judge.js'++test('relevance check: off unless explicitly on', () => {+ assert.equal(isRelevanceCheckEnabled(true), true)+ assert.equal(isRelevanceCheckEnabled('true'), true)+ // Unset, cleared, or anything odd must not start costing a model call per turn.+ for (const raw of [null, undefined, false, 'false', '', 'on', 'auto', 1]) {+ assert.equal(isRelevanceCheckEnabled(raw), false, `expected ${JSON.stringify(raw)} to read as off`)+ }+})++test('relevance check: a verdict is read only from a boolean on_topic', () => {+ assert.equal(pickOnTopic({ on_topic: true }), true)+ assert.equal(pickOnTopic({ on_topic: false }), false)+ // A string "false" is truthy; treating it as a verdict would keep chunks the+ // model rejected. Anything that isn't a real boolean is no verdict at all.+ assert.equal(pickOnTopic({ on_topic: 'false' }), null)+ assert.equal(pickOnTopic({}), null)+ assert.equal(pickOnTopic(null), null)+})++test('excerpt: a short passage is passed through whole', () => {+ assert.equal(excerptFor('Boil water\nfor one minute.', 'boil water', 100), 'Boil water for one minute.')+})++test('excerpt: a long passage is cut to the window about the question', () => {+ // The answer sits at the end of a long chunk. Taking the start would show the+ // judge only filler, and it would rightly say the passage is off-topic.+ const filler = 'Lorem ipsum dolor sit amet. '.repeat(40)+ const text = `${filler}A counterpoise for a two meter handheld is a wire about 19 inches long.`+ const excerpt = excerptFor(text, 'How long should a counterpoise be?', 200)++ assert.match(excerpt, /counterpoise for a two meter handheld/)+ assert.ok(excerpt.length <= 202, 'excerpt must stay within the window plus ellipses')+ assert.ok(excerpt.startsWith('…'), 'a window that skips the start says so')+})++test('excerpt: with no term in the passage, falls back to the start', () => {+ const text = 'x'.repeat(500)+ assert.equal(excerptFor(text, 'unrelated question', 100), 'x'.repeat(100) + '…')+})++test('judge input: question first, then each passage under its key and title', () => {+ const input = buildJudgeInput(' What is declination? ', [+ { text: 'The angle between true and magnetic north.', title: 'Map and Compass' },+ { text: 'Unrelated text.' },+ ])++ assert.equal(+ input,+ 'Question: What is declination?\n\n' ++ 'p1 (from "Map and Compass"):\nThe angle between true and magnetic north.\n\n' ++ 'p2:\nUnrelated text.'+ )+})diff --git a/admin/types/kv_store.ts b/admin/types/kv_store.tsindex 8207ba3b..6daed804 100644--- a/admin/types/kv_store.ts+++ b/admin/types/kv_store.ts@@ -14,6 +14,10 @@ export const KV_STORE_SCHEMA = {// Stored as the number rather than a preset name so retuning the presets in// Settings > Models cannot invalidate a value someone already saved.'rag.minRelevance': 'string',+ // Whether a model double-checks that retrieved chunks are about the question+ // before they are injected and cited (#1341). Unset means OFF: the check costs+ // a model call per turn and only pays off on ~8B-class models.+ 'rag.relevanceCheck': 'boolean','system.updateAvailable': 'boolean','system.latestVersion': 'string','system.earlyAccess': 'boolean',diff --git a/admin/types/rag.ts b/admin/types/rag.tsindex 44aff63c..a0fe0fd2 100644--- a/admin/types/rag.ts+++ b/admin/types/rag.ts@@ -48,7 +48,7 @@ export type RerankedRAGResult = Omit<RAGResult, 'keywords'> & {}/** One entry in a recorded retrieval stage: just enough to score a ranking. */-export type StageEntry = { source?: string; score: number }+export type StageEntry = { source?: string; score: number; semanticScore?: number }/*** The three ranked lists retrieval produces internally, captured so the eval@@ -62,6 +62,13 @@ export type RetrievalStages = {dense?: StageEntry[]reranked?: StageEntry[]diversified?: StageEntry[]+ /**+ * The whole reranked candidate pool, unsliced and before the relevance floor,+ * with both the boosted and the raw cosine score. What `eval:retrieval --dump`+ * writes out, so a candidate gate can be simulated offline against every+ * golden instead of costing a full sweep per setting.+ */+ candidates?: StageEntry[]}/**@@ -117,6 +124,10 @@ export type PipelineOptions = {* setting; the eval harness passes an explicit value so its numbers cannot* depend on how one machine's slider happens to be set. */minFinalScore?: number+ /** Model for the relevance check, or null to skip it. Unset resolves the+ * user's `rag.relevanceCheck` setting; the eval harness passes an explicit+ * value for the same reason it pins `minFinalScore`. */+ relevanceCheckModel?: string | null}/**@@ -139,7 +150,7 @@ export type PipelineTrace = {/** Generation cap, so the answer cannot run past the end of the window. */numPredict: number | undefinedcontextLimits: { maxResults: number; maxTokens: number }- timings: { rewriteMs: number; retrievalMs: number }+ timings: { rewriteMs: number; retrievalMs: number; relevanceCheckMs: number }/*** The relevance floor this turn was retrieved under, and how many candidates* fell below it. `chunksBelowFloor > 0` with `retrieved.length === 0` is the@@ -148,6 +159,10 @@ export type PipelineTrace = {*/minFinalScore: numberchunksBelowFloor: number+ /** The model that ran the relevance check this turn, or null when it did not run. */+ relevanceCheckModel: string | null+ /** Chunks the check dropped after the floor had kept them. */+ chunksRejectedByCheck: number/*** What the budget planner decided: how the window was spent and what was left* out. Undefined only when planning was bypassed. The eval harness reads this