Programming Reference

by Juan-Marcel Campos

Abstract Base Class

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self): pass

Define a blueprint for other classes to inherit.

Aiohttp Client

async with aiohttp.ClientSession() as s:
    async with s.get(url) as res:
        return await res.json()

Make asynchronous HTTP requests.

Async Function

async def main():
    await asyncio.sleep(1)

Define a function that can run concurrently.

Asyncio Gathering

await asyncio.gather(task1, task2)

Run multiple coroutines concurrently and wait for all.

Base64 Encode

import base64
encoded = base64.b64encode(b'data')

Convert binary data to a Base64 string.

Binary Read

with open('file.bin', 'rb') as f:
    data = f.read()

Open and read files in binary mode.

CSV Read (Dict)

import csv
with open('d.csv') as f:
    reader = csv.DictReader(f)

Read CSV rows directly into dictionaries.

Custom Exception

class MyError(Exception): pass

Create a user-defined error type.

Data Classes

from dataclasses import dataclass
@dataclass
class User: id: int; name: str

Auto-generate init, repr, and eq methods.

Datetime Now

from datetime import datetime
now = datetime.now()

Get current system date and time.

Datetime Parse

datetime.strptime('2024-01-01', '%Y-%m-%d')

Convert a string into a datetime object.

Deep Copy

import copy
new_obj = copy.deepcopy(old_obj)

Copy an object and all nested items inside it.

Dict Comprehension

{k: v for k, v in data if v > 0}

Create a new dictionary using logic in one line.

Docstring

"""Multi-line description of function."""

Standard way to document code modules/methods.

Environment Path

import sys
sys.path.append('path/to/mod')

Add a custom directory to Python's module search.

Filter List

list(filter(lambda x: x > 0, l))

Keep only items that meet a specific condition.

F-String Precision

print(f"{pi:.2f}")

Format a float to a specific number of decimals.

Get Recursion Limit

import sys
sys.getrecursionlimit()

Check the maximum depth of the call stack.

Hash Password

import hashlib
hashlib.sha256(b'pass').hexdigest()

Generate a secure SHA-256 hash of a string.

Heap Queue

import heapq
heapq.nlargest(3, list)

Efficiently find the largest items in a collection.

Inspect Object

import inspect
inspect.getsource(my_func)

Retrieve the source code of a live object.

Itertools Chain

from itertools import chain
new_l = list(chain(l1, l2))

Combine multiple iterables into one sequence.

Itertools Cycle

from itertools import cycle
c = cycle(['A', 'B', 'C'])

Infinitely repeat a sequence of items.

Lambda Function

add = lambda x, y: x + y

Create a small, anonymous one-line function.

List Dir

import os
os.listdir('.')

List all files and folders in a directory.

Logging Basic

import logging
logging.basicConfig(level=logging.INFO)

Setup standard logging for debugging applications.

LRU Cache

from functools import lru_cache
@lru_cache(maxsize=32)

Store function results to speed up repeated calls.

Math Constants

import math
print(math.pi, math.e)

Access standard mathematical constants.

Memory Map

import mmap

Read a large file directly from memory for speed.

Named Tuple

from collections import namedtuple
P = namedtuple('P', ['x', 'y'])

Create tuple-like objects with named fields.

Partial Function

from functools import partial
hex = partial(int, base=16)

Fix some arguments of a function and return new.

Pathlib Join

from pathlib import Path
p = Path('dir') / 'file.txt'

Modern, readable way to handle file paths.

Pickle Save

import pickle
pickle.dump(obj, open('o.pkl', 'wb'))

Serialize and save a Python object to disk.

Platform Info

import platform
platform.system()

Check if code is running on Windows, Linux, or Mac.

Pretty Print

from pprint import pprint
pprint(complex_dict)

Print nested data structures in a readable way.

Property Decorator

@property
def name(self): return self._name

Turn a class method into a read-only attribute.

Pydantic Model

from pydantic import BaseModel
class Schema(BaseModel): id: int

Strict data validation and settings management.

Pytest Mark

@pytest.mark.skip(reason='...')

Skip specific tests during a test run.

Pytest Setup

def test_func():
    assert func(1) == 2

Standard unit test assertion boilerplate.

Random Range

import random
random.randint(1, 10)

Generate a random integer between two values.

Regex Match

import re
re.search(r'\d+', text)

Find a pattern within a string using regex.

Regex Sub

re.sub(r'\s+', '_', text)

Replace patterns in a string using regex.

Reload Module

import importlib
importlib.reload(module)

Reload an imported module without restarting.

Reverse List

l.reverse() # or l[::-1]

Flip the order of items in a list.

Set Operations

set1.intersection(set2)

Find common elements between two sets.

Shallow Copy

new_l = old_l.copy()

Create a new collection with references to items.

Signal Handler

import signal
signal.signal(signal.SIGINT, handler)

Capture system signals like Ctrl+C.

Singleton Pattern

_instance = None
def __new__(cls): ...

Ensure a class has only one instance.

Sorted Function

sorted(l, reverse=True)

Return a new sorted list from an iterable.

SQLlite Connect

import sqlite3
db = sqlite3.connect('app.db')

Interact with a local SQL database file.

Static Method

@staticmethod
def info(): return "text"

Define a class method that doesn't need 'self'.

String Formatting

"Hello {}".format(name)

Classic way to inject variables into strings.

Temp File

import tempfile
with tempfile.TemporaryFile() as t:

Create a file that deletes itself when closed.

Threading Basic

import threading
t = threading.Thread(target=f)

Run code in a separate system thread.

Time Delta

from datetime import timedelta
future = now + timedelta(days=7)

Calculate dates in the future or past.

Time Strftime

now.strftime("%Y-%m-%d %H:%M")

Format a datetime object into a custom string.

Traceback Print

import traceback
traceback.print_exc()

Print the full error history to the console.

Type Hinting

def greet(name: str) -> str:

Annotate variable types for better IDE support.

Unpack List

first, *middle, last = [1, 2, 3, 4]

Assign list elements to variables using stars.

Yield Generator

def count():
    yield 1; yield 2

Create an iterator that produces values lazily.

ACTIVATE ENV

conda activate my_env

Switch to a specific conda environment.

ACTIVE ENV PATH

conda info --active-env-path

Display the file path of the currently active environment.

ADD CHANNEL

conda config --add channels conda-forge

Add a new channel to the top of the priority list.

ADD CHANNEL BOTTOM

conda config --append channels conda-forge

Add a new channel to the end of the priority list.

ADD LAB EXTENSION

conda install -c conda-forge jupyterlab

Install JupyterLab into the environment.

ARCHITECTURE INFO

conda info --system

View OS and architecture details (e.g., win-64, osx-arm64).

AUTO-ACTIVATE BASE

conda config --set auto_activate_base false

Disable automatic activation of the base environment.

BATCH INSTALL

conda install --file requirements.txt

Install multiple packages from a text file list.

CHECK CONDA VERSION

conda --version

Verify the currently installed version of Conda.

CHECK PYTHON PATH

which python

Verify which conda environment Python is executing from.

CHECK UNUSED

conda clean --dry-run --all

Preview what files would be deleted by a clean command.

CLEAN ALL

conda clean --all

Remove unused packages and caches to save disk space.

CLEAN INDEX CACHE

conda clean -i

Remove the index cache to fix package search issues.

CLEAN PACKAGES

conda clean -p

Remove unused cached packages.

CLEAN TARBALLS

conda clean -t

Remove cached package tarballs.

CLEAR ALL CACHES

conda clean -a

The most aggressive cleanup for disk space.

CLONE ENVIRONMENT

conda create --name new_env --clone old_env

Create an exact copy of an existing environment.

COMPARE ENVS

conda compare env1.txt

Compare an environment against an environment file.

CONFIG DESCRIBE

conda config --describe

Show descriptions of all available configuration parameters.

CONFIG GET

conda config --get channels

View specific configuration settings.

CONFIG SET VALUE

conda config --set show_channel_urls yes

Enable/disable specific conda features via config.

CONFIG SHOW

conda config --show

Display all current configuration settings.

CONFIG SHOW SOURCES

conda config --show-sources

Show where config settings are being pulled from (.condarc).

CONFIG WRITE

conda config --set key value

Modify the condarc file from the command line.

CREATE ENV FROM FILE

conda env create -f environment.yml

Build an environment from a YAML configuration file.

CREATE ENV PATH

conda create --prefix ./envs

Create an environment in a specific folder path.

CREATE ENV SPEC

conda create --name new_env --file spec.txt

Create an environment from an explicit spec list.

CREATE ENV WITH PYTHON

conda create -n my_env python=3.9

Create environment with a specific Python version.

CREATE ENVIRONMENT

conda create --name my_env

Create a new, empty conda environment.

DEACTIVATE ENV

conda deactivate

Exit the current environment and return to base.

DESCRIBE ENV

conda env export --name my_env

View the YAML structure of a specific environment.

DETAILED SEARCH

conda search package_name --info

Show detailed metadata for a specific package search.

DISABLE CHANNEL

conda config --remove channels channel_name

Remove a specific channel from your configuration.

DISABLE UPDATE

conda install package_name --no-update-deps

Install package without updating existing dependencies.

DRY RUN INSTALL

conda install package_name --dry-run

Preview changes before actually installing a package.

ENV EXPORT NO BUILDS

conda env export --no-builds

Export environment without platform-specific build tags.

EXPORT ENVIRONMENT

conda env export > environment.yml

Save environment details to a YAML file for sharing.

EXPORT EXPLICIT

conda list --explicit > spec.txt

Create an explicit platform-specific package list.

EXPORT HISTORY

conda env export --from-history > env.yml

Export only packages explicitly installed by the user.

FIND ENV BY NAME

conda info --envs | grep my_env

Locate an environment path using a keyword search.

FORCE REINSTALL

conda install --force-reinstall package_name

Overwrite an existing installation of a package.

FULL SYSTEM INFO

conda info --all

Show detailed information about the conda installation.

GET BASE PATH

conda info --base

Show the location of the base conda installation.

HELP COMMAND

conda install --help

Get documentation for any specific conda command.

INIT SHELL

conda init bash

Initialize conda for a specific shell (bash, zsh, powershell).

INSTALL FROM CHANNEL

conda install -c conda-forge package_name

Install a package from a specific channel.

INSTALL MULTIPLE

conda install numpy scipy pandas

Install several packages in a single command.

INSTALL PACKAGE

conda install package_name

Install a package into the active environment.

INSTALL SPEC VERSION

conda install package_name=1.2.3

Install a very specific version of a package.

JSON OUTPUT

conda list --json

Format conda output as JSON for script processing.

LIST CHANNEL URLS

conda config --show channel_urls

Check if channel origins are shown in list output.

LIST ENVIRONMENTS

conda env list

Show all environments created on your system.

LIST EXPLICIT

conda list --explicit

List packages as URLs for exact environment replication.

LIST IN ENV

conda list -n my_env

List packages for an environment without activating it.

LIST PACKAGES

conda list

List all packages installed in the active environment.

LIST UNTRACKED

conda list --untracked

List files in the environment not managed by conda.

LIST WITH REGEX

conda list "^py"

List packages matching a regular expression.

LOCAL INSTALL

conda install /path/to/package.tar.bz2

Install a package from a local file.

LOGS VIEW

ls $CONDA_PREFIX/conda-meta/history

Manually check the raw history log of an environment.

NOTICE UPDATES

conda config --set notify_outdated_conda true

Get alerts when a newer conda version is available.

OFFLINE INSTALL

conda install package_name --offline

Try to install package using only local cached files.

OVERRIDE CHANNELS

conda install package --override-channels -c my_channel

Ignore default channels and use only the one specified.

PACKAGE CONTENTS

conda list --export

List packages in a format compatible with requirements files.

PRUNE ENV

conda env update --file env.yml --prune

Sync environment with file and remove unlisted packages.

QUIET MODE

conda install package -q

Run installation with minimal terminal output.

REMOVE ALL CACHES

conda clean --index-cache --tarballs --packages

Targeted cleanup of specific conda cache types.

REMOVE ENV PATH

conda env remove -p ./envs

Delete an environment using its directory path.

REMOVE ENVIRONMENT

conda remove --name my_env --all

Delete an entire environment and all its packages.

REMOVE FROM ALL ENVS

conda clean --packages

Remove cached versions of packages not in use anywhere.

REMOVE PACKAGE

conda remove package_name

Uninstall a package from the active environment.

RENAME ENVIRONMENT

conda rename -n old_name new_name

Change the name of an existing environment.

RESET CONFIG

conda config --remove-key key_name

Delete a specific configuration key and value.

REVISION HISTORY

conda list --revisions
conda install --revision 2

See history of changes and roll back to a previous state.

RUN COMMAND

conda run -n my_env python script.py

Run a command inside an environment without activating it.

SEARCH FOR PACKAGE

conda search package_name

Check if a package is available in current channels.

SEARCH FOR VERSION

conda search python=3.10

Find all available sub-versions of a package.

SEARCH PLATFORM

conda search package --platform win-64

Search for packages available on other operating systems.

SEARCH VIRTUAL

conda info --virtual

List "virtual" packages detected from the system (libc, etc).

SET CHANNEL PRIORITY

conda config --set channel_priority strict

Ensure conda only pulls from top priority channels.

SET PROXY

conda config --set proxy_servers.http http://user:pass@host:port

Configure conda to work behind a corporate proxy.

SET SOLVER

conda config --set solver libmamba

Switch to the faster libmamba solver (Conda 23.1+).

SHOW ENVS ONLY

conda info -e

Short command to list all environment names.

SHOW PKGS PATHS

conda info --pkgs-dirs

Show where conda stores downloaded package files.

TEST PACKAGE

conda test package_name

Run built-in tests for an installed conda package.

UNSUBSCRIBE CHANNEL

conda config --remove channels channel_url

Stop tracking a specific remote channel URL.

UPDATE ALL

conda update --all

Update all packages in the current environment.

UPDATE COND

conda update -n base conda

Update the conda package manager itself.

UPDATE ENV SPECS

conda env update -n my_env --file environment.yml

Modify an existing environment to match a YAML file.

UPDATE ENVIRONMENT

conda env update -f environment.yml

Update an environment based on a YAML file.

UPDATE PACKAGE

conda update package_name

Update a specific package to its latest compatible version.

UPGRADE CONDA BASE

conda upgrade -n base conda

Upgrade core conda to the latest stable release.

USE DEFAULT CHANNELS

conda config --remove channels channel_name

Revert to using only the default conda channels.

VALIDATE ENV

conda list --verify

Check if all packages in the env have valid metadata.

VERIFY PACKAGES

conda verify package_name

Verify the integrity of installed packages.

VIEW CONDARC

cat ~/.condarc

View the content of the hidden conda config file.

VIEW ENV HISTORY

conda list --revisions

Look at every install/update event in this environment.

WAIT FOR LOCK

conda install --lock

Wait for a process lock if another conda instance is running.

WHO INSTALLED

conda list --explicit

Check package origins via explicit URLs.

Y/N AUTO-CONFIRM

conda install package -y

Automatically answer "Yes" to all prompts during install.

ZIP ENVIRONMENT

conda-pack -n my_env -o my_env.tar.gz

Archive an environment for relocation (requires conda-pack).

APPEND FILE

cat file1 >> file2

Append the contents of one file to the end of another.

ARCHIVE DIRECTORY

tar -czvf archive.tar.gz dir/

Create a compressed gzip archive of a folder.

BACKGROUND JOB

command &

Run a terminal command in the background.

BASE64 DECODE

echo "str" | base64 --decode

Decode a base64 string via terminal.

BASH HISTORY

history

View a list of all recently executed commands.

CALCULATOR

echo "scale=2; 10/3" | bc

Perform math calculations directly in the shell.

CALENDAR

cal

Display a simple text-based calendar.

CHANGE GROUP

chgrp groupname file

Change the group ownership of a file.

CHANGE OWNER

chown user:group file

Change the user and group ownership of a file.

CHANGE PERMISSIONS

chmod 755 file

Modify read, write, and execute permissions.

CHECK DISK USAGE

du -sh *

Show human-readable size of files in directory.

CLEAR TERMINAL

clear

Clear all text from the current terminal window.

COPY DIRECTORY

cp -r dir1 dir2

Copy a directory and all its contents recursively.

COPY FILE

cp file1 file2

Copy a file from one location to another.

COUNT LINES

wc -l file

Count the number of lines in a text file.

CPU INFO

lscpu

Display detailed information about the CPU architecture.

CREATE DIRECTORY

mkdir new_folder

Create a new directory in the current path.

CREATE EMPTY FILE

touch file.txt

Create a new file or update a timestamp.

CREATE SYMLINK

ln -s /path/to/file linkname

Create a symbolic link to a file or folder.

CRON JOBS

crontab -e

Edit the list of scheduled background tasks.

CURL GET

curl http://api.com

Send an HTTP GET request to a URL.

CURRENT DIRECTORY

pwd

Print the full path of the working directory.

CURRENT USER

whoami

Display the username of the active session.

DISK FREE SPACE

df -h

Show available disk space on all mounted filesystems.

DISPLAY DATE

date

Print the current system date and time.

DNS LOOKUP

dig domain.com

Query DNS records for a specific domain.

DOWNLOAD FILE

wget http://url.com/file

Download a file from the internet to local storage.

EDIT WITH NANO

nano file.txt

Open a simple terminal-based text editor.

EDIT WITH VIM

vim file.txt

Open the advanced Vi IMproved text editor.

ENVIRONMENT VARS

printenv

List all active environment variables.

EXTRACT TAR

tar -xzvf archive.tar.gz

Extract files from a compressed tar archive.

FILE DETAILS

stat file.txt

Show detailed status and metadata of a file.

FILE TYPE

file picture.png

Determine the actual format of a file.

FIND BY NAME

find . -name "*.log"

Search for files based on their filename.

FIND BY SIZE

find / -size +100M

Find all files larger than 100MB.

FIND EXECUTABLE

which python

Locate the path of a command executable.

FIND TEXT

grep -r "pattern" .

Search for text within files recursively.

FOLLOW LOG

tail -f access.log

View a file's content in real-time as it updates.

FREE MEMORY

free -m

Show used and available RAM in megabytes.

GENERATE SSH KEY

ssh-keygen -t rsa

Create a new pair of SSH public/private keys.

GET IP ADDRESS

curl ifconfig.me

Quickly find your public IP address.

GREP IGNORE CASE

grep -i "text" file

Search for text regardless of capitalization.

GREP LINE NUMBER

grep -n "text" file

Find text and display the corresponding line number.

HARDWARE INFO

sudo lshw -short

Display a brief summary of system hardware.

HEAD OF FILE

head -n 10 file

View the first 10 lines of a file.

HOSTNAME

hostname -I

Display the internal IP address of the host.

HTTP HEADERS

curl -I http://site.com

Fetch only the HTTP headers from a URL.

JSON PRETTY PRINT

cat data.json | jq .

Format and colorize JSON output (requires jq).

KILL BY NAME

pkill -f process_name

Stop a process using its name instead of PID.

KILL PROCESS

kill -9 1234

Forcefully stop a process using its ID.

LIST ALL FILES

ls -la

List all files, including hidden ones, with details.

LIST BLOCK DEVICES

lsblk

List all hard drives and partitions.

LIST OPEN FILES

lsof -i :8000

Find which process is using a specific port.

LIST PCI DEVICES

lspci

List all PCI buses and devices (GPUs, etc).

LIST PROCESSES

ps aux

View all currently running processes on the system.

LIST USB DEVICES

lsusb

List all USB controllers and connected devices.

LOCATE FILE

locate file.txt

Quickly find a file using an indexed database.

MAKE EXECUTABLE

chmod +x script.sh

Grant execute permissions to a script file.

MANUAL PAGE

man command

Open the official documentation for a command.

MONITOR CPU

top

Display real-time system resource usage.

MONITOR GPU

nvidia-smi

Check NVIDIA GPU usage and temperature.

MOVE FILE

mv file1 destination/

Move or rename files and directories.

NETWORK INTERFACES

ip addr

Show all network interfaces and IP addresses.

NETWORK STATS

netstat -tuln

View all active listening ports and connections.

OPEN DIRECTORY

cd folder_name

Change the current working directory.

PARENT DIRECTORY

cd ..

Move up one level in the folder hierarchy.

PING HOST

ping google.com

Check network connectivity to a remote host.

READ FILE

cat file.txt

Display the entire content of a file in terminal.

REBOOT SYSTEM

sudo reboot

Immediately restart the computer.

RELOAD BASHRC

source ~/.bashrc

Apply changes made to the bash config file.

REMOVE DIRECTORY

rm -rf folder/

Forcefully delete a directory and its contents.

REMOVE FILE

rm file.txt

Delete a file from the system permanently.

RENAME FILE

mv old.txt new.txt

Rename a file by moving it to a new name.

REPLACE TEXT

sed -i 's/old/new/g' file

Find and replace text within a file via CLI.

RSYNC COPY

rsync -avz local/ remote:/path

Sync files between folders or remote servers.

SEARCH HISTORY

history | grep "cmd"

Search your command history for a specific string.

SEND SHUTDOWN

sudo shutdown now

Turn off the computer immediately.

SESSIONS (SCREEN)

screen -S session_name

Start a persistent terminal session.

SESSIONS (TMUX)

tmux new -s session

Start a terminal multiplexer session.

SHOW GROUPS

groups username

List all groups a specific user belongs to.

SORT FILE

sort file.txt

Alphabetically sort the lines in a text file.

SSH CONNECT

ssh user@host

Log into a remote server securely via SSH.

SUDO PRIVILEGE

sudo command

Run a command with administrative/root rights.

SYSTEM LOGS

journalctl -xe

View system logs and error messages.

SYSTEM UPTIME

uptime

Show how long the system has been running.

TAIL OF FILE

tail -n 10 file

View the last 10 lines of a file.

TRACEROUTE

traceroute google.com

Trace the path packets take to a network host.

UNIQUE LINES

uniq file.txt

Remove duplicate lines from a sorted file.

UNMOUNT DISK

sudo umount /dev/sdb1

Safely unmount a disk partition or USB drive.

UPDATE PACKAGES

sudo apt update

Refresh the list of available software updates.

UPGRADE SYSTEM

sudo apt upgrade

Install all available software updates.

USER GUID

id -u username

Display the unique User ID for a person.

VIEW KERNEL

uname -a

Show the OS version and kernel release info.

VIEW PATH

echo $PATH

Display the directories included in the system PATH.

WHO IS LOGGED IN

w

Show who is logged in and what they are doing.

WORDS COUNT

wc -w file

Count the total number of words in a file.

WRITE TO FILE

echo "text" > file.txt

Overwrites a file with the specified string.

XARGS COMMAND

find . -name "*.bak" | xargs rm

Pass output of one command as arguments to another.

ZIP FILE

zip archive.zip file1 file2

Compress files into a standard ZIP archive.

ACTIVATE SHEET

Sheets("Sheet1").Activate

Brings a specific worksheet to the foreground.

ADD NEW SHEET

Sheets.Add(After:=Sheets(Sheets.Count)).Name = "NewSheet"

Create a new worksheet at the end of the workbook.

AUTO-FIT COLUMNS

Columns("A:Z").AutoFit

Adjust column widths to fit the content automatically.

AUTO-FILTER OFF

If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilterMode = False

Remove any active filters from the worksheet.

BOLD TEXT

Range("A1:A10").Font.Bold = True

Apply bold formatting to a specific range.

CALL SUBROUTINE

Call MyMacro

Execute another macro from within the current code.

CELL BACKGROUND COLOR

Range("A1").Interior.Color = RGB(255, 0, 0)

Change a cell's background color using RGB values.

CELL COMMENT

Range("A1").AddComment "This is a note"

Add a text comment/note to a specific cell.

CENTER ALIGN

Range("A1:C1").HorizontalAlignment = xlCenter

Horizontally center content within cells.

CLEAR ALL

Cells.Clear

Delete everything (content and formatting) on the sheet.

CLEAR CONTENTS

Range("A1:D10").ClearContents

Remove values but keep cell formatting intact.

CLOSE WORKBOOK

ActiveWorkbook.Close SaveChanges:=True

Close the current file and save changes.

COLUMN WIDTH

Columns("B").ColumnWidth = 25

Set a specific width for a column.

CONCATENATE STRINGS

fullText = str1 & " " & str2

Combine two or more strings together.

COPY RANGE

Range("A1:A10").Copy Destination:=Range("B1")

Copy data from one location to another.

COUNT SHEETS

sheetCount = Sheets.Count

Get the total number of worksheets in the workbook.

CREATE FOLDER

MkDir "C:\MyFolder"

Create a new directory on the hard drive.

CURRENT DATE

todayDate = Date

Store the current system date in a variable.

CUSTOM MESSAGE BOX

MsgBox "Process Complete", vbInformation, "Done"

Display a popup window with an info icon.

DELETE COLUMN

Columns("C").Delete

Permanently remove a column from the sheet.

DELETE ROW

Rows(5).Delete

Permanently remove a specific row.

DELETE SHEET

Application.DisplayAlerts = False
Sheets("Temp").Delete
Application.DisplayAlerts = True

Delete a sheet without showing a warning prompt.

DISABLE EVENTS

Application.EnableEvents = False

Stop macros from triggering other macros.

DISABLE REFRESH

Application.ScreenUpdating = False

Hide Excel updates while macro runs (increases speed).

DO UNTIL LOOP

Do Until Cells(i, 1) = ""
  i = i + 1
Loop

Repeat code until a specific condition is met.

ERROR HANDLING

On Error Resume Next

Skip lines that cause errors (use with caution).

EXIT SUB

If x = 0 Then Exit Sub

Immediately stop the macro if a condition is met.

FILE EXISTS CHECK

If Dir("C:\file.xlsx") <> "" Then

Check if a file exists before opening it.

FIND AND REPLACE

Cells.Replace What:="Old", Replacement:="New"

Replace text across the entire worksheet.

FIND LAST COLUMN

lastCol = Cells(1, Columns.Count).End(xlToLeft).Column

Get index of the last used column in Row 1.

FIND LAST ROW

lastRow = Cells(Rows.Count, 1).End(xlUp).Row

Get index of the last used row in Column A.

FIND STRING

Set found = Cells.Find(What:="SearchTerm")

Search for specific data within the sheet.

FIXED STRING LENGTH

newStr = Left(str & Space(10), 10)

Pad a string with spaces to a fixed length.

FONT COLOR

Range("A1").Font.Color = vbBlue

Change the text color of a specific cell.

FONT SIZE

Range("A1").Font.Size = 14

Adjust the font size of the text.

FOR EACH LOOP

For Each ws In Worksheets
  Debug.Print ws.Name
Next ws

Iterate through every sheet in the workbook.

FOR LOOP

For i = 1 To 10
  Cells(i, 1).Value = i
Next i

Standard loop to repeat code a specific number of times.

FREEZE PANES

ActiveWindow.FreezePanes = True

Freeze the rows/columns at the current selection.

GET ACTIVE CELL

addr = ActiveCell.Address

Store the address of the currently selected cell.

GET CELL VALUE

val = Range("A1").Value

Retrieve data from a cell and store it in a variable.

GET COMPUTER NAME

cName = Environ("COMPUTERNAME")

Retrieve the PC name using environment variables.

GET SCREEN SIZE

w = Application.Width

Get the width of the Excel application window.

GET USERNAME

uName = Environ("USERNAME")

Retrieve the Windows login name of the user.

GET WORKBOOK NAME

wbName = ThisWorkbook.Name

Return the filename of the macro-enabled workbook.

HIDE COLUMN

Columns("B").Hidden = True

Make a specific column invisible.

HIDE ROW

Rows("5:10").Hidden = True

Make specific rows invisible.

HIDE SHEET

Sheets("Sheet1").Visible = xlSheetHidden

Hide a worksheet from the tab bar.

IF THEN ELSE

If x > 10 Then
  msg = "High"
Else
  msg = "Low"
End If

Basic conditional logic structure.

INPUT BOX

userInput = InputBox("Enter Name")

Prompt the user to type in a value.

INSERT COLUMN

Columns("B").Insert

Add a new blank column to the left of Column B.

INSERT ROW

Rows(2).Insert

Add a new blank row above Row 2.

IS NUMERIC CHECK

If IsNumeric(Range("A1")) Then

Verify if a cell contains a number or text.

KILL FILE

Kill "C:\temp.txt"

Delete a file from the hard drive via VBA.

LAST SAVED DATE

dt = ThisWorkbook.BuiltinDocumentProperties("Last Save Time")

Retrieve the timestamp of the last file save.

LOWERCASE STRING

lowStr = LCase("EXCEL")

Convert text to all lowercase letters.

MERGE CELLS

Range("A1:B2").Merge

Combine multiple cells into one large cell.

MOVE SHEET

Sheets("Sheet1").Move After:=Sheets(3)

Reorder worksheets within the workbook.

NAMED RANGE

ThisWorkbook.Names.Add Name:="MyData", RefersTo:="=Sheet1!$A$1:$B$10"

Programmatically create a named range.

NEW WORKBOOK

Workbooks.Add

Create a brand new Excel file.

NUMBER FORMAT

Range("A1").NumberFormat = "$#,##0.00"

Apply currency formatting to a cell.

OPEN WORKBOOK

Workbooks.Open "C:\data.xlsx"

Open an existing Excel file from a path.

PASTE VALUES ONLY

Range("B1").PasteSpecial Paste:=xlPasteValues

Paste data without copying the formulas or formatting.

PROTECT SHEET

ActiveSheet.Protect Password:="123"

Lock the sheet to prevent editing.

QUIT EXCEL

Application.Quit

Close the entire Excel application.

REFRESH ALL

ActiveWorkbook.RefreshAll

Update all PivotTables and Data Connections.

REMOVE DUPLICATES

Range("A1:C100").RemoveDuplicates Columns:=1, Header:=xlYes

Delete duplicate rows based on a specific column.

RENAME SHEET

ActiveSheet.Name = "Report"

Change the name of the current worksheet.

RESET STATUS BAR

Application.StatusBar = False

Return control of the status bar to Excel.

ROW HEIGHT

Rows(1).RowHeight = 30

Set a specific height for a row.

SAVE AS PDF

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Doc.pdf"

Export the current sheet as a PDF file.

SAVE WORKBOOK

ActiveWorkbook.Save

Save the current progress of the file.

SELECT RANGE

Range("A1:B10").Select

Highlight a specific block of cells.

SELECT TRIAL

Select Case Range("A1").Value
  Case 1: MsgBox "One"
  Case Else: MsgBox "Other"
End Select

Advanced "If" logic for multiple scenarios.

SEND KEYS

Application.SendKeys "^p"

Simulate keyboard shortcuts (e.g., Ctrl+P for Print).

SET CELL FORMULA

Range("B1").Formula = "=SUM(A1:A10)"

Inject an Excel formula into a cell.

SET CELL VALUE

Range("A1").Value = "Hello World"

Write text or numbers into a specific cell.

SHEET EXISTS

Function SheetExists(n As String) As Boolean

Boilerplate to check if a sheet name already exists.

SORT DATA

Range("A1:B10").Sort Key1:=Range("A1"), Order1:=xlAscending

Alphabetize a range based on the first column.

STATUS BAR MESSAGE

Application.StatusBar = "Processing..."

Show custom text in the bottom Excel bar.

STRING LENGTH

n = Len("Text")

Count how many characters are in a string.

STRING REPLACE

newVal = Replace("A-B-C", "-", "")

Swap parts of a string within a variable.

THICK BORDERS

Range("A1").BorderAround Weight:=xlThick

Add a heavy border around a selection.

TIME STAMP

Range("A1").Value = Now

Insert the current date and time into a cell.

TIMER START

startTime = Timer

Capture the current time to measure macro speed.

TOGGLE GRIDLINES

ActiveWindow.DisplayGridlines = False

Hide or show the cell gridlines.

TRIM SPACES

cleanStr = Trim(" Text ")

Remove leading and trailing spaces from text.

UNHIDE ALL SHEETS

For Each ws In Worksheets: ws.Visible = True: Next ws

Loop through and make every sheet visible.

UNPROTECT SHEET

ActiveSheet.Unprotect Password:="123"

Unlock a sheet using the required password.

UPPERCASE STRING

upStr = UCase("excel")

Convert text to all capital letters.

USER INPUT DIALOG

Set r = Application.InputBox("Select Range", Type:=8)

Ask the user to physically click/select a range.

VAL CONVERSION

num = Val("123")

Convert a string number into a real numeric type.

VARIABLE DECLARE

Dim myVar As String

Properly define a variable type for memory efficiency.

VLOOKUP IN VBA

res = Application.VLookup("Key", Range("A1:B10"), 2, False)

Run an Excel VLookup within your macro code.

WAIT / SLEEP

Application.Wait (Now + TimeValue("0:00:05"))

Pause macro execution for 5 seconds.

WHILE LOOP

While x < 10: x = x + 1: Wend

Execute code as long as a condition is true.

WORKBOOK PATH

p = ThisWorkbook.Path

Get the folder path where the current file is saved.

WORKSHEET FUNCTION

res = Application.WorksheetFunction.Max(Range("A:A"))

Access standard Excel functions through VBA.

WRAP TEXT

Range("A1").WrapText = True

Enable text wrapping within a cell.

ZOOM LEVEL

ActiveWindow.Zoom = 85

Set the zoom percentage of the current window.

ABORT MERGE

git merge --abort

Stop the merge process and return to the state before the merge started.

ABORT REBASE

git rebase --abort

Stop an in-progress rebase and return the branch to its original state.

ADD ALL CHANGES

git add .

Stage all new, modified, and deleted files in the current directory.

ADD BY EXTENSION

git add *.txt

Stage all files with a specific extension.

ADD REMOTE

git remote add origin [url]

Link your local repository to a remote server.

ADD SPECIFIC FILE

git add filename.txt

Stage a single file for the next commit.

AMEND COMMIT

git commit --amend -m "new message"

Replace the last commit with a new message or staged changes.

APPLY STASH

git stash apply

Bring back changes from the stash without removing them from the stash list.

BLAME FILE

git blame filename.txt

See who changed which line of a file and when.

BRANCH LIST

git branch

List all local branches in the current repository.

BRANCH LIST REMOTE

git branch -r

List all branches currently tracked on the remote server.

CHERRY PICK

git cherry-pick [commit-hash]

Apply the changes from a specific commit to your current branch.

CHECKOUT BRANCH

git checkout [branch-name]

Switch from your current branch to another branch.

CHECKOUT COMMIT

git checkout [hash]

View the state of the repository at a specific point in time.

CHECKOUT FILE

git checkout -- filename.txt

Discard local changes in a specific file and revert to the last commit.

CLEAN DRY RUN

git clean -n

Preview which untracked files will be deleted.

CLEAN UNTRACKED

git clean -f

Forcefully delete all untracked files from the working directory.

CLONE REPO

git clone [url]

Download an existing repository from a remote source.

CLONE SPECIFIC BRANCH

git clone -b [name] [url]

Clone only a single specific branch from a repository.

COMMIT CHANGES

git commit -m "message"

Record staged changes to the repository history.

COMMIT STAGED ONLY

git commit -a -m "message"

Automatically stage and commit all modified files (skips new files).

CONFIG EMAIL

git config --global user.email "you@example.com"

Set the email address associated with your commits.

CONFIG LIST

git config --list

Show all current configuration settings for Git.

CONFIG NAME

git config --global user.name "Your Name"

Set the username associated with your commits.

CREATE BRANCH

git branch [branch-name]

Create a new branch pointer at the current commit.

CREATE AND SWITCH

git checkout -b [branch-name]

Create a new branch and switch to it immediately.

DELETE BRANCH

git branch -d [name]

Delete a branch that has already been merged.

DELETE BRANCH FORCE

git branch -D [name]

Delete a branch regardless of its merge status.

DELETE REMOTE BRANCH

git push origin --delete [name]

Remove a branch from the remote server.

DELETE REMOTE TAG

git push origin --delete [tagname]

Remove a specific tag from the remote server.

DELETE TAG

git tag -d [tagname]

Remove a specific tag from your local repository.

DESCRIBE COMMIT

git describe --tags

Find the most recent tag reachable from a commit.

DIFF BRANCHES

git diff [branch1]..[branch2]

Compare the differences between two branches.

DIFF STAGED

git diff --staged

Show changes between the staging area and the last commit.

DIFF UNSTAGED

git diff

Show changes in the working directory that are not yet staged.

DROP STASH

git stash drop

Discard the most recent set of stashed changes.

FETCH REMOTE

git fetch origin

Download history from the remote without merging it.

FETCH ALL REMOTES

git fetch --all

Retrieve updates from all configured remote repositories.

FORCED PUSH

git push origin [branch] --force

Overwrite remote history with your local history (use with caution).

GREP REPO

git grep "text"

Search for a string in the entire repository history.

IGNORE FILE

echo "node_modules/" >> .gitignore

Prevent specific files or folders from being tracked.

INIT REPO

git init

Initialize a brand new Git repository in the current folder.

LIST REMOTES

git remote -v

List all remote connections and their URLs.

LIST STASHES

git stash list

Show all sets of changes currently saved in the stash.

LIST TAGS

git tag

List all tags (versions) in the repository.

LOG GRAPH

git log --graph --oneline --all

Visualize the branch and merge history in the console.

LOG ONELINE

git log --oneline

View commit history in a condensed, single-line format.

LOG STATS

git log --stat

Show which files were changed and how many lines were added/deleted.

MERGE BRANCH

git merge [branch-name]

Join the history of another branch into your current branch.

MOVE FILE

git mv [old-path] [new-path]

Rename or move a file and stage the change automatically.

PATCH ADD

git add -p

Review and stage changes piece by piece (hunks).

POP STASH

git stash pop

Recover stashed changes and remove them from the stash list.

PULL CHANGES

git pull origin [branch]

Fetch from remote and immediately merge into the current branch.

PULL REBASE

git pull --rebase origin [branch]

Fetch changes and re-apply your local commits on top of them.

PUSH BRANCH

git push origin [branch]

Upload local commits to a specific remote branch.

PUSH TAGS

git push --tags

Upload all local tags to the remote repository.

REBASE BRANCH

git rebase [base-branch]

Move your current branch's commits to a new starting point.

REBASE INTERACTIVE

git rebase -i HEAD~5

Modify, squash, or delete commits in the last 5 entries.

REF LOG

git reflog

Show a log of all changes made to the local HEAD (useful for recovery).

REMOVE FILE

git rm filename.txt

Remove a file from the working directory and the index.

REMOVE FROM INDEX

git rm --cached filename.txt

Stop tracking a file but keep it in the local folder.

REMOVE REMOTE

git remote remove origin

Disconnect the local repository from a remote server.

RENAME BRANCH

git branch -m [new-name]

Change the name of the current branch.

RESET HARD

git reset --hard HEAD

Discard all local changes and match the last commit exactly.

RESET SOFT

git reset --soft HEAD~1

Undo the last commit but keep changes in the staging area.

RESTORE FILE

git restore [filename]

Revert a file to its state in the last commit.

REVERT COMMIT

git revert [commit-hash]

Create a new commit that undoes the changes of a previous one.

REV-PARSE HEAD

git rev-parse HEAD

Show the full SHA-1 hash of the current commit.

SET UPSTREAM

git push -u origin [branch]

Push and set the default remote tracking branch.

SHOW COMMIT

git show [commit-hash]

Display the details and file changes of a specific commit.

SHOW REMOTE

git remote show origin

View detailed information about a remote and its branches.

STASH CHANGES

git stash

Temporarily save modified, tracked files to a clean state.

STASH INCLUDE UNTRACKED

git stash -u

Stash changes including new files that aren't tracked yet.

STASH MESSAGE

git stash save "message"

Save a stash with a specific label for easy identification.

STATUS

git status

Show the state of the working directory and staging area.

STATUS SHORT

git status -s

View a simplified, compact version of the repository status.

SUBMODULE ADD

git submodule add [url]

Add a different repository as a subdirectory of this one.

SUBMODULE UPDATE

git submodule update --init

Initialize and update all submodules in the repo.

TAG COMMIT

git tag [tagname]

Create a simple pointer to a specific commit (versioning).

TAG MESSAGE

git tag -a [v1.0] -m "message"

Create an annotated tag with a descriptive message.

UNDO COMMIT

git reset --soft HEAD~1

Roll back the last commit but keep changes staged.

UNDO STAGING

git restore --staged [filename]

Unstage a file but keep the changes in the working directory.

UNSET CONFIG

git config --unset [key]

Remove a specific configuration setting.

UPDATE REMOTE URL

git remote set-url origin [new-url]

Change the URL of an existing remote connection.

VERIFY REPO

git fsck

Check the integrity of the Git database and objects.

VIEW BRANCH LOGS

git log [branch1]..[branch2]

See commits that exist in branch2 but not in branch1.

VISUALIZE HISTORY

gitk

Launch a built-in graphical interface to browse the repo.

WHATCHANGED

git whatchanged

View commit logs with the list of files impacted.

WORKTREE ADD

git worktree add ../new-dir [branch]

Check out a branch into a separate physical directory.

WORKTREE LIST

git worktree list

Show all linked working trees for the current repository.