今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

标签:#tutorial

找到 371 篇相关文章

AI 资讯

Optimizing Django ORM Queries: A Practical Guide to select_related and prefetch_related

1. Introduction Django's ORM is one of its greatest strengths. It abstracts away raw SQL, lets you express database operations in clean Python, and gets you productive fast. But that convenience comes with a hidden cost: if you're not deliberate about how you fetch related objects, you'll silently generate far more queries than you intend — and you won't notice until your app slows to a crawl in production. The most common culprit is the N+1 query problem : a pattern where fetching a list of N objects triggers an additional query for each one, resulting in N+1 total round-trips to the database. At ten rows it's invisible. At ten thousand rows, it's a disaster. Django provides two tools to fix this: select_related and prefetch_related . This article explains how each one works internally, when to use which, and how to combine them effectively — with before/after examples and real query counts throughout. 2. Understanding the N+1 Problem Consider a simple blog with posts and authors. You want to render a list of posts, showing each post's title and its author's name. Models: # models.py from django.db import models class Author ( models . Model ): name : str = models . CharField ( max_length = 100 ) class Post ( models . Model ): title : " str = models.CharField(max_length=200) " author : Author = models . ForeignKey ( Author , on_delete = models . CASCADE , related_name = " posts " , ) The naive approach: # views.py from django.db import connection from .models import Post def list_posts () -> None : posts = Post . objects . all () # Query 1: fetch all posts for post in posts : print ( f " { post . title } by { post . author . name } " ) # ^^^ Query 2, 3, 4, ... N+1: one per post For 100 posts, this produces 101 queries . Django lazily fetches post.author the first time you access it on each object. Each access hits the database separately. You can verify this with django.db.connection.queries (requires DEBUG = True ): from django.db import connection , reset_queries

2026-06-22 原文 →
AI 资讯

Power BI Data Modeling Unleashed: Master Schemas, Relationships, and Joins for High-Performance Reporting

Whether you're brand new to Power BI or just getting started with data analytics, this guide walks you through everything you need to know about data modeling — from how tables connect, to the schemas that make your reports fast and reliable. What Is Data Modeling in Power BI? Imagine you have three spreadsheets: one with your customers , one with your products , and one with your sales transactions . Individually, each table tells you something. But together, they can tell you which customer bought which product, when, and for how much . That's exactly what data modeling is: the process of organizing your data tables and defining how they relate to each other so Power BI can combine them into meaningful reports and dashboards. A data model in Power BI has three core building blocks: Tables — your data sources (Excel files, databases, CSVs, cloud services, etc.) Relationships — the links between tables that tell Power BI how data connects Measures & Calculations — formulas (in DAX) that compute totals, averages, and other insights A well-designed data model is the difference between a report that loads in seconds and one that takes forever. It's also what keeps your numbers accurate and your dashboards easy to use. Why Does Data Modeling Matter? Here's a simple analogy: a city without roads is just a collection of buildings. Data modeling is the road system that lets you travel between your tables. Without a good data model: Your visuals may show incorrect or duplicated numbers Filters in one chart won't affect another Reports will be slow and hard to maintain With a good data model: Clicking on a customer in one visual automatically filters every other visual Calculations are accurate and consistent You can easily add new data sources without rebuilding everything Types of Tables: Facts vs. Dimensions Before diving into schemas and relationships, you need to understand the two types of tables that make up most Power BI models. Fact Tables A Fact table stores the ev

2026-06-22 原文 →
AI 资讯

React Folder Structures That Scale: A Practical Guide for Modern Frontend Teams

Learn how to organize React projects for scalability, maintainability, and team collaboration. Introduction As React applications grow, one challenge consistently emerges: project organization . A folder structure that works perfectly for a small side project can quickly become a nightmare when multiple developers contribute to a production-scale application. Whether you're a junior React developer preparing for interviews, a mid-level frontend engineer looking to improve code maintainability, or a technical recruiter trying to understand modern React development practices, understanding scalable React folder structures is essential. In this guide, we'll explore the most popular React folder organization strategies, their pros and cons, and the structure many modern engineering teams use to build scalable applications. Why React Folder Structure Matters A well-organized React project provides several benefits: Faster onboarding for new developers Easier code maintenance Better scalability as features grow Reduced code duplication Improved team collaboration Cleaner separation of concerns Many React applications start simple: src/ ├── App.jsx ├── Home.jsx ├── Login.jsx └── Dashboard.jsx This works initially, but as the project grows to dozens or hundreds of components, finding and maintaining files becomes increasingly difficult. Common React Folder Structure Approaches 1. Type-Based Folder Structure One of the earliest and most common approaches is organizing files by their type. src/ ├── components/ ├── pages/ ├── hooks/ ├── services/ ├── utils/ ├── assets/ └── contexts/ Advantages Easy to understand Suitable for small projects Quick setup Disadvantages Components folder can become enormous Related files are spread across multiple directories Harder to maintain in large teams For example, a user profile feature might have files located in: components/UserProfile.jsx hooks/useUser.js services/userService.js pages/ProfilePage.jsx Finding all files related to one feat

2026-06-21 原文 →
AI 资讯

What to Put in Your CLAUDE.md (and What to Leave Out)

A great CLAUDE.md is not the longest one. It is the one where every line changes what Claude does. The whole skill is knowing what belongs in it — and, just as importantly, what does not. The sections that earn their place Start with a one or two line project description and your stack, with version numbers. Claude infers a lot from your code, but it will not guess that you are on Next.js 15 instead of 14, or which ORM you chose. Then a directory map — not every file, just the top-level layout with a note on what each part holds. After that: the build and test commands, the conventions a formatter does not enforce, and critically, the things not to touch. # Project: Acme Dashboard Next.js 15 (App Router), TypeScript, Drizzle ORM, Vitest. ## Structure src/app/ # routes and pages src/lib/ # shared utilities, db client db/migrations/ # generated - never hand-edit ## Commands Build: npm run build Test: npm run test ## Conventions - API routes return { data, error } - never throw to client - Server components by default ## Do not touch - db/migrations/ is generated. Never edit by hand. Every line in that file would cause a mistake if removed. That is the bar. What to leave out This is where most files go wrong. Two kinds of content waste your budget: Personality instructions. "Act as a senior engineer," "think step by step," "be thorough." These feel productive but change nothing — Claude already does them. General advice that does not prevent a specific mistake is pure noise. Rules a tool already enforces. If you have a formatter or linter, do not restate what it enforces. Wire it into a hook instead, and keep CLAUDE.md for what tools cannot enforce. The one-line test For every line, ask: "If I remove this, will Claude make a mistake?" If yes, keep it. If no, delete it. This single question, applied ruthlessly, is the difference between a file Claude follows and one it ignores. A bloated file buries the rules that matter in noise, so Claude cannot tell which line is the

2026-06-21 原文 →
AI 资讯

What Is CLAUDE.md? A Practical Guide to Configuring Claude Code

If you use Claude Code, there is one file that quietly shapes every session: CLAUDE.md. Most developers either do not have one or have one that works against them. Here is what it actually is, in plain terms. The file Claude reads every session CLAUDE.md is a markdown file that Claude Code reads at the start of every conversation. Think of it as your project's constitution — the source of truth for how your specific repository works. Because Claude reads it every time, you stop re-explaining your stack, your conventions, and your commands on every task. Why it exists Without a CLAUDE.md, every session starts cold. Claude can read your code, but it cannot infer the things that live outside the code: that you are on Next.js 15 and not 14, that a directory is generated and must never be edited, that your team has a particular commit style. You end up explaining these again and again, slightly differently each time, so the output drifts. CLAUDE.md captures that knowledge once, somewhere Claude always sees it. Where it lives, and how to start Put CLAUDE.md in the root of your project. You do not have to write it from a blank page — the /init command analyses your codebase and generates a starter, detecting your build tools, test framework, and existing patterns: $ claude > /init Treat the result as a foundation, not a finished product. The real value comes from refining it as you learn what Claude gets wrong without guidance. What belongs in it A good CLAUDE.md is short and specific: A one-line stack description, with versions — Claude will not guess Next.js 15 over 14 A directory map — the top-level layout and what each part holds The build and test commands The conventions a newcomer could not infer from the code A "do not touch" section — generated files, migrations, protected paths Here is a compact example: # Project: Acme Dashboard Next.js 15 (App Router), TypeScript, Drizzle ORM, Vitest. ## Structure src/app/ # routes and pages db/migrations/ # generated - never h

2026-06-21 原文 →
AI 资讯

Why Claude Code Ignores Your CLAUDE.md (And How to Fix It)

You wrote a detailed CLAUDE.md, and Claude Code still gets things wrong — wrong convention, touches files it should not, ignores rules you clearly wrote down. The cause is almost never that the rules are missing. It is that they are buried. The over-specified file problem CLAUDE.md loads into Claude's context every single session, and performance degrades as that context fills. When the file grows too long, something counterintuitive happens: Claude starts ignoring parts of it. The important rules get lost in the noise, and the genuinely critical instructions sit too deep to reliably influence output. A bloated file does not just waste tokens. It actively makes Claude less reliable, because it cannot tell which of your hundred lines is the one that matters. The trap of good intentions It always starts reasonably: "let me put everything relevant in here." But relevant is a low bar. The file grows until it is impossible to scan, full of duplication, and so noisy that the truly important rules carry no weight. More content felt like more control. It was the opposite. The fix: prune ruthlessly Run every line through one question: "If I remove this, will Claude make a mistake?" If the answer is no, the line is noise — delete it. And if something only matters in a specific situation rather than always, it does not belong in the always-loaded file at all. That is what skills and subdirectory CLAUDE.md files are for — they load on demand, only when relevant. Let Claude fetch what it needs Instead of embedding everything, tell Claude how to pull context when it needs it. Rather than pasting an entire API guide into the file: # Wasteful - embeds the whole file every session: @docs/api-guide.md # Better - Claude reads it only when relevant: For Stripe integration work, read docs/stripe-guide.md The second form costs almost nothing until the moment it is needed. The result A pruned CLAUDE.md is often a third of the length and many times more effective. The rules that matter are

2026-06-21 原文 →
AI 资讯

Gelişmiş Veri İşleme (Python)

Gelişmiş Veri İşleme (Python) Sıralama, Filtreleme ve Arama – Profesyonel Veri Manipülasyonu Rehberi Python’da veri işleme, sadece döngülerden ibaret değildir. Modern Python yaklaşımı; fonksiyonel programlama araçları , yüksek seviyeli built-in fonksiyonlar ve lambda ifadeleri ile daha kısa, daha okunabilir ve daha performanslı çözümler üretmeyi hedefler. Bu bölümde dört kritik alanı derinlemesine inceleyeceğiz: sorted() ile gelişmiş sıralama lambda ile karmaşık veri yapıları üzerinde sıralama filter() ve map() ile fonksiyonel veri dönüşümü any() ve all() ile toplu doğrulama (validation) Her bölümde gerçek dünya senaryoları ve hands-on örnekler olacak. 1. sorted() Fonksiyonu — Gelişmiş Sıralama Motoru 1.1 Temel Yapı sorted ( iterable , key = None , reverse = False ) Parametreler: iterable: Liste, tuple, set vb. key: Sıralama kriteri (fonksiyon) reverse: True → büyükten küçüğe 1.2 Basit Sıralama ```python id="s1" sayilar = [5, 1, 9, 3, 7] sonuc = sorted(sayilar) print(sonuc) --- ## 1.3 Ters Sıralama ```python id="s2" sayilar = [5, 1, 9, 3, 7] print(sorted(sayilar, reverse=True)) 1.4 Tuple Sıralama ```python id="s3" veri = (10, 5, 20, 15) print(sorted(veri)) --- ## 1.5 String Sıralama (ASCII mantığı) ```python id="s4" kelimeler = ["python", "ai", "data", "backend"] print(sorted(kelimeler)) 2. key Parametresi — Sıralamanın Beyni sorted() fonksiyonunun gerçek gücü burada başlar. 2.1 String Uzunluğuna Göre Sıralama ```python id="k1" kelimeler = ["python", "ai", "veri", "makineöğrenmesi"] sonuc = sorted(kelimeler, key=len) print(sonuc) --- ## 2.2 Sayıların Moduna Göre Sıralama ```python id="k2" sayilar = [10, 3, 7, 21, 14, 9] sonuc = sorted(sayilar, key=lambda x: x % 5) print(sonuc) 2.3 Tuple Sıralama (Gerçek Dünya) ```python id="k3" urunler = [ ("Laptop", 45000), ("Mouse", 500), ("Monitör", 12000) ] sonuc = sorted(urunler, key=lambda x: x[1]) print(sonuc) --- ## 2.4 Çok Katmanlı Sıralama Fiyat → sonra isim ```python id="k4" urunler = [ ("Laptop", 45000), ("Mouse", 500),

2026-06-21 原文 →
AI 资讯

PostgreSQL Indexing Deep Dive - Choosing the Right Index

In the earlier posts of this series, we looked at practical query tuning tips and how to read and interpret query plans . A recurring theme in both was: "add an index here." But "add an index" is a bit like saying "use the right tool" — the interesting part is which one. PostgreSQL ships with several index types, each tuned for a different kind of data and query. Picking the wrong one means PostgreSQL quietly ignores your index and goes back to a sequential scan. In this post, we'll walk through the main index types, when each shines, and the special index variations (composite, partial, covering, expression) that often matter more than the type itself. Setting the Scene: Schema and Sample Data We'll reuse the same schema from the previous posts, with one small addition — a metadata JSONB column and a tags array on orders , so we can explore the more exotic index types. CREATE TABLE customers ( id SERIAL PRIMARY KEY , customer_name VARCHAR ( 255 ), email VARCHAR ( 255 ), created_at TIMESTAMPTZ DEFAULT NOW () ); CREATE TABLE orders ( id SERIAL PRIMARY KEY , customer_id INT REFERENCES customers ( id ), order_date TIMESTAMPTZ DEFAULT NOW (), total_amount NUMERIC ( 10 , 2 ), status VARCHAR ( 20 ), tags TEXT [], metadata JSONB ); -- Insert sample customers INSERT INTO customers ( customer_name , email ) SELECT 'Customer ' || i , 'customer' || i || '@example.com' FROM generate_series ( 1 , 1000000 ) AS s ( i ); -- Insert sample orders INSERT INTO orders ( customer_id , order_date , total_amount , status , tags , metadata ) SELECT ( RANDOM () * 1000000 ):: INT , NOW () - interval '1 day' * ( RANDOM () * 365 ):: int , ( RANDOM () * 500 + 20 ), ( ARRAY [ 'pending' , 'shipped' , 'delivered' , 'cancelled' ])[ FLOOR ( RANDOM () * 4 + 1 )], ARRAY [( ARRAY [ 'gift' , 'priority' , 'fragile' , 'bulk' ])[ FLOOR ( RANDOM () * 4 + 1 )]], jsonb_build_object ( 'channel' , ( ARRAY [ 'web' , 'mobile' , 'store' ])[ FLOOR ( RANDOM () * 3 + 1 )]) FROM generate_series ( 1 , 1000000 ) AS s ( i

2026-06-21 原文 →
AI 资讯

Use Unix Domain Sockets on Windows Python: Building an AF_UNIX Compatibility API

Python provides socket.AF_UNIX , asyncio.open_unix_connection() , and asyncio.start_unix_server() for working with Unix Domain Sockets on Unix-like operating systems. On Windows, however, support for Unix Domain Sockets tends to depend on the Python version and runtime environment. In particular, differences become apparent when trying to use the higher-level asyncio APIs in the same way as on Unix. To address this, I created a compatibility layer that hides the differences between Unix and Windows and allows AF_UNIX sockets to be used through a largely identical API. This article covers two types of APIs: An asyncio -based AF_UNIX compatibility API A synchronous socket -based AF_UNIX compatibility API Goal The objective is straightforward. On Unix, use the standard library APIs as-is. On Windows, fill in the missing functionality so that application code can remain as unified as possible. For example, on Unix you can write: reader , writer = await asyncio . open_unix_connection ( path ) And on the server side: server = await asyncio . start_unix_server ( handle_client , path ) The goal is to preserve this style of programming on Windows as much as possible. What Was Built The compatibility layer consists of two major components. 1. Asyncio Version This is the asynchronous implementation designed to match the asyncio Unix Domain Socket APIs. The main APIs are: await open_unix_connection ( path , * , limit = ...) await start_unix_server ( callback , path , * , limit = ..., backlog = ...) await create_unix_connection ( protocol_factory , path , ...) await create_unix_server ( protocol_factory , path , ...) install () On Unix-like systems, these simply delegate to the standard asyncio implementation. On Windows, they use Winsock AF_UNIX sockets and combine WSAEventSelect with event-loop handle waiting to implement asynchronous operations. 2. Synchronous Socket Version This version provides a traditional blocking-socket-style API without using asyncio . The main APIs ar

2026-06-21 原文 →
AI 资讯

Three post-deploy checks I run after every Cloudflare Pages build

After spending two weeks debugging issues that only showed up in production — a sitemap _redirects rule that was blocking my own sitemap-index.xml and a Bluesky image upload race against Cloudflare Pages deploy lag — I added three post-deploy checks to my workflow. They're fast and specific to the failure modes I've actually hit, not a full end-to-end test suite. Three sites (aiappdex.com, findindiegame.com, ossfind.com) on Cloudflare Pages with Astro 5 SSG. Here's what I check. Check 1: Sitemap reachability The simplest check and the one I should have had from day one. After a Cloudflare Pages deploy, I verify that sitemap-index.xml is reachable and returning 200 on all three domains: for domain in aiappdex.com findindiegame.com ossfind.com ; do status = $( curl -s -o /dev/null -w "%{http_code}" "https:// $domain /sitemap-index.xml" ) echo " $domain /sitemap-index.xml → $status " if [ " $status " != "200" ] ; then echo "FAIL: $domain sitemap unreachable" fi done I also check sitemap-0.xml — the actual URL sub-sitemap that @astrojs/sitemap generates — and assert that it contains at least a minimum expected URL count. For aiappdex.com that threshold is 1,000; if it drops below that after a deploy, the ETL data pipeline probably broke silently. The reason this check exists: I had a _redirects rule rewriting sitemap-index.xml → sitemap-0.xml as an emergency workaround that turned out to be wrong. It was live for five days before I found it. The rule was blocking the real sitemap-index.xml from reaching crawlers while appearing fine in the browser (which followed the redirect). Curl with -o /dev/null -w "%{http_code}" doesn't follow redirects by default, so it would have caught this immediately. Check 2: IndexNow batch submission After every successful sitemap check, I run node scripts/indexnow.mjs . The script reads the live sitemap XML from each domain, collects all URLs, and POSTs them to the IndexNow endpoint for Bing, Yandex, Naver, and Seznam using site-specific k

2026-06-21 原文 →
AI 资讯

Three post-deploy checks I run after every Cloudflare Pages build

After spending two weeks debugging issues that only showed up in production — a sitemap _redirects rule that was blocking my own sitemap-index.xml and a Bluesky image upload race against Cloudflare Pages deploy lag — I added three post-deploy checks to my workflow. They're fast and specific to the failure modes I've actually hit, not a full end-to-end test suite. Three sites (aiappdex.com, findindiegame.com, ossfind.com) on Cloudflare Pages with Astro 5 SSG. Here's what I check. Check 1: Sitemap reachability The simplest check and the one I should have had from day one. After a Cloudflare Pages deploy, I verify that sitemap-index.xml is reachable and returning 200 on all three domains: for domain in aiappdex.com findindiegame.com ossfind.com ; do status = $( curl -s -o /dev/null -w "%{http_code}" "https:// $domain /sitemap-index.xml" ) echo " $domain /sitemap-index.xml → $status " if [ " $status " != "200" ] ; then echo "FAIL: $domain sitemap unreachable" fi done I also check sitemap-0.xml — the actual URL sub-sitemap that @astrojs/sitemap generates — and assert that it contains at least a minimum expected URL count. For aiappdex.com that threshold is 1,000; if it drops below that after a deploy, the ETL data pipeline probably broke silently. The reason this check exists: I had a _redirects rule rewriting sitemap-index.xml → sitemap-0.xml as an emergency workaround that turned out to be wrong. It was live for five days before I found it. The rule was blocking the real sitemap-index.xml from reaching crawlers while appearing fine in the browser (which followed the redirect). Curl with -o /dev/null -w "%{http_code}" doesn't follow redirects by default, so it would have caught this immediately. Check 2: IndexNow batch submission After every successful sitemap check, I run node scripts/indexnow.mjs . The script reads the live sitemap XML from each domain, collects all URLs, and POSTs them to the IndexNow endpoint for Bing, Yandex, Naver, and Seznam using site-specific k

2026-06-21 原文 →
AI 资讯

Cara Cepat Menambahkan MIT License di Repositori GitHub yang Sudah Ada

Pernahkah kamu membuat sebuah proyek perangkat lunak, mengunggahnya ke GitHub, lalu menyadari bahwa kamu belum menambahkan lisensi apa pun di repositori tersebut? Banyak developer pemula yang mengira bahwa menaruh kode di GitHub otomatis membuatnya menjadi open-source . Padahal, secara default , proyek tanpa fail lisensi memiliki hak cipta yang tertutup ( exclusive copyright ). Artinya, orang lain atau developer penerus secara teknis tidak boleh menyalin, mendistribusikan, atau memodifikasi kodemu. Agar proyek tersebut aman untuk dilanjutkan dan dimodifikasi oleh pengembang selanjutnya, kita wajib menambahkan lisensi terbuka. MIT License adalah pilihan paling aman dan populer karena sifatnya yang sangat membebaskan. Berikut adalah cara kilat menyematkan MIT License pada repositori GitHub yang sudah telanjur berjalan tanpa perlu menggunakan command line : Langkah 1: Buat Fail Baru di Repositori Buka halaman utama repositori GitHub kamu. Di bagian atas daftar fail dan folder kodemu, klik tombol Add file , kemudian pilih Create new file . Langkah 2: Pancing Fitur "License Template" Pada kolom pengisian nama fail, ketikkan kata LICENSE (pastikan menggunakan huruf kapital semua). Begitu kamu selesai mengetikkan kata tersebut, GitHub akan otomatis memunculkan sebuah tombol baru di sebelah kanan bernama Choose a license template . Klik tombol tersebut. Langkah 3: Pilih MIT License Kamu akan dibawa ke halaman yang berisi daftar berbagai jenis lisensi open-source . Pilih MIT License dari menu di sebelah kiri. GitHub akan otomatis meracik draf teks lisensinya, lengkap dengan nama akun GitHub kamu dan tahun saat ini. Klik tombol hijau Review and submit di pojok kanan atas. Langkah 4: Lakukan Commit Gulir ke bagian bawah halaman. Tulis pesan commit yang singkat dan jelas (misalnya: "Add MIT License for future development" ), lalu klik tombol hijau Commit changes... . Selesai! Sekarang proyek lama kamu sudah memiliki "payung" yang jelas dan resmi berstatus open-source . Reposito

2026-06-21 原文 →
AI 资讯

while Loop, break & continue, Lists (Creation, Mutability, Methods, List Comprehension)

📌 Key Concepts Overview Concept One-Line Definition while loop Repeats code as long as a condition is True while True Infinite loop — needs break to stop break Immediately exits the loop continue Skips current iteration, moves to next List Ordered, mutable collection — heterogeneous elements allowed List Comprehension One-line way to build a list using a loop + condition List Mutability Lists can be changed in place — id() stays the same 🔁 Part 1 — while Loop The 3 Components (Critical Pattern) # 1. Initialisation 2. Condition 3. Increment/Decrement a = 1 # 1. Initialisation while a <= 10 : # 2. Condition print ( ' Devops ' ) a += 1 # 3. Increment # Without increment → INFINITE LOOP (condition never becomes False) How it works: Condition is checked before each iteration. As soon as it's False , the loop stops. Miss the increment/decrement → infinite loop (a real production hazard — can hang a script or burn CPU). while — Practical Patterns # Countdown (decrement) a = 10 while a > 0 : print ( ' Devops ' ) a -= 1 # Sum of 1 to 20 total = 0 a = 1 while a <= 20 : total += a a += 1 print ( total ) # 210 # Product (factorial-style) of 1 to 20 product = 1 a = 1 while a <= 20 : product *= a a += 1 print ( product ) # Pattern using while + string repetition str1 = ' Devops ' i = 0 while i < len ( str1 ): print ( str1 [ i ] * ( i + 1 )) i += 1 # D # ee # vvv # oooo # ppppp # ssssss for vs while — When to Use Which Use for Use while You know the iterable / number of repetitions You don't know how many times — depends on a condition Looping over list, string, range Retry logic, polling, waiting for a state # DevOps: retry logic — classic while True use case max_attempts = 5 attempt = 0 while attempt < max_attempts : print ( f ' Attempt { attempt + 1 } : Connecting to server... ' ) # if connection succeeds: break attempt += 1 while True — Infinite Loop Pattern # Always True — runs forever until break is hit # Used for: retry logic, polling, menu-driven scripts, password validati

2026-06-20 原文 →
开发者

Remote File Inclusion: How a Single URL Parameter Can Give Attackers Full Control of Your Server

Remote File Inclusion (RFI) is a web vulnerability where an application accepts a URL from user input, fetches the file at that URL, and executes it. When there is no validation on what URLs are allowed, an attacker can point the application to a malicious script on their own server and get it executed remotely. This pattern shows up in automation tools, plugin systems, and CI/CD pipelines. The idea of loading scripts from a URL seems useful, but without strict controls, it becomes a direct path to remote code execution. Here is a simplified example of vulnerable server-side code: // Vulnerable automation runner - DO NOT USE IN PRODUCTION const express = require ( ' express ' ); const http = require ( ' http ' ); const https = require ( ' https ' ); const app = express (); app . get ( ' /api/automation/run ' , ( req , res ) => { const scriptUrl = req . query . scriptUrl ; const startTime = Date . now (); const parsedUrl = new URL ( scriptUrl ); const client = parsedUrl . protocol === ' https: ' ? https : http ; client . get ( scriptUrl , ( response ) => { let data = '' ; response . on ( ' data ' , ( chunk ) => { data += chunk ; }); response . on ( ' end ' , () => { // VULNERABLE: executes fetched script without sandboxing or validation const output = eval ( data ); const executionTime = Date . now () - startTime ; res . json ({ status : ' success ' , output : output , executionTimeMs : executionTime }); }); }); }); app . listen ( 8080 , () => { console . log ( ' Server running on port 8080 ' ); }); The core problem with the code above: It accepts any URL from user input without validation It fetches and runs that URL's content using eval() There is no sandboxing or restriction on what the script can do The code runs with the same privileges as the application itself Ethical Considerations This is for educational purposes only. You should only test for RFI on systems you own or have explicit permission to test. Unauthorized testing is illegal and can lead to serious

2026-06-20 原文 →
AI 资讯

AI Model Failover Drills: Keep Agents Useful When Providers Break

A model fallback that only works in a diagram is not resilience. It is a TODO with better branding. If your product depends on AI agents, one slow provider, rate-limit spike, regional restriction, malformed response, or model behavior change can turn a useful workflow into a confusing user experience. The dangerous part is not always a clean outage. The dangerous part is a half-working fallback that silently changes schemas, drops tool state, skips citations, or gives users lower-confidence output without saying so. This guide shows how to run practical AI model failover drills before production traffic teaches you the lesson the hard way. The goal is not to make every model interchangeable. The goal is to keep the user workflow safe, honest, and recoverable when the primary model cannot do the job. Why model failover needs drills, not just retries Most teams start with a simple fallback chain: try the primary model, then a backup model, then show an error. That is better than nothing, but it misses the real problems in AI applications. Traditional APIs usually fail in obvious ways: timeout, 500, bad credentials, quota exceeded. AI systems can fail more subtly: The backup model returns valid JSON with different field meanings. A cheaper model ignores part of the tool policy. A provider accepts the request but streams tokens too slowly. A fallback model does not support the same function-calling format. A regional policy or access rule changes availability. The model completes the answer but loses citation discipline. The agent retries and burns the tenant budget. The final response looks polished but skipped the expensive verification step. Recent AI infrastructure conversations are pointing in the same direction: the system around the model now matters as much as the model. Agent benchmarks, provider reliability, AI cost pressure, and model routing are all active developer concerns. Search results also show many broad posts about LLM fallback strategy, but fewer pr

2026-06-20 原文 →
AI 资讯

Python for Beginners — Part 1: Getting Started & Syntax

A beginner-friendly series on learning Python from scratch, one concept at a time. If you've ever wanted to learn programming but felt intimidated by curly braces, semicolons, and confusing syntax — Python is where you start breathing easy. It reads almost like English, and it's one of the most in-demand languages in the world today, used everywhere from web apps to data science to automation scripts. This is Part 1 of a beginner series that will take you from "what even is Python" to writing real, working programs. Let's begin. What is Python? Python is a general-purpose programming language created by Guido van Rossum and first released in 1991. It's popular because of three big reasons: It's beginner-friendly. The syntax is clean and close to natural language. It's versatile. You can build websites, automate tasks, analyze data, train machine learning models, or write small scripts — all with Python. It has a massive ecosystem. Thousands of ready-made libraries mean you rarely build things from scratch. Python runs on Windows, macOS, and Linux, and it's free and open source. Installing Python Most systems can run Python after a quick install: Go to python.org/downloads and grab the latest stable version. During installation on Windows, make sure to check "Add Python to PATH" — this saves you a lot of headaches later. Verify the install by opening your terminal (Command Prompt, PowerShell, or your Mac/Linux terminal) and typing: python --version If you see something like Python 3.13.0 , you're good to go. Tip: On some systems (especially macOS/Linux), you might need to type python3 instead of python . Your First Python Program Open a terminal, type python , hit Enter, and you'll land inside the Python interactive shell . Try this: print ( " Hello, World! " ) You should see: Hello, World! Congratulations — you just wrote your first Python program. print() is a built-in function that displays output on the screen. For anything beyond one-liners, you'll want to write

2026-06-20 原文 →
AI 资讯

Parsing and Rebuilding EPUB Files in Python: Lessons Learned from Building an AI Translation Service

How we extract, translate, and reconstruct entire ebooks with Python while preserving every detail At LectuLibre, we built a service that translates entire books using large language models. Our users upload EPUB files, and our backend pipeline parses them, extracts the text, sends it to an LLM for translation, and then rebuilds the EPUB with the translated content—all while preserving the original formatting, images, and metadata. This sounded straightforward until we looked inside a real EPUB. EPUB is essentially a ZIP file containing a structured set of XHTML, CSS, and XML files. The content.opf file defines the reading order (spine), metadata, and manifest. The toc.ncx holds the table of contents. The actual text lives in XHTML documents, often split per chapter. To translate a book, we needed to: 1) reliably parse the EPUB, 2) locate all translatable text, 3) send it chunk by chunk to the LLM, and 4) rebuild the EPUB with the translated text while keeping every byte of the formatting intact. The Problem with Off-the-Shelf Libraries We initially reached for ebooklib , the most popular Python library for EPUB manipulation. It worked great for simple EPUBs—until we threw a few hundred real-world files at it. We quickly hit issues: Metadata loss : ebooklib didn’t fully preserve custom metadata or namespace-prefixed properties in the OPF. Namespace handling : When modifying XHTML, it could strip or mangle xmlns attributes, breaking rendering on some devices. TOC and spine sync : After rebuilding, the table of contents and spine often got out of sync unless we manually repaired them. Large files : Processing a 200‑chapter book consumed surprising memory because ebooklib loaded everything at once. We could have used a heavyweight tool like Calibre’s command-line interface, but that introduced external dependencies and wasn’t as programmatically flexible. Instead, we decided to stick with ebooklib for high-level book structure and augment it with lxml for precise XML c

2026-06-20 原文 →
AI 资讯

Supervised vs. Unsupervised Machine Learning: How to Choose the Right Approach

Supervised vs. Unsupervised Machine Learning: How to Choose the Right Approach Supervised learning trains a model on data that's already labeled with the correct answer, so it learns to predict outcomes for new, unseen examples. Unsupervised learning works on unlabeled data and finds patterns or groupings on its own, without being told what the "right answer" looks like. Use supervised learning when you have historical examples of the outcome you want to predict; use unsupervised learning when you're trying to discover structure in data you don't yet understand. That's the short version. Here's what it actually means in practice, and how to know which one your project needs. What is supervised learning? In supervised learning, every training example comes with a label — the "correct answer" the model is trying to learn to predict. Feed a model thousands of emails, each tagged "spam" or "not spam," and it learns the patterns that separate the two. Once trained, it can label emails it's never seen before. The defining trait: you already know the outcome for your training data. You're not asking the model to discover something new — you're asking it to learn a pattern well enough to apply it to fresh cases. Common supervised tasks: Classification — sorting things into categories (spam vs. not spam, fraudulent vs. legitimate transaction) Regression — predicting a number (home price, next month's revenue) What is unsupervised learning? Unsupervised learning gets raw, unlabeled data and is asked to find structure in it — without anyone telling it what to look for. There's no "correct answer" to check against during training. The defining trait: you don't know the outcome in advance — you're trying to find it. A retailer might feed customer purchase histories into an unsupervised model not because they have a label called "customer segment" already assigned, but because they want the model to discover natural groupings on its own. Common unsupervised tasks: Clustering — gr

2026-06-20 原文 →
AI 资讯

Event-Handling-Basics

Event Handling Basics in euv Project Code: https://github.com/euv-dev/euv euv is a Rust + WASM frontend UI framework that enables developers to build interactive web applications using the power of reactive signals and the html! macro. One of the most critical aspects of any UI framework is how it handles user interactions. In this article, we will take a deep dive into euv's event handling system — from inline closures to native event handlers, from input events to form changes, and from the comprehensive list of supported event names to utility functions that simplify common patterns. Table of Contents Inline Closure Events NativeEventHandler Input Events Form Change Events Supported Event Names Accessing Event Data Utility Functions for Event Handling Putting It All Together Inline Closure Events The most straightforward way to handle events in euv is through inline closures. You define the event handler directly within the html! macro using the move |event: Event| { ... } syntax. html! { button { onclick : move | event : Event | { } "Click me" } } This pattern is ideal for simple, self-contained event handlers that don't need to be reused across multiple components. The move keyword ensures that any captured variables (like signals) are moved into the closure, which is essential for the Rust ownership model. Inline closures work with any event type — not just onclick . You can use them for keyboard events, focus events, mouse events, and more. The closure receives an Event object that you can inspect to extract relevant data. NativeEventHandler For more complex scenarios where you need reusable event handlers or want to define handlers outside the html! macro, euv provides the NativeEventHandler type. This allows you to create named, parameterized event handler functions. pub fn counter_on_increment ( counter : Signal < i32 > ) -> NativeEventHandler { NativeEventHandler :: create ( "click" , move | _event : Event | { let current : i32 = counter .get (); counter

2026-06-20 原文 →
AI 资讯

Metadata Routing

Stop Fighting Scikit-Learn Pipelines: How Metadata Routing Fixes Sample Weights & Groups A couple of months ago, I stumbled upon this video by Vincent D. Warmerdam about metadata routing in scikit-learn. I'll be honest, I had no idea what "metadata routing" even meant, but Vincent's explanation completely changed how I think about building ML pipelines. The video showed me that one of the most frustrating problems in scikit-learn; passing sample weights and groups through complex pipelines finally had an elegant solution. It piqued my curiosity enough that I dove deep into the feature, tested it extensively, and honestly, I was surprised by how little coverage this gets in technical blogs and articles. So I figured, why not write about it myself and share what I learned? If you've ever struggled with imbalanced datasets, grouped cross-validation, or just wanted to pass custom information through your pipelines, this article is for you. Let's start from the very beginning. What is "Metadata" in Machine Learning? Let's start with a concrete example. You're building a credit card fraud detection model with this data: # Your training data X = transaction_features # Amount, merchant, time, location, etc. y = is_fraud # 0 = legitimate, 1 = fraud # But you also have additional information: sample_weights = [ 1.0 , 1.0 , 10.0 , 1.0 , ...] # Fraud transactions weighted 10x customer_ids = [ 101 , 102 , 101 , 103 , ...] # Which customer made each transaction Metadata is the "extra information" beyond your features (X) and labels (y): sample_weight : How important is each transaction? (Fraud = 10x more important) groups : Which customer does each transaction belong to? (For proper cross-validation) Custom metadata : Transaction timestamps, confidence scores, data quality flags, etc. Why Metadata Matters: The Credit Card Fraud Problem Imagine you're building a fraud detection system for a financial company. You have: Imbalanced data : 99% legitimate transactions, 1% fraudulent T

2026-06-20 原文 →