rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};

#[derive(Default)]
struct Metrics {
    per_endpoint: HashMap<String, u64>,

Thread-Safe Request Metrics with Arc, Mutex, and a Poison-Recovery Guard

rust concurrency arc
by codesnips 3 tabs
python
import base64
import json

from django.core.exceptions import BadRequest

Cursor-Paginated JSON Feed with a Django Class-Based ListView

django pagination cursor-pagination
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  has_many :line_items, inverse_of: :order, dependent: :destroy

  accepts_nested_attributes_for :line_items,
    allow_destroy: true,
    reject_if: ->(attrs) { attrs["product_id"].blank? && attrs["quantity"].blank? }

Validate Nested Attributes for an Order and Its Line Items in Rails

rails activerecord validations
by codesnips 3 tabs
typescript
import { z } from "zod";

export const signupSchema = z
  .object({
    email: z.string().min(1, "Email is required").email("Enter a valid email"),
    username: z

React Signup Form Validation With Zod and Field-Level Errors

react zod forms
by codesnips 3 tabs
python
import io
import os
from uuid import uuid4
from PIL import Image, UnidentifiedImageError

ALLOWED_FORMATS = {"JPEG", "PNG", "WEBP"}

Validate and Generate Image Thumbnails on a Flask Upload Endpoint With Pillow

flask pillow image-processing
by codesnips 3 tabs
go
package export

import (
	"encoding/csv"
	"log"
	"net/http"

Streaming Large CSV Exports in Go Without Buffering the Whole File

go http csv
by codesnips 3 tabs
rust
use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer};

#[derive(Debug, Clone, Deserialize)]
pub struct Transaction {

Aggregate CSV Transaction Totals per Category With Serde and csv Crate

rust csv serde
by codesnips 3 tabs
javascript
'use strict';

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function backoffDelay(attempt, baseMs, maxDelayMs) {
  const exponential = baseMs * 2 ** attempt;

Retry Failed Async Operations With Exponential Backoff and Jitter in Node.js

nodejs retry backoff
by codesnips 2 tabs
rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Interval {
    pub start: i64,
    pub end: i64,
}

Merging Overlapping Booking Intervals with a Sweep-Line in Rust

rust algorithms intervals
by codesnips 3 tabs
ruby
class AddVersionsToArticles < ActiveRecord::Migration[7.1]
  def change
    add_column :articles, :versions, :jsonb, null: false, default: []
    add_index :articles, :versions, using: :gin
  end
end

Versioning Rails Records with a JSON Snapshot Column and Diff Helper

rails postgres jsonb
by codesnips 3 tabs
typescript
import { useCallback, useEffect, useState } from "react";

type Patch = Record<string, string | null | undefined>;

function readParams(): URLSearchParams {
  return new URLSearchParams(window.location.search);

Sync a Filter Panel to the URL Query String with a Custom useSearchParams Hook

react hooks url-state
by codesnips 3 tabs
java
@Entity
@Table(name = "stored_files")
public class StoredFile {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

Spring Boot Multipart File Upload with Metadata Persistence and Validation

spring-boot multipart file-upload
by codesnips 3 tabs