Friday 17 July 2020

Functions in Go

To declare a function in Go, use the keyword func followed by the function name, any
parameters, and then any return values.

feeds, err := RetrieveFeeds()
if err != nil {

NOTE: You can omit the parentheses () from an if statement in Golang, but the curly braces {} are mandatory!

This function belongs to the search package and returns two values. The first return value is a slice
of Feed type values. A slice is a reference type that implements a dynamic array. You use
slices in Go to work with lists of data.

The second return value is an error.  
Functions can have multiple return values. It’s common to declare functions that return a value and an error value just like the RetrieveFeeds function. If an error occurs, never trust the other values being returned from the function. They should always be ignored, or else you run the risk of the code generating more errors or panics.

Why doesn't Go allow nested function declarations (functions inside functions)? - Stack Overflow

func plus(a int, b int) int {...}

Can Functions be passed as parameters in Go? Yes.

type MyFunc func(int) string

func Foo(fn MyFunc) {
    str := fn(123)

Variable can be of a function type and be assigned a function:

sayHello := func() {

go sayHello()

Go by Example: Variadic Functions

func sum(nums... int){...}

Three dots (ellipsis) notation

Specifying function's default value for an argument is NOT supported.
Default value in Go's method

When to return pointer to local variable?

Return pointer to local struct

Go performs pointer escape analysis. If the pointer escapes the local stack, the object is allocated on the heap. If it doesn't escape the local function, the compiler is free to allocate it on the stack (although it makes no guarantees; it depends on whether the pointer escape analysis can prove that the pointer stays local to this function).

Golang documentation states that it's perfectly legal to return a pointer to local variable.
Compiler sees you return the address and just makes it on the heap for you.

Escape Analysis in Go


Your custom function can't have the same name as the name of some imported package.

Function Overloading

Does the Go language have function/method overloading? (Answer: NO)
Optional parameters, default parameter values and method overloading

The idiomatic way to emulate optional parameters and method overloading in Go is to write several methods with different names.

Alternative Patterns for Method Overloading in Go
Functional options for friendly APIs <-- MUST READ (!)

Deferred execution

go - Multiple defers vs deferred anonymous function - Stack Overflow

defer func() {
  err := f.Close()
  if err != nil {
    log.Println("close:", err)
  err = os.Remove(f.Name())
  if err != nil {
    log.Println("remove:", err)

Built-in Functions



Go by Example: Panic
When to call panic() : golang
Panic in Golang - GeeksforGeeks


Go by Example: Closures

What exactly does “closing over” mean?

 "A closes over B" == "B is a free variable of A", where free variables are those that appear in a function's body, but not in its signature.

What will be the output of the following snippet?

var wg sync.WaitGroup

for _, letter := range []string{"a", "b", "c"} {
   go func() {
      defer wg.Done()


Go closure variable scope

Closures in Go capture variables by reference. That means the inner function holds a reference to the  i variable in the outer scope, and each call of it accesses this same variable.

Closure (computer programming)

Comapre to JS Clsoures.
Lexical scoping:
This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

How golang's “defer” capture closure's parameter?

// Launch the goroutine
go func(matcher Matcher, feed *Feed) {
   Match(matcher, feed, searchTerm, results) 
}(matcher, feed)


  • light-weight process that is automatically time-sliced onto one or more operating system threads by the Go runtime.
  • a function that’s launched to run independently from other functions in the program.
  • Use the keyword go to launch and schedule goroutines to run concurrently. 
  • the order the goroutines get executed is unpredictable
  • can be an anonymous function
  • can be launched in a (for-range) loop, for each element of some set: this allows each element to be processed independently in a concurrent fashion
  • There's no goroutine ID available from the runtime
  • not an OS thread (thread managed/scheduled natively by OS)
  • not exactly a green thread (thread managed/scheduled by languages runtime or virtual machine) [Green threads] [Why not Green Threads?]
  • is a special type of coroutine (concurrent subroutines - functions, closures or methods) - the one that is non-preemptive. It cannot be interrupted but instead has multiple points through which it can be suspended or reentered. Go runtime defines this points internally and automatically suspends them when they block and resumes them when they become unblocked.
  • goroutines operate within the same address space as each other, and host functions
  • Go implements M:N scheduler, which means it maps M green threads to N OS threads. Goroutines are then scheduled onto the green threads. When we have more goroutines than green threads available, the scheduler handles the distribution of the goroutines across the available threads and ensures that when these goroutines become blocked, other goroutines can be run.
  • Go follows a model of concurrency called the fork-join model.
  • function which runs as goroutine can have return value(s) and return them but they will never be read => they should not have a return value. If we want to read some value which is calculated in goroutine we should either use channels or variable capturing mechanisms [Catching return values from goroutines].

To launch a function as goroutine:
goroutines operate within the same address space as each other, and
simply host functions,
func foo() {

go foo()

To launch anonymous function as goroutine:

go func() {

anonymous function

  • a function that’s declared without a name
  • can take parameters

pointer variables

  • are great for sharing variables between functions. They allow functions to access and change the state of a variable that was declared within the scope of a different function and possibly a different goroutine.
  • In Go, all variables are passed by value. Since the value of a pointer variable is the address to the memory being pointed to, passing pointer variables between functions is still considered a pass by value.
Pointers vs. values in parameters and return values


Once the main task withing the goroutine completes, we execute the code which decrements the WaitGroup count. Once every goroutine finishes calling Done method, the program will know every main task has been done (e.g. element has been processed).

There’s something else interesting about the method call to Done: the WaitGroup
value was never passed into the anonymous function as a parameter, yet the anony-
mous function has access to it. Go supports closures and you’re seeing this in action. In fact, the searchTerm and results variables are also being accessed by the anonymous function via closures.
Thanks to closures, the function can access those variables directly without the need to
pass them in as parameters. The anonymous function isn’t given a copy of these variables; it has direct access to the same variables declared in the scope of the outer function. This is the reason why we don’t use closures for the matcher and feed variables.


With all the processing goroutines working, sending results on the results channel
and decrementing the waitGroup counter, we need a way to display those results and
keep the main function alive until all the processing is done. We'll launch yet another anonymous function as a goroutine. This anonymous function takes no parameters and uses closures to access both the waitGroup and results variables. This goroutine calls the method Wait() on the WaitGroup value, which is causing the goroutine to block until the count for the WaitGroup hits zero. Once that happens, the goroutine calls the built-in function close on the channel, which as you’ll see causes the program to terminate.

// Launch a goroutine to monitor when all the work is done.
go func() {
   // Wait for everything to be processed.

   // Close the channel to signal to the Display

   // function that we can exit the program.


func Match(matcher Matcher, feed *Feed, searchTerm string, results chan<- *Result) {
   // Perform the search against the specified matcher.
   searchResults, err := matcher.Search(feed, searchTerm)
   if err != nil {
   // Write the results to the channel.
   for _, result := range searchResults {
      results <- result

results are written to the channel

BK: not how nil is used instead of null
BK: note how it's so convenient the model of returning function result and error at the same time; no need to pass variable by pointer and no expensive exceptions
BK: note how there are no brackets around conditions in if, for... statements.

init() function

All init functions in any code file that are part of the program will get called before
the main function.

When is the init() function run?

func init() {
  // Change the device for logging to stdout.

This init function sets the logger from the standard library to write to the stdout device. By default, the logger is set to write to the stderr device.

main() function

How do I return from func main in Go? - Stack Overflow

func main() { os.Exit(mainReturnWithCode()) }

func mainReturnWithCode() int {
    // do stuff, defer functions, etc.
    return exitcode // a suitable exit code

Working with strings in Go

Strings are implemented as a reference type, though they're immutable.


s := "This is in first line"
s += "\n"
s += "...and this is in the second line"

How do you write multiline strings in Go?

This raw quote (raw literal) does not parse escape sequences (\n would remain):

`line 1
line 2\n
line 3`

It is possible to use formatters though:

fmt.Sprintf(`a = %d`, 123)

Another option:

"line 1" +
"line 2" +
"line 3"

What is the difference between backticks (``) & double quotes (“”) in golang?

String Comparison - use == or !=

Slice string into letters

String Formatting 

s := fmt.Sprintf("a %s", "string")

Go by Example: String Formatting
Extracting substrings in Go

%x - formats value as HEX string with lowercase letters
%X - formats value as HEX string with uppercase letters

var n []byte = ...
s := fmt.Sprinf("%x", n) 

How to print struct variables in console? To print the name of the fields in a struct:

fmt.Printf("%+v\n", myStruct)

To convert string to byte array use:

s string
buffer := []byte(s)


fmt.Println("Table names:", tableNames)

SPACE character is automatically inserted between these two strings.

Golang - How to print the values of Arrays?

fmt.Printf("%v", projects)


%+v - prints struct’s field names (if value is a struct)

Go string = byte sequence, UTF-8 encoded
Unicode UTF-8 code point = 1-4 bytes (1 for ASCII)
rune = int32 => can store each UTF-8 code point 

Unicode string example: en dash & Chinese letter 

package main

import (

func main() {
s := "\u2013汉"
fmt.Printf("Character %s has %d bytes, %d UTF-8 code points", s, len(s), len([]rune(s)))


Character –汉 has 6 bytes, 2 UTF-8 code points

Working with File system in Go

Package os contains useful functions for working with file system.

os - The Go Programming Language


  • opens the named file for reading (O_RDONLY mode).

  • opens file in a specified mode set via flag e.g.  O_RDWR or O_WRONLY.

  • creates or truncates the named file
  • If the file already exists, it is truncated. 
  • If the file does not exist, it is created. 
  • Methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR.

Truncate() function:
  • requires file to be opened in mode which allows writing into it.
  • if specified size is 0 deletes the content of the file and sets its size to 0.

Writing to files

Go by Example: Writing Files

Without buffering:

f, err := os.Create("/tmp/test.txt")
if err != nil {
defer f.Close()
f.WriteString("some text!\n")

WriteString() under the hood calls system function write():

r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))

write() belongs to the group of Unix unbuffered file I/O functions (together with openclosereadlseek...).

From FILE I/O:
They are part of the POSIX standard for UNIX programming, not part of ANSI C. Unlike the standard I/O routines provided by ANSI C (such as fscanf and fprintf which store the data they read in buffers) these functions are unbuffered I/O. They invoke a system call in the kernel, and will be called by the standard ANSI C function calls in the UNIX environment.

With buffering:

f, err := os.Create("/tmp/test.txt")
if err != nil {
defer f.Close()
w := bufio.NewWriter(f)
w.WriteString("some text!\n")

Wednesday 15 July 2020

Introduction to JSON

JSON (JavaScript Object Notation) is:
  • lightweight data-interchange format
  • open standard file format
  • easy for humans to read and write
  • easy for machines to parse and generate
  • uses human-readable text to store and transmit data objects


Valid JSON: array of objects:

"a": 1
"b": 2

Valid JSON: array of arrays where each array has a single element:

"a": {}
"b": {}

How to represent an array of integers?

JSON for List of int

    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [

JSON (object) vs JSON string

JSON object is an instance of the data type (e.g. Object in JavaScript) which represents a JSON (structure) and which can be initialised with a JSON literal:

var jsonObject = { "prop": "val" };

JSON string is a string:

var jsonString = '{ "prop": "val" }';

JavaScript provides methods for converting JSON Object to string:

JSON.stringify to convert objects into JSON string.
JSON.parse to convert JSON string back into an object.

Friday 10 July 2020

Using ESLint

ESLint is one of most popular linters for JavaScript and TypeScript (via typescript-eslint).

To use, we need to install it first. It can be installed locally (per project) or globally. To install it globally:

$ npm install -g eslint

We can verify that package is installed:

$ npm -g list  | grep eslint
├─┬ eslint@7.4.0
│ ├─┬ eslint-scope@5.1.0
│ ├─┬ eslint-utils@2.1.0
│ │ └── eslint-visitor-keys@1.3.0 deduped
│ ├── eslint-visitor-keys@1.3.0
│ │ └── eslint-visitor-keys@1.3.0 deduped

...and also check its command line args:

$ eslint --help
eslint [options] file.js [file.js] [dir]

Basic configuration:
  --no-eslintrc                   Disable use of configuration from .eslintrc.*
  -c, --config path::String       Use this configuration, overriding .eslintrc.* config options if present
  --env [String]                  Specify environments
  --ext [String]                  Specify JavaScript file extensions
  --global [String]               Define global variables
  --parser String                 Specify the parser to be used
  --parser-options Object         Specify parser options
  --resolve-plugins-relative-to path::String  A folder where plugins should be resolved from, CWD by default

Specifying rules and plugins:
  --rulesdir [path::String]       Use additional rules from this directory
  --plugin [String]               Specify plugins
  --rule Object                   Specify rules

Fixing problems:
  --fix                           Automatically fix problems
  --fix-dry-run                   Automatically fix problems without saving the changes to the file system
  --fix-type Array                Specify the types of fixes to apply (problem, suggestion, layout)

Ignoring files:
  --ignore-path path::String      Specify path of ignore file
  --no-ignore                     Disable use of ignore files and patterns
  --ignore-pattern [String]       Pattern of files to ignore (in addition to those in .eslintignore)

Using stdin:
  --stdin                         Lint code provided on <STDIN> - default: false
  --stdin-filename String         Specify filename to process STDIN as

Handling warnings:
  --quiet                         Report errors only - default: false
  --max-warnings Int              Number of warnings to trigger nonzero exit code - default: -1

  -o, --output-file path::String  Specify file to write report to
  -f, --format String             Use a specific output format - default: stylish
  --color, --no-color             Force enabling/disabling of color

Inline configuration comments:
  --no-inline-config              Prevent comments from changing config or rules
  --report-unused-disable-directives  Adds reported errors for unused eslint-disable directives

  --cache                         Only check changed files - default: false
  --cache-file path::String       Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
  --cache-location path::String   Path to the cache file or directory

  --init                          Run config initialization wizard - default: false
  --env-info                      Output execution environment information - default: false
  --no-error-on-unmatched-pattern  Prevent errors when pattern is unmatched
  --debug                         Output debugging information
  -h, --help                      Show help
  -v, --version                   Output the version number
  --print-config path::String     Print the configuration for the given file

To initialise and configure ESLint launch configuration wizard:

$ eslint --init

ESLint configuration will be saved in file .eslintrc.json (if you opt json file to be used). Example content:


    "env": {
        "browser": true,
        "es2020": true
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 11
    "rules": {
        "indent": [
        "quotes": [
        "semi": [

If you use VS Code, you can install ESLint plugin which will pick up this configuration and automatically lint your code and show warnings and error son the go.

ESLint should be added to Node project as a dev dependency.

package.json (created by $npm init):

  "devDependencies": {
    "eslint": "^7.4.0"

It is also possible to run this linter from the terminal. For example, to lint all files in the current project recursively with respect to .eslintrc.json:

$eslint .

  2:32009  error  Strings must use singlequote                                               quotes
  3:23     error  Strings must use singlequote                                               quotes
  3:42     error  Missing semicolon                                                          semi
  3:43     error  Strings must use singlequote                                               quotes
  3:70     error  Strings must use singlequote                                               quotes
  3:166    error  Strings must use singlequote                                               quotes
  3:207    error  Strings must use singlequote                                               quotes
  3:280    error  Strings must use singlequote                                               quotes
  3:338    error  Missing semicolon                                                          semi
  3:460    error  Missing semicolon                                                          semi
  3:555    error  Missing semicolon                                                          semi
  4:22578  error  Missing semicolon                                                          semi
  4:22601  error  Missing semicolon                                                          semi

✖ 11436 problems (11436 errors, 0 warnings)

To ignore rules in .eslintrc.json and run the linter only for JavaScript files and only to check one particular rule:

/my-project$ eslint . --ext .js --no-eslintrc --rule 'indent: ["error", 4, { "SwitchCase": 1 }]'

   28:1  error  Expected indentation of 12 spaces but found 16  indent
   46:1  error  Expected indentation of 12 spaces but found 16  indent
  186:1  error  Expected indentation of 4 spaces but found 8    indent
  187:1  error  Expected indentation of 4 spaces but found 8    indent
  188:1  error  Expected indentation of 4 spaces but found 8    indent
  189:1  error  Expected indentation of 4 spaces but found 8    indent

Rules used here was indent.


Image processing on Linux

mogrify is a part of ImageMagick package which enables processing a set of input images (instead of a single one).

Resizing JPG images

If image is e.g. 4608px wide and we want to make it 2 times smaller (maintaining the aspect ratio) we can do:

# assume all .jpg images are in current directory
$ mkdir output
$ mogrify -path ./output -resize 2304  *.jpg


$ mogrify -path ./output -resize 50%  *.jpg

Converting JPG images to PNG

$ mkdir output_png
$ mogrify -path ./output_png -format png  *.jpg

mogrify - full list of arguments and options

$ mogrify
Version: ImageMagick 6.9.7-4 Q16 x86_64 20170114
Copyright: © 1999-2017 ImageMagick Studio LLC
Features: Cipher DPC Modules OpenMP 
Delegates (built-in): bzlib djvu fftw fontconfig freetype jbig jng jpeg lcms lqr ltdl lzma openexr pangocairo png tiff wmf x xml zlib
Usage: mogrify-im6.q16 [options ...] file [ [options ...] file ...]

Image Settings:
  -adjoin              join images into a single multi-image file
  -affine matrix       affine transform matrix
  -alpha option        activate, deactivate, reset, or set the alpha channel
  -antialias           remove pixel-aliasing
  -authenticate password
                       decipher image with this password
  -attenuate value     lessen (or intensify) when adding noise to an image
  -background color    background color
  -bias value          add bias when convolving an image
                       use black point compensation
  -blue-primary point  chromaticity blue primary point
  -bordercolor color   border color
  -caption string      assign a caption to an image
  -cdl filename        color correct with a color decision list
  -channel type        apply option to select image channels
  -colors value        preferred number of colors in the image
  -colorspace type     alternate image colorspace
  -comment string      annotate image with comment
  -compose operator    set image composite operator
  -compress type       type of pixel compression when writing the image
  -decipher filename   convert cipher pixels to plain pixels
  -define format:option
                       define one or more image format options
  -delay value         display the next image after pausing
  -density geometry    horizontal and vertical density of the image
  -depth value         image depth
  -direction type      render text right-to-left or left-to-right
  -display server      get image or font from this X server
  -dispose method      layer disposal method
  -dither method       apply error diffusion to image
  -encipher filename   convert plain pixels to cipher pixels
  -encoding type       text encoding type
  -endian type         endianness (MSB or LSB) of the image
  -family name         render text with this font family
  -features distance   analyze image features (e.g. contrast, correlation)
  -fill color          color to use when filling a graphic primitive
  -filter type         use this filter when resizing an image
  -flatten             flatten a sequence of images
  -font name           render text with this font
  -format "string"     output formatted image characteristics
  -function name       apply a function to the image
  -fuzz distance       colors within this distance are considered equal
  -gravity type        horizontal and vertical text placement
  -green-primary point chromaticity green primary point
  -intensity method    method to generate intensity value from pixel
  -intent type         type of rendering intent when managing the image color
  -interlace type      type of image interlacing scheme
  -interline-spacing value
                       set the space between two text lines
  -interpolate method  pixel color interpolation method
  -interword-spacing value
                       set the space between two words
  -kerning value       set the space between two letters
  -label string        assign a label to an image
  -limit type value    pixel cache resource limit
  -loop iterations     add Netscape loop extension to your GIF animation
  -mask filename       associate a mask with the image
  -matte               store matte channel if the image has one
  -mattecolor color    frame color
  -monitor             monitor progress
  -morphology method kernel
                       apply a morphology method to the image
  -orient type         image orientation
  -page geometry       size and location of an image canvas (setting)
  -path path           write images to this path on disk
  -ping                efficiently determine image attributes
  -pointsize value     font point size
  -precision value     maximum number of significant digits to print
  -preview type        image preview type
  -quality value       JPEG/MIFF/PNG compression level
  -quiet               suppress all warning messages
  -red-primary point   chromaticity red primary point
  -regard-warnings     pay attention to warning messages
  -remap filename      transform image colors to match this set of colors
  -respect-parentheses settings remain in effect until parenthesis boundary
  -sampling-factor geometry
                       horizontal and vertical sampling factor
  -scene value         image scene number
  -seed value          seed a new sequence of pseudo-random numbers
  -size geometry       width and height of image
  -stretch type        render text with this font stretch
  -stroke color        graphic primitive stroke color
  -strokewidth value   graphic primitive stroke width
  -style type          render text with this font style
  -synchronize         synchronize image to storage device
  -taint               declare the image as modified
  -texture filename    name of texture to tile onto the image background
  -tile-offset geometry
                       tile offset
  -treedepth value     color tree depth
  -transparent-color color
                       transparent color
  -undercolor color    annotation bounding box color
  -units type          the units of image resolution
  -verbose             print detailed information about the image
  -view                FlashPix viewing transforms
  -virtual-pixel method
                       virtual pixel access method
  -weight type         render text with this font weight
  -white-point point   chromaticity white point

Image Operators:
  -adaptive-blur geometry
                       adaptively blur pixels; decrease effect near edges
  -adaptive-resize geometry
                       adaptively resize image using 'mesh' interpolation
  -adaptive-sharpen geometry
                       adaptively sharpen pixels; increase effect near edges
  -alpha option        on, activate, off, deactivate, set, opaque, copy
                       transparent, extract, background, or shape
  -annotate geometry text
                       annotate the image with text
  -auto-gamma          automagically adjust gamma level of image
  -auto-level          automagically adjust color levels of image
  -auto-orient         automagically orient (rotate) image
  -bench iterations    measure performance
  -black-threshold value
                       force all pixels below the threshold into black
  -blue-shift          simulate a scene at nighttime in the moonlight
  -blur geometry       reduce image noise and reduce detail levels
  -border geometry     surround image with a border of color
  -bordercolor color   border color
  -brightness-contrast geometry
                       improve brightness / contrast of the image
  -canny geometry      detect edges in the image
  -cdl filename        color correct with a color decision list
  -charcoal radius     simulate a charcoal drawing
  -chop geometry       remove pixels from the image interior
  -clamp               keep pixel values in range (0-QuantumRange)
  -clip                clip along the first path from the 8BIM profile
  -clip-mask filename  associate a clip mask with the image
  -clip-path id        clip along a named path from the 8BIM profile
  -colorize value      colorize the image with the fill color
  -color-matrix matrix apply color correction to the image
  -connected-components connectivity
                       connected-components uniquely labeled
  -contrast            enhance or reduce the image contrast
  -contrast-stretch geometry
                       improve contrast by `stretching' the intensity range
  -convolve coefficients
                       apply a convolution kernel to the image
  -cycle amount        cycle the image colormap
  -decipher filename   convert cipher pixels to plain pixels
  -deskew threshold    straighten an image
  -despeckle           reduce the speckles within an image
  -distort method args
                       distort images according to given method ad args
  -draw string         annotate the image with a graphic primitive
  -edge radius         apply a filter to detect edges in the image
  -encipher filename   convert plain pixels to cipher pixels
  -emboss radius       emboss an image
  -enhance             apply a digital filter to enhance a noisy image
  -equalize            perform histogram equalization to an image
  -evaluate operator value
                       evaluate an arithmetic, relational, or logical expression
  -extent geometry     set the image size
  -extract geometry    extract area from image
  -hough-lines geometry
                       identify lines in the image
  -features distance   analyze image features (e.g. contrast, correlation)
  -fft                 implements the discrete Fourier transform (DFT)
  -flip                flip image vertically
  -floodfill geometry color
                       floodfill the image with color
  -flop                flop image horizontally
  -frame geometry      surround image with an ornamental border
  -function name parameters
                       apply function over image values
  -gamma value         level of gamma correction
  -gaussian-blur geometry
                       reduce image noise and reduce detail levels
  -geometry geometry   preferred size or location of the image
  -grayscale method    convert image to grayscale
  -help                print program options
  -identify            identify the format and characteristics of the image
  -ift                 implements the inverse discrete Fourier transform (DFT)
  -implode amount      implode image pixels about the center
  -kuwahara geometry   edge preserving noise reduction filter
  -lat geometry        local adaptive thresholding
  -layers method       optimize, merge,  or compare image layers
  -level value         adjust the level of image contrast
  -level-colors color,color
                       level image with the given colors
  -linear-stretch geometry
                       improve contrast by `stretching with saturation'
  -liquid-rescale geometry
                       rescale image with seam-carving
  -local-contrast geometry
                       enhance local contrast
  -magnify             double the size of the image with pixel art scaling
  -mean-shift geometry delineate arbitrarily shaped clusters in the image
  -median geometry     apply a median filter to the image
  -mode geometry       make each pixel the 'predominant color' of the
  -modulate value      vary the brightness, saturation, and hue
  -monochrome          transform image to black and white
  -morphology method kernel
                       apply a morphology method to the image
  -motion-blur geometry
                       simulate motion blur
  -negate              replace every pixel with its complementary color 
  -noise geometry      add or reduce noise in an image
  -normalize           transform image to span the full range of colors
  -opaque color        change this color to the fill color
  -ordered-dither NxN
                       add a noise pattern to the image with specific
  -paint radius        simulate an oil painting
  -perceptible epsilon
                       pixel value less than |epsilon| become epsilon or
  -polaroid angle      simulate a Polaroid picture
  -posterize levels    reduce the image to a limited number of color levels
  -profile filename    add, delete, or apply an image profile
  -quantize colorspace reduce colors in this colorspace
  -radial-blur angle   radial blur the image
  -raise value         lighten/darken image edges to create a 3-D effect
  -random-threshold low,high
                       random threshold the image
  -region geometry     apply options to a portion of the image
  -render              render vector graphics
  -repage geometry     size and location of an image canvas
  -resample geometry   change the resolution of an image
  -resize geometry     resize the image
  -roll geometry       roll an image vertically or horizontally
  -rotate degrees      apply Paeth rotation to the image
  -sample geometry     scale image with pixel sampling
  -scale geometry      scale the image
  -segment values      segment an image
  -selective-blur geometry
                       selectively blur pixels within a contrast threshold
  -sepia-tone threshold
                       simulate a sepia-toned photo
  -set property value  set an image property
  -shade degrees       shade the image using a distant light source
  -shadow geometry     simulate an image shadow
  -sharpen geometry    sharpen the image
  -shave geometry      shave pixels from the image edges
  -shear geometry      slide one edge of the image along the X or Y axis
  -sigmoidal-contrast geometry
                       increase the contrast without saturating highlights or
  -sketch geometry     simulate a pencil sketch
  -solarize threshold  negate all pixels above the threshold level
  -sparse-color method args
                       fill in a image based on a few color points
  -splice geometry     splice the background color into the image
  -spread radius       displace image pixels by a random amount
  -statistic type radius
                       replace each pixel with corresponding statistic from the neighborhood
  -strip               strip image of all profiles and comments
  -swirl degrees       swirl image pixels about the center
  -threshold value     threshold the image
  -thumbnail geometry  create a thumbnail of the image
  -tile filename       tile image when filling a graphic primitive
  -tint value          tint the image with the fill color
  -transform           affine transform image
  -transparent color   make this color transparent within the image
  -transpose           flip image vertically and rotate 90 degrees
  -transverse          flop image horizontally and rotate 270 degrees
  -trim                trim image edges
  -type type           image type
  -unique-colors       discard all but one of any pixel color
  -unsharp geometry    sharpen the image
  -vignette geometry   soften the edges of the image in vignette style
  -wave geometry       alter an image along a sine wave
  -wavelet-denoise threshold
                       removes noise from the image using a wavelet transform
  -white-threshold value
                       force all pixels above the threshold into white

Image Sequence Operators:
  -affinity filename   transform image colors to match this set of colors
  -append              append an image sequence
  -clut                apply a color lookup table to the image
  -coalesce            merge a sequence of images
  -combine             combine a sequence of images
  -compare             mathematically and visually annotate the difference between an image and its reconstruction
  -complex operator    perform complex mathematics on an image sequence
  -composite           composite image
  -copy geometry offset
                       copy pixels from one area of an image to another
  -crop geometry       cut out a rectangular region of the image
  -deconstruct         break down an image sequence into constituent parts
  -evaluate-sequence operator
                       evaluate an arithmetic, relational, or logical expression
  -flatten             flatten a sequence of images
  -fx expression       apply mathematical expression to an image channel(s)
  -hald-clut           apply a Hald color lookup table to the image
  -layers method       optimize, merge, or compare image layers
  -morph value         morph an image sequence
  -mosaic              create a mosaic from an image sequence
  -poly terms          build a polynomial from the image sequence and the corresponding
                       terms (coefficients and degree pairs).
  -print string        interpret string and print to console
  -process arguments   process the image with a custom image filter
  -separate            separate an image channel into a grayscale image
  -smush geometry      smush an image sequence together
  -write filename      write images to this file

Image Stack Operators:
  -delete indexes      delete the image from the image sequence
  -duplicate count,indexes
                       duplicate an image one or more times
  -insert index        insert last image into the image sequence
  -reverse             reverse image sequence
  -swap indexes        swap two images in the image sequence

Miscellaneous Options:
  -debug events        display copious debugging information
  -distribute-cache port
                       distributed pixel cache spanning one or more servers
  -help                print program options
  -list type           print a list of supported option arguments
  -log format          format of debugging information
  -version             print version information

By default, the image format of `file' is determined by its magic
number.  To specify a particular image format, precede the filename
with an image format name and a colon (i.e. ps:image) or specify the
image type as the filename suffix (i.e.  Specify 'file' as
'-' for standard input or output.