【公告】
主题第四弹已更新
免费下载,搜索Typecho即可

代码高亮测试

Typecho · 2024-11-30 · 275 人浏览

PHP 代码示例fsf

fsfsf
<?php
class HelloWorld {
    private $message;
    
    public function __construct($message = 'Hello World!') {
        $this->message = $message;
    }
    
    public function sayHello() {
        return $this->message;
    }
}

// 创建实例并调用
$hello = new HelloWorld();
echo $hello->sayHello();  // 输出: Hello World!

JavaScript 代码示例

// ES6 类定义
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    sayHello() {
        return `Hi, I'm ${this.name}, ${this.age} years old.`;
    }
}

// Promise 示例
const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = { id: 1, name: 'Test' };
            Math.random() > 0.5 ? resolve(data) : reject('Error!');
        }, 1000);
    });
}

// Async/Await 使用
async function getData() {
    try {
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

Python 代码示例

from typing import List, Optional
import asyncio

class DataProcessor:
    def __init__(self, data: List[int]):
        self.data = data
    
    async def process(self) -> Optional[List[int]]:
        if not self.data:
            return None
        
        # 模拟异步处理
        await asyncio.sleep(1)
        return sorted(self.data)

    @staticmethod
    def filter_positive(numbers: List[int]) -> List[int]:
        return [n for n in numbers if n > 0]

# 使用示例
async def main():
    processor = DataProcessor([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
    result = await processor.process()
    filtered = DataProcessor.filter_positive(result)
    print(f"Processed data: {filtered}")

if __name__ == "__main__":
    asyncio.run(main())

SQL 代码示例

-- 创建用户表
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 插入数据
INSERT INTO users (username, email) VALUES
    ('john_doe', 'john@example.com'),
    ('jane_doe', 'jane@example.com');

-- 复杂查询示例
SELECT 
    u.username,
    COUNT(p.id) as post_count,
    MAX(p.created_at) as last_post_date
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
WHERE u.created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
GROUP BY u.id
HAVING post_count > 0
ORDER BY post_count DESC
LIMIT 10;

HTML/CSS 代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>样式测试</title>
    <style>
        .container {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
        }

        .card {
            padding: 2rem;
            border-radius: 1rem;
            background: rgba(255, 255, 255, 0.9);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            transition: transform 0.3s ease;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        @media (max-width: 768px) {
            .card {
                margin: 1rem;
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>Hello, World!</h1>
            <p>这是一个样式测试。</p>
        </div>
    </div>
</body>
</html>

Shell 脚本示例

#!/bin/bash

# 定义颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# 函数定义
function check_status() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}Success${NC}"
    else
        echo -e "${RED}Failed${NC}"
        exit 1
    fi
}

# 主要逻辑
echo "Starting deployment..."

# 更新代码
git pull origin main
check_status

# 安装依赖
npm install
check_status

# 构建项目
npm run build
check_status

echo "Deployment completed successfully!"
Typecho
表情
爱心
手势
动物
美食
天气

网站已运行 71 天 | 共有文章 672 篇 | 累计访问 17221 人次