Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
FAQ Section Markup
A simple FAQ section using semantic HTML and details/summary elements.
<section class="faq-section" aria-labelledby="faq-title">
<h2 id="faq-title">Frequently asked questions</h2>
<details>
<summary>Can I use CodShot for free?</summary>
<p>Yes. The free plan is a good way to try the platform.</p>
</details>
Toggle Class on Click
Toggle a CSS class on an element when a button is clicked.
const button = document.querySelector('#menuButton');
const menu = document.querySelector('#menu');
button.addEventListener('click', () => {
menu.classList.toggle('is-open');
});
Simple Class with Property
Create a small class with properties and instantiate it.
using System;
Product product = new()
{
Name = "Keyboard",
Price = 49.99m
};
Console.WriteLine($"{product.Name}: {product.Price:C}");
class Product
{
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
Read All Lines from File
Read a text file into lines and print each line with its index.
using System;
using System.IO;
string path = "notes.txt";
if (!File.Exists(path))
{
Console.WriteLine("File not found.");
return;
}
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
Read Console Input Safely
Read a number from the console without crashing on invalid input.
using System;
Console.Write("Enter your age: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age))
{
Console.WriteLine($"You are {age} years old.");
}
else
{
Console.WriteLine("Please enter a valid number.");
}
Create Project Folders
Create a simple frontend project folder structure.
$folders = @(
"src",
"public",
"assets",
"assets/css",
"assets/js",
"assets/img"
)
foreach ($folder in $folders) {
New-Item -ItemType Directory -Path $folder -Force | Out-Null
}
Write-Host "Project folders created."
Find HTML Tags
Find simple opening or closing HTML tags in text.
<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?>
Match Email Address
A practical beginner regex for basic email-like text matching.
^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
Reset One File to Last Commit
Discard local changes from one file and restore the committed version.
git restore path/to/file.php
Show Changed Files
Show which files changed before you commit.
git status --short
git diff --name-only
Stash Work in Progress
Temporarily save unfinished changes and restore them later.
git stash push -m "work in progress"
git stash list
git stash pop
Undo Last Commit Keep Changes
Undo the last commit but keep the changed files in your working directory.
git reset --soft HEAD~1
Create and Switch Branch
Create a new Git branch and switch to it in one command.
git switch -c feature/login-page
Select Rows with Pagination
A basic SQL pagination query using LIMIT and OFFSET.
SELECT id, title, created_at
FROM blog_posts
WHERE is_published = 1
ORDER BY created_at DESC
LIMIT 20 OFFSET 40;
Safe JSON Load
Load JSON data from a file and handle invalid JSON safely.
import json
from pathlib import Path
file_path = Path("settings.json")
try:
data = json.loads(file_path.read_text(encoding="utf-8"))
print(data)
except FileNotFoundError:
print("settings.json was not found")
except json.JSONDecodeError:
Simple CSV Reader
Read a CSV file with headers and print selected columns.
import csv
with open("students.csv", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
name = row.get("name", "")
grade = row.get("grade", "")
print(f"{name}: {grade}")
Count Word Frequency
Count how often each word appears in a short text.
text = "python is fun and python is useful"
words = text.lower().split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
for word, count in counts.items():
print(word, count)
Filter Even Numbers
Filter even numbers from a list using a simple list comprehension.
numbers = [3, 8, 12, 15, 20, 21, 30]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Read Text File Lines
Read a text file line by line and remove the newline characters.
from pathlib import Path
file_path = Path("notes.txt")
if not file_path.exists():
print("File not found")
else:
lines = file_path.read_text(encoding="utf-8").splitlines()
for line_number, line in enumerate(lines, start=1):
List Files by Extension
A Windows CMD command that lists files with a selected extension into a text file.
@echo off
dir /b *.png > png-files.txt
echo File list saved to png-files.txt
pause
Group Array Items by Key
A useful PHP helper for grouping database rows by a selected key.
<?php
function groupByKey(array $items, string $key): array
{
$groups = [];
foreach ($items as $item) {
$groupKey = (string) ($item[$key] ?? '');
if ($groupKey === '') {
continue;
}
Filter an Array of Objects
A beginner-friendly JavaScript example for filtering objects by search text.
const snippets = [
{ title: 'PHP Slug Generator', language: 'php' },
{ title: 'CSS Loading Spinner', language: 'css' },
{ title: 'JavaScript Debounce', language: 'javascript' }
];
function searchSnippets(items, query) {
Copy Text to Clipboard
A vanilla JavaScript helper to copy text to the clipboard with a fallback message.
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard');
return true;
} catch (error) {
console.error('Clipboard copy failed:', error);
return false;
}
}
Button Pulse Animation
A simple CSS pulse effect for call-to-action buttons.
.button-pulse {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.75rem 1.25rem;
border-radius: 999px;
background: #4f46e5;
color: #fff;
text-decoration: none;
animation: pulse 1.8s infinite;
}
@keyframes pulse {