# Peasy Dev — Full Catalog > Developer tools made easy. Peasy Dev provides free browser-based tools at https://peasydev.com/. All processing happens client-side — files never leave your device. ## Tools (26) ### Hash Generator Generate SHA-1, SHA-256, SHA-384, SHA-512 hashes from text Generate cryptographic hash digests from text using the Web Crypto API. Supports SHA-1, SHA-256, SHA-384, and SHA-512 algorithms with hex or Base64 output. All hashing is done in your browser — your data never leaves your device. - URL: https://peasydev.com/dev/hash-generator/ - Category: Developer Tools - Processing: client - Steps: 1. Paste or type text in the input area 2. Select the hash algorithm (SHA-256 is the default) 3. Choose output format: Hex (lowercase) or Base64 4. Toggle 'Hash per line' to hash each line separately 5. Click Generate to compute the hash ### Password Generator Generate strong, random passwords Generate cryptographically secure passwords with customizable length, character sets, and ambiguous character exclusion. Create multiple passwords at once for batch provisioning. - URL: https://peasydev.com/dev/password-generator/ - Category: Developer Tools - Processing: client - Steps: 1. Set the desired password length (8–128 characters) 2. Choose character types: uppercase, lowercase, numbers, symbols 3. Optionally exclude ambiguous characters (0, O, l, 1, I) 4. Set how many passwords to generate 5. Click Generate ### Unix Timestamp Converter Convert between Unix timestamps and human-readable dates Convert Unix epoch timestamps to human-readable dates and vice versa. Supports seconds and milliseconds. Auto-detects input format. - URL: https://peasydev.com/dev/timestamp-converter/ - Category: Developer Tools - Processing: client - Steps: 1. Enter a Unix timestamp or a date string 2. The tool auto-detects the format, or choose a direction manually 3. View the converted result with timezone information ### Cron Expression Generator Build and understand cron schedule expressions Build cron expressions with a visual interface. See the human-readable description and next scheduled run times. Supports standard 5-field cron syntax. - URL: https://peasydev.com/dev/cron-expression-generator/ - Category: Developer Tools - Processing: client - Steps: 1. Set each field: minute, hour, day of month, month, day of week 2. Use * for 'every', */N for intervals, comma-separated values for specific times 3. Click Generate to see the expression and next run times ### Chmod Calculator Convert between numeric and symbolic Unix file permissions Convert Unix file permissions between numeric (e.g., 755) and symbolic (e.g., rwxr-xr-x) notation. Auto-detects input format. - URL: https://peasydev.com/dev/chmod-calculator/ - Category: Developer Tools - Processing: client - Steps: 1. Enter a numeric permission (e.g., 755) or symbolic (e.g., rwxr-xr-x) 2. The tool auto-detects the format and converts to the other 3. View the permission breakdown for owner, group, and others ### String Escape / Unescape Escape and unescape strings for JSON, HTML, URL, XML, CSV, SQL Escape or unescape strings for use in JSON, HTML, URLs, XML, CSV, or SQL. Handles special characters, Unicode sequences, and encoding formats. - URL: https://peasydev.com/dev/string-escape-unescape/ - Category: Developer Tools - Processing: client - Steps: 1. Paste or type text in the input area 2. Select the format: JSON, HTML, URL, XML, CSV, or SQL 3. Choose direction: Escape or Unescape 4. Click Convert to transform the text ### IP Subnet Calculator Calculate subnet ranges, broadcast addresses, and CIDR notation Calculate IPv4 subnet details from an IP address and subnet mask or CIDR notation. View network address, broadcast address, usable host range, and total hosts. - URL: https://peasydev.com/dev/ip-subnet-calculator/ - Category: Developer Tools - Processing: client - Steps: 1. Enter an IP address with CIDR notation (e.g., 192.168.1.0/24) 2. Or enter an IP with subnet mask (e.g., 192.168.1.0 255.255.255.0) 3. Click Calculate to view subnet details ### Color Code Converter Convert colors between HEX, RGB, and HSL formats Convert colors between HEX, RGB, and HSL formats instantly. Auto-detects input format and shows all representations with a live color preview. - URL: https://peasydev.com/dev/color-converter/ - Category: Developer Tools - Processing: client - Steps: 1. Enter a color in any format: #FF6B35, rgb(255,107,53), or hsl(20,100%,60%) 2. Click Convert to see all representations 3. View the color preview swatch ### CSV ↔ JSON Converter Convert between CSV and JSON formats Convert CSV data to JSON arrays or JSON back to CSV. Supports custom delimiters, header rows, and nested values. - URL: https://peasydev.com/dev/csv-json-converter/ - Category: Developer Tools - Processing: client - Steps: 1. Paste CSV or JSON data in the input area 2. Select direction: CSV → JSON or JSON → CSV 3. Set delimiter (comma, tab, semicolon, pipe) for CSV 4. Toggle whether the first row contains headers 5. Click Convert ### XML ↔ JSON Converter Convert between XML and JSON formats Convert XML documents to JSON or JSON back to XML. Uses the browser's built-in DOMParser for accurate XML parsing. - URL: https://peasydev.com/dev/xml-json-converter/ - Category: Developer Tools - Processing: client - Steps: 1. Paste XML or JSON data in the input area 2. Select direction: XML → JSON or JSON → XML 3. Set indentation for formatted output 4. Click Convert ### SQL Formatter Format and minify SQL queries Format messy SQL queries into readable, indented code or minify formatted SQL into a single line. Supports keyword uppercasing. - URL: https://peasydev.com/dev/sql-formatter/ - Category: Developer Tools - Processing: client - Steps: 1. Paste a SQL query in the input area 2. Choose action: Format or Minify 3. Set indentation (2 or 4 spaces) 4. Toggle keyword uppercasing 5. Click Format ### Markdown Table Generator Convert CSV/TSV data into formatted Markdown tables Transform tabular data into clean Markdown table syntax. Paste CSV, TSV, or pipe-separated data and get properly formatted Markdown tables with column alignment options. - URL: https://peasydev.com/dev/markdown-table/ - Category: Developer Tools - Processing: client - Steps: 1. Paste or type your tabular data (CSV, TSV, or pipe-separated) 2. Choose column alignment (left, center, right, or default) 3. Toggle header row detection on or off 4. Copy the generated Markdown table ### HTTP Status Code Reference Look up HTTP status codes with descriptions and usage Quick reference for all HTTP status codes. Search by code number or keyword to find the meaning, description, and common usage of any HTTP response status code. - URL: https://peasydev.com/dev/http-status/ - Category: Developer Tools - Processing: client - Steps: 1. Type a status code number (e.g., 404) or keyword (e.g., 'not found') 2. Browse matching results with descriptions 3. Copy any status code information you need ### Meta Tags Generator Generate HTML meta tags, Open Graph, and Twitter Card tags Create complete meta tag sets for web pages including standard HTML meta tags, Open Graph (Facebook/LinkedIn), and Twitter Card tags. Enter your page details and get ready-to-use HTML. - URL: https://peasydev.com/dev/meta-tags/ - Category: Developer Tools - Processing: client - Steps: 1. Enter your page title and description 2. Select the Open Graph type (website, article, product, etc.) 3. Optionally add URL and image URL 4. Copy the generated meta tags into your HTML <head> ### Robots.txt Generator Create robots.txt files with AI crawler blocking options Generate robots.txt files for your website with easy-to-use options. Include rules for search engine crawlers, AI bots, and custom paths. Supports sitemap URL declaration and crawl delay. - URL: https://peasydev.com/dev/robots-txt/ - Category: Developer Tools - Processing: client - Steps: 1. Choose to allow all or selectively disallow paths 2. Add paths to block (e.g., /admin/, /api/) 3. Optionally add your sitemap URL 4. Set crawl delay if needed 5. Copy the generated robots.txt content ### .gitignore Generator Generate .gitignore files for popular frameworks Create .gitignore files for popular programming languages and frameworks. Choose from Node.js, Python, Java, Go, Rust, Ruby, Swift, .NET, Flutter, and Unity templates. - URL: https://peasydev.com/dev/gitignore/ - Category: Developer Tools - Processing: client - Steps: 1. Select your framework/language from the dropdown 2. Review the generated .gitignore patterns 3. Copy and save as .gitignore in your project root ### HTML Formatter Beautify or minify HTML code with proper indentation Format HTML code with proper indentation and line breaks, or minify it by removing whitespace. Supports customizable indent size for beautified output. - URL: https://peasydev.com/dev/html-formatter/ - Category: Developer Tools - Processing: client - Steps: 1. Paste your HTML code in the input area 2. Choose Format (beautify) or Minify 3. Select indent size (2 or 4 spaces) 4. Copy the formatted result ### CSS Unit Converter Convert between px, rem, em, pt, %, vw, and vh Convert CSS units between px, rem, em, pt, percentage, vw, and vh. Set your base font size and viewport dimensions for accurate conversions across all CSS length units. - URL: https://peasydev.com/dev/css-units/ - Category: Developer Tools - Processing: client - Steps: 1. Enter a CSS value with unit (e.g., '16px', '1rem', '12pt') 2. Set base font size for rem/em calculations (default: 16px) 3. Set viewport width/height for vw/vh calculations 4. See all equivalent values across 7 CSS units ### JSONPath Evaluator Query JSON data using JSONPath expressions Evaluate JSONPath expressions against JSON data. Supports dot notation, bracket notation, wildcards, array slicing, and recursive descent. - URL: https://peasydev.com/dev/json-path/ - Category: Developer Tools - Processing: client - Steps: 1. Paste your JSON data in the input area 2. Enter a JSONPath expression (e.g., $.store.book[0].title) 3. View the matching results ### Text Diff Checker Compare two texts and highlight differences Compare two text inputs and see the differences highlighted in unified diff format. Useful for comparing code versions, configuration files, or any text content. - URL: https://peasydev.com/dev/dev-text-diff/ - Category: Developer Tools - Processing: client - Steps: 1. Paste the original text in the first input area 2. Paste the modified text in the second input area 3. Toggle whitespace handling if needed 4. View the unified diff output with +/- indicators ### Data URI Converter Encode text to Data URIs or decode Data URIs to text Convert text content to Base64-encoded Data URIs or decode existing Data URIs back to readable text. Supports multiple MIME types including text, HTML, CSS, JavaScript, JSON, and SVG. - URL: https://peasydev.com/dev/data-uri/ - Category: Developer Tools - Processing: client - Steps: 1. Choose Encode (text→URI) or Decode (URI→text) 2. For encoding: paste content and select MIME type 3. For decoding: paste the full data: URI 4. Copy the result ### Lorem Ipsum Generator Generate placeholder text, code snippets, names, and emails Generate various types of placeholder content for development and design. Create lorem ipsum text, code variable names, fake person names, or test email addresses. - URL: https://peasydev.com/dev/lorem/ - Category: Developer Tools - Processing: client - Steps: 1. Select content type: Lorem Ipsum, Code, Names, or Emails 2. Choose the count and unit (words, sentences, or paragraphs) 3. Copy the generated placeholder content ### Path Converter Convert between Windows backslash and Unix forward-slash paths Convert file paths between Windows (backslash) and Unix/macOS (forward-slash) formats. Automatically detects the input format and converts to the other style. - URL: https://peasydev.com/dev/backslash/ - Category: Developer Tools - Processing: client - Steps: 1. Paste one or more file paths 2. The tool auto-detects Windows or Unix format 3. Get the converted paths in the opposite format ### .htaccess Generator Generate Apache .htaccess rules for redirects, caching, and security Create .htaccess configuration files for Apache web servers. Generate rules for HTTPS redirect, www handling, gzip compression, browser caching, and custom URL redirects. - URL: https://peasydev.com/dev/htaccess/ - Category: Developer Tools - Processing: client - Steps: 1. Toggle the rules you need (HTTPS, www, gzip, cache) 2. Add custom redirect paths if needed 3. Copy the generated .htaccess content 4. Upload to your Apache web server root ### .env Validator Validate, sort, and compare .env environment files Validate .env files for syntax errors, sort variables alphabetically, or compare two .env files to find differences. Essential for managing environment configuration across deployments. - URL: https://peasydev.com/dev/env/ - Category: Developer Tools - Processing: client - Steps: 1. Paste your .env file content 2. Choose action: Validate, Sort, or Compare 3. For Compare mode, paste the second .env in the input below 4. Review the results and copy cleaned output ### Placeholder Image Generator Generate placeholder image URLs for development and design Generate placeholder image URLs from popular services like placehold.co, picsum.photos, and dummyimage.com. Customize dimensions, text, and colors for development mockups. - URL: https://peasydev.com/dev/placeholder/ - Category: Developer Tools - Processing: client - Steps: 1. Set width and height in pixels 2. Choose a placeholder service 3. Optionally customize text and colors 4. Copy the generated URL or HTML img tag ## Guides (140) ### Video Codecs Explained: H.264, H.265, VP9, and AV1 Video codecs determine file size, quality, and compatibility. This guide compares the major codecs, from the ubiquitous H.264 to the next-generation AV1, to help you choose the right one for your project. - URL: https://peasydev.com/guides/video-codecs-explained/ - Category: Comparison - Reading time: 1 min - Words: 233 Key takeaways: - A codec (coder-decoder) compresses raw video data into a manageable file size. - H.264 has been the dominant video codec since 2003. - H.265 achieves 40-50% better compression than H.264 at equivalent quality. - VP9 is Google's royalty-free codec, roughly matching H.265 in efficiency. - AV1 offers 30% better compression than VP9/H.265. ## What Is a Video Codec? A codec (coder-decoder) compresses raw video data into a manageable file size. Without compression, one minute of 1080p video would be about 10 GB. Modern codecs reduce this to 50-150 MB with minimal quality loss. ## H.264 (AVC): The Universal Standard H.264 has been the dominant video codec since 2003. It's supported by every browser, every device, and every video platform. Hardware encoding and decoding are universal. **Best for:** Maximum compatibility, live streaming, video conferencing. ## H.265 (HEVC): Better Compression H.265 achieves 40-50% better compression than H.264 at equivalent quality. However, it's encumbered by patents and licensing fees, limiting adoption. **Best for:** 4K video, storage-constrained environments, Apple ecosystem. ## VP9: Google's Free Alternative VP9 is Google's royalty-free codec, roughly matching H.265 in efficiency. It's the primary codec for YouTube and is supported in most modern browsers. **Best for:** YouTube uploads, web video, Chrome-focused distribution. ## AV1: The Future AV1 offers 30% better compression than VP9/H.265. It's royalty-free and backed by major tech companies. Hardware decoding support is growing rapidly. **Best for:** Next-generation streaming, bandwidth-limited distribution. ## Quick Reference | Codec | Efficiency | Licensing | Browser Support | |-------|-----------|-----------|----------------| | H.264 | Baseline | Capped royalties | 99%+ | | H.265 | +40-50% | Complex licensing | ~75% | | VP9 | +40-50% | Royalty-free | ~95% | | AV1 | +60-70% | Royalty-free | ~85% | ### QR Code Generation: Best Practices for Print and Digital QR codes bridge physical and digital experiences, but poorly generated codes fail to scan. This guide covers sizing, error correction, design customization, and testing best practices for reliable QR codes. - URL: https://peasydev.com/guides/qr-code-generation-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 262 Key takeaways: - QR (Quick Response) codes store data in a two-dimensional barcode pattern. - The minimum QR code size depends on the scanning distance: - QR codes have four error correction levels that determine how much damage the code can sustain while remaining scannable: - You can customize QR codes while maintaining scannability: - Always test QR codes on multiple devices and under various lighting conditions before printing. ## QR Code Fundamentals QR (Quick Response) codes store data in a two-dimensional barcode pattern. They can encode URLs, text, phone numbers, Wi-Fi credentials, calendar events, and other structured data. ## Size Guidelines The minimum QR code size depends on the scanning distance: | Scanning Distance | Minimum QR Size | |-------------------|----------------| | 10 cm (phone held close) | 2 cm x 2 cm | | 30 cm (business card) | 2.5 cm x 2.5 cm | | 1 m (poster) | 10 cm x 10 cm | | 3 m (sign) | 30 cm x 30 cm | General rule: QR code width should be 1/10th of the scanning distance. ## Error Correction Levels QR codes have four error correction levels that determine how much damage the code can sustain while remaining scannable: - **L (Low, 7%)**: Smallest QR code, least redundancy. - **M (Medium, 15%)**: Good balance for most uses. - **Q (Quartile, 25%)**: Good for printed materials that may get worn. - **H (High, 30%)**: Best for codes with logo overlays. ## Design Customization You can customize QR codes while maintaining scannability: - **Colors**: Use dark modules on light backgrounds. Maintain at least 40% contrast. - **Logo overlay**: Place in the center over the error correction area. Use Level H. - **Rounded corners**: Slight rounding is fine; extreme rounding reduces scan reliability. - **Quiet zone**: Keep the white border (at least 4 modules wide). ## Testing Always test QR codes on multiple devices and under various lighting conditions before printing. Test with at least 3 different QR scanner apps. ### JSON vs YAML vs TOML: Choosing a Configuration Format Configuration files are the backbone of modern applications. JSON, YAML, and TOML each offer different trade-offs between readability, complexity, and tooling support that affect your development workflow. - URL: https://peasydev.com/guides/json-vs-yaml-vs-toml/ - Category: Comparison - Reading time: 1 min - Words: 244 Key takeaways: - Choosing a configuration format affects how easy your project is to set up, maintain, and debug. - JSON (JavaScript Object Notation) is the most widely supported data format. - YAML uses indentation instead of braces, making it more readable for complex nested structures. - TOML (Tom's Obvious Minimal Language) was designed specifically for configuration files. ## The Configuration Format Landscape Choosing a configuration format affects how easy your project is to set up, maintain, and debug. Each format has a loyal community and specific strengths. ## JSON: The Data Exchange Standard JSON (JavaScript Object Notation) is the most widely supported data format. Every programming language has a JSON parser, and it's the default for web APIs and package manifests. **Strengths:** Universal support, strict syntax, excellent tooling. **Weaknesses:** No comments, verbose (lots of quotes and braces), no trailing commas. ## YAML: Human-Readable Configuration YAML uses indentation instead of braces, making it more readable for complex nested structures. It's the default for Kubernetes, Docker Compose, GitHub Actions, and many CI/CD systems. **Strengths:** Readable, comments supported, multi-line strings, anchors/aliases. **Weaknesses:** Indentation-sensitive, implicit type coercion (e.g., `on` becomes boolean), complex spec. ## TOML: The Modern Alternative TOML (Tom's Obvious Minimal Language) was designed specifically for configuration files. It's used by Rust's Cargo, Python's pyproject.toml, and Hugo. **Strengths:** Comments, explicit types, readable, simple spec. **Weaknesses:** Deeply nested structures are awkward, less widespread tooling. ## Decision Matrix | Factor | JSON | YAML | TOML | |--------|------|------|------| | Comments | No | Yes | Yes | | Readability | Medium | High | High | | Complexity | Low | High | Low | | Trailing commas | No | N/A | Yes | | API data exchange | Best | Rare | Rare | | App configuration | Common | Common | Growing | ### QR Code Design Best Practices: Balancing Aesthetics and Scannability A QR code that looks great but fails to scan is worse than useless. Understanding the relationship between visual customization and error correction ensures reliable scanning across all devices and environments. - URL: https://peasydev.com/guides/qr-code-design-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 296 Key takeaways: - QR scanners rely on three finder patterns (the large squares in three corners) to locate and orient the code. - The center of a QR code is the safest area for logos or graphics. - Minimum contrast ratio:** 4:1 between foreground and background - The quiet zone (blank border around the code) must be at least 4 modules wide. - Test every custom QR code with at least three different scanning apps on both iOS and Android. ## How QR Scanners Read Codes QR scanners rely on three finder patterns (the large squares in three corners) to locate and orient the code. They then read the timing patterns (alternating modules between finders) to establish the grid, and finally decode the data modules. Any design modification that disrupts these structural elements will cause scan failures. ## Safe Customization Zones The center of a QR code is the safest area for logos or graphics. With error correction level H (30% redundancy), up to 25-30% of the data area can be obscured while maintaining scannability. This does not mean 30% of the entire code — the finder patterns, timing patterns, and format information must remain untouched. ## Color Rules - **Minimum contrast ratio:** 4:1 between foreground and background - **Dark on light only:** QR scanners expect dark modules on a light background. Inverted (light on dark) codes fail on many older scanner apps. - **Avoid gradients on modules:** Individual modules must have uniform color - **Background must be truly light:** Off-white, light pastels work. Medium gray reduces contrast below the scanning threshold. ## Size and Quiet Zone The quiet zone (blank border around the code) must be at least 4 modules wide. Many design failures happen when the QR code is placed on a busy background without sufficient quiet zone. The minimum printable size depends on scanning distance — a general rule is 10:1 ratio (10 cm code scans reliably at 1 meter). ## Testing Protocol Test every custom QR code with at least three different scanning apps on both iOS and Android. Test at the intended viewing distance, in the intended lighting conditions, and on the intended material (screen, paper, fabric). What scans perfectly on a high-resolution screen may fail when printed on textured cardstock. ### QR Codes for Restaurant Menus: Implementation Guide Contactless menus via QR codes became standard during the pandemic and remain popular for cost savings and easy updates. Implementing them well requires attention to scanning ergonomics, loading speed, and accessibility. - URL: https://peasydev.com/guides/qr-codes-restaurant-menus/ - Category: How-To - Reading time: 2 min - Words: 342 Key takeaways: - Beyond hygiene, QR menus eliminate printing costs ($500-2,000/year for a typical restaurant), allow instant menu updates (86'd items, daily specials, seasonal changes), and enable analytics on which items customers view most. - Place QR codes where diners naturally look: table tents, table stickers near the edge, or embedded in the table surface under a clear coating. - The menu page must load in under 2 seconds on a mobile device over cellular data. - QR menus must be accessible to users with disabilities: - QR menus can detect the device language and display the menu in the diner's preferred language automatically. ## Why QR Menus Persist Beyond hygiene, QR menus eliminate printing costs ($500-2,000/year for a typical restaurant), allow instant menu updates (86'd items, daily specials, seasonal changes), and enable analytics on which items customers view most. The key challenge is user experience — a poorly implemented QR menu frustrates diners more than a printed one. ## Physical Placement Place QR codes where diners naturally look: table tents, table stickers near the edge, or embedded in the table surface under a clear coating. The code should be at arm's length (30-50 cm scanning distance), requiring a minimum code size of 3×3 cm. Include brief text: 'Scan for Menu' — not everyone recognizes QR codes on sight. ## Landing Page Optimization The menu page must load in under 2 seconds on a mobile device over cellular data. Common mistakes that slow loading: - High-resolution food photography (compress to WebP, max 200 KB per image) - PDF menus requiring download (use a mobile-optimized web page instead) - Third-party widget scripts that block rendering The page should be a responsive HTML page, not a PDF. PDFs require pinch-to-zoom on mobile and cannot be updated without regenerating the entire file. ## Accessibility Requirements QR menus must be accessible to users with disabilities: - Provide a physical menu alternative on request (legally required in many jurisdictions) - Ensure the web menu works with screen readers (semantic HTML, proper heading hierarchy) - Use sufficient font size (minimum 16px body text) and contrast ratios - Avoid horizontal scrolling on any screen width ## Multilingual Menus QR menus can detect the device language and display the menu in the diner's preferred language automatically. This is a significant advantage for restaurants in tourist areas — a single QR code can serve menus in 5-10 languages without printing multilingual physical menus. … ### Two-Factor Authentication Methods Compared: TOTP, SMS, and Hardware Keys Compare the security, convenience, and cost of major 2FA methods including authenticator apps, SMS codes, hardware security keys, and biometrics. Find the right balance between protection and usability for your accounts. - URL: https://peasydev.com/guides/two-factor-authentication-methods-compared/ - Category: Comparison - Reading time: 1 min - Words: 289 Key takeaways: - Over 80% of data breaches involve compromised credentials. - SMS-based 2FA is the most widely supported method but also the weakest. - Time-based One-Time Password apps like Google Authenticator and Authy generate six-digit codes that rotate every 30 seconds. - FIDO2/WebAuthn hardware keys like YubiKey provide the strongest protection available. - The shared secret never leaves your device after initial setup, eliminating network interception risks. ## Why Passwords Alone Fail Over 80% of data breaches involve compromised credentials. Two-factor authentication adds a second verification layer that remains effective even when passwords are stolen. However, not all 2FA methods provide equal protection — the differences matter significantly for security-conscious users. ## Comparison of 2FA Methods | Method | Security | Convenience | Cost | Phishing Resistance | | --- | --- | --- | --- | --- | | SMS codes | Low | High | Free | None | | TOTP apps | Medium | Medium | Free | Low | | Push notifications | Medium | High | Free | Low | | Hardware keys (FIDO2) | Very high | Medium | $25-70 | Full | | Passkeys | High | High | Free | Full | ## SMS: Convenient but Vulnerable SMS-based 2FA is the most widely supported method but also the weakest. SIM-swap attacks allow criminals to port your phone number to their device. SS7 protocol vulnerabilities enable interception of text messages in transit. Despite these risks, SMS 2FA is still dramatically better than no second factor at all. ## TOTP Authenticator Apps Time-based One-Time Password apps like Google Authenticator and Authy generate six-digit codes that rotate every 30 seconds. The shared secret never leaves your device after initial setup, eliminating network interception risks. However, TOTP codes can still be captured by sophisticated phishing sites that relay them in real time. ## Hardware Security Keys FIDO2/WebAuthn hardware keys like YubiKey provide the strongest protection available. They use public-key cryptography bound to the specific website origin, making phishing mathematically impossible. The key signs a challenge that includes the site URL — a fake site produces a different challenge that the key rejects. ### Audio Bitrate and Quality: Finding the Right Balance Bitrate determines both file size and audio quality in lossy formats. Understanding the relationship between bitrate, codec efficiency, and perceptual quality helps you choose the optimal setting for each use case. - URL: https://peasydev.com/guides/audio-bitrate-quality-guide/ - Category: Best Practice - Reading time: 2 min - Words: 315 Key takeaways: - Bitrate measures the amount of data used to represent one second of audio, expressed in kilobits per second (kbps). - Every second of audio uses the same number of bits. - 'Transparent' means indistinguishable from the lossless source in double-blind testing. - At equivalent bitrates, modern codecs significantly outperform older ones: - Music streaming:** AAC 256 kbps or Opus 128 kbps ## What Bitrate Means Bitrate measures the amount of data used to represent one second of audio, expressed in kilobits per second (kbps). Higher bitrate means more data per second, which generally means higher quality — but codec efficiency determines how much quality a codec extracts from each kilobit. ## Constant vs. Variable Bitrate ### CBR (Constant Bitrate) Every second of audio uses the same number of bits. Simple passages waste bits; complex passages may be under-allocated. Predictable file size but suboptimal quality distribution. ### VBR (Variable Bitrate) The encoder allocates more bits to complex passages (dense orchestral, cymbals) and fewer to simple passages (silence, sustained notes). VBR produces better quality at a given average bitrate but results in slightly unpredictable file sizes. **Recommendation:** Always use VBR for quality-critical applications. ## Quality Thresholds by Format | Format | Transparent Threshold | Good Enough | Minimum Acceptable | |--------|---------------------|-------------|-------------------| | MP3 (LAME V0) | ~245 kbps VBR | 192 kbps | 128 kbps | | AAC (Apple/FDK) | ~192 kbps VBR | 128 kbps | 96 kbps | | OGG Vorbis | ~192 kbps VBR | 128 kbps | 96 kbps | | Opus | ~128 kbps VBR | 96 kbps | 64 kbps | 'Transparent' means indistinguishable from the lossless source in double-blind testing. ## Codec Efficiency Rankings At equivalent bitrates, modern codecs significantly outperform older ones: 1. **Opus** — Best overall efficiency (especially below 128 kbps) 2. **AAC (Apple/FDK)** — Best for music distribution 3. **OGG Vorbis** — Excellent open-source alternative 4. **MP3 (LAME)** — Oldest, least efficient, but most compatible ## Practical Guidelines - **Music streaming:** AAC 256 kbps or Opus 128 kbps - **Podcasts:** AAC 128 kbps mono or Opus 64 kbps mono - **Voice calls:** Opus 32-64 kbps (designed for speech) - **Background music (web):** AAC … ### Regex Cheat Sheet: Essential Patterns for Text Processing A practical regular expression reference covering the most commonly needed patterns for text processing. Includes email validation, URL matching, date parsing, and number formatting patterns with explanations. - URL: https://peasydev.com/guides/regex-cheat-sheet-essential-patterns/ - Category: How-To - Reading time: 1 min - Words: 243 Key takeaways: - Regular expressions describe text patterns using a concise syntax. - `*?`, `+?` — Non-greedy versions - Catastrophic backtracking: Patterns like `(a+)+b` can take exponential time on inputs like `aaaaaaaaaaac`. - ## Essential Patterns | Pattern | Matches | Example | | --- | --- | --- | | `\d{1,3}\. ## Regex Basics Regular expressions describe text patterns using a concise syntax. They power search-and-replace in editors, input validation in forms, and text extraction in data pipelines. Mastering a handful of core patterns covers 90% of real-world regex needs. ## Essential Patterns | Pattern | Matches | Example | | --- | --- | --- | | `\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}` | IPv4 address (loose) | `192.168.1.1` | | `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}` | Email (simple) | `user@example.com` | | `https?://[^\s]+` | URL (simple) | `https://example.com/page` | | `\d{4}-\d{2}-\d{2}` | ISO date | `2026-03-10` | | `#[0-9a-fA-F]{3,8}` | Hex color | `#FF6B35` | | `\b\w+\b` | Word boundary | Individual words | ## Quantifiers and Groups - `*` — Zero or more (greedy) - `+` — One or more (greedy) - `?` — Zero or one (optional) - `*?`, `+?` — Non-greedy versions - `{n,m}` — Between n and m repetitions - `(abc)` — Capture group - `(?:abc)` — Non-capturing group - `(?=abc)` — Lookahead (matches position before abc) - `(?<=abc)` — Lookbehind (matches position after abc) ## Common Mistakes **Catastrophic backtracking**: Patterns like `(a+)+b` can take exponential time on inputs like `aaaaaaaaaaac`. Avoid nested quantifiers on the same characters. **Greedy matching**: `<.*>` matches from the first `<` to the last `>` on a line, not individual tags. Use `<.*?>` (non-greedy) or `<[^>]*>` (character class). Test and refine your regex patterns with the Peasy regex tester — real-time matching with step-by-step explanation of how the engine processes each pattern. ### Text Encoding Explained: UTF-8, ASCII, Latin-1, and Unicode Demystify character encoding — why text appears as garbled symbols, how UTF-8 became the universal standard, and practical strategies for handling encoding issues in your workflow. - URL: https://peasydev.com/guides/text-encoding-utf8-ascii-unicode-explained/ - Category: How-To - Reading time: 1 min - Words: 261 Key takeaways: - Every text file is a sequence of bytes. - UTF-8 uses variable-length encoding: ASCII characters (U+0000 to U+007F) use one byte, identical to ASCII. - Double encoding**: UTF-8 bytes interpreted as Latin-1, then re-encoded to UTF-8 → `café` (two bytes for é become four) - Use UTF-8 everywhere — source files, databases, APIs, and file storage. ## Why Encoding Matters Every text file is a sequence of bytes. Character encoding defines the mapping between bytes and characters. When the wrong encoding is assumed, text appears as garbled symbols (mojibake) — `café` becomes `café` when UTF-8 is decoded as Latin-1. Understanding encoding prevents data corruption. ## The Encoding Timeline | Era | Encoding | Characters | Bytes/Char | | --- | --- | --- | --- | | 1960s | ASCII | 128 | 1 | | 1980s | Latin-1 (ISO 8859-1) | 256 | 1 | | 1990s | Windows-1252 | 256 (extended) | 1 | | 2000s | UTF-8 | 1,114,112 (all Unicode) | 1-4 | | Current | UTF-8 dominates (>98% of web) | — | — | ## How UTF-8 Works UTF-8 uses variable-length encoding: ASCII characters (U+0000 to U+007F) use one byte, identical to ASCII. Latin characters use two bytes. CJK characters and emoji use three to four bytes. This backward compatibility with ASCII is why UTF-8 won — existing ASCII text is valid UTF-8 without modification. ## Common Encoding Problems - **Double encoding**: UTF-8 bytes interpreted as Latin-1, then re-encoded to UTF-8 → `café` (two bytes for é become four) - **BOM insertion**: Some tools prepend a Byte Order Mark (EF BB BF) that other tools do not expect - **Database charset mismatch**: Connection charset differs from table charset ## Best Practice Use UTF-8 everywhere — source files, databases, APIs, and file storage. Specify encoding explicitly (`charset=utf-8`) rather than relying on platform defaults. Detect and convert encodings with the Peasy encoding tools. ### CSS Custom Properties (Variables): A Complete Guide Master CSS custom properties — from basic variable usage to advanced patterns like theming, component APIs, and responsive design tokens. Understand how they differ from preprocessor variables and when to use each. - URL: https://peasydev.com/guides/css-custom-properties-variables-complete-guide/ - Category: How-To - Reading time: 1 min - Words: 204 Key takeaways: - CSS custom properties (declared with `--`) are fundamentally different from Sass/Less variables. - background: var(--color-primary); - Define theme tokens as custom properties and swap them for different themes: - Custom properties create clean component interfaces. - Custom properties trigger style recalculation when changed. ## Custom Properties vs Preprocessor Variables CSS custom properties (declared with `--`) are fundamentally different from Sass/Less variables. Custom properties exist at runtime — they cascade, inherit, and can be changed dynamically with JavaScript. Preprocessor variables are compile-time constants that disappear in the output CSS. ## Basic Usage ```css :root { --color-primary: #3b82f6; --spacing-md: 1rem; --radius-lg: 0.75rem; } .button { background: var(--color-primary); padding: var(--spacing-md); border-radius: var(--radius-lg); } ``` ## Theming with Custom Properties Define theme tokens as custom properties and swap them for different themes: ```css :root { --bg: #ffffff; --text: #1a1a1a; } .dark { --bg: #1a1a1a; --text: #ffffff; } ``` Every element using `var(--bg)` automatically updates when the `.dark` class is toggled — no JavaScript per-element manipulation needed. ## Component APIs Custom properties create clean component interfaces. The component defines defaults, and consumers override only what they need: ```css .card { padding: var(--card-padding, 1.5rem); background: var(--card-bg, white); } ``` ## Performance Considerations Custom properties trigger style recalculation when changed. Avoid changing properties on `:root` during animations — scope them to the animated element to limit the recalculation scope. For static design tokens, preprocessor variables perform slightly better since they compile away. Generate and preview CSS custom property themes with the Peasy CSS tools. ### Video Codec Comparison: H.264 vs H.265 vs VP9 vs AV1 Four dominant video codecs compete for web delivery and streaming. Each balances compression efficiency, encoding speed, and browser support differently. This guide helps you choose the right codec. - URL: https://peasydev.com/guides/video-codec-comparison-h264-h265-vp9-av1/ - Category: Comparison - Reading time: 2 min - Words: 336 Key takeaways: - A codec (coder-decoder) compresses raw video into a manageable file size and decompresses it for playback. - Released in 2003, H.264 remains the most widely supported codec. - H.265 achieves roughly 50% better compression than H.264. - Google's royalty-free answer to H.265. - The newest codec, developed by the Alliance for Open Media. ## Understanding Video Codecs A codec (coder-decoder) compresses raw video into a manageable file size and decompresses it for playback. The codec determines quality-per-bit — better codecs produce smaller files at the same visual quality. ## H.264 (AVC) Released in 2003, H.264 remains the most widely supported codec. Every browser, device, and hardware decoder supports it. Encoding is fast and well-optimized after two decades of development. **Best for:** Maximum compatibility, real-time encoding, legacy device support. **Drawback:** 30-50% larger files than newer codecs at equivalent quality. ## H.265 (HEVC) H.265 achieves roughly 50% better compression than H.264. However, it carries licensing fees and limited browser support — only Safari and Edge support it natively. Chrome and Firefox do not. **Best for:** Apple ecosystem, 4K/HDR content, offline playback. **Drawback:** Patent licensing costs, poor browser support. ## VP9 Google's royalty-free answer to H.265. VP9 achieves similar compression to HEVC and is supported in Chrome, Firefox, and Edge. YouTube uses VP9 extensively for its streaming pipeline. **Best for:** Web delivery, YouTube, royalty-free workflows. **Drawback:** Slower encoding than H.264, no Safari support. ## AV1 The newest codec, developed by the Alliance for Open Media. AV1 achieves 30% better compression than VP9 and is royalty-free. Browser support is growing (Chrome, Firefox, Safari 17+). **Best for:** Future-proof delivery, maximum compression. **Drawback:** Very slow encoding (10-100x slower than H.264). Hardware encoders are still emerging. ## Comparison Table | Feature | H.264 | H.265 | VP9 | AV1 | |---------|-------|-------|-----|-----| | Compression | Baseline | +50% | +50% | +65% | | Browser support | 99%+ | Safari/Edge | 95%+ | ~90% | | Royalty-free | No* | No | Yes | Yes | | Encoding speed | Fast | Moderate | Slow | Very slow | | HDR support | Limited | Yes | Yes | Yes | … ### Structured Data Implementation: Schema.org for SEO Structured data helps search engines understand your content semantically, enabling rich results like stars, prices, FAQs, and recipe cards in search. This guide covers JSON-LD implementation. - URL: https://peasydev.com/guides/structured-data-schema-org-guide/ - Category: How-To - Reading time: 1 min - Words: 272 Key takeaways: - Structured data uses a standardized vocabulary (Schema.org) to annotate page content so search engines can parse meaning beyond raw text. - When a page needs multiple schema types (Article plus BreadcrumbList plus Organization), wrap them in a single `@graph` array rather than multiple separate script tags. - Missing required fields (e.g., `image` for Article) ## What Is Structured Data Structured data uses a standardized vocabulary (Schema.org) to annotate page content so search engines can parse meaning beyond raw text. The preferred format is JSON-LD (JavaScript Object Notation for Linked Data), embedded in a `<script type="application/ld+json">` tag. ## Rich Result Types | Schema Type | Rich Result | Use Case | |-------------|------------|----------| | Article | News carousel | Blog posts, news | | Product | Price, rating, availability | E-commerce | | FAQPage | Expandable Q&A | FAQ sections | | HowTo | Step-by-step cards | Tutorials | | Recipe | Image, time, rating | Food content | | BreadcrumbList | Navigation trail | All pages | | WebApplication | App info | Online tools | | Organization | Knowledge panel | About pages | ## JSON-LD Best Practices ### Use @graph for Multiple Types When a page needs multiple schema types (Article plus BreadcrumbList plus Organization), wrap them in a single `@graph` array rather than multiple separate script tags. ### Match Visible Content Google requires that structured data reflects content actually visible on the page. Marking up content that users cannot see violates guidelines and can result in manual actions. ### Test Before Deploying Use Google's Rich Results Test and Schema Markup Validator to verify your JSON-LD is error-free before pushing to production. ## Common Errors - Missing required fields (e.g., `image` for Article) - Using incorrect types (e.g., WebPage instead of Article for blog posts) - Hardcoded URLs instead of dynamic values - Forgetting to escape special characters in JSON strings - Nesting types incorrectly (publisher inside Article should be an Organization, not a string) ### Video Compression for Web: Reducing File Size Without Losing Quality Large video files slow page loads and consume bandwidth. Effective compression balances visual quality with file size using the right codec settings, resolution, and bitrate. - URL: https://peasydev.com/guides/video-compression-web-delivery/ - Category: How-To - Reading time: 1 min - Words: 281 Key takeaways: - An uncompressed 1080p video at 30fps generates about 178 MB per second. - Higher resolution means more pixels to encode. - Two-pass encoding analyzes the entire video first, then allocates bits optimally. - Always use VBR over constant bitrate (CBR) for web ## Why Video Compression Matters An uncompressed 1080p video at 30fps generates about 178 MB per second. Compression reduces this by 100-1000x while preserving acceptable visual quality. The goal is finding the lowest bitrate where compression artifacts remain invisible to viewers. ## Key Parameters ### Resolution Higher resolution means more pixels to encode. Downscaling from 4K to 1080p can halve file size with negligible quality loss on most screens. Match resolution to your delivery context — mobile viewers rarely benefit from resolutions above 720p. ### Bitrate Bitrate controls how many bits per second the encoder allocates. Higher bitrate means better quality but larger files. Use variable bitrate (VBR) to allocate more bits to complex scenes and fewer to static ones. **Recommended web bitrates:** | Resolution | Bitrate (H.264) | Bitrate (VP9/AV1) | |------------|-----------------|-------------------| | 480p | 1-2 Mbps | 0.7-1.5 Mbps | | 720p | 2.5-5 Mbps | 1.5-3 Mbps | | 1080p | 5-8 Mbps | 3-5 Mbps | | 4K | 15-25 Mbps | 8-15 Mbps | ### Constant Rate Factor (CRF) CRF is the simplest quality control. Lower values mean higher quality (and larger files). For H.264, CRF 23 is the default; 18-20 is visually lossless. For VP9, CRF 31 is a good starting point. ## Two-Pass Encoding Two-pass encoding analyzes the entire video first, then allocates bits optimally. This produces better quality than single-pass at the same file size but takes twice as long to encode. ## Practical Tips - Always use VBR over constant bitrate (CBR) for web - Set a maximum bitrate cap to prevent bandwidth spikes - Use keyframe intervals of 2-4 seconds for streaming - Test on slow connections (3G simulation) before publishing ### QR Code Content Generation Patterns and Best Practices QR codes can encode URLs, contact cards, Wi-Fi credentials, and more. Each content type follows a specific format that scanning apps interpret automatically. - URL: https://peasydev.com/guides/qr-code-content-generation-patterns/ - Category: How-To - Reading time: 1 min - Words: 257 Key takeaways: - The most commonly searched format: - QR codes include redundancy for damage tolerance: - Use short URLs or URL shorteners for smaller QR codes ## QR Code Content Types | Type | Format | Scanner Action | |------|--------|---------------| | URL | `https://example.com` | Opens browser | | Email | `mailto:user@example.com` | Opens email composer | | Phone | `tel:+1234567890` | Initiates call | | SMS | `smsto:+1234567890:Hello` | Opens messaging app | | Wi-Fi | `WIFI:T:WPA;S:NetworkName;P:Password;;` | Connects to network | | vCard | `BEGIN:VCARD...END:VCARD` | Adds contact | | Calendar | `BEGIN:VEVENT...END:VEVENT` | Creates event | | Plain text | Any string | Displays text | ## Wi-Fi QR Code Format The most commonly searched format: ``` WIFI:T:WPA;S:MyNetwork;P:MyPassword;H:false;; ``` Parameters: - T = Authentication type (WPA, WEP, or nopass) - S = Network SSID (name) - P = Password - H = Hidden network (true/false) ## vCard Format ``` BEGIN:VCARD VERSION:3.0 N:Doe;John;;; TEL:+1234567890 EMAIL:john@example.com ORG:Example Corp END:VCARD ``` ## Error Correction Levels QR codes include redundancy for damage tolerance: | Level | Recovery | Best For | |-------|----------|----------| | L (7%) | Low | Clean digital displays | | M (15%) | Medium | General use (default) | | Q (25%) | Quartile | Printed materials | | H (30%) | High | Labels, stickers (logo overlay) | Higher error correction means larger QR codes (more modules) for the same data. ## Best Practices - Use short URLs or URL shorteners for smaller QR codes - Test scanning with multiple apps and devices - Maintain adequate quiet zone (margin) around the code - Use high contrast (dark modules on light background) - Track scans by appending UTM parameters to URLs ### API Response Formats: JSON vs XML vs Protocol Buffers Choosing the right serialization format affects API performance, developer experience, and client compatibility. JSON dominates the web, but XML and Protocol Buffers have distinct advantages in specific use cases. - URL: https://peasydev.com/guides/api-response-formats-json-xml-protobuf/ - Category: Comparison - Reading time: 2 min - Words: 373 Key takeaways: - API response format is often chosen by default (JSON) without considering alternatives. - JSON (JavaScript Object Notation) became the dominant API format because it maps naturally to JavaScript objects and is human-readable. - XML (Extensible Markup Language) predates JSON and remains essential in enterprise, government, and legacy systems. - Developed by Google, Protocol Buffers use a binary serialization format with a schema defined in `.proto` files. ## The Serialization Landscape API response format is often chosen by default (JSON) without considering alternatives. For most web APIs, JSON is indeed the right choice — but understanding why helps you recognize the cases where it isn't. ## JSON JSON (JavaScript Object Notation) became the dominant API format because it maps naturally to JavaScript objects and is human-readable. Parsing is built into every modern programming language. **Strengths:** - Native browser support (`JSON.parse()` and `fetch()`) - Human-readable and debuggable - Lightweight — no schema required - Universal library support across all languages **Weaknesses:** - No native date/time type (ISO 8601 strings by convention) - No binary data support (requires Base64 encoding, 33% overhead) - No schema enforcement without external tools (JSON Schema) - Larger payload than binary formats for numeric-heavy data ## XML XML (Extensible Markup Language) predates JSON and remains essential in enterprise, government, and legacy systems. SOAP APIs, RSS feeds, SVG graphics, and many financial standards (FIX, SWIFT) use XML. **Strengths:** - Built-in schema validation (XSD) - Namespace support prevents naming conflicts across merged schemas - Mature tooling (XSLT, XPath, XQuery) - Required by many regulatory standards **Weaknesses:** - Verbose — opening/closing tags double the structural overhead - Complex parsing compared to JSON - Multiple valid representations of the same data (attributes vs elements) ## Protocol Buffers (Protobuf) Developed by Google, Protocol Buffers use a binary serialization format with a schema defined in `.proto` files. gRPC, Google's RPC framework, uses Protobuf as its default serialization format. **Strengths:** - 3-10x smaller payloads than JSON for the same data - 20-100x faster serialization/deserialization - Strict schema with backward/forward compatibility rules - Auto-generated client libraries from `.proto` files **Weaknesses:** - Not human-readable (binary format) - No native browser support (requires grpc-web proxy) - Schema compilation step adds build complexity - Debugging … ### Environment Variable Management: Security and Best Practices Environment variables separate configuration from code, keeping secrets out of version control. Mismanaging them leads to leaked API keys, broken deployments, and configuration drift between environments. - URL: https://peasydev.com/guides/environment-variable-management-guide/ - Category: Best Practice - Reading time: 2 min - Words: 361 Key takeaways: - Hardcoding configuration values — database URLs, API keys, feature flags — into source code creates three problems: secrets end up in version control (and Git history forever), the same code can't run in different environments without modification, and configuration changes require code deployments. - `.env` files store key-value pairs loaded at application startup: - Maintain separate configurations for each environment: - For small teams, 1Password or similar tools can store and sync `.env` files. - Using different variable names across environments (DB_HOST vs DATABASE_HOST) causes confusion. ## Why Environment Variables Exist Hardcoding configuration values — database URLs, API keys, feature flags — into source code creates three problems: secrets end up in version control (and Git history forever), the same code can't run in different environments without modification, and configuration changes require code deployments. Environment variables solve all three by storing configuration outside the codebase, injected at runtime. ## The .env File Pattern ### Structure `.env` files store key-value pairs loaded at application startup: ```bash DATABASE_URL=postgres://user:pass@host:5432/dbname DJANGO_SECRET_KEY=a-long-random-string-here STRIPE_API_KEY=sk_live_... DEBUG=false ALLOWED_HOSTS=example.com,www.example.com ``` ### Critical Rule: Never Commit .env Files Add `.env` and `.env.prod` to `.gitignore` immediately when starting a project. If a secret is committed even once, it exists in Git history forever — even after deleting the file. Leaked secrets should be rotated immediately, not just removed from the repository. ### .env.example Maintain a `.env.example` file (committed to Git) that lists all required variables with placeholder values. This documents what configuration a new developer needs without exposing actual secrets: ```bash DATABASE_URL=postgres://user:password@localhost:5432/myapp DJANGO_SECRET_KEY=change-me-to-a-random-string STRIPE_API_KEY=sk_test_... ``` ## Environment Separation ### Per-Environment Configuration Maintain separate configurations for each environment: | Variable | Development | Staging | Production | |----------|------------|---------|------------| | DEBUG | true | false | false | | DATABASE_URL | localhost | staging-rds | production-rds | | LOG_LEVEL | DEBUG | INFO | WARNING | | API keys | Test keys | Test keys | Live keys | Never use production secrets in development. Most third-party services provide separate test/sandbox keys for this reason. ## Secret Management at Scale ### Password Managers For small teams, 1Password or similar tools can store and sync `.env` files. A `sync-secrets` command pulls the latest values from the password manager and writes them to the local `.env` file. ### Cloud Secret Managers For larger deployments, use AWS Secrets Manager, Google Secret Manager, … ### Regex Pattern Generation and Testing Guide Regular expressions are powerful but notoriously hard to write correctly. This guide covers common patterns, testing strategies, and tools that help you build reliable regex. - URL: https://peasydev.com/guides/regex-pattern-generation-testing/ - Category: Troubleshooting - Reading time: 2 min - Words: 302 Key takeaways: - `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` - Nested quantifiers like `(a+)+` can cause exponential time complexity on certain inputs. - regex101.com**: Interactive testing with explanation of each token - ## Essential Regex Syntax | Pattern | Matches | Example | |---------|---------|--------| | `. - Avoid patterns where a failing match must backtrack through exponentially many paths. ## Essential Regex Syntax | Pattern | Matches | Example | |---------|---------|--------| | `.` | Any character (except newline) | `a.c` → abc, aXc | | `\d` | Any digit [0-9] | `\d{3}` → 123 | | `\w` | Word character [a-zA-Z0-9_] | `\w+` → hello_world | | `\s` | Whitespace | `\s+` → spaces, tabs | | `^` / `$` | Start / end of string | `^Hello$` → exact match | | `*` / `+` / `?` | 0+, 1+, 0 or 1 | `colou?r` → color, colour | | `{n,m}` | Between n and m times | `\d{2,4}` → 12, 1234 | | `(...)` | Capture group | `(\d{4})-(\d{2})` → groups | | `(?:...)` | Non-capturing group | Group without capture overhead | | `[abc]` | Character class | `[aeiou]` → any vowel | | `[^abc]` | Negated class | `[^0-9]` → non-digit | ## Common Patterns ### Email (Basic) `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` This catches 99% of valid emails. Full RFC 5322 validation requires a much more complex pattern. ### URL `^https?://[\w.-]+(?:\.[\w]{2,})(?:/[^\s]*)?$` ### IPv4 Address `^(?:\d{1,3}\.){3}\d{1,3}$` Note: This matches syntax but not value ranges. 999.999.999.999 passes but is not a valid IP. ## Testing Strategy 1. **Positive tests**: Strings that should match 2. **Negative tests**: Strings that should not match 3. **Edge cases**: Empty strings, very long strings, unicode, special characters 4. **Performance**: Test with long input strings to catch catastrophic backtracking ## Catastrophic Backtracking Nested quantifiers like `(a+)+` can cause exponential time complexity on certain inputs. Avoid patterns where a failing match must backtrack through exponentially many paths. Use possessive quantifiers (`a++`) or atomic groups when available. ## Tools - **regex101.com**: Interactive testing with explanation of each token - **Regex visualizers**: Show the state machine to spot backtracking risks - **IDE regex search**: Test patterns against real files … ### Structured Data and Schema.org: A Practical Guide Structured data helps search engines understand your content and can generate rich results like star ratings, FAQs, and product cards. Learn how to implement Schema.org markup effectively with JSON-LD. - URL: https://peasydev.com/guides/structured-data-schema-org/ - Category: How-To - Reading time: 1 min - Words: 225 Key takeaways: - Structured data uses a standardized vocabulary (Schema.org) to describe your content to search engines. - Google recommends JSON-LD (JavaScript Object Notation for Linked Data) over microdata or RDFa. - Mark up visible content only — don't include hidden data. - ## Best Practices - Mark up visible content only — don't include hidden data. ## What Is Structured Data? Structured data uses a standardized vocabulary (Schema.org) to describe your content to search engines. It enables rich results — enhanced search listings with images, ratings, prices, and other visual elements. ## JSON-LD: The Recommended Format Google recommends JSON-LD (JavaScript Object Notation for Linked Data) over microdata or RDFa. JSON-LD sits in a `<script>` tag and doesn't mix with your HTML markup. ## Common Schema Types | Schema Type | Rich Result | Best For | |------------|-------------|----------| | Article | Article byline, date | Blog posts, news | | FAQPage | Expandable Q&A | FAQ sections | | HowTo | Step-by-step | Tutorials | | Product | Price, availability, reviews | E-commerce | | WebApplication | App info | Online tools | | BreadcrumbList | Breadcrumb trail | Navigation | ## Implementation Steps 1. Identify the primary content type of each page. 2. Add the appropriate JSON-LD script to the `<head>` or `<body>`. 3. Include all required properties for the schema type. 4. Test with Google's Rich Results Test tool. 5. Monitor in Google Search Console under Enhancements. ## Best Practices - Mark up visible content only — don't include hidden data. - Use the most specific schema type available. - Include BreadcrumbList on every page. - Test after every change. - Don't mark up content that isn't on the page. ### How to Format and Validate JSON Data Malformed JSON causes silent failures in APIs and configuration files. Learn how to format, validate, and debug JSON documents to prevent integration errors and improve readability. - URL: https://peasydev.com/guides/format-validate-json/ - Category: How-To - Reading time: 1 min - Words: 212 Key takeaways: - A single misplaced comma or missing quote can break an entire JSON document. - JSON does not allow trailing commas after the last item in an array or object. - Use consistent indentation (2 or 4 spaces) for readability. - For structured validation, use JSON Schema to define expected types, required fields, value constraints, and nested object structures. - ## Formatting Best Practices ### Indentation Use consistent indentation (2 or 4 spaces) for readability. ## Why JSON Validation Matters A single misplaced comma or missing quote can break an entire JSON document. Unlike XML, JSON has no schema validation by default, so structural errors are only caught at parse time. ## Common JSON Errors ### Trailing Commas JSON does not allow trailing commas after the last item in an array or object. This is the most common syntax error, especially when editing JSON by hand. ### Single Quotes JSON requires double quotes for strings. Single quotes are valid in JavaScript but not in JSON. ### Unquoted Keys Object keys must be double-quoted strings. Unquoted keys work in JavaScript objects but not in JSON. ### Comments Standard JSON does not support comments. If you need comments, consider JSONC (JSON with Comments, used by VS Code) or JSON5. ## Formatting Best Practices ### Indentation Use consistent indentation (2 or 4 spaces) for readability. Tabs work but spaces are more universally displayed consistently. ### Key Ordering Alphabetically ordered keys make it easier to find values in large documents and produce more predictable diff outputs in version control. ## JSON Schema For structured validation, use JSON Schema to define expected types, required fields, value constraints, and nested object structures. Many editors provide autocomplete and validation when a schema is available. ### CSV vs JSON vs XML: Data Exchange Formats Compared Data exchange formats serve different needs. CSV excels at tabular data, JSON dominates web APIs, and XML powers enterprise integrations. This comparison helps you choose the right format for data interchange. - URL: https://peasydev.com/guides/csv-vs-json-vs-xml/ - Category: Comparison - Reading time: 1 min - Words: 219 Key takeaways: - Each format represents a different philosophy about data structure, readability, and tooling. - CSV (Comma-Separated Values) represents flat, tabular data. - JSON supports nested objects, arrays, strings, numbers, booleans, and null. - XML provides rich metadata through attributes and namespaces. ## Three Approaches to Data Each format represents a different philosophy about data structure, readability, and tooling. ## CSV: Simple Tabular Data CSV (Comma-Separated Values) represents flat, tabular data. It's the simplest format: rows of values separated by commas. **Strengths:** Universal spreadsheet support, tiny file size, human-readable. **Weaknesses:** No standard for escaping, no data types, no hierarchical data. ## JSON: Hierarchical Data JSON supports nested objects, arrays, strings, numbers, booleans, and null. It's the default data format for web APIs and modern applications. **Strengths:** Hierarchical data, type support, universal API format. **Weaknesses:** No comments, verbose for large datasets, no schema by default. ## XML: Enterprise Data XML provides rich metadata through attributes and namespaces. It supports schemas (XSD), transformations (XSLT), and querying (XPath). **Strengths:** Schemas, namespaces, enterprise tooling, self-describing. **Weaknesses:** Verbose, complex, declining popularity. ## Decision Matrix | Factor | CSV | JSON | XML | |--------|-----|------|-----| | Tabular data | Excellent | Awkward | Verbose | | Nested data | No | Excellent | Excellent | | File size | Smallest | Medium | Largest | | Schema validation | No | JSON Schema | XSD (mature) | | Web API standard | No | Yes | Legacy | | Spreadsheet import | Excellent | Possible | Possible | | Comments | No | No | Yes | ### Regular Expressions: A Practical Guide for Text Processing Regular expressions are powerful patterns for searching, matching, and transforming text. This guide covers the most useful regex patterns with real-world examples for common text processing tasks. - URL: https://peasydev.com/guides/regex-practical-guide/ - Category: How-To - Reading time: 1 min - Words: 167 Key takeaways: - Regular expressions let you describe complex text patterns in a concise syntax. - `\w` matches word characters (letters, digits, underscore) - A practical (not RFC-compliant) email pattern: - Greedy matching**: `.*` matches as much as possible. Use `.*?` for non-greedy. - ## Essential Patterns ### Character Classes - `\d` matches any digit (0-9) - `\w` matches word characters (letters, digits, underscore) - `\s` matches whitespace (space, tab, newline) - `. ## Why Learn Regex? Regular expressions let you describe complex text patterns in a concise syntax. They're supported in virtually every programming language, text editor, and command-line tool. ## Essential Patterns ### Character Classes - `\d` matches any digit (0-9) - `\w` matches word characters (letters, digits, underscore) - `\s` matches whitespace (space, tab, newline) - `.` matches any character except newline ### Quantifiers - `*` matches zero or more - `+` matches one or more - `?` matches zero or one - `{3}` matches exactly three - `{2,5}` matches two to five ## Practical Examples ### Email Validation A practical (not RFC-compliant) email pattern: `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}` ### Phone Numbers Match various phone number formats: `\+?\d{1,3}[-.\s]?\(?(\d{1,4})\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}` ### URL Extraction Find URLs in text: `https?://[^\s<>"]+` ## Common Pitfalls - **Greedy matching**: `.*` matches as much as possible. Use `.*?` for non-greedy. - **Catastrophic backtracking**: Nested quantifiers like `(a+)+` can cause exponential processing time. - **Escaping special characters**: Characters like `.`, `*`, `(`, `)` need backslash escaping when used literally. ### How to Trim and Edit Audio Files in the Browser Browser-based audio editing lets you trim silence, cut sections, and adjust audio without installing software. Learn how to use the Web Audio API and client-side tools for common audio editing tasks. - URL: https://peasydev.com/guides/trim-edit-audio-browser/ - Category: How-To - Reading time: 1 min - Words: 223 Key takeaways: - Modern browsers include the Web Audio API, which provides powerful audio processing capabilities without server uploads. - Trimming removes unwanted audio from the beginning or end of a recording. - The waveform shows amplitude over time. - When exporting edited audio, match the source quality when possible. - This means your audio files never leave your device. ## Client-Side Audio Editing Modern browsers include the Web Audio API, which provides powerful audio processing capabilities without server uploads. This means your audio files never leave your device. ## Common Editing Tasks ### Trimming Trimming removes unwanted audio from the beginning or end of a recording. This is the most frequent editing task for podcasters, voice-over artists, and musicians. **Steps:** 1. Load the audio file into the waveform display. 2. Select the region you want to keep. 3. Delete everything outside the selection. 4. Export the trimmed audio. ### Splitting Split a long recording into multiple files. Useful for breaking a lecture into chapters, separating songs from a live recording, or creating clips from interviews. ### Silence Detection Automatic silence detection identifies pauses in speech or music. You can use this to remove long pauses, split at silence points, or generate timestamps for chapters. ## Waveform Visualization The waveform shows amplitude over time. Louder sections appear taller, silence appears flat. Learning to read waveforms helps you quickly identify: - Where speech starts and ends - Clipping (flat-topped peaks indicate distortion) - Background noise (visible as a thin baseline above zero) ## Export Settings When exporting edited audio, match the source quality when possible. For web distribution, MP3 at 192 kbps or AAC at 128 kbps provides good quality at reasonable file sizes. ### Unit Conversion Best Practices for Developers Incorrect unit conversions have caused spacecraft crashes and medical errors. This guide covers best practices for implementing unit conversions in software, including precision handling and common pitfalls. - URL: https://peasydev.com/guides/unit-conversion-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 217 Key takeaways: - NASA's Mars Climate Orbiter was lost in 1999 because one team used metric units while another used imperial. - Store all measurements in SI base units internally and convert for display only. - Temperature conversions are not simple multiplication: - Define conversion factors as constants, not inline numbers. ## Unit Conversion Failures NASA's Mars Climate Orbiter was lost in 1999 because one team used metric units while another used imperial. The $125 million spacecraft burned up in Mars's atmosphere due to a simple unit mismatch. ## Fundamental Principles ### Use SI Internally Store all measurements in SI base units internally and convert for display only. This prevents conversion errors in calculations and simplifies testing. ### Floating Point Precision Floating point numbers cannot represent all decimal values exactly. 0.1 + 0.2 = 0.30000000000000004 in IEEE 754. For financial and scientific calculations, use decimal types or integer arithmetic. ## Common Conversion Categories ### Temperature Temperature conversions are not simple multiplication: - Celsius to Fahrenheit: F = C x 9/5 + 32 - Celsius to Kelvin: K = C + 273.15 ### Length - 1 inch = 25.4 mm (exact) - 1 mile = 1.609344 km (exact) - 1 nautical mile = 1.852 km (exact) ### Data Storage Be clear about SI vs binary prefixes: - 1 KB (kilobyte) = 1,000 bytes (SI) - 1 KiB (kibibyte) = 1,024 bytes (binary) ## Implementation Tips - Define conversion factors as constants, not inline numbers. - Include units in variable names: `distance_meters`, not just `distance`. - Write tests that verify round-trip conversions. - Document which unit system your API uses. ### QR Code vs Barcode: When to Use Each QR codes and traditional barcodes serve different purposes. This comparison covers data capacity, scanning requirements, and optimal use cases to help you choose the right technology for your needs. - URL: https://peasydev.com/guides/qr-code-vs-barcode/ - Category: Comparison - Reading time: 1 min - Words: 240 ## Fundamental Differences Traditional barcodes store data in one dimension (varying line widths), while QR codes use two dimensions (a matrix of modules). This fundamental difference determines their capabilities. ## Data Capacity | Type | Max Characters | Data Types | |------|---------------|------------| | UPC-A | 12 digits | Numbers only | | EAN-13 | 13 digits | Numbers only | | Code 128 | ~80 characters | Alphanumeric | | QR Code | ~4,296 characters | Alphanumeric + binary | | Data Matrix | ~2,335 characters | Alphanumeric + binary | ## Scanning Requirements ### Barcodes Traditional barcodes require the scanner to be aligned with the barcode orientation. They're typically scanned with dedicated barcode scanners or positioned horizontally. ### QR Codes QR codes can be scanned from any angle and work with smartphone cameras. They include finder patterns (the three corner squares) that help the scanner locate and orient the code. ## Use Case Guide | Use Case | Best Choice | Why | |----------|------------|-----| | Retail products | Barcode (UPC/EAN) | Standard, compatible with POS | | Marketing materials | QR Code | URLs, rich content, phone-scannable | | Inventory tracking | Barcode (Code 128) | Fast scanning, established systems | | Event tickets | QR Code | Unique IDs, easy validation | | Payments | QR Code | URL/data payload, universal scanning | | Shipping labels | Barcode + QR | Barcode for sorting, QR for details | ### How to Create QR Codes for Wi-Fi Networks Wi-Fi QR codes let guests connect to your network instantly by scanning with their phone camera. This guide covers the Wi-Fi QR format, security considerations, and best placement practices. - URL: https://peasydev.com/guides/create-wifi-qr-codes/ - Category: How-To - Reading time: 1 min - Words: 211 Key takeaways: - Wi-Fi QR codes use a specific text format that phones recognize and auto-connect: - Create a separate guest network for QR code sharing. - Hotels: Room cards or welcome packets. - iOS**: Built-in Camera app (iOS 11+). - ## Placement Best Practices - Hotels: Room cards or welcome packets. ## Wi-Fi QR Code Format Wi-Fi QR codes use a specific text format that phones recognize and auto-connect: `WIFI:T:WPA;S:NetworkName;P:Password;;` ### Format Parameters - **T**: Authentication type (WPA, WEP, or nopass for open networks). - **S**: Network SSID (name). Use `\` to escape `;`, `,`, `"`, and `\`. - **P**: Password. Same escaping rules apply. - **H**: Hidden network (true/false). Optional. ## Security Considerations ### Guest Networks Create a separate guest network for QR code sharing. This isolates guest devices from your main network, protecting your devices and data. ### Password Rotation When you change your Wi-Fi password, the QR code becomes invalid. Print QR codes that are easy to replace, or use a redirect URL that you can update. ### Physical Security Anyone who can see (or photograph) the QR code gets network access. Place Wi-Fi QR codes where they're visible to authorized guests but not from outside your premises. ## Placement Best Practices - Hotels: Room cards or welcome packets. - Restaurants: Table tents or menus. - Offices: Meeting room displays. - Homes: Near the router or on the fridge. ## Device Compatibility - **iOS**: Built-in Camera app (iOS 11+). - **Android**: Built-in Camera app (Android 10+), or Google Lens. - **Older devices**: May need a third-party QR scanner app. ### How to Generate Color Palettes Programmatically Algorithmic color palette generation creates harmonious color schemes from a single base color. Learn the math behind complementary, analogous, and triadic palettes and how to implement them in code. - URL: https://peasydev.com/guides/generate-color-palettes/ - Category: How-To - Reading time: 1 min - Words: 227 Key takeaways: - Programmatic palette generation uses color theory rules applied to a base color. - Rotate the hue by 180 degrees to find the complement: - From a base color, generate a full shade scale by adjusting lightness: - For more consistent perceived lightness across hues, use OKLCH instead of HSL. ## Color Palette Algorithms Programmatic palette generation uses color theory rules applied to a base color. The HSL (Hue, Saturation, Lightness) color space is most intuitive for algorithmic manipulation. ## HSL-Based Generation ### Complementary Rotate the hue by 180 degrees to find the complement: - Base: hsl(210, 80%, 50%) (blue) - Complement: hsl(30, 80%, 50%) (orange) ### Analogous Select colors 30 degrees apart on the color wheel: - Base: hsl(210, 80%, 50%) - Analogous 1: hsl(180, 80%, 50%) - Analogous 2: hsl(240, 80%, 50%) ### Triadic Three colors 120 degrees apart: - Base: hsl(210, 80%, 50%) - Triadic 1: hsl(330, 80%, 50%) - Triadic 2: hsl(90, 80%, 50%) ## Generating Shades and Tints From a base color, generate a full shade scale by adjusting lightness: | Step | Lightness | Usage | |------|-----------|-------| | 50 | 95% | Subtle backgrounds | | 100 | 90% | Light backgrounds | | 200 | 80% | Borders | | 300 | 70% | Hover states | | 500 | 50% | Primary (base) | | 700 | 30% | Dark variant | | 900 | 10% | Very dark | ## OKLCH: Perceptually Uniform Palettes For more consistent perceived lightness across hues, use OKLCH instead of HSL. HSL's lightness is not perceptually uniform — yellow at 50% lightness appears much brighter than blue at 50% lightness. OKLCH corrects this. ### How to Add Logos and Branding to QR Codes Branded QR codes with logos increase scan rates and reinforce brand identity. Learn how to customize QR codes with logos, colors, and shapes while maintaining reliable scannability. - URL: https://peasydev.com/guides/add-logos-branding-qr-codes/ - Category: How-To - Reading time: 1 min - Words: 249 Key takeaways: - Studies show that branded QR codes receive up to 80% more scans than plain black-and-white codes. - Place your logo in the center of the QR code, overlapping the error correction data. - Dark modules on light backgrounds (maintain contrast). - After adding branding, test thoroughly: - These are critical for the scanner to locate and orient the code. ## Why Brand Your QR Codes? Studies show that branded QR codes receive up to 80% more scans than plain black-and-white codes. A recognizable logo gives users confidence that the QR code leads to a legitimate destination. ## Logo Placement Rules ### Center Overlay Place your logo in the center of the QR code, overlapping the error correction data. This is the safest approach because the center area is reconstructable from surrounding modules. **Requirements:** - Use Error Correction Level H (30%). - Logo should cover no more than 20-25% of the QR code area. - Add a white border around the logo for contrast. ### Corner Integration Do NOT place logos over the three finder patterns (corner squares). These are critical for the scanner to locate and orient the code. ## Color Customization ### Safe Color Choices - Dark modules on light backgrounds (maintain contrast). - Brand primary color for modules, white or light background. - Gradient effects are possible but reduce scan reliability at distance. ### Avoid - Light modules on dark backgrounds (inverted) — some scanners fail. - Low contrast combinations (yellow on white, light gray on white). - Neon or highly saturated colors that blend together on camera. ## Testing Protocol After adding branding, test thoroughly: 1. Scan from 3 different distances. 2. Test in bright and dim lighting. 3. Test with at least 3 different phones. 4. Print a test copy and scan the printed version. 5. Test the smallest size you plan to use. ### How to Convert Case and Clean Up Messy Text Messy text with inconsistent capitalization, extra whitespace, and mixed formatting is a common problem. This guide covers tools and techniques for cleaning, transforming, and standardizing text efficiently. - URL: https://peasydev.com/guides/convert-case-clean-text/ - Category: How-To - Reading time: 1 min - Words: 223 Key takeaways: - Text from various sources often arrives in inconsistent formats: ALL CAPS from legacy databases, mixed case from OCR scans, extra spaces from copy-pasting, or invisible Unicode characters from web scraping. - UPPERCASE**: All characters capitalized. Used for headings, acronyms. - Remove leading and trailing whitespace from each line. - Text copied from the web may contain zero-width spaces, soft hyphens, non-breaking spaces, and other invisible Unicode characters. ## Common Text Mess Scenarios Text from various sources often arrives in inconsistent formats: ALL CAPS from legacy databases, mixed case from OCR scans, extra spaces from copy-pasting, or invisible Unicode characters from web scraping. ## Case Transformations ### Common Cases - **UPPERCASE**: All characters capitalized. Used for headings, acronyms. - **lowercase**: All characters in lowercase. Used for URLs, identifiers. - **Title Case**: First letter of each word capitalized. Used for headlines. - **Sentence case**: First letter of first word capitalized. Used for body text. - **camelCase**: Words joined, each word capitalized except the first. Used in code. - **snake_case**: Words joined with underscores. Used in Python, SQL. - **kebab-case**: Words joined with hyphens. Used in URLs, CSS classes. ## Whitespace Cleanup ### Trimming Remove leading and trailing whitespace from each line. This is the most basic cleanup operation and prevents issues with string comparison. ### Normalizing Spaces Replace multiple consecutive spaces with a single space. This commonly happens when copying from PDFs or formatted documents. ### Line Ending Normalization Different operating systems use different line endings: `\n` (Unix/macOS), `\r\n` (Windows), `\r` (old macOS). Normalize to your target platform to prevent display issues. ## Invisible Characters Text copied from the web may contain zero-width spaces, soft hyphens, non-breaking spaces, and other invisible Unicode characters. These can cause string comparison failures and parsing errors. ### Matrix Operations: A Visual Guide for Developers Matrices are fundamental to graphics, machine learning, and data processing. This guide explains matrix addition, multiplication, transposition, and inversion with visual examples and practical applications. - URL: https://peasydev.com/guides/matrix-operations-visual-guide/ - Category: How-To - Reading time: 1 min - Words: 245 Key takeaways: - Matrices are everywhere in computing: CSS transforms use 4x4 matrices, machine learning models are essentially matrix operations, and 3D graphics rely on matrix multiplication for every frame. - A matrix is a rectangular grid of numbers arranged in rows and columns. - Add matrices of the same size by adding corresponding elements. - Every CSS `transform` (translate, rotate, scale, skew) is a matrix operation. - ## Why Matrices Matter Matrices are everywhere in computing: CSS transforms use 4x4 matrices, machine learning models are essentially matrix operations, and 3D graphics rely on matrix multiplication for every frame. ## Why Matrices Matter Matrices are everywhere in computing: CSS transforms use 4x4 matrices, machine learning models are essentially matrix operations, and 3D graphics rely on matrix multiplication for every frame. ## Matrix Basics A matrix is a rectangular grid of numbers arranged in rows and columns. A matrix with m rows and n columns is called an m x n matrix. ## Core Operations ### Addition and Subtraction Add matrices of the same size by adding corresponding elements. This is used in neural network gradient updates and image processing (blending). ### Scalar Multiplication Multiply every element by a single number. Used for scaling transformations and adjusting learning rates in ML. ### Matrix Multiplication The most important operation. For matrices A (m x n) and B (n x p), the result is an m x p matrix. The number of columns in A must equal the number of rows in B. Key property: matrix multiplication is NOT commutative. A x B is usually not equal to B x A. ### Transposition Flipping a matrix along its diagonal — rows become columns. An m x n matrix becomes n x m. Used in linear algebra, statistics, and ML. ## Practical Applications ### CSS Transforms Every CSS `transform` (translate, rotate, scale, skew) is a matrix operation. The browser multiplies a 4x4 transformation matrix by each point's coordinates. ### Machine Learning Neural networks are chains of matrix multiplications with nonlinear activation functions. Training involves computing matrix derivatives (gradients). ### Troubleshooting CSS Specificity Conflicts When CSS rules unexpectedly override each other, specificity is usually the culprit. This guide explains how specificity is calculated and provides strategies for managing it in growing codebases. - URL: https://peasydev.com/guides/troubleshooting-css-specificity/ - Category: Troubleshooting - Reading time: 1 min - Words: 227 Key takeaways: - When multiple CSS rules target the same element, the browser uses specificity to decide which rule wins. - Libraries like Bootstrap or Material UI use moderately specific selectors. - CSS Cascade Layers provide explicit control over which stylesheets take precedence. - ### The !important Escape Hatch `!important` overrides all specificity rules. - Multiple `!important` declarations compete by specificity again. ## How Specificity Works When multiple CSS rules target the same element, the browser uses specificity to decide which rule wins. Specificity is calculated as a tuple of four values. ## Specificity Hierarchy | Level | Selector | Specificity | |-------|----------|-------------| | 1 (highest) | Inline styles | (1,0,0,0) | | 2 | ID selectors | (0,1,0,0) | | 3 | Classes, attributes, pseudo-classes | (0,0,1,0) | | 4 (lowest) | Elements, pseudo-elements | (0,0,0,1) | ## Common Conflicts ### Third-Party CSS Overriding Your Styles Libraries like Bootstrap or Material UI use moderately specific selectors. When your styles don't apply, the library's specificity may be higher. **Solutions:** - Add a class to increase your selector's specificity. - Use `:where()` (zero specificity) for resets. - Use CSS Layers (`@layer`) to control cascade order. ### The !important Escape Hatch `!important` overrides all specificity rules. It should be used sparingly — only for utility classes (like `.hidden`) or overriding third-party styles when no other option exists. Multiple `!important` declarations compete by specificity again. ## Modern Solutions ### CSS Layers (@layer) CSS Cascade Layers provide explicit control over which stylesheets take precedence. Rules in later-declared layers override earlier layers regardless of specificity. ### :where() and :is() `:where()` contributes zero specificity, making it ideal for default styles that should be easy to override. `:is()` takes the specificity of its most specific argument. ### Troubleshooting QR Code Scanning Problems QR codes that fail to scan frustrate users and waste printing costs. This guide helps you diagnose and fix the most common reasons QR codes don't scan reliably on smartphones and dedicated scanners. - URL: https://peasydev.com/guides/troubleshooting-qr-scanning/ - Category: Troubleshooting - Reading time: 1 min - Words: 297 Key takeaways: - Most scanning failures come down to three issues: the code is too small, the contrast is too low, or the data is too long. - A QR code printed at 1 cm on a billboard won't scan from the road. - QR scanners need clear contrast between modules and background. - The QR code scans successfully but leads nowhere. - The code must be large enough that individual modules are distinguishable by the camera at the intended scanning distance. ## Why QR Codes Fail to Scan Most scanning failures come down to three issues: the code is too small, the contrast is too low, or the data is too long. ## Size Issues ### Too Small for Distance A QR code printed at 1 cm on a billboard won't scan from the road. The code must be large enough that individual modules are distinguishable by the camera at the intended scanning distance. **Fix:** Width = scanning distance / 10 (minimum). ### Too Dense Long URLs create dense QR codes with tiny modules. When printed small, individual modules blur together. **Fix:** Use a URL shortener or redirect service to reduce data length. ## Contrast Issues ### Insufficient Contrast QR scanners need clear contrast between modules and background. Low contrast combinations, reflective surfaces, and transparent overlays all reduce scannability. **Fix:** Test with black on white first. Then apply colors while maintaining at least 40% contrast. ### Print Quality Low-resolution printing, ink bleeding, and paper texture can degrade module edges. Laser printing produces sharper results than inkjet for QR codes. ## Data Issues ### Invalid Data The QR code scans successfully but leads nowhere. Common with mistyped URLs, expired redirect links, or invalid vCard format. **Fix:** Verify the encoded data is correct and the destination is accessible. ### Encoding Errors Special characters in URLs or text may need proper encoding. URLs with spaces, accented characters, or non-ASCII text should be percent-encoded. ## Diagnostic Checklist 1. Can you scan a known-good QR code? (eliminates device issues) 2. Does the code scan from up close? (size issue if not) 3. Does a different QR scanner app work? (app compatibility) 4. Does the code work on screen but not printed? (print quality) 5. Is the quiet zone (white border) intact? (cropping issue) ### Troubleshooting JWT Token Issues JSON Web Tokens are widely used for authentication but can be frustrating to debug. This guide covers common JWT problems including expiration errors, signature mismatches, and payload decoding issues. - URL: https://peasydev.com/guides/troubleshooting-jwt-tokens/ - Category: Troubleshooting - Reading time: 1 min - Words: 263 Key takeaways: - A JWT consists of three Base64URL-encoded parts separated by dots: header, payload, and signature. - Symptom: `TokenExpiredError` or `jwt expired` error. - This is also a known security vulnerability — never trust the `alg` claim from untrusted tokens. - Never let the JWT itself dictate which algorithm to use. ## JWT Structure A JWT consists of three Base64URL-encoded parts separated by dots: header, payload, and signature. Understanding this structure is key to debugging. ## Common Issues ### Token Expired **Symptom:** `TokenExpiredError` or `jwt expired` error. **Cause:** The `exp` (expiration) claim in the payload is in the past. This can happen due to clock skew between servers, or because the token's lifetime is too short. **Fix:** Check the `exp` claim by decoding the payload (without verification). Compare with the current time. Add a clock tolerance (leeway) of 30-60 seconds to account for clock differences. ### Invalid Signature **Symptom:** `JsonWebTokenError: invalid signature`. **Cause:** The signing key used to verify doesn't match the key used to create the token. This happens when keys are rotated, when using the wrong key for the algorithm, or when the token was tampered with. **Fix:** Ensure you're using the correct signing key. For RS256, verify you're using the public key (not private) for verification. Check the `kid` (key ID) claim in the header. ### Algorithm Confusion **Symptom:** Signature verification fails despite correct keys. **Cause:** The `alg` header says RS256 but verification uses HS256, or vice versa. This is also a known security vulnerability — never trust the `alg` claim from untrusted tokens. **Fix:** Always specify the expected algorithm explicitly in your verification code. Never let the JWT itself dictate which algorithm to use. ## Debugging Steps 1. Decode the header and payload (Base64URL) without verification. 2. Check `exp`, `iat`, and `nbf` timestamps. 3. Verify the `iss` (issuer) and `aud` (audience) claims. 4. Confirm the algorithm matches your verification setup. ### Two-Factor Authentication Methods: TOTP, WebAuthn, and SMS Two-factor authentication (2FA) adds a critical layer of security beyond passwords. This guide compares TOTP apps, hardware security keys, SMS codes, and passkeys to help you choose the strongest protection. - URL: https://peasydev.com/guides/two-factor-authentication-methods/ - Category: Comparison - Reading time: 1 min - Words: 235 Key takeaways: - Passwords alone are insufficient. - A one-time code sent via text message. - Use passkeys or hardware keys for critical accounts (email, banking, cloud). ## Why 2FA Matters Passwords alone are insufficient. Even strong, unique passwords can be compromised through phishing, server breaches, or malware. 2FA ensures that a stolen password alone isn't enough to access your account. ## Authentication Methods ### SMS Codes A one-time code sent via text message. While better than no 2FA, SMS is the weakest method due to SIM-swapping attacks and SS7 vulnerabilities. **Security:** Low | **Convenience:** High ### TOTP (Authenticator Apps) Time-based One-Time Passwords generated by apps like Google Authenticator, Authy, or 1Password. Codes rotate every 30 seconds and work offline. **Security:** Good | **Convenience:** Medium ### Hardware Security Keys (WebAuthn/FIDO2) Physical devices (YubiKey, Google Titan) that use public-key cryptography. They're phishing-resistant because the key verifies the website's identity. **Security:** Excellent | **Convenience:** Medium ### Passkeys The newest standard, combining the security of hardware keys with the convenience of biometrics. Passkeys are stored in your device's secure enclave and synced across your ecosystem. **Security:** Excellent | **Convenience:** High ## Comparison | Method | Phishing Resistant | Offline | Recovery | |--------|-------------------|---------|----------| | SMS | No | No | Easy | | TOTP | No | Yes | Medium | | Hardware Key | Yes | Yes | Difficult | | Passkey | Yes | Yes | Easy (cloud sync) | ## Recommendation Use passkeys or hardware keys for critical accounts (email, banking, cloud). Use TOTP for everything else. Avoid SMS-only 2FA when possible. ### Dynamic QR Codes vs Static QR Codes Static QR codes encode data permanently, while dynamic QR codes use redirect URLs that can be updated after printing. Understanding the trade-offs helps you choose the right type for marketing, inventory, and operational uses. - URL: https://peasydev.com/guides/dynamic-vs-static-qr-codes/ - Category: Comparison - Reading time: 1 min - Words: 235 Key takeaways: - Static codes encode data directly in the QR pattern. - Dynamic codes encode a short redirect URL. - If your dynamic QR service goes offline or you stop paying, all your printed codes stop working. ## Static QR Codes Static codes encode data directly in the QR pattern. The data cannot be changed after the code is created. **Characteristics:** - Data is embedded in the code itself. - No internet connection needed to read the data. - No tracking or analytics possible. - Free to generate and use indefinitely. **Best for:** Wi-Fi passwords, contact cards, fixed URLs, product serial numbers. ## Dynamic QR Codes Dynamic codes encode a short redirect URL. The destination can be changed without reprinting the physical code. **Characteristics:** - Redirect URL can be updated anytime. - Scan analytics (when, where, how many). - Smaller QR code (shorter URL = fewer modules). - Requires a redirect service (ongoing cost). **Best for:** Marketing campaigns, menus, event info, seasonal promotions. ## Comparison | Feature | Static | Dynamic | |---------|--------|---------| | Data change after print | No | Yes | | Scan analytics | No | Yes | | Code size | Larger (more data) | Smaller (short URL) | | Internet required to read | No | Yes (for redirect) | | Ongoing cost | Free | Service fee | | Works forever | Yes | Depends on service | ## When Dynamic Goes Wrong If your dynamic QR service goes offline or you stop paying, all your printed codes stop working. For long-lived applications (permanent signage, product packaging), consider whether the updateability is worth the dependency risk. ### How to Find and Replace Text Using Regular Expressions Regular expressions enable powerful pattern-based find and replace operations. Learn practical regex patterns for common text transformation tasks. - URL: https://peasydev.com/guides/how-to-find-replace-regex/ - Category: How-To - Reading time: 1 min - Words: 170 Key takeaways: - Standard find-and-replace handles exact text matches. - Capture groups `()` let you rearrange matched text. - Lookahead `(?=...)` matches a position before a pattern without including it. - Always test regex patterns on a small sample before applying to large text. - ## Essential Patterns | Pattern | Matches | Example | |---------|---------|--------| | `\d{3}-\d{4}` | Phone numbers | 555-1234 | | `[\w. ## Beyond Simple Find and Replace Standard find-and-replace handles exact text matches. Regular expressions match patterns — phone numbers, email addresses, dates, URLs — letting you transform text at scale with surgical precision. ## Essential Patterns | Pattern | Matches | Example | |---------|---------|--------| | `\d{3}-\d{4}` | Phone numbers | 555-1234 | | `[\w.]+@[\w.]+` | Email addresses | user@example.com | | `\d{1,2}/\d{1,2}/\d{4}` | Dates (M/D/YYYY) | 3/15/2025 | | `https?://\S+` | URLs | https://example.com/page | ## Capture Groups for Transformation Capture groups `()` let you rearrange matched text. For example, converting dates from MM/DD/YYYY to YYYY-MM-DD: pattern `(\d{2})/(\d{2})/(\d{4})` with replacement `$3-$1-$2`. ## Lookahead and Lookbehind Lookahead `(?=...)` matches a position before a pattern without including it. Lookbehind `(?<=...)` matches a position after a pattern. These are powerful for inserting or removing text at specific locations. ## Testing Regex Safely Always test regex patterns on a small sample before applying to large text. Use tools that highlight matches in real-time so you can verify the pattern captures exactly what you intend. ### QR Code Size and Resolution Guide Determine the optimal size and resolution for QR codes based on scanning distance, print medium, and content complexity. - URL: https://peasydev.com/guides/qr-code-size-resolution-guide/ - Category: Best Practice - Reading time: 1 min - Words: 276 ## QR Code Size and Resolution A QR code that's too small won't scan reliably; one that's too large wastes space. The optimal size depends on scanning distance, content length, and the print or display medium. ### Minimum Size Formula The general rule is that a QR code should be at least 1/10th of the expected scanning distance. For a poster viewed from 1 meter, the QR code should be at least 10cm. For a business card scanned from 15cm, 1.5cm minimum. This assumes good lighting and a modern smartphone camera. ### Module Size Matters Each small square in a QR code is called a module. For reliable scanning, each module should be at least 0.75mm in print (about 3 pixels at 100 DPI). As the data content increases, the QR code contains more modules in the same physical space, making each module smaller. A QR code encoding a 20-character URL might have 25×25 modules, while a 300-character text block requires 57×57 modules. ### Print vs Screen For print, generate at minimum 300 DPI. Newspaper and offset printing can introduce dot gain that fills in small modules — increase the minimum module size to 1mm for these media. For screen display, ensure each module is at least 4×4 CSS pixels. On retina displays, the physical pixel count is doubled, so the visual appearance is fine even at 2×2 CSS pixels. ### Testing Protocol Always test printed QR codes with at least three different smartphone models under realistic lighting conditions. Test at both the expected and maximum scanning distances. If more than 10% of test scans fail, increase the physical size or reduce the encoded data length. ### How to Debug JWT Tokens Step by Step JWT tokens contain encoded claims that can be decoded and inspected. Learn how to decode, verify, and troubleshoot JWT authentication issues. - URL: https://peasydev.com/guides/how-to-debug-jwt-tokens/ - Category: How-To - Reading time: 1 min - Words: 197 Key takeaways: - A JWT consists of three Base64URL-encoded parts separated by dots: header, payload, and signature. - JWT payloads are encoded, not encrypted. - Token expired**: The `exp` claim is in the past. Check server-client time sync. - Never paste production JWT tokens into online decoders — they contain sensitive user data. - JWT `exp` is a Unix timestamp in seconds. ## JWT Structure A JWT consists of three Base64URL-encoded parts separated by dots: header, payload, and signature. The header specifies the algorithm. The payload contains claims (user data, expiration, permissions). The signature verifies integrity. ## Decoding Without Verification JWT payloads are encoded, not encrypted. You can decode the header and payload without the secret key. This is useful for debugging — inspect the claims, check expiration times, and verify the token structure. ## Common JWT Problems - **Token expired**: The `exp` claim is in the past. Check server-client time sync. - **Invalid signature**: The token was modified or signed with a different key. - **Missing claims**: Required fields like `sub`, `iss`, or `aud` are absent. - **Wrong algorithm**: The server expects RS256 but the token uses HS256. ## Security Considerations Never paste production JWT tokens into online decoders — they contain sensitive user data. Use client-side tools that decode tokens in the browser without sending data to any server. ## Expiration Management JWT `exp` is a Unix timestamp in seconds. A common mistake is using milliseconds, which makes the token expire thousands of years in the future. Always verify the timestamp format matches your JWT library's expectations. ### How to Format and Validate JSON Data Minified JSON is unreadable and errors are hard to find. Learn how to pretty-print, validate, and transform JSON for debugging and development. - URL: https://peasydev.com/guides/how-to-format-validate-json/ - Category: How-To - Reading time: 1 min - Words: 175 Key takeaways: - API responses and configuration files often arrive as single-line minified JSON. - JSON syntax is strict — a single missing comma or extra bracket breaks the entire document. - Trailing commas**: `{"a": 1,}` — not allowed in JSON (allowed in JS). - JSON5 and JSONC are supersets that allow comments, trailing commas, and single quotes. - The reverse of pretty-printing — removing whitespace to minimize file size. ## Why Format JSON? API responses and configuration files often arrive as single-line minified JSON. Pretty-printing adds indentation and line breaks, making the structure visible and errors easy to spot. ## Validation JSON syntax is strict — a single missing comma or extra bracket breaks the entire document. Validators highlight the exact line and character where parsing fails, saving debugging time. ## Common JSON Errors - **Trailing commas**: `{"a": 1,}` — not allowed in JSON (allowed in JS). - **Single quotes**: `{'key': 'value'}` — JSON requires double quotes. - **Unquoted keys**: `{key: "value"}` — keys must be quoted strings. - **Comments**: `// comment` — JSON doesn't support comments. ## JSON vs JSON5 vs JSONC JSON5 and JSONC are supersets that allow comments, trailing commas, and single quotes. They're used in configuration files (tsconfig.json, VS Code settings) but aren't valid JSON for APIs. ## Minification The reverse of pretty-printing — removing whitespace to minimize file size. Minified JSON is 30-50% smaller than pretty-printed, making it ideal for API responses and storage where human readability isn't needed. ### How to Create vCard QR Codes Generate QR codes that instantly add contact information to smartphones, with proper vCard formatting and testing. - URL: https://peasydev.com/guides/how-to-create-vcard-qr-codes/ - Category: How-To - Reading time: 2 min - Words: 301 Key takeaways: - vCard QR codes let recipients add your contact information to their phone with a single scan — no typing required. - ### Encoding Best Practices Use UTF-8 encoding for international characters in names and addresses. - Line endings must use CRLF (\r\n) per the vCard specification. - Always include the BEGIN:VCARD and END:VCARD delimiters. ## Creating vCard QR Codes vCard QR codes let recipients add your contact information to their phone with a single scan — no typing required. They're ideal for business cards, conference badges, and email signatures. ### vCard Format A vCard QR code encodes a text block in vCard format (VCF). The minimum viable vCard includes version, full name, and at least one contact method. Version 3.0 is the most widely supported format across iOS and Android devices. ### Required and Optional Fields At minimum, include FN (formatted name), TEL (phone), and EMAIL. Optional but valuable fields include ORG (company), TITLE (job title), URL (website), and ADR (address). Each additional field increases the QR code complexity, requiring more modules and thus a larger physical size. ### Encoding Best Practices Use UTF-8 encoding for international characters in names and addresses. Keep the total vCard size under 300 characters for reliable scanning — this means prioritizing the most important contact fields. Phone numbers should include the country code in E.164 format (+1 for US, +44 for UK). Line endings must use CRLF (\r\n) per the vCard specification. ### Testing Across Platforms iOS and Android handle vCard QR codes differently. iOS presents a contact card preview with an "Add to Contacts" button. Android may open the Contacts app directly or show a dialog depending on the manufacturer. Test with both platforms and verify that all fields are parsed correctly — special characters in names and non-standard field ordering cause parsing failures on some devices. ### Common Mistakes Avoid including a photo in the vCard — it dramatically increases the data size, making the QR code too dense to scan reliably. Don't use vCard 4.0 features if you need broad compatibility — many Android devices still only support 3.0. Always include the BEGIN:VCARD and END:VCARD … ### UUID vs CUID vs NanoID: Choosing an ID Generator Compare UUID, CUID, NanoID and other ID generation strategies for databases, APIs, and distributed systems. - URL: https://peasydev.com/guides/uuid-vs-cuid-vs-nanoid/ - Category: Comparison - Reading time: 1 min - Words: 234 ## Comparing ID Generation Strategies Choosing the right ID format affects database performance, URL readability, and system scalability. Each approach makes different trade-offs between uniqueness guarantees, sortability, and string length. ### UUID v4 UUID v4 generates 128-bit random identifiers formatted as 36-character strings (e.g., `550e8400-e29b-41d4-a716-446655440000`). They're universally supported and virtually guaranteed unique, but they're long, not sortable by creation time, and can cause B-tree index fragmentation in databases due to random ordering. ### UUID v7 and ULID UUID v7 (RFC 9562) and ULID both embed a timestamp prefix, making them naturally sortable by creation time. This dramatically improves database insert performance since new records always append to the end of B-tree indexes. ULID uses Crockford Base32 encoding, producing 26-character strings that are URL-safe and case-insensitive. ### NanoID and CUID2 NanoID generates compact 21-character IDs using a customizable alphabet. CUID2 produces collision-resistant IDs optimized for horizontal scaling. Both are shorter than UUIDs, making them better for URLs and client-side storage. NanoID is particularly popular in frontend applications where bundle size matters — the library is only 130 bytes. ### Selection Guide Use UUID v7 or ULID for database primary keys where sort order matters. Choose NanoID for URL slugs and client-facing identifiers where brevity is valued. Stick with UUID v4 when you need maximum interoperability with existing systems. Avoid sequential integers for public-facing IDs, as they leak information about your system's scale and growth rate. ### How to Generate Test Data for Development Create realistic fake data for testing databases, APIs, and user interfaces without exposing real user information. - URL: https://peasydev.com/guides/how-to-generate-test-data/ - Category: How-To - Reading time: 1 min - Words: 250 Key takeaways: - Realistic test data is essential for meaningful development and QA work. - ## Generating Test Data Realistic test data is essential for meaningful development and QA work. - ### Privacy Considerations Never use real data as a template for generating fake data — patterns in the fake data could still reveal information about real users. ## Generating Test Data Realistic test data is essential for meaningful development and QA work. Using production data introduces privacy risks and compliance violations, while obviously fake data (all users named "Test User") fails to reveal edge cases. ### What Makes Good Test Data Effective test data mirrors production patterns without containing real information. Names should include various lengths, special characters (O'Brien, García), and Unicode scripts. Email addresses should use reserved domains (example.com, test.example). Phone numbers should use formats from multiple countries. Dates should span realistic ranges and include edge cases like leap years and timezone boundaries. ### Data Generation Strategies For small datasets, online generators that produce CSV, JSON, or SQL output work well. Specify the exact schema you need — column names, data types, value ranges, and null percentages. For larger datasets, use libraries like Faker (Python/JS) that generate millions of records programmatically with consistent relationships between tables. ### Maintaining Referential Integrity When generating data for relational databases, create parent records before children. Ensure foreign key relationships are valid, and generate realistic distributions — not every user should have the same number of orders. Include orphaned records and edge cases that your application should handle gracefully. ### Privacy Considerations Never use real data as a template for generating fake data — patterns in the fake data could still reveal information about real users. Use statistically representative distributions rather than anonymized copies of production data. Document your test data generation process so it can be reproduced consistently across environments. ### Barcode Types Compared: 1D vs 2D Compare 1D barcodes (UPC, EAN, Code 128) with 2D codes (QR, Data Matrix, PDF417) for different use cases. - URL: https://peasydev.com/guides/barcode-types-1d-vs-2d-compared/ - Category: Comparison - Reading time: 2 min - Words: 308 ## 1D vs 2D Barcode Comparison Barcodes come in two fundamental types: one-dimensional (linear) codes that encode data in varying bar widths, and two-dimensional codes that use patterns of squares, dots, or hexagons to encode data in both directions. ### 1D Barcode Types UPC-A (12 digits) and EAN-13 (13 digits) are the retail standards — every product on a store shelf uses one of these. Code 128 encodes the full ASCII character set and is used for shipping labels, inventory, and logistics. Code 39 is simpler but less dense, common in military and automotive applications. Interleaved 2 of 5 (ITF-14) is used for outer cartons and shipping containers. ### 2D Barcode Types QR codes are the most recognized, supporting up to 4,296 alphanumeric characters with built-in error correction. Data Matrix codes are smaller than QR for the same data amount, making them ideal for small electronic components and medical devices. PDF417 is a stacked linear format used on driver's licenses and boarding passes — it doesn't require a camera, just a linear scanner. ### Choosing the Right Type For retail products, UPC/EAN is mandatory — no other format is accepted by point-of-sale systems. For logistics and warehousing, Code 128 or GS1-128 (which adds application identifiers for batch numbers, expiry dates, etc.) is standard. For consumer-facing applications where users scan with smartphones, QR codes are the clear choice due to universal camera app support. For industrial marking on small parts, Data Matrix is preferred. ### Technical Considerations 1D barcodes require a clear horizontal scan line — they can't be read at extreme angles. 2D codes can be read from any orientation. 1D barcodes are faster to generate and print but encode far less data. 2D codes support error correction, making them more resilient to damage. Both types require adequate quiet zones … ### H.264 vs H.265 vs AV1: Video Codec Comparison Video codecs determine compression efficiency, quality, and compatibility. Compare the three dominant codecs for streaming and distribution. - URL: https://peasydev.com/guides/h264-vs-h265-vs-av1-comparison/ - Category: Comparison - Reading time: 1 min - Words: 205 Key takeaways: - H.264 is supported on virtually every device made in the last decade. - H.265 achieves 30-50% better compression than H.264 at equivalent quality. - AV1 matches or exceeds H.265 compression with no patent fees. - Use H.264 for maximum compatibility. ## H.264 (AVC): The Universal Standard H.264 is supported on virtually every device made in the last decade. Hardware encoding and decoding is available on all modern CPUs and GPUs. It's the safe choice when compatibility is the priority. ## H.265 (HEVC): Better Compression H.265 achieves 30-50% better compression than H.264 at equivalent quality. A 1 GB H.264 file becomes 500-700 MB in H.265. The trade-off is slower encoding and patent licensing costs that limit browser support. ## AV1: The Open Future AV1 matches or exceeds H.265 compression with no patent fees. It's backed by Google, Netflix, Amazon, and others. Hardware decoding is available on newer devices (2020+). Encoding is very slow but improving rapidly. ## Comparison | Feature | H.264 | H.265 | AV1 | |---------|-------|-------|-----| | Browser support | Universal | Safari only | Chrome, Firefox | | Hardware decode | All devices | Most modern | 2020+ devices | | Compression | Baseline | +30-50% | +35-55% | | Encoding speed | Fast | Medium | Slow | | License | Licensed | Licensed | Royalty-free | ## Recommendation Use H.264 for maximum compatibility. Use H.265 for Apple devices and storage savings. Use AV1 for web streaming where you control the player. ### How to Encode and Decode Base64 Data Base64 converts binary data to ASCII text for safe transmission. Learn how Base64 encoding works and its common uses in web development. - URL: https://peasydev.com/guides/how-to-encode-decode-base64/ - Category: How-To - Reading time: 1 min - Words: 185 Key takeaways: - Base64 encodes binary data using 64 ASCII characters (A-Z, a-z, 0-9, +, /). - Data URIs**: Embedding images directly in HTML/CSS as `data:image/png;base64,...` - Standard Base64 uses `+` and `/` which are special characters in URLs. - Decoding reverses the process, converting the ASCII text back to binary. ## What Is Base64? Base64 encodes binary data using 64 ASCII characters (A-Z, a-z, 0-9, +, /). It's used to embed binary data in text-based formats like JSON, XML, HTML, and email. The output is ~33% larger than the input. ## Common Use Cases - **Data URIs**: Embedding images directly in HTML/CSS as `data:image/png;base64,...` - **Email attachments**: MIME encoding uses Base64 for binary attachments. - **API payloads**: Sending binary files in JSON API requests. - **JWT tokens**: Header and payload are Base64URL-encoded. ## Base64 vs Base64URL Standard Base64 uses `+` and `/` which are special characters in URLs. Base64URL replaces these with `-` and `_`, making encoded data safe for URLs and filenames. JWT tokens and URL parameters use Base64URL. ## Performance Considerations Base64 adds 33% overhead. A 1MB image becomes 1.33MB when Base64-encoded. For small inline images (under 10KB), the overhead is acceptable. For larger files, separate file uploads are more efficient. ## Decoding Decoding reverses the process, converting the ASCII text back to binary. If the Base64 string is corrupted (wrong length, invalid characters), decoding fails. Common issues include missing padding (`=`) characters. ### QR Code Security and Phishing Prevention Protect against QR code phishing attacks and implement secure QR code practices for businesses and consumers. - URL: https://peasydev.com/guides/qr-code-security-phishing-prevention/ - Category: Best Practice - Reading time: 1 min - Words: 287 Key takeaways: - QR codes present unique security challenges because users cannot visually inspect the encoded content before scanning. - ### For Businesses Creating QR Codes Always use your own domain rather than URL shorteners — users should see your brand in the URL preview. - ### For Users Scanning QR Codes Modern smartphone cameras show a URL preview before opening — always read this preview. - Never scan QR codes from unsolicited emails or messages. ## QR Code Security QR codes present unique security challenges because users cannot visually inspect the encoded content before scanning. This makes them a vector for phishing, malware distribution, and financial fraud. ### Common Attack Vectors Quishing (QR phishing) involves placing malicious QR codes over legitimate ones — a sticker on a parking meter redirecting to a fake payment site, for example. Attackers also distribute QR codes via email, printed flyers, and social media that link to credential-harvesting pages. Since shortened URLs hide the destination, users have no way to verify the link before scanning. ### For Businesses Creating QR Codes Always use your own domain rather than URL shorteners — users should see your brand in the URL preview. Register all variations of your domain to prevent typosquatting. Use HTTPS exclusively. Include your brand logo in the QR code to make unauthorized replacements more obvious. Monitor your QR code destinations with analytics to detect if a physical code has been replaced with a sticker. ### For Users Scanning QR Codes Modern smartphone cameras show a URL preview before opening — always read this preview. Look for suspicious domain names, HTTP (not HTTPS), or unfamiliar URL shorteners. If a QR code is on a sticker placed over another code, it's likely malicious. Never scan QR codes from unsolicited emails or messages. Be especially cautious with QR codes that request payment or login credentials. ### Dynamic QR Code Security Dynamic QR codes redirect through a service that can change the destination URL. While convenient for marketing, this means the QR code creator can change where it points at any time. Only use dynamic QR codes from trusted services, and prefer static codes for security-sensitive applications like payment links. ### How to Convert Between Number Systems (Binary, Hex, Octal) Developers regularly work with binary, hexadecimal, and octal numbers. Learn conversion techniques and when each number system is used. - URL: https://peasydev.com/guides/how-to-convert-number-systems/ - Category: How-To - Reading time: 1 min - Words: 178 Key takeaways: - Computers operate in binary (base-2), but humans find large binary numbers unreadable. - Hex uses digits 0-9 and letters A-F. - Octal (base-8) uses digits 0-7. - It's essential for understanding bitwise operations, subnet masks, file permissions (chmod 755 = 111 101 101), and hardware-level data representation. ## Number Systems in Computing Computers operate in binary (base-2), but humans find large binary numbers unreadable. Hexadecimal (base-16) provides a compact representation where each hex digit maps to exactly 4 binary bits. ## Hexadecimal Hex uses digits 0-9 and letters A-F. It's used for memory addresses, color codes (#FF6B35), MAC addresses (00:1A:2B:3C:4D:5E), and byte-level data representation. Two hex digits represent one byte (0x00 to 0xFF = 0 to 255). ## Binary Binary uses only 0 and 1. It's essential for understanding bitwise operations, subnet masks, file permissions (chmod 755 = 111 101 101), and hardware-level data representation. ## Octal Octal (base-8) uses digits 0-7. Its primary modern use is Unix file permissions where each digit represents read (4), write (2), and execute (1) for owner, group, and others. ## Conversion Table | Decimal | Binary | Hex | Octal | |---------|--------|-----|-------| | 10 | 1010 | A | 12 | | 255 | 11111111 | FF | 377 | | 42 | 101010 | 2A | 52 | | 100 | 1100100 | 64 | 144 | ### Troubleshooting QR Code Printing Issues Fix QR codes that won't scan after printing, including resolution, contrast, and sizing problems. - URL: https://peasydev.com/guides/troubleshooting-qr-code-printing/ - Category: Troubleshooting - Reading time: 1 min - Words: 295 Key takeaways: - A QR code that scans perfectly on screen may fail completely when printed. - Solution: always generate QR codes as vector graphics (SVG or EPS) for print use. - The quiet zone (white border) must be at least 4 module widths on all sides. ## Troubleshooting Printed QR Codes A QR code that scans perfectly on screen may fail completely when printed. Print-specific issues include resolution loss, color shifts, substrate interference, and physical damage. ### Resolution Too Low If the source image is low resolution, printing scales up the pixels, creating blurry module edges that confuse scanners. Solution: always generate QR codes as vector graphics (SVG or EPS) for print use. If you must use raster images, generate at minimum 300 DPI at the final print size. A 3cm QR code printed at 300 DPI should be generated at least 354×354 pixels. ### Insufficient Contrast Some printers reduce contrast, especially on colored backgrounds. Dark blue modules on a light blue background may have adequate screen contrast but insufficient print contrast. Solution: use black modules on white background for maximum reliability. If brand colors are required, test print samples and scan them before committing to a large print run. ### Quiet Zone Violated Designers sometimes crop QR codes too tightly or place them against busy backgrounds. The quiet zone (white border) must be at least 4 module widths on all sides. Without it, scanners cannot reliably detect the code boundaries. Solution: enforce the quiet zone in your design template, making it non-negotiable during layout. ### Substrate Problems Glossy surfaces create reflections that interfere with camera autofocus. Textured papers distort module edges. Transparent or semi-transparent substrates reduce contrast. Solution: use matte-finish paper for printed QR codes. On packaging, place QR codes on flat, opaque panels rather than curved or transparent surfaces. ### Verification Workflow Print a test batch of 10 codes. Scan each with three different devices (iPhone, Android, dedicated scanner) under both good and poor lighting. If fewer than 90% scan successfully, increase the code size by 25% and retest. ### Slug Generation and URL-Safe String Best Practices Generate clean, SEO-friendly URL slugs from titles and names, handling Unicode, transliteration, and edge cases. - URL: https://peasydev.com/guides/slug-generation-url-safe-strings/ - Category: Best Practice - Reading time: 1 min - Words: 243 ## URL Slug Generation Clean URL slugs improve SEO, readability, and shareability. Converting arbitrary text into URL-safe strings requires handling Unicode characters, multiple whitespace patterns, and special characters consistently. ### Basic Slug Rules A well-formed slug uses only lowercase ASCII letters, digits, and hyphens. Leading and trailing hyphens are removed. Multiple consecutive hyphens are collapsed to one. Common word separators (spaces, underscores, dots) become hyphens. The result should be a readable, meaningful summary of the content. ### Unicode and Transliteration For international content, transliterate Unicode characters to ASCII equivalents before slugifying: ü→ue, ñ→n, 日本→nihon. Libraries like python-slugify and slugify.js handle this automatically for most scripts. For CJK characters without standard transliterations, consider using romanization systems (Pinyin, Romaji) or keeping the original characters in the URL if your stack supports IRI. ### SEO Considerations Keep slugs under 60 characters — search engines may truncate longer URLs. Remove stop words (the, a, an, is, of) to focus on keywords, but only if the result remains readable. Avoid including dates or version numbers unless the content is inherently temporal. Once a slug is published and indexed, never change it without setting up a 301 redirect. ### Collision Handling When two different titles generate the same slug, append a numeric suffix (my-title, my-title-2, my-title-3). Check for collisions at generation time, not just at database insert time, to provide immediate feedback. For high-volume systems, consider appending a short random suffix instead of sequential numbers to avoid race conditions. ### REST API Testing: Best Practices for Developers Testing APIs thoroughly prevents bugs and ensures reliability. Learn strategies for testing endpoints, handling edge cases, and validating responses. - URL: https://peasydev.com/guides/rest-api-testing-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 164 Key takeaways: - API testing covers multiple dimensions: functional correctness (does it return the right data?), error handling (does it fail gracefully?), performance (how fast is it?), and security (is it properly authenticated?). - Test every HTTP method your API supports. - Don't just check the status code — validate the entire response body structure. - Test boundary conditions: empty strings, maximum-length values, Unicode characters, null values, negative numbers, zero, extremely large numbers, and special characters in URLs. - Verify that unauthenticated requests return 401, insufficient permissions return 403, and expired tokens are rejected. ## Test Categories API testing covers multiple dimensions: functional correctness (does it return the right data?), error handling (does it fail gracefully?), performance (how fast is it?), and security (is it properly authenticated?). ## Request Testing Test every HTTP method your API supports. Verify that GET requests are idempotent, POST creates new resources, PUT/PATCH updates correctly, and DELETE removes resources. Test with valid data, missing fields, and invalid types. ## Response Validation Don't just check the status code — validate the entire response body structure. Verify data types, required fields, date formats, and nested object shapes. Schema validation catches subtle bugs that manual checking misses. ## Edge Cases Test boundary conditions: empty strings, maximum-length values, Unicode characters, null values, negative numbers, zero, extremely large numbers, and special characters in URLs. These edge cases reveal parsing and validation bugs. ## Authentication Testing Verify that unauthenticated requests return 401, insufficient permissions return 403, and expired tokens are rejected. Test token refresh flows and rate limiting behavior. ### How to Generate Barcodes for Products Create UPC, EAN, and ISBN barcodes for retail products, including registration, formatting, and printing requirements. - URL: https://peasydev.com/guides/how-to-generate-product-barcodes/ - Category: How-To - Reading time: 1 min - Words: 258 ## Generating Product Barcodes Every product sold at retail needs a barcode. The process involves obtaining a company prefix, assigning product numbers, generating the barcode image, and ensuring print quality meets scanner requirements. ### Getting a Company Prefix In the US, company prefixes are issued by GS1 US. The prefix length determines how many unique products you can number — a 7-digit prefix allows 100,000 products, while a 10-digit prefix allows 100. Costs range from $250 for small businesses to $10,500 for enterprises, plus annual renewal fees. Third-party barcode resellers offer individual UPCs, but major retailers may reject them. ### UPC vs EAN UPC-A (12 digits) is the North American standard. EAN-13 (13 digits) is used internationally. A UPC-A can be converted to EAN-13 by prepending a zero. If you sell internationally, register for EAN-13 through your national GS1 organization. The last digit is always a check digit calculated from the preceding digits. ### Barcode Image Generation Generate barcode images at the exact print dimensions — scaling introduces errors. The minimum bar width is 0.264mm (1X magnification) for UPC/EAN. Most retail barcodes print at 80-200% magnification. Include human-readable digits below the bars. Use vector format (EPS) for print production to avoid rasterization artifacts. ### Print Quality Verification Use a barcode verifier (not just a scanner) to grade your printed barcodes. Verifiers check symbol contrast, modulation, decodability, and quiet zones, assigning a grade from A to F. Most retailers require grade C or better. Common causes of low grades include ink spread (dot gain), insufficient contrast, and truncated bars. ### Troubleshooting File Format Conversion Errors Diagnose and fix common file conversion failures including codec errors, corruption, and compatibility issues. - URL: https://peasydev.com/guides/troubleshooting-format-conversion-errors/ - Category: Troubleshooting - Reading time: 2 min - Words: 317 ## Troubleshooting File Conversions File conversion failures range from obvious error messages to subtle quality degradation. Understanding common failure modes helps you diagnose issues quickly. ### Corrupted Source Files If a file fails to open in its native application, it won't convert successfully either. Common causes: incomplete download (truncated file), storage media errors, or software crashes during save. Solution: re-download or recover from backup. For partially corrupted files, specialized repair tools can sometimes extract readable content. ### Codec and Library Errors Conversion tools depend on codec libraries. Missing or outdated codecs cause failures with specific format variants. HEIC conversion requires the HEVC codec. AVIF requires libaom or libsvtav1. Some older TIFF files use proprietary compression (LZW was patented until 2003) that not all libraries support. Solution: update your conversion tool or use a tool that bundles its own codecs. ### Color Space Mismatches Converting from CMYK (print) to RGB (screen) changes colors visibly — what looked like deep blue in CMYK may appear brighter in RGB. ICC color profiles embedded in the source file should be applied during conversion. If the output colors look wrong, check whether the converter is ignoring the embedded color profile. ### Font and Layout Issues Document conversions (PDF to DOCX, DOCX to PDF) often produce layout problems. Missing fonts are substituted, changing line breaks and page layouts. Tables may lose alignment. Headers and footers may be duplicated or lost. Solution: embed fonts in the source document. For PDF to DOCX, accept that the result will need manual cleanup — pixel-perfect conversion between these fundamentally different formats is not possible. ### Character Encoding Problems Text file conversions between different encodings (UTF-8, Latin-1, Shift-JIS) can produce garbled characters (mojibake). If you see "é" instead of "é", the file was UTF-8 but interpreted as Latin-1. Solution: identify the … ### QR Code Analytics and Tracking Track QR code scans with UTM parameters, dynamic redirects, and analytics platforms for marketing campaigns. - URL: https://peasydev.com/guides/qr-code-analytics-tracking/ - Category: Best Practice - Reading time: 1 min - Words: 280 ## QR Code Analytics Tracking QR code scans transforms them from static links into measurable marketing channels. Understanding who scans, when, and where lets you optimize placement and content. ### UTM Parameters The simplest tracking method is appending UTM parameters to the encoded URL: `utm_source=qr`, `utm_medium=print`, `utm_campaign=spring-sale`, `utm_content=poster-a`. Google Analytics and similar tools automatically parse these parameters into campaign reports. Keep URLs under 100 characters total to maintain QR code simplicity. ### Dynamic QR Codes Dynamic QR codes redirect through an intermediary server that logs each scan before forwarding to the destination. This provides scan counts, timestamps, geographic locations (from IP), device types, and unique vs repeat visitor data — all without modifying the destination URL. The trade-off is dependence on the intermediary service remaining operational. ### A/B Testing with QR Codes Create multiple QR codes pointing to different landing pages (or the same page with different UTM content values) and place them in different locations. Compare scan rates and conversion rates to determine which placements and creatives perform best. Use statistically significant sample sizes — at least 100 scans per variant — before drawing conclusions. ### Privacy Considerations QR code tracking typically collects IP addresses, which are personal data under GDPR and similar regulations. Dynamic QR code services may set cookies on redirect. Disclose tracking in your privacy policy. For sensitive contexts (healthcare, government), use static QR codes without intermediary tracking to minimize data collection. ### Metrics That Matter Raw scan count is vanity — focus on unique scanners, conversion rate (scans that lead to desired actions), and scan-to-action time. Geographic distribution reveals which physical locations drive the most engagement. Time-of-day patterns indicate when your audience is most receptive. ### Text Diff and Comparison: Finding Changes Between Versions Comparing text versions reveals exactly what changed. Learn how diff algorithms work and how to use them for code review, document comparison, and data validation. - URL: https://peasydev.com/guides/text-diff-comparison-guide/ - Category: How-To - Reading time: 1 min - Words: 175 Key takeaways: - Diff algorithms compare two texts and identify the minimal set of changes (additions, deletions, modifications) needed to transform one into the other. - Line-level diff shows which lines changed. - Side-by-side view shows the old and new versions in parallel columns, making it easy to scan for differences. - Code review**: Compare code versions to understand changes. - Many diffs are cluttered by whitespace changes (indentation, trailing spaces). ## How Diff Works Diff algorithms compare two texts and identify the minimal set of changes (additions, deletions, modifications) needed to transform one into the other. The most common algorithm is the longest common subsequence (LCS) approach. ## Line-Level vs Character-Level Diff Line-level diff shows which lines changed. Character-level diff highlights exactly which characters within a line were modified. Character-level is more precise but can be overwhelming for large changes. ## Side-by-Side vs Unified View Side-by-side view shows the old and new versions in parallel columns, making it easy to scan for differences. Unified view interleaves additions and deletions in a single stream, using +/- prefixes. ## Use Cases - **Code review**: Compare code versions to understand changes. - **Contract comparison**: Find what changed between contract drafts. - **Data validation**: Verify that a transformation produced expected results. - **Configuration audit**: Detect unauthorized changes to config files. ## Ignoring Whitespace Many diffs are cluttered by whitespace changes (indentation, trailing spaces). Most diff tools offer options to ignore whitespace, focus on content changes, and collapse unchanged sections. ### JSON vs XML vs Protocol Buffers: Data Serialization Compared Choosing the right data serialization format affects performance, readability, and development speed. Compare JSON, XML, and Protocol Buffers for your use case. - URL: https://peasydev.com/guides/json-vs-xml-vs-protobuf/ - Category: Comparison - Reading time: 1 min - Words: 206 Key takeaways: - JSON is lightweight, human-readable, and natively supported by JavaScript. - Protocol Buffers (protobuf) use binary encoding, producing payloads 3-10x smaller than JSON and 10-30x smaller than XML. - JSON for web APIs and configuration. ## JSON: The Web Standard JSON is lightweight, human-readable, and natively supported by JavaScript. It's the default choice for REST APIs, configuration files, and data exchange. JSON lacks a schema language (though JSON Schema exists) and doesn't support comments. ## XML: The Enterprise Standard XML is verbose but powerful. It supports namespaces, schemas (XSD), transformations (XSLT), and is widely used in enterprise systems (SOAP APIs, RSS feeds, office documents). Its verbosity increases payload size by 3-5x compared to JSON. ## Protocol Buffers: The Performance Choice Protocol Buffers (protobuf) use binary encoding, producing payloads 3-10x smaller than JSON and 10-30x smaller than XML. Serialization and deserialization are 20-100x faster. The trade-off is that protobufs aren't human-readable. ## Comparison | Feature | JSON | XML | Protobuf | |---------|------|-----|----------| | Readability | Good | Good | None | | Size | Medium | Large | Small | | Parse speed | Fast | Slow | Very Fast | | Schema | Optional | Built-in | Required | | Browser support | Native | Built-in | Library needed | ## When to Choose Each JSON for web APIs and configuration. XML for enterprise integration and document formats. Protobuf for high-performance microservices and mobile apps where bandwidth and latency matter. ### How to Generate QR Codes with Custom Designs Create branded QR codes with custom colors, logos, and patterns while maintaining reliable scannability. - URL: https://peasydev.com/guides/how-to-generate-custom-qr-codes/ - Category: How-To - Reading time: 1 min - Words: 272 Key takeaways: - QR codes support significant visual customization without sacrificing functionality, thanks to built-in error correction. - ### Color Customization Dark modules must contrast against light modules with a minimum 40% luminance difference for reliable scanning. - The quiet zone (white border) must be maintained — it's at least 4 modules wide on all sides. - Always test the final code with multiple scanner apps — what works on one may fail on another. ## Custom QR Code Generation QR codes support significant visual customization without sacrificing functionality, thanks to built-in error correction. Understanding the technical constraints lets you create branded codes that scan reliably. ### Error Correction Levels QR codes have four error correction levels: L (7%), M (15%), Q (25%), and H (30%). The percentage indicates how much of the code can be obscured or damaged while remaining scannable. For branded QR codes with logos, use level H — this lets you place a logo over up to 30% of the code area. For plain codes, level M offers a good balance between data density and resilience. ### Color Customization Dark modules must contrast against light modules with a minimum 40% luminance difference for reliable scanning. You can use brand colors as long as this contrast ratio is maintained. Avoid red/green combinations that are problematic for colorblind users. The quiet zone (white border) must be maintained — it's at least 4 modules wide on all sides. ### Adding Logos Center logos work best because QR scanners typically start reading from the corner finder patterns. Keep the logo within the center 20-25% of the code area. Use a white background behind the logo to create a clean boundary. Always test the final code with multiple scanner apps — what works on one may fail on another. ### Output Formats Generate QR codes as SVG for web use — they scale perfectly to any size. Use PNG at minimum 300 DPI for print materials. For very small physical sizes (under 2cm), simplify the code by using shorter URLs and lower error correction to reduce module density. ### CSS Performance Optimization Best Practices CSS affects page rendering speed more than developers realize. Learn how to reduce render-blocking, optimize selectors, and minimize layout thrashing. - URL: https://peasydev.com/guides/css-performance-optimization/ - Category: Best Practice - Reading time: 1 min - Words: 159 Key takeaways: - Browsers won't render content until they've downloaded and parsed all CSS. - CSS selectors are evaluated right-to-left. - Remove unused CSS with tree-shaking tools. - Reading layout properties (offsetHeight, getBoundingClientRect) forces the browser to recalculate layout. - Custom fonts can cause FOIT (Flash of Invisible Text) or FOUT (Flash of Unstyled Text). ## CSS Is Render-Blocking Browsers won't render content until they've downloaded and parsed all CSS. A large stylesheet delays the first paint. Critical CSS (styles for above-the-fold content) should be inlined in `<head>` for fastest first paint. ## Selector Performance CSS selectors are evaluated right-to-left. A selector like `.sidebar .nav li a` first finds all `<a>` elements, then filters. Flat selectors (`.nav-link`) are faster than deeply nested ones. ## Reducing CSS Size - Remove unused CSS with tree-shaking tools. - Use shorthand properties (`margin: 0 auto` instead of four margin declarations). - Combine duplicate rules. - Use modern features like `gap` instead of margin hacks. ## Layout Thrashing Reading layout properties (offsetHeight, getBoundingClientRect) forces the browser to recalculate layout. Batch reads and writes separately to avoid forced synchronous layout. ## Font Loading Custom fonts can cause FOIT (Flash of Invisible Text) or FOUT (Flash of Unstyled Text). Use `font-display: swap` to show fallback fonts immediately while custom fonts load. ### Troubleshooting Barcode Scanner Compatibility Fix barcode scanning failures across different scanner types, symbologies, and environments. - URL: https://peasydev.com/guides/troubleshooting-barcode-scanner-compatibility/ - Category: Troubleshooting - Reading time: 1 min - Words: 288 ## Troubleshooting Barcode Scanner Compatibility Barcodes that work with one scanner may fail with another due to symbology support, configuration settings, or environmental factors. Systematic troubleshooting identifies the root cause quickly. ### Scanner Configuration Most barcode scanners support multiple symbologies but may have some disabled by default. If a scanner reads UPC but not Code 128, check its configuration — Code 128 may need to be explicitly enabled. Laser scanners cannot read 2D codes (QR, Data Matrix) — they only decode 1D linear barcodes. Camera-based (imager) scanners support both 1D and 2D codes. ### Symbology Detection Failures If a scanner misreads a barcode (returns wrong data), it may be detecting the wrong symbology. Code 39 and Code 93 can look similar to scanners. Adding start/stop characters and configuring the scanner to verify check digits prevents misreads. For GS1-128 barcodes, ensure the scanner is configured to parse GS1 Application Identifiers correctly. ### Environmental Factors Direct sunlight overwhelms the scanner's sensor, causing read failures. Reflective surfaces (glossy packaging, metallic labels) create glare. Solution: use matte finishes for barcode labels, or position scanning stations away from windows. Cold environments can slow laser scanners — LED-based imagers are more reliable in temperature extremes. ### Damaged or Degraded Barcodes Shipping damage, moisture, abrasion, and UV exposure degrade printed barcodes. Thermal labels fade after 6-12 months of sun exposure. Solution: use synthetic label materials for outdoor or long-term applications. For warehouse environments, laminate barcode labels or use laser-etched codes on durable surfaces. ### Mobile App Scanning Smartphone camera scanning depends on autofocus speed, camera resolution, and lighting. Older phones with lower-resolution cameras struggle with dense QR codes. Provide adequate lighting at scan points. Consider offering a manual entry fallback for situations where scanning fails. ### Video Format Containers vs Codecs: What's the Difference? MP4, MKV, and WebM are containers; H.264, H.265, and VP9 are codecs. Understanding this distinction is essential for video conversion and compatibility troubleshooting. - URL: https://peasydev.com/guides/video-containers-vs-codecs-explained/ - Category: Comparison - Reading time: 1 min - Words: 284 ## Containers vs Codecs A video container (format) is like a box that holds different types of content — video, audio, subtitles, metadata, and chapter markers. A codec (compressor-decompressor) is the algorithm that encodes and decodes the actual video or audio data inside the container. ### Common Containers MP4 (.mp4) is the most universally supported container, compatible with virtually every device and browser. It typically holds H.264 or H.265 video with AAC audio. MKV (.mkv) is a flexible open-source container that supports nearly any codec and can hold multiple audio/subtitle tracks. WebM (.webm) is Google's open-source container designed for web use, typically holding VP9 video and Opus audio. ### Common Video Codecs H.264 (AVC) is the most widely supported codec — every device and browser plays it. H.265 (HEVC) provides 40-50% better compression than H.264 but has licensing complexities and limited browser support. AV1 is royalty-free, offers excellent compression (comparable to H.265), and is supported by modern browsers. VP9 is Google's royalty-free codec, widely used on YouTube. ### Why This Distinction Matters When a video "won't play," the issue is almost always the codec, not the container. A browser may support MP4 containers but not the H.265 codec inside it. Renaming a file from .mkv to .mp4 doesn't change the codecs — it usually creates a broken file. Proper conversion requires re-encoding with a compatible codec. ### Choosing the Right Combination For maximum compatibility: MP4 with H.264 + AAC. For best quality per byte on modern devices: MP4 with H.265 + AAC or WebM with AV1 + Opus. For web delivery: MP4 with H.264 as fallback, WebM with VP9 or AV1 as primary (progressive enhancement). For archival: MKV with the original codec (no re-encoding). ### Troubleshooting Video Export and Rendering Errors Fix common video export failures including codec errors, audio sync issues, and rendering crashes. - URL: https://peasydev.com/guides/troubleshooting-video-export-rendering-errors/ - Category: Troubleshooting - Reading time: 2 min - Words: 315 ## Troubleshooting Video Export Video export failures are frustrating because they often occur after a long rendering process. Understanding common failure modes helps you diagnose and fix issues without starting from scratch. ### Out of Memory Errors Video rendering is memory-intensive, especially at high resolutions with effects. 4K video with complex effects can consume 8GB+ of RAM. Solutions: close other applications during rendering, reduce preview quality (render quality can stay high), render in sections and concatenate afterward, or use proxy editing (edit with low-res proxies, render from full-res originals). ### Audio/Video Sync Issues Sync problems usually originate from variable frame rate (VFR) source footage. Most screen recorders and smartphones record in VFR, where the frame rate varies based on scene complexity. Convert VFR to constant frame rate (CFR) before editing. If sync drift is gradual (audio slowly gets ahead or behind), the frame rate of the timeline doesn't match the source. ### Codec Compatibility The export codec must be supported by your target platform. H.264 is the safest choice for universal compatibility. H.265 (HEVC) produces smaller files but isn't supported everywhere. ProRes is preferred for professional editing workflows but produces very large files. AV1 offers the best compression but encoding is extremely slow. ### Color Shift After Export If exported video looks different from the preview — washed out, oversaturated, or with a color cast — check the color space settings. Editing in Rec. 709 and exporting in Rec. 2020 (or vice versa) causes visible color shifts. Ensure the export color space matches the source and editing color space. ### Partial Render Failures If rendering fails at a specific timestamp, that section likely contains a problematic element: a corrupt source clip, an unsupported effect, or a transition that exceeds available memory. Navigate to the failure point, simplify or remove the … ### QR Code Error Correction Levels Explained Learn how QR code error correction works and when to use each level for optimal scanning reliability. - URL: https://peasydev.com/guides/qr-error-correction-levels-explained/ - Category: How-To - Reading time: 1 min - Words: 245 Key takeaways: - QR codes use Reed-Solomon error correction to remain scannable even when partially damaged or obscured. - For digital-only QR codes displayed on screens, Level L provides the smallest code size with minimal error tolerance. - Higher error correction means more data modules in the QR code. - When embedding a logo in a QR code center, use at minimum Level Q correction. - Generate test codes at each error level and simulate damage by covering portions with tape. ## Understanding QR Code Error Correction QR codes use Reed-Solomon error correction to remain scannable even when partially damaged or obscured. There are four correction levels: L (7%), M (15%), Q (25%), and H (30%), each representing the percentage of data that can be restored. ## Choosing the Right Level For digital-only QR codes displayed on screens, Level L provides the smallest code size with minimal error tolerance. Level M is the default choice for most printed materials. Level Q works well for codes that may be partially covered by logos or design elements. Level H is essential for industrial environments where codes face physical damage. ## Impact on Code Size Higher error correction means more data modules in the QR code. A URL encoded at Level L might fit in a Version 2 code (25×25), while the same URL at Level H might require Version 4 (33×33). This tradeoff between reliability and size is critical for small-format printing. ## Best Practices for Logo Placement When embedding a logo in a QR code center, use at minimum Level Q correction. The logo should not exceed 30% of the code area. Always test the resulting code with multiple scanner apps to verify readability across devices. ## Testing and Validation Generate test codes at each error level and simulate damage by covering portions with tape. Scan with at least three different devices to confirm reliability. Document the minimum acceptable level for each use case in your project. ### QR Codes for Restaurant Menus: Implementation Guide QR code menus became standard during the pandemic. Learn how to implement them effectively, avoid common usability pitfalls, and provide a good customer experience. - URL: https://peasydev.com/guides/qr-codes-restaurant-menus-guide/ - Category: How-To - Reading time: 1 min - Words: 278 Key takeaways: - Initially adopted for hygiene during COVID-19, QR code menus have stayed because they solve real problems: instant menu updates (no reprinting), multi-language support, dynamic pricing, and allergen filtering. - ### Menu Page Best Practices The linked page must be mobile-optimized — not a PDF of your physical menu. - ### Accessibility Considerations Not all customers can or want to use QR codes — always provide a physical menu option when requested. ## Why QR Menus Persist Initially adopted for hygiene during COVID-19, QR code menus have stayed because they solve real problems: instant menu updates (no reprinting), multi-language support, dynamic pricing, and allergen filtering. However, poor implementation frustrates customers. ### Menu Page Best Practices The linked page must be mobile-optimized — not a PDF of your physical menu. Use a responsive web page with clear category navigation, readable font sizes (minimum 16px), and high-contrast text. Include prices, descriptions, and allergen information. Load time should be under 2 seconds on a 4G connection. ### Physical Placement Place QR codes where they're easily accessible without requiring customers to stand up or move objects. Table tents, laminated table stickers, and menu stands at eye level work best. Print at minimum 2cm x 2cm for close-range scanning (arm's length). Include a brief instruction: "Scan for menu" with an arrow pointing to the code. ### Error Correction and Durability Use high error correction level (H, 30%) for QR codes that will be printed on surfaces exposed to wear, spills, and sunlight. Laminate or coat printed codes. Test scanning in the actual restaurant lighting conditions — dim ambiance lighting makes some phone cameras struggle with low-contrast codes. ### Accessibility Considerations Not all customers can or want to use QR codes — always provide a physical menu option when requested. Ensure the digital menu is screen-reader accessible. Provide large-print viewing options. Consider elderly customers who may be unfamiliar with QR scanning. ### Analytics Use trackable QR codes with UTM parameters to measure scan rates, popular menu sections, and peak viewing times. This data helps optimize menu layout and identify items that get viewed but not ordered. ### QR Code Error Correction Levels: Choosing the Right One QR codes can be partially damaged and still scan successfully. Learn how error correction works, when to use each level, and the tradeoff between resilience and data capacity. - URL: https://peasydev.com/guides/qr-code-error-correction-levels/ - Category: Best Practice - Reading time: 1 min - Words: 286 ## How Error Correction Works QR codes use Reed-Solomon error correction, a mathematical technique that adds redundant data to the code. When part of the QR code is damaged, obscured, or missing, the redundant data allows the decoder to reconstruct the original information. ### The Four Levels Level L (Low): ~7% recovery. Smallest QR code for a given data payload. Best for clean, controlled environments like digital screens. Level M (Medium): ~15% recovery. The default choice for most applications — good balance between size and resilience. Level Q (Quartile): ~25% recovery. Suitable for outdoor use, packaging, and environments with moderate wear. Level H (High): ~30% recovery. Required when placing logos over the QR code center or when expecting significant damage. ### Size vs Resilience Tradeoff Higher error correction means more modules (black/white squares) in the QR code. A URL encoded at Level L might fit in a Version 3 QR code (29x29 modules), while Level H of the same URL might require Version 5 (37x37 modules). Larger QR codes need to be printed bigger to remain scannable. ### When to Use Each Level Level L: Digital displays, receipts (single use), data-dense applications where size must be minimized. Level M: Standard printed materials, business cards, flyers. Level Q: Product packaging, labels that may be scratched or dented, outdoor signage under cover. Level H: Branded QR codes with logos, outdoor posters, industrial labels, harsh environments. ### Testing Methodology Print your QR code at the intended size and scan it with at least three different phone models. Then simulate damage: cover 10%, 20%, and 30% of the code area with tape and re-scan. The code should remain scannable up to the damage threshold of your chosen error correction level. ### How to Extract and Transform Structured Data from Text Parse emails, addresses, phone numbers, dates, and URLs from unstructured text using regex and pattern matching. - URL: https://peasydev.com/guides/how-to-extract-structured-data-from-text/ - Category: How-To - Reading time: 2 min - Words: 313 ## Extracting Structured Data from Text Unstructured text contains valuable structured data — email addresses, phone numbers, dates, URLs, prices, and identifiers. Extracting this data accurately requires understanding the patterns and edge cases of each data type. ### Email Extraction The RFC 5322 email specification allows a surprising range of characters, but practical extraction uses simpler patterns. Match sequences of alphanumeric characters, dots, hyphens, and underscores, followed by @, followed by a domain with at least one dot. Be aware of edge cases: plus-addressed emails (user+tag@domain.com), subdomains (user@mail.domain.com), and new TLDs (.museum, .technology). ### Phone Number Parsing Phone numbers appear in dozens of formats: (555) 123-4567, +1-555-123-4567, 555.123.4567, 5551234567. Rather than writing one regex to match all formats, strip all non-digit characters first, then validate the resulting digit sequence against known country formats. The E.164 format (+[country][subscriber]) is the universal normalized form. ### Date Recognition Dates are ambiguous: 01/02/03 could be January 2, 2003 (US), February 1, 2003 (UK), or 2001 February 3 (ISO). When extracting dates from text, look for unambiguous patterns first (written month names, ISO 8601 format), then fall back to locale-specific patterns with clear documentation about which interpretation you're using. ### URL Detection URLs in text may or may not have the protocol prefix. Match both http(s)://domain.tld/path and bare domain.tld/path patterns. Be careful with punctuation at the end: "Visit example.com." — the period is sentence punctuation, not part of the URL. Parentheses in URLs (common in Wikipedia links) require careful handling to avoid matching surrounding sentence parentheses. ### Validation After Extraction Extraction finds patterns; validation confirms they're real. Extracted emails should have valid MX records on their domain. Phone numbers should have the correct number of digits for their country. URLs should be accessible (HTTP HEAD request). Dates should be valid calendar dates (no February 30th). … ### How to Convert Between Video Containers and Codecs Understand the relationship between video containers (MP4, MKV, WebM) and codecs (H.264, H.265, VP9) for proper conversion. - URL: https://peasydev.com/guides/how-to-convert-video-containers-codecs/ - Category: How-To - Reading time: 2 min - Words: 319 Key takeaways: - Video conversion requires understanding two distinct concepts: the container (file format) and the codec (compression algorithm). - Minimize re-encoding passes — never convert from one lossy codec to another lossy codec unless absolutely necessary. - Always start from the highest-quality source available. ## Video Containers and Codecs Video conversion requires understanding two distinct concepts: the container (file format) and the codec (compression algorithm). Confusing these leads to unnecessary re-encoding and quality loss. ### Containers vs Codecs A container (MP4, MKV, WebM, MOV, AVI) is a wrapper that holds video, audio, subtitles, and metadata streams. A codec (H.264, H.265, VP9, AV1) is the algorithm that compresses video data. MP4 can contain H.264 or H.265 video with AAC or AC-3 audio. MKV is the most flexible, supporting virtually any codec combination. ### When Re-Encoding Is Unnecessary Changing container without changing codecs (remuxing) is instant and lossless. Converting MKV (H.264 + AAC) to MP4 (H.264 + AAC) simply repackages the same streams in a different wrapper. No quality loss occurs because the compressed video data is copied byte-for-byte. This takes seconds regardless of file size. ### When Re-Encoding Is Required Changing codecs requires re-encoding: converting H.264 to H.265 reduces file size but involves decoding and re-encoding every frame. Each generation of re-encoding introduces quality loss. Minimize re-encoding passes — never convert from one lossy codec to another lossy codec unless absolutely necessary. Going from H.264 to H.265 for storage savings is reasonable; going from H.264 to H.264 with different settings is wasteful. ### Codec Compatibility H.264 in MP4: universal compatibility — every device, browser, and player supports this combination. H.265 in MP4: newer devices support it; some browsers don't. VP9 in WebM: supported by Chrome, Firefox, Edge; not Safari (but Safari supports VP9 in MP4). AV1 in WebM or MP4: best compression but slowest encoding; growing browser support. ### Practical Conversion Guide For maximum compatibility: H.264 + AAC in MP4. For smaller files: H.265 + AAC in MP4 (with H.264 fallback). For web-only: VP9 + Opus in WebM. For archival: original codec in MKV (don't … ### QR Code vs NFC Tags: Which to Use Compare QR codes and NFC tags for contactless interactions, covering cost, range, and use cases. - URL: https://peasydev.com/guides/qr-code-vs-nfc-tags-comparison/ - Category: Comparison - Reading time: 1 min - Words: 222 Key takeaways: - Both QR codes and NFC tags enable contactless digital interactions, but they work fundamentally differently. - QR codes are essentially free to create and deploy — they can be printed on any surface. - NFC requires a simple tap with no app needed on modern smartphones. - NFC tags can be encrypted and support mutual authentication, making them suitable for access control and payments. - Use QR codes for marketing materials, menus, product information, and any scenario where cost matters and the interaction is casual. ## QR Codes vs NFC Tags Overview Both QR codes and NFC tags enable contactless digital interactions, but they work fundamentally differently. QR codes are optical — requiring a camera and line of sight. NFC tags use radio frequency — requiring physical proximity (typically under 4cm). ## Cost Comparison QR codes are essentially free to create and deploy — they can be printed on any surface. NFC tags cost $0.10-$2.00 per unit depending on type and volume. For large-scale deployments like restaurant menus or marketing campaigns, QR codes have a massive cost advantage. ## User Experience Differences NFC requires a simple tap with no app needed on modern smartphones. QR codes require opening a camera app and pointing at the code. However, QR codes work at greater distances and don't require the user to physically reach the tag. ## Security Considerations NFC tags can be encrypted and support mutual authentication, making them suitable for access control and payments. QR codes are visually exposed and can be replaced by malicious codes (QR-jacking). For security-sensitive applications, NFC is generally preferred. ## Recommended Use Cases Use QR codes for marketing materials, menus, product information, and any scenario where cost matters and the interaction is casual. Choose NFC for access control, loyalty programs, asset tracking, and scenarios requiring security or repeated interactions with the same tag. ### URL Encoding Best Practices for Web Developers Proper URL encoding prevents broken links and security vulnerabilities. Learn which characters must be encoded and how to handle international URLs. - URL: https://peasydev.com/guides/url-encoding-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 173 Key takeaways: - URLs can only contain ASCII characters. - Spaces become `%20` (or `+` in query strings). - Different URL parts have different encoding rules: - Domain names with non-ASCII characters use Punycode encoding. - A common bug is encoding already-encoded values, turning `%20` into `%2520`. ## Why URL Encoding Matters URLs can only contain ASCII characters. Special characters, spaces, and non-ASCII characters must be percent-encoded (%XX format) to be safely transmitted. Incorrect encoding causes broken links, XSS vulnerabilities, and data loss. ## Characters That Must Be Encoded Spaces become `%20` (or `+` in query strings). Forward slashes in values must be encoded as `%2F`. Ampersands in values need `%26` to avoid being interpreted as parameter separators. ## Component-Specific Encoding Different URL parts have different encoding rules: - **Path**: Encode spaces and special chars, preserve `/`. - **Query string**: Encode spaces as `+`, preserve `&` and `=` as separators. - **Fragment**: Encode most special characters. ## International Domain Names (IDN) Domain names with non-ASCII characters use Punycode encoding. For example, `münchen.de` becomes `xn--mnchen-3ya.de`. Modern browsers display the Unicode version while transmitting the Punycode version. ## Double Encoding A common bug is encoding already-encoded values, turning `%20` into `%2520`. This happens when a URL passes through multiple encoding layers. Always check if data is already encoded before encoding it again. ### Troubleshooting QR Codes That Won't Scan Diagnose and fix common QR code scanning failures including size, contrast, and encoding issues. - URL: https://peasydev.com/guides/troubleshooting-qr-codes-wont-scan/ - Category: Troubleshooting - Reading time: 1 min - Words: 244 Key takeaways: - When a QR code fails to scan, the issue typically falls into one of four categories: insufficient size, poor contrast, encoding errors, or environmental factors. - The minimum recommended size for a printed QR code is 2cm × 2cm for close-range scanning. - QR scanners rely on high contrast between dark and light modules. - URLs that are too long can push the QR code to a version that's difficult to scan at small sizes. - Poor lighting, extreme angles, dirty camera lenses, and screen reflections all affect scanning. ## Common QR Code Scanning Failures When a QR code fails to scan, the issue typically falls into one of four categories: insufficient size, poor contrast, encoding errors, or environmental factors. Systematic diagnosis helps identify the root cause quickly. ## Size and Resolution Issues The minimum recommended size for a printed QR code is 2cm × 2cm for close-range scanning. For scanning from 1 meter away, the code should be at least 10cm × 10cm. A general rule: the scanning distance in centimeters divided by 10 gives the minimum code size. Low print resolution (under 300 DPI) can blur module boundaries. ## Contrast Problems QR scanners rely on high contrast between dark and light modules. The minimum recommended contrast ratio is 4:1. Avoid using similar-toned colors for foreground and background. Glossy surfaces can create glare that interferes with scanning — use matte finishes for printed codes. ## Encoding and Data Issues URLs that are too long can push the QR code to a version that's difficult to scan at small sizes. Use URL shorteners or redirect services for long URLs. Ensure the encoded data uses the correct character encoding (UTF-8 for international characters). Test that the destination URL is still active. ## Environmental Factors Poor lighting, extreme angles, dirty camera lenses, and screen reflections all affect scanning. For outdoor installations, consider using weather-resistant materials and ensuring adequate lighting. When displaying QR codes on screens, avoid low-brightness settings and ensure the display resolution is sufficient. ### Video Encoding Settings for Web Delivery Optimize video encoding with the right codec, bitrate, and container settings for web playback. - URL: https://peasydev.com/guides/video-encoding-settings-web-delivery/ - Category: Best Practice - Reading time: 1 min - Words: 280 Key takeaways: - H.264 (AVC) remains the most compatible codec — supported by virtually every browser and device. - For 1080p H.264 web video, target 5-8 Mbps for high quality and 3-5 Mbps for good quality. - MP4 (with H.264 or H.265) is the universal web container. - AAC is the standard audio codec for MP4 containers. - Export from your editing software at the highest quality (ProRes, DNxHR, or high-bitrate H.264). ## Codec Selection H.264 (AVC) remains the most compatible codec — supported by virtually every browser and device. H.265 (HEVC) offers 50% better compression but has limited browser support and licensing complexity. VP9 (Google's open codec) is well-supported in Chrome and Firefox. AV1 is the newest option with the best compression but requires significant encoding time. ## Bitrate Guidelines For 1080p H.264 web video, target 5-8 Mbps for high quality and 3-5 Mbps for good quality. For 4K, double these values. For screen recordings and tutorials (low motion), you can use 30-50% lower bitrates. For high-motion content (sports, action), use the higher end of the range. Variable bitrate (VBR) encoding allocates bits where needed, producing better quality than constant bitrate (CBR) at the same average rate. ## Container Format MP4 (with H.264 or H.265) is the universal web container. WebM (with VP9 or AV1) is preferred for Chrome-first applications. For adaptive streaming, use fragmented MP4 with DASH or HLS. For simple file downloads and social media uploads, plain MP4 with H.264 baseline profile ensures maximum compatibility. ## Audio in Video Files AAC is the standard audio codec for MP4 containers. For stereo voice content, 128-192 kbps is sufficient. For music or sound-design-heavy content, use 256-320 kbps. Sample rate should match your source (typically 48 kHz for video). Normalize audio loudness to -14 LUFS for web platforms. ## Encoding Workflow Export from your editing software at the highest quality (ProRes, DNxHR, or high-bitrate H.264). Then compress for delivery using FFmpeg or HandBrake. Two-pass encoding produces better quality at the target bitrate than single-pass. Always test the encoded file on multiple devices before publishing. Consider creating multiple quality versions for adaptive streaming. ### Dynamic QR Codes: When and How to Use Them Understand dynamic QR codes that allow destination changes without reprinting the physical code. - URL: https://peasydev.com/guides/dynamic-qr-codes-when-how-to-use/ - Category: Best Practice - Reading time: 1 min - Words: 258 Key takeaways: - Dynamic QR codes encode a short redirect URL instead of the final destination. - The primary benefit is flexibility — update destinations for seasonal campaigns, fix broken links, or A/B test landing pages. - Most dynamic QR code services charge monthly fees ranging from free (limited scans) to $50+/month for enterprise features. - Choose a reliable provider with strong uptime guarantees — a down redirect service means all your codes stop working. - Static codes are preferable when the destination never changes (product serial numbers, permanent URLs), when you need the code to work offline or without internet, or when you want to avoid ongoing subscription costs. ## What Are Dynamic QR Codes Dynamic QR codes encode a short redirect URL instead of the final destination. This allows you to change where the code points without reprinting it. The QR code itself contains a permanent short URL that redirects to your target, which you can update anytime through a management dashboard. ## Advantages Over Static Codes The primary benefit is flexibility — update destinations for seasonal campaigns, fix broken links, or A/B test landing pages. Dynamic codes are also physically smaller since they encode a short URL instead of a long one. Analytics tracking is built in, showing scan counts, locations, devices, and times. ## Cost Considerations Most dynamic QR code services charge monthly fees ranging from free (limited scans) to $50+/month for enterprise features. Compare this against the cost of reprinting static codes when changes are needed. For one-time-use codes, static is more cost-effective. ## Implementation Best Practices Choose a reliable provider with strong uptime guarantees — a down redirect service means all your codes stop working. Use your own domain for redirect URLs to maintain brand consistency and avoid dependency on a single provider. Always have a fallback plan if the redirect service becomes unavailable. ## When to Choose Static Instead Static codes are preferable when the destination never changes (product serial numbers, permanent URLs), when you need the code to work offline or without internet, or when you want to avoid ongoing subscription costs. Static codes also have no single point of failure — they work as long as the destination exists. ### How to Validate and Format Data Formats Validate JSON, XML, YAML, and CSV data for structural correctness and format them for readability. - URL: https://peasydev.com/guides/how-to-validate-format-data-formats/ - Category: How-To - Reading time: 1 min - Words: 292 Key takeaways: - Invalid data causes silent failures, corrupted imports, and hard-to-trace bugs downstream. - ### Browser-Based Validation Client-side validators process data locally without uploading to servers — important for sensitive configuration files and data. - ### JSON Validation Common JSON errors: trailing commas (valid in JavaScript, invalid in JSON), single quotes (must be double quotes), unquoted keys, comments (not allowed in standard JSON), and control characters in strings. ## Data Format Validation Invalid data causes silent failures, corrupted imports, and hard-to-trace bugs downstream. Validating data format correctness before processing catches problems at the point of entry. ### JSON Validation Common JSON errors: trailing commas (valid in JavaScript, invalid in JSON), single quotes (must be double quotes), unquoted keys, comments (not allowed in standard JSON), and control characters in strings. A JSON validator checks syntax and reports the exact line and character position of errors. Pretty-printing formatted JSON makes structural errors visible. ### XML Validation XML has two levels of correctness. Well-formed XML follows syntax rules: every open tag has a close tag, attributes are quoted, and special characters are escaped. Valid XML additionally conforms to a schema (DTD, XSD) that defines allowed elements, attributes, and data types. Validation against a schema catches semantic errors like missing required fields. ### YAML Validation YAML errors are often caused by indentation problems: mixing tabs and spaces, inconsistent indent levels, and missing indentation for block content. YAML's implicit type coercion also causes validation issues: values that look like numbers, booleans, or dates are converted automatically. Use quoting to prevent unintended type conversion. ### CSV Validation CSV validation checks: consistent column count across all rows, proper quoting of fields containing delimiters or newlines, matching quote characters (no unclosed quotes), and correct character encoding (UTF-8 with or without BOM). Column headers should be unique and not contain special characters that could be misinterpreted. ### Browser-Based Validation Client-side validators process data locally without uploading to servers — important for sensitive configuration files and data. Paste or upload your data, see errors highlighted with line numbers, and use auto-format features to fix indentation and spacing. Some validators also convert between formats (JSON ↔ YAML ↔ TOML) for convenience. ### CSS Architecture: BEM, SMACSS, and ITCSS Compared Large CSS codebases become unmaintainable without architecture. Compare the three most popular CSS methodologies and learn which suits your project. - URL: https://peasydev.com/guides/css-architecture-bem-smacss-itcss/ - Category: Comparison - Reading time: 1 min - Words: 227 ## Why CSS Architecture Matters CSS has no built-in scoping or encapsulation. Every rule is global, and specificity conflicts grow exponentially with codebase size. CSS architecture methodologies provide naming conventions and organizational patterns to maintain order. ### BEM (Block Element Modifier) BEM structures class names as `.block__element--modifier`. A card component becomes `.card`, its title becomes `.card__title`, and a highlighted variant becomes `.card--featured`. BEM's flat specificity (everything is a single class) eliminates specificity wars. The verbose naming is its main criticism, but it makes relationships between components explicit. ### SMACSS (Scalable and Modular Architecture for CSS) SMACSS categorizes CSS into five types: Base (reset/normalize), Layout (grid systems, page sections), Module (reusable components), State (is-active, is-hidden), and Theme (visual variations). This separation makes it clear where new styles should go and where to look for existing ones. ### ITCSS (Inverted Triangle CSS) ITCSS organizes styles from generic to specific, creating an inverted triangle of specificity. Layers from broadest to narrowest: Settings, Tools, Generic, Elements, Objects, Components, Utilities. Each layer has higher specificity than the last, eliminating specificity conflicts by design. ### Choosing the Right Architecture BEM is the simplest to adopt and works well for component-based projects. SMACSS suits content-heavy sites with distinct page types. ITCSS provides the most rigorous organization for large teams. In practice, many teams combine elements — using BEM naming within an ITCSS layer structure. ### How to Debug API Requests and Responses Inspect HTTP headers, request bodies, response codes, and timing to diagnose API integration issues. - URL: https://peasydev.com/guides/how-to-debug-api-requests-responses/ - Category: How-To - Reading time: 1 min - Words: 298 ## Debugging API Requests API integration issues manifest in many ways: unexpected response codes, malformed payloads, authentication failures, and timeout errors. Systematic debugging isolates the problem layer by layer. ### HTTP Status Code Diagnosis Start with the status code. 4xx errors are client-side issues: 400 means your request body is malformed, 401 means authentication failed, 403 means your credentials lack permission, 404 means the endpoint doesn't exist, 422 means the request is syntactically valid but semantically wrong, 429 means you're rate-limited. 5xx errors are server-side: 500 is an unhandled exception, 502/503/504 indicate infrastructure problems. ### Request Inspection Compare your actual request against the API documentation. Check: HTTP method (GET vs POST), Content-Type header (application/json vs multipart/form-data), authentication header format (Bearer vs Basic vs API key), URL encoding of parameters, and request body structure. A common mistake is sending JSON with Content-Type: application/x-www-form-urlencoded. ### Response Analysis Parse the response body for error messages — many APIs return detailed error descriptions in JSON format. Check the Content-Type of the response: receiving text/html instead of application/json usually means you're hitting a load balancer error page or wrong endpoint. Check response headers for rate limit information (X-RateLimit-Remaining, Retry-After). ### Timing and Timeout Issues Network timeouts can occur at multiple layers: DNS resolution, TCP connection, TLS handshake, time to first byte, and content download. Browser-based API testing tools show timing breakdowns for each phase. If requests work locally but fail in production, check whether your production environment has different network constraints (proxy, firewall, egress rules). ### Reproducibility Document the exact request that fails: method, URL, headers, body, and the response received. Use curl commands or tool-specific request formats that can be shared with the API provider's support team. Include timestamps, since intermittent failures may correlate with the provider's maintenance windows or traffic patterns. ### Fixing Video Playback Issues in Browsers Troubleshoot common HTML5 video playback problems including codec errors, autoplay blocks, and CORS. - URL: https://peasydev.com/guides/fixing-video-playback-issues-browsers/ - Category: Troubleshooting - Reading time: 1 min - Words: 271 Key takeaways: - HTML5 video playback can fail for numerous reasons: unsupported codecs, CORS restrictions, autoplay policies, missing server configuration, or memory limitations. - The most common failure is a codec mismatch. - Modern browsers block autoplay with audio to prevent annoying user experiences. - Videos served from a different domain require proper CORS headers. - Large video files can cause memory issues on mobile devices. ## Common Playback Failures HTML5 video playback can fail for numerous reasons: unsupported codecs, CORS restrictions, autoplay policies, missing server configuration, or memory limitations. Systematic diagnosis starts with the browser console — video errors appear there before any visual indication. ## Codec Compatibility Issues The most common failure is a codec mismatch. Safari requires H.264 in MP4 containers. Firefox and Chrome support VP9/WebM in addition to H.264. Some H.264 profiles (High 4:4:4) aren't supported in hardware decoders. Use the HTML5 source element to provide multiple formats. As a universal fallback, H.264 Baseline or Main profile in MP4 works everywhere. ## Autoplay Restrictions Modern browsers block autoplay with audio to prevent annoying user experiences. Chrome, Firefox, and Safari all require user interaction before playing audio. Solutions: use the muted attribute for autoplay (always works), add playsinline for iOS Safari, or trigger playback in response to a user click event. The play() Promise rejection is the most common JavaScript error for video. ## CORS and Server Configuration Videos served from a different domain require proper CORS headers. The server must return Access-Control-Allow-Origin headers. Additionally, the server must support range requests (Accept-Ranges: bytes) for seeking to work properly. Missing Content-Type headers can cause browsers to refuse playback. Check that your server returns the correct MIME type (video/mp4, video/webm). ## Performance and Memory Large video files can cause memory issues on mobile devices. Implement adaptive bitrate streaming (HLS or DASH) for videos longer than a few minutes. Lazy-load videos that are below the fold. Use the preload attribute wisely — preload="none" prevents unnecessary bandwidth usage, preload="metadata" loads duration and dimensions without downloading the full file. ### Advanced Regex Patterns for Log File Analysis Log files contain critical diagnostic information buried in semi-structured text. Master regex patterns to extract timestamps, error codes, IP addresses, and stack traces. - URL: https://peasydev.com/guides/advanced-regex-log-analysis/ - Category: How-To - Reading time: 1 min - Words: 208 ## Log File Structure Most log files follow a predictable pattern: timestamp, severity level, component name, and message. However, multi-line entries (stack traces, JSON payloads) and inconsistent formatting across different services make automated extraction challenging. ### Essential Patterns Timestamp extraction handles multiple formats: - ISO 8601: `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})` - Common Log Format: `\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} [+-]\d{4}` - Syslog: `\w{3}\s+\d{1,2} \d{2}:\d{2}:\d{2}` IP address matching uses: `\b(?:\d{1,3}\.){3}\d{1,3}\b` for IPv4. For IPv6, the pattern is considerably more complex due to abbreviation rules. ### Error Pattern Extraction Match error codes and their context using capturing groups. For HTTP status codes: `HTTP/\d\.\d"\s+(\d{3})\s+`. For stack traces, match the exception line first, then greedily capture indented lines below it. ### Performance Tips Anchor your patterns where possible — `^` for line starts and `$` for line ends dramatically improve matching speed in large files. Avoid catastrophic backtracking by using possessive quantifiers or atomic groups when nesting quantifiers. Test your patterns against a sample of your actual log data before running against gigabytes of production logs. ### Building a Log Analysis Workflow Chain multiple regex operations: first filter by severity level, then extract timestamps and messages from matching lines, and finally aggregate by error type or time window. This layered approach is more maintainable than a single monolithic pattern. ### Barcode Formats Compared: Code 128 vs Code 39 vs EAN Compare popular 1D barcode formats for density, character support, and industry requirements. - URL: https://peasydev.com/guides/barcode-formats-code128-code39-ean-comparison/ - Category: Comparison - Reading time: 1 min - Words: 240 Key takeaways: - One-dimensional barcodes remain essential in retail, logistics, and manufacturing. - Code 128 supports all 128 ASCII characters and produces the most compact barcodes of any 1D format. - Code 39 supports uppercase letters, digits, and a few special characters. - EAN-13 (international) and UPC-A (North America) are fixed-length numeric-only formats designed specifically for retail point-of-sale. - For general-purpose labeling with full character support, use Code 128. ## 1D Barcode Format Landscape One-dimensional barcodes remain essential in retail, logistics, and manufacturing. The three most common formats — Code 128, Code 39, and EAN — serve different needs. Understanding their differences helps you choose the right format for your application. ## Code 128: High-Density Universal Code 128 supports all 128 ASCII characters and produces the most compact barcodes of any 1D format. It uses three character sets (A, B, C) and automatically switches between them for optimal density. Code 128 is the go-to choice for shipping labels (GS1-128), inventory management, and any application where space is limited. ## Code 39: Simple and Widely Supported Code 39 supports uppercase letters, digits, and a few special characters. It's self-checking (no checksum digit required), making it simple to implement. While less dense than Code 128, its simplicity and near-universal scanner support make it popular in government, military (LOGMARS), and automotive (AIAG) applications. ## EAN/UPC: Retail Standard EAN-13 (international) and UPC-A (North America) are fixed-length numeric-only formats designed specifically for retail point-of-sale. They include a GS1 company prefix that uniquely identifies the manufacturer. These formats are mandatory for products sold through retail channels. ## Choosing the Right Format For general-purpose labeling with full character support, use Code 128. For compliance with specific industry standards, check the required format. For retail products, EAN-13 or UPC-A is non-negotiable. Consider scanner compatibility — older scanners may not support Code 128 but will read Code 39. ### Unicode Normalization: NFC, NFD, NFKC, NFKD Explained The same visible character can have multiple Unicode representations. Learn when and how to normalize text to prevent comparison failures and search issues. - URL: https://peasydev.com/guides/unicode-normalization-forms-explained/ - Category: Best Practice - Reading time: 1 min - Words: 249 ## The Normalization Problem Unicode allows the same visual character to be represented in multiple ways. The letter "e" (e-acute) can be a single code point (U+00E9) or a combination of "e" (U+0065) + combining acute accent (U+0301). These look identical but fail string comparison. ### The Four Normalization Forms NFC (Canonical Decomposition, followed by Canonical Composition) composes characters where possible. This is the most common web standard and what most applications expect. NFD (Canonical Decomposition) decomposes composed characters into base characters plus combining marks. NFKC and NFKD additionally handle compatibility equivalences — for example, converting the Roman numeral "IV" (single character) to separate "I" and "V" characters. ### When to Normalize Normalize text at system boundaries: when receiving user input, importing data, and before storing in a database. Use NFC for web content (W3C recommendation), database storage, and general-purpose text. Use NFKC for search indexing and string comparison where visual similarity matters more than semantic precision. ### Real-World Impact Without normalization, a search for "cafe" won't match "cafe" if one uses NFC and the other NFD encoding of the accent. File names with accented characters can create "duplicate" files that differ only in normalization form. URLs containing Unicode characters must be normalized to prevent routing failures. ### Platform Differences macOS file systems use NFD normalization, while Windows uses NFC. This means copying files between operating systems can change filename byte sequences. Linux file systems are normalization-agnostic, which can result in visually identical filenames coexisting in the same directory. ### QR Code Design: Branding Without Breaking Scannability Design branded QR codes with custom colors, logos, and shapes while maintaining reliable scanning. - URL: https://peasydev.com/guides/qr-code-branding-design-scannability/ - Category: Best Practice - Reading time: 1 min - Words: 234 Key takeaways: - Branded QR codes can increase scan rates by 30-50% compared to plain black-and-white codes. - The three finder patterns (large squares in corners) must maintain their shape and contrast — they're how scanners locate and orient the code. - Dark modules must be darker than light modules — this sounds obvious but is often violated with brand colors. - Place logos in the center of the code, covering no more than 10% of the total area at Level M correction, or 20% at Level H. - Generate branded codes and test with at least five different devices across iOS and Android. ## Balancing Aesthetics and Function Branded QR codes can increase scan rates by 30-50% compared to plain black-and-white codes. However, excessive customization can render codes unscannable. The key is understanding which elements can be modified and which are critical for scanner recognition. ## Safe Customization Areas The three finder patterns (large squares in corners) must maintain their shape and contrast — they're how scanners locate and orient the code. The quiet zone (white border) must remain clear. Data modules in the center can tolerate more modification since error correction can compensate. ## Color Guidelines Dark modules must be darker than light modules — this sounds obvious but is often violated with brand colors. Minimum contrast ratio is 4:1. Avoid red-green combinations as they fail for colorblind users. Light backgrounds with dark modules work best; inverted codes (light on dark) have lower scan rates. ## Logo Insertion Techniques Place logos in the center of the code, covering no more than 10% of the total area at Level M correction, or 20% at Level H. Use a clean white or matching-background border around the logo. Never place logos over finder patterns or alignment patterns. ## Testing Protocol Generate branded codes and test with at least five different devices across iOS and Android. Test at various distances, angles, and lighting conditions. Create a comparison matrix documenting scan success rates for each design variant before committing to production. ### Text Diff and Merge Tools Compared Compare text comparison tools for code review, document editing, and content management. - URL: https://peasydev.com/guides/text-diff-merge-tools-compared/ - Category: Comparison - Reading time: 1 min - Words: 237 Key takeaways: - Comparing text versions is fundamental to software development (code review), content management (document revisions), and quality assurance (translation verification). - Line-level diff (traditional) highlights entire changed lines but doesn't show which specific words changed within a line. - Git diff is the standard for version-controlled files. - VS Code's built-in diff viewer handles most development needs. - When two people edit the same file independently, three-way merge compares both versions against the common ancestor to identify non-conflicting changes (automatically mergeable) and conflicts (requiring human decision). ## Why Text Diff Tools Matter Comparing text versions is fundamental to software development (code review), content management (document revisions), and quality assurance (translation verification). The right diff tool saves hours of manual comparison and catches changes that human eyes miss. ## Character-Level vs Line-Level Diff Line-level diff (traditional) highlights entire changed lines but doesn't show which specific words changed within a line. Character-level diff highlights the exact characters that changed — much more useful for code review and document editing. Word-level diff is a middle ground that's ideal for prose where character-level changes are too granular. ## Command-Line Tools Git diff is the standard for version-controlled files. diff (Unix) handles basic file comparison. colordiff adds syntax highlighting. delta and diff-so-fancy improve Git diff output. For structured data, specialized tools exist: jq for JSON diff, xmldiff for XML, and daff for CSV comparison. ## GUI and Web Tools VS Code's built-in diff viewer handles most development needs. Beyond Compare (paid) offers three-way merge and folder comparison. Meld (free, Linux/Mac) provides clean side-by-side comparison. For one-off comparisons, online tools provide immediate results without installation. Web-based tools process text client-side for privacy. ## Three-Way Merge When two people edit the same file independently, three-way merge compares both versions against the common ancestor to identify non-conflicting changes (automatically mergeable) and conflicts (requiring human decision). Git uses this automatically. Understanding three-way merge helps you resolve merge conflicts more confidently and correctly. ### SVG Optimization and Best Practices Optimize SVG files for web performance by removing unnecessary elements, minifying code, and choosing the right export settings. - URL: https://peasydev.com/guides/svg-optimization-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 279 ## SVG Optimization SVG files from design tools contain substantial bloat: editor metadata, unused definitions, redundant groups, excessive precision, and embedded raster images. Optimization can reduce SVG file size by 30-80%. ### Common Bloat Sources Design tools embed metadata (Illustrator, Figma, Sketch identifiers), unused gradients and filters, empty groups, redundant transforms, and coordinates with 15 decimal places of precision. A simple icon might be 10KB from Illustrator but 1KB after optimization. These extra bytes add up when a page loads dozens of SVG icons. ### Optimization Techniques Remove editor metadata and comments. Collapse unnecessary groups. Convert shapes to paths where simpler. Round coordinates to 1-2 decimal places (visually imperceptible). Remove unused definitions (gradients, filters, clip paths). Merge overlapping paths. Convert absolute commands to relative where shorter. ### Embedding Strategies Inline SVGs load with the HTML — no additional requests but larger initial HTML. External SVG files can be cached independently. SVG sprites (using symbol and use) combine multiple icons into one file. For icon systems, sprites with a cache header provide the best balance of performance and maintainability. ### Accessibility SVGs need proper accessibility markup. Add role="img" for decorative images and aria-label or title elements for informative images. For complex SVGs (charts, diagrams), add desc elements with detailed descriptions. Ensure sufficient color contrast — SVG content is subject to the same WCAG requirements as any other visual content. ### Animation Performance CSS animations on SVGs are generally smooth, but animating complex paths or filters can cause jank. Use transform (translate, rotate, scale) and opacity for smooth animations — these properties are GPU-accelerated. Avoid animating d (path data), which requires the browser to recalculate the entire path on every frame. ### Regular Expressions: Pattern Matching Essentials Master fundamental regex patterns for text search, validation, and transformation tasks. - URL: https://peasydev.com/guides/regular-expressions-pattern-matching-essentials/ - Category: How-To - Reading time: 1 min - Words: 223 Key takeaways: - Regular expressions (regex) are pattern descriptions for matching text. - Character classes: [a-z] matches any lowercase letter, [0-9] any digit, [A-Za-z0-9_] any word character (shorthand: \w). - Email validation: ^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$ (simplified). - Parentheses create capture groups: (\d{4})-(\d{2})-(\d{2}) captures year, month, day separately. - Build patterns incrementally — start simple and add complexity. ## Why Regular Expressions Regular expressions (regex) are pattern descriptions for matching text. They're used in every programming language, text editor, and command-line tool for search, validation, and transformation. A single regex pattern can replace dozens of lines of string manipulation code. ## Essential Patterns Character classes: [a-z] matches any lowercase letter, [0-9] any digit, [A-Za-z0-9_] any word character (shorthand: \w). Quantifiers: * (zero or more), + (one or more), ? (zero or one), {3} (exactly 3), {2,5} (2 to 5). Anchors: ^ (start of line), $ (end of line), \b (word boundary). ## Common Use Cases Email validation: ^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$ (simplified). Phone numbers: \+?\d{1,3}[-.\s]?\(?\d{1,4}\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}. IP addresses: \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b. URLs: https?://[\w\-]+(\.[\w\-]+)+[/\w\-.?=&#%]*. Note: production validation should use dedicated parsers, not regex alone. ## Groups and Backreferences Parentheses create capture groups: (\d{4})-(\d{2})-(\d{2}) captures year, month, day separately. Backreferences (\1, \2) refer to captured groups in replacement patterns. Named groups (?P<year>\d{4}) make patterns self-documenting. Non-capturing groups (?:...) group without capturing (better performance). ## Debugging Regex Build patterns incrementally — start simple and add complexity. Use online regex testers (regex101.com) that explain each part of your pattern and highlight matches in real-time. Watch for greedy vs lazy quantifiers: .* matches as much as possible (greedy), .*? matches as little as possible (lazy). Test with edge cases: empty strings, very long strings, special characters, and strings that should NOT match. ### How to Generate Secure API Keys Create cryptographically secure API keys with proper entropy, formatting, and management practices. - URL: https://peasydev.com/guides/how-to-generate-secure-api-keys/ - Category: How-To - Reading time: 2 min - Words: 300 Key takeaways: - API keys authenticate applications and services. - For security-critical APIs, enforce key expiration (90-365 days) with automated renewal. - ### Secure Storage Never embed API keys in source code or client-side applications. ## Generating Secure API Keys API keys authenticate applications and services. A weak or predictable key is equivalent to no authentication. Proper key generation ensures keys are unguessable and resistant to brute-force attacks. ### Entropy Requirements API keys should have at least 128 bits of entropy (16 random bytes). This produces approximately 3.4 × 10^38 possible values — computationally infeasible to brute-force. 256 bits (32 random bytes) is better for long-lived keys. Use the operating system's CSPRNG (cryptographically secure pseudo-random number generator): `crypto.getRandomValues()` in browsers, `/dev/urandom` on Linux, `CryptGenRandom` on Windows. ### Encoding and Format Encode random bytes as hex (32-64 characters) or base64url (22-43 characters). Include a recognizable prefix for the service: `pk_live_` for production keys, `pk_test_` for test keys. This helps identify keys found in logs and prevents accidentally using test keys in production. Stripe's format (sk_live_...) is a good model. ### Key Rotation All API keys should have a rotation schedule. Offer two active keys simultaneously so applications can rotate without downtime: generate a new key, update the application to use the new key, verify it works, then revoke the old key. For security-critical APIs, enforce key expiration (90-365 days) with automated renewal. ### Secure Storage Never embed API keys in source code or client-side applications. Use environment variables on servers. For mobile apps, use the device's secure storage (Keychain on iOS, Keystore on Android). For CI/CD pipelines, use secret management services. API keys committed to Git repositories should be immediately revoked — the key's history in Git makes it permanently exposed. ### Rate Limiting and Monitoring Associate each API key with rate limits and usage quotas. Monitor for anomalous usage patterns: sudden volume spikes, requests from unexpected IP ranges, or access to unusual endpoints. Alert on failed authentication attempts — they may indicate a brute-force attack. ### How to Design RESTful API URL Structures Well-designed API URLs are intuitive, consistent, and follow REST conventions. Learn patterns for resource naming, versioning, filtering, and pagination. - URL: https://peasydev.com/guides/how-to-design-restful-api-urls/ - Category: How-To - Reading time: 1 min - Words: 193 ## REST URL Design Principles REST URLs should represent resources (nouns), not actions (verbs). Use plural nouns for collections, nested resources for relationships, and query parameters for filtering and pagination. ### Resource Naming Conventions Use lowercase with hyphens for multi-word resources: `/api/v1/user-profiles/` not `/api/v1/UserProfiles/`. Keep URLs shallow — avoid nesting beyond two levels. `/users/123/orders/456` is fine; `/users/123/orders/456/items/789/reviews` is too deep. Create a top-level `/reviews` endpoint instead. ### Versioning Strategies URL path versioning (`/api/v1/`, `/api/v2/`) is the most explicit and visible approach. Header versioning (`Accept: application/vnd.api.v2+json`) keeps URLs clean but is harder to test and debug. Query parameter versioning (`?version=2`) is simple but can conflict with caching. ### Filtering and Pagination Use query parameters for filtering: `/products?category=electronics&min_price=100`. For pagination, cursor-based pagination (using an opaque token) is more reliable than offset-based pagination for large datasets. Include `next` and `previous` links in your response for easy navigation. ### Common Mistakes Avoid verbs in URLs — use HTTP methods instead: `POST /orders/` not `POST /create-order`. Don't return different resource types from the same endpoint. Don't use query parameters for resource identification (`/users?id=123` should be `/users/123`). Always use HTTPS — API URLs should never work over plain HTTP. ### YAML vs JSON vs TOML for Configuration Files Compare configuration file formats for developer tools, CI/CD pipelines, and application settings. - URL: https://peasydev.com/guides/yaml-vs-json-vs-toml-configuration/ - Category: Comparison - Reading time: 1 min - Words: 281 ## Configuration File Format Comparison Configuration files define application behavior, build processes, and deployment settings. The format affects readability, error-proneness, and tooling support. ### JSON JSON is strict, unambiguous, and universally supported. Every programming language has a JSON parser. However, JSON lacks comments (a significant limitation for configuration files), requires quoted keys, doesn't support trailing commas, and requires escaping in multi-line strings. JSON is best when configuration is generated/consumed by machines, not edited by humans. ### YAML YAML is human-readable with minimal syntax: no brackets, no quotes (usually), and support for comments. But YAML's implicit type coercion is dangerous: `Norway: NO` becomes `Norway: false`, `version: 3.10` becomes `version: 3.1`, and `port: 0800` becomes `port: 512` (octal). Indentation-sensitivity causes subtle bugs when mixing tabs and spaces. Despite these issues, YAML dominates DevOps (Docker Compose, Kubernetes, GitHub Actions). ### TOML TOML uses an INI-inspired syntax with explicit types, comments, and multi-line strings. It avoids YAML's type coercion pitfalls: `version = "3.10"` stays a string. TOML is the standard for Rust (Cargo.toml) and Python (pyproject.toml) ecosystems. Its flat structure can be verbose for deeply nested configurations. TOML is best when humans edit configuration files frequently. ### Selection Guide For API responses and data exchange: JSON (universal parser support). For DevOps and infrastructure: YAML (industry standard, despite pitfalls). For project and tool configuration: TOML (type safety, readability). For settings that need comments: YAML or TOML (never JSON). For maximum safety against type coercion bugs: TOML or JSON (never YAML). ### Migration Path If your YAML configuration has bitten you with type coercion, migrating to TOML is usually straightforward. The structure maps directly; you mainly add quotes around values and convert indentation-based nesting to table headers. ### Git Hooks for Automated Code Quality Git hooks run scripts automatically before or after Git events. Set up pre-commit hooks for linting, formatting, and testing to catch issues before they reach your repository. - URL: https://peasydev.com/guides/git-hooks-automated-code-quality/ - Category: Best Practice - Reading time: 1 min - Words: 253 ## Why Git Hooks? Git hooks provide automatic quality gates in your development workflow. A pre-commit hook can run linters, formatters, and type checkers on staged files, catching issues before they're committed. A pre-push hook can run the full test suite before code leaves your machine. ### Essential Pre-Commit Hooks Lint staged files (not the entire project) for speed. Format code automatically — if the formatter changes a file, stage the changes and allow the commit. Check for debug statements, TODO comments, and hardcoded secrets. Validate file sizes to prevent accidental binary commits. Run type checking on changed files. ### Setting Up with pre-commit Framework The pre-commit framework (pre-commit.com) manages hook installation and execution. Define hooks in `.pre-commit-config.yaml`, and the framework handles virtual environments, caching, and updates. Hooks run only on staged files, keeping execution fast even in large repositories. ### Commit Message Hooks The commit-msg hook validates commit message format. Enforce conventional commit prefixes (feat:, fix:, docs:), minimum length, and ticket reference patterns. This enables automatic changelog generation and semantic versioning. ### Team Adoption Install hooks automatically when developers clone the repository. Add a setup script that runs `pre-commit install` or configure your package manager to include this step. Document which hooks are active and how to bypass them in emergencies (`git commit --no-verify` for rare exceptions). ### Performance Considerations Keep pre-commit hooks under 5 seconds for developer experience. Run expensive checks (full test suite, integration tests) in pre-push hooks or CI/CD instead. Cache results where possible — don't re-lint unchanged files. ### Environment Variable Management Best Practices Environment variables separate configuration from code, enabling the same application to run in development, staging, and production. Learn secure patterns for managing them. - URL: https://peasydev.com/guides/environment-variable-management-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 248 ## The Twelve-Factor Approach The Twelve-Factor App methodology stores configuration in environment variables. This separates secrets and deployment-specific settings from code, preventing accidental commits of API keys and enabling the same codebase to run across environments. ### .env Files for Local Development Use a `.env` file for local development, loaded by your application framework. Include `.env` in `.gitignore` to prevent secrets from reaching version control. Provide a `.env.example` with placeholder values documenting all required variables. ### Required vs Optional Variables Validate all required environment variables at application startup. Fail fast with a clear error message listing missing variables rather than crashing deep in business logic when a variable is first accessed. For optional variables, define sensible defaults in code. ### Secret Management in Production Never store secrets in environment variables on disk (`.bashrc`, `docker-compose.yml`). Use a secrets manager — AWS Secrets Manager, HashiCorp Vault, 1Password, or your platform's native secrets store. Inject secrets at runtime, not build time. Rotate secrets regularly and audit access. ### Naming Conventions Use SCREAMING_SNAKE_CASE for environment variables. Prefix with your application name to avoid conflicts: `MYAPP_DATABASE_URL`. Group related variables: `MYAPP_SMTP_HOST`, `MYAPP_SMTP_PORT`, `MYAPP_SMTP_USER`. Use `_URL` suffixes for connection strings that combine host, port, credentials, and database name. ### Common Pitfalls Don't use environment variables for complex structured data — they're strings, not JSON objects. Don't share the same secrets across environments. Don't log environment variables at startup (leaks secrets). Don't use environment variables for feature flags — use a dedicated feature flag service instead. ### API Testing and Debugging with Developer Tools Test REST APIs effectively using browser DevTools, curl, and dedicated API testing tools. - URL: https://peasydev.com/guides/api-testing-debugging-developer-tools/ - Category: How-To - Reading time: 1 min - Words: 278 Key takeaways: - API testing verifies that endpoints return correct data, handle errors gracefully, and perform within acceptable latency. - The Network tab shows every HTTP request your application makes. - curl is the most universal API testing tool — available on every platform. - Postman provides a GUI for building requests, organizing them into collections, and running automated tests. - 401 Unauthorized: check authentication headers and token expiration. ## API Testing Fundamentals API testing verifies that endpoints return correct data, handle errors gracefully, and perform within acceptable latency. Unlike UI testing, API tests are fast, reliable, and provide direct feedback on backend functionality. Every developer should be comfortable testing APIs manually and automating those tests. ## Browser DevTools Network Tab The Network tab shows every HTTP request your application makes. Filter by XHR/Fetch to see API calls. Inspect request headers, body, and response data. Right-click any request to copy as curl — this gives you a command-line equivalent with all headers and cookies. The timing breakdown shows DNS, connection, TTFB, and download times. ## curl for Direct API Testing curl is the most universal API testing tool — available on every platform. Basic GET: curl -s https://api.example.com/users | jq. POST with JSON: curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' https://api.example.com/users. Add -v for verbose output showing headers. Add -w '\n%{http_code}' to display the status code. ## Dedicated API Testing Tools Postman provides a GUI for building requests, organizing them into collections, and running automated tests. Insomnia offers a similar experience with a cleaner interface. HTTPie is a friendlier command-line alternative to curl with colored output and intuitive syntax. For load testing, k6 and Apache Bench (ab) measure performance under concurrent requests. ## Common API Issues 401 Unauthorized: check authentication headers and token expiration. 403 Forbidden: valid auth but insufficient permissions. 404 Not Found: verify the URL path and HTTP method. 422 Unprocessable: check request body format and required fields. 500 Internal Server Error: server-side issue — check server logs. CORS errors: browser security policy blocking cross-origin requests — the server needs to set Access-Control-Allow-Origin headers. ### QR Codes for Healthcare: Patient Safety and Medication Tracking Healthcare facilities use QR codes on patient wristbands, medication packaging, and equipment to reduce errors and improve traceability. Learn the standards and best practices for medical QR implementations. - URL: https://peasydev.com/guides/qr-codes-healthcare-medication-tracking/ - Category: use-case - Reading time: 2 min - Words: 305 Key takeaways: - QR codes on patient wristbands encode a unique identifier that links to electronic health records. - The FDA requires unique device identification (UDI) on medical devices and encourages barcode or QR-based verification for pharmaceuticals. - Hospitals attach QR codes to mobile equipment (IV pumps, wheelchairs, monitors) for location tracking and maintenance scheduling. - QR codes in healthcare must comply with HIPAA (US), GDPR (EU), and local privacy regulations. - ## Data Privacy Considerations QR codes in healthcare must comply with HIPAA (US), GDPR (EU), and local privacy regulations. ## Patient Identification QR codes on patient wristbands encode a unique identifier that links to electronic health records. Staff scan the wristband before administering medication, drawing blood, or performing procedures. This prevents misidentification errors — a leading cause of adverse events in hospitals. **Key requirements:** - High contrast (black on white) for reliable scanning under fluorescent lighting - Error correction level Q or H (wristbands get wet, wrinkled, and smudged) - Minimum 15mm module size for bedside scanners - Encoding a short patient ID rather than PHI directly ## Medication Verification The FDA requires unique device identification (UDI) on medical devices and encourages barcode or QR-based verification for pharmaceuticals. A QR code on medication packaging can encode the NDC (National Drug Code), lot number, expiration date, and serial number. **Five Rights verification:** 1. Right patient (scan wristband) 2. Right drug (scan medication QR) 3. Right dose (system cross-checks) 4. Right route (system alerts) 5. Right time (system validates schedule) ## Equipment and Asset Tracking Hospitals attach QR codes to mobile equipment (IV pumps, wheelchairs, monitors) for location tracking and maintenance scheduling. Scanning logs the equipment's current location and triggers maintenance alerts based on usage hours or calendar intervals. ## Data Privacy Considerations QR codes in healthcare must comply with HIPAA (US), GDPR (EU), and local privacy regulations. Never encode protected health information directly in the QR code — use a reference ID that resolves through an authenticated system. The QR code itself should be meaningless without database access. ## Implementation Checklist | Requirement | Specification | |-------------|---------------| | Error correction | Level Q minimum (H for wristbands) | | Print material | Medical-grade adhesive, waterproof | | Scanner type | 2D imager (not laser) | | Encoding format | Alphanumeric ID, no PHI | | Backup system | Manual ID … ### HTTP Status Codes: A Developer's Quick Reference Choosing the right HTTP status code communicates your API's intent clearly. Learn when to use each status code family and the most important codes in each range. - URL: https://peasydev.com/guides/http-status-codes-quick-reference/ - Category: How-To - Reading time: 1 min - Words: 296 ## The Five Families HTTP status codes are grouped into five families: 1xx (informational), 2xx (success), 3xx (redirection), 4xx (client error), and 5xx (server error). Each family communicates a different class of response. ### 2xx Success Codes 200 OK — the standard success response for GET and PUT requests. 201 Created — return this for successful POST requests that create a resource, with a Location header pointing to the new resource. 204 No Content — use for successful DELETE requests or updates that return no body. 202 Accepted — the request is queued for processing but not yet complete (asynchronous operations). ### 3xx Redirection Codes 301 Moved Permanently — the resource has a new URL permanently; search engines transfer ranking. 302 Found — temporary redirect; search engines keep indexing the original URL. 304 Not Modified — the resource hasn't changed since the client's last request (used with caching headers). ### 4xx Client Error Codes 400 Bad Request — the request body or parameters are malformed. Include a descriptive error message. 401 Unauthorized — authentication is required or the provided credentials are invalid. 403 Forbidden — the authenticated user doesn't have permission. 404 Not Found — the resource doesn't exist. 409 Conflict — the request conflicts with the current state (e.g., duplicate email). 422 Unprocessable Entity — the request is syntactically correct but semantically invalid (validation errors). 429 Too Many Requests — rate limit exceeded; include a Retry-After header. ### 5xx Server Error Codes 500 Internal Server Error — an unexpected error occurred; log the details server-side. 502 Bad Gateway — the server acting as proxy received an invalid response from upstream. 503 Service Unavailable — the server is temporarily overloaded or in maintenance; include Retry-After. 504 Gateway Timeout — the upstream server didn't respond in time. ### QR Code Tracking and Analytics: Measuring Scan Performance Without analytics, QR codes are a black box — you know they exist but not whether anyone scans them. Tracking scan volume, location, device type, and time patterns transforms QR codes into a measurable marketing channel. - URL: https://peasydev.com/guides/qr-code-tracking-analytics/ - Category: How-To - Reading time: 2 min - Words: 324 Key takeaways: - Dynamic QR codes route through a redirect server that logs each scan event. - Append UTM parameters to the destination URL encoded in the QR code: - Restaurant QR menus peak at lunch (11 AM-1 PM) and dinner (6-9 PM). ## What QR Analytics Can Track Dynamic QR codes route through a redirect server that logs each scan event. The redirect captures: - **Scan count** — Total and unique scans - **Timestamp** — When each scan occurred (hour, day, week patterns) - **Geolocation** — City/country based on IP address - **Device type** — iOS vs. Android, specific models - **Referrer context** — Which physical location the code was placed at ## Setting Up Tracking ### Method 1: UTM Parameters Append UTM parameters to the destination URL encoded in the QR code: `https://example.com/menu?utm_source=qr&utm_medium=table-tent&utm_campaign=spring-2026` This lets Google Analytics attribute traffic to specific QR code placements. Use unique utm_campaign values for each physical location or print run. ### Method 2: Short URL Services Services like Bitly and QR-specific platforms provide dashboards showing scan metrics over time. Each short URL acts as a unique tracking pixel. ### Method 3: Self-Hosted Redirects For full data ownership, set up a simple redirect server that logs scan events to your database. A minimal implementation is a web server that reads the QR code ID from the URL, logs the request metadata, and returns a 301 redirect. ## Interpreting Scan Data ### Time Patterns Restaurant QR menus peak at lunch (11 AM-1 PM) and dinner (6-9 PM). Retail product QR codes peak on weekends. Marketing collateral QR codes show spikes on the day of distribution followed by a steep decline. ### Location Insights If a QR code on in-store signage generates scans from a distant city, the code has been photographed and shared online. This is valuable organic distribution. ## Actionable Metrics | Metric | Healthy Range | Action If Low | |--------|-------------|---------------| | Scan rate | 5-15% of viewers | Improve placement or CTA text | | Unique/total ratio | > 70% | Multiple rescans suggest broken … ### Barcode Symbology Comparison: EAN, UPC, Code 128, and More Different barcode formats serve different purposes — retail products use EAN/UPC, shipping uses Code 128, and healthcare uses DataMatrix. Choosing the wrong symbology causes scanning failures and compliance violations. - URL: https://peasydev.com/guides/barcode-symbology-comparison/ - Category: Comparison - Reading time: 2 min - Words: 337 ## One-Dimensional (Linear) Barcodes ### EAN-13 (International Article Number) The global standard for retail products. Encodes 13 digits: country prefix (2-3 digits), manufacturer code, product code, and a check digit. Required for products sold in supermarkets, retail chains, and online marketplaces worldwide. EAN-8 is a compact variant for small packaging. ### UPC-A (Universal Product Code) The North American retail standard. Encodes 12 digits. Functionally equivalent to EAN-13 (a UPC-A is an EAN-13 with a leading zero). If you sell only in the US/Canada, UPC-A is sufficient. For international sales, register for an EAN. ### Code 128 A high-density barcode supporting the full ASCII character set (letters, numbers, symbols). Used in shipping labels (GS1-128/EAN-128), inventory management, and any application requiring alphanumeric data. Three subsets (A, B, C) optimize for different character ranges. ### Code 39 An older alphanumeric symbology still used in automotive (AIAG labels), defense (MIL-STD-1189), and some healthcare applications. Lower density than Code 128 but simpler to implement and self-checking (no check digit required). ## Two-Dimensional Barcodes ### QR Code Encodes up to 4,296 alphanumeric characters in a square matrix. Readable from any angle with built-in error correction. Dominant in consumer-facing applications (marketing, payments, menus) because smartphone cameras scan them natively. ### DataMatrix Compact 2D barcode for small items. Encodes up to 2,335 alphanumeric characters. Preferred in healthcare (FDA UDI requirement), electronics (PCB marking), and aerospace. Can be printed as small as 2×2 mm. ## Selection Guide | Use Case | Recommended Symbology | Reason | |----------|----------------------|--------| | Retail products (global) | EAN-13 | Industry standard, GS1 registered | | Retail products (US/CA) | UPC-A | Compatible with EAN, simpler registration | | Shipping labels | GS1-128 | Encodes weight, dates, batch numbers | | Internal inventory | Code 128 | Flexible alphanumeric, high density | | Medical devices … ### API Rate Limiting: Strategies and Implementation Rate limiting protects APIs from abuse and ensures fair resource allocation. Learn common algorithms, response headers, and client-side handling strategies. - URL: https://peasydev.com/guides/api-rate-limiting-strategies/ - Category: Best Practice - Reading time: 1 min - Words: 255 ## Why Rate Limit Without rate limiting, a single misbehaving client can overwhelm your API, degrading service for all users. Rate limiting prevents abuse (scraping, brute-force attacks), ensures fair access, controls costs, and maintains service quality. ### Common Algorithms Fixed window: Count requests per time window (e.g., 100 requests per minute). Simple but allows burst traffic at window boundaries. Sliding window: Uses a moving time frame to smooth out the boundary problem. More accurate but slightly more complex. Token bucket: Tokens accumulate at a fixed rate; each request consumes a token. When the bucket is empty, requests are rejected. Allows controlled bursts while maintaining an average rate. Leaky bucket: Requests queue up and are processed at a constant rate. Smoothest output but adds latency. ### Response Headers Communicate rate limit status through standard headers: `X-RateLimit-Limit` (maximum requests per window), `X-RateLimit-Remaining` (requests remaining), `X-RateLimit-Reset` (Unix timestamp when the window resets), and `Retry-After` (seconds to wait before retrying, included with 429 responses). ### Client-Side Handling Check `X-RateLimit-Remaining` before making requests and slow down proactively. When receiving 429 Too Many Requests, respect the `Retry-After` header. Implement exponential backoff for retries: wait 1s, 2s, 4s, 8s between attempts. Add jitter (random delay) to prevent thundering herd problems when many clients retry simultaneously. ### Per-User vs Per-IP IP-based limiting is simpler but unfair to users behind corporate NAT (hundreds of users sharing one IP). API key or token-based limiting provides per-user fairness. Consider tiered limits: authenticated users get higher limits than anonymous requests. Geographic rate limiting can mitigate region-specific abuse. ### QR Codes for Business Cards: Creating Digital vCards A QR code on a business card lets recipients save contact information with a single scan instead of manual typing. Encoding vCard data correctly ensures compatibility across iOS, Android, and desktop contact apps. - URL: https://peasydev.com/guides/qr-codes-business-cards-vcards/ - Category: How-To - Reading time: 1 min - Words: 299 Key takeaways: - vCard (VCF) is the universal format for digital contact cards. - The entire vCard text is encoded directly into the QR code as plain text. - Every additional field increases QR code density. - Place the QR code on the back of the business card where it has maximum space. - Use static QR codes for business cards. ## The vCard Standard vCard (VCF) is the universal format for digital contact cards. Version 3.0 has the broadest compatibility, though version 4.0 adds features like instant messaging handles and relationship fields. A minimal vCard contains: ``` BEGIN:VCARD VERSION:3.0 FN:Jane Smith ORG:Acme Corp TITLE:Product Manager TEL;TYPE=WORK:+1-555-123-4567 EMAIL;TYPE=WORK:jane@acme.com URL:https://acme.com END:VCARD ``` ## Encoding vCards in QR Codes The entire vCard text is encoded directly into the QR code as plain text. When scanned, the phone recognizes the vCard format and offers to add the contact. Keep the vCard data minimal — more data creates a denser QR code that is harder to scan at small sizes. ## Data to Include vs. Exclude | Include | Exclude | |---------|--------| | Full name (FN) | Photo (dramatically increases QR density) | | Organization + Title | Physical address (unless essential) | | Phone (one number) | Multiple phone numbers | | Email (one address) | Social media profiles | | Website URL | Notes or extended biography | Every additional field increases QR code density. A vCard with name, phone, email, and URL creates a scannable code at 2×2 cm. Adding a photo or multiple addresses may require 4×4 cm to remain scannable. ## Design Integration Place the QR code on the back of the business card where it has maximum space. Minimum recommended size is 2×2 cm (20×20 mm) with error correction level M or H. Surround it with a quiet zone of at least 3 mm. Include a brief label such as 'Scan to save contact' to communicate the purpose. ## Static vs. Dynamic for Business Cards Use static QR codes for business cards. Contact information changes infrequently, and offline scanning reliability is important (no dependency on a redirect server). If you change jobs, you will be reprinting cards anyway. ### Video Container vs Codec: Understanding MP4, WebM, AVI, and MKV Demystify the relationship between video containers and codecs. Learn why changing a file extension does not convert video, and how to choose the right container-codec combination for your needs. - URL: https://peasydev.com/guides/video-container-vs-codec-mp4-webm-avi-mkv/ - Category: How-To - Reading time: 2 min - Words: 318 Key takeaways: - A container (MP4, WebM, MKV) is a wrapper that holds encoded video, audio, subtitles, and metadata. - For maximum browser compatibility, use MP4 with H.264 video and AAC audio. - Re-encoding video is computationally intensive. ## Containers and Codecs Are Different Things A container (MP4, WebM, MKV) is a wrapper that holds encoded video, audio, subtitles, and metadata. A codec (H.264, VP9, AV1) is the algorithm that compresses and decompresses the actual video data. Renaming a file from .avi to .mp4 does not re-encode the video — it just changes the wrapper, often producing a broken file. ## Container Comparison | Container | Common Codecs | Streaming | Subtitles | Patent Status | | --- | --- | --- | --- | --- | | MP4 (.mp4) | H.264, H.265, AAC | Yes | Limited | Patented codecs | | WebM (.webm) | VP8, VP9, AV1, Opus | Yes | WebVTT | Royalty-free | | MKV (.mkv) | Any codec | Limited | Extensive | Open format | | AVI (.avi) | Legacy codecs | No | Limited | Legacy | | MOV (.mov) | H.264, ProRes | Yes | Limited | Apple ecosystem | ## Codec Comparison | Codec | Compression | Speed | Quality | Browser Support | | --- | --- | --- | --- | --- | | H.264 | Good | Fast encode/decode | Good | Universal | | H.265 (HEVC) | 50% better than H.264 | Slow encode | Excellent | Safari, some others | | VP9 | Similar to H.265 | Medium | Excellent | Chrome, Firefox, Edge | | AV1 | 30% better than VP9 | Very slow encode | Best | Growing support | ## Choosing for the Web For maximum browser compatibility, use MP4 with H.264 video and AAC audio. For better compression, add a WebM (VP9/Opus) source and let browsers choose. AV1 offers the best quality per bit but encoding is computationally expensive. ## Conversion Tips Re-encoding video is computationally intensive. Use stream copying … ### Comparing QR Code Error Correction Levels QR codes use Reed-Solomon error correction to remain scannable even when partially damaged or obscured. This comparison explains the four correction levels and how to choose the right one for your specific use case. - URL: https://peasydev.com/guides/comparing-qr-code-error-correction-levels/ - Category: Comparison - Reading time: 3 min - Words: 592 Key takeaways: - QR codes embed redundant data using Reed-Solomon error correction codes, allowing scanners to recover the original information even if part of the code is damaged, dirty, or covered by a logo. - Level L recovers data if up to 7% of the code is damaged. - Higher error correction levels require more modules (the small squares that make up the code). - Use Level L for the smallest possible code. - Always test QR codes under real-world conditions. ## What Is QR Error Correction? QR codes embed redundant data using Reed-Solomon error correction codes, allowing scanners to recover the original information even if part of the code is damaged, dirty, or covered by a logo. The QR standard defines four error correction levels, each offering a different trade-off between data recovery capacity and the amount of data the code can store. ## The Four Levels ### Level L (Low) — 7% Recovery Level L recovers data if up to 7% of the code is damaged. It produces the smallest QR codes (fewest modules) because it devotes the least space to redundancy. Use Level L when the QR code will be displayed on a clean digital screen — website, app, or digital signage — where physical damage is unlikely. ### Level M (Medium) — 15% Recovery Level M is the default choice for most QR generators. It recovers from up to 15% damage, providing a reasonable safety margin for printed materials like business cards, flyers, and product packaging that may experience normal handling wear. ### Level Q (Quartile) — 25% Recovery Level Q handles up to 25% damage. It's appropriate for outdoor signage, warehouse labels, and industrial environments where codes may be exposed to moisture, dirt, or partial obstruction. The increased redundancy means the QR code needs to be larger (more modules) or must encode less data. ### Level H (High) — 30% Recovery Level H can recover from up to 30% damage. This is the required level when embedding a logo or image in the center of the QR code — the logo effectively 'damages' that region, and Level H ensures the remaining modules contain enough redundant data to reconstruct the full message. ## Size and Density Trade-offs ### Module Count Impact Higher error correction levels require more … ### WiFi QR Codes: Connecting Guests Without Sharing Passwords WiFi QR codes let guests connect to a network with a single scan, eliminating the need to dictate complex passwords. The encoding format is standardized and supported natively by iOS and Android camera apps. - URL: https://peasydev.com/guides/wifi-qr-codes-guest-networks/ - Category: How-To - Reading time: 2 min - Words: 305 Key takeaways: - WiFi QR codes use a standardized plain-text format that smartphone cameras recognize automatically: - The WiFi password is encoded in plain text inside the QR code. - Hospitality:** Hotels, Airbnb rentals, cafes — print and frame near the entrance - Print the QR code on a small card or sticker alongside the network name and password in text form. - The most common failure is an SSID mismatch — the SSID in the QR code must exactly match the router's broadcast name, including capitalization and spaces. ## The WiFi QR Format WiFi QR codes use a standardized plain-text format that smartphone cameras recognize automatically: ``` WIFI:T:WPA;S:MyNetworkName;P:MyPassword123;H:false;; ``` | Field | Value | Notes | |-------|-------|-------| | T | WPA, WEP, or nopass | Security type | | S | Network SSID | Case-sensitive | | P | Password | Plain text (security consideration) | | H | true/false | Whether SSID is hidden | ## Security Considerations The WiFi password is encoded in plain text inside the QR code. Anyone with a QR scanner can extract it. This is acceptable for guest networks but not for primary networks carrying sensitive traffic. **Best practice:** Create a dedicated guest network isolated from your main network. Set bandwidth limits on the guest network. Rotate the guest password periodically and regenerate the QR code. ## Use Cases - **Hospitality:** Hotels, Airbnb rentals, cafes — print and frame near the entrance - **Offices:** Visitor guest network in reception areas and meeting rooms - **Events:** Conference WiFi on event badges or signage - **Retail:** Customer WiFi in stores to encourage dwell time - **Home:** Guest bathroom or living room for visitors ## Presentation Tips Print the QR code on a small card or sticker alongside the network name and password in text form. Not all guests will know how to scan QR codes, and some devices may have older camera apps that do not support WiFi QR codes. The text fallback ensures universal access. ## Troubleshooting Scan Failures The most common failure is an SSID mismatch — the SSID in the QR code must exactly match the router's broadcast name, including capitalization and spaces. Special characters in the password (semicolons, colons, backslashes) must be escaped with a backslash in the encoded string. Test the QR code on a device that is not … ### Event Ticket QR Codes: Generation, Validation, and Security QR codes on event tickets must balance ease of scanning with resistance to duplication and fraud. A well-designed ticket QR system validates entry in under one second while preventing unauthorized copies. - URL: https://peasydev.com/guides/event-ticket-qr-codes-guide/ - Category: Best Practice - Reading time: 2 min - Words: 303 Key takeaways: - Each ticket QR code encodes a unique identifier — typically a UUID or cryptographically signed token. - Unique per ticket:** Never encode the same data in multiple QR codes - Scanner reads QR → sends identifier to server → server checks validity and marks as used → returns allow/deny. - The simplest fraud is screenshotting a QR code and sharing it. - At events with 1,000+ attendees, scan speed determines entry throughput. ## Ticket QR Code Architecture Each ticket QR code encodes a unique identifier — typically a UUID or cryptographically signed token. The identifier maps to a record in the event management database containing the ticket holder's information, ticket type, and validation status. ## Generation Best Practices - **Unique per ticket:** Never encode the same data in multiple QR codes - **Cryptographic signing:** Embed a digital signature that the scanner verifies offline, preventing forged QR codes - **Error correction level H:** Events involve physical handling (folding, pockets, rain) — maximum error correction prevents scan failures - **Minimum size:** 3×3 cm for reliable scanning at arm's length under variable lighting conditions ## Validation Workflow ### Online Validation Scanner reads QR → sends identifier to server → server checks validity and marks as used → returns allow/deny. Latency must be under 500ms to maintain entry throughput. Requires network connectivity at the venue. ### Offline Validation For venues without reliable connectivity, embed a cryptographic signature in the QR data itself. The scanner verifies the signature against a pre-shared public key without contacting the server. Trade-off: offline validation cannot detect duplicate use in real time. ## Preventing Fraud ### Screenshot Duplication The simplest fraud is screenshotting a QR code and sharing it. Mitigate with first-scan-wins policy (the first person to scan enters, duplicates are rejected) and rotating QR codes that change every 30 seconds in the ticket app. ### Counterfeit Tickets Without cryptographic signing, anyone who knows the QR format can generate valid-looking codes. Always sign the ticket data so scanners can verify authenticity. ## Scaling for Large Events At events with 1,000+ attendees, scan speed determines entry throughput. Aim for sub-second validation per ticket. Pre-download the attendee database to scanner devices for offline capability. Deploy multiple scanning lanes with independent devices to avoid single … ### Text Diff and Merge: Understanding Algorithms and Tools Understand how diff algorithms work, the differences between line-based and word-based diffs, and best practices for three-way merging. Essential knowledge for code review and collaborative editing. - URL: https://peasydev.com/guides/text-diff-merge-algorithms-tools/ - Category: How-To - Reading time: 1 min - Words: 263 Key takeaways: - Diff algorithms find the Longest Common Subsequence (LCS) between two texts, then report everything else as additions or deletions. - Three-way merge uses a common ancestor to resolve changes. - When conflicts occur, the merge tool marks both versions with conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`). - Keep changes small and focused to minimize conflicts ## How Diff Works Diff algorithms find the Longest Common Subsequence (LCS) between two texts, then report everything else as additions or deletions. The classic Myers algorithm runs in O(ND) time where N is the total text length and D is the number of differences. For similar texts (small D), this is nearly linear. ## Diff Granularity | Level | Compares | Best For | | --- | --- | --- | | Line-based | Whole lines | Source code, configuration | | Word-based | Individual words | Prose, documentation | | Character-based | Individual characters | Short strings, titles | | Semantic | Meaningful units | Code-aware refactoring | ## Three-Way Merge Three-way merge uses a common ancestor to resolve changes. When both sides modify different regions, the merge is automatic. When both sides modify the same region, a conflict occurs. The ancestor helps distinguish 'Alice changed this' from 'Bob changed this' — without it, all differences appear as potential conflicts. ## Merge Conflict Resolution When conflicts occur, the merge tool marks both versions with conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`). Resolution strategies include: - **Accept ours/theirs**: Choose one side entirely - **Manual edit**: Combine elements from both sides - **Re-implement**: Rewrite the section from scratch ## Best Practices - Keep changes small and focused to minimize conflicts - Rebase frequently against the main branch - Use semantic diff tools for code (AST-based diffing) - Review word-level diffs for prose and documentation Compare and merge texts with the Peasy diff tool — visualize changes at line, word, or character level with syntax highlighting. ### Payment QR Codes: Standards, Platforms, and Implementation QR-based payments are the dominant payment method in China, India, and Southeast Asia, and are growing rapidly in Western markets. Understanding the different standards and integration approaches is essential for merchants. - URL: https://peasydev.com/guides/payment-qr-codes-guide/ - Category: How-To - Reading time: 2 min - Words: 335 Key takeaways: - The merchant displays a QR code (printed or on screen). - For small businesses accepting QR payments: - QR code tampering:** Fraudsters overlay stickers with their own QR codes on merchant displays. Inspect physical QR codes regularly. - Tourists from QR-dominant markets (China, India) expect QR payment options abroad. - Drawback: the customer must enter the amount manually, which introduces errors. ## Global Payment QR Standards | Standard | Region | Platforms | |----------|--------|----------| | EMVCo QR | Global | Visa, Mastercard, UnionPay | | UPI QR | India | Google Pay, PhonePe, Paytm | | Alipay QR | China/Global | Alipay | | WeChat Pay QR | China/Global | WeChat Pay | | PIX QR | Brazil | All Brazilian banks | | PromptPay QR | Thailand | All Thai banks | | PayNow QR | Singapore | DBS, OCBC, UOB | ## Customer-Presented vs. Merchant-Presented ### Merchant-Presented (Static) The merchant displays a QR code (printed or on screen). The customer scans it, enters the payment amount, and confirms. Simple to implement — a single printed QR code can last months. Drawback: the customer must enter the amount manually, which introduces errors. ### Customer-Presented (Dynamic) The customer displays a QR code on their phone screen. The merchant's POS terminal scans it and processes the payment for the exact amount. Faster, more accurate, but requires a scanner device on the merchant side. ## Implementation for Small Merchants For small businesses accepting QR payments: 1. **Register with a payment processor** that supports QR codes (Stripe, Square, local alternatives) 2. **Generate a static merchant QR code** linked to your account 3. **Print and display** at the point of sale with clear signage 4. **Verify payments** via the processor's app notification before completing the transaction ## Security Considerations - **QR code tampering:** Fraudsters overlay stickers with their own QR codes on merchant displays. Inspect physical QR codes regularly. - **Screen capture fraud:** A customer shows a screenshot of a previous successful payment instead of initiating a new one. Always verify via the payment processor's real-time notification. - **Amount manipulation:** In merchant-presented mode, verify the amount shown on the customer's confirmation screen before completing the … ### How to Convert Between Number Systems (Binary, Hex, Octal) Understanding binary, hexadecimal, and octal number systems is fundamental for developers and anyone working with low-level data. This guide explains the conversion logic step by step with practical examples. - URL: https://peasydev.com/guides/how-to-convert-between-number-systems/ - Category: How-To - Reading time: 3 min - Words: 621 Key takeaways: - Computers operate in binary (base-2) because digital circuits have two states: on and off. - The familiar system using digits 0 through 9. - To convert 42 to binary: 42 / 2 = 21 remainder 0, 21 / 2 = 10 remainder 1, 10 / 2 = 5 remainder 0, 5 / 2 = 2 remainder 1, 2 / 2 = 1 remainder 0, 1 / 2 = 0 remainder 1. - CSS hex colors encode RGB values in hexadecimal. - Memorize powers of 2 up to 2^10 (1024). ## Why Multiple Number Systems Exist Computers operate in binary (base-2) because digital circuits have two states: on and off. Humans prefer decimal (base-10) because we have ten fingers. Hexadecimal (base-16) and octal (base-8) serve as convenient shorthand for binary values — hex maps cleanly to 4-bit groups and octal to 3-bit groups, making them far more readable than long binary strings. ## The Four Common Bases ### Binary (Base-2) Uses digits 0 and 1. Each position represents a power of 2. The binary number 1011 means (1 x 8) + (0 x 4) + (1 x 2) + (1 x 1) = 11 in decimal. Binary is the native language of computers and appears in networking (IP addresses, subnet masks), permissions (Unix file modes), and bit manipulation. ### Octal (Base-8) Uses digits 0 through 7. Each octal digit maps to exactly 3 binary digits: octal 7 = binary 111, octal 5 = binary 101. Octal is commonly used for Unix file permissions (755 = rwxr-xr-x) and some legacy computing contexts. To convert octal to binary, simply expand each octal digit to its 3-bit binary equivalent. ### Decimal (Base-10) The familiar system using digits 0 through 9. Converting from decimal to other bases requires repeated division: divide the number by the target base, record the remainder, then divide the quotient again until it reaches zero. The remainders read bottom-to-top form the converted number. ### Hexadecimal (Base-16) Uses digits 0-9 and letters A-F (where A=10, B=11, C=12, D=13, E=14, F=15). Each hex digit maps to exactly 4 binary digits: hex F = binary 1111, hex A = binary 1010. Hex is ubiquitous in computing: color codes (#FF6B35), memory addresses (0x7FFE), MAC addresses, and byte-level data inspection. ## Conversion Methods ### Decimal to Binary (Repeated Division) To convert 42 to binary: 42 … ### Search and Replace Power Techniques for Text Processing Advanced search and replace techniques using regex capture groups, lookaheads, and conditional replacements. Transform text data efficiently with patterns that handle complex real-world scenarios. - URL: https://peasydev.com/guides/search-replace-power-techniques/ - Category: How-To - Reading time: 1 min - Words: 212 Key takeaways: - Basic find-replace handles exact strings, but real-world text transformation requires pattern matching. - Capture groups `()` save matched portions for use in the replacement. - Lookaheads and lookbehinds match positions without consuming characters. - Some regex engines support conditional replacement — different output depending on which alternative matched. - For files under 10MB, client-side regex processing is instant. ## Beyond Simple Find-Replace Basic find-replace handles exact strings, but real-world text transformation requires pattern matching. Regex-powered search and replace can reformat dates, restructure CSV columns, rename variables, and transform data formats — tasks that would otherwise require custom scripts. ## Capture Groups for Restructuring Capture groups `()` save matched portions for use in the replacement. Number references (`$1`, `$2`) insert the captured text: - **Swap order**: Pattern `(\w+), (\w+)` → Replace `$2 $1` - Input: `Doe, John` → Output: `John Doe` - **Reformat dates**: Pattern `(\d{2})/(\d{2})/(\d{4})` → Replace `$3-$1-$2` - Input: `03/10/2026` → Output: `2026-03-10` ## Lookaheads and Lookbehinds Lookaheads and lookbehinds match positions without consuming characters. This enables surgical replacements that only affect text in specific contexts: - **Add commas to numbers**: Pattern `(?<=\d)(?=(\d{3})+$)` → Replace `,` - Input: `1000000` → Output: `1,000,000` ## Conditional Patterns Some regex engines support conditional replacement — different output depending on which alternative matched. This handles multi-format input in a single pass without writing multiple rules. ## Performance Considerations For files under 10MB, client-side regex processing is instant. Larger files may benefit from streaming line-by-line. Avoid patterns with catastrophic backtracking potential (`(a+)+b`) on untrusted input. Apply complex regex search and replace with the Peasy text tools — live preview shows results before committing changes. ### QR Codes in Education: Classroom and Campus Applications QR codes streamline classroom workflows, campus navigation, and student engagement. From linking printed worksheets to digital resources to contactless attendance tracking, educational QR uses keep growing. - URL: https://peasydev.com/guides/qr-codes-education-classroom-campus/ - Category: use-case - Reading time: 2 min - Words: 330 Key takeaways: - The most common educational QR use is bridging printed materials to digital content. - Display a QR code on the projector at the start of class. - QR codes on building directories, room signs, and campus maps link to interactive maps, room schedules, and wayfinding directions. - Libraries attach QR codes to shelf labels linking to the digital catalog entry, related e-books, or reservation systems. - Students generate QR codes linking to their digital portfolios, project presentations, or multimedia assignments. ## Linking Print to Digital The most common educational QR use is bridging printed materials to digital content. A textbook page links to a video explanation. A poster links to an interactive simulation. A worksheet links to the answer key or additional practice problems. **Implementation tips:** - Use static QR codes for stable URLs (school website, YouTube videos) - Use dynamic QR codes if you plan to update linked resources each semester - Print at minimum 2cm × 2cm for reliable phone scanning - Add a short text label below the QR code explaining what it links to ## Attendance Tracking Display a QR code on the projector at the start of class. Students scan with their phones to check in. The QR code can rotate every 30-60 seconds to prevent sharing. This replaces paper sign-in sheets and reduces class disruption. **Privacy note:** Only collect the minimum data needed — student ID and timestamp. Avoid tracking location or device information. ## Campus Navigation QR codes on building directories, room signs, and campus maps link to interactive maps, room schedules, and wayfinding directions. New students and visitors benefit most during orientation periods. ## Library and Lab Resources Libraries attach QR codes to shelf labels linking to the digital catalog entry, related e-books, or reservation systems. Science labs use QR codes on equipment to link to safety data sheets (SDS), operating procedures, and calibration logs. ## Student Portfolios and Assignments Students generate QR codes linking to their digital portfolios, project presentations, or multimedia assignments. Teachers scan to access and grade submissions without manual URL entry. ## Best Practices for Schools | Consideration | Recommendation | |---------------|----------------| | Student age | Under 13: teacher-controlled devices only (COPPA) | | Accessibility | Always provide a text URL alongside the QR code | | Connectivity … ### Data Serialization Formats: JSON, YAML, TOML, XML, and Protocol Buffers Compare data serialization formats for configuration files, API responses, and inter-service communication. Understand parsing performance, human readability, and schema validation capabilities. - URL: https://peasydev.com/guides/data-serialization-json-yaml-toml-xml-protobuf/ - Category: Best Practice - Reading time: 1 min - Words: 269 Key takeaways: - Serialization formats divide into human-readable text formats (JSON, YAML, TOML, XML) and binary formats (Protocol Buffers, MessagePack, CBOR). - JSON's simplicity and universal language support make it the default for APIs and data interchange. - YAML supports comments, anchors, multi-line strings, and rich data types. - JSON**: APIs, data interchange, structured storage ## Human-Readable vs Binary Formats Serialization formats divide into human-readable text formats (JSON, YAML, TOML, XML) and binary formats (Protocol Buffers, MessagePack, CBOR). Text formats prioritize debuggability and editability. Binary formats prioritize parsing speed and compact wire size. ## Text Format Comparison | Feature | JSON | YAML | TOML | XML | | --- | --- | --- | --- | --- | | Comments | No | Yes | Yes | Yes | | Multi-line strings | No (escaped) | Yes | Yes | CDATA | | Data types | 6 types | Rich | Typed | String-based | | Nesting | Braces | Indentation | Tables/sections | Tags | | Trailing commas | No | N/A | No | N/A | | Parse speed | Fast | Slow | Fast | Medium | ## JSON: The API Standard JSON's simplicity and universal language support make it the default for APIs and data interchange. Its limitations — no comments, no trailing commas, no multi-line strings — make it less ideal for human-edited configuration files but excellent for machine-generated data. ## YAML: Powerful but Dangerous YAML supports comments, anchors, multi-line strings, and rich data types. However, its flexibility creates foot-guns: `on` and `off` are booleans, `1.0` can be a float or a string depending on context, and indentation errors cause silent data corruption rather than parse failures. ## Choosing Your Format - **JSON**: APIs, data interchange, structured storage - **TOML**: Application configuration files - **YAML**: Kubernetes manifests, CI/CD pipelines (where the ecosystem demands it) - **XML**: Document markup, legacy systems, SOAP APIs - **Protocol Buffers**: High-performance microservice communication ### String Manipulation Best Practices for Developers Best practices for common string operations — trimming, padding, case conversion, truncation, and escaping. Covers Unicode-aware handling and the subtle bugs caused by naive string processing. - URL: https://peasydev.com/guides/string-manipulation-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 262 Key takeaways: - Many string operations that seem simple with ASCII become complex with Unicode. - Unicode defines four normalization forms. - Different contexts require different escaping: - Use grapheme-cluster-aware operations when dealing with user-visible text. - Always normalize before comparison, hashing, or storage to prevent phantom duplicates. ## Unicode-Aware String Processing Many string operations that seem simple with ASCII become complex with Unicode. A 'character' can be multiple code points (emoji with skin tone modifiers), a 'word' boundary differs by language, and 'uppercase' transforms are locale-dependent. Using the correct abstraction level prevents subtle data corruption. ## Common Operations and Pitfalls | Operation | ASCII Safe | Unicode Pitfall | | --- | --- | --- | | Length | `str.length` | Emoji `👨‍👩‍👧` is 5 code points, 1 grapheme | | Uppercase | `toUpperCase()` | Turkish `i` → `İ` (not `I`) | | Reverse | Swap chars | Combining marks detach from base characters | | Truncate | Slice at index | May split surrogate pairs or grapheme clusters | | Compare | `===` | `é` (one codepoint) ≠ `é` (e + combining accent) | ## Normalization Unicode defines four normalization forms. NFC (Canonical Decomposition + Composition) is the web standard — it composes characters into their precomposed forms where possible. Always normalize before comparison, hashing, or storage to prevent phantom duplicates. ## Escaping and Encoding Different contexts require different escaping: - **HTML**: `&`, `<`, `>`, `"`, `'` → entities - **URL**: Non-ASCII and reserved chars → percent encoding - **JSON**: Backslash, quotes, control characters → backslash escape - **SQL**: Use parameterized queries (never manual escaping) - **Regex**: `\`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `{` → backslash ## Best Practices Use grapheme-cluster-aware operations when dealing with user-visible text. Use code-point-level operations for protocol and storage layer work. Process text with the Peasy string tools for Unicode-safe operations. ### QR Code Size and Scanning Distance: A Practical Reference A QR code that scans perfectly on a business card may be unreadable on a billboard. The relationship between code size, scanning distance, and module count determines minimum print dimensions for reliable scanning. - URL: https://peasydev.com/guides/qr-code-size-scanning-distance/ - Category: Troubleshooting - Reading time: 2 min - Words: 379 Key takeaways: - As a rough guideline, the scanning distance is approximately 10 times the QR code width. - A QR code's version determines its grid size. - The quiet zone (empty border around the code) must be at least 4 modules wide for QR codes. - Print a test code at the intended size on the intended material. - Each module must be large enough for the camera to resolve it. ## The 10:1 Rule of Thumb As a rough guideline, the scanning distance is approximately 10 times the QR code width. A 3 cm code scans at about 30 cm (arm's length). A 30 cm code scans at about 3 meters. This ratio assumes a standard smartphone camera with autofocus in adequate lighting. ## Factors Affecting Scan Distance ### Module Count (Version) A QR code's version determines its grid size. Version 1 is 21×21 modules; version 40 is 177×177 modules. Each module must be large enough for the camera to resolve it. A version 40 code needs to be physically larger than a version 1 code for the same scanning distance because its modules are proportionally smaller. ### Contrast and Lighting Low contrast (gray on white, or dark blue on black) reduces effective scanning distance by 30-50%. Direct sunlight creates glare on glossy surfaces. Backlit codes (printed on translucent material with light behind) scan at greater distances than reflected-light codes. ### Camera Quality Modern smartphones (2022+) have autofocus cameras that scan QR codes at greater distances than budget phones or older models. Design for the lowest common denominator in your audience. ## Size Recommendations by Application | Application | Scanning Distance | Minimum Code Size | |------------|------------------|------------------| | Business card | 10-20 cm | 2×2 cm | | Product label | 15-30 cm | 2.5×2.5 cm | | Table tent (restaurant) | 30-50 cm | 3×3 cm | | Poster (A3) | 50-100 cm | 5×5 cm | | Banner/sign | 1-3 m | 15×15 cm | | Billboard | 3-10 m | 50×50 cm | | Building/vehicle wrap | 10-30 m | 1.5×1.5 m | ## Quiet Zone Requirements The quiet zone (empty border around the code) must be at least 4 modules wide for QR codes. At small … ### Audio Compression for Streaming: Optimizing for Bandwidth Streaming audio over the internet requires balancing quality against bandwidth consumption and latency. Codec selection, bitrate adaptation, and buffering strategy determine whether listeners hear music or stuttering. - URL: https://peasydev.com/guides/audio-compression-streaming-optimization/ - Category: Best Practice - Reading time: 2 min - Words: 306 Key takeaways: - Modern streaming services dynamically adjust audio quality based on available bandwidth. - The optimal codec for real-time streaming. - Streaming clients maintain a playback buffer — pre-downloaded audio ahead of the current playback position. - Music service:** AAC 256 kbps default, adaptive to 128/64 on slow networks ## Bandwidth Reality | Connection | Typical Bandwidth | Supported Audio Quality | |------------|------------------|------------------------| | 2G mobile | 50-100 kbps | Low-quality speech only | | 3G mobile | 300-700 kbps | MP3 128-192 kbps | | 4G mobile | 5-50 Mbps | Any lossy, some lossless | | 5G / WiFi | 50+ Mbps | Lossless, Hi-Res | | Satellite | 1-5 Mbps | Most lossy formats | ## Adaptive Bitrate Streaming Modern streaming services dynamically adjust audio quality based on available bandwidth. Spotify offers four quality tiers (24, 96, 160, 320 kbps) and switches between them mid-stream as network conditions change. Apple Music similarly adapts between AAC 64 kbps and lossless ALAC. ## Codec Choice for Streaming ### Opus The optimal codec for real-time streaming. Opus adapts seamlessly between speech and music modes, supports bitrates from 6 kbps to 510 kbps, and has the lowest latency of any modern codec (2.5 ms minimum frame size). Used by Discord, WhatsApp, and most VoIP services. ### AAC-LC and HE-AAC AAC-LC (Low Complexity) is the standard music streaming codec. HE-AAC v2 adds spectral band replication and parametric stereo for excellent quality at very low bitrates (32-64 kbps) — used for bandwidth-constrained music streaming. ## Buffer Management Streaming clients maintain a playback buffer — pre-downloaded audio ahead of the current playback position. Typical buffer sizes: - **Music streaming:** 10-30 seconds ahead - **Live radio:** 3-5 seconds (latency trade-off) - **Video conferencing:** <200 ms (real-time requirement) Larger buffers improve reliability on unstable connections but increase initial wait time and memory usage. ## Optimizing for Your Use Case - **Music service:** AAC 256 kbps default, adaptive to 128/64 on slow networks - **Podcast delivery:** MP3 128 kbps CBR mono (widest compatibility) - **Live communication:** Opus 32-64 kbps (lowest latency) - **Background web audio:** AAC … ### Barcode Inventory Management: Setup and Best Practices Barcode-based inventory management reduces counting errors by 67% compared to manual entry. Setting up an effective system requires choosing the right symbology, label design, and scanning hardware. - URL: https://peasydev.com/guides/barcode-inventory-management-guide/ - Category: How-To - Reading time: 1 min - Words: 279 Key takeaways: - Manual inventory entry averages one error per 300 keystrokes. - For internal inventory (not retail sale), Code 128 is the standard choice. - Design a structured SKU system before generating barcodes: - For warehouse environments, choose laser scanners (fast, long range, 1D only) or imaging scanners (read 1D and 2D, can capture images, shorter range). - Integrate barcode scanning into every inventory touchpoint: receiving (scan incoming items), putaway (scan shelf location + item), picking (scan pick list items), and shipping (scan outgoing items). ## Why Barcodes for Inventory Manual inventory entry averages one error per 300 keystrokes. Barcode scanning averages one error per 36 trillion scans. This difference eliminates the cascading problems caused by miscounts — incorrect reorder points, phantom stock, and fulfillment errors. ## Choosing a Symbology For internal inventory (not retail sale), Code 128 is the standard choice. It encodes alphanumeric data at high density, supports variable length, and includes a built-in check digit. For items that may be sold retail, use GS1 standards (EAN-13 or GS1-128). ## SKU Design Design a structured SKU system before generating barcodes: - **Category prefix:** 2-3 characters identifying the product category - **Identifier:** Unique product number (sequential or meaningful) - **Variant suffix:** Size, color, or configuration code Example: `ELC-4521-BLK` (Electronics, product 4521, Black) Avoid sequential-only SKUs (`0001`, `0002`) — they carry no semantic information and are easy to transpose. ## Label Specifications | Parameter | Recommendation | |-----------|---------------| | Barcode height | Minimum 15 mm | | Module width | 0.33-0.50 mm | | Quiet zone | 10× module width (minimum) | | Human-readable text | Below barcode, 8pt+ font | | Label material | Thermal-transfer for durability | ## Scanner Selection For warehouse environments, choose laser scanners (fast, long range, 1D only) or imaging scanners (read 1D and 2D, can capture images, shorter range). For mobile inventory apps, modern smartphone cameras work for low-volume scanning but are too slow for high-volume warehouse operations. ## Workflow Integration Integrate barcode scanning into every inventory touchpoint: receiving (scan incoming items), putaway (scan shelf location + item), picking (scan pick list items), and shipping (scan outgoing items). Every scan event creates an auditable trail of item movement. ### QR Codes for Product Packaging: Design and Compliance QR codes on product packaging bridge the physical-digital gap, linking to instructions, authentication, warranty registration, and marketing content. Packaging constraints require careful attention to print quality and placement. - URL: https://peasydev.com/guides/qr-codes-product-packaging/ - Category: Best Practice - Reading time: 2 min - Words: 322 Key takeaways: - Different packaging materials present scanning challenges: - Some jurisdictions require QR codes on packaging for compliance: - Place the QR code where it is visible without opening the package — ideally the back panel or side panel at the consumer's eye level on shelf. - Always use dynamic QR codes on packaging. - High-contrast ink is essential on reflective surfaces. ## Common Packaging QR Use Cases | Use Case | Destination | Consumer Value | |----------|------------|---------------| | Product manual | PDF or web guide | Reduces paper waste, always up to date | | Warranty registration | Form with pre-filled product info | Faster registration | | Authentication/anti-counterfeit | Verification page | Trust and safety | | Recipe/usage ideas | Content hub | Extended brand engagement | | Sustainability info | Supply chain transparency page | ESG-conscious consumers | | Reorder link | Direct purchase URL | Friction-free repurchase | ## Printing on Packaging Materials Different packaging materials present scanning challenges: - **Cardboard:** Good — provides natural contrast. Use dark ink on unbleached cardboard. Avoid printing over folds or seams. - **Plastic wrap/bags:** Challenging — wrinkles and reflections cause scan failures. Place QR code on a flat, non-reflective area. Use matte finish. - **Glass/metal:** Use a label or direct print. High-contrast ink is essential on reflective surfaces. - **Fabric tags:** Low resolution printing limits QR density. Keep data minimal. ## Regulatory Requirements Some jurisdictions require QR codes on packaging for compliance: - **EU Digital Product Passport** (2027+): QR code linking to product lifecycle data - **FDA UDI (US):** Medical devices must carry a DataMatrix barcode - **GS1 Digital Link:** Transitioning from linear barcodes to QR codes carrying GS1-standard product identifiers ## Placement Best Practices Place the QR code where it is visible without opening the package — ideally the back panel or side panel at the consumer's eye level on shelf. Avoid placement near the barcode used for retail scanning (EAN/UPC) to prevent confusion at checkout. Minimum size of 1.5×1.5 cm for typical consumer packaging scanning distance. ## Dynamic Codes for Packaging Always use dynamic QR codes on packaging. Product URLs may change, landing pages may be redesigned, and warranty … ### JSON Formatting and Validation: Best Practices for Clean Data Best practices for formatting, validating, and structuring JSON data. Covers indentation standards, JSON Schema validation, common syntax errors, and the differences between JSON and JSON5. - URL: https://peasydev.com/guides/json-formatting-validation-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 268 Key takeaways: - JSON has a single universal syntax — no competing standards or flavors. - Trailing comma**: `{"a": 1,}` — invalid in JSON (valid in JS/JSON5) - JSON Schema defines the expected structure, types, and constraints of your JSON data. - JSON5 relaxes JSON's strict syntax — allowing comments, trailing commas, single quotes, and unquoted keys. - For data interchange, always use standard JSON. ## JSON Formatting Standards JSON has a single universal syntax — no competing standards or flavors. Yet formatting varies widely: minified for production, pretty-printed for debugging, and sorted keys for deterministic output. Consistent formatting prevents unnecessary diff noise in version control. ## Formatting Conventions | Convention | When | Benefit | | --- | --- | --- | | 2-space indent | Most codebases | Compact, readable | | 4-space indent | Python ecosystems | Extra readability | | Sorted keys | Config files, snapshots | Deterministic diffs | | Minified | API responses, storage | Minimal size | | One item per line | Arrays of objects | Clean diffs | ## Common Syntax Errors - **Trailing comma**: `{"a": 1,}` — invalid in JSON (valid in JS/JSON5) - **Single quotes**: `{'a': 1}` — invalid, must use double quotes - **Unquoted keys**: `{a: 1}` — invalid, keys must be quoted strings - **Comments**: `// comment` — not allowed in JSON - **Infinity/NaN**: Not valid JSON values ## JSON Schema Validation JSON Schema defines the expected structure, types, and constraints of your JSON data. It catches type errors (`string` where `number` expected), missing required fields, and invalid enum values before they cause runtime failures. Use schemas for API request/response validation and configuration file validation. ## JSON5 and Alternatives JSON5 relaxes JSON's strict syntax — allowing comments, trailing commas, single quotes, and unquoted keys. It is popular for configuration files that humans edit directly. For data interchange, always use standard JSON. Format, validate, and transform JSON with the Peasy JSON tools — supports pretty-printing, minification, sorting, and JSON Schema validation. ### XML vs JSON: When to Use Each and How to Convert Between Them Compare XML and JSON across use cases, tooling, and data modeling capabilities. Learn when each format is the better choice and how to convert between them without losing information. - URL: https://peasydev.com/guides/xml-vs-json-comparison-conversion/ - Category: Comparison - Reading time: 1 min - Words: 266 Key takeaways: - JSON and XML model data differently at a conceptual level. - XML excels when document structure matters: HTML/XHTML, SVG, SOAP web services, office document formats (OOXML, ODF), and any content with mixed text and markup. - JSON dominates for data interchange: REST APIs, configuration files, NoSQL databases, and browser-to-server communication. - XML attributes, namespaces, mixed content, and element ordering have no direct JSON equivalents. - Always verify the output structure after conversion. ## Fundamental Differences JSON and XML model data differently at a conceptual level. JSON uses a data-centric model — arrays, objects, and primitives. XML uses a document-centric model — elements, attributes, and mixed content (text interspersed with markup). This distinction means some data converts cleanly while other structures lose information in translation. ## Feature Comparison | Feature | JSON | XML | | --- | --- | --- | | Data types | 6 (string, number, boolean, null, array, object) | Strings (with schema typing) | | Comments | No | Yes | | Attributes | No concept | Yes | | Mixed content | No | Yes (text + elements) | | Namespaces | No | Yes | | Schema validation | JSON Schema | XSD, DTD, RelaxNG | | XPath/XSLT queries | No (use JSONPath) | Yes (mature tooling) | | File size | Smaller (typically 30-50%) | Larger (verbose tags) | ## When XML Wins XML excels when document structure matters: HTML/XHTML, SVG, SOAP web services, office document formats (OOXML, ODF), and any content with mixed text and markup. XML namespaces enable combining vocabularies without conflicts. ## When JSON Wins JSON dominates for data interchange: REST APIs, configuration files, NoSQL databases, and browser-to-server communication. Its native mapping to JavaScript objects and Python dicts makes it the natural choice for web applications. ## Conversion Pitfalls XML attributes, namespaces, mixed content, and element ordering have no direct JSON equivalents. Different converters handle these differently, producing incompatible JSON structures. Always verify the output structure after conversion. Convert between XML and JSON with the Peasy format converter. ### Custom QR Code Logos: Embedding Brand Identity Safely Embedding a logo in the center of a QR code reinforces brand identity but risks scan failures if done incorrectly. Understanding the safe zone, error correction requirements, and design constraints ensures reliable scanning. - URL: https://peasydev.com/guides/custom-qr-code-logos-guide/ - Category: How-To - Reading time: 2 min - Words: 333 Key takeaways: - The logo is not technically part of the QR code data. - Always use error correction level H (30% recovery) when embedding logos. - The center of the QR code is the safest area for logos because: - Round or rounded-square logos work best because they avoid sharp corners that interfere with adjacent data modules. - Test logo QR codes with at least 5 different scanning apps on both iOS and Android. ## How Logo Embedding Works The logo is not technically part of the QR code data. It physically obscures data modules in the center of the code. The QR scanner uses error correction to reconstruct the obscured data. This means the logo area counts against the error correction budget — you are deliberately damaging the code and relying on redundancy to compensate. ## Error Correction Requirements Always use error correction level H (30% recovery) when embedding logos. Even so, the logo should not obscure more than 20-25% of the data area. The remaining 5-10% of recovery capacity handles real-world damage (scratches, printing imperfections, dirt). ## Safe Zone Dimensions The center of the QR code is the safest area for logos because: - Finder patterns (three corners) remain intact - Timing patterns (between finders) remain intact - Alignment patterns (bottom-right region) remain intact - Format and version information (near finders) remain intact A safe logo size is approximately 20% of the QR code's total area. For a 100×100 module code, the logo should fit within approximately 20×20 modules. ## Design Guidelines ### Shape Round or rounded-square logos work best because they avoid sharp corners that interfere with adjacent data modules. Add a white buffer zone (2-3 modules) between the logo edge and the surrounding data modules. ### Color The logo can use brand colors because it is not part of the scannable data. However, maintain sufficient contrast between the logo background and the surrounding QR modules so the scanner can distinguish the boundary. ### Transparency Never use semi-transparent logos that partially obscure data modules. Each module must be either clearly readable or clearly obscured — partial obscuration confuses the error correction algorithm. ## Testing Rigorously Test logo QR codes with at least 5 different scanning apps on both iOS and Android. … ### Base64 Encoding: How It Works, When to Use It, and Common Pitfalls Understand Base64 encoding — the mechanism behind data URIs, email attachments, and API payloads. Learn when Base64 is appropriate, when it wastes bandwidth, and how to handle the 33% size overhead. - URL: https://peasydev.com/guides/base64-encoding-guide-common-pitfalls/ - Category: How-To - Reading time: 1 min - Words: 262 Key takeaways: - Base64 converts binary data into a text string using 64 safe characters (A-Z, a-z, 0-9, +, /). - Small inline images**: Data URIs under 2KB save an HTTP request - Large files**: 33% overhead adds up — a 1MB file becomes 1.33MB - Forgetting the `data:` URI prefix (`data:image/png;base64,...`) ## What Base64 Does Base64 converts binary data into a text string using 64 safe characters (A-Z, a-z, 0-9, +, /). This allows binary data to travel through text-only channels — email (SMTP), JSON APIs, HTML attributes, and URL parameters. The tradeoff is a 33% size increase: 3 bytes of binary become 4 characters of Base64. ## Encoding Variants | Variant | Characters | Padding | Use Case | | --- | --- | --- | --- | | Standard (RFC 4648) | A-Z, a-z, 0-9, +, / | `=` | Email, MIME | | URL-safe (RFC 4648 §5) | A-Z, a-z, 0-9, -, _ | Optional | URLs, filenames | | Base64url (no padding) | A-Z, a-z, 0-9, -, _ | None | JWT, compact tokens | ## When to Use Base64 - **Small inline images**: Data URIs under 2KB save an HTTP request - **Email attachments**: MIME requires Base64 for binary content - **JSON payloads**: Embedding binary data in JSON fields - **HTTP headers**: Authentication tokens, encoded parameters ## When NOT to Use Base64 - **Large files**: 33% overhead adds up — a 1MB file becomes 1.33MB - **Image optimization**: Serve WebP/AVIF files directly instead - **Binary protocols**: gRPC, WebSocket, and HTTP/2 handle binary natively - **Storage**: Store binary files as binary, not Base64 text ## Common Pitfalls - Forgetting the `data:` URI prefix (`data:image/png;base64,...`) - Mixing standard and URL-safe alphabets in the same system - Not stripping whitespace from Base64 copied from email sources Encode and decode Base64 with the Peasy encoder — supports all variants with instant preview. ### Batch QR Code Generation: Techniques for Large-Scale Creation Generating hundreds or thousands of unique QR codes for events, inventory, or marketing campaigns requires automation. Batch generation combines template design with data-driven code creation for consistent, scalable output. - URL: https://peasydev.com/guides/batch-qr-code-generation-guide/ - Category: How-To - Reading time: 1 min - Words: 288 Key takeaways: - Manual QR code generation works for 1-10 codes. - Start with a structured data source — typically a CSV or spreadsheet with one row per QR code. - JavaScript QR libraries can generate codes in the browser from uploaded CSV data. - PNG:** Best for digital use and basic printing - After batch generation, randomly sample 5-10% of codes and scan them. ## When Batch Generation Is Needed Manual QR code generation works for 1-10 codes. Beyond that, automation becomes essential: - **Event badges:** One unique QR per attendee (100-10,000+) - **Product labels:** One QR per SKU or serial number (100-100,000+) - **Direct mail:** Personalized QR codes linking to individual landing pages - **Asset tracking:** One QR per physical asset in an organization ## Data Preparation Start with a structured data source — typically a CSV or spreadsheet with one row per QR code. Each row contains the unique data to encode and any metadata for the label template: ``` id,name,url,location 001,Server Rack A1,https://assets.co/001,DC-North-R1 002,Server Rack A2,https://assets.co/002,DC-North-R2 ``` Validate the data before generation: check for duplicates, empty fields, malformed URLs, and character encoding issues (special characters in names). ## Generation Approaches ### Client-Side (Browser) JavaScript QR libraries can generate codes in the browser from uploaded CSV data. Best for batches under 1,000 codes. No data leaves the user's device, which is important for sensitive data like serial numbers. ### Command-Line Tools Tools like `qrencode` (Linux/macOS) can be scripted for batch generation: ```bash while IFS=, read -r id name url; do qrencode -o "qr_${id}.png" -s 10 -l H "$url" done < data.csv ``` ## Output Formats - **PNG:** Best for digital use and basic printing - **SVG:** Best for print at any size (vector, infinitely scalable) - **PDF:** Best for direct printing with label templates - **ZIP archive:** Package all generated codes for download ## Quality Assurance After batch generation, randomly sample 5-10% of codes and scan them. Verify that each scanned code resolves to the correct destination. Automated validation can use a QR decoding library to read back each generated image and compare the decoded data against the source CSV. ### Database Export Formats: SQL, CSV, JSON, and Parquet Choose the right export format for database migrations, analytics, and data sharing. Understand the tradeoffs between portability, performance, schema preservation, and human readability. - URL: https://peasydev.com/guides/database-export-formats-sql-csv-json-parquet/ - Category: Best Practice - Reading time: 1 min - Words: 266 Key takeaways: - Database exports serve different purposes — migrations require schema and data fidelity, analytics need columnar efficiency, and sharing demands universal readability. - SQL dumps preserve everything — schemas, constraints, indexes, sequences, and data. - Apache Parquet stores data in columnar format with per-column compression and type encoding. - Same-engine migration**: SQL dump (pg_dump, mysqldump) ## Export Format Tradeoffs Database exports serve different purposes — migrations require schema and data fidelity, analytics need columnar efficiency, and sharing demands universal readability. No single format excels at everything. ## Format Comparison | Feature | SQL Dump | CSV | JSON | Parquet | | --- | --- | --- | --- | --- | | Schema included | Yes | No | Flexible | Yes (typed) | | Data types | Full | Strings only | Basic (6 types) | Rich | | Relationships | Yes (FK) | No | Nested | No | | Compression | No (text) | No (text) | No (text) | Built-in (columnar) | | Human readable | Yes | Yes | Yes | No (binary) | | Query without import | No | Limited | Limited | Yes (DuckDB, Polars) | ## SQL Dump: Full Fidelity SQL dumps preserve everything — schemas, constraints, indexes, sequences, and data. They are the standard for database-to-database migration within the same engine. Cross-engine compatibility is limited; PostgreSQL dumps do not import cleanly into MySQL without modification. ## Parquet: The Analytics Standard Apache Parquet stores data in columnar format with per-column compression and type encoding. A 1GB CSV file typically compresses to 100-200MB as Parquet while being dramatically faster to query. Tools like DuckDB, Polars, and pandas can query Parquet files directly without importing into a database. ## Choosing Your Format - **Same-engine migration**: SQL dump (pg_dump, mysqldump) - **Cross-engine migration**: CSV + separate schema DDL - **Analytics/data science**: Parquet - **API data exchange**: JSON - **Human review**: CSV or formatted SQL ### Random Data Generation for Software Testing Generating realistic random test data improves code coverage and catches edge cases that manual test data misses. This guide covers strategies for different data types and testing scenarios. - URL: https://peasydev.com/guides/random-data-generation-testing/ - Category: How-To - Reading time: 1 min - Words: 267 Key takeaways: - Static test fixtures test the same paths repeatedly. - Generate strings of varying lengths (empty, 1 char, max length, beyond max). - Faker** (Python/JS): Realistic fake names, addresses, companies, text - Always seed your random generator with a fixed value in CI. ## Why Random Test Data Static test fixtures test the same paths repeatedly. Random data generation (also called fuzzing or property-based testing) explores a wider input space, uncovering bugs that fixed test cases miss: buffer overflows, encoding errors, and boundary conditions. ## Data Types and Strategies ### Strings Generate strings of varying lengths (empty, 1 char, max length, beyond max). Include unicode characters, emoji, null bytes, RTL text, and SQL injection patterns to test input handling. ### Numbers Test boundary values: 0, -1, MAX_INT, MIN_INT, NaN, Infinity, very large floats, and numbers with many decimal places. These edge cases frequently cause arithmetic overflows. ### Dates Generate dates across time zones, leap years (Feb 29), century boundaries (2000, 2100), and DST transitions. Include timestamps at epoch (0), negative epoch, and far-future dates. ### Structured Data | Data Type | Strategy | |-----------|----------| | Email addresses | Valid format + edge cases (very long local parts, special chars) | | Phone numbers | Various international formats, with/without country codes | | URLs | Valid + malformed + extremely long paths | | JSON | Valid + deeply nested + circular refs + large arrays | ## Tools and Libraries - **Faker** (Python/JS): Realistic fake names, addresses, companies, text - **Hypothesis** (Python): Property-based testing with automatic shrinking - **fast-check** (TypeScript): Property-based testing for JS/TS - **QuickCheck** (Haskell, ported to many languages): The original property-based testing library ## Reproducibility Always seed your random generator with a fixed value in CI. Log the seed so that any failure can be reproduced. A random test that cannot be reproduced provides no actionable information. ### CSS Cascade Layers: Managing Specificity at Scale Learn CSS cascade layers (`@layer`) — the solution to specificity wars in large codebases. Control which styles override others regardless of selector specificity, enabling clean architecture in complex projects. - URL: https://peasydev.com/guides/css-cascade-layers-managing-specificity/ - Category: Best Practice - Reading time: 1 min - Words: 253 Key takeaways: - In large projects, CSS specificity becomes unmanageable. - Cascade layers create explicit priority groups. - /* Declare layer order (lowest to highest priority) */ - Cascade layers are supported in all modern browsers since early 2022 (Chrome 99+, Firefox 97+, Safari 15.4+). - Third-party component libraries use high-specificity selectors that your custom styles cannot override without `!important`. ## The Specificity Problem at Scale In large projects, CSS specificity becomes unmanageable. Third-party component libraries use high-specificity selectors that your custom styles cannot override without `!important`. Utility classes fight with component styles. Each developer escalates specificity to win, creating an unwinnable arms race. ## How @layer Works Cascade layers create explicit priority groups. Styles in a higher-priority layer always win over styles in a lower-priority layer, regardless of specificity. A simple `.button` class in the `overrides` layer beats `#app .sidebar .button` in the `base` layer. ## Layer Declaration ```css /* Declare layer order (lowest to highest priority) */ @layer reset, base, components, utilities; /* Add styles to layers */ @layer reset { * { margin: 0; box-sizing: border-box; } } @layer base { body { font-family: system-ui; line-height: 1.5; } } @layer components { .card { padding: 1.5rem; border: 1px solid var(--border); } } @layer utilities { .hidden { display: none; } .text-center { text-align: center; } } ``` ## Practical Architecture | Layer | Content | Priority | | --- | --- | --- | | reset | CSS reset, normalize | Lowest | | base | Typography, colors, defaults | Low | | third-party | External libraries | Medium | | components | Custom components | High | | utilities | Utility classes | Highest | ## Browser Support Cascade layers are supported in all modern browsers since early 2022 (Chrome 99+, Firefox 97+, Safari 15.4+). For older browsers, layers are ignored and styles fall back to normal cascade behavior. ### QR Code Security: Risks, Attacks, and Mitigation Strategies QR codes are inherently trusted by users — most people scan without hesitation. This trust creates attack vectors including phishing, malware distribution, and payment fraud that require awareness and mitigation. - URL: https://peasydev.com/guides/qr-code-security-considerations/ - Category: Troubleshooting - Reading time: 2 min - Words: 338 Key takeaways: - When a user scans a QR code, they cannot inspect the encoded URL before their phone opens it. - Attackers place a sticker with a malicious QR code over a legitimate one — on parking meters, restaurant tables, or public transit. - Use HTTPS URLs exclusively** — Browsers warn on HTTP, providing a safety net - Check the URL preview** before opening — most phone cameras show the URL before navigating - Organizations deploying QR codes at scale should inventory all deployed codes, regularly audit physical placements for tampering, use dynamic codes (allowing rapid destination changes if compromised), and implement monitoring to detect anomalous scan patterns. ## The Trust Problem When a user scans a QR code, they cannot inspect the encoded URL before their phone opens it. Unlike clicking a link in an email (where the URL is visible), a QR code is a black box. This makes QR codes an effective phishing vector — a malicious QR code on a legitimate-looking poster can redirect to a credential harvesting page. ## Attack Vectors ### QR Code Overlay (Quishing) Attackers place a sticker with a malicious QR code over a legitimate one — on parking meters, restaurant tables, or public transit. The user believes they are scanning a trusted code. This is the most common real-world QR attack. ### Phishing via QR Email-based phishing using QR codes ('quishing') bypasses traditional URL scanning in email security tools because the malicious URL is encoded in an image rather than as a text link. ### Malicious App Downloads A QR code linking to a sideloaded APK or a convincing fake app store page can trick users into installing malware. ## Mitigation for QR Code Creators - **Use HTTPS URLs exclusively** — Browsers warn on HTTP, providing a safety net - **Use branded short URLs** — `qr.yourbrand.com/abc` is visually trustworthy on the preview screen - **Sign your codes** — For high-value applications (payments, tickets), embed a cryptographic signature - **Monitor redirect analytics** — Sudden traffic spikes from unexpected locations may indicate a cloned code ## Mitigation for QR Code Scanners (Users) - **Check the URL preview** before opening — most phone cameras show the URL before navigating - **Look for tamper signs** — stickers placed over existing codes, misaligned prints, different paper quality - **Avoid scanning codes from untrusted sources** — unsolicited flyers, random stickers in public places - **Use a scanner app that previews URLs** rather than auto-opening them … ### Log File Format Troubleshooting: Parsing JSON, Syslog, and Custom Formats Troubleshoot common log file parsing issues. Covers multiline log entries, timestamp format variations, character encoding problems, and strategies for parsing non-standard log formats. - URL: https://peasydev.com/guides/log-file-format-troubleshooting-guide/ - Category: Troubleshooting - Reading time: 1 min - Words: 284 Key takeaways: - Log files from different applications and systems use incompatible formats, inconsistent timestamp representations, and varying field delimiters. - Stack traces, SQL queries, and XML payloads span multiple lines. - Different applications use different timestamp formats — ISO 8601, Unix epoch, RFC 2822, or locale-specific strings. - Legacy applications may write logs in Windows-1252, Shift_JIS, or other encodings while modern tooling expects UTF-8. ## Why Log Parsing Breaks Log files from different applications and systems use incompatible formats, inconsistent timestamp representations, and varying field delimiters. When a log aggregation pipeline silently drops entries or misparses fields, finding the root cause requires understanding both the source format and the parser's expectations. ## Common Log Formats | Format | Structure | Multiline | Typing | Example Source | | --- | --- | --- | --- | --- | | JSON Lines | One JSON object per line | No (by design) | Yes | Docker, structlog | | Syslog (RFC 5424) | Structured with PRI | No | Limited | Linux system logs | | Apache/Nginx CLF | Space-delimited | No | No | Web servers | | Java stack traces | Unstructured | Yes | No | JVM applications | | Custom delimited | Application-specific | Maybe | No | Legacy applications | ## Multiline Log Entries Stack traces, SQL queries, and XML payloads span multiple lines. Most parsers treat each line as a separate entry, splitting stack traces into dozens of fragments. Solutions include: configuring multiline patterns in the collector (Filebeat, Fluentd), switching to JSON Lines format, or using a codec that recognizes continuation patterns. ## Timestamp Normalization Different applications use different timestamp formats — ISO 8601, Unix epoch, RFC 2822, or locale-specific strings. A single pipeline might receive all of these simultaneously. Define timestamp parsing rules per source and normalize to UTC ISO 8601 at ingestion time. ## Encoding Issues Legacy applications may write logs in Windows-1252, Shift_JIS, or other encodings while modern tooling expects UTF-8. Invalid byte sequences cause silent truncation or parser crashes. Identify the source encoding and convert at the collection layer. ### Language Detection: How It Works and Its Limitations Understand the algorithms behind automatic language detection — n-gram frequency analysis, Unicode script detection, and machine learning approaches. Learn the reliability limits and how to handle ambiguous or mixed-language text. - URL: https://peasydev.com/guides/language-detection-how-it-works-limitations/ - Category: Comparison - Reading time: 1 min - Words: 282 Key takeaways: - Language detection analyzes statistical patterns in text to identify the most likely language. - Short text**: A single word like 'hotel' is valid in 20+ languages - For reliable detection, require at least 50 characters of natural text. - When detection is uncertain, return multiple candidates with confidence scores rather than a single guess. ## How Language Detection Works Language detection analyzes statistical patterns in text to identify the most likely language. The primary technique is n-gram frequency comparison — counting sequences of 2-4 characters and matching against known language profiles. Each language has a distinctive character frequency fingerprint. ## Detection Methods | Method | Accuracy | Speed | Minimum Text | Best For | | --- | --- | --- | --- | --- | | Unicode script | 60-80% | Instant | 1 character | Script identification | | Character n-grams | 95%+ | Fast | 20+ characters | Single-language text | | Word n-grams | 98%+ | Medium | 50+ characters | Long texts | | ML (fastText) | 97%+ | Fast | 10+ characters | Short texts, mixed | ## Where Detection Fails - **Short text**: A single word like 'hotel' is valid in 20+ languages - **Similar languages**: Serbian/Croatian/Bosnian are linguistically close - **Mixed language**: Code-switching within a paragraph confuses n-gram models - **Romanized text**: Japanese in romaji looks like Italian to character n-grams - **Technical jargon**: English technical terms appear in many language contexts ## Practical Strategies For reliable detection, require at least 50 characters of natural text. Use confidence scores — only accept detections above a threshold (typically 0.8). For user-generated content, prefer explicit language tags over detection when available. Combine Unicode script detection with n-gram analysis for the best results on short texts. ## Handling Ambiguity When detection is uncertain, return multiple candidates with confidence scores rather than a single guess. Let the application layer decide — user preferences, page language, or geographic context can disambiguate. Detect languages with the Peasy language detection tool for instant multi-language identification. ### Micro QR Codes and Small-Format Alternatives When standard QR codes are too large for the available space, micro QR codes and other compact formats offer alternatives. Each has trade-offs in data capacity, scanning compatibility, and use case suitability. - URL: https://peasydev.com/guides/micro-qr-codes-small-format/ - Category: Comparison - Reading time: 2 min - Words: 355 Key takeaways: - Micro QR (ISO 18004) is a compact variant with only one finder pattern instead of three, reducing the minimum size by approximately 50% compared to a standard QR code. - Developed by Denso Wave (the original QR inventors), rMQR creates rectangular codes ideal for narrow spaces like PCB boards, pharmaceutical vials, and industrial labels. - DataMatrix is not a QR variant but a competing 2D symbology optimized for small sizes. - For consumer-facing applications, the best small QR code is simply a standard QR code with minimal data. ## Micro QR Code Micro QR (ISO 18004) is a compact variant with only one finder pattern instead of three, reducing the minimum size by approximately 50% compared to a standard QR code. Four versions exist (M1-M4) encoding up to 35 numeric or 21 alphanumeric characters. | Version | Modules | Numeric Capacity | Alphanumeric | |---------|---------|-----------------|-------------| | M1 | 11×11 | 5 | — | | M2 | 13×13 | 10 | 6 | | M3 | 15×15 | 23 | 14 | | M4 | 17×17 | 35 | 21 | **Limitation:** Most smartphone cameras do not natively scan Micro QR codes. A dedicated scanner app is usually required, limiting consumer-facing applications. ## rMQR (Rectangular Micro QR) Developed by Denso Wave (the original QR inventors), rMQR creates rectangular codes ideal for narrow spaces like PCB boards, pharmaceutical vials, and industrial labels. Sizes range from 7×43 to 17×139 modules. Encoding capacity reaches up to 361 numeric characters. **Limitation:** Even more limited scanner support than Micro QR. Primarily used in industrial settings with dedicated scanners. ## DataMatrix DataMatrix is not a QR variant but a competing 2D symbology optimized for small sizes. It can be printed as small as 2×2 mm (300 DPI) while encoding up to 2,335 alphanumeric characters. FDA-mandated for medical device UDI markings. Better suited for industrial applications than consumer use. ## When to Use Each Format | Scenario | Best Format | Reason | |----------|------------|--------| | Consumer mobile scanning | Standard QR | Universal scanner support | | Small component marking | DataMatrix | 2mm minimum, industrial scanner | | Narrow label space | rMQR | Rectangular, industrial scanner | | Short numeric data, tiny space | Micro QR M1-M2 | Smallest possible 2D code | | General small-space consumer | Standard QR (low version) | … ### Trigonometry Basics for Developers and Designers Trigonometric functions power animations, game physics, audio visualization, and SVG path generation. This guide covers sin, cos, and tan with practical code examples. - URL: https://peasydev.com/guides/trigonometry-basics-for-developers/ - Category: How-To - Reading time: 2 min - Words: 304 Key takeaways: - Trigonometry is the math of angles and distances. - For a right triangle with angle θ: - Most programming languages use radians. - Place points on a circle of radius r centered at (cx, cy): ## Why Developers Need Trigonometry Trigonometry is the math of angles and distances. It underlies circular motion, wave animations, audio waveforms, radar charts, analog clocks, and collision detection. Understanding sine and cosine unlocks an enormous range of visual and interactive effects. ## The Big Three Functions For a right triangle with angle θ: - **sin(θ)** = opposite / hypotenuse - **cos(θ)** = adjacent / hypotenuse - **tan(θ)** = opposite / adjacent = sin / cos ## Radians vs Degrees Most programming languages use radians. Convert with: - Degrees to radians: `rad = deg * (π / 180)` - Radians to degrees: `deg = rad * (180 / π)` Full circle = 360° = 2π radians. ## Practical Applications ### Circular Motion Place points on a circle of radius r centered at (cx, cy): `x = cx + r * cos(angle)` `y = cy + r * sin(angle)` Distribute 12 items evenly: increment angle by 2π/12 = 30° between each. ### Wave Animation A sine wave oscillates between -1 and 1. Control amplitude (height), frequency (speed), and phase (offset): `y = amplitude * sin(frequency * x + phase)` ### Rotation Rotate point (x, y) by angle θ around the origin: `x' = x * cos(θ) - y * sin(θ)` `y' = x * sin(θ) + y * cos(θ)` ### Distance and Angle Between Points Distance: `d = sqrt((x2-x1)² + (y2-y1)²)` Angle: `θ = atan2(y2-y1, x2-x1)` Use `atan2` instead of `atan` because it handles all four quadrants correctly. ## Quick Reference | Angle | sin | cos | tan | |-------|-----|-----|-----| | 0° | 0 | 1 | 0 | | 30° | 0.5 | 0.866 | 0.577 | | 45° | 0.707 | 0.707 | 1 | | 90° | 1 | 0 | undefined | | 180° | 0 | … ### Scroll-Driven Animations: Triggering CSS Animations on Scroll Learn the new CSS Scroll-Driven Animations API — trigger animations based on scroll position without JavaScript. Covers scroll() and view() timelines, browser support, and progressive enhancement. - URL: https://peasydev.com/guides/scroll-driven-animations-css-guide/ - Category: How-To - Reading time: 1 min - Words: 252 Key takeaways: - The CSS Scroll-Driven Animations specification introduces two new animation timelines: `scroll()` (linked to scroll position) and `view()` (linked to element visibility). - The animation progresses from 0% to 100% as the user scrolls from top to bottom. - The `view()` timeline triggers based on an element's visibility in the viewport: - Scroll-driven animations are supported in Chrome 115+ and Edge 115+. ## Scroll Animations Without JavaScript The CSS Scroll-Driven Animations specification introduces two new animation timelines: `scroll()` (linked to scroll position) and `view()` (linked to element visibility). These replace JavaScript scroll listeners for common patterns like progress bars, parallax effects, and reveal animations. ## Scroll Progress Timeline ```css .progress-bar { animation: fill-bar linear; animation-timeline: scroll(); } @keyframes fill-bar { from { width: 0%; } to { width: 100%; } } ``` The animation progresses from 0% to 100% as the user scrolls from top to bottom. No JavaScript, no IntersectionObserver, no scroll event handlers. ## View Progress Timeline The `view()` timeline triggers based on an element's visibility in the viewport: ```css .fade-in { animation: appear linear; animation-timeline: view(); animation-range: entry 0% entry 100%; } @keyframes appear { from { opacity: 0; transform: translateY(2rem); } to { opacity: 1; transform: translateY(0); } } ``` ## Animation Range | Range | Meaning | | --- | --- | | `entry 0%` | Element starts entering viewport | | `entry 100%` | Element fully inside viewport | | `exit 0%` | Element starts leaving viewport | | `exit 100%` | Element fully outside viewport | | `contain 0%` | Element just fully contained | | `cover 0%` | Element starts covering scroll port | ## Browser Support Scroll-driven animations are supported in Chrome 115+ and Edge 115+. Firefox and Safari support is in progress. Use `@supports (animation-timeline: scroll())` for progressive enhancement — the animation simply will not play in unsupported browsers, which is a graceful degradation. ### Video Format Conversion Guide: MP4, WebM, MOV, and AVI Different platforms and devices require different video formats. Understanding container formats and their codec compatibility prevents quality loss during conversion. - URL: https://peasydev.com/guides/video-format-conversion-mp4-webm-mov/ - Category: How-To - Reading time: 1 min - Words: 238 Key takeaways: - A container (MP4, WebM, MOV) is the file format that holds video, audio, and metadata streams. - Google's open container for VP8/VP9/AV1 video and Vorbis/Opus audio. - Remuxing copies the video stream into a new container without re-encoding — it is instant and lossless. - ## Conversion Best Practices | From | To | Recommendation | |------|-----|---------------| | MOV (ProRes) | MP4 (H. ## Container vs Codec A container (MP4, WebM, MOV) is the file format that holds video, audio, and metadata streams. A codec (H.264, VP9) is the compression algorithm used on those streams. The same H.264 video can live inside an MP4, MOV, or MKV container. ## Common Containers ### MP4 (.mp4) The universal container. Supports H.264, H.265, and AAC audio. Plays on every device and browser. This is the default choice for web delivery. ### WebM (.webm) Google's open container for VP8/VP9/AV1 video and Vorbis/Opus audio. Smaller files than MP4 at equivalent quality but limited support outside browsers. ### MOV (.mov) Apple's QuickTime container. Supports ProRes for editing workflows. Common in professional video production but not ideal for web delivery. ### AVI (.avi) Microsoft's legacy container from 1992. No streaming support, limited codec options. Avoid for new projects. ## Conversion Best Practices | From | To | Recommendation | |------|-----|---------------| | MOV (ProRes) | MP4 (H.264) | Re-encode for web | | AVI | MP4 (H.264) | Always re-encode | | MP4 (H.264) | WebM (VP9) | Re-encode for smaller size | | MKV (H.264) | MP4 (H.264) | Remux only (no quality loss) | ## Remuxing vs Re-encoding Remuxing copies the video stream into a new container without re-encoding — it is instant and lossless. This works when the target container supports the source codec (e.g., H.264 from MKV to MP4). Re-encoding is required when changing codecs. ### Data Matrix vs QR Code: Choosing the Right 2D Barcode Data Matrix and QR codes are the two dominant 2D barcode formats, each optimized for different use cases. Understanding their structural differences, scanning characteristics, and industry adoption guides the right choice. - URL: https://peasydev.com/guides/data-matrix-vs-qr-code-comparison/ - Category: Comparison - Reading time: 2 min - Words: 300 Key takeaways: - QR codes are designed for fast scanning at distance. - Consumer marketing and advertising - Data Matrix excels in direct part marking (DPM) — etching, engraving, or laser marking directly onto metal, glass, or plastic parts. - If consumers will scan with smartphones → QR Code. ## Structural Differences | Feature | QR Code | Data Matrix | |---------|---------|------------| | Finder pattern | 3 large squares (corners) | L-shaped border (2 sides) | | Shape | Square | Square or rectangular | | Max capacity | 4,296 alphanumeric | 2,335 alphanumeric | | Error correction | 4 levels (L/M/Q/H) | ECC 200 (fixed ~30%) | | Minimum size | ~21×21 modules | ~10×10 modules | | Versions | 1-40 | 10×10 to 144×144 | ## Scanning Characteristics QR codes are designed for fast scanning at distance. The three large finder patterns allow rapid detection and orientation from any angle. Data Matrix codes are designed for small-size reliability — the L-shaped finder pattern is simpler and works well at very small print sizes but is harder to detect at distance. ## Industry Adoption ### Where QR Dominates - Consumer marketing and advertising - Mobile payments (Alipay, WeChat Pay, UPI) - Restaurant menus and ticketing - URLs, vCards, WiFi credentials - Any application where smartphones are the scanner ### Where Data Matrix Dominates - Medical devices (FDA UDI requirement) - Pharmaceutical packaging (EU FMD serialization) - Electronic component marking (PCBs, chips) - Aerospace parts identification - Any application requiring marking on very small surfaces ## Direct Marking Data Matrix excels in direct part marking (DPM) — etching, engraving, or laser marking directly onto metal, glass, or plastic parts. The L-shaped finder pattern survives surface wear better than QR's three large squares. This is why aerospace and automotive industries standardized on Data Matrix. ## The Decision If consumers will scan with smartphones → QR Code. If industrial scanners will read at small sizes → Data Matrix. If regulated by FDA, EU FMD, or aerospace standards → Data Matrix (mandated). If capacity above 2,335 characters is needed → QR Code. ### API Mock Data Generation for Frontend Development Frontend developers often need to work before the backend API is ready. Mock data generators create realistic API responses that match the expected schema, enabling parallel development. - URL: https://peasydev.com/guides/api-mock-data-generation/ - Category: Best Practice - Reading time: 1 min - Words: 289 Key takeaways: - Waiting for the backend to be complete before starting frontend work wastes time. - The simplest approach: create JSON files that mirror expected API responses. - Good mock servers simulate failure modes: - Cons: Setup overhead, must maintain mocks. - Pros: Always in sync with API contract. ## Why Mock APIs Waiting for the backend to be complete before starting frontend work wastes time. Mock APIs decouple the two teams, allowing parallel development with agreed-upon contracts (schemas). ## Approaches ### 1. Static JSON Files The simplest approach: create JSON files that mirror expected API responses. Serve them with a static file server or import directly in code. **Pros**: Zero setup, version-controlled. **Cons**: No dynamic behavior, stale quickly. ### 2. Mock Server Tools like MSW (Mock Service Worker), JSON Server, or Prism intercept API requests and return mock responses. MSW runs in the browser's service worker — no separate server process needed. **Pros**: Realistic network behavior, error simulation. **Cons**: Setup overhead, must maintain mocks. ### 3. Schema-Driven Generation Define your API with OpenAPI (Swagger) and use tools that auto-generate mock data from the schema. Libraries like Faker.js can populate schema-defined types with realistic values. **Pros**: Always in sync with API contract. **Cons**: Requires upfront schema definition. ## Mock Data Quality | Aspect | Bad Mock | Good Mock | |--------|---------|----------| | Names | 'Test User 1' | 'Alejandra Moreno' | | Dates | '2020-01-01' everywhere | Varied realistic dates | | IDs | 1, 2, 3 | UUIDs or realistic ID formats | | Lists | Always 3 items | Varying lengths (0, 1, 5, 20) | | Errors | Never tested | Include 404, 500, timeout scenarios | ## Error and Edge Case Simulation Good mock servers simulate failure modes: - Slow responses (add artificial latency) - Empty results (no data state) - Paginated results with varying page sizes - Authentication errors (401, 403) - Server errors (500, 503) - Network timeout Testing against these scenarios in development catches error handling bugs before they reach production. ### Best Practices for Handling Sensitive Data in the Browser Guidelines for safely processing passwords, keys, and personal data in client-side JavaScript. Covers memory handling, clipboard security, and preventing data leaks through browser APIs. - URL: https://peasydev.com/guides/handling-sensitive-data-browser-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 264 Key takeaways: - Processing sensitive data in the browser eliminates server-side exposure but introduces unique challenges. - JavaScript does not offer direct memory management, but you can minimize exposure. - The Clipboard API is convenient for password tools but requires caution: - Never store passwords, encryption keys, or tokens in `localStorage` — it persists across sessions and is accessible to any JavaScript running on the same origin. - Browser extensions run with elevated privileges and can intercept any data on the page. ## The Client-Side Security Model Processing sensitive data in the browser eliminates server-side exposure but introduces unique challenges. JavaScript runs in a shared memory space, browser extensions can inject scripts, and APIs like clipboard and localStorage persist data beyond the session. Careful handling prevents accidental leaks. ## Memory Handling JavaScript does not offer direct memory management, but you can minimize exposure. Overwrite sensitive variables with empty strings or random data when no longer needed. Avoid storing secrets in global variables — use closures or WeakRefs to limit scope and enable garbage collection. Never log sensitive values to the console, even during development. ## Clipboard Security The Clipboard API is convenient for password tools but requires caution: - Clear the clipboard after a timeout (30-60 seconds) - Use `navigator.clipboard.writeText()` instead of `document.execCommand('copy')` - Warn users before copying sensitive data - Never read from the clipboard without explicit user action ## Storage Considerations Never store passwords, encryption keys, or tokens in `localStorage` — it persists across sessions and is accessible to any JavaScript running on the same origin. Use `sessionStorage` for temporary data that should not survive tab closure. For encryption keys that must persist, use the Web Crypto API's `CryptoKey` objects with `extractable: false` to prevent the key from being read by JavaScript. ## Extension and DevTools Risks Browser extensions run with elevated privileges and can intercept any data on the page. Advise users processing highly sensitive data to use a clean browser profile with no extensions installed. DevTools memory snapshots can also expose in-memory secrets — this is a known limitation of client-side processing. ### Troubleshooting QR Code Scan Failures: Diagnosis and Fixes When a QR code fails to scan, the cause is usually one of five common issues: insufficient contrast, inadequate size, missing quiet zone, data corruption, or environmental interference. Systematic diagnosis identifies the fix quickly. - URL: https://peasydev.com/guides/troubleshooting-qr-code-scan-failures/ - Category: Troubleshooting - Reading time: 2 min - Words: 357 ## Diagnostic Flowchart ### Step 1: Does It Scan on Any Device? Test with 3+ different phones. If it scans on some but not others, the issue is marginal — the code is near the failure threshold. If it fails on all devices, the code itself is defective. ### Step 2: Check Contrast The most common cause of scan failure. Measure the contrast ratio between foreground and background. Minimum 4:1 for reliable scanning. Common contrast problems: - Dark blue on black (ratio ~2:1) - Light gray on white (ratio ~1.5:1) - Colored modules on colored background (perceived contrast varies) - Inverted colors (light modules on dark background) **Fix:** Regenerate with black modules on white background. ### Step 3: Check Size Measure the physical QR code size and the scanning distance. Apply the 10:1 rule — if the code is 2 cm wide and you are scanning from 50 cm away, it is too small. **Fix:** Increase the printed size or reduce scanning distance. ### Step 4: Check Quiet Zone Is there at least 4 modules of blank space around the code? Busy backgrounds, adjacent text, or decorative borders that intrude into the quiet zone cause the scanner to misidentify the code boundaries. **Fix:** Add a white border of at least 4 module widths around the code. ### Step 5: Check Data Integrity Decode the QR code using a verification tool to confirm the data is correct. Encoding errors — truncated URLs, special character corruption, wrong encoding mode — produce codes that decode to garbage data. **Fix:** Regenerate the code from the original source data. ## Environmental Issues - **Glare:** Glossy surfaces under direct light reflect into the camera. Use matte finish or angle the code away from light sources. - **Curvature:** Codes printed on bottles or cylinders distort the module … ### CAD File Formats: DXF, DWG, STEP, and IGES for Non-Engineers A practical guide to CAD file formats for developers, designers, and project managers who need to work with engineering files. Understand what each format contains and how to handle them. - URL: https://peasydev.com/guides/cad-file-formats-dxf-dwg-step-iges/ - Category: How-To - Reading time: 1 min - Words: 293 Key takeaways: - CAD files appear in web applications, data pipelines, and collaboration tools more often than many developers expect. - DWG is Autodesk's native binary format — the dominant standard in architecture and civil engineering. - STEP (Standard for the Exchange of Product Data) is the ISO standard for 3D solid model exchange. - For web-based CAD viewing, convert STEP/DXF to glTF for 3D or SVG for 2D. ## Why CAD Formats Matter Outside Engineering CAD files appear in web applications, data pipelines, and collaboration tools more often than many developers expect. Manufacturing companies share STEP files with suppliers, architectural firms distribute DWG drawings, and 3D printing services accept multiple CAD formats. Understanding the basics helps you handle them correctly. ## Format Overview | Format | Type | Standard | Primary Use | Open? | | --- | --- | --- | --- | --- | | DWG | 2D/3D | Autodesk proprietary | Architecture, mechanical | No | | DXF | 2D/3D | Autodesk (documented) | CAD interchange | Partially | | STEP (.stp) | 3D solid | ISO 10303 | Manufacturing exchange | Yes | | IGES (.igs) | 3D surface | ANSI Y14.26M | Legacy exchange | Yes | | Parasolid (.x_t) | 3D solid | Siemens | Solid modeling kernel | No | ## DWG and DXF: The AutoCAD Ecosystem DWG is Autodesk's native binary format — the dominant standard in architecture and civil engineering. DXF (Drawing Exchange Format) is the text-based interchange variant that most CAD software can read. When you receive DWG files but do not have AutoCAD, request DXF conversion or use open-source viewers. ## STEP: The Universal 3D Exchange STEP (Standard for the Exchange of Product Data) is the ISO standard for 3D solid model exchange. It preserves geometry, topology, and manufacturing information across different CAD systems. When a supplier sends you a 3D model, STEP is the safest format to request. ## Handling CAD Files in Web Applications For web-based CAD viewing, convert STEP/DXF to glTF for 3D or SVG for 2D. These web-native formats render in any browser without plugins. Libraries like Three.js can load converted models directly for interactive visualization. ### Certificate and Key Generation Basics for Developers SSL/TLS certificates, SSH keys, and API signing keys are essential for secure communication. This guide explains the types of keys, how to generate them, and common pitfalls. - URL: https://peasydev.com/guides/certificate-key-generation-basics/ - Category: Best Practice - Reading time: 1 min - Words: 299 Key takeaways: - SSH keys authenticate you to remote servers without passwords. - For local development, generate a self-signed certificate. - Many APIs require HMAC or RSA signatures for request authentication. - Using RSA-1024 (insecure since 2010) - ## Key Management Rules | Rule | Why | |------|-----| | Never commit private keys to Git | Keys in repo history are permanently exposed | | Use `. ## Symmetric vs Asymmetric Keys | Type | Description | Use Case | |------|-----------|----------| | Symmetric | Single shared secret | AES encryption, session keys | | Asymmetric | Public + private key pair | TLS, SSH, digital signatures | ## SSH Key Generation SSH keys authenticate you to remote servers without passwords. ### Recommended: Ed25519 `ssh-keygen -t ed25519 -C "your_email@example.com"` Ed25519 keys are shorter (68 chars vs 400+ for RSA), faster to verify, and more secure than RSA-2048. ### Legacy: RSA `ssh-keygen -t rsa -b 4096` Use RSA-4096 only when connecting to systems that do not support Ed25519. ## SSL/TLS Certificates ### Self-Signed (Development) For local development, generate a self-signed certificate. Browsers will show a warning, but the connection is encrypted. ### Let's Encrypt (Production) Free, automated, and trusted by all browsers. Certbot handles certificate issuance and renewal. Certificates expire every 90 days and should be auto-renewed via cron or systemd timer. ## Key Management Rules | Rule | Why | |------|-----| | Never commit private keys to Git | Keys in repo history are permanently exposed | | Use `.env` files or secret managers | 1Password, Vault, AWS Secrets Manager | | Rotate keys periodically | Limits exposure window if compromised | | Use minimum necessary key length | Ed25519 (256-bit) or RSA-4096 | | Protect private keys with passphrases | Second factor if key file is stolen | ## API Signing Keys Many APIs require HMAC or RSA signatures for request authentication. Generate a secure random key (32+ bytes for HMAC, 2048+ bits for RSA) and store it in a secrets manager. Never hardcode signing keys in application code. ## Common Mistakes - Using RSA-1024 (insecure since 2010) - Sharing private keys between environments - Ignoring certificate expiration alerts - Storing keys in plaintext config files ### Brand Color Consistency: Maintaining Colors Across Digital and Print The same hex code can look different on a monitor, a phone screen, and a printed brochure. This guide explains color profiles, gamut mapping, and practical techniques for brand color fidelity. - URL: https://peasydev.com/guides/brand-color-consistency-across-media/ - Category: Troubleshooting - Reading time: 1 min - Words: 278 Key takeaways: - Monitors use RGB light, printers use CMYK inks, and each device has a unique color gamut — the range of colors it can reproduce. - Color profiles define how numbers map to real colors. - CIE Lab is device-independent and represents human-perceived color. - Using CMYK values derived from a simple formula instead of the printer's actual ICC profile ## Why Colors Shift Across Media Monitors use RGB light, printers use CMYK inks, and each device has a unique color gamut — the range of colors it can reproduce. A vibrant electric blue on your monitor may print as a dull navy because CMYK cannot reproduce that specific blue wavelength. ## Color Profiles Color profiles define how numbers map to real colors. The most important profiles: | Profile | Use Case | Gamut | |---------|----------|------| | sRGB | Web, email, social | Standard (smallest) | | Display P3 | Apple devices, HDR | 25% larger than sRGB | | Adobe RGB | Photography, prepress | Wider greens and cyans | | CMYK (Fogra39) | European offset printing | Different shape (less red, more cyan) | ## Practical Workflow ### 1. Define Master Colors in Lab CIE Lab is device-independent and represents human-perceived color. Define your brand colors in Lab first, then derive sRGB, P3, and CMYK values from that reference. ### 2. Create a Brand Color Specification Document every color with its value in each target space: HEX for web, P3 for Apple, Pantone for spot-color printing, CMYK for process printing. Include acceptable tolerance ranges. ### 3. Soft-Proof Before Printing Use Photoshop or Acrobat soft-proofing (View > Proof Colors) with the printer's ICC profile to preview how digital colors will look on paper. Adjust problem areas before sending to press. ## Common Mistakes - Using CMYK values derived from a simple formula instead of the printer's actual ICC profile - Assuming Display P3 colors will look the same on sRGB monitors - Not testing brand colors on both OLED and LCD screens, which render saturated colors differently ### Slug and URL-Safe String Generation Best Practices Slugs transform human-readable titles into URL-safe strings. Proper slug generation handles unicode, special characters, and collisions while preserving readability. - URL: https://peasydev.com/guides/slug-url-safe-string-generation/ - Category: Best Practice - Reading time: 1 min - Words: 299 Key takeaways: - A slug is a URL-safe version of a string, typically derived from a title or name. - Convert accented characters to ASCII equivalents: ü → u, ñ → n, ø → o. - Two different titles can produce the same slug. - Keep slugs under 80 characters for readability and under 255 characters for filesystem compatibility. - Generate slugs on creation, not on every request ## What Is a Slug A slug is a URL-safe version of a string, typically derived from a title or name. 'How to Merge PDF Files' becomes `how-to-merge-pdf-files`. Slugs appear in URLs, filenames, and database identifiers. ## Generation Rules | Step | Input | Output | |------|-------|--------| | 1. Lowercase | 'Hello World' | 'hello world' | | 2. Transliterate | 'café résumé' | 'cafe resume' | | 3. Remove special chars | 'hello! world?' | 'hello world' | | 4. Replace spaces | 'hello world' | 'hello-world' | | 5. Collapse hyphens | 'hello--world' | 'hello-world' | | 6. Trim hyphens | '-hello-world-' | 'hello-world' | ## Unicode Handling ### Transliteration Convert accented characters to ASCII equivalents: ü → u, ñ → n, ø → o. Libraries like `python-slugify` and `slugify` (npm) handle this automatically with locale-aware rules. ### CJK Characters Chinese, Japanese, and Korean characters do not transliterate to Latin. Options: - Keep original characters in the URL (modern browsers display them correctly) - Romanize: 東京 → tokyo (requires language-specific romanization libraries) - Use a numeric or UUID identifier instead ## Collision Handling Two different titles can produce the same slug. Handle collisions by appending a counter: - `my-article` - `my-article-2` - `my-article-3` Check for existing slugs in the database before saving. Use a unique constraint as a safety net. ## Length Considerations Keep slugs under 80 characters for readability and under 255 characters for filesystem compatibility. Truncate at word boundaries to avoid cutting words in half. ## Implementation Tips - Generate slugs on creation, not on every request - Make slugs immutable after creation (changing them breaks URLs) - If a title changes, keep the old slug and add a redirect to the new URL - Store slugs in a dedicated indexed column for fast lookups ### Git Hooks for Code Quality: Pre-Commit, Pre-Push, and Beyond Git hooks automate code quality checks at commit and push time, catching issues before they enter the codebase. This guide covers setting up linting, formatting, type checking, and test hooks with practical examples. - URL: https://peasydev.com/guides/git-hooks-code-quality-guide/ - Category: How-To - Reading time: 2 min - Words: 342 Key takeaways: - Without automated checks, code quality depends entirely on developer discipline and code review. - Runs before a commit is created. - The `pre-commit` framework (pre-commit.com) manages hooks declaratively via a `.pre-commit-config.yaml` file: - Add a secret detection hook to prevent accidental commits of API keys, passwords, and tokens. - Hooks are local to each developer's machine — they're not automatically shared via Git. ## What Git Hooks Solve Without automated checks, code quality depends entirely on developer discipline and code review. Git hooks add an automated layer: linting runs before every commit, tests run before every push, and formatting is enforced consistently. Issues are caught in seconds on the developer's machine rather than minutes later in CI. ## Hook Types ### pre-commit Runs before a commit is created. If the hook exits with a non-zero status, the commit is aborted. This is the most commonly used hook. **Best for:** Linting, formatting, type checking, secret detection, file size limits, and trailing whitespace removal. ### pre-push Runs before `git push` sends data to the remote. Use for checks that are too slow for pre-commit but should catch issues before they reach the team. **Best for:** Running the full test suite, integration tests, build verification. ### commit-msg Validates the commit message format. Useful for enforcing conventional commit messages (`feat:`, `fix:`, `docs:`) that enable automated changelog generation. ## Setting Up Pre-Commit Hooks ### The pre-commit Framework The `pre-commit` framework (pre-commit.com) manages hooks declaratively via a `.pre-commit-config.yaml` file: ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-added-large-files args: ['--maxkb=500'] - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.8.0 hooks: - id: ruff args: [--fix] - id: ruff-format ``` ### Speed Optimization Pre-commit hooks should complete in under 5 seconds. Slow hooks frustrate developers and get bypassed with `--no-verify`. Only check staged files (not the entire codebase), use incremental checking tools, and skip expensive operations (full test suites belong in pre-push or CI). ## Secret Detection Add a secret detection hook to prevent accidental commits of API keys, passwords, and tokens. Tools like `detect-secrets` and `gitleaks` scan staged files for patterns matching common secret formats (AWS keys, JWT tokens, private keys). ## … ### Technical SEO Audit Checklist for Web Developers A technical SEO audit identifies crawlability, indexability, and performance issues that prevent search engines from properly ranking your site. This checklist covers the most impactful items. - URL: https://peasydev.com/guides/technical-seo-audit-checklist/ - Category: Best Practice - Reading time: 2 min - Words: 300 Key takeaways: - [ ] Robots.txt allows crawling of important pages - [ ] No accidental noindex tags on important pages - [ ] Unique title tag per page (50-60 chars) - [ ] HTTPS everywhere (no mixed content) - [ ] Core Web Vitals pass (LCP < 2.5s, INP < 200ms, CLS < 0.1) ## Crawlability - [ ] Robots.txt allows crawling of important pages - [ ] XML sitemap exists, is valid, and references only indexable URLs - [ ] No excessive crawl depth (important pages within 3 clicks) - [ ] No orphan pages (every page has at least one internal link) - [ ] Server responds within 200ms (TTFB) ## Indexability - [ ] No accidental noindex tags on important pages - [ ] Canonical tags present and correct on all pages - [ ] No duplicate titles or descriptions - [ ] Pagination uses self-referencing canonicals - [ ] Faceted navigation does not create combinatorial URL explosion ## On-Page SEO - [ ] Unique title tag per page (50-60 chars) - [ ] Meta description per page (150-160 chars) - [ ] Single H1 per page containing primary keyword - [ ] Logical heading hierarchy (H1 > H2 > H3) - [ ] Image alt text on all meaningful images - [ ] Internal links with descriptive anchor text ## Technical Infrastructure - [ ] HTTPS everywhere (no mixed content) - [ ] Proper 301 redirects (no chains or loops) - [ ] Custom 404 page with navigation - [ ] Hreflang tags for multilingual content - [ ] Structured data validates without errors ## Performance - [ ] Core Web Vitals pass (LCP < 2.5s, INP < 200ms, CLS < 0.1) - [ ] Gzip or Brotli compression enabled - [ ] Static assets cached with long max-age - [ ] Images optimized and served in next-gen formats ## Tools for Auditing | Tool | Focus | |------|------| | Screaming Frog | Crawl analysis, broken links | | Google Search Console | Indexing issues, performance | | Lighthouse | Performance, accessibility | | Ahrefs/SEMrush | Backlinks, keyword rankings | ### Timestamp and Date Generation Utilities for Developers Timestamps are the backbone of logging, scheduling, and data synchronization. This guide covers Unix timestamps, ISO 8601, and generating dates for testing various scenarios. - URL: https://peasydev.com/guides/timestamp-date-generation-utilities/ - Category: Comparison - Reading time: 2 min - Words: 318 Key takeaways: - Seconds since January 1, 1970 00:00:00 UTC (the Unix epoch). - Generate dates relative to 'now' for test scenarios: - Generate timestamps with various offsets to test timezone handling: - Always store timestamps in UTC and convert to local time only at the display layer. ## Timestamp Formats | Format | Example | Use Case | |--------|---------|----------| | Unix (seconds) | 1741564800 | APIs, databases | | Unix (milliseconds) | 1741564800000 | JavaScript, Java | | ISO 8601 | 2026-03-10T00:00:00Z | JSON, XML, display | | RFC 2822 | Tue, 10 Mar 2026 00:00:00 +0000 | Email headers | | Human readable | March 10, 2026 | UI display | ## Unix Timestamp Seconds since January 1, 1970 00:00:00 UTC (the Unix epoch). Simple, timezone-agnostic, and easy to compute durations by subtracting. **2038 problem**: 32-bit Unix timestamps overflow on January 19, 2038. Most modern systems use 64-bit timestamps, but check legacy systems. ## Generating Test Dates ### Relative Dates Generate dates relative to 'now' for test scenarios: - 1 hour ago (recently created) - 30 days ago (monthly billing cycle) - 366 days ago (leap year boundary) - 5 years in the future (subscription expiry) ### Boundary Dates | Scenario | Test Date | Why | |----------|-----------|-----| | Leap year | 2028-02-29 | Feb 29 exists | | Non-leap year | 2027-02-28 | Feb 29 does not exist | | Century leap year | 2000-02-29 | Divisible by 400, so it IS leap | | Non-century leap | 1900-02-28 | Divisible by 100 but not 400, NOT leap | | DST spring forward | 2026-03-08 02:30 EST | This time does not exist | | DST fall back | 2026-11-01 01:30 EST | This time occurs twice | | Year boundary | 2025-12-31 23:59:59 | Midnight rollover | ## Timezone Generation Generate timestamps with various offsets to test timezone handling: - UTC (Z or +00:00) - Positive offsets: +05:30 (India), +09:00 (Japan) - Negative offsets: -05:00 (EST), -08:00 (PST) - Half-hour offsets: +05:45 (Nepal), +09:30 (Australia Central) ## Best Practice Always store timestamps in UTC … ### CI/CD Pipeline Setup: From Code Push to Production Deploy A well-designed CI/CD pipeline catches bugs early, enforces code quality, and deploys with confidence. This guide walks through building a pipeline from scratch with lint, test, build, and deploy stages. - URL: https://peasydev.com/guides/ci-cd-pipeline-setup-guide/ - Category: How-To - Reading time: 2 min - Words: 375 Key takeaways: - Continuous Integration (CI) means every code change triggers automated checks — linting, type checking, unit tests, integration tests. - Tools: Ruff (Python), ESLint (JavaScript), Biome (JS/TS), golangci-lint (Go) - run: pip install ruff && ruff check . - Fail fast — run cheap checks before expensive ones. ## What CI/CD Means in Practice **Continuous Integration (CI)** means every code change triggers automated checks — linting, type checking, unit tests, integration tests. Broken code is detected within minutes, not days. **Continuous Deployment (CD)** extends this by automatically deploying code that passes all checks to staging or production. ## Pipeline Stages ### Stage 1: Lint and Format The fastest checks run first. Linting catches syntax errors, unused imports, and style violations in seconds. Formatting verification ensures consistent code style across the team. If linting fails, there's no point running slower tests. **Tools:** Ruff (Python), ESLint (JavaScript), Biome (JS/TS), golangci-lint (Go) ### Stage 2: Type Checking Static type analysis catches type errors without executing code. This stage runs in parallel with linting since they're independent. **Tools:** mypy (Python), TypeScript compiler, Flow (JavaScript) ### Stage 3: Unit Tests Unit tests verify individual functions and classes in isolation. They should complete in under 2 minutes for fast feedback. Mock external dependencies (databases, APIs) to keep unit tests fast and deterministic. ### Stage 4: Integration Tests Integration tests verify that components work together correctly — database queries return expected results, API endpoints respond correctly, and background jobs process as expected. These are slower (5-15 minutes) and may require database fixtures or Docker containers. ### Stage 5: Build Compile the application, build Docker images, bundle frontend assets, and generate static files. The build output is an artifact that can be deployed to any environment. ### Stage 6: Deploy Deploy the build artifact to the target environment. For staging, this may be automatic. For production, add a manual approval gate. Post-deploy, run smoke tests to verify the deployment is healthy. ## Pipeline Configuration Example ```yaml # GitHub Actions example name: CI/CD on: [push, pull_request] jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: pip … ### Time Zone Math and Date Calculations Explained Time zone conversions, daylight saving transitions, and date arithmetic are notoriously error-prone. This guide covers the rules and edge cases that trip up even experienced developers. - URL: https://peasydev.com/guides/time-zone-math-date-calculations/ - Category: Troubleshooting - Reading time: 2 min - Words: 307 Key takeaways: - Coordinated Universal Time (UTC) is the zero-offset reference point. - DST shifts clocks forward (spring) and backward (fall), changing the UTC offset temporarily. - Convert both dates to a day count (Julian Day Number or Unix timestamp) and subtract. - The international standard for date/time strings: - Assuming all days have 24 hours (DST days have 23 or 25) ## UTC as the Universal Reference Coordinated Universal Time (UTC) is the zero-offset reference point. All time zones are expressed as offsets from UTC: EST is UTC-5, JST is UTC+9. To convert between zones: subtract the source offset and add the target offset. Example: 3:00 PM EST (UTC-5) to JST (UTC+9): `15:00 + 5 (to UTC) + 9 (to JST) = 29:00 = 05:00 next day` ## Daylight Saving Time DST shifts clocks forward (spring) and backward (fall), changing the UTC offset temporarily. Not all regions observe DST, and transition dates vary by country: | Region | Spring Forward | Fall Back | |--------|---------------|----------| | US/Canada | 2nd Sunday March | 1st Sunday November | | EU | Last Sunday March | Last Sunday October | | Australia | 1st Sunday October | 1st Sunday April | During the spring transition, 2:00 AM jumps to 3:00 AM — the hour from 2:00 to 2:59 does not exist. In fall, 1:00-1:59 AM occurs twice. ## Date Arithmetic ### Days Between Dates Convert both dates to a day count (Julian Day Number or Unix timestamp) and subtract. Account for leap years: a year is leap if divisible by 4, except centuries unless divisible by 400. ### Adding Months Adding 1 month to January 31 creates an ambiguous result (February 31 does not exist). Libraries typically clamp to the last valid day of the target month (February 28/29). ## ISO 8601 Format The international standard for date/time strings: `2026-03-10T14:30:00+09:00` Always store datetimes in UTC and convert to local time zones for display. This prevents ambiguity and simplifies calculations. ## Common Mistakes - Assuming all days have 24 hours (DST days have 23 or 25) - Hardcoding UTC offsets instead of using timezone database names (America/New_York) - Calculating age by subtracting years without checking … ### JWT Token Generation and Structure Explained JSON Web Tokens (JWT) are the standard for stateless authentication. Understanding their structure, signing algorithms, and security considerations prevents common vulnerabilities. - URL: https://peasydev.com/guides/jwt-token-generation-structure/ - Category: Comparison - Reading time: 1 min - Words: 264 Key takeaways: - A JWT consists of three Base64URL-encoded parts separated by dots: - Always validate the `exp` claim server-side - If the server accepts `alg: none`, an attacker can forge tokens without a signature. - Always whitelist accepted algorithms server-side. - Always transmit tokens in the Authorization header or HTTP-only cookies. ## JWT Structure A JWT consists of three Base64URL-encoded parts separated by dots: `header.payload.signature` ### Header ```json {"alg": "HS256", "typ": "JWT"} ``` Specifies the signing algorithm and token type. ### Payload (Claims) ```json { "sub": "1234567890", "name": "John Doe", "iat": 1741564800, "exp": 1741568400 } ``` Standard claims: `iss` (issuer), `sub` (subject), `exp` (expiration), `iat` (issued at), `aud` (audience), `nbf` (not before). ### Signature `HMAC-SHA256(base64(header) + '.' + base64(payload), secret)` ## Signing Algorithms | Algorithm | Type | Key | Use Case | |-----------|------|-----|----------| | HS256 | Symmetric | Shared secret | Single-server apps | | RS256 | Asymmetric | RSA key pair | Microservices, third-party verification | | ES256 | Asymmetric | ECDSA key pair | Mobile apps (smaller keys) | | none | No signature | — | NEVER use (vulnerability) | ## Security Best Practices - Always validate the `exp` claim server-side - Use short expiration times (15 minutes for access tokens) - Use refresh tokens for re-authentication - Never store sensitive data in the payload (it is only Base64 encoded, not encrypted) - Reject tokens with `alg: none` - Validate the `iss` and `aud` claims ## Common Vulnerabilities ### Algorithm Confusion If the server accepts `alg: none`, an attacker can forge tokens without a signature. Always whitelist accepted algorithms server-side. ### Excessive Token Lifetime Long-lived tokens (hours or days) give attackers a wide window if stolen. Use short-lived access tokens + refresh token rotation. ### Token in URL Parameters JWTs in URLs appear in server logs, browser history, and Referer headers. Always transmit tokens in the Authorization header or HTTP-only cookies. ### Code Formatting Tools Compared: Prettier vs ESLint vs Biome Consistent code formatting eliminates style debates and reduces diff noise in code reviews. Prettier, ESLint, and Biome take different approaches to formatting and linting. This comparison helps you choose the right tool. - URL: https://peasydev.com/guides/code-formatting-prettier-eslint-biome/ - Category: Comparison - Reading time: 2 min - Words: 387 Key takeaways: - Code formatting debates (tabs vs spaces, semicolons vs no semicolons, trailing commas) consume disproportionate review time. - Prettier is an opinionated formatter for JavaScript, TypeScript, CSS, HTML, JSON, Markdown, and more. - ESLint is primarily a linter (code quality checker) for JavaScript/TypeScript, but with plugins like `eslint-plugin-prettier` or its built-in formatting rules, it can also enforce formatting. - Biome (formerly Rome) is a Rust-based all-in-one tool that combines formatting and linting in a single binary. ## Why Consistent Formatting Matters Code formatting debates (tabs vs spaces, semicolons vs no semicolons, trailing commas) consume disproportionate review time. An automated formatter ends these debates permanently: the tool decides, everyone follows, and code reviews focus on logic instead of style. ## Prettier Prettier is an opinionated formatter for JavaScript, TypeScript, CSS, HTML, JSON, Markdown, and more. Its key philosophy: minimal configuration. Prettier makes most formatting decisions for you, offering fewer than 20 options. **Strengths:** - Broad language support (JS, TS, CSS, HTML, JSON, MD, YAML, GraphQL) - Truly opinionated — minimal configuration debates - Excellent IDE integration - Industry standard for JavaScript/TypeScript projects **Weaknesses:** - Formatter only — does not catch code quality issues (unused variables, bugs) - Some formatting decisions are controversial and non-configurable - Performance can be slow on large codebases (Node.js-based) ## ESLint ESLint is primarily a linter (code quality checker) for JavaScript/TypeScript, but with plugins like `eslint-plugin-prettier` or its built-in formatting rules, it can also enforce formatting. ESLint 9's flat config simplified configuration. **Strengths:** - Code quality rules beyond formatting (no-unused-vars, no-undef, complexity) - Highly configurable — hundreds of rules, each independently toggleable - Auto-fix capability for many issues - Massive plugin ecosystem **Weaknesses:** - Configuration complexity (config files can grow to hundreds of lines) - Formatting rules conflict with Prettier if both are used - Slower than dedicated formatters for pure formatting tasks - JavaScript/TypeScript only (no CSS, HTML, Markdown) ## Biome Biome (formerly Rome) is a Rust-based all-in-one tool that combines formatting and linting in a single binary. It's dramatically faster than Prettier and ESLint because it's compiled, not interpreted. **Strengths:** - 10-100x faster than Prettier + ESLint combined - Single tool for both formatting and linting - Zero-config defaults that match Prettier's output - No Node.js dependency (standalone Rust binary) **Weaknesses:** … ### Design Handoff Best Practices: From Figma to Production Poor design handoff causes miscommunication, wasted developer time, and pixel-imperfect implementations. A structured handoff process bridges the gap between design intent and code. - URL: https://peasydev.com/guides/design-handoff-best-practices/ - Category: Best Practice - Reading time: 1 min - Words: 277 Key takeaways: - The most common handoff failures are missing states (hover, disabled, error, empty, loading), undefined responsive behavior, and ambiguous spacing values. - Document every interactive state for each component as a Figma variant: default, hover, focus, active, disabled, loading, error, and success. - Schedule a design review before launch. ## Why Handoff Fails The most common handoff failures are missing states (hover, disabled, error, empty, loading), undefined responsive behavior, and ambiguous spacing values. Developers fill gaps with guesses that diverge from design intent. ## The Handoff Checklist ### 1. Component States Document every interactive state for each component as a Figma variant: default, hover, focus, active, disabled, loading, error, and success. Missing states are the number one source of design-dev discrepancies. ### 2. Responsive Specifications Provide layouts at three to four breakpoints: mobile (375px), tablet (768px), desktop (1280px), and optionally large desktop (1536px). Annotate which elements stack, hide, resize, or reorder at each breakpoint. ### 3. Spacing and Alignment Use auto layout in Figma with explicit gap and padding values. Developers can read these values directly from the Inspect panel without measuring pixel distances between elements. ### 4. Content Extremes Show designs with minimum and maximum content lengths. What happens when a username is 3 characters versus 30? When a product description is one line versus ten? Edge cases reveal layout fragility. ### 5. Animation Specifications Describe motion with timing (duration in ms), easing curve (ease-in-out, spring), and trigger event (on hover, on mount, on scroll). Use Figma prototyping or record a short video reference. ## Tools and Formats | Tool | Strength | |------|--------| | Figma Dev Mode | Inspect values, copy CSS snippets | | Storybook | Interactive component documentation | | Zeroheight | Design system documentation | | Loom/video recordings | Animation and interaction specs | ## Post-Handoff QA Schedule a design review before launch. Compare the implementation to the original designs at each breakpoint, checking spacing, typography, color accuracy, and interactive states. ### Developer Productivity CLI Tools You Should Know The command line remains the most efficient interface for many developer tasks. Modern CLI tools offer dramatic speed improvements, better defaults, and richer output compared to their traditional Unix counterparts. - URL: https://peasydev.com/guides/developer-productivity-cli-tools/ - Category: How-To - Reading time: 2 min - Words: 414 Key takeaways: - A new generation of CLI tools, many written in Rust, replaces traditional Unix commands with faster, more user-friendly alternatives. - `fd` is a fast, user-friendly alternative to `find`. - `bat` displays file contents with syntax highlighting, line numbers, and git diff markers. - `jq` is essential for working with JSON API responses. - On macOS, install everything via Homebrew: `brew install fd ripgrep fzf bat eza delta jq httpie direnv`. ## The Modern CLI Renaissance A new generation of CLI tools, many written in Rust, replaces traditional Unix commands with faster, more user-friendly alternatives. These tools maintain compatibility with their predecessors while adding features like syntax highlighting, fuzzy matching, and intelligent defaults. ## File Navigation and Search ### fd (find replacement) `fd` is a fast, user-friendly alternative to `find`. It ignores `.gitignore` patterns by default, uses regex, and provides colorized output. Finding all Python files: `fd -e py` instead of `find . -name '*.py'`. ### ripgrep (grep replacement) `rg` searches file contents faster than grep by respecting `.gitignore`, using parallelism, and skipping binary files. Search for a function name: `rg 'def process_image'` instead of `grep -r 'def process_image' .` ### fzf (fuzzy finder) `fzf` adds fuzzy search to any command. Pipe file lists, command history, or git branches through `fzf` for interactive selection. Press `Ctrl+R` with fzf installed for fuzzy command history search — far superior to the default reverse search. ## Better Defaults ### bat (cat replacement) `bat` displays file contents with syntax highlighting, line numbers, and git diff markers. It automatically pipes through a pager for long files. Use it as a drop-in `cat` replacement: `alias cat='bat'`. ### eza (ls replacement) `eza` replaces `ls` with colorized output, git status indicators, and tree views. `eza -la --git` shows permissions, sizes, and git status in a single command. `eza --tree --level=3` replaces `tree -L 3` with better formatting. ### delta (diff replacement) `delta` enhances `git diff` output with syntax highlighting, side-by-side view, and line numbers. Configure it as your default git pager: `git config --global core.pager delta`. ## Development Workflow ### jq (JSON processor) `jq` is essential for working with JSON API responses. Pretty-print: `curl -s api.example.com | jq .` — Extract fields: `jq '.data[] | .name'` — Filter: `jq … ### Troubleshooting Video Playback: Codec Errors, Black Screens, and Audio Sync Video playback problems — black screens, no audio, stuttering, or sync issues — usually stem from codec incompatibilities or corrupted containers. - URL: https://peasydev.com/guides/troubleshooting-video-playback-issues/ - Category: Troubleshooting - Reading time: 1 min - Words: 256 Key takeaways: - Cause: The video codec is not supported by the player or browser. - Cause: Mismatched container and codec. - Cause: Variable frame rate (VFR) recordings from phones or screen capture tools. - Cause: Bitrate exceeds available bandwidth or decode capability. - Cause: GPU driver issues with hardware-accelerated decoding. ## Black Screen with Audio **Cause:** The video codec is not supported by the player or browser. Common with HEVC (H.265) in Chrome/Firefox. **Fix:** Re-encode to H.264, which is universally supported. Alternatively, install the appropriate codec pack for desktop players. ## Audio but No Video (or Vice Versa) **Cause:** Mismatched container and codec. The container (MP4) may declare one codec while containing another, or the audio codec is unsupported. **Fix:** Inspect the file's actual codecs (not just the file extension). Re-encode the problematic stream only. ## Audio-Video Sync Drift **Cause:** Variable frame rate (VFR) recordings from phones or screen capture tools. Players assume constant frame rate and accumulate timing errors. **Fix:** Convert VFR to constant frame rate (CFR) by re-encoding. Set the target frame rate to match the source's average frame rate. ## Stuttering and Buffering **Cause:** Bitrate exceeds available bandwidth or decode capability. 4K HEVC requires significant CPU/GPU power. **Fix:** Reduce resolution or bitrate. Enable hardware acceleration in the player. For streaming, use adaptive bitrate with a lower starting quality. ## Green or Purple Artifacts **Cause:** GPU driver issues with hardware-accelerated decoding. Common with AMD GPUs and VP9/AV1 content. **Fix:** Update GPU drivers. Disable hardware acceleration in the browser (Settings > System). If the issue is in an exported file, the encoder may have a bug — try a different encoder. ## File Won't Open **Cause:** Corrupted container header, incomplete download, or wrong file extension. **Fix:** Try renaming to the correct extension. Use a repair tool that rebuilds the container index from the stream data. ## Glossary (65 terms) ### 12-Factor App (Twelve-Factor Application) A methodology of twelve best practices for building scalable, maintainable software-as-a-service applications. - URL: https://peasydev.com/glossary/12-factor-app/ ### API Gateway (API Gateway) A server that acts as a single entry point for API requests, handling routing, authentication, and rate limiting. - URL: https://peasydev.com/glossary/api-gateway/ ### AST (Abstract Syntax Tree) A tree representation of the syntactic structure of source code, used by compilers and code analysis tools. - URL: https://peasydev.com/glossary/ast/ ### Backpressure (Stream Backpressure) A flow control mechanism where a slow consumer signals a fast producer to reduce its output rate, preventing buffer overflow. - URL: https://peasydev.com/glossary/backpressure/ ### Base58 (Base58 Encoding) A binary-to-text encoding that excludes visually ambiguous characters (0, O, I, l), used in Bitcoin addresses. - URL: https://peasydev.com/glossary/base58/ ### Canary Release (Canary Deployment) A deployment strategy that routes a small percentage of traffic to a new version to detect issues before full rollout. - URL: https://peasydev.com/glossary/canary-release/ ### CI/CD (Continuous Integration / Continuous Deployment) A development practice where code changes are automatically built, tested, and deployed to production. - URL: https://peasydev.com/glossary/cicd/ ### CIDR (Classless Inter-Domain Routing) A notation for IP address ranges using a base address and prefix length (e.g. 192.168.1.0/24). - URL: https://peasydev.com/glossary/cidr/ ### Content Negotiation (HTTP Content Negotiation) A mechanism where the client and server agree on the best representation of a resource using Accept headers. - URL: https://peasydev.com/glossary/content-negotiation/ ### CORS Preflight (CORS Preflight Request) An automatic OPTIONS request sent by browsers before cross-origin requests to check server permissions. - URL: https://peasydev.com/glossary/cors-preflight/ ### Cron Expression (Cron Schedule Expression) A string format representing a schedule using five fields: minute, hour, day, month, and day of week. - URL: https://peasydev.com/glossary/cron-expression/ ### Dead Letter Queue (Dead Letter Queue (DLQ)) A message queue that stores messages that could not be processed successfully, enabling later inspection and retry. - URL: https://peasydev.com/glossary/dead-letter-queue/ ### Debounce (Function Debouncing) Delaying a function execution until a specified time has passed since the last invocation. - URL: https://peasydev.com/glossary/debounce/ ### Diff Algorithm (Difference Algorithm) An algorithm (e.g. Myers, patience) that computes the minimal set of changes between two sequences of text. - URL: https://peasydev.com/glossary/diff-algorithm/ ### DNS (Domain Name System) The hierarchical naming system that translates human-readable domain names into IP addresses. - URL: https://peasydev.com/glossary/dns/ ### Docker (Docker Container Platform) A platform for building, shipping, and running applications in lightweight, isolated containers that share the host OS kernel. - URL: https://peasydev.com/glossary/docker/ ### Edge Computing (Edge Computing) Processing data closer to the user at network edge locations to reduce latency and bandwidth usage. - URL: https://peasydev.com/glossary/edge-computing/ ### Endian Swap (Byte Order Swap) Reversing the byte order of a multi-byte value, converting between big-endian and little-endian formats. - URL: https://peasydev.com/glossary/endian-swap/ ### Environment Variable (Environment Variable) A key-value pair set in the operating system environment, used to configure application behavior. - URL: https://peasydev.com/glossary/environment-variable/ ### Epoch Time (Unix Epoch Timestamp) The number of seconds elapsed since January 1, 1970 UTC, used as a universal time reference. - URL: https://peasydev.com/glossary/epoch-time/ ### ETag (Entity Tag) An HTTP header providing a unique identifier for a specific version of a resource, used for cache validation. - URL: https://peasydev.com/glossary/etag/ ### Feature Flag (Feature Flag (Feature Toggle)) A configuration switch that enables or disables features at runtime without deploying new code, used for gradual rollouts and A/B testing. - URL: https://peasydev.com/glossary/feature-flag/ ### Glob Pattern (Glob Pattern Matching) A wildcard syntax for matching file paths using characters like * (any) and ? (single character). - URL: https://peasydev.com/glossary/glob-pattern/ ### GraphQL (Graph Query Language) A query language for APIs that lets clients request exactly the data they need in a single request. - URL: https://peasydev.com/glossary/graphql/ ### gRPC (gRPC Remote Procedure Call) A high-performance RPC framework using HTTP/2 and Protocol Buffers for efficient service-to-service communication. - URL: https://peasydev.com/glossary/grpc/ ### Hex Encoding (Hexadecimal Encoding) Representing binary data as a string of hexadecimal (base-16) characters, using digits 0-9 and letters A-F. - URL: https://peasydev.com/glossary/hex-encoding/ ### HTTP Status Code (HTTP Response Status Code) A three-digit code indicating the result of an HTTP request (e.g. 200 OK, 404 Not Found, 500 Server Error). - URL: https://peasydev.com/glossary/http-status-code/ ### Idempotent (Idempotent Operation) An operation that produces the same result regardless of how many times it is applied. - URL: https://peasydev.com/glossary/idempotent/ ### ISO 8601 (ISO 8601 Date Format) An international standard for date and time representation (e.g. 2026-03-08T14:30:00Z). - URL: https://peasydev.com/glossary/iso-8601/ ### JQ (JQ Command-Line Processor) A lightweight command-line tool for filtering, transforming, and querying JSON data using a concise syntax. - URL: https://peasydev.com/glossary/jq/ ### JSON Lines (JSON Lines (NDJSON)) A text format where each line is a valid JSON value, designed for streaming and log processing one record at a time. - URL: https://peasydev.com/glossary/json-lines/ ### JSON Patch (JSON Patch (RFC 6902)) A format for describing a sequence of operations to modify a JSON document (add, remove, replace, move). - URL: https://peasydev.com/glossary/json-patch/ ### JSON Schema (JSON Schema) A vocabulary for annotating and validating the structure, types, and constraints of JSON documents. - URL: https://peasydev.com/glossary/json-schema/ ### Kubernetes (Kubernetes Container Orchestration) An open-source system for automating deployment, scaling, and management of containerized applications across clusters. - URL: https://peasydev.com/glossary/kubernetes/ ### Microservices (Microservices Architecture) A design pattern where an application is composed of small, independently deployable services communicating via APIs. - URL: https://peasydev.com/glossary/microservices/ ### Monorepo (Monolithic Repository) A version control strategy where multiple projects or packages are stored in a single repository, simplifying dependency management. - URL: https://peasydev.com/glossary/monorepo/ ### OAuth 2.0 (OAuth 2.0 Authorization Framework) An authorization protocol allowing third-party applications to access resources on behalf of a user without sharing credentials. - URL: https://peasydev.com/glossary/oauth-20/ ### OpenAPI (OpenAPI Specification) A standard for describing RESTful APIs in a machine-readable format (formerly known as Swagger). - URL: https://peasydev.com/glossary/openapi/ ### Polyfill (Browser Polyfill) JavaScript code that implements a modern API on older browsers that lack native support, enabling cross-browser compatibility. - URL: https://peasydev.com/glossary/polyfill/ ### Protocol Buffers (Protocol Buffers (Protobuf)) A language-neutral binary serialization format by Google, more compact and faster than JSON or XML. - URL: https://peasydev.com/glossary/protocol-buffers/ ### Rate Limiting (API Rate Limiting) Restricting the number of API requests a client can make within a given time window. - URL: https://peasydev.com/glossary/rate-limiting/ ### REST (Representational State Transfer) An architectural style for web APIs using standard HTTP methods to access and manipulate resources. - URL: https://peasydev.com/glossary/rest/ ### RFC (Request for Comments) A publication by internet standards bodies like the IETF that defines protocols, procedures, and conventions for internet technologies. - URL: https://peasydev.com/glossary/rfc/ ### Semver (Semantic Versioning) A versioning scheme using MAJOR.MINOR.PATCH format to communicate the nature of changes in software. - URL: https://peasydev.com/glossary/semver/ ### Serverless (Serverless Computing) A cloud execution model where the provider manages server infrastructure and scales automatically per request. - URL: https://peasydev.com/glossary/serverless/ ### Service Worker (Service Worker) A browser script running in the background that enables offline caching, push notifications, and network interception. - URL: https://peasydev.com/glossary/service-worker/ ### Shebang (Shebang Line) The #! characters at the start of a script file specifying which interpreter should execute it. - URL: https://peasydev.com/glossary/shebang/ ### Source Map (JavaScript Source Map) A file mapping minified or transpiled code back to the original source, enabling readable stack traces during debugging. - URL: https://peasydev.com/glossary/source-map/ ### SQL (Structured Query Language) A language for managing and querying relational databases using statements like SELECT, INSERT, and UPDATE. - URL: https://peasydev.com/glossary/sql/ ### SSE (Server-Sent Events) A standard allowing servers to push real-time updates to the browser over a single HTTP connection. - URL: https://peasydev.com/glossary/sse/ ### STDIN (Standard Input) The default input stream for a program, typically connected to the keyboard or piped from another command. - URL: https://peasydev.com/glossary/stdin/ ### Terraform (HashiCorp Terraform) An infrastructure-as-code tool that defines cloud resources in declarative configuration files for reproducible deployments. - URL: https://peasydev.com/glossary/terraform/ ### Throttle (Function Throttling) Limiting a function to execute at most once per specified time interval, regardless of how often it is called. - URL: https://peasydev.com/glossary/throttle/ ### TOML (Tom's Obvious Minimal Language) A configuration file format designed to be easy to read and map to a dictionary data structure. - URL: https://peasydev.com/glossary/toml/ ### Tree Shaking (Dead Code Elimination (Tree Shaking)) A build optimization that removes unused exports from JavaScript modules, reducing the final bundle size. - URL: https://peasydev.com/glossary/tree-shaking/ ### Type Coercion (Type Coercion) The automatic or implicit conversion of a value from one data type to another (e.g. string to number). - URL: https://peasydev.com/glossary/type-coercion/ ### URI (Uniform Resource Identifier) A string that identifies a resource, encompassing both URLs (locators) and URNs (names). - URL: https://peasydev.com/glossary/uri/ ### UUID (Universally Unique Identifier) A 128-bit identifier guaranteed to be unique across space and time, formatted as a 36-character string. - URL: https://peasydev.com/glossary/uuid/ ### WASM (WebAssembly) A binary instruction format enabling near-native performance for code running in web browsers. - URL: https://peasydev.com/glossary/wasm/ ### Webhook (HTTP Webhook) An HTTP callback that automatically sends data to a specified URL when a specific event occurs. - URL: https://peasydev.com/glossary/webhook/ ### WebSocket (WebSocket Protocol) A communication protocol providing full-duplex, persistent connections between a client and server over a single TCP connection. - URL: https://peasydev.com/glossary/websocket/ ### Web Worker (Web Worker) A JavaScript execution context running in a background thread, enabling CPU-intensive tasks without blocking the UI. - URL: https://peasydev.com/glossary/web-worker/ ### XML (Extensible Markup Language) A markup language for encoding structured data in a format readable by both humans and machines. - URL: https://peasydev.com/glossary/xml/ ### XPath (XML Path Language) A query language for selecting nodes from an XML document using path expressions. - URL: https://peasydev.com/glossary/xpath/ ### XSLT (Extensible Stylesheet Language Transformations) A language for transforming XML documents into other formats such as HTML, text, or different XML structures. - URL: https://peasydev.com/glossary/xslt/ ## API Base URL: https://peasydev.com/api/v1/ | Endpoint | Description | |----------|-------------| | GET /api/v1/tools/ | List all tools (filterable by category) | | GET /api/v1/tools/{slug}/ | Tool detail with description, steps, FAQ | | GET /api/v1/categories/ | Tool categories | | GET /api/v1/formats/ | File formats reference | | GET /api/v1/formats/{slug}/ | Format detail with history, pros/cons | | GET /api/v1/conversions/ | Format conversion guides | | GET /api/v1/glossary/ | Terminology with definitions | | GET /api/v1/glossary/{slug}/ | Term with simple + technical explanations, code examples, references | | GET /api/v1/guides/ | Educational guides (filterable by category, audience_level) | | GET /api/v1/guides/{slug}/ | Full guide with content, takeaways, ToC, related guides | | GET /api/v1/use-cases/ | Real-world use cases by industry | | GET /api/v1/search/?q={query} | Cross-model search | | GET /api/v1/sites/ | All 16 Peasy sites | OpenAPI spec: https://peasydev.com/api/openapi.json ## Content Negotiation All pages support Markdown output for AI agents: - Add `?format=md` to any page URL - Or send `Accept: text/markdown` header ## Platform Stats - 251 tools across 16 sites - 131 file formats documented - 1484 format conversion guides - 695 glossary terms (with simple + technical explanations) - 645 educational guides (avg 1,308 words) - 302 real-world use cases