Skip to content

Instantly share code, notes, and snippets.

@lkubicek1
Last active March 19, 2024 02:03
Show Gist options
  • Save lkubicek1/2ded8fd6c289d3bc45a618be9de569e9 to your computer and use it in GitHub Desktop.
Save lkubicek1/2ded8fd6c289d3bc45a618be9de569e9 to your computer and use it in GitHub Desktop.
Developer Field Notes

Developer Field Notes

Welcome to "Developer Field Notes" – a curated collection of cheatsheets, code snippets, and quick references designed for software developers, engineers, and technology enthusiasts. This resource aims to provide concise, at-a-glance guides to various programming languages, tools, and techniques, facilitating quick access to essential information needed during development.

Contents

  • docker.md - Dive into Docker commands, including image and container management, network and volume configurations, and system cleanup strategies.
  • python.md - A Python cheatsheet covering basics like list comprehensions, dictionary comprehensions, lambda functions, and more advanced concepts such as generators.
  • unix.md - An essential Unix command line cheat sheet featuring navigation and file management, text searching and manipulation, system monitoring, networking basics, file permissions, archiving and compression, viewing and editing files, and getting help and documentation.
  • More to come...

Purpose

The purpose of "Developer Field Notes" is to serve as a quick-reference guide that developers can turn to for recalling syntax, commands, and patterns that aren't used daily but are crucial when needed. It's intended to grow over time, incorporating more languages, tools, and best practices as they are encountered and documented.

Contribution

This is a living document, and contributions are welcome! If you have a cheatsheet, snippet, or piece of knowledge you think would benefit others, please feel free to add it to the collection. Your insights can help make this resource more comprehensive and valuable to the community.

Thank you for visiting, and happy coding!

Docker Cheatsheet

This Docker cheatsheet includes commonly used commands and operations within Docker, offering a quick way to manage containers, images, volumes, and more, including cleaning up your Docker system.

Back to contents

Basic Docker Commands

  • List Docker Images
    List all Docker images on the machine.

    docker image ls
  • Run a Docker Container
    Run a Docker container from an image. Common flags include -d for detached mode, -p for port mapping (host:container), and --name to name the container.

    docker run -d -p 8080:80 --name mycontainer <image>
  • Build a Docker Image
    Build a Docker image from a Dockerfile in the current directory, tagging it with the specified name. -t assigns a tag/name.

    docker build -t <tag> .
  • Remove a Docker Image
    Remove the specified Docker image. The image must not be used by any running container.

    docker rmi <image>
  • List Running Containers
    List all currently running containers. Use -a to show all containers (running and stopped).

    docker ps -a
  • Stop a Running Container
    Stop a container that is currently running, using its ID or name.

    docker stop <container_id>

Advanced Docker Commands

  • Inspecting Containers
    Get detailed information on a container's configuration and state.

    docker inspect <container_id>
  • Viewing Logs
    View the logs of a container. Useful for debugging or monitoring the application's output.

    docker logs <container_id>
  • Managing Volumes
    List, create, and remove volumes. Volumes are used for persistent data storage.

    • List volumes:
      docker volume ls
    • Create a volume:
      docker volume create <volume_name>
    • Remove a volume:
      docker volume rm <volume_name>
  • Port Mapping
    When running a container, use -p to map a port of the container to a port on the host.

    docker run -p 8080:80 <image>
  • Using Environment Variables
    Use -e to set environment variables within the container.

    docker run -e "ENV_VAR_NAME=value" <image>
  • Docker Compose Commands

    • Start services defined in docker-compose.yml:
      docker-compose up
    • Stop and remove containers, networks, images, and volumes:
      docker-compose down
  • Executing Commands in a Running Container
    Use docker exec to execute commands inside a running container. For example, to start an interactive bash session inside a container:

    docker exec -it <container_id> /bin/bash

Cleaning Up

  • Clean Entire Docker System
    Remove unused data and clean up your system. This will remove all unused images, containers, volumes, and networks.

    docker image ls -q | xargs docker rmi -f && docker system prune --volumes -a -f
  • Clean Entire Docker System, including Volumes
    Additionally removes all volumes.

    docker image ls -q | xargs docker rmi -f && docker volume ls -q | xargs docker volume rm -f && docker system prune --volumes -a -f
  • Clean Specific Docker Images
    Remove specific images and associated unused resources.

    docker ps -aqf "ancestor=<image_tag_or_id>" | xargs -r docker stop && docker ps -aqf "ancestor=<image_tag_or_id>" | xargs -r docker rm && docker rmi -f <image_tag_or_id> && docker system prune -a --volumes -f

Please use the cleaning commands with caution, as they can remove a significant amount of data from your Docker environment

Python Cheatsheet

This Python cheatsheet covers basic concepts, including list comprehensions, dictionary comprehensions, and more, to serve as a quick reference.

Back to contents

List Comprehensions

List comprehensions provide a concise way to create lists. The basic syntax is [expression for item in iterable if condition].

Example 1: Squares of Numbers

squares = [x**2 for x in range(10)]

Example 2: Even Numbers

evens = [x for x in range(10) if x % 2 == 0]

Dictionary Comprehensions

Similar to list comprehensions, dictionary comprehensions offer a succinct way to create dictionaries.

Example: Squares Index

square_dict = {x: x**2 for x in range(5)}

Ternary Operators

Ternary operators provide a way to condense an if-else block into a single line. The syntax is [on_true] if [condition] else [on_false].

Example: Minimum Value

min_val = a if a < b else b

Example: Classification

status = "Adult" if age >= 18 else "Minor"

Example: Default Values

Ternary operators can be especially useful for setting default values in scenarios where a variable might otherwise be None or another falsy value. This approach is handy in ensuring that a variable holds a meaningful default value if a certain condition is not met. Here's how you can apply ternary operators for defaulting values:

Example: Default Greeting

This example demonstrates setting a default string value if the original string is empty or None.

name = "John"
# Potentially mutate the name variable
greeting = f"Hello, {name}" if name else "Hello, Guest"

In this example, if name is an empty string or None, greeting will default to "Hello, Guest". Otherwise, it will use the value of name to create a personalized greeting.

Example: Default List

This example shows how to ensure a variable holds an empty list as a default value if the original list is None.

original_list = None
# Potentially initialize and/or mutate the list...
safe_list = original_list if original_list is not None else []

Here, safe_list will be an empty list if original_list is None. This technique prevents errors that could occur when attempting to access or manipulate None as if it were a list.

Example: Default Number

The following example sets a default number when the original value could be None or any other falsy value like 0.

number = None
# Potentially initialize and/or mutate the number
default_number = number if number is not None else 10

In this case, default_number will be 10 if number is None. This pattern ensures that default_number always has a valid numeric value, even if number doesn't.

Lambda Functions

Lambda functions provide a quick way of creating anonymous functions.

Example: Adder Function

adder = lambda x, y: x + y
print(adder(2, 3))

Map, Filter, and Reduce

Map Example

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

Filter Example

filtered = list(filter(lambda x: x % 2 == 0, items))

Reduce Example

from functools import reduce
product = reduce((lambda x, y: x * y), items)

Generators

Generators are a simple way of creating iterators using a function.

Example: Yield Squares

def gen_squares(n):
    for x in range(n):
        yield x ** 2

for square in gen_squares(5):
    print(square)

Unix Command Line Cheat Sheet

An essential Unix command line cheat sheet featuring navigation and file management, text searching and manipulation, system monitoring, networking basics, file permissions, archiving and compression, viewing and editing files, and getting help and documentation.

Back to contents

Navigating and Managing Files and Directories

  • ls - List files and directories.
    • ls -l - List with long format, showing permissions, ownership, size, and modification date.
    • ls -a - List all files, including hidden files (those starting with a dot).
  • cd directory_name - Change directory. Use cd .. to go up one directory.
  • pwd - Print the current working directory.
  • mkdir directory_name - Create a new directory.
  • rmdir directory_name - Remove an empty directory.
  • rm file_name - Remove a file. Use rm -r directory_name to remove a directory and its contents recursively.
  • cp source destination - Copy files or directories. Use cp -r for directories.
  • mv source destination - Move or rename files or directories.

Searching and Manipulating Text

  • grep "search_pattern" file_or_directory - Search for a specific pattern in files. Use -r for recursive search.
  • wc file_name - Count lines, words, and characters in a file.
    • wc -l - Count lines.
    • wc -w - Count words.
    • wc -c - Count characters.
  • sed 's/find/replace/g' file_name - Find and replace text within a file (streams the output; use -i for in-place edit).
  • awk '{print $1}' file_name - Process text files to extract and manipulate data (example shows how to print the first column).

Monitoring System and Processes

  • top - Display an ongoing view of running processes and system resources.
  • ps - List the currently running processes.
    • ps aux - List all running processes with detailed information.
  • kill process_id - Terminate a process with the given ID. Use kill -9 process_id for a forceful termination.
  • df - Display disk space usage for file systems.
    • df -h - Display in a human-readable format.
  • du - Estimate file space usage.
    • du -sh directory_name - Show total size of a directory in a human-readable format.

Networking

  • ping host_or_ip - Send ICMP ECHO_REQUEST packets to network hosts.
  • ifconfig or ip addr - Display network interfaces and IP addresses.
  • netstat -tulnp - List all current network connections with program names.

File Permissions

  • chmod - Change the permissions of files or directories.
    • chmod +x file_name - Add execute permission to a file.
  • chown user:group file_or_directory - Change ownership of a file or directory.

Archiving and Compression

  • tar -czvf archive_name.tar.gz directory_or_file - Create a compressed (gzip) tar archive.
  • tar -xzvf archive_name.tar.gz - Extract a compressed (gzip) tar archive.
  • zip -r archive_name.zip directory_or_file - Create a ZIP archive.
  • unzip archive_name.zip - Extract a ZIP archive.

Viewing and Editing Files

  • cat file_name - Display file content.
  • less file_name - View file content in a scrollable interface.
  • nano file_name - Edit file using the nano editor.
  • vi file_name - Edit file using the Vi editor.

Getting Help and Documentation

Most Unix commands come with built-in help documentation that can be accessed in a few different ways. Here are the primary methods for getting help directly in the terminal:

Using the man Command

The man command displays the manual pages for other commands. Manual pages provide detailed documentation about commands, including their options, usage, and examples.

man command_name

Replace command_name with the name of the command you want to learn more about. For example, man grep will show the manual page for the grep command.

Using the --help Flag

Many commands support the --help flag, which displays a brief overview of the command's usage and options directly in the terminal.

command_name --help

For example, grep --help will display usage information for the grep command.

Using the info Command

Some systems also provide the info command, which offers detailed information about commands in a format that's easier to navigate than traditional man pages.

info command_name

This command works similarly to man but might provide the information in a different format or offer more detailed documentation for some commands.

Searching Manual Pages with apropos

If you're not sure which command you need, you can use apropos to search the manual pages for keywords.

apropos search_term

This command will list any manual pages related to search_term, helping you find relevant commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment