Skip to content

Archive / page 96

All articles

Every practical article from the Nalar archive, newest first.

JavaScript Updated 07 Sep 2025 2 min read

Understanding the Differences Between pnpm, Yarn, npm, and Bun

JavaScript projects commonly use npm, Yarn, pnpm, or Bun to install dependencies and run package scripts. They all work with the npm package ecosystem, but they differ in installation strategy, lockfiles, workspace tooling, runtime integration, and compatibility details. npm npm ships with Node.js and is the most universal default. It supports lockfiles, workspaces, package scripts, and the standard npm registry with minimal setup. npm install npm run build Choose npm when you want the conventional Node.js toolchain and broad compatibility without adding another package manager.

JavaScript Updated 07 Sep 2025 2 min read

Create a Simple Static Web Server with `http-server`

When you need to test static HTML, CSS, JavaScript, images, or a generated site locally, the Node.js package http-server provides a small command-line server with minimal setup. Run It Without a Global Install If Node.js and npm are already installed, you can run the package with npx: npx http-server . The final . means “serve the current directory.” The command prints the local addresses and port it is using.

CSS Updated 02 Sep 2025 2 min read

Create a Hover Zoom Effect with Tailwind CSS

Small interactions can make a web page feel more polished. One simple example is a zoom effect when the pointer hovers over an image. With Tailwind CSS, you can build it with utility classes instead of writing a separate CSS rule. 1. HTML Structure Here is a basic example: <div class="relative"> <img src="https://picsum.photos/500/300.webp" alt="Image" class="hover:scale-125 transition-transform duration-300 ease-in-out"> </div> 2. What Do the Tailwind Classes Do? relative → gives the wrapper relative positioning. It does not create the zoom effect itself, but it is useful if you later add positioned overlays. hover:scale-125 → scales the image to 125% while it is hovered. transition-transform → animates changes to the transform property. duration-300 → makes the transition last 300 milliseconds. ease-in-out → starts and ends the transition gradually for a smoother feel. 3. Customize It Use a larger scale:

CSS Updated 02 Sep 2025 2 min read

Build a Masonry Gallery with a Zoom Effect in Tailwind CSS

Have you seen photo galleries where images are arranged like a brick wall in a masonry layout and smoothly zoom when you hover over them? You can build that effect with only a few Tailwind CSS utility classes. In this article, we will create a responsive masonry gallery with a hover zoom effect. 1. Gallery HTML Structure A few div elements with Tailwind classes are enough to create the layout:

Web Development Updated 02 Sep 2025 3 min read

Data Validation in Laravel: A Complete Developer Guide

Validation is an important boundary in web applications. It ensures incoming data has the shape and constraints your application expects before that data reaches business logic or persistence. Laravel provides several validation APIs, from quick controller validation to reusable Form Request classes and custom rules. 1. Basic Validation For small request handlers, call validate() on the request: use Illuminate\Http\Request; public function store(Request $request) { $validatedData = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', 'unique:users,email'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); // Use $validatedData rather than the entire request payload. } For a normal browser request, Laravel redirects back with validation errors in the session. For requests expecting JSON, Laravel returns a validation error response, normally with HTTP status 422.

Data Science Updated 02 Sep 2025 2 min read

Working with Pandas: A Beginner Guide

Pandas is a widely used Python library for tabular data manipulation and analysis. This guide covers a few everyday DataFrame operations: renaming columns, adding and updating rows, deleting data, sorting, and filtering. Install Pandas python -m pip install pandas Create a DataFrame import pandas as pd df = pd.DataFrame( { "Name": [ "Braund, Mr. Owen Harris", "Allen, Mr. William Henry", "Bonnell, Miss. Elizabeth", ], "Age": [22, 35, 58], "Sex": ["male", "male", "female"], } ) Rename a Column df = df.rename(columns={"Sex": "Gender"}) Returning a new DataFrame instead of relying on inplace=True often makes transformation pipelines easier to reason about.

Data Science Updated 02 Sep 2025 2 min read

Working with CSV Files in Pandas

CSV (Comma-Separated Values) is a common format for storing and exchanging tabular data. Pandas makes it straightforward to export a DataFrame to CSV and load CSV data back into a DataFrame. Install Pandas If Pandas is not installed yet: python -m pip install pandas Using python -m pip helps ensure that pip belongs to the Python interpreter you intend to use.

Web Development Updated 07 Sep 2025 2 min read

Using PHP's Built-In Server: A Quick Guide to `php -S`

When developing PHP applications, especially small projects or prototypes, configuring a full web server such as Apache or Nginx can be unnecessary. PHP includes a lightweight development server that starts with a single command: php -S. It is convenient for local development and quick testing, but it is not designed for production traffic. What Is php -S? php -S starts PHP’s built-in development web server. It can serve PHP scripts and static files without a separate web-server configuration.

Linux Updated 02 Sep 2025 2 min read

Uploading and Downloading Files over SSH on Linux

SSH is commonly used for remote shell access, but the same secure connection can also transfer files. The scp command provides a straightforward way to copy individual files or directories between a local machine and an SSH server. 1. Prerequisites Before using scp, make sure: You can connect to the server with SSH. You know the remote username and hostname or IP address. The destination path is writable by that user. Your SSH key or other authentication method is configured. 2. Upload a File The general form is:

Python Updated 02 Sep 2025 2 min read

Understanding Tuples in Python: A Practical Guide

A tuple is an ordered Python collection whose item references cannot be reassigned after creation. Tuples are useful for fixed groups of related values, function return values, dictionary keys when their contents are hashable, and lightweight records. Create Tuples coordinates = (10, 20) colors = ("red", "green", "blue") The comma is what creates a tuple, not the parentheses alone. A one-item tuple therefore needs a trailing comma:

Python Updated 02 Sep 2025 3 min read

Sets in Python: A Practical Beginner Guide

A Python set is a mutable collection of unique, hashable elements. Sets are especially useful for membership tests, deduplication, and mathematical set operations such as union and intersection. Create a Set Use braces for a non-empty set: numbers = {1, 2, 3, 4, 5} Duplicates are removed automatically:

Python Updated 02 Sep 2025 2 min read

Python Lists: From Basics to Nested Lists

Python lists are mutable ordered collections and one of the most commonly used data structures in the language. They work well for sequences that need to grow, shrink, reorder, or contain arbitrary Python objects. Create Lists empty_list = [] numbers = [1, 2, 3, 4, 5] mixed = [1, "Hello", 3.14, True] A list can contain values of different types, although homogeneous lists are often easier to process predictably.

Python Updated 02 Sep 2025 2 min read

Python Dictionaries: A Comprehensive Guide

Python dictionaries are mutable mappings that associate unique keys with values. They are a natural fit for configuration, structured records, caches, lookup tables, and JSON-like application data. Create a Dictionary Use a literal: person = { "name": "Alice", "age": 30, "city": "New York", } Or use dict():

Linux Updated 02 Sep 2025 3 min read

Managing Users on Linux: A Practical Guide

Linux user management controls who can sign in, which files they can access, and which administrative actions they can perform. A few standard commands cover most day-to-day account management tasks. 1. Create a User The low-level useradd command creates a new account. A practical invocation is: sudo useradd -m -s /bin/bash -c "John Doe" john The options mean:

Python Updated 02 Sep 2025 2 min read

Extract Text from PDFs in Python with PyMuPDF

Extracting text from PDF files is useful for search, indexing, analysis, migration, and accessibility workflows. PyMuPDF provides a fast Python API for reading PDF pages and extracting their text. Install PyMuPDF python -m pip install pymupdf Current PyMuPDF versions support the pymupdf import name. Older examples often use import fitz, which is still seen in existing codebases.

Python Updated 02 Sep 2025 2 min read

Common Types of Functions in Python

Python functions range from ordinary def functions to lambdas, generators, methods, and asynchronous functions. Understanding the differences helps you choose the clearest abstraction for each task. 1. Built-in Functions Python includes many functions that are available without imports: print("Hello, world!") print(len([1, 2, 3])) print(sum([1, 2, 3])) Other examples include type(), range(), enumerate(), zip(), min(), and max().

Python Updated 02 Sep 2025 2 min read

Arrays in Python: Lists, `array`, and NumPy

Python has several ways to represent sequence data. The right choice depends on whether you need flexible general-purpose containers, compact typed storage, or high-performance numerical operations. 1. Lists: The Default General-Purpose Sequence Python lists are flexible and can contain objects of different types: numbers = [1, 2, 3, 4, 5] mixed = [1, "Python", 3.14, True] print(numbers[0]) numbers[1] = 10 numbers.append(6) For most application code, a list is the correct default.

Go Updated 02 Sep 2025 2 min read

Variables in Go: A Practical Guide

Variables are one of the basic building blocks of Go programs. Understanding declaration syntax, scope, zero values, constants, and type inference helps keep code predictable and easy to maintain. Declare Variables with var var name string var age int If you do not provide an initializer, Go assigns the type’s zero value. Here, name starts as "" and age starts as 0.

Go Updated 02 Sep 2025 2 min read

Search Multiple Texts Concurrently with Goroutines in Go

Go makes concurrent work straightforward with goroutines. One practical example is searching for a word across many text values at the same time. Instead of checking each text sequentially, you can launch a goroutine for each item and wait for all searches to finish. Overview The program below will: Search for a word in a single text value with searchInText. Search multiple text values concurrently with searchWordInTexts. Print whether the word was found. Complete Example package main import ( "fmt" "strings" "sync" ) // searchInText reports whether word occurs in text. func searchInText(text, word string) bool { if text == "" || word == "" { return false } // Make the search case-insensitive. text = strings.ToLower(text) word = strings.ToLower(word) return strings.Contains(text, word) } // searchWordInTexts searches multiple texts concurrently. func searchWordInTexts(texts []string, word string) bool { var wg sync.WaitGroup var mu sync.Mutex found := false for _, text := range texts { wg.Add(1) go func(t string) { defer wg.Done() if searchInText(t, word) { mu.Lock() found = true mu.Unlock() } }(text) } wg.Wait() return found } func main() { texts := []string{ "This is a long example text", "Another text for word searching", "This program uses goroutines for searching", } word := "program" if searchWordInTexts(texts, word) { fmt.Printf("Word '%s' was found in at least one text\n", word) } else { fmt.Printf("Word '%s' was not found\n", word) } } How It Works searchInText converts both the text and search term to lowercase, then uses strings.Contains for a case-insensitive match. searchWordInTexts uses sync.WaitGroup to wait for every goroutine and sync.Mutex to protect the shared found variable. main provides sample data, runs the concurrent search, and prints the result. A Practical Note For short in-memory strings, launching one goroutine per string may be slower than a simple loop because goroutines and synchronization have overhead. This pattern becomes more useful when each task is expensive or blocking, such as reading files, calling services, or processing large independent inputs.

Go Updated 02 Sep 2025 2 min read

Pointers in Go: A Practical Guide with Examples

A pointer stores the memory address of another value. In Go, pointers are useful when a function needs to modify a caller-owned value, when a type needs a meaningful nil state, or when pointer receiver semantics are appropriate. Declaring a Pointer var ptr *int The zero value of a pointer is nil. Use & to take an address and * to dereference it:

Go Updated 02 Sep 2025 3 min read

Implement HMAC Message Authentication in Go

When an application exchanges sensitive data, it is often important to verify both the integrity and authenticity of each message. If an attacker can modify a request in transit or replay an old valid request, the receiving service needs a reliable way to reject it. One common building block is HMAC (Hash-based Message Authentication Code). This article shows how to generate and verify an HMAC in Go with SHA-512, plus a nonce and timestamp to reduce replay risk.

Go Updated 02 Sep 2025 3 min read

Encrypt and Decrypt Data in Go with AES-GCM

Applications that store tokens, private configuration, or other sensitive values often need encryption at rest. Go includes everything required to implement modern symmetric encryption in its standard library. This example uses AES-GCM, an authenticated encryption mode that protects both confidentiality and integrity. That makes it a better default for new applications than older unauthenticated modes such as CFB. AES-GCM in Brief Symmetric encryption uses the same secret key for encryption and decryption. AES accepts 16-, 24-, or 32-byte keys for AES-128, AES-192, or AES-256. GCM adds authentication, so modified ciphertext is rejected during decryption. A fresh nonce must be used for every encryption operation with the same key. Complete Go Example package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" ) func generateRandomKey() ([]byte, error) { key := make([]byte, 32) // AES-256 if _, err := rand.Read(key); err != nil { return nil, err } return key, nil } func encrypt(plaintext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err := rand.Read(nonce); err != nil { return nil, err } // Prefix the ciphertext with the nonce so decrypt can recover it. return gcm.Seal(nonce, nonce, plaintext, nil), nil } func decrypt(ciphertext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonceSize := gcm.NonceSize() if len(ciphertext) < nonceSize { return nil, fmt.Errorf("ciphertext too short") } nonce := ciphertext[:nonceSize] ciphertext = ciphertext[nonceSize:] return gcm.Open(nil, nonce, ciphertext, nil) } func main() { plaintext := []byte("Secret application data") key, err := generateRandomKey() if err != nil { panic(err) } ciphertext, err := encrypt(plaintext, key) if err != nil { panic(err) } fmt.Println("Ciphertext (base64):", base64.StdEncoding.EncodeToString(ciphertext)) decrypted, err := decrypt(ciphertext, key) if err != nil { panic(err) } fmt.Println("Decrypted text:", string(decrypted)) } How It Works generateRandomKey creates a cryptographically secure 32-byte key for AES-256. encrypt creates an AES cipher, wraps it with GCM, generates a random nonce, and encrypts the plaintext. The nonce is stored at the beginning of the returned byte slice. A nonce does not need to be secret, but it must not be reused with the same key. decrypt separates the nonce from the ciphertext and calls gcm.Open. If the ciphertext was modified, authentication fails and an error is returned. Key Management Matters The encryption code is only one part of a secure design. Do not hard-code real encryption keys in source control. In production, load keys from an appropriate secret-management system, protected environment, or key-management service.

Go Updated 02 Sep 2025 2 min read

Common Function Patterns in Go with Practical Examples

Functions are first-class values in Go: they can be assigned to variables, passed as arguments, returned from other functions, and wrapped in closures. Combined with multiple return values and defer, this gives Go a small but flexible set of function patterns. 1. Basic Functions func add(a, b int) int { return a + b } result := add(3, 4) fmt.Println(result) // 7 Functions declare parameter types and, when needed, a return type after the parameter list.

Linux Updated 02 Sep 2025 2 min read

Understand and Use `htop` Effectively

htop is an interactive process monitor for Linux and other Unix-like systems. It presents CPU, memory, swap, load, and process information in a navigable terminal interface. Install and Run Debian/Ubuntu: sudo apt install htop Fedora and many RHEL-family systems: