Spaces:
Sleeping
Sleeping
File size: 5,331 Bytes
1bd2bb8 9fb8186 1bd2bb8 9fb8186 1bd2bb8 9fb8186 1bd2bb8 df1ba4a ca86369 df1ba4a ca86369 df1ba4a 1bd2bb8 9fb8186 df1ba4a 9fb8186 df1ba4a 9fb8186 df1ba4a 9fb8186 1bd2bb8 ca86369 df1ba4a ca86369 1bd2bb8 ca86369 df1ba4a ca86369 1bd2bb8 9fb8186 df1ba4a 9fb8186 1bd2bb8 9fb8186 1bd2bb8 df1ba4a ca86369 1bd2bb8 ca86369 1bd2bb8 ca86369 df1ba4a ca86369 df1ba4a ca86369 1bd2bb8 9fb8186 1bd2bb8 df1ba4a ca86369 9fb8186 ca86369 9fb8186 df1ba4a ca86369 df1ba4a ca86369 df1ba4a ca86369 9fb8186 df1ba4a 9fb8186 df1ba4a 9fb8186 1bd2bb8 9fb8186 1bd2bb8 9fb8186 1bd2bb8 | 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | import os
import random
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
# 示例代码片段
SNIPPETS = [
# --- Python ---
{
"language": "Python",
"code": """# Binary Search Implementation
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Target found
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Not found"""
},
{
"language": "Python",
"code": """# Flask Route Example
@app.route('/api/users', methods=['GET'])
def get_users():
# Get user list from database
users = db.session.query(User).all()
return jsonify({
"count": len(users),
"data": [u.to_dict() for u in users]
})"""
},
{
"language": "Python",
"code": """# Quick Sort Algorithm
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)"""
},
# --- JavaScript ---
{
"language": "JavaScript",
"code": """/**
* Debounce Function
* Limits the rate at which a function can fire.
*/
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
// Execute later
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}"""
},
{
"language": "JavaScript",
"code": """// Promise Chain Example
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});"""
},
# --- Go ---
{
"language": "Go",
"code": """// Concurrency Example
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
// Start 5 goroutines
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Worker %d starting\\n", id)
}(i)
}
wg.Wait() // Wait for all goroutines to finish
fmt.Println("All workers done")
}"""
},
# --- SQL ---
{
"language": "SQL",
"code": """-- Query High Value Users
SELECT
u.username,
COUNT(o.id) as order_count,
SUM(o.amount) as total_spent
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.created_at >= '2024-01-01'
GROUP BY u.id
HAVING total_spent > 1000
ORDER BY total_spent DESC;"""
},
# --- React ---
{
"language": "React",
"code": """// Simple Counter Component
import React, { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div className="p-4 border rounded">
<h2 className="text-xl">Current Count: {count}</h2>
<button
onClick={() => setCount(count + 1)}
className="bg-blue-500 text-white px-4 py-2 mt-2"
>
Increment (+1)
</button>
</div>
);
}"""
},
# --- Java ---
{
"language": "Java",
"code": """// Singleton Pattern (Double Checked Locking)
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}"""
},
# --- HTML/CSS ---
{
"language": "HTML",
"code": """<!-- Simple Card Layout -->
<div class="card">
<img src="avatar.jpg" alt="User Avatar" class="card-img">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Some quick example text to build on the card title.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<style>
.card { border: 1px solid #ccc; border-radius: 8px; padding: 16px; }
.card-img { width: 100%; height: auto; border-radius: 4px; }
</style>"""
}
]
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/snippet')
def get_snippet():
lang = request.args.get('lang')
if lang and lang != 'All':
filtered = [s for s in SNIPPETS if s['language'] == lang]
if filtered:
return jsonify(random.choice(filtered))
# 默认随机返回
snippet = random.choice(SNIPPETS)
return jsonify(snippet)
@app.route('/api/languages')
def get_languages():
# 获取所有唯一的语言列表
languages = sorted(list(set(s['language'] for s in SNIPPETS)))
return jsonify(['All'] + languages)
@app.route('/health')
def health():
return "OK", 200
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)
|