本文用于演示 moeMac 主题所有语言的代码高亮样式,包括浅色(GitHub Light)和暗色(Tokyo Night)两套配色。你可以切换主题来对比效果。
JavaScript
// JavaScript 示例 — 涵盖各种语法元素
import { useState, useEffect } from 'react';
import * as utils from './utils';
const API_URL = 'https://api.example.com/v2';
const TIMEOUT = 5000;
/**
* 异步获取用户数据
* @param {number} id - 用户 ID
* @returns {Promise<Object>} 用户信息
*/
async function fetchUser(id) {
try {
const response = await fetch(`${API_URL}/users/${id}`, {
method: 'GET',
headers: { 'Authorization': `Bearer ${token}` },
signal: AbortSignal.timeout(TIMEOUT)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
return { ...data, fetchedAt: Date.now() };
} catch (err) {
console.error('Fetch failed:', err.message);
return null;
}
}
class UserStore {
#users = new Map();
add(user) {
this.#users.set(user.id, user);
}
get(id) {
return this.#users.get(id) ?? null;
}
get size() {
return this.#users.size;
}
}
const store = new UserStore();
const numbers = [1, 2, 3, 4, 5].map(n => n * 2).filter(n => n > 4);
const regex = /^https?:\/\/[\w.-]+/i;
const template = `Total: ${numbers.length} items`;
TypeScript
// TypeScript 示例 — 泛型、接口、类型守卫
interface User<T extends Record<string, unknown>> {
id: string;
name: string;
email?: string;
metadata: T;
roles: ReadonlyArray<'admin' | 'user' | 'guest'>;
}
type UserStatus = 'active' | 'inactive' | 'banned';
type UserFilter = Partial<Pick<User<{}>, 'name' | 'email'>>;
function isUser(obj: unknown): obj is User<{}> {
return typeof obj === 'object' && obj !== null && 'id' in obj && 'name' in obj;
}
function processUsers<T extends User<{}>>(
users: T[],
filter: (u: T) => boolean
): T[] {
return users.filter(filter).map(u => ({ ...u, processed: true }));
}
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT'
}
abstract class Animal<T extends string> {
abstract readonly species: T;
constructor(public name: string, protected age: number) {}
abstract makeSound(): string;
toString(): string {
return `${this.species}(${this.name}, ${this.age})`;
}
}
Python
# Python 示例 — 装饰器、类型提示、异步
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from typing import Generic, TypeVar, Callable, Awaitable
from functools import wraps
T = TypeVar('T')
def retry(max_attempts: int = 3):
"""重试装饰器"""
def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
@wraps(func)
async def wrapper(*args, **kwargs) -> T:
last_error = None
for attempt in range(1, max_attempts + 1):
try:
return await func(*args, **kwargs)
except Exception as e:
last_error = e
print(f"Attempt {attempt}/{max_attempts} failed: {e}")
raise last_error
return wrapper
return decorator
@dataclass
class Point(Generic[T]):
x: T
y: T
tags: list[str] = field(default_factory=list)
def distance_to(self, other: Point[T]) -> float:
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
def __repr__(self) -> str:
return f"Point({self.x}, {self.y})"
class Fibonacci:
"""无限斐波那契数列迭代器"""
def __init__(self):
self._a, self._b = 0, 1
def __iter__(self):
return self
def __next__(self):
value = self._a
self._a, self._b = self._b, self._a + self._b
return value
if __name__ == "__main__":
fib = Fibonacci()
first_ten = [next(fib) for _ in range(10)]
print(f"First 10 Fibonacci: {first_ten}")
CSS
/* CSS 示例 — 变量、嵌套、动画 */
:root {
--primary: #007aff;
--radius: 12px;
--shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.card {
display: flex;
flex-direction: column;
gap: 16px;
padding: 24px;
border-radius: var(--radius);
background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
box-shadow: var(--shadow);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}
.card__title {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary);
}
.card__title::after {
content: '';
display: block;
width: 40px;
height: 3px;
margin-top: 8px;
background: var(--primary);
border-radius: 2px;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@media (max-width: 768px) {
.card {
padding: 16px;
border-radius: 8px;
}
}
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>示例页面</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="site-header">
<nav>
<a href="/" class="logo">My Site</a>
<ul class="nav-list">
<li><a href="/about">关于</a></li>
<li><a href="/contact">联系</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h1>文章标题</h1>
<p>这是一段 <strong>加粗</strong> 和 <em>斜体</em> 的文字。</p>
<img src="cover.jpg" alt="封面图" loading="lazy">
<blockquote>引用文字</blockquote>
</article>
<section data-component="comments">
<!-- 评论区 -->
</section>
</main>
<script type="module">
import { init } from './app.js';
init();
</script>
</body>
</html>
JSON
{
"name": "moeMac-theme",
"version": "2.1.0",
"description": "Mac 风格的 Hexo 博客主题",
"author": {
"name": "moeMac",
"email": "dev@moemac.com"
},
"keywords": ["hexo", "theme", "mac", "blog"],
"config": {
"darkMode": "auto",
"language": "zh-CN",
"features": {
"search": true,
"comments": true,
"analytics": false
}
},
"scripts": {
"build": "hexo generate",
"server": "hexo server"
},
"engines": {
"node": ">=18.0.0"
}
}
Bash / Shell
#!/bin/bash
# 部署脚本示例
set -euo pipefail
PROJECT_DIR="/var/www/blog"
BACKUP_DIR="/var/backups/blog/$(date +%Y%m%d)"
echo "=== 开始部署 ==="
# 创建备份目录
mkdir -p "$BACKUP_DIR"
# 备份当前版本
if [ -d "$PROJECT_DIR" ]; then
echo "备份当前版本到 $BACKUP_DIR"
cp -r "$PROJECT_DIR" "$BACKUP_DIR/"
fi
# 拉取最新代码
cd "$PROJECT_DIR"
git pull origin main
# 安装依赖
npm ci --production
# 构建
npx hexo clean
npx hexo generate
# 重启服务
sudo systemctl restart hexo-blog
echo "=== 部署完成 ==="
Go
// Go 示例 — 并发、接口、错误处理
package main
import (
"context"
"fmt"
"sync"
"time"
)
type Fetcher interface {
Fetch(ctx context.Context, url string) ([]byte, error)
}
type Result struct {
URL string
Status int
Body []byte
Err error
}
func fetchAll(ctx context.Context, fetcher Fetcher, urls []string) []Result {
var wg sync.WaitGroup
results := make([]Result, len(urls))
for i, url := range urls {
wg.Add(1)
go func(idx int, u string) {
defer wg.Done()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
body, err := fetcher.Fetch(ctx, u)
results[idx] = Result{URL: u, Body: body, Err: err}
}(i, url)
}
wg.Wait()
return results
}
func main() {
urls := []string{
"https://api.example.com/users",
"https://api.example.com/posts",
"https://api.example.com/comments",
}
for _, r := range fetchAll(context.Background(), nil, urls) {
if r.Err != nil {
fmt.Printf("ERROR %s: %v\n", r.URL, r.Err)
} else {
fmt.Printf("OK %s: %d bytes\n", r.URL, len(r.Body))
}
}
}
Rust
// Rust 示例 — 所有权、生命周期、trait
use std::collections::HashMap;
use std::fmt::{self, Display};
#[derive(Debug, Clone)]
struct Config {
name: String,
version: String,
debug: bool,
}
impl Display for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}@{} (debug={})", self.name, self.version, self.debug)
}
}
trait Cache<K, V> {
fn get(&self, key: &K) -> Option<&V>;
fn insert(&mut self, key: K, value: V);
fn remove(&mut self, key: &K) -> Option<V>;
}
struct LruCache<K, V> {
entries: HashMap<K, V>,
capacity: usize,
}
impl<K: std::hash::Hash + Eq, V> Cache<K, V> for LruCache<K, V> {
fn get(&self, key: &K) -> Option<&V> {
self.entries.get(key)
}
fn insert(&mut self, key: K, value: V) {
if self.entries.len() >= self.capacity && !self.entries.contains_key(&key) {
// 简化:移除第一个 key
if let Some(first_key) = self.entries.keys().next().cloned() {
self.entries.remove(&first_key);
}
}
self.entries.insert(key, value);
}
fn remove(&mut self, key: &K) -> Option<V> {
self.entries.remove(key)
}
}
fn main() {
let config = Config {
name: String::from("moeMac"),
version: String::from("2.1.0"),
debug: true,
};
println!("{}", config);
let mut cache = LruCache {
entries: HashMap::new(),
capacity: 3,
};
cache.insert("a", 1);
cache.insert("b", 2);
cache.insert("c", 3);
if let Some(val) = cache.get(&"b") {
println!("cache['b'] = {}", val);
}
}
SQL
-- SQL 示例 — DDL + DML + 查询
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
role VARCHAR(20) DEFAULT 'user' CHECK (role IN ('admin', 'user', 'guest')),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users(email);
-- 插入数据
INSERT INTO users (username, email, role)
VALUES
('alice', 'alice@example.com', 'admin'),
('bob', 'bob@example.com', 'user'),
('charlie', 'charlie@example.com', 'user')
ON CONFLICT (username) DO UPDATE
SET email = EXCLUDED.email,
updated_at = CURRENT_TIMESTAMP;
-- 复杂查询
SELECT
u.username,
u.email,
COUNT(p.id) AS post_count,
COALESCE(SUM(p.views), 0) AS total_views
FROM users u
LEFT JOIN posts p ON p.author_id = u.id
WHERE u.role = 'user'
AND p.created_at >= NOW() - INTERVAL '30 days'
GROUP BY u.id, u.username, u.email
HAVING COUNT(p.id) > 0
ORDER BY total_views DESC
LIMIT 10;
-- 窗口函数
WITH ranked_posts AS (
SELECT
title,
author_id,
views,
ROW_NUMBER() OVER (PARTITION BY author_id ORDER BY views DESC) AS rank
FROM posts
WHERE published = true
)
SELECT * FROM ranked_posts WHERE rank <= 3;
Java
// Java 示例 — 接口、泛型、Stream API
package com.example.blog;
import java.util.*;
import java.util.stream.*;
import java.util.concurrent.CompletableFuture;
public class PostService {
private final PostRepository repository;
public PostService(PostRepository repository) {
this.repository = Objects.requireNonNull(repository);
}
public List<Post> getPublishedPosts(int limit) {
return repository.findAll().stream()
.filter(Post::isPublished)
.sorted(Comparator.comparing(Post::getPublishedAt).reversed())
.limit(limit)
.collect(Collectors.toList());
}
public Map<String, Long> getTagCounts() {
return repository.findAll().stream()
.filter(Post::isPublished)
.flatMap(post -> post.getTags().stream())
.collect(Collectors.groupingBy(
tag -> tag,
Collectors.counting()
));
}
public CompletableFuture<Optional<Post>> findByIdAsync(Long id) {
return CompletableFuture.supplyAsync(() -> repository.findById(id));
}
public sealed interface PostStatus permits Draft, Published, Archived {
String label();
}
public record Draft() implements PostStatus {
@Override public String label() { return "草稿"; }
}
public record Published() implements PostStatus {
@Override public String label() { return "已发布"; }
}
public record Archived() implements PostStatus {
@Override public String label() { return "已归档"; }
}
}
Vue SFC (单文件组件)
<template>
<div class="counter">
<h2>{{ title }}</h2>
<button @click="decrement" :disabled="count <= 0">-</button>
<span class="count">{{ count }}</span>
<button @click="increment">+</button>
<p v-if="count > 10" class="warning">已经超过 10 了!</p>
</div>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
const props = defineProps({
title: { type: String, default: '计数器' },
initial: { type: Number, default: 0 }
})
const count = ref(props.initial)
const double = computed(() => count.value * 2)
watch(count, (newVal, oldVal) => {
console.log(`Count: ${oldVal} -> ${newVal}`)
})
function increment() {
count.value++
}
function decrement() {
count.value--
}
</script>
<style scoped>
.counter {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 24px;
border-radius: 12px;
}
.count {
font-size: 2rem;
font-weight: 700;
min-width: 48px;
text-align: center;
}
.warning {
color: #f59e0b;
font-size: 0.875rem;
}
</style>
PHP
<?php
// PHP 示例 — 命名空间、trait、闭包、生成器
namespace App\Services;
use App\Models\User;
use App\Models\Post;
use Illuminate\Database\Eloquent\Builder;
class BlogService
{
private array $cache = [];
public function __construct(
private readonly UserRepository $users,
private readonly PostRepository $posts
) {}
public function getPopularPosts(int $limit = 10): array
{
return $this->cache[$limit] ??= $this->posts
->query()
->where('published', true)
->where('views', '>', 100)
->orderByDesc('views')
->limit($limit)
->get()
->map(fn (Post $post) => [
'id' => $post->id,
'title' => $post->title,
'author' => $post->user->name,
'views' => $post->views,
])
->toArray();
}
public function generateTags(Post $post): \Generator
{
foreach ($post->tags as $tag) {
yield $tag->name => $tag->count;
}
}
public function filterPosts(callable $callback): array
{
$posts = $this->posts->all();
return array_filter($posts, $callback);
}
}
trait Sluggable
{
public function slug(): string
{
return strtolower(
preg_replace('/[^A-Za-z0-9-]+/', '-', $this->title)
);
}
}
interface Renderable
{
public function render(): string;
}
class MarkdownPost implements Renderable
{
use Sluggable;
public function __construct(
public readonly string $title,
public readonly string $content
) {}
public function render(): string
{
return "<article><h1>{$this->title}</h1>{$this->content}</article>";
}
}
$post = new MarkdownPost('Hello World', '## Welcome');
echo $post->slug();
echo $post->render();
Ruby
# Ruby 示例 — 模块、块、元编程
module Bloggable
attr_accessor :title, :content
def word_count
content.split.size
end
def summary(length = 50)
content.length > length ? "#{content[0...length]}..." : content
end
end
class Post
include Bloggable
def initialize(title, content, tags = [])
@title = title
@content = content
@tags = tags
end
def each_tag(&block)
@tags.each(&block)
end
def method_missing(name, *args)
if name.to_s =~ /^tag_(.+)\?$/
@tags.include?($1.to_sym)
else
super
end
end
end
class PostsCollection
include Enumerable
def initialize
@posts = []
end
def add(post)
@posts << post
self
end
def each(&block)
@posts.each(&block)
end
end
posts = PostsCollection.new
posts.add(Post.new("Ruby Tips", "Learn Ruby metaprogramming...", [:ruby, :meta]))
posts.add(Post.new("Rails Guide", "Build web apps with Rails", [:ruby, :rails]))
longest = posts.max_by(&:word_count)
puts "Longest: #{longest.title} (#{longest.word_count} words)"
posts.each_tag { |tag| puts "Tag: #{tag}" }
Swift
// Swift 示例 — 协议、泛型、async/await
import Foundation
protocol Describable {
var description: String { get }
}
struct Post: Identifiable, Describable {
let id: UUID
var title: String
var views: Int
var tags: [String]
var description: String { "\(title) (\(views) views)" }
func contains(tag: String) -> Bool {
tags.contains(tag)
}
}
@MainActor
class BlogStore: ObservableObject {
@Published var posts: [Post] = []
func fetchPosts() async throws {
let (data, _) = try await URLSession.shared.data(from: URL(string: "https://api.example.com/posts")!)
self.posts = try JSONDecoder().decode([Post].self, from: data)
}
func popularPosts(minViews: Int = 100) -> [Post] {
posts.filter { $0.views >= minViews }.sorted { $0.views > $1.views }
}
func groupedByTag() -> [String: [Post]] {
Dictionary(grouping: posts.flatMap { post in
post.tags.map { ($0, post) }
}, by: { $0.0 })
.mapValues { $0.map { $0.1 } }
}
}
// 泛型函数
func topN<T>(_ items: [T], count: Int, by keyPath: KeyPath<T, Int>) -> [T] {
items.sorted { $0[keyPath: keyPath] > $1[keyPath: keyPath] }
.prefix(count)
.map { $0 }
}
let store = BlogStore()
Task {
try? await store.fetchPosts()
for post in store.popularPosts(minViews: 50) {
print(post.description)
}
}
Kotlin
// Kotlin 示例 — 协程、密封类、扩展函数
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val message: String) : Result<Nothing>()
object Loading : Result<Nothing>()
}
data class Post(
val id: Long,
val title: String,
val author: String,
val views: Int,
val tags: List<String>
)
class PostRepository {
private val posts = mutableListOf<Post>()
fun add(post: Post) = posts.add(post)
fun getAll(): List<Post> = posts.toList()
fun getPopular(minViews: Int): List<Post> =
posts.filter { it.views >= minViews }.sortedByDescending { it.views }
}
// 扩展函数
fun List<Post>.groupByTag(): Map<String, List<Post>> =
flatMap { post -> post.tags.map { tag -> tag to post } }
.groupBy({ it.first }, { it.second })
// 协程 Flow
fun PostRepository.fetchFlow(): Flow<Result<List<Post>>> = flow {
emit(Result.Loading)
delay(500)
try {
emit(Result.Success(getAll()))
} catch (e: Exception) {
emit(Result.Error(e.message ?: "Unknown error"))
}
}
fun main() = runBlocking {
val repo = PostRepository().apply {
add(Post(1, "Kotlin Tips", "Alice", 150, listOf("kotlin", "jvm")))
add(Post(2, "Coroutines", "Bob", 300, listOf("kotlin", "async")))
}
repo.fetchFlow().collect { result ->
when (result) {
is Result.Loading -> println("Loading...")
is Result.Success -> result.data.forEach { println("${it.title} by ${it.author}") }
is Result.Error -> println("Error: ${result.message}")
}
}
repo.getPopular(100).groupByTag().forEach { (tag, posts) ->
println("#$tag: ${posts.size} posts")
}
}
Dart
// Dart 示例 — 异步、泛型、Mixin
import 'dart:async';
import 'dart:convert';
abstract class DataSource<T> {
Future<List<T>> fetch();
Stream<T> watch();
}
class Post {
final int id;
final String title;
final String author;
final int views;
const Post({
required this.id,
required this.title,
required this.author,
required this.views,
});
factory Post.fromJson(Map<String, dynamic> json) => Post(
id: json['id'] as int,
title: json['title'] as String,
author: json['author'] as String,
views: json['views'] as int,
);
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'author': author,
'views': views,
};
}
mixin Serializable {
Map<String, dynamic> toJson();
}
class PostService implements DataSource<Post> {
final List<Post> _cache = [];
Future<List<Post>> fetch() async {
await Future.delayed(Duration(milliseconds: 300));
return _cache;
}
Stream<Post> watch() async* {
for (final post in _cache) {
yield post;
await Future.delayed(Duration(milliseconds: 100));
}
}
Future<void> loadFromJson(String jsonStr) async {
final List<dynamic> json = jsonDecode(jsonStr);
_cache.addAll(json.map((j) => Post.fromJson(j.cast<String, dynamic>())));
}
}
void main() async {
final service = PostService();
await service.loadFromJson('''
[{"id":1,"title":"Dart Tips","author":"Alice","views":100},
{"id":2,"title":"Flutter UI","author":"Bob","views":250}]
''');
final posts = await service.fetch();
final popular = posts.where((p) => p.views > 50).toList()
..sort((a, b) => b.views.compareTo(a.views));
for (final post in popular) {
print('${post.title} by ${post.author} (${post.views} views)');
}
}
Dockerfile
# Dockerfile 示例 — 多阶段构建
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
FROM nginx:alpine AS runtime
COPY /app/public /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
HEALTHCHECK \
CMD wget -q --spider http://localhost/ || exit 1
LABEL maintainer="dev@example.com" \
version="2.1.0" \
description="moeMac blog static site"
Nginx 配置
# Nginx 配置示例 — 反向代理 + HTTPS
upstream blog_backend {
server 127.0.0.1:3000 weight=3;
server 127.0.0.1:3001 weight=2;
keepalive 32;
}
server {
listen 443 ssl http2;
server_name blog.example.com;
ssl_certificate /etc/ssl/certs/blog.pem;
ssl_certificate_key /etc/ssl/private/blog.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
root /var/www/blog;
index index.html;
# 静态资源缓存
location ~* \.(css|js|woff2|png|jpg|webp)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# API 反向代理
location /api/ {
proxy_pass http://blog_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# SPA 路由回退
location / {
try_files $uri $uri/ /index.html;
}
}
C
// C 示例 — 指针、结构体、内存管理
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 256
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* create_node(int data) {
Node* node = (Node*)malloc(sizeof(Node));
if (node == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
node->data = data;
node->next = NULL;
return node;
}
// 链表反转
Node* reverse_list(Node* head) {
Node* prev = NULL;
Node* current = head;
Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
// 安全字符串拷贝
void safe_copy(char* dest, const char* src, size_t size) {
strncpy(dest, src, size - 1);
dest[size - 1] = '\0';
}
int main(int argc, char** argv) {
Node* head = create_node(1);
head->next = create_node(2);
head->next->next = create_node(3);
head = reverse_list(head);
Node* cur = head;
while (cur != NULL) {
printf("%d -> ", cur->data);
cur = cur->next;
}
printf("NULL\n");
while (head != NULL) {
Node* tmp = head;
head = head->next;
free(tmp);
}
return 0;
}
C++
// C++ 示例 — 模板、STL、智能指针
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
#include <optional>
#include <concepts>
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template<Numeric T>
class Matrix {
private:
std::vector<std::vector<T>> data;
size_t rows, cols;
public:
Matrix(size_t r, size_t c, T init = T{})
: rows(r), cols(c), data(r, std::vector<T>(c, init)) {}
T& operator()(size_t i, size_t j) { return data[i][j]; }
const T& operator()(size_t i, size_t j) const { return data[i][j]; }
Matrix operator+(const Matrix& other) const {
Matrix result(rows, cols);
for (size_t i = 0; i < rows; ++i)
for (size_t j = 0; j < cols; ++j)
result(i, j) = data[i][j] + other(i, j);
return result;
}
static std::unique_ptr<Matrix> create(size_t r, size_t c) {
return std::make_unique<Matrix>(r, c);
}
};
auto get_stats(const std::vector<int>& v) {
auto [min_it, max_it] = std::minmax_element(v.begin(), v.end());
double avg = std::accumulate(v.begin(), v.end(), 0.0) / v.size();
return std::make_tuple(*min_it, *max_it, avg);
}
int main() {
auto m = Matrix::create(3, 3, 1.0);
(*m)(1, 1) = 5.0;
std::vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6};
auto [min, max, avg] = get_stats(nums);
std::cout << "Min: " << min << ", Max: " << max
<< ", Avg: " << avg << std::endl;
std::sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; });
for (const auto& n : nums) std::cout << n << ' ';
std::cout << std::endl;
return 0;
}
C#
// C# 示例 — LINQ、异步、泛型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlogDemo
{
public record Post(int Id, string Title, string Author, int Views, DateTime PublishedAt);
public class BlogService
{
private readonly List<Post> _posts = new();
public void AddPost(Post post) => _posts.Add(post);
public IEnumerable<Post> GetTopPosts(int count)
{
return _posts
.Where(p => p.PublishedAt < DateTime.Now)
.OrderByDescending(p => p.Views)
.Take(count);
}
public Dictionary<string, int> GetAuthorStats()
{
return _posts
.GroupBy(p => p.Author)
.ToDictionary(g => g.Key, g => g.Count());
}
public async Task<Post?> FindByIdAsync(int id)
{
await Task.Delay(100);
return _posts.FirstOrDefault(p => p.Id == id);
}
public T[] Filter<T>(IEnumerable<T> source, Func<T, bool> predicate)
{
return source.Where(predicate).ToArray();
}
}
class Program
{
static async Task Main(string[] args)
{
var service = new BlogService();
service.AddPost(new Post(1, "Hello", "Alice", 100, DateTime.Now.AddDays(-1)));
service.AddPost(new Post(2, "World", "Bob", 200, DateTime.Now.AddDays(-2)));
service.AddPost(new Post(3, "C# Tips", "Alice", 300, DateTime.Now.AddDays(-3)));
var top = service.GetTopPosts(2);
foreach (var post in top)
Console.WriteLine($"{post.Title} by {post.Author} ({post.Views} views)");
var found = await service.FindByIdAsync(2);
Console.WriteLine($"Found: {found?.Title ?? "Not found"}");
}
}
}
YAML
# _config.yml 示例
title: 我的博客
subtitle: 记录生活与技术
description: 一个使用 Hexo + moeMac 主题的个人博客
language: zh-CN
timezone: Asia/Shanghai
url: https://blog.example.com
root: /
permalink: posts/:abbrlink/
theme: moeMac
highlight:
enable: true
line_number: true
auto_detect: false
tab_replace: ' '
deploy:
type: git
repo: git@github.com:user/blog.git
branch: gh-pages
social:
github: https://github.com/user
twitter: https://twitter.com/user
email: mailto:user@example.com
menu:
home: /
archives: /archives
about: /about
行内代码演示
这是一段包含行内代码的文字:使用 npm install 安装依赖,然后用 npx hexo server 启动本地服务器。你还可以用 Ctrl + A 选中所有代码,行号不会被选中哦!
纯文本代码块(无语言标记)
这是一个没有指定语言的纯文本代码块
没有语法高亮
但依然有行号和 Mac 风格窗口
超长行(测试水平滚动)
const veryLongLine = { id: 1, name: 'This is a very long line to test horizontal scrolling behavior of the code block container, it should scroll smoothly without breaking the layout or causing the line numbers to misalign', value: 42, timestamp: Date.now(), metadata: { source: 'test', priority: 'high', tags: ['long', 'scroll', 'demo'] } };
多行代码(测试三位数行号)
// 第 1 行 — 测试三位数行号的显示
// 第 2 行
// 第 3 行
// 第 4 行
// 第 5 行
// 第 6 行
// 第 7 行
// 第 8 行
// 第 9 行
// 第 10 行
// 第 11 行
// 第 12 行
// 第 13 行
// 第 14 行
// 第 15 行
// 第 16 行
// 第 17 行
// 第 18 行
// 第 19 行
// 第 20 行
// 第 21 行
// 第 22 行
// 第 23 行
// 第 24 行
// 第 25 行
// 第 26 行
// 第 27 行
// 第 28 行
// 第 29 行
// 第 30 行
// 第 31 行
// 第 32 行
// 第 33 行
// 第 34 行
// 第 35 行
// 第 36 行
// 第 37 行
// 第 38 行
// 第 39 行
// 第 40 行
// 第 41 行
// 第 42 行
// 第 43 行
// 第 44 行
// 第 45 行
// 第 46 行
// 第 47 行
// 第 48 行
// 第 49 行
// 第 50 行
// 第 51 行
// 第 52 行
// 第 53 行
// 第 54 行
// 第 55 行
// 第 56 行
// 第 57 行
// 第 58 行
// 第 59 行
// 第 60 行
// 第 61 行
// 第 62 行
// 第 63 行
// 第 64 行
// 第 65 行
// 第 66 行
// 第 67 行
// 第 68 行
// 第 69 行
// 第 70 行
// 第 71 行
// 第 72 行
// 第 73 行
// 第 74 行
// 第 75 行
// 第 76 行
// 第 77 行
// 第 78 行
// 第 79 行
// 第 80 行
// 第 81 行
// 第 82 行
// 第 83 行
// 第 84 行
// 第 85 行
// 第 86 行
// 第 87 行
// 第 88 行
// 第 89 行
// 第 90 行
// 第 91 行
// 第 92 行
// 第 93 行
// 第 94 行
// 第 95 行
// 第 96 行
// 第 97 行
// 第 98 行
// 第 99 行
// 第 100 行 — 到达三位数行号!
// 第 101 行
// 第 102 行
// 第 103 行
// 第 104 行
// 第 105 行
提示:试试用
Ctrl + A全选本文,然后Ctrl + C复制——你会发现行号完全不会被选中!这就是 CSS counter 伪元素方案的优势。
版权声明
评论加载中…