Help
Playground
This card doesn't have much content.
This card doesn't have much content.
This card doesn't have much content.
Components
Note
Make sure you know how these changes affect you.
Warning
Make sure you know how these changes affect you.
Error
Make sure you know how these changes affect you.
Tip
Make sure you know how these changes affect you.
Primary and accent
Primary
Grey
Accents
Code blocks
{{ range slice "one" "two" "three" (dict "test" 1) }}
<p>{{ . }}</p>
{{ end }}
// rebind to page
{{ with .Page }}
<p>{{ . }}</p>
{{ end }}
Revision TLDR;
Sentence
Find the verb
- Find the verb. Put either “who” or “what” in front of the verb to figure out who is performing the action of the verb. If this reveals that the verb does not point to a main character, you need to revise.
- Do not use vague verbs or nominalizations. Verbs should name important story actions.
Tips
Review these strategies:
- Subject of an empty verb
- Follows empty verb
- Subject of empty verb followed by nominalization
- There is/there are
- Nominalizations joined by prepositions
Refer to Useful Nominalizations.
Project structure
Before writing any code, decide what you are building. JavaScript projects fall into two categories. A script is a focused, self-contained file that performs a single task. It requires no build step, minimal dependencies, and no module system. An application is a collection of modules, assets, and configuration that solves a broader problem. Applications benefit from a build step, package management, and deliberate directory organization. The choice affects every structural decision that follows.
SQL
SQL databases
Go has two packages to interact with a SQL db:
database/sql: API to interact with a various dbsdatabase/sql/driver: Defines behaviors that db drivers must implement
Registering a driver
Download the driver
go get modernc.org/sqlite@latest # most recent stable release
go get modernc.org/sqlite@v1.38.0 # specific version
go get github.com/mattn/go-sqlite3 # requires C bindings (CGO_ENABLED=1 go build)
Import the driver
Use the blank import to tell the compiler that you won’t use the driver package name sqlite in this file:
Continuous integration (CI)
CI is the practice of merging code changes into a shared repo and testing the results. It helps you catch errors early, and it completes all tasks automatically.
GitHub Actions syntax
The following table describes the syntax used in GitHub action files.
| Item | What it is | What it does | Example | Why it matters |
|---|---|---|---|---|
uses | Action reference | Runs a prebuilt GitHub Action instead of a shell command | uses: actions/checkout@v3 | Reuses tested logic instead of writing scripts |
with | Action inputs | Supplies configuration parameters to an action | with: go-version: "^1.24" | Customizes action behavior |
key | Cache identifier | Unique identifier for a cache entry | key: ubuntu-go-abc123 | Determines when cache is reused vs recreated |
restore-keys | Cache fallback | Prefixes used to find closest matching cache | restore-keys: ubuntu-go- | Speeds builds even if exact cache is missing |
${{ }} | Expression syntax | Evaluates an expression at runtime | ${{ runner.os }} | Injects dynamic values into YAML |
In other words
uses runs code, with configures it, key names cached data, restore-keys loosens matching rules, and ${{ }} injects runtime values.
Configuration objects
The Functional Options pattern creates clean and flexible configuration objects. It lets you set values on a configuration object for your application. You create a configuration object with default values, and then you can optionally set custom values with the Functional Options pattern.
Configuration struct
To begin, define your configuration struct. This example creates a configuration object for a CLI app that writes output and errors:
type CliConfig struct {
ErrStream, OutStream io.Writer
}
Option function type
Define the Option type. This type is a function that accepts a pointer to a configuration object and returns an error:
System Calls
System calls (“syscalls”) are the interface between user-level programs and the operating system kernel. System calls are made through the system call API, a collection of low-level functions provided by the OS kernel to provide user mode processes to request services from the kernel.
Find Linux syscalls with the searchable syscall table.
x/sys package
The syscall package became so bloated and unwieldly that it is no longer maintained. Now, all syscall functions are available in the x/sys and os packages.
Quality docs
Drafts
The purpose of a rough draft is to figure out which parts you understand well enough to document, and which parts you need to research.
Titles
- Tasks: Use the verbal form: Installing, configuring,…
- Concepts: Use concrete words that summarize the concept.
- Referece: Noun or noun phrase that indicates the name of the item and a common noun.
- Troubleshooting: State the problem that the topic addresses. For example, Cannot connect to the server.
Tasks
Focus on user goals
User-oriented tasks
A user-oriented task is a task that users want to perform whether or not they are using your product. For example, “Trimming strings” rather than “Using the string package to trim strings”.
Fundamentals
Go includes built-in testing tools for functional and performance testing.
- Unit testing
- Checks code in individual functions or modules.
- Integration testing
- Verifies that different modules work well together.
- Functional testing
- Verifies the correctness of the program output.
- Test suite
- Collection of test cases. If you use testing resources, set up the resources at the start of the test suite, then tear them down at the end.
Conventions
All Go tests must follow these conventions:
Sentence analysis
Identify the core of the sentence. Find the main clause (subject + verb).
Ask these questions:
- Who or what is doing something? → Subject
- What are they doing or being? → Verb
Cross out modifiers and side details until you see the skeleton.
Example:
After reviewing the data, the team concluded that the report was inaccurate. → Core: The team concluded.
Label parts of speech
Mark each main word by role:
CSV
CSV (comma-separated values) is a file format for easily reading tabular data such as numbers and text. It is defined in the RFC 4180 specification, but not all CSV files follow the spec. Some might delimit data with pipes, tabs, or semicolons.
CSV values are text
CSV is stored in a text file, so all values are assumed to be text. If you want to use the value as another type, you have to cast it as the desired type.
HTTP client
HTTPBin for testing
You can test clients with HTTPBin.
Network programming in Go uses the
httppackage—built on top of thenetpackage—to perform the fundamental aspects of network programming:- Establish a connection to a remote server.
- Retrieve data.
- Close the connection gracefully.
Go’s HTTP client can perform almost any HTTP request, and it is highly customizable. Sending a request and returning a response is an HTTP round trip.
Basic client
A simple Go client performs a a helper function. Helper functions are a wrapper around a request a
Requestobject and HTTP client. Other common helper functions include the following: -http.GetHTML
Go has a templating engine that lets you return text and HTML in response to HTTP requests. The HTML library is built on top of the text engine.
The templating engine is context-aware, which means it understands HTML, CSS, JS, and URIs and escapes data based on where it appears in the HTML output. In short, developers are trusted and any user data that is injected with variables is untrusted and is escaped. This is a security measure to prevent attacks such as cross-site scripting (XSS) from untrusted data.
Characters and actions
To be able to understand how your readers feel about your writing, you need to know what counts as a well-told story. This means finding the correct subject and verbs—characters and actions. A story is an account of real or imagined events with characters that do things—perform actions.
Finding the correct characters and actions means transforming nominalizations into verbs and finding the correct subject. This provides the following results for your sentences:
Terraform
Terraform automates cloud infrastructure by letting you write code that describes your desired end state. When you run Terraform, it reads your configuration files and provisions the corresponding infrastructure. Store configuration files in a git repository so other administrators can read the scripts and understand the infrastructure.
Terraform is lower-level than Ansible or Puppet and works across cloud providers. It is made by HashiCorp.
Two block types control network access on a resource:
Cloud
Cloud providers manage the physical hardware, so you do not need to monitor components or replace failed devices. All physical servers eventually fail, and cloud infrastructure abstracts that risk away.
Virtual private server (VPS) providers offer virtual machines at lower cost but with fewer features than full cloud platforms like AWS or GCP. Common VPS providers include DigitalOcean, Linode, and Amazon Lightsail.
Even cloud services experience outages, so automation is critical. Automated deployments let you redeploy quickly when problems occur. Back up your cloud resources regularly, keep copies of server images, and store at least one recent backup outside your primary cloud infrastructure.
Container orchestration
Container orchestration manages large numbers of containers across multiple hosts. An orchestrator creates containers as demand increases and removes them when demand drops. It also provides fault recovery, load balancing, and simplified application deployment.
Orchestrators are self-healing: if a container fails, the orchestrator starts a replacement automatically.
Kubernetes lab
Kubernetes schedules pods on worker nodes. Each worker node requires at least 2 CPUs or 1 CPU with 2 cores, and all nodes must have static IP addresses.
Containers
A container is an isolated filesystem that shares the host’s CPU and kernel. Unlike virtual machines, containers do not require dedicated CPU, RAM, or disk allocations. When you disconnect from a container without leaving a running process, the container stops.
Containers are portable and run on any infrastructure that has a container runtime. They are designed to do one thing, such as run a web server or a browser-based application. Use a container any time you need to run a web application while preserving host resources.
Virtualization
Ubuntu includes a virtualization suite built on KVM (Kernel-based VM) and QEMU (Quick Emulator). KVM is built into the Linux kernel and separates the host from guest operating systems, enabling near-native performance. QEMU emulates the hardware components found in physical servers.
KVM/QEMU lets you run virtual machines without a third-party product like VirtualBox. You cannot run VirtualBox and KVM/QEMU simultaneously — the CPU cannot support both hypervisors at the same time.
Ansible
Ansible is an infrastructure-as-code (IaC) tool for configuration management and automated deployments. Use it to install packages, manage config files, create users, and apply firewall rules across all your servers with a single command.
Unlike tools such as Chef and Puppet, Ansible does not require an agent on each client. It connects over SSH, which reduces CPU and RAM overhead and scales better across large environments. A dedicated
ansibleuser account on each managed server handles remote execution.Firewalls
A firewall controls which network ports are accessible and from where. When you start a service, open the corresponding port in the firewall. Open only the ports your server requires: for example, ports 80 and 443 for a web server.
Ubuntu includes Uncomplicated Firewall (UFW), a simplified interface to
iptables. Use UFW for most tasks. UFW is inactive by default — configure your rules before enabling it.iptablesis the lower-level packet-filtering engine that UFW wraps. It gives you full control over packet flow but requires more detailed configuration.Securing the server
Every application accessible from outside your network increases your attack surface: the set of entry points an attacker can exploit. Reduce the attack surface by limiting what is exposed:
- Uninstall unused applications.
- Configure firewalls to allow only required connections.
- Use strong, randomly generated passwords.
- Allow external access only to services that require it. Lock down all internal applications completely.
Check ports
Regularly audit which ports are listening for connections. Processes listening on
0.0.0.0accept connections from any network. Processes listening on127.0.0.1accept local connections only. Stop and remove any service you do not need:Networks
Hostname
The hostname identifies a server on a network. Choose a name that reflects the server’s purpose and develop a consistent naming scheme, such as
webserver-01,webserver-02. The hostname is stored in both/etc/hostnameand/etc/hosts. Update both files when you change it:hostnamectlonly updates/etc/hostname.The default shell prompt displays the hostname up to the first period (
.). Use these commands to view and change the hostname:hostname # view the current hostname hostnamectl set-hostname <hostname> # update /etc/hostname vim /etc/hostname # edit /etc/hostname manually vim /etc/hosts # edit /etc/hosts manuallyThe
/etc/hostsfile maps IP addresses to hostnames for local resolution:Databases
MariaDB
The Linux community has largely migrated to MariaDB. Oracle acquired MySQL in 2010, and concerns about licensing led the original MySQL development team to fork the project as MariaDB.
Follow these guidelines before you install:
- Use LVM for the partition that stores database files so you can expand the filesystem as needed.
- Do not install MariaDB and MySQL on the same server — package and port conflicts can cause unexpected behavior.
- Use the root account only for initial setup, then create a dedicated admin user.
- Beyond backups, run a secondary server for redundancy so your database remains available if the primary fails.
Installation
Install MariaDB and secure it:
Web Servers
Apache
The configurations described here are specific to Ubuntu. Apache serves content from the document root (
/var/www/htmlby default) and uses modules to extend functionality.Follow these guidelines when managing Apache:
- Reload the service after configuration changes to avoid downtime. Restart only when enabling a new module or resolving an issue.
- Configuration files are in
/etc/apache2. The main configuration file is/etc/apache2/apache2.conf.
You can run multiple websites on a single server using virtual hosts. Each virtual host has its own configuration file in
/etc/apache2/sites-available. To run a single site, replace the defaultindex.htmlin/var/www/html.Setup
Shell environment
When you log in, bash configures your environment before displaying the prompt. It reads a series of configuration files called environment files or startup files. Bash starts in one of three ways:
- Default login: a text-only login with no GUI
- Interactive shell: a subshell spawned from a GUI terminal
- Non-interactive shell: a shell started to run a script
Environment variables
Environment variables store information about the current shell session, such as the current user, home directory, and default editor. View them with any of the following commands:
Installation
Versions
Ubuntu releases a new server version every 6 months. Long Term Support (LTS) versions receive 5 years of support. Non-LTS (interim) releases are supported for 9 months.
Installation process
Each section below corresponds to a screen in the Ubuntu Server installation wizard.
GNU GRUB
Test memory runs a diagnostic program that detects errors in your RAM modules. Run it once a year.
Guided storage configuration
Custom storage layout lets you create your own partitioning scheme. Consider creating a separate partition for:
TCP
Transmission Control Protocol (TCP) provides built-in handshaking, error detection, and reconnection features.
TCP uses a reliablity method called Go-Back-N to ensure there is no data loss in a connection. If a packet is lost, the sender rolls back and retransmits from the lost packet onward. This means that even received packets are retransmitted.
TCP server
TCP ensures a reliable and ordered delivery of birectional data with messag acknowledgements and sequences of data packets. A simple TCP server has the following parts:
Logging
Logs are records of events that occur during the running of an application. When something breaks, they are an invaluable diagnostic resource.
The IETF maintains standards for logging in RFC 5424.
Types of logs
You can generate logs for development purposes or observation. These are called debugging and monitoring logs.
Debugging logs
Debugging logs help during the development phase or when you need to diagnose issues. They provide developers with detailed, contextual information about the application’s behavior at a specific moment in time. The most common examples include stack traces and variables at certain checkpoints.
Goroutines
A goroutine is an independently running concurrent function that is invoked after the keyword
go. Goroutines are executed and managed by the Go Scheduler. The Scheduler distributes the goroutines over multiple operating system threads that run on one or more processors. They run separate alongside other code with a thir own call stack that is a few KB.Goroutines use a few features that manage goroutines:
- Channels: Channels enable communication between goroutines.
- WaitGroups: A WaitGroup tracks the number of executing goroutines and blocks the calling process until all goroutines are complete.
maingoroutineThe
mainmethod is a goroutine—the main goroutine that comprises the lifetime of the application. To demonstrate, thecountToTenfunction in the following example counts from 1 to 10 and logs the current number to the console each second. The main function callscountToTenas a goroutine, then sleeps for seven seconds.countToTenruns concurrently to the main method, logging numbers to the console, while the main method sleeps. After seven seconds, the main method resumes execution and exits. This means thatcountToTendoes not have enough time to complete its loop before the program ends:Language features
Type system
Go has no type hierarchies. There are no classes, no parent-child relationships, and no inheritance. Polymorphism is achieved with interfaces.
Composition over inheritance
Go uses struct embedding instead of inheritance. Embedding places one struct type inside another, and the outer type can access the inner type’s fields and methods directly, as if they were its own.
The
hlog.Interceptorfrom thelinkdproject is a practical example. It needs to behave like anhttp.ResponseWriter— forwarding all standard methods — but interceptWriteHeaderto capture the status code:Errors
Unlike other languages, Go doesn’t have exceptions—it has errors. An
erroris a built-in type that represents an unexpected condition. It indicates that a task was not successfully completed.Go “bubbles up” errors to a receiver to be handled in one or more places in the call stack. An example is when you return an
errortype to the caller for handling. Errors are idiomatically returned as the last return value. For example:Configuration
systemd configuration
You should start and stop your servers with your operating system’s initialization daemon, such as Ubuntu’s systemd. Do not run your application as a daemon—use an initialization daemon to manage the execution of the application, including rules for service health and restarts.
Here is an example unit file for systemd:
[Unit] Description=My Test Service # Human-readable name for service After=network.target # Start only after system networking is up [Service] ExecStart=/usr/local/bin/myapp # Command to start service Restart=on-failure # systemd restarts service on failure RestartSec=5 Environment=PORT=4002 # Environment variable Environment=APP_ENV=production User=myuser # Linux user acct that runs the app (instead of root) Group=myuser # Linux group acct that runs the app WorkingDirectory=/home/myuser/app # Process cwd that might store config files or write logs to StandardOutput=journal # Set stdout to system journal StandardError=journal # Set stderr to system journal [Install] WantedBy=multi-user.target # Start service when system is in multi-user mode (normal startup)These commands manage the service with
systemctlTooling
For a deeper reference, see Alex Edwards’ An overview of Go’s tooling.
Dependencies and maintenance
Go modules enable reproducible builds through a module cache and a defined set of versioned dependencies. They address three common problems in software releases:
- Reliable versioning: Go modules use Semantic Versioning (
MAJOR.MINOR.PATCH) to communicate compatibility:MAJOR: Breaking changes that require code modification. Read the changelog.MINOR: Backward-compatible new features.PATCH: Backward-compatible bug fixes.
- Reproducible builds: The Go module proxy sits between your code and source control to download, cache, and serve modules. Your code never talks directly to GitHub.
- Dependency hygiene: Running
go mod tidyremoves unused dependencies and ensuresgo.modreflects only what your code imports.
go.mod and go.sum
These files support the Minimal Version Selection (MVS) algorithm that manages your project dependencies:
Project Setup
Project structure
When you build an executable, the convention is to nest
mainandinitfunctions within subdirectories of/cmd. For example,/cmd/host/main.go. You cannot have more than onemain.gofile in a directory.CLI tools
Separate your CLI program executable from the client/package logic so your code is flexible. For example, you can use a client package across different programs rather than have it tied to the CLI.
- Client package.
cmd/groups executable commands within subdirectories. Each subdirectory incmd/becomes its own binary.- CLI tool directory.
- CLI tool configuration, such as flag parsing.
- CLI tools entry point (
main) - Daemon, such as an API service.
hit ├── . . . # 1 ├── cmd # 2 │ ├── hit # 3 │ │ ├── config.go # 4 │ │ ├── config_test.go │ │ ├── hit.go # 5 │ │ └── hit_test.go │ └── hitd # 6 └── go.modEmmet
Find key bindings with Ctrl + k then Ctrl + s.
Links
Wrapper
.wrapper>h1{Title}+.content<div class="wrapper"> <h1>Title</h1> <div class="content"></div> </div>Auto-gen
Creates button:
button[type="button"]Creates div
[data-selected]Add text to auto-gen elements:
header>nav>ul>li*3{test}<header> <nav> <ul> <li>test</li> <li>test</li> <li>test</li> </ul> </nav> </header>Dynamic auto-gen:
header>nav>ul>li*3{List Item $}<header> <nav> <ul> <li>List Item 1</li> <li>List Item 2</li> <li>List Item 3</li> </ul> </nav> </header>Dynamic classes:
header>nav>ul>li*3.class-${List Item $}<header> <nav> <ul> <li class="class-1">List Item 1</li> <li class="class-2">List Item 2</li> <li class="class-3">List Item 3</li> </ul> </nav> </header>Zero padding
header>nav>ul>li*3.class-${List Item $$}<header> <nav> <ul> <li class="class-1">List Item 01</li> <li class="class-2">List Item 02</li> <li class="class-3">List Item 03</li> </ul> </nav> </header>Grouping
Group with parentheses:
Transitions
Transitions add motion and change to the page:
- tell the browser to ease one value into another when the value changes. Think state changes on a link–you could have a 0px border radius on a button, and then when you hover you transition into a 5px border radius.
transition-*properties add motion to the page.
Accessibility
Some users set up their OSs to prevent certain motions on the screen. Check whether these settings exist with the
prefers-reduced-motionmedia query as part of yourresetstyles:Colors
Color is one of the primary tools for creating contrast in a design. Contrast draws the user’s attention to what matters most on the page.
- For contrast to work, you must establish patterns and then break those patterns to highlight the important part of the page.
- Establish contrast with color, spacing, or size.
- Every page asks users to do something: read a story, submit information, or complete a task. Use contrast to guide them toward that action.
Defining color
A color palette typically centers on one primary color from which all other colors derive. Assign these values to custom properties so you can reuse them throughout the stylesheet.
Layers
Layer support
Check which browsers support layers at https://caniuse.com. There is also a polyfill for layers if there is no support.
Cascade layers let you group styles into named buckets and declare an explicit priority order between those buckets. This gives you reliable control over which styles win when rules conflict, without relying on specificity tricks or source order. Styles that are not in a layer always take precedence over styles that are in a layer.
Document flow
Definitions
- Normal document flow
- Default layout behavior of elements on the page - how inline and block elements behave on in the HTML document.
- Inline elements
- Flow along with the text of the page and will line wrap if they reach the end of their container.
- Ex:
<b>,<a>,<span> - inline-block elements use margin and padding for their height, but behave like inline elements.
- span is a generic inline element that you can use to group text and other inline elements.
- Ex:
- Block elements
- Appear on their own lines and fill the width of the container. Have a line break before and below them. The user-agent stylesheet sets block elements to
display: block;.- Ex:
<p>,<div>, and<header> <div>is a generic block element that you can use as a container.
- Ex:
Building a layout
When you are creating a layout, start with the larger elements, and work from the outside inward. This ensures that your larger container elements are in the right place before you start working with smaller elements.
Syntax and selectors
CSS is a domain-specific, declarative programming language. Domain-specific means that it is a specialized language that solves a specific problem. It is a declarative language because it tells the browser what to do, rather than how to do it.
Syntax
CSS often depends on the context, so it is best to understand the fundamental elements of the language:
- declaration
- A line of CSS that includes a property and a value. Invalid declarations are ignored.
- declaration block
- A group of declarations inside curly braces that is preceded by a selector
- ruleset | rule
- Selector plus declaration block is a ruleset or rule. Rule is less common.
- at-rule
- Rules that begin with the
@symbol, like@importor@media. These are statements that dictate how our styles should behave or when they should be applied.
/* ruleset */ selector { /* declaration block */ property: value; /* declaration */ property: value; } /* Example */ body { color: black; font-family: Helvetica; }Adding CSS to HTML
You can add CSS to a file with the following methods:
Child page
General
My name is Ryan Seymour and I will be 42 in a few weeks.
The current context is /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/child-page.md. The page title is Child page.
Section: hugo
The parent is /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/_index.md. You can chain `.Parent` values. For example:
- Parent of this page: /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/_index.md
- Grandparent of this page: /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/_index.md
- Great-grandparent of this page: /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/_index.md
- Great-great-grandparent of this page: There is not one, so it fails
Context
Page context
Shortcode context
$currentContext := .: {[] /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/child-page.md <nil> hugo-vals false 0 {{} {{} 0} {{} {0 0}}} {{} {{} 0} {{} {0 0}}} 196 { 0 0 0} <nil>}
Concepts
This is the page summary lorem ipsumARIA attributes
Accessible Rich Internet Applications (ARIA) is a set of HTML attributes that communicate the role, state, and properties of user interface elements to assistive technologies. Before reaching for ARIA, always check whether a native HTML element already conveys the same meaning. A
<button>is always preferable to<div role="button">, and a<nav>is always preferable to<div role="navigation">.Rules of ARIA use
The W3C defines five rules for ARIA. Apply them in order:
Best practices
This page covers three real-world git workflows: managing a software application as part of a team, tracking system administration files, and configuring a new workstation from scratch. Each workflow builds on the commands covered in the other pages in this section.
Environment setup
Run these steps once on any new machine before working with git.
1. Install git and set your identity
sudo apt install git-all git config --global user.name "Your Name" git config --global user.email you@example.com git config --global init.defaultBranch main git config --global core.autocrlf input # Linux/macOS git config --global pull.rebase true # keep history linear on pull git config --global color.ui auto2. Generate an SSH key and add it to your git host
SSH authentication is faster and more secure than HTTPS with a password. Generate a key pair and copy the public key to GitHub or GitLab:
Build tools
Why you need a bundler
Without a bundler, managing JavaScript dependencies means:
- Linking each library manually with a
<script>tag. - Shipping every file as a separate HTTP request — slow on mobile.
- No support for
importsyntax in older browsers. - No way to use modern JS syntax without manually transpiling.
A bundler solves this: it reads your source files, resolves all
importstatements, and produces a single optimized output file the browser downloads once. It also tree-shakes dead code, minifies output, and can process non-JS assets like CSS and images.MySQL
MySQL service
The MySQL service must be running to access a database. The following commands check the service, restart the service, and then configure the service to start each time the computer boots:
# check status $ sudo systemctl status mysql # start service $ sudo systemctl start mysql # stop service $ sudo systemctl stop mysql # restart service $ sudo systemctl restart mysql # start at boot $ sudo systemctl enable mysqlMySQL writes errors and startup events to
/var/log/mysql/error.log. Check this file when diagnosing connection or startup failures.The bash shell
When you log in to a Linux system, open a terminal, or connect to a remote server, you interact with bash. Bash is the program that reads your commands, evaluates them, and passes them to the operating system. Understanding how bash works at this level makes the difference between a user who types commands and a practitioner who can construct pipelines, diagnose unexpected behavior, and write reliable scripts.
This page covers the core mechanics: how bash classifies and finds commands, how data flows between programs, how the environment shapes every command you run, and how the shell connects remote machines into a single workflow.
Robot
The Go
database/sqlpackage exposes a generic API for SQL databases. It does not connect to a database by itself. You supply a driver that implements the wire protocol for the database you use.This article focuses on PostgreSQL and SQLite, which are common choices for services and tests.
Register drivers
Drivers register in package
initby calling:sql.Register("driverName", driver)You rarely call
Registeryourself. Instead, import the driver only for its side effect (a blank import):Structuring packages and services
For a thorough reference, see Organizing a Go module.
A package is a unit of responsibility with a single, clear purpose. Design packages around what they do, not what they are. A package named
utilsorhelpersis a warning sign. It has no defined purpose and will accumulate unrelated code over time.This page covers how to design, name, and divide packages. For project layout and dependency direction, see Project setup.
Iterators (TODO)
Beginning with Go 1.23, the standard library supports custom iterators. An iterator is a function that standardizes the way you push values from a sequence (e.g. a slice or channel) to a consumer. This gives consumers more control to decide how they retrieve values from the iterator.
Prefer using an iterator rather than a slice because the consumer doesn’t have to preallocate memory for a slice that might be large.
Traces
Tracing allows you to observe the behavior of your program during execution. It offers invaluable insights into performance bottlenecks and bugs. Go provides the runtime/trace package to collect event data on your goroutines, heap allocation, etc.
Tracing should focus on parts of your program where performance is critical.
Performance impact
Tracing impacts performance more than logging, so use it wisely.
runtime/trace features
This table describes the fundamental parts of the
runtime/tracepackage:Files and directories
File and directory information
os.Statgets information about a file or directory. It takes a file name string and returns aFileInfotype and anerror. Here is the information available inFileInfo:type FileInfo interface { Name() string // base name of the file Size() int64 // length in bytes for regular files; system-dependent for others Mode() FileMode // file mode bits ModTime() time.Time // modification time IsDir() bool // abbreviation for Mode().IsDir() Sys() any // underlying data source (can return nil) }Here is a simple program that returns information about
test.txt:Errors
Basic error handling
A client can read error messages and codes from the response. This snippet prints the value of each:
Statusprovides a text message for the response status. For example,200 OKor404 Not Found.StatusCodeprovides the status code as an integer.
func main() { res, _ := http.Get("http://example.com") fmt.Println(res.Status) // 1 fmt.Println(res.StatusCode) // 2 }Common errors
2xx – Success
Status Code Name Description 200 OK The request succeeded and the server returned the requested data. 201 Created The request succeeded, and a new resource was created. 202 Accepted The request has been accepted for processing, but not completed yet. 204 No Content The request succeeded, but there is no content to send back. 3xx – Redirection
Status Code Name Description 301 Moved Permanently The resource has been moved to a new permanent URL. 302 Found The resource is temporarily located at a different URL. 303 See Other The client should retrieve the resource using a GET request to another URI. 304 Not Modified The resource has not changed since the last request (used with caching). 307 Temporary Redirect The resource is temporarily located at a new URL, method not changed. 308 Permanent Redirect The resource has permanently moved to a new URL, method not changed. 4xx – Client Error
Status Code Name Description 400 Bad Request The server could not understand the request due to invalid syntax. 401 Unauthorized Authentication is required or has failed. 403 Forbidden The client is authenticated but does not have permission to access resource. 404 Not Found The requested resource could not be found. 405 Method Not Allowed The HTTP method is not supported for this resource. 408 Request Timeout The server timed out waiting for the request. 409 Conflict The request conflicts with the current state of the resource. 410 Gone The resource requested is no longer available and will not return. 413 Payload Too Large The request body is larger than the server is willing to process. 415 Unsupported Media Type The request format is not supported by the server. 429 Too Many Requests The client has sent too many requests in a given time. 5xx – Server Error
Status Code Name Description 500 Internal Server Error A generic server error. Something went wrong on the server. 501 Not Implemented The server does not support the functionality required to fulfill request. 502 Bad Gateway The server, acting as a gateway, received an invalid response. 503 Service Unavailable The server is temporarily unable to handle the request (overloaded/down). 504 Gateway Timeout The server, acting as a gateway, timed out waiting for an upstream server. Check successful request
Here is a quick
ifclause to check whether a request returned a successful 2xx success code. If the status code is below 200 or greater than 300, it returns a formatted error with the HTTP status:Arrays
An array in Go is a fixed-length sequence of elements of the same type. After you declare an array, neither the element type nor the length can change.
Storing elements contiguously in memory means each element follows the previous at a predictable offset. The processor loads cache lines sequentially, so iterating over an array is fast and cache-friendly.
Arrays are values, not references. When you pass an array to a function, Go copies the entire array regardless of its size. Assignment works the same way: assigning one array to another produces an independent copy of every element.
Slices
A slice in Go is a dynamically sized view into an array. A slice has three fields:
- Pointer
- Points to the element in the underlying array where the slice begins.
- Length
- The number of elements the slice can access.
- Capacity
- The number of elements between the start of the slice and the end of the underlying array.
You cannot create a slice with a capacity smaller than its length.
slice vs array
If you specify a value inside the
[]operator ([4]varName), you are creating an array. If you do not specify a value, you create a slice:Active vs passive
A passive verb is a form of be followed by the past participle of a verb. (The past participle is the past-tense verb preceded by some form of have. For example, He has walked home.) In passive voice:
- The subject is the goal of the action—the subject is the direct object of the verb.
- The agent, or doer, of the action is either omitted or after the verb in a by phrase.
Passive verbs can make the sentence feel flat, especially if the characters are abstractions, the actions are nominalizations, or there are no flesh-and-blood characters. However, there are some circumstances in which passive verbs are the right choice.
Loops
In Go, every loop is a
forloop.C-style loops
A C-style loop has three components separated by semicolons:
- Initializer: runs once before the loop starts
- Condition: evaluated before each iteration; the loop runs while it’s true
- Post statement: runs at the end of each iteration
for i := 0; i < 5; i++ { // do something }While-style loops
Use the
forkeyword where other languages would usewhile. Omit the initializer and post statement and provide only a condition:JSON
JavaScript Object Notation (JSON) is a lightweight data exchange format that is popular with RESTful web services and configuration. It is human-readable but also easily read by machines. It is described by RFC 7159 and ECMA-404.
Marshal vs Unmarshal
Action Meaning Direction Marshal Make (marshall) data to send Go → JSON Unmarshal Undo marshaling (read raw data) JSON → Go Decoding JSON
Decoding is another way to say “parsing”. When you decode data, you convert it from an encoded format to the format you use in your program. You are parsing the data, byte by byte, into your program’s memory.
Strings
Raw strings
Create a raw string with backticks in place of double quotes. Raw strings ignore all formatting and escape characters, allow double quotes, and let you create multi-line strings:
var str = ` This is a "multi-line" string `Bytes and runes
In Go, a string is an immutable slice of bytes in UTF-8 encoding. UTF-8 is a variable-length encoding that allows one to four bytes. A byte is an alias for
int8. Go stores a string as slice of UTF-8 encoded bytes so it can efficiently send strings across the network in its default format, or it can be converted to runes for character manipulation.Network Services
Network addressing
In the network
192.168.1.0/24, two addresses have reserved purposes and cannot be assigned to hosts:Address Purpose 192.168.1.0Network address. Identifies the network itself. 192.168.1.255Broadcast address. Sends packets to all hosts on the network. A DHCP reservation (also called a static lease) assigns the same address to a specific device each time it connects. Use reservations for devices that need a predictable address, such as servers or admin workstations.
Packages
Linux distributes software through repositories hosted as mirrors, which are copies spread across geographic locations so you can download from the nearest one. Package managers handle dependencies automatically. Maintainers package new software versions and submit them for approval before they are distributed to mirrors.
Most package updates address security vulnerabilities rather than introduce new features. Major feature changes typically wait for the next major distribution release. In Ubuntu, fixes and patches that are safe to backport to a stable release go through an approval process called Stable Release Updates (SRUs).
UDP
UDP clients faster than TCP clients because they have the following advantages:
- Do not require
ACKmessages from the server to continue sending data. - Do not establish connections
- Do not ensure packet order.
- Can easily broadcast and multicast, sending data packets to multiple recipients on a network.
- Let you implement your own reliability mechanism for your use case.
These reasons all reduce overhead and alleviates common network issues like backpressure.
Channels
Channels let you send data as messages from one goroutine to another. They are often described as sockets between goroutines in a single application, or pipes that share information asynchronously. It might be easiest to think of them as a mailbox where you send and receive data.
Channels have the following properties:
- Typed and can send structured data
- Bidirectional or unidirectional
- Short-lived or long-lived
- Can use multiple channels per app, with each channel working with a different data type
The idiomatic way to use channels is for passing data, distributing tasks, or communicating results.
Panics
A panic indicates that a severe, often unrecoverable event occurred, and the program must exit immediately. This is likely a result of programmer error or environment state in which you are asking the program to do something that it cannot do.
When Go encounters a panic, it unwinds the stack looking for a handler for the panic. When Go reaches the top of the stack, it stops the program. “Unwinding” the stack means that Go finds the line of code that caused the panic, and then the line that called that, and so on. For example:
Structs
A struct is a user-defined type, and the most common way we represent data in Go. A struct is similar to a class in object-oriented languages, but there is no inheritance, and a struct is not an object. However, an instance of a struct is sometimes referred to as an object.
Define a type
Define a custom type with the keyword
struct:type Person struct { Id int Name string email string BirthDate time.Time }Capitalized names are exported outside of the package. For example, the
Persontype and itsId,Name, andBirthDatefields are exported.HTTP Servers
Web server vs web service
A web application is a computer program that responds to an HTTP request by a client and sends back HTML to the client over HTTP. The web application is also called a web server, and the client is usually a browser. A web application generally consists of these three parts:
- Multiplexer: A router that matches the request URI to a handler function according to a URL route.
- Handlers: Functions that takes in a request, processes data from the request, and returns a response.
- Template engine: Engine that combines one or more templates with data and renders a response. This can be HTML, XML, plain text, or binary data like PDFs or images.
A web service is a computer program that responds to an HTTP request by a client that is not a browser or human, but another computer program. Web services usually respond in JSON, but they also respond in binary formats.
vim
vim is a modal text editor available on virtually every Linux system. It operates in distinct modes: normal mode for navigation and commands, and insert mode for typing text. Press
Escto return to normal mode at any time.vim.nox
vim.noxis a minimal vim build for server environments. It includes scripting language support but omits the GUI components of full vim..vimrc
.vimrcis your personal vim configuration file, stored in your home directory. Settings here apply every time you open vim. It is part of the broader dot file system for managing shell and tool configuration. A system-wide configuration file also exists at/etc/vimrc.Flag Package
- Arguments
- Necessary parameters for the program to run.
- Flags
- Optional settings that modify the program behavior.
Define flags, and then execute their logic in the main method. Think of CLI flag implementations as programs that call external libraries, even if the library is included in the same project.
FlagSet
When you create flags in Go, each flag definition is saved in a structure called *Flagset for tracking. The default Flagset for the flag package is named
CommandLine, and it has access to all Flagset functions.Patterns
Navigation menu
When creating menu items:
- Apply padding to the internal
<a>tags to provide more clickable surface area. - Make the
<a>tags block elements withdisplay: block;. This means that you can control their height with their padding and content. - Add space between flex items with the
gapproperty. Definegapas a variable. - Use
margin: autoto fill available space between flex items, like place a flex item on the other side of a flex container.
Here is the HTML:
Transforms
The
transformproperty can change or distort the shape or position of an element on the page by rotating, scaling, or skewing the element in two or three dimensions:- most commonly used with transitions or animations
- the document flow does not change when you transform an element. No other elements can use the space occupied by the transformed element
- set margin to prevent a transformed element from overlapping other elements
- you can’t transform inline elements. Either change it to an
inline-blockorblockelement, or change it to a flex or grid item.
Basics
transformtakes a function that specifies how the element should be transformed:Gradients Shadows Blends
Gradients
The
backgroundproperty is shorthand for these eight properties:background-image: Specifies an image from a file or color gradientbackground-position: Initial position of the background imagebackground-size: How large to render the background image within the elementbackground-repeat: Whether to tile the image to fill the elementbackground-origin: Whether the background positioning is relative to the element’sborder-box,padding-box, orcontent-boxbackground-clip: Should the background fill theborder-box,padding-box, orcontent-boxbackground-attachment: Does the background image scroll with the element or stay fixed in place in the viewport?background-color: Solid background color that renders behind any image
If you need to use more than one of these, don’t use the shorthand, use the individual properties. If you do use the shorthand, it will set the properties that you set and then reset the others to the initial value.
Modular CSS
Modular CSS is when you encapsulate your CSS, which means you break the CSS into component parts—modules—where each part has its own styles and other modules can’t interfere with the styles. You should define a module for each component on your page, such as navigation, dialog, progess bars, etc
Each module has a single selector (class name, etc) that you can reuse across the website. If there was a more specific selector (
#sidebar .classname), then you can’t reuse that as easily because its so specific to a portion of the page.Box Model
The box model refers to the parts of an element and the size they contribute to the element size. Each element on the page is made of four overlapping rectangles:
- content area: innermost rectangle where the contents of the element reside.
- padding area: content area plus any padding. Top and bottom padding on inline elements does not contribute to the height of the container element.
- border area: padding area plus any border.
- margin area: outermost rectangle that contains the border area plus any margins. Top and bottom margin on inline elements does not contribute to the height of the container element.
outlinepropertyThe
outlineproperty is not part of the box model, so it does not contribute to the element’s size. It is placed outside the border and overlaps the margin.Units
Definitions
Absolute units
Definite - they do not change in context:
px: pixel - difficult to measure now with high-res screens.96pxis about 1 physical inch on the screen.mm: millimetercm: centimeterQ: quarter-millimeterin: inchpt: point (12ptis equal to16px)pc: pica
Computed value
Absolute value that the browser computes for values declared using relative units. When an element has a value defined using a length (px, rem, em, etc), its computed value is inherited by its child elements.
Page one
General
My name is Ryan Seymour and I will be 42 in a few weeks.
The current context is /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/page.one.md. The page title is Page one.
Section: hugo
The parent is /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/_index.md. You can chain `.Parent` values. For example:
- Parent of this page: /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/_index.md
- Grandparent of this page: /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/_index.md
- Great-grandparent of this page: /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/_index.md
- Great-great-grandparent of this page: There is not one, so it fails
Context
Page context
Shortcode context
$currentContext := .: {[] /home/runner/work/rjseymour66.github.io/rjseymour66.github.io/content/hugo/troubleshooting/page.one.md <nil> hugo-vals false 0 {{} {{} 0} {{} {0 0}}} {{} {{} 0} {{} {0 0}}} 194 { 0 0 0} <nil>}
Writing Functions
Here are the general steps to create a function using your content and Hugo built-ins. Here are some general tips:
printforscratchfor formatting and intermediate variableswith,if, andrangeto conditionally render blocks.Sitefor global data,.Paramsfor front matter
Start with the data:
.Content: rendered HTML.RawContent: raw markdown source.Title,.Date,.Params: common page fields
Apply functions with pipeline syntax:
{{ $words := countwords .Content }} {{ $readingTime := div $words 250 }}Use Hugo built-in functions:
Configuration
Before you commit anything, git needs to know who you are. Your name and email are embedded in every commit you create. Git reads configuration from three scopes, applying the most specific scope last:
Scope File Flag System /etc/gitconfig--systemUser ~/.gitconfigor~/.config/git/config--globalRepository <project>/.git/config(none) Repository settings override user settings, and user settings override system settings.
Install git
On Debian and Ubuntu systems, install git with the following command:
Document structure
Natural language with
langThe
<html>element should include thelangattribute, which defines the natural language of the page content:<!DOCTYPE html> <html lang="en"> <head> ...The value of
langmust be a valid BCP 47 language tag composed of one or more subtags:- Script subtag: Defines the writing system. For example,
lang="sr-Latn"specifies Serbian written in the Latin script rather than Cyrillic. - Region subtag: A two-character country code in uppercase. For example,
lang="en-GB"specifies British English. Screen readers typically ignore the region subtag, but translation services and spell checkers rely on it.
You can also add
langto any element that encloses text in a different language. This helps screen readers switch to the correct pronunciation engine for that passage. Apply it sparingly, because it can interrupt the document flow. This example specifies that a paragraph is written in German:Document structure
And HTML document includes the
<html>element, which also contains the<head>element and<body>element. The<head>element contains all the meta info about your page, like info for search engines, social media, icons for the browser tab, and behavior and presentation of your content with the character set and human language.Essential features
<!DOCTYPE html>: Tells the browser to use standards mode, as opposed to quirks mode, when rendering the document. Quirks mode is a leftover from before W3C web standards, where the browser had to render Netscape Navigator or Internet Explorer pages that did not follow a common HTML standard.Environment
Links
- DOM tree and nodes
- Javascript DOM tutorial
- Eloquent Javascript “The Document Object Model”
- DOM Enlightenment
HTML <script> tags
The
<script>tag tells the browser where to find JavaScript and how to load it. You can write JavaScript inline between opening and closing<script>tags, but the more common approach is to reference an external file with thesrcattribute. Even when you specifysrc, the closing</script>tag is still required. External scripts separate content from behavior, can be shared across multiple HTML files, and are downloaded once and retrieved from cache on subsequent page loads. Thesrcattribute accepts any URL, so you can also load scripts hosted on other servers. JavaScript files use the.jsextension.Postgres
Peer authentication
When you install Postgres, the installation process creates a postgres operating system user on your machine:
$ cat /etc/passwd | grep 'postgres' postgres:x:128:133:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bashThis facilitates peer authentication. Peer authentication occurs when the current operating system username matches a valid Postgres username. The OS authenticates the user, so no password is required. Change to the postgres system user to connect:
$ sudo -u postgres psqlPostgres controls authentication rules in the
pg_hba.conf(host-based authentication) file. Each line specifies a connection type, database, user, address, and authentication method. To locate the file:Project structure
A Python project that starts as a single script will eventually need a test suite, configuration, and shared utilities. Adding those without a plan creates a tangle that slows every change. Starting with the right structure means later growth follows a clear path.
This guide walks through a reference project called
pricemon, a command-line tool that reads a product catalog from a JSON file and reports items below a target price. The complete directory tree and all source files appear at the end.SQL package
Execute queries
Go provides the following three methods for executing SQL queries with the connection pool:
DB.Query():SELECTqueries that return multiple rows.DB.QueryRow(),DB.QueryRowContext():SELECTqueries that return a single row. Use the*Context()method to implement a timeout.DB.Exec(),DB.ExecContext(): Queries likeINSERTandDELETEthat return no rows. Use the*Context()method to implement a timeout.
Create (add) data to a database with the
Exec()function. It returns aResulttype whose interface defines the following functions:Writing bash scripts
Scripts turn a manual sequence of steps into a repeatable, automated process. A script that backs up a database, sends an alert when disk space runs low, or renames a thousand files eliminates repetitive work and removes the chance of human error from routine operations. When something does go wrong, a well-written script produces clear exit codes and error messages that make the failure easy to diagnose.
This page covers everything you need to write reliable bash scripts: from the first line of the file to argument parsing, control flow, math, and signal handling.
Project setup
Production-ready Go applications share a common structure: a domain model that captures business rules, a service layer that orchestrates logic, adapters that handle I/O, and a composition root that wires everything together.
This page covers the blueprint. Apply it to any Go application regardless of domain.
Define requirements
Requirements answer three questions: what does the system do, what are the rules, and what does failure look like?
Document requirements in three areas before writing any code:
Concurrent pipeline
A concurrent pipeline consists of several stages that work concurrently and are connected by channels. It is similar to a UNIX pipeline command, where the first stage produces a value, the next stages perform an operation on a value, and the last stage delivers the result to output. For example, this command has three stages, each connected by a pipe (
|):- Stage 1:
echoprints its arguments to STDOUT. - Stage 2:
trtranslates the output from stage 1, deleting the whitespace. - Stage 3:
wccounts the characters in the output.
echo 'this is a test' | tr -d ' ' | wc -cBuilding a pipeline
In Go, a concurrent pipeline consists of any of the following components:
Metrics
Metrics are essential tools to help you understand the behavior and performance of your application. They provide insight into your system’s memory usage, CPU load, and goroutine counts. The Go runtime exposes performance data through its
runtimeandnet/pprofpackages.Prometheus
Prometheus is the most popular third-party libraries that can define and collect metrics.
Install and run
Download the Prometheus client server and run it. This command maps port 9091 on your machine to port 9090 in the container. The
-vcommand mounts your configuration file inside the container atetc/prometheus/:System events
A signal notifies a process that a specific event was triggered by one of these sources:
- Hardware: Hardware detects a fault condition. It notifies the kernel and dispatches the signal to the affected process.
- User: Generated from the terminal, such as an interrupt (Ctrl + C).
- Software: Terminated child process that is a associated with the main process.
Signals are a form of inter-process communication (IPC) and are crucial for several reasons:
Cohesion and coherence
Readers feel whether a passage is cohesive and coherent. How are the words arranged so that it flows from start to finish and tells a story?
Definitions
- Coherent
- How each sentence ends and the next begins. Begin a sentence with familiar information, and end it with new or complex information.
- Coherent
- How all sentences cumulatively begin. The subject of each sentence should contain the main characters.
Cohesion
Cohesion > Clarity
There are three principles of clarity:
Static files
Go’s standard library can serve static files the same as a standalone web server like Apache or nginx.
Serving files
All files in a directory
You can use the
FileServerfunction as the handler inListenAndServeto serve files from a directory. It returns aIf-Modified-SinceHTTP header and304 Not Modifiedresponse if the file is already cached on the user’s machine:http.Dirimplements theFileSysteminterface. This means that the path you pass the function is treated like the root directory on disk that the program serves files from.
In this example, the app serves files from thefile/directory. You do not need to specify a file because it serves all in that directory. If you were to go tolocalhost:8080, you would see a list of links to the files in the directory. When you clicked the link, you are sent tolocalhost:8080/<filename>.html.- Use
FileServeras the server’s handler.
func main() { dir := http.Dir("./files") // 1 if err := http.ListenAndServe(":8080", http.FileServer(dir)); err != nil { // 2 panic(err) } }Single file
You can use
ServeFileto serve a specific file with a handler. This example registers a handler with theDefaultMuxserver. The handler usesServeFileto serve a file namedhello.htmlat the web root path (/):Security
Basic Auth
Basic authentication uses a username and password in the request’s
Authenticationheader. The following example is a commenting app that lets you create and retrieve comments for a user. It stores the credentials in memory and aloginfunction to validate the username and password. All credentials are stored in memory:- In-memory map that holds the
usernameandpassword. loginfunction looks up theusernamein thevalidUsersmap with Go’s two-value assignment syntax. If thepasswordstored as the key forusernameis the provided password, it returnstrue. Otherwise,false.postCommentsusesr.BasicAuth()to get the contents of theAuthenticationheader. It returns theusername,password, and a Boolean that indicates whenther the header is present, correctly formatted, and decodable. Here, we store that in theauthvariable.- If
authisfalseor the login failed, then return a 403 error on failure.
type comment struct { username string text string dateString string } var comments []comment var validUsers = map[string]string{ // 1 "bill": "abc123", } func login(username, password string) bool { // 2 if validPassword, ok := validUsers[username]; ok { return validPassword == password } return false } func postComments(w http.ResponseWriter, r *http.Request) { username, password, auth := r.BasicAuth() // 3 if !auth || !login(username, password) { // 4 w.WriteHeader(http.StatusUnauthorized) return } commentText, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } comments = append(comments, comment{ username: username, text: string(commentText), dateString: time.Now().Format(time.RFC3339), }) w.WriteHeader(http.StatusOK) } func getComments(w http.ResponseWriter, r *http.Request) { commentBody := "" for i := range comments { commentBody += fmt.Sprintf("%s (%s) - @%s\n", comments[i].text, comments[i].dateString, comments[i].username) } fmt.Fprintln(w, fmt.Sprintf("Comments: \n%s", commentBody)) } func main() { http.HandleFunc("GET /comments", getComments) http.HandleFunc("POST /comments", postComments) if err := http.ListenAndServe(":8000", nil); err != nil { panic(err) } }cURL examples
To test the preceding app, use cURL. This example adds a comment:
Sharing files
A file server gives users a central location to store and share files. It runs a daemon that accepts connections and shares specified directories with authorized users.
Samba and NFS are the most common file-sharing technologies on Linux. You can run both on one machine, but each suits different environments: Samba works well in mixed Windows/Linux networks, while NFS is designed for Linux and Unix environments. Before configuring either service, choose a directory to store your file shares.
Shell
The shell is the command-line interface between you and the operating system. Each user account is assigned a default shell, stored in the last field of
/etc/passwd. System accounts are typically assigned/bin/falseor/usr/sbin/nologinto prevent interactive login:cat /etc/passwd | cut -d: -f 1,7 ... dhcpcd:/bin/false sshd:/usr/sbin/nologin testuser:/bin/bashGeneral command efficiency
Common keyboard shortcuts for navigating and editing commands at the prompt:
Shortcut Description TabTabCycle through tab completion options Ctrl + aMove cursor to beginning of line Ctrl + eMove cursor to end of line Ctrl + lClear the screen Ctrl + kDelete from cursor to end of line Ctrl + uDelete entire line (also clears passwords) Ctrl + wDelete word to the left of cursor Ctrl + rSearch command history Ctrl + xeOpen current command in editor echo $?View exit code of previous command History
The shell records every command you run in
~/.bash_history. To prevent a command from being saved, prefix it with a space. On some distributions, addHISTCONTROL=ignorebothto~/.bashrcto enable this behavior:Filesystem
The Linux filesystem directory structure follows the Filesystem Hierarchy Standard (FHS), where every directory has a specific purpose.
Common directories
The following table describes common directories. Run
man hierfor a complete reference.Directory Description / Beginning of the fs /etc System-wide application configuration /home User home directories /root Home directory for root/media Removable media, i.e. flash drives /mnt Volumes that will be mounted for a while /opt Additional software packages /bin Essential user libraries such as cp,ls, etc…/proc Virtual filesystem for OS-level components such as running processes /usr/bin Common user commands that are not needed to boot or repair the system /usr/lib Object libraries /var/log Log files Distro info
To view full distribution details, read the
os-releasefile:Websockets and SSEs
Websockets
A websocket lets you create real-time and bidirectional persistent connections to deliver data efficiently. These connections remove some of the overhead and delays in the HTTP/TCP layer (such as polling).
The websocket protocol keeps TCP connections active and can multiplex incoming messages to multiple clients as they arrive.
Server-sent events
A server-sent event (SSE, or
EventSourcein JS) is a long-lived HTTP connection that allows communication from the server to client only (unidirectional). SSEs are good for messages like notifications.Unit testing
In Go, a unit is a package, and a unit test verifies the behavior of a single package. Unit tests test simple pieces of code in isolation, such as functions or methods.
Table-driven tests
Table tests use a slice of inputs and conditions that you feed a looping function to evalute their outputs.
Here is a simple example to illustrate. This tests a function named
addOne(a int) int, which takes an integer as an argument and returns that argument plus 1. So,addOne(3)returns4:Functions
Variadic functions
A variadic function accepts a variable number of arguments of the same type. Place
...before the type in the parameter list to mark it as variadic. Go converts the arguments into a slice, so you can use any slice operation on them.The variadic parameter must be last if the function has multiple parameters.
This function accepts zero or more strings and prints each one:
func varString(str ...string) { for _, s := range str { fmt.Printf("%s ", s) } fmt.Println() }Call it with any number of arguments:
Cobra
Cobra is a CLI framework for Go. It provides POSIX-style commands with automatic help text, shell completion, and flag management. Use Cobra when your tool needs subcommands, persistent flags, or shell completion. For simple single-command tools, the standard
flagpackage is sufficient.Install
Cobra has two components:
cobralibrary: The framework your application imports as a dependency.cobra-cli: A code generator that scaffolds commands and subcommands.
Add the library to your module:
Secrets
Vendor prefixes
Here are some helpful links to determin if you need an autoprefixer:
Tips
currentColor
Considered the first ever variable in CSS, this value is equal to the
colorproperty. Thecolorproperty is inherited. This means that it applies either thecolorvalue for the current element or–ifcoloris not defined–the initial color for that property.(avoid) media queries
Now, you can use container queries.
Animations
Keyframe animations let you make an element take a roundabout path from location to location, or you might want the element to return to its previous location.
A keyframe is a way to define multiple properties that change over a period of time. For example, you can change the background color of an element multiple times over a specified period, or you could rotate an element over a period with multiple
transformdeclarations.Masks Shapes Clipping
Filters
filterproperty to apply blur, color shift, or desaturation to an element:- Use multiple filters at the same time by separating them with a space. This applies filter effects from left to right
- Use filters subtly, like whenn a user hovers over an image
Types of filters
Function example Description Parameter(s) blur(10px) Applies a Gaussian blur The higher the length, the stronger the blur effect. brightness(150%) Increases or decreases the brightness A value lower than 100% reduces the brightness; a value greater than 100% increases it. contrast(150%) Increases or decreases the contrast A value lower than 100% reduces contrast (fades the image); a value greater than 100% increases it. drop-shadow(10px 10px 15px black) Adds a drop shadow, similar to the drop-shadow property The first two parameters are lengths indicating the x- and y-offsets, respectively. The third is a blur amount (optional). The fourth is a color (optional). Unlike the drop-shadow property, the spread radius value and inset keyword are not supported. grayscale(50%) Desaturates the color A value between 0% and 100%, which produces a fully grayscale image. hue-rotate(30deg) Shifts the hue value of every pixel Any angle indicating how far around the color wheel to shift colors. invert(100%) Inverts the colors A value of 100% completely inverts the colors. A value between 0% and 100% applies the effect at the indicated strength. opacity(50%) Makes the element transparent, similar to the opacity property A value of 0% makes the element completely transparent; 100% is fully opaque. saturate(150%) Increases or decreases the color saturation Values higher than 100% increase the image color saturation; values lower than 100% desaturate the image. saturate(25%) is equivalent to grayscale(75%). sepia(100%) Replaces color with a sepia-tone effect A value between 0% and 100%, controlling the strength of the effect. blur()
Takes a single parameter that is a length that indicates the strength of the blur–how many pixels will blend together:
Flexbox
Flexbox (Flexible Box Layout) defines one-dimensional layouts: either a single row or a single column. Each Flexbox layout consists of the following components:
Terminology
- Flex container
- The container element with properties that control the direction and behavior of the flex items.
- Flex items
- Elements within the flex container with properties that control the relative size of each element.
Flexbox works from the content out, so you do not need to set element sizes explicitly. Common use cases include the following:
Creating a Site
Generate a website project with this command. It will create a directory using the provided
<site-name>, so you might have to move all generated contents into the current working directory if you already have a git repo cloned:hugo new site site-name # create website mv site-name/* . # move generated files to pwd rmdir site-name # delete empty dirDirectory structure
https://gohugo.io/getting-started/directory-structure/
site-name ├── archetypes # md templates for your content types │ └── default.md ├── assets # global resources like CSS, Sass, JS, etc ├── content # md files that comprise the site content ├── data # JSON, YAML, XML, etc files that you can extract to populate your site ├── hugo.toml # site config file ├── i18n # translation tables for multilingual sites ├── layouts # template files that define look and feel of site ├── static # static assets (CSS, images, JS, ect) copied to the public/ dir when you build your site └── themes # themes that you download or createBuilding the home page
Each type of page that you have in your site will have its own layout page. The home page has its own layout because you likely want your home page to be different than the rest of the site.
Basics
These commands cover the day-to-day cycle of working with git: starting or cloning a repository, tracking files, reviewing what has changed, and saving snapshots. Every git workflow runs through this loop repeatedly.
Initialize or clone a repository
git init
git initcreates a new.gitdirectory in the current folder and begins tracking it as a git repository:git initgit clone
git clonecopies an existing repository to your machine. It creates a new directory, initializes.gitinside it, pulls down all project data, and checks out a working copy of the latest version. All files start as tracked and unmodified:Basics
Comments
// Single comment /* Multi-line comment. Make sure this is the correct commenting style. */Essentials
let name = "My name"; name = "Rename";letandconsthave block scope,varhas global or function scope.Prefer
constby default — useletonly when you need to reassign a value. This makes your intent clear and prevents accidental reassignment:const MAX_RETRIES = 3; // value never changes let currentAttempt = 0; // will increment in a loop // const with objects/arrays: the reference is fixed, but contents are mutable const user = { name: 'Alice' }; user.name = 'Bob'; // allowed user = {}; // TypeError: Assignment to constant variableStrings
let doubleQuote = "Don't you dare do that" let name = "Jimmy" // template strings let sentence = `My name is ${name}`;// Combine strings s1.concat(s2)// split string into array by a sep // s.split("sep") let s = "This is going to be an array" let arr = s.split(" ") console.log(arr);Output:
Concepts
A relational database organizes data into tables. Each table represents a single entity — for example, customers or invoices. Tables are made of rows and columns, sometimes called records and fields.
Understanding these terms makes it easier to read SQL documentation and reason about schema design decisions.
Terminology
The following terms appear throughout SQL documentation and query output:
- Cell
- The intersection of a row and a column.
- Column
- Represents an attribute of an entity, such as the amount of an invoice. Each column has a data type that constrains what values it can hold.
- Row
- Contains a set of values for a single instance of the entity.
- Constraint
- A rule that restricts the type of data a column can store. For example,
NOT NULLprevents empty values andUNIQUEprevents duplicate values. - Data type
- Determines what kind of information a column stores. Choosing the smallest appropriate data type reduces storage overhead and improves query performance. Common data types include
CHAR,VARCHAR,INT,DECIMAL,FLOAT, andDATE. - Primary key
- Uniquely identifies each row in a table. Usually a single column, but can span multiple columns.
- Composite primary key
- A primary key that uses two or more columns together.
- Non-primary key
- Also called a unique key. Uniquely identifies each row but is not designated as the primary key.
- Foreign key
- One or more columns in a table that reference the primary key of another table. Foreign keys express a one-to-many relationship between tables.
- Referential integrity
- The guarantee that changes to data do not create invalid relationships between tables. Enforced through foreign key constraints.
- Index
- Provides efficient access to rows based on the values in specific columns. MySQL creates indexes automatically for primary keys, foreign keys, and unique keys.
- Null
- A value that is unknown, unavailable, or not applicable. Null is not the same as zero or an empty string.
- Default value
- A value assigned to a column automatically when no other value is provided.
- Auto-increment column
- A column whose value the database generates automatically when a new row is inserted.
- Entity-relationship (ER) diagram
- A visual representation of how the tables in a database are defined and related.
- Result set
- The data returned by a query. Also called a result table.
- Scalar function
- A function that operates on a single value and returns a single value.
- Aggregate function
- A function that operates on a series of values and returns a single summary value. Also called a column function because it typically operates on column values.
- Summary query
- A query that contains one or more aggregate functions.
- Database object
- Any defined object in a database used to store or reference data. Everything created with a
CREATEstatement is a database object, including tables, views, sequences, indexes, and synonyms.
DML and DDL statements
SQL statements fall into two categories. DML (Data Manipulation Language) statements work with data. DDL (Data Definition Language) statements create and modify the structure of a database.
Fundamentals
This page covers Python’s core building blocks: operators, control flow, and loops. Understanding where Python differs from other languages — chained comparisons, loop
elseclauses,match/case— pays dividends throughout the rest of the language.Operators
Comparison and assignment operators
The following operators form the foundation of Python expressions:
= # assignment — binds a name to a value == # equality — compares values, not memory location # Identity — compares memory location, not value is # True if both names refer to the same object is not # True if both names refer to different objects # Membership in # True if x is in y not in # True if x is not in y # Logical and or not # Boolean literals True FalseTo test equality between values, apply
==. To test whether two names refer to the same object in memory, applyis.Nonechecks should always applyisrather than==:Metadata
Use the
<meta>tag for metadata that cannot be represented by the<title>,<link>,<script>,<style>, and<base>tags. There are many kinds of<meta>tags, but the most common ones are useful for SEO, socail media posting, and UX.Required
<meta>tagsOriginally, you defined the charset and viewport metadata with this tag:
<meta http-equiv="Content-Type" content="text/html; charset=<characterset>" />The
http-equivis short for “HTTP equivalent”, which means that the meta tag is replicating what is sent in the HTTPContent-Typeheader. Developers mistyped this so much, that the specification was changed to this:Page structure
Navigation landmarks
Navigation is a major landmark, and a page can have several: a main navigation, a breadcrumb trail, a local table of contents, and a footer navigation. Without labels, screen reader users cannot tell them apart. Distinguish navigations with
aria-labelso users can confidently identify and jump to the one they need.Add the
aria-current="page"attribute to identify which nav link corresponds to the current page.Main nav
The main navigation is nested in the
<header>element and identifies the current page witharia-current="page":PostgreSQL
Links:
Import the driver
- Go to https://github.com/lib/pq
- Go to the root of the project, and use
go getto download the driver:$ go get github.com/lib/pq@v1 - In the Go file that runs the SQL code, import the driver. Because you are not using the driver directly, import it with the
blank identifier:package main import "_ github.com/lib/pq"
Get a database connection pool
The Postgres data source name (DSN) uses the following format:
Text processing
Most system data on Linux is stored as plain text. Log files record application events, configuration files control behavior, CSV exports carry database contents, and
/procfiles expose kernel state. The command line provides a set of composable tools for filtering, transforming, and extracting data from these files without requiring a database query language or spreadsheet software.The real power is in combining these tools in pipelines. Each command in a pipeline does one thing and does it well. A two-minute investigation of a production issue often comes down to three or four of these commands chained together. This page covers the tools you will reach for most frequently.
Toggle buttons
Buttons are inherently accessible to keyboards and screen readers. If the button is not submitting a form, use
type=button. This means that you don’t have to adde.preventDefault()to keep the browser from submitting a form.Pressed button styles
If you are creating a button that looks like an actual button–is depressed after a click–add
aria-pressed. This makes some screen readers announce the button as a toggle button.Use
position: relative;so you can move the element without removing it from the doc flow. This is better for performance because it does not trigger GPU acceleration or trigger a new stacking context. In addition, its great for subtle static layout tweaks that need to include shadows or outlines. Shadows, outlines, and background layers are shifted with the element.Architecture
linkdis a URL shortener.POST /shortenaccepts a URL and returns a short key.GET /r/{key}redirects to the original URL. The program stores links in SQLite or in memory. It’s a concrete example of the layered architecture from Project setup and Structuring packages and services.Project layout
link/ ├── cmd/linkd/ │ └── linkd.go # composition root: config, wiring, server startup ├── link.go # domain: Link and Key types, Shorten function ├── error.go # domain: sentinel errors ├── shortener.go # in-memory Shortener (development and test use) ├── rest/ │ ├── health.go # health check handler │ └── shortener.go # HTTP handlers, Shortener and Resolver interfaces ├── sqlite/ │ ├── schema.sql # embedded table schema │ ├── sqlite.go # Dial and DialTestDB helpers │ └── shortener.go # SQLite-backed Shortener implementation └── kit/ ├── hio/ │ ├── hio.go # Handler type and ServeHTTP │ ├── request.go # DecodeJSON, MaxBytesReader │ └── response.go # Responder: JSON, Text, Redirect, Error ├── hlog/ │ └── hlog.go # HTTP request logging middleware └── traceid/ ├── traceid.go # trace ID generation and context storage ├── http.go # middleware that injects a trace ID into context └── slog.go # slog handler that adds trace_id to every log recordDependency direction:
Task Scheduling
Schedule tasks with concurrency and time package. Scheduling has this benefits:
- Run processes at off-peak hours to use resources efficiently.
- Create backups, updates, and maintenance.
- In distributed systems, manage when and how tasks are executed in parallel.
- Make sure tasks are performed at regular intervals.
Create a scheduler
Define a
Jobtype and aSchedulertype:Jobtakes no arguments and returns no value.Schedulerhas a channel namedjobQueuethat stores and manages scheduled jobs.- The factory function creates a new scheduler. It creates a buffered channel of a given size so you can add jobs to
jobQueuewithout blocking.
type Job func() // 1 type Scheduler struct { // 2 jobQueue chan Job } func NewScheduler(size int) *Scheduler { // 3 return &Scheduler{ jobQueue: make(chan Job, size), } }Next, define the behavior of the scheduler. We want to run every job in its own goroutine:
Maps
A map is an unordered collection of key/value pairs. Because maps are unordered, there’s no way to predict the order in which the key/value pairs will be returned.
Internally, a map is a pointer to the
runtime.hmapstructure. This hash table contains a collection of buckets. When you’re storing, removing, or looking up a key/value pair, everything starts with selecting a bucket. This is performed by passing the key to the map’s hash function. The hash function generates an index that evenly distributes key/value pairs across all available buckets.Emphasis
Simplicity to complexity
The sentence should open with a short segment that readers can easily grasp and that frames the more complex information that follows.
Placing your subject/character and verb/action at the beginning of the sentence makes it easier for the reader to understand complex information at the end of the sentence. If the reader gets through the character and action in a few words, they have enough momentum to carry them through the remainder of the sentence.
Users and groups
Linux organizes users into three types based on the level of access they have:
root: Has unrestricted access to the entire system- Sudo user: A regular user granted permission to run commands with root privileges
- Regular user: Has access only to their own files and explicitly granted resources
sudo
sudostands for “superuser do.” It lets you run individual commands with elevated privileges without logging in asroot.Best practices for using
sudo:Storage
Add storage volumes
Before adding storage, determine how much space you need, which filesystem to format it with, and where to mount it. Linux assigns new devices a name from the
/dev/sd[a..z]or/dev/vd[a..z]scheme. For example, a disk named/dev/sdbhas its first partition at/dev/sdb1.Find devices
Before partitioning, identify the device name the system assigned to your new disk. The following commands each accomplish this in a different way:
Interfaces
Interfaces are types that declare behavior with a set of methods. Types do not have to explicitly declare that they implement an interface. You can pass types to a function based only on its methods, and Go checks at compile time whether the type matches the interface definition.
To implement an interface in Go, a user-defined type must a method set with signatures that exactly match the methods declared in the interface. If a type implements an interface, then a value of that type can be assigned to values of the interface type.
Idioms
Naked returns
A naked return omits the return values when the function uses named return values. Name the return values in the signature, assign them in the body, then return with no arguments:
func nakedReturn() (a, b string) { a = "First string" // named return vals b = "second string" return // naked return }Comma-ok
The comma-ok idiom uses a second boolean return value to distinguish a missing key or failed assertion from a zero value.
Theme Switcher
You can add dark and light themes with custom properties. First, create the theme colors with class styles on the
:rootelement::root.dark { --border-btn: 1px solid rgb(220, 220, 220); --color-base-bg: rgb(18, 18, 18); --color-base-text: rgb(240, 240, 240); --color-btn-bg: rgb(36, 36, 36); } :root.light { --border-btn: 1px solid rgb(36, 36, 36); --color-base-bg: rgb(240, 240, 240); --color-base-text: rgb(18, 18, 18); --color-btn-bg: rgb(220, 220, 220); } /* apply custom props to elements below */Then, use JS to grab the root element (
documentElement), and toggle the theme:let setTheme = () => { const root = document.documentElement; const newTheme = root.className === "dark" ? "light" : "dark"; root.className = newTheme; document.querySelector(".theme-name").textContent = newTheme; }; document.querySelector(".theme-toggle").addEventListener("click", setTheme);Responsive
Websites need to work on all devices, where you serve the same pages to all devices but they render differently based on viewport.
Use breakpoints to achieve responsive design. A breakpoint is a browser width or height where the styles change to provide the best possible layout for that size.
Three key principles
- Mobile-first approach: Develop the mobile version before the desktop version. All versions must share the same HTML, so make sure you design mobile, tablet, and desktop viewports before you begin so you can properly structure the HTML.
- @media rule (media queries): Write styles that apply to viewports of specified sizes.
- Fluid layouts: Containers scale differently based on viewport width
Viewport meta tag
Tells mobile devices that your website is responsive. Otherwise, mobile devices will try to emulate a desktop browser:
Grid
Officially titled the Grid Layout Module.
Grid lets you create 2-D layouts of columns and rows. It works from the layout in. If you make an element a grid, it creates a grid row for each child element until you explicitly place the elements in a different grid structure.
Like flexbox, grid has two levels that create a hierarchy:
- grid container
- grid items
Grid containers behave like block elements, it fills 100% of the available width.
Themes
Create a new theme with this command. It will generate theme directories in
/themes/<theme-name>:hugo new theme theme-nameTo use a theme in your site, add it to the config file:
theme = "theme-name"A basic theme needs only these files:
layouts/ ├── default/ │ └── list.html │ └── single.html # default archetype ├── index.html # home pagePartials
layouts/baseof.htmlis the skeleton for all layout files–the “base of” all files. It contains partials that define the head, header, main, etc. A partial is a file that contains commonly reused parts of the layout, such as the head, header, etc.Commit history
git logis your primary tool for understanding what happened in a repository and when. You might run it to find which commit introduced a bug, to see what a colleague pushed while you were away, or to verify your own work before opening a pull request. It lists commits in reverse chronological order by default.Quick reference
The table below summarizes the most common
git logflags:Linking content
Links should have a concise and descriptive text label, and users should know what to expect when they click or select one. Essential criteria include the following:
- Must convey its role: Apply the
<a>tag with anhrefattribute. It has an implicitlinkrole, and a screen reader announces the role with the text. Links should not have click events or placeholder text. That is what a button is for. - Have an accessible name: Link text should be meaningful, short, understandable, and unique. Do not write ’learn more’ or ‘click here’. A screen reader user who browses links in a list out of context needs “Download the Q3 report (PDF)”, not “Click here”.
- Unique label, concise and straightforward: Do not have multiple links with the same text on a single page.
- Accessible to assistive tech: The link should communicate its current state (visited, focus-visible, hover, active).
- Focusable with a keyboard: By default, the
<a>element is interactive and tabbable.
Styles
Links should look like links. Select a link color and underline them. Best practices for link styles:
Navigating the filesystem
Knowing how to navigate the Linux filesystem quickly and find what you are looking for is a skill that pays off in nearly every situation: investigating a configuration file that changed unexpectedly, finding large files filling up a disk, searching a codebase for a string, or collecting logs before an incident review. This page covers the primary tools for filesystem navigation and search, along with practical patterns for gathering system information.
Objects
Links
Objects and object constructors
Object literals
const myObject = { property: 'Value!', otherProperty: 77, "obnoxious property": function() { // do stuff! } }; // dot notation myObject.property; // 'Value!' // bracket notation myObject["obnoxious property"]; // [Function]Object constructors
Object constructors are functions that use
thisto bind properties (state) and functions (behavior) to objects (places in memory):function Player(name, marker) { this.name = name; this.marker = marker; this.sayName = function() { console.log(name) }; }Create a new object with the
newkeyword:Querying
The
SELECTstatement retrieves data from one or more tables. Most queries you write day-to-day combineSELECTwithWHEREfor filtering andORDER BYfor sorting. Understanding the clauses available lets you express most data retrieval tasks without resorting to application-level filtering.SELECT syntax
The full syntax for a
SELECTstatement is as follows:SELECT select_list [FROM table_source] [WHERE search_condition] [ORDER BY order_by_list] [LIMIT row_limit]Column specifications
The
SELECTlist names the columns to retrieve. You can specify:Refactoring UI
Starting from scratch
Design one feature at a time, not the whole app at once. Build it, then move to the next. Starting to build as soon as possible prevents you from relying entirely on your imagination. Expect each feature to be difficult. Design the smallest, most useful version before expanding scope.
For early sketches, reach for a sharpie and paper. The resistance of the medium prevents you from focusing on low-level details like typefaces and padding values. Design in grayscale first so you focus on space, contrast, and size before committing to a color palette.
Semantic HTML
Semantic means “relating to meaning”. Semantic HTML means using HTML elements to structure your content based on each element’s meaning, not its appearance. It is the difference between using a
<div>to wrap the website’s navigation, or using the<nav>element.Always ask yourself, “Which element best represents the function of this section of markup?”. Don’t worry about how the element looks, that is a job for CSS.
This is helpful for the developer and for automated tools (e.g. screen readers) to understand the markup with the Accessibility Object Model (AOM).
SQLite
SQLite databases are a single file with the .db extension. Saving the entire database in a file makes it more portable.
To start SQLite, enter
sqlite3followed by the name of the file you want to use as a database:$ sqlite3 dbname.db SQLite version 3.22.0 2018-01-22 18:45:57 Enter ".help" for usage hints. sqlite>Prepend commands with a period (
.):sqlite> .tables sqlite> .help sqlite> .quit -- Create a table sqlite> CREATE TABLE "interval" ( ...> "id" INTEGER, ...> "start_time" DATETIME NOT NULL, ...> "planned_duration" INTEGER DEFAULT 0, ...> "actual_duration" INTEGER DEFAULT 0, ...> "category" TEXT NOT NULL, ...> "state" INTEGER DEFAULT 1, ...> PRIMARY KEY("id") ...> ); -- Insert data into a table sqlite> INSERT INTO interval VALUES(NULL, date('now'),25,25,"Pomodoro",3); sqlite> INSERT INTO interval VALUES(NULL, date('now'),25,25,"ShortBreak",3); sqlite> INSERT INTO interval VALUES(NULL, date('now'),25,25,"LongBreak",3); -- Select date from a table sqlite> SELECT * FROM interval; sqlite> SELECT * FROM interval WHERE category='Pomodoro'; -- Delete a table, and then verify sqlite> DELETE FROM interval; sqlite> SELECT COUNT(*) FROM interval; 0Connecting with Go
SQLite requires C bindings, so makes sure CG0 is enabled:
Strings
Strings in Python are immutable sequences of Unicode characters. Every string method returns a new string — modifying a string always creates a new object rather than changing the original.
Creating strings
Apply triple quotes for multi-line content such as SQL queries, email templates, or configuration blocks:
# Single or double quotes for short strings: greeting = "Hello, world" name = 'Alice' # Three single or double quotes for multi-line strings: query = ''' SELECT id, email, created_at FROM users WHERE active = true ORDER BY created_at DESC ''' # Convert another data type to a string with str(): version = str(3.11) # "3.11" port = str(5432) # "5432" # Multiply strings to repeat them: name = 'Jack' name * 4 # 'JackJackJackJack' # Retrieve a single character by position (zero-based): name[1] # 'a'String methods
Python provides built-in methods for searching, testing, and transforming strings. The following examples operate on a common
songvariable:Todo list
This todo list example is really about making inclusive components that you create or delete.
Empty state
Before you add items to your todo list, you will have an empty space. You need to inform users and screen readers there is a part of the page that can contain content, even if it does not currently contain content.
To accomplish this, place an element with an
empty-stateclass after the<ul>element:Testing
When you test a CLI tool, you test that the flags accept the correct values.
Production environment
The following example tests a CLI tool that uses an
envstruct to inject dependencies to arunfunction, which is then passed tomain. Here is the dependency struct:type env struct { args []string stdout io.Writer stderr io.Writer dryRun bool }Test environment
The tests need to pass test
args, and then capture the output of bothstdoutandstderr. To capture the output, you can create atestenvstruct that usesstrings.Builderforstdoutandstderr.File Monitoring
The easiest way to watch for changes to files is with the
fsnotifypackage, a cross-platform package that wathces for file system events. To install, run this command in your terminal:go get github.com/fsnotify/fsnotifyfsnotify
This program watches a directory for changes to the file system. It uses a signal channel to listen for interrupts from the terminal:
- Define the path that you want to watch.
- Create a new
Watcher. A Watcher watches for file system events on a channel of typeEvent. - Check for errors.
- Close the Events channel right before the method returns.
Addregisters the directory with the Watcher. The Watcher now monitors the path for changes.- Check for errors.
- In a goroutine, run an inifinite loop with a
selectloop that watches for events on the Wather. - When
watcher.Eventssends a filesystem event, it prints it to the screen. - When the Watcher gets an error, it prints it to the screen.
- Set up a signals channel.
- Watch for interrupt signals from the terminal.
- Block until there is a value sent from
signalCh.
func main() { watchPath := "./testdir" // 1 watcher, err := fsnotify.NewWatcher() // 2 if err != nil { // 3 log.Fatal("Error creating watcher:", err) } defer watcher.Close() // 4 err = watcher.Add(watchPath) // 5 if err != nil { // 6 log.Fatal("Error adding watch:", err) } go func() { // 7 for { select { case event := <-watcher.Events: // 8 fmt.Printf("Event: %s\n", event.Name) case err := <-watcher.Errors: // 9 log.Println("Error:", err) } } }() signalCh := make(chan os.Signal, 1) // 10 signal.Notify(signalCh, os.Interrupt, syscall.SIGINT) // 11 <-signalCh // 12 fmt.Println("Received SIGINT. Exiting...") }File rotation
File rotation helps you efficiently manage and organize files so they do not consume too many resources. It is helpful in the following scenarios:
Benchmarking
Benchmarking is a systematic method of measuring and comparing the performance of software. It creates a controlled environment where you can analyze the impact of changes in code, algorithms, or system architecture.
Benchmark tests are nonfunctional tests—they do test whether the software performs its intended purpose. They test how well the software performs in terms of stability, speed, and scalability.
Benchmark tests take
*testing.Bas a parameter. This type has many of the log and error functions available to the*testing.Ttype.Concision
Writing concisely means using just enough words to say what you mean.
How to revise
There are six principles to write concisely.
Delete meaningless words
Some examples:
- kind of
- actually
- particular
- really
- certain
- various
- virtually
- individual
- basically
- generally
- given
- practically
Delete doubled words
Doubled words began when writers paired a French or Latin word with an English word to sound smarter. Just pick one:
- hope and desire -> hope
- each and every -> each
- any and all -> all
Delete what readers can infer
Redundant modifiers
When the meaning of the word is implied by its modifier:
Input/output
In Go, input and output center around the
io.Readerandio.Writerinterfaces. A type that implementsio.Readeris a “reader”, and a type that implementsio.Writeris a “writer”. Here is a summary of each:- Reader: A type that reads its own bytes. Each reader has a
Readmethod that reads the contents of the reader itself and stores it in a slice of bytes in memory. - Writer: A type that can receive bytes. Each writer has a
Writemethod that writes a slice of bytes from memory into the writer itself.
Memory management
Memory management is a primary design feature of the Reader and Writer interface. Both interfaces require that the caller provide a byte slice (
[]byte). This lets the caller allocate memory for one byte slice, read or write data into that slice, then do something with the data. The caller can fill that single buffer as many times as needed instead of allocating multiple byte slices.Files and directories
Streams
STDIN, STDOUT, STDERR
Every program is a process, and every process has three distinct file descriptors:
Stream File descriptor Description stdin0 The default source of input to a program stdout1 The default destination for program output stderr2 The default destination for error messages Redirection and piping
Redirection lets you change where a program reads input from and sends output to, without modifying the program itself:
Operator Description Example >Redirects STDOUT to a file ls -la > listing.out<Sends a file to a program as STDIN program < input.txt2>Redirects STDERR to a file cp -r /etc/a /etc/b 2> err.msg2>&1Redirects STDERR to the same location as STDOUT program > output.out 2>&1&>Shorthand to redirect both STDOUT and STDERR program &> output.out>and2>Redirect STDOUT and STDERR to separate files find / -name 'syslog' > stdout.txt 2> stderr.txtRedirect STDIN and STDOUT
The following command sends
input.txttoprogramas STDIN and redirects STDOUT tooutput.out:Compression
Linux bundles files and directories in one step, then optionally compresses them in the next. The available tools range from single-file compression with
gzip,bzip2, andxz, to multi-file archives withtar, to splitting large archives for transfer withsplit.Compression methods
- The following compression methods all provide lossless compression:
- gzip
- Replaced the old
compressprogram. Replaces the original file with a compressed version using the.gzextension. Rungunzipto reverse the operation. - bzip2
- Compressed the Linux kernel until 2013. Replaces the original file.
- xz
- Popular with Linux admins. Has compressed the Linux kernel since 2013. Replaces the original file.
- zip
- Operates on multiple files and packs them into an archive. Does not replace the original file. Instead, it places a copy into the archive.
Comparing compression methods
To compare compression methods on the same set of files:
Config files
Config files let you supply persistent configuration without command-line arguments. Go supports JSON natively; YAML, INI, and environment variables require small third-party libraries or the standard
ospackage.JSON
Go’s
encoding/jsonpackage reads JSON config files into structs. JSON doesn’t support comments.Here is
conf.json:{ "username": "rjs", "password": "secret", "port": 4001, "storage": "path/to/local/store", "enableFlag": true }This code sample parses
conf.jsonand stores its values in memory:Capitalize all
configfields to export them.Sample CSS stylesheet
Deprecated Still has some good info, so keeping.
/* -------------------- */ /* Helpful links */ /* -------------------- */ /* clamp details: https://css-tricks.com/linearly-scale-font-size-with-css-clamp-based-on-the-viewport/ */ /* breakpoints: https://www.freecodecamp.org/news/the-100-correct-way-to-do-css-breakpoints-88d6a5ba1862/ 600px, 900px, 1200px, and 1800px */ /* -------------------- */ /* Custom Properties */ /* -------------------- */ :root { /* colors */ --clr-dark: 230 35% 7%; /* font sizes */ /* 400 is the base size. Work from base 16 */ --fs-900: clamp(5rem, 8vw + 1rem, 9.375rem); --fs-400: 0.9375rem; /* font-families */ --ff-serif: 'Bellefair', serif; /* use em because of Safari issue */ @media (min-width: 35em) { } @media (min-width: 45em) { } } /* -------------------- */ /* Reset */ /* -------------------- */ /* https://piccalil.li/blog/a-modern-css-reset/ */ /* Box sizing */ *, *::before, *::after { box-sizing: border-box; } /* Reset margins (collapsing margins) */ body, h1, h2, h3, h4, h5, p, figure, picture { margin: 0; } h1, h2, h3, h4, h5, h6, p { font-weight: 400; } /* set up the body */ body { font-family: var(--ff-sans-normal); font-size: var(--fs-400); color: hsl(var(--clr-white)); background-color: hsl(var(--clr-dark)); line-height: 1.5; /* browser default is 1.4 */ min-height: 100vh; /* prevents strange short pages */ display: grid; grid-template-rows: min-content 1fr; /* */ overflow-x: hidden; } /* make images easier to work with */ img, picture { max-width: 100%; display: block; } /* make forms easier to work with. By default, these items do not inherit font properties */ input, button, textarea, select { font: inherit; } /* remove animations for people who've turned them off (when motion causes problems) */ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } } /* -------------------- */ /* Utility Classes */ /* -------------------- */ /* gap is custom prop you can set on each flex/grid container */ .flex { display: flex; gap: var(--gap, 1rem); } /* https://css-tricks.com/snippets/css/complete-guide-grid/ */ .grid { display: grid; gap: var(--gap, 1rem); } .d-block { display: block; } /* --flow-space lets you set the margin-top differently on specific els */ .flow * + * { margin-top: var(--flow-space, 1rem); } .flow--space-small { --flow-space: .5rem; } .container { padding: 0 2em; margin: 0 auto; max-width: 80rem; /* margin-inline: auto; */ /* padding-inline: 2em (l/r not t/b) */ } /* screen reader only. Still in DOM, just hidden */ .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } .skip-to-content { /* absolute pulls it out of the flow so it doesn't interfere with other elements */ position: absolute; z-index: 9999; background: hsl(var( --clr-white)); color: hsl(var( --clr-dark)); padding: .5em 1em; margin-inline: auto; /* hides this from the screen */ transform: translateY(-100%); } .skip-to-content:focus { transform: translateY(0); transition: transform 250ms ease-in-out; } /* colors */ .bg-dark { background-color: hsl( var(--clr-dark) );} /* typography */ .ff-serif { font-family: var(--ff-serif); } /* you can use px for small and specific things every now and then */ .letter-spacing-1 { letter-spacing: 4.75px; } .letter-spacing-2 { letter-spacing: 2.7px; } .uppercase { text-transform: uppercase; } .fs-900 { font-size: var(--fs-900); } .fs-400 { font-size: var(--fs-400); } .fs-900, .fs-800, .fs-700, .fs-600 { line-height: 1.1; } /* -------------------- */ /* Components */ /* -------------------- */ /* primary header */ /* --------------------------- *\ /* Layout *\ /* --------------------------- */ .grid-container { text-align: center; display: grid; place-items: center; padding-inline: 1rem; padding-bottom: 4rem; } @media (min-width: 45em) { .grid-container { text-align: left; column-gap: var(--container-gap, 2rem); /* 2rem -> as much space as you need | 0-40rem | 0-40rem | 2rem -> as much space as you need */ grid-template-columns: minmax(2rem, 1fr) repeat(2, minmax(0, 40rem)) minmax(2rem, 1fr); }Typography
Text and typography
Good article: Modern CSS Techniques to Improve Legibility
If your
font-familyproperty setting uses this hierarchy:- First setting
- Fallback font
- Default user agent style
System font stack
You can make sure you get the font that you want with the system font stack, which is a long list of fallback fonts.
With variables:
:root { --system-ui: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } .element { font-family: var(--system-ui); }Without variables:
Positioning
By default, all elements are
position: static;. Anytime you change thepositionvalue, the element becomes positioned. Positioned elements are removed from the document flow so that you can place them anywhere on the screen.Initially, every element has static positioning:
position: static;Cheatsheet
Positioning Containing Block Use cases Fixed Viewport modal, navigation bars, floating chat buttons Absolute Closest-positioned ancestor element, (usually a relativepositioned element)popup menus, tooltips, “info” boxes Relative element with position: absolute;dropdown menus Sticky section headings Fixed
Containing block: viewport
Content Sections
Archetypes are content templates. You can create a new archetype in your site or theme, then generate a markdown page using the template with this command:
hugo new <archetype>/filename.mdHugo creates an
<archetype>directory if it doesn’t exist, and then create thefilename.mdfile using the archetype as a template. For example, if you want to create a blog post, you create an archetype titledposts.md, then run this command to create your first post:Buttons
According to the WCAG, buttons need to meet these six baseline criteria:
- Must convey a semantic button role programmatically
- Apply the
<button>element so it has the implicitbuttonrole. - Must have a concise and straightforward accessible name
- Label the button, or the user and screen reader will not know what it does.
- Communicates its state (pressed, etc)
- Apply ARIA attributes to convey the button’s state, or the state of a different element that the button controls.
- Recognizable as a button
- Buttons should look like buttons. Users spend time on other sites that follow the same general visual conventions, and they expect your site’s buttons to match.
- Colors must have sufficient contrast
- Must have a contrast ratio of 4.5:1 for normal text and 3:1 for large text.
- The background color or outline of a focus indicator or border must have a contrast ratio of 3:1.
- Must be focusable and allow activation through click, touch, or key events
- A button is an interactive element, which means users must be able to perform identical actions with the mouse and keyboard by pressing
EnterorSpace. To do this, make it tabbable.
The following examples cover the two main button types and ARIA state communication:
Data structures
Python provides four core sequence and collection types: tuples, lists, dictionaries, and sets. Choosing the right type affects both correctness and performance.
Tuples and lists both hold ordered sequences of any type. The key distinction is mutability:
- Tuples are immutable. Once created, their contents cannot change. Apply tuples for values that should not be modified — function return values, dictionary keys, or fixed configuration records.
- Lists are mutable. Apply lists when a collection’s contents need to change over time — adding items, removing items, or sorting.
Tuples
Creating a tuple
Apply parentheses or a trailing comma to create a tuple. A trailing comma after a single value is required to distinguish a tuple from a grouped expression:
Events
JavaScript is event-driven: the browser generates an event whenever something changes in the document or the browser itself. A page finishing its load, a user clicking a button, or a cursor moving across the screen all produce events. Any HTML element can be an event target, and you register functions — called event handlers — to run when a specific event occurs on a specific element.
Further reading
- Eloquent JavaScript: “Handling Events” — a deep dive into the event model with interactive examples.
- MDN: Introduction to Events — the reference guide for event types, properties, and browser compatibility.
Event model
The JavaScript event model has five core concepts.
Headings and sections
Use the right element so you don’t have to add notes to your markup. It also means you don’t have to add extra classes or IDs to target elements with CSS or JS. Classes and IDs add no semantic value for screen readers or search engines. It also means that you don’t have to use the
roleattribute as much.Semantic landmarks
Don’t overdo landmarks in your page. It might create too much noise for screen readers and actually hurt accessibility.
Joins
Joins retrieve data from two or more tables and combine it into a single result set. You will rely on joins constantly when working with normalized databases, where data is split across related tables to avoid duplication. For example, an invoices table stores vendor IDs rather than repeating vendor names on every row. A join reconnects that data at query time.
INNER JOIN
An inner join returns only the rows where the join condition is satisfied in both tables. This is the most common type of join.
Menus
Navigation menus
When creating navigation menus with submenus, be careful with these ARIA attributes. Make sure you use
aria-expanded="true|false"on the top level menu item. Use this attribute on click, not on focus.These ARIA attributes are for application menus and not navs:
aria-haspopup="true": activated on click and only reveal a secret menurole="menu"role="menuitem"
For touch screens, top-level destination pages should have a table of contents rather than a submenu.
MySQL
This section borrows heavily from Tutorial: Accessing a relational database. For information about transactions, query cancellation, and connection pools, see Accessing a relational database.
Import the driver
Go to SQLDrivers and locate the go-sql-driver/mysql link.
In the go file that runs SQL code, import the driver. Because you are not using the driver directly, import it with the
blank identifier:package main import "_ github.com/go-sql-driver/mysql"Use the blank identifier because you do not use any methods from the
mysqldriver–you use only the driver’sinit()function so the driver can register itself with thedatabase/sqlpackage.Shell efficiency
The shell rewards investment in learning its efficiency features. Most of what makes an experienced administrator fast is not typing speed – it is knowing which tools to reach for and how to combine them. History navigation lets you recall and fix commands in seconds instead of retyping them. Job control lets you run long tasks in the background while you continue working. Process substitution and
xargslet you feed the output of one command into another in ways that pipes alone cannot.Undoing changes
Git gives you several ways to undo work at different stages of the workflow. The right tool depends on whether the change is in your working tree, in the staging area, or already committed. The sections below cover the most common recovery operations.
Amending the last commit
git commit –amend
--amendreplaces the most recent commit with a new one. Git creates a fresh commit object (with a new SHA-1 hash) that incorporates any staged changes alongside the previous content. It is best reserved for local commits that have not been pushed to a shared branch, because rewriting a published commit forces anyone who has based work on it to reconcile their history.Processes and pipes
The
os/execpackage contains the types and methods to run external processes.Execute commands
This trivial example runs executes the Bash command
sleep 2, which makes the terminal sleep for two seconds. You can manage the process with a context with a timeout and channels:exec.Commandtakes astringcommand and a variable number ofstringarguments so you can pass multiple flags or options.- Define a custom timeout. This timeout is longer than the
sleepargument so there is enough time forsleepto complete. - Create a cancellable context with a timeout deadline. This returns a context and a cancel function.
- Defer the cancel function so that it is called either when the function exits or the context expires.
- Run the command with
Start. The command is run asynchronously, so it does not block. - Create a
donechannel of type error to track when the command completes. - In a goroutine, run the command
Waitmethod. This method waits for the command to complete, and then returns an error. Run it in a goroutine because it will block execution. - The
selectstatement waits for events on channels.- Wait for the context to fire the
Donemethod.Doneis a channel that closes when the timeout expires. WhenDonesends a value, usecmd.Process.Killto stop the process. Handle any errors. - If the command does not complete before the timeout expires, receive an error from the
donechannel.
- Wait for the context to fire the
func main() { cmd := exec.Command("sleep", "2") // 1 timeout := 3 * time.Second // 2 ctx, cancel := context.WithTimeout(context.Background(), timeout) // 3 defer cancel() // 4 if err := cmd.Start(); err != nil { // 5 panic(err) } done := make(chan error, 1) // 6 go func() { // 7 done <- cmd.Wait() }() select { // 8 case <-ctx.Done(): // 8.1 if err := cmd.Process.Kill(); err != nil { panic("failed to kill process: " + err.Error()) } fmt.Println("Process killed as timeout reached") case err := <-done: // 8.2 if err != nil { panic("process finished with error: " + err.Error()) } else { fmt.Println("Process finished successfully") } } }IPC and pipes
Inter-process communication (IPC) allows efficient data transfer between system processes. A pipe is an in-memory conduit for transporting data between two or more processes. Pipes use the consumer-producer model: one process produces data and funnels it into a pipe, and the consumer process reads data from that stream.
TLS
Transport Security Layer (TLS)—also called a Secure Socket Layer (SSL) certificate—encrypts communications between the client and server. It serves two purposes:
- Encryption: Ecrypts the data in transit between client and server.
- Authentication: Verifies the identity of the server to client, and vice versa.
A TLS certificate is signed by a trusted Certificate Authority (CA). This “trust” comes from a root CA cert that is already installed in the client’s trust store, which is in the OS or browser. In reality, the cert is signed by an intermediate CA, which chains up to a trusted root.
Shape
Follow these rules, and your sentence will not be shapeless:
- Place the point near the beginning
- Get to the verb in the main clause quickly
- Do not tack on phrases and subordinate clauses after the verb
- Do not interrupt the flow too often
Starting with your point
Begin with a short, concrete subject directly followed by a verb that states a specific action. The beginning should be short and direct, and it should frame the more complex information at the end of the sentence. This is true both grammatically and logically—the beginning is the point (short and direct), and what follows is the supporting information (complex).
Regex
Regular expressions (regex) let you search, validate, and transform text using a compact pattern syntax. You write a pattern, and the regex engine matches it against a string to find specific characters, words, or structures.
Practice tools:
How regex patterns work
Wrap your pattern in forward slashes. Everything between them is the pattern:
/cat/gThe
gafter the closing slash is a flag. Flags control how the match runs. The next section covers them in detail.Processes
Jobs
Use job control to run and manage multiple processes from a single shell session:
CTRL + z # suspend the current process and send it to the background jobs # list all background jobs fg # bring the most recent job to the foreground fg 1 # bring job 1 to the foreground bg 1 # resume job 1 in the background <program> & # start <program> directly in the backgroundps
Use
psto list processes running on your system.Files
Reading files
Go’s
ospackage provides several ways to read a file. Choose based on file size and whether you need to process data all at once or as a stream:Method Description Use case os.ReadFileReads the entire file into memory at once Small, bounded files os.Open+bufio.ScannerReads tokenized input one token at a time Line-by-line text, log files os.Open+bufio.ReaderReads raw bytes or strings with full EOF control Custom protocols, binary formats ReadFile
os.ReadFilereads the entire file into memory and returns a byte slice. It’s the simplest option, but it has tradeoffs:Container Queries
Container queries make individual UI modules responsive based on their container’s size or style, rather than the viewport. A container is an ancestor element that contains the element you are sizing. It typically defines a region of the page through its dimensions, background, or other visual boundary.
There are two kinds of container queries:
- Container size queries: Adjust element styles based on the width of their container.
- Container style queries: Adjust element styles based on a custom property value on the container.
Without container queries, a module that does not fit its context at certain sizes forces you to write multiple
@mediaqueries, one for each breakpoint where the layout breaks. This couples the module to specific viewport sizes, which violates a key principle of modular design: design modules independently of where you use them. Container queries solve this by letting each module respond to its own container instead.Data Sources
Info about Google Analytics is on pg 36.
Site configuration data
Access data in
hugo.tomlwith the.Siteobject. Hugo has many configuration settings that you can add. Here, we add a params section with the author and description field:[params] author = "Arthur Gname" description = "My portfolio site"We want to add this info to the
<head>on all pages, so we go tothemes/docsite/layouts/_partials/head/head.htmland add the following:Attributes
Attributes provide details about the functionality of the element. They are always in the opening tag:
- global attributes can be used in any element
- some attributes apply to some elements but not all
- element-specific attrs apply to a single element
- Boolean attrs do not require a value
Case-sensitive
You should always quote attribute values:
- Attrs that are part of the HTML spec are case-insensitive
- Values that you assign to the attrs are case-sensitive
<!-- the type attribute is case insensitive: these are equivalent --> <input type="text" /> <input type="TeXt" /> <!-- the id attribute is case sensitive: they are not equivalent --> <div id="myId"> <div id="MyID"></div> </div>Booleans
If a Boolean attribute is present, it is considered true. Examples:
Commands reference
This page lists all commands covered in the bash documentation section, organized by category. Each entry includes a brief description, common options, and a real-world usage example. Refer to this page when you need a quick reminder of syntax or flags.
Text processing
awk
A programming language for transforming structured text. Splits each line into fields and runs your program against each line. Fields are numbered
$1,$2, …,$NF(last field).$0is the whole line.Dictionaries and sets
Dictionaries
Dictionaries store key-value pairs. Keys must be hashable — strings, numbers, or tuples of hashable types. Values can be any type. Python 3.7 and later preserve insertion order.
Creating dictionaries
The following examples show the standard ways to create dictionaries:
# With curly braces: empty_dict = {} beatles = { "John": "Lennon", "Paul": "McCartney", "George": "Harrison", "Ringo": "Starr", } # With dict() — keyword arguments become string keys: poet = dict(first='Edgar', middle='Alan', last='Poe') # {'first': 'Edgar', 'middle': 'Alan', 'last': 'Poe'}Convert two-value sequences into a dictionary by passing a list of pairs to
dict():DML
DML (Data Manipulation Language) statements add, modify, and remove rows in a table. In application development, these statements power the create, update, and delete operations behind any user-facing feature. Understanding how to combine them with subqueries lets you express complex data changes in a single statement rather than coordinating multiple round trips from application code.
INSERT
The
INSERTstatement adds one or more rows to a table. Name the target table in theINSERT INTOclause, optionally list the columns to populate, then provide values in theVALUESclause.Migrations
A database migration is a version-controlled database automation workflow that creates and reverses changes to a database schema. Mirgration files come in pairs and contain database statements that create and delete objects in the database: the
upfiles create, thedownfiles delete. For example, anupfile might create a table, and thedownfile might drop the table.Install
In Go, you can manage PostreSQL database migrations with the migrate tool. The following command downloads the binary, then extracts the archive file into your current directory:
Remotes
A remote is a version of your repository hosted at another location: a service like GitHub or GitLab, an on-site server, or even another directory on the same machine. Remotes let teams share work. You push commits to share your changes and fetch or pull to receive changes from others.
Managing remotes
git remote
git remotelists the remotes configured for the current repository. The default name git assigns to the server you cloned from isorigin:Scripting
JavaScript was created to build interactive web applications from static HTML documents. Every
Windowobject has adocumentproperty that references theDocumentobject. TheDocumentobject is the central object in the Document Object Model (DOM) and provides the API you use to manipulate document content.Selecting document elements
CSS selectors describe elements or sets of elements within a document. The following examples show common selector patterns:
div // any <div> #nav // id="nav" .warning // class="warning" p[lang="fr"] // p with lang="fr" attribute *[name="x"] // any element with name="x" attribute span.fatal.error // <span> with class="fatal error" span[lang="fr"].warning // <span> with lang="fr" and class="warning" #log span // <span> descendant of element with id="log" #log>span // <span> child of element with id="log" body>h1:first-child // first <h1> in the body img + p.caption // <p class="caption"> immediately following an <img> h2 ~ p // <p> after an <h2> and is a sibling of the <h2> button, input[type=button] // either a button element or <input type="button">querySelector()andquerySelectorAll()search for elements matching a CSS selector. They are the preferred selection methods and can be called ondocumentor any element object to search within that element’s descendants:Styles
Many of these styles focus on progressive enhancement, which is a strategy of building layers of styles that activate based on the browser’s capabilities. A browser that supports a newer feature gets the enhanced experience. A browser that does not falls back to a functional baseline. Here are some links about progressive enhancement:
- It’s about time I tried to explain what progressive enhancement actually is
- Understanding Progressive Enhancement
- Quick Tips for High Contrast
- WHCM and System Colors
Color
Do not rely on color alone to convey information. Approximately 8% of men and 0.5% of women have some form of color vision deficiency. A red/green error indicator, for example, is completely invisible to users with red-green color blindness. Always pair color with a second cue such as an icon, a text label, a pattern, or a shape.
Testing
Create a test database
This tests that you are correctly connecting to the database. It creates a unique database for each test:
- Designate the test function as a helper.
mode=memorycreates a unique, in-memory database named after the database (tb.Name()) that is shared (cache=shared) by all database connections in the test.Cleanupruns after the test finishes to clean up the test db resources. This is a special method for testing. Don’t usedefer—it would close the connection when the function completes, which is too soon for database operations.
func DialTestDB(tb testing.TB) *sql.DB { tb.Helper() dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", tb.Name()) db, err := Dial(tb.Context(), dsn) if err != nil { tb.Fatalf("DialTestDB: %v", err) } tb.Cleanup(func() { if err := db.Close(); err != nil { tb.Logf("DialTestDB: closing: %v", err) } }) return db }Integration testing
This tests whether the
Shotenerfunction properly calls thelinkpackage to shorten and persist a link:Testing
Servers
httptest.Serveris a server that is tuned for testing. It serves HTTP requests with anhttp.Handlerinterface.This example tests that the
SendNfunction sends the correct amount of requests to a server. It uses 5 concurrent goroutines. Because we are counting concurrent tasks, we use anatomiccounter:- Create a thread-safe counter. Use the
atomicpackage rather than a normalintto prevent a race condition. - Create the test server. This passes a
HandlerFuncthat converts a function into anhttp.Handler. This handler increments thehitsatomic variable. - Call the function you are testing.
t.Contextreturns a context tied to the life of the test. - When you run concurrent tests that use a channel, you need to make sure you consume the results, or the channel might block and break your test.
- The
Loadfunction retrieves the number stored in the atomic variable.
func TestSendN(t *testing.T) { t.Parallel() var hits atomic.Int64 // 1 srv := httptest.NewServer(http.HandlerFunc( // 2 func(_ http.ResponseWriter, _ *http.Request) { hits.Add(1) }, )) defer srv.Close() req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody) if err != nil { t.Fatalf("creating http requests: %v", err) } results, err := SendN(t.Context(), 10, req, Options{ // 3 Concurrency: 5, }) if err != nil { t.Fatalf("SendN() err=%v, want nil", err) } for range results { // just consume the results // 4 } if got := hits.Load(); got != 10 { // 5 t.Errorf("got %d hits, want 10", got) } }Handlers
Testing a handler involves providing a
RequestandResponseWriterand observing its response. You can inspect a handler’s response withhttptest.ResponseRecorderto verify it responds with what you expect.UNIX Sockets
UNIX sockets—also called UNIX domain sockets—are a local alternative to TCP/IP sockets for IPC. They provide a way for processes to communicate with each other on the same machine quickly and efficiently. UNIX sockets can be stream- or datagram-oriented, and they are represented as files or directories. They have the following features:
- Efficiency: You can transfer data between processes without a network. Even calling localhost requires that you use the TCP/IP stack.
- Filesystem namespace: They are file system paths—they are easy to locate and persist until you remove them.
- Security: Manage access with standard filesystem permissions.
Creating a socket
When you create a UNIX domain socket, Go creates a socket file descriptor in the OS and binds the socket it to the given file system path.
Date Time
Computers have two types of clocks: a wall clock and a monotonic clock. A wall clock synchronizes with an NTP server to track the current time. Its value can be inconsistent: another user or program might reset it, or it might jump forward or backward.
A monotonic clock always moves forward and is unaffected by those adjustments. Because it never goes backward, the monotonic clock is used to measure elapsed time.
System Resources
Disk space
When a disk fills up, start with
df -hto identify the affected volume, then drill down withduandncduto find what is consuming space.- Run
df -hto identify which volume is running low. - Run
du -hsc *in the affected volume to find the directory consuming the most space. - Run
ncdu -xfor an interactive breakdown of that directory.
df
df(disk free) shows file system usage across all mounted volumes. By default it reports sizes in bytes. Pass-hfor human-readable output. Device names reflect the underlying storage hardware. For example,sdafor SATA/SCSI disks andnvme0n1for NVMe drives.Common Features
.Summary content
Add
<!-- more -->to the file to indicate the end of the page summary. Hugo will grab the text before<!-- more -->and use it as the.Page.Summaryvalue:Lorem ipsum dolor sit amet consectetur adipiscing elit. Quisque faucibus ex sapien vitae pellentesque sem placerat. In id cursus mi pretium tellus duis convallis. Tempus leo eu aenean sed diam urna tempor. <!-- more --> ...Blog post format
Here is a simple format for a blog post. It uses site configuration info to populate some content, and it uses Hugo functions to calculate the amount of time that it takes to read the blog (assuming a person reads 200 wpm):
Aggregates
Aggregate functions operate on a series of values and return a single summary value. A query that contains one or more aggregate functions is called a summary query. Aggregates power reporting, dashboards, and any feature that needs counts, totals, or averages from a set of rows — for example, calculating total revenue per vendor or finding the average invoice amount for a given month.
Aggregate functions
The following aggregate functions are available:
Focus
Keyboard navigation is not just for users with motor disabilities. Power users, developers, and anyone who prefers not to reach for a mouse all rely on it. If a user cannot see where focus is on the page, they cannot navigate your site with a keyboard. Focus management is the foundation of keyboard accessibility.
Tips
- Do not create custom modal elements if you can avoid it. The native
<dialog>element manages focus automatically: it traps focus inside the dialog while it is open and returns focus to the triggering element when it closes. A custom modal requires you to implement all of that behavior yourself.
Styles
Adding focus styles is one of the most important things you can do for keyboard accessibility. You need visible styles on elements so users can track which element is currently active as they tab through the page. Default browser styles are sufficient but inconsistent across browsers. Define your own to ensure consistency.
Functions
Functions are the primary unit of reusable logic in Python. When you call a function with arguments, Python copies the argument values into the function’s parameters. Because Python is dynamically typed, parameters accept any type — type hints make the expected types explicit without enforcing them at runtime.
Basic functions
Defining and calling functions
Python requires the
passstatement in a function body that does nothing:def nothing(): pass nothing()Positional argument values are copied to parameters in the order they are listed:
Geometry and scrolling
Understanding how the browser renders elements on the screen requires you to understand a coordinate-based view of the document.
Document coordinates and viewport coordinates
The
xcoordinate increases from left to right andyincreases from top to bottom. Every coordinate is measured relative to one of two reference frames.Document coordinates measure position relative to the top-left corner of the full rendered HTML document, regardless of scroll position.
Viewport coordinates measure position relative to the top-left corner of the visible browser window, excluding tabs, menus, and toolbars. Viewport coordinates are sometimes called window coordinates. An
<iframe>element acts as its own viewport.Tagging
Tags mark specific commits as significant, most commonly to identify release points such as
v1.0.0orv2.3.1. Unlike branches, tags do not move when new commits are added. Git supports two types: lightweight tags, which are simple pointers to a commit, and annotated tags, which are full objects stored in the git database with their own metadata and optional signature.Prefer annotated tags for releases. They carry the tagger’s name, email, date, and a message, and they can be signed with GPG. Lightweight tags are better suited for temporary or local markers.
Text and links
Text basics
Headings
Headings are not used to outline documents, but screenreaders do use them to explore the page and learn about its content:
- Default heading size is determined by the agent stylesheet, with
<h1>being the largest, and getting smaller through<h6> <h1>might be smaller based on whether it is nested. If it is nested, it is less important, so it is smaller- AOM still reports the
<h1>as a first-level heading
- AOM still reports the
To turn a section into a
regionlandmark, you need to add thearia-labelledbylabel to the section, and a matchingidto the section heading:Tooltips
Dependency injection
mainis hard to test because it produces side effects: actions that reach outside a function’s own scope. Common side effects include:- Reading from
os.Argsor environment variables - Writing to
os.Stdoutoros.Stderr - Calling
os.Exit - Reading or writing files directly
You can’t capture what was written to stdout in a test, and you can’t stop
os.Exitfrom killing your test process. Dependency injection solves this by making those dependencies explicit parameters rather than global calls. Go doesn’t need a framework for it. Interfaces, structs, and explicit parameters are enough.Performance
Performance optimization in Go requires that you understand its garbage collector, and the distinctions between stack and heap memory allocations. You need to optimize code to reduce memory usage and minimize garbage collection, which increases the scalability and responsiveness of Go applications.
Garbage collection
Blog post about Go’s garbage collector
Garbage collection prevents memory links, dangling pointers, and double frees. Go’s garbage collector (GC) handles memory inference—which memory to free—by tracking allocations on the heap, freeing unneeded allocations, and keeping allocations in use. The GC does this with tracing and reference counting.
Logs
syslog
Logging is now handled by
journald, but historically it was done bysyslogd. Thesyslogddaemon collected log messages from system data sources and sent them to the/dev/logpseudo device. It then read the metadata and headers to route each message to the correct plain text log file in/var/log/.Example rules
The following example shows the default rsyslog distribution rules:
# view logging distribution rules cat /etc/rsyslog.d/50-default.conf # routes log messages by facility auth,authpriv.* /var/log/auth.log # auth events *.*;auth,authpriv.none -/var/log/syslog # everything except auth #cron.* /var/log/cron.log kern.* -/var/log/kern.log ...Syntax reference
kern.crit # kernel events at critical severity or higher kern.=crit # kernel events at critical severity only *.emerg # all facilities at emergency severity auth,authpriv.* # separate multiple facilities with a comma authpriv.none -/var/log/syslog # .none excludes a facility; - skips sync after write *.emerg :omusrmsg:* # send all emergency events to all logged-in userslog rotation
Log rotation prevents logs from consuming too much disk space. Three locations control how rotation works:
Images
To change the size of an image without changing its proportions, set the
widthto the size you want, and set theheighttoauto:img { height: auto; width: val; }Setting the height and width on an image also helps the browser calculate the image size while it loads the other content. This might prevent strange rendering behavior during page loads.
object-fit and object-position
An image might distort when you set its height and width dimensions. To prevent this, set
object-fit: cover;to maintain the object’s original aspect ratio while fitting inside the specified dimensions.Search
Sites with database-driven searches have built-in search capabilities. The site takes the search terms and builds a query that is sent to the database that contains the content. The db returns the matching results, and the site displays it to the user.
Hugo doesn’t use a database, so you need a solution that can index your site and search it:
- Algolia indexes your content and lets you search it
- ElasticSearch indexes your content
- You can generate your own search index and use client-side JS to perform the search
To generate your own search engine, you need Hugo to generate a list of your site content in JSON format.
Branching
A branch in git is a lightweight movable pointer to a commit. Creating a branch does not copy files. Git simply writes a 41-byte file containing the SHA-1 hash the branch points to. This makes branching nearly instant, regardless of repository size.
Branches let you isolate work. You can develop a feature, fix a bug, or run an experiment on a branch without touching the code on
main. When the work is ready, you bring it back by merging.Lists
These are the main kinds of lists:
- unordered lists:
<ul> - ordered lists:
<ol> - description lists:
<dl>
Unordered and Ordered lists can only have
<li>elements as a child.Ordered lists
By default, ols use numbers for their marker. You can change the marker with either the
list-style-typeCSS property or thetypeattribute:- If you remove the type, consider adding
role="list"to the list if it is important to know that this acts like a list
<ol type="A"> <li>Blender</li> <li>Toaster</li> <li>Vacuum</li> </ol>OLs have three element-specific attributes:
Location, nav, history
Location
The Location object, accessible as
window.locationordocument.location, represents the current URL of the document displayed in the window and provides an API for loading new documents. Thehrefproperty andtoString()method return the full URL string. Thehashproperty returns the fragment identifier, andsearchreturns the query string, which is the portion of the URL starting with?. Thedocument.URLproperty also returns the URL as a plain string.Navigation
Main nav
The main navigation of a site should follow this basic outline. The
aria-label="Main"attribute distinguishes this navigation landmark from other<nav>elements on the page (such as breadcrumbs or a footer navigation), so screen reader users can jump directly to the right one:<header> <a href="#main-nav" class="skip-link">Skip to navigation</a> <a href="#">Website logo</a> <a href="#">another link</a> <nav id="main-nav" aria-label="Main"> <ul> <li><a href="#">Home</a></li> <li><a href="#" aria-current="page">Products</a></li> <li><a href="#">Team</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header>- You do not need to add
role="list"to the navigation<ul>because the<nav>element preserves the native semantic information for list children, regardless of CSS styles applied. - The skip link lets users jump past interactive elements between the skip link and the target. Apply one if there are more than two interactive elements before the main navigation.
aria-current
aria-currenttells a screen reader which item in a set of related elements is the active one. It is a better alternative toclass="active"because class names are invisible to assistive technologies. You can apply both if you need the class for styling.Objects
An object is a data structure that combines data (stored as attributes) and behavior (defined as methods). In Python, everything is an object — numbers, strings, functions, and modules all follow the same object model.
Simple objects
Define a class with the
classkeyword. Instantiate it by calling the class name as a function:class Dog(): pass fido = Dog() pluto = Dog() # Each instantiation creates a distinct object at a different memory address.Attributes
Adding attributes with init
__init__()initializes a new object’s attributes. Python calls it automatically after creating the object. Its first parameter must beself— a reference to the object being initialized:Patterns
Data access layer
You want to encapsulate the code that works with MySQL in its own package. Create a new file in
root/internal/models/project.gofor your SQL data model.The data access layer consists of the following:
- An interface that holds method signatures for the data object. This facilitates testing with mocks:
type SnippetModelInterface interface { Insert(title string, content string, expires int) (int, error) Get(id int) (*Example, error) Latest() ([]*Example, error) } - A struct that holds data for each individual object that you want to commit to the database. Generally, the struct fields should correspond to the table columns:
type Example struct { ID int Title string Content string Created time.Time Expires time.Time } - An
ExampleModelstruct that wraps ansql.DBconnection pool. This is the type that you use as the receiver on the interface methods:type ExampleModel struct { DB *sql.DB } - Interface method implementations (
Insert,Get, etc.)
After you create the data access layer, you have to import it into the
mainfunction and inject it as a dependency into your main application struct:Window functions
Window functions apply an aggregate or ranking calculation across a set of rows related to the current row, without collapsing those rows into a single output row. Unlike
GROUP BY, which returns one row per group, window functions preserve every row in the result set while adding a calculated column alongside it. This makes them ideal for running totals, ranking within categories, comparing a value to the previous period, and percentile calculations.Backups
Follow the Backup Rule of Three: always keep three copies of your data:
- Two local copies on different media.
- One remote copy in case of disaster.
A backup is sometimes called an archive. An archive is a group of files with associated metadata that can be restored if the data becomes corrupted. When planning a backup strategy, consider the backup type, compression method, and tools best suited to your needs.
Forms
Forms are usually contained within the
<form>element, and contain form fields, or “controls.”Links
Form element
The form is a container (like a div) that wraps all the inputs that a user interacts with. Each form must have the following attributes:
action: accepts the URL value that the form sends its data tomethod: tells the browswer which HTTP method the form uses.Assets and Pipes
The extended version of Hugo has pipes that let you transform your assets from within Hugo. For example:
- Minify JS and CSS makes your files transfer faster, which improves speed
- Fingerprint to each file, so when you deploy a modified version, the browser invalidates the cached version and fetches the new one.
- Image processing, including resizing images
- Hugo doesn’t support advanced features like JS modules, so it integrates with Webpack.
Directory structure
Pipelines require that you move your assets from the
static/directory toassets/:Error handling
Python signals errors and unusual conditions through exceptions. When code raises an exception, Python unwinds the call stack looking for a matching
exceptclause. If it finds none, the program terminates and prints a traceback.try and except
Wrap code that might fail in a
tryblock. Provide oneexceptclause for each exception type you expect:alist = [0, 1, 2, 3, 4] bad_index = 6 # Without error handling: alist[bad_index] # IndexError: list index out of range # With error handling: try: alist[bad_index] except: print('Requires an index between 0 and', len(alist) - 1, 'but got', bad_index)Capture the exception object by name to inspect its details. Provide a specific
exceptfor each error type and a generalexcept Exceptionas a fallback:Navigation
Always use the
<nav>element for navigation. It tells the screen reader and search engine that the section has a role ofnavigationwhich is a landmark.Types of navigation:
- Global navigation: Links leading to top-level pages of the website that is found on every page. Can be displayed in nav bars, drop-down menus, and flyout menus. Changes according to viewport size
- Local navigation: Named anchors within text that link to other pages within the same website
- Breadcrumb: Local navigation that consists of a series of links that display the hierarchy of the current page in relation to the site’s structure
- Page TOC:
- Sitemap: Page containing hierarchical links to every single page on the site
“Skip to content” link
For better accessibility, let users skip blocks of content that appear on each page and go directly to the content.
Networking
Browsers load every web page over HTTP or HTTPS, and JavaScript provides APIs that let you make those same requests from your own code. The
fetch()API handles HTTP requests, the URL API constructs and parses URLs, and the WebSocket and Server-Sent Events APIs maintain persistent server connections.fetch()
fetch()is a promise-based API for making HTTP and HTTPS requests. It replaces the older XMLHttpRequest (XHR) API and supports every standard HTTP method and use case.Rebasing
Rebasing is one of the two ways to integrate changes from one branch into another. Merging preserves the full history of both branches, including when they diverged and when they came back together. Rebasing replays your commits on top of another branch, as if you had started your work from that point. The result is a linear history with no merge commits.
Choose rebasing when you want a clean, readable history on a feature branch before merging it into
main. Choose merging when you want to preserve the exact record of how work developed in parallel.Subqueries
A subquery is a
SELECTstatement nested inside another SQL statement. Subqueries let you reference computed values and derived tables without intermediate storage. A subquery cannot include anORDER BYclause.Where to introduce a subquery
A subquery can appear in four positions:
- In a
WHEREclause as a search condition - In a
HAVINGclause as a search condition - In the
FROMclause as a table specification (called an inline view) - In the
SELECTclause as a column specification
Subqueries vs. JOINs
Most subqueries can be rewritten as joins, and vice versa. Choose the form that is clearest for the problem at hand:
Visibility
Hide content
Hiding content responsibly provides a thorough overview.
Here are some general guidelines:
- Do not put
aria-hidden="true"orrole="presentation"on focusable, interactive elements like a button. - If you hide content visually with
opacity,height, ortransform, also hide the content semantically withvisibility: hidden;so screen readers do not read it. - Do not hide elements semantically if they are referenced elsewhere in the document. For example, do not hide an input that has a visible label.
As an example, you want a skip link before the navigation to be readable by screen readers, but you do not want to display it visually until the user focuses it. The following example hides content visually while keeping it accessible to screen readers. Read about the technique in The Anatomy of Visually-Hidden:
Troubleshooting
You need to know where to start troubleshooting, and some common techniques.
Evaluating the scope
Determine where the problem is and how many systems and services are affected. Reproducing the problem makes this easier. If you can’t reproduce it, trace how each network component contributes to the symptoms.
Start by asking: What are the symptoms? When did the problem start? Has this happened before? Were there recent network changes? If so, check the DNS or DHCP server. Identify which servers and users are impacted.
Preprocessor
A preprocessor takes the source file that you write and translates it into an output file, which is a standard CSS stylesheet. A preprocessor doesn’t add features to CSS, but it makes it easier to write.
- SCSS uses bracket syntax and the
.scssextension
Links
Installation and setup
npm init -y # create new npm project npm install --save-dev sass # install sass and add to package.json mkdir sass dist # create two dirs touch sass/index.scss # create main scss file touch index.html # create html file in root dir, link dist/styles.css cp $HOME/Development/scss-partials/reset.scss sass/ # copy reset into your files echo '@use "reset";' > sass/index.scss # include reset partial vim package.json # edit generated scripts { ... "scripts": { "start": "sass --watch sass/index.scss dist/styles.css", "build": "sass sass/index.scss dist/styles.css" }, ... } npm run start # starts a dev server for sass - updates when changes to files npm run build # run build script, [over]write dist/styles.cssWhen you run
npm run [start|build], npm does the following:Data types
A data type specifies the kind of information a column is intended to store and determines what operations can be performed on it. Choosing the smallest appropriate data type reduces storage requirements and improves query performance, since smaller rows fit more efficiently in memory and disk cache.
Data type categories
MySQL organizes data types into the following categories:
Category Description Character Strings of character data Numeric Integers and real numbers Date and time Dates, times, or both Large Object (LOB) Large strings of character or binary data Spatial Geographical values JSON JSON documents Character types
The two most common character types are
CHARandVARCHAR:Forms
Forms are often the most critical path in a product, covering login, checkout, search, and account management. An inaccessible form blocks a user from completing the task entirely. Follow these basic principles:
- Apply native form elements when possible
- Apply form elements for their intended purpose
- Keep forms short
- Label and describe all fields
- Inform users about changes to the form
People do not enjoy filling in forms, so keep them short. Before you add a question to a form, ask yourself the following questions:
Functional programming
Python supports functional programming patterns: passing functions as arguments, applying functions to sequences, and composing small functions into pipelines. The built-in
map(),filter(), andreduce()functions are the main tools — though list comprehensions often express the same ideas more clearly.map()
map(function, iterable)applies a function to every item in an iterable and returns a lazy iterator. Convert it to alistwhen you need all results at once.Storage
Browsers provide several APIs for storing data locally on the user’s device. This is called client-side storage. All client-side storage is segregated by origin: data stored by one site cannot be read by another. All client-side storage is also unencrypted, so you should never store sensitive data such as passwords or authentication tokens in any client-side storage mechanism.
Web apps control how long data persists. Some storage lasts only until the browser tab closes. Other storage remains until the user clears it or the app removes it through the API.
Tables
Table styling: https://estelle.github.io/CSS/tables/#slide1
Displays data in rows and columns. Good when you want to present data that should be:
- compared
- calculated
- sorted
- cross-referenced
Table elements
All elements are wrapped in
<table>, which has an implicit ARIA role oftable:- if the table has a selection state or lets the user rearrange data, use
role="grid" - if rows or cols can be expanded and collapsed, use
role="treegrid"
These elements all have table rows (
<tr>) that can have table headers (<th>) and table data (<td>):Disasters
You need a plan in case things break, because they will.
General guidance
Set network shares to read-only by default.
gitfor configuration filesConfiguration files control the behavior of your apps and services. Tracking and backing them up is nearly as important as backing up your data. Git can track server configurations and uses OpenSSH by default.
Set up the server
The server hosts the bare repository that clients push to. Run these steps on the machine that will act as your central config store:
Async
Asynchronous programs must wait for data to arrive or for some event to occur before they can continue. In the browser, JavaScript is event-driven: it waits for the user to act and then runs code in response. Callbacks originally handled these deferred operations.
Three language features now give you structured ways to work with async operations:
- Promises: Objects that represent the result of an async operation that has not yet completed
async/await: Keywords that let you structure Promise-based code as if it were synchronous- Async iterators and the
for/awaitloop: Work with streams of async events in loops
The core mental model
JavaScript runs on a single thread. It cannot literally pause and wait. Doing so would freeze the browser. Instead, async operations are registered and a callback (or Promise) runs when the result is ready. The rest of your code continues running in the meantime.
Best practices
Writing a Python script that works is the first step. Writing one that you can hand to a colleague, run in a cron job six months from now, or debug at 2 a.m. is the goal. These practices close that gap.
Project layout
Single-file scripts
A script that does one thing well belongs in a single file. Keep it short enough to read in one sitting, typically under 300 lines. When the file grows beyond that, or when you need to share logic across scripts, convert to a package.
Filtering data
Consider a product listing page where users can filter by brand, price range, and availability. When a user applies a filter, the page updates with new results. A sighted user sees the list change. A screen reader user hears nothing unless you explicitly notify them. This page covers how to build accessible filter interfaces.
To make a form a landmark, add
role="form"and give it an accessible name witharia-label="<name>".Forms
The
<form>element is a document landmark that contains interactive controls for submitting information. HTML<forms>can do the following without help from JS:- require the user to select form controls or enter a value
- define specific criteria that the value must match
- perform client-side constraint validation and prevent submission until it passes the criteria
To turn off client-side validation and let the user save progress until ready to submit, set the
novalidateattribute on the form, or theformnovalidateattribute on a button.Functions
MySQL provides a large library of built-in functions for transforming and analyzing data within queries. These functions let you format output, perform arithmetic, manipulate strings, work with dates, and implement conditional logic without requiring application-level post-processing.
String functions
Parsing with SUBSTRING_INDEX
SUBSTRING_INDEX(string, delimiter, count)returns the part of a string before (count > 0) or after (count < 0) the nth occurrence of a delimiter. This is commonly applied to split delimited values stored in a single column:Tables
Good article: Grids Part 1: To grid or not to grid
Tables appear in dashboards, leaderboards, financial reports, and comparison pages. When a screen reader encounters a table, it announces the number of columns and rows before the user reads any data. This orientation depends on correct table markup. Some screen readers also provide shortcuts to jump directly to a table.
Follow these practices for all tables:
- Add a
<caption>element to label the table. The screen reader announces the caption along with the column and row count, giving users immediate context. - If the table is nested in a
<figure>, apply a<figcaption>to label it instead. - If a table cell in the
<tbody>labels its row, apply the<th>element even though it is outside the table header section. The<th>element carries an implicit label role. - Avoid spanning headers with
rowspanandcolspan. Screen reader support for spanned headers is inconsistent.
Scrollable tables
You cannot apply scroll styles directly to a
<table>. To make a table scrollable, follow these steps:Arrays
You can create an array with the
newkeyword, but the array literal syntax is more common:let arr1 = new Array("purple", "green", "yellow"); let arr2 = new Array(10); // creates an array with 10 undefined values let bestAr = ["black", "orange", "pink"];A single array can hold elements of different types:
let arr = ["hi there", 5, true]; console.log(typeof arr[0]); // string console.log(typeof arr[1]); // number console.log(typeof arr[2]); // booleanYou can change the values of elements in a
constarray, but you cannot reassign it to a new array:Debugging
Accessibility testing requires multiple tools because no single tool catches every issue. Automated scanners catch roughly 30–40% of WCAG violations. The rest require keyboard navigation, screen reader testing, and visual inspection. A good testing workflow combines at least one automated tool, keyboard-only navigation, and a screen reader.
Testing tools
The following tools cover different parts of the accessibility audit process:
- axe DevTools: Open-source automated scanner by Deque Systems. It reports WCAG violations with no false positives, making it a reliable first pass. Available as a Chrome extension and a JavaScript library you can integrate into your test suite.
- Lighthouse: Google’s built-in audit tool. It scores accessibility alongside performance and SEO. Run it from Chrome DevTools or as a CI GitHub Action to catch regressions in pull requests.
- WAVE: Visual overlay tool that annotates the page with icons showing errors, alerts, and structural information. Available as a Chrome extension. Useful for understanding how a page is structured from an assistive technology perspective.
- ARC Toolkit: Detailed inspector from TPGi. It provides granular checks for ARIA, colour contrast, and keyboard accessibility. Available as a Chrome extension.
- IBM Equal Access Accessibility Checker: IBM’s rule-based scanner with its own rule set that complements axe. Available as a Chrome extension.
- pa11y: A headless command-line scanner built for continuous integration pipelines. Run it against any URL as part of a CI workflow to block regressions before they ship.
Chrome dev tools
Accessibility Tree, ARIA Attributes, Computed Properties, and Source Order
Browsers have built-in tools to inspect the accessibility tree, which is what a screen reader actually reads. This view shows each element’s computed role, name, and state after the browser has applied all CSS and JavaScript. Follow these steps to open it in Chrome:
Images
Schema
The schema is the structure of a database: its tables, columns, constraints, indexes, and relationships. You define and modify this structure with DDL (Data Definition Language) statements. Getting the schema right matters because changes to live tables with many rows can be slow and require careful planning.
Databases
To create a new database, run the
CREATE DATABASEstatement:CREATE DATABASE [IF NOT EXISTS] dbname;To remove an existing database and all its tables:
Testing
Writing code that works is the first goal. Knowing it still works after you change something is the second. Automated tests give you that confidence without manually running the program after every edit.
A test is a function that calls your code, checks the result, and either passes or fails. When a test fails, you know exactly what broke and where. When all tests pass, you can ship with confidence.
Patterns
This page collects common browser JS patterns — small, self-contained examples that combine DOM manipulation, event handling, and data management. Each example is intentionally minimal so the core technique is easy to extract and adapt.
Examples
Getting text content from click event
Passes
thisfrom an inlineonclickhandler to read the element’s text content. Demonstrates how to identify which button was clicked when multiple buttons share a handler.Pythonic patterns
Every language has idioms — patterns experienced developers reach for instinctively. In Python, these idioms are called Pythonic: code that is clear, concise, and takes advantage of what the language does best.
This guide covers the patterns you will encounter most often in production Python code. For each pattern, you will find an explanation of what it does, when to apply it, and a concrete example.
Comprehensions
A list comprehension builds a new list by applying an expression to each item in an iterable, with an optional filter. It replaces a
forloop and anappendcall with a single readable expression.Views
A view is a
SELECTstatement stored in the database as a named object. Think of it as a virtual table that consists only of the rows and columns itsCREATE VIEWstatement defines. Unlike query scripts saved to files, views are stored as part of the database itself, so any application or SQL client with database access can query them by name.Views are commonly applied to simplify complex joins, restrict which columns a user can see, and present a stable interface to application code even as the underlying schema evolves.
Best practices
These practices summarize patterns that consistently produce readable, predictable code. They are not rules to memorize — they are trade-offs to understand, so you know when to apply them and when a specific situation calls for something different.
Declarations
Prefer
const; useletwhen you need to reassignconstsignals intent: this binding will not change. It prevents accidental reassignment and makes code easier to reason about. Reach forletonly when you actually need to reassign the variable.Stored procedures
Stored programs are database objects that contain procedural code, allowing you to run logic inside the database rather than in application code. They reduce round trips between the application and the database and can enforce business rules at the data layer.
MySQL supports four types of stored programs:
Type Description Stored procedure Called explicitly from an application or SQL client with CALLStored function Called from a SQL statement like a built-in function (for example, CONCAT)Trigger Executed automatically in response to an INSERT,UPDATE, orDELETEon a specified tableEvent Executed at a scheduled time This page focuses on stored procedures.
Transactions
A transaction groups two or more SQL statements into a single logical unit of work. If any statement in the group fails, you can roll back all the changes as if none of them ran. Transactions are essential whenever a business operation requires multiple table updates that must succeed or fail together — for example, recording an invoice and its line items simultaneously.
Note: only storage engines that support transactions (such as InnoDB) can apply the statements on this page. MyISAM does not support transactions.
- Script subtag: Defines the writing system. For example,