857 字
4 分钟
代码主题预览(临时页)
⚠️ 这是一个临时页面,只为预览代码块主题(暗色 = Nord)。看完就会删除。
站点默认跟随系统明暗;想对比两套配色,点右上角的明暗切换按钮。
1. Python
from dataclasses import dataclassfrom typing import Iterable
import torch
@dataclass(frozen=True)class Sample: """一条训练样本。""" text: str label: int
def batchify(samples: Iterable[Sample], size: int = 32) -> list[list[Sample]]: batch: list[Sample] = [] for item in samples: batch.append(item) if len(batch) == size: # 满一批就吐出 yield batch batch = [] if batch: yield batch
if __name__ == "__main__": total = sum(1 for _ in batchify([Sample(f"x{i}", i % 2) for i in range(100)])) print(f"batches = {total}, cuda = {torch.cuda.is_available()}")2. C++
#include <algorithm>#include <iostream>#include <queue>#include <vector>
namespace graph {
template <typename T>class BFS {public: explicit BFS(const std::vector<std::vector<int>>& adj) : adj_(adj) {}
std::vector<int> run(int src) const { std::vector<int> dist(adj_.size(), -1); std::queue<int> q; dist[src] = 0; q.push(src); while (!q.empty()) { const int u = q.front(); q.pop(); for (const int v : adj_[u]) { if (dist[v] == -1) { // 未访问 dist[v] = dist[u] + 1; q.push(v); } } } return dist; }
private: const std::vector<std::vector<int>>& adj_;};
} // namespace graph
int main() { const std::vector<std::vector<int>> adj{{1, 2}, {3}, {3}, {}}; const auto dist = graph::BFS<int>(adj).run(0); for (std::size_t i = 0; i < dist.size(); ++i) std::cout << "dist[" << i << "] = " << dist[i] << '\n'; return 0;}3. Rust
use std::collections::HashMap;use std::hash::Hash;
#[derive(Debug, Default)]pub struct LruCache<K, V> { map: HashMap<K, V>, capacity: usize, hits: u64,}
impl<K: Eq + Hash + Clone, V: Clone> LruCache<K, V> { pub fn new(capacity: usize) -> Self { assert!(capacity > 0, "capacity must be positive"); Self { map: HashMap::new(), capacity, hits: 0 } }
pub fn get(&mut self, key: &K) -> Option<&V> { match self.map.get(key) { Some(value) => { self.hits += 1; Some(value) } None => None, } }
pub fn insert(&mut self, key: K, value: V) -> Result<(), String> { if self.map.len() >= self.capacity && !self.map.contains_key(&key) { return Err(format!("cache full: {} entries", self.capacity)); } self.map.insert(key, value); Ok(()) }
pub fn hit_rate(&self) -> f64 { if self.map.is_empty() { 0.0 } else { self.hits as f64 / self.map.len() as f64 } }}4. Bash
#!/usr/bin/env bashset -euo pipefail
REPO="${1:-ATMxsp01/blog-content}"BRANCH="${BRANCH:-main}"
echo "==> 同步 $REPO ($BRANCH)"if ! git -C "$REPO" diff --quiet; then echo "工作树不干净,先提交" >&2 exit 1fi
for step in sync validate build; do printf ' -> %s ... ' "$step" pnpm "content:$step" >/dev/null 2>&1 && echo "ok" || { echo "failed"; exit 1; }done
# 统计产物find dist -name '*.html' | wc -l | xargs printf 'pages: %s\n'echo "done in ${SECONDS}s"5. Lean 4
import Mathlib.Data.Nat.Basic
namespace Demo
/-- 归纳定义的偶数谓词。 -/inductive Even : Nat → Prop | zero : Even 0 | add_two {n : Nat} : Even n → Even (n + 2)
theorem even_add (m n : Nat) (hm : Even m) (hn : Even n) : Even (m + n) := by induction hm with | zero => simpa using hn | add_two _ ih => simpa [Nat.add_assoc] using Even.add_two ih
def double (n : Nat) : Nat := n * 2
example (n : Nat) : double n = n + n := by simp [double, Nat.mul_two] -- 一条 tactic 搞定
end Demo6. 同一段代码的对比(无 title、无行号)
行号在 Expressive Code 里默认开启(
plugin-line-numbers的showLineNumbers默认值为true),所以必须显式写showLineNumbers=false才是真的无行号。
def fib(n: int) -> int: a, b = 0, 1 for _ in range(n): a, b = b, a + b return a7. 字体四形态(ComicMathMono)
当前 mono 角色是 ComicMathMono 的 Regular / Bold / Italic / Bold Italic 四个真实字面;
粗斜体不再依赖浏览器合成。
const total = items.reduce((a, b) => a + b, 0); // Regular
const total = items.reduce((a, b) => a + b, 0); // Bold
const total = items.reduce((a, b) => a + b, 0); // Italic
const total = items.reduce((a, b) => a + b, 0); // Bold Italic
| 形式 | 行内代码效果 |
|---|---|
| Regular | const total = items.reduce((a, b) => a + b, 0); |
| Bold | const total = items.reduce((a, b) => a + b, 0); |
| Italic | const total = items.reduce((a, b) => a + b, 0); |
| Bold Italic | const total = items.reduce((a, b) => a + b, 0); |
表格使用作者强调:Regular 400 / Bold 600 / Italic 400 italic / Bold Italic 600 italic; 主题会把 600 匹配到最近的 700 真实字面,四行宽度一致。
分享文章
生成精美分享图或复制链接,与更多人分享本文。
评论