From 52cb3e8bafd88157e4cc13248fb5978a2e3bbbf2 Mon Sep 17 00:00:00 2001 From: Igor Chubin Date: Mon, 8 May 2017 20:27:00 +0000 Subject: [PATCH] added initial cheat sheets --- sheets/aspell | 8 ++++ sheets/aws | 38 +++++++++++++++ sheets/azure | 22 +++++++++ sheets/btrfs | 55 ++++++++++++++++++++++ sheets/bzr | 13 ++++++ sheets/curl | 44 ++++++++++++++++++ sheets/dict | 8 ++++ sheets/dmesg | 12 +++++ sheets/extundelete | 14 ++++++ sheets/fdisk | 8 ++++ sheets/go/Arrays | 12 +++++ sheets/go/Axioms | 26 +++++++++++ sheets/go/Channels | 36 ++++++++++++++ sheets/go/Declarations | 7 +++ sheets/go/Embedding | 23 +++++++++ sheets/go/Errors | 19 ++++++++ sheets/go/Interfaces | 13 ++++++ sheets/go/Maps | 16 +++++++ sheets/go/Operators | 40 ++++++++++++++++ sheets/go/Pointers | 7 +++ sheets/go/Structs | 38 +++++++++++++++ sheets/go/for | 9 ++++ sheets/go/func | 84 +++++++++++++++++++++++++++++++++ sheets/go/go | 16 +++++++ sheets/go/hello | 11 +++++ sheets/go/http | 25 ++++++++++ sheets/go/if | 23 +++++++++ sheets/go/packages | 8 ++++ sheets/go/print | 12 +++++ sheets/go/range | 20 ++++++++ sheets/go/slices | 19 ++++++++ sheets/go/switch | 27 +++++++++++ sheets/go/types | 29 ++++++++++++ sheets/ioreg | 3 ++ sheets/lvcreate | 21 +++++++++ sheets/masscan | 5 ++ sheets/mutt | 80 ++++++++++++++++++++++++++++++++ sheets/parted | 9 ++++ sheets/pygmentize | 6 +++ sheets/redis-cli | 23 +++++++++ sheets/rip | 5 ++ sheets/rust/Basics | 85 ++++++++++++++++++++++++++++++++++ sheets/rust/ControlFlow | 36 ++++++++++++++ sheets/rust/PatternMatching | 20 ++++++++ sheets/rust/Pointers | 33 +++++++++++++ sheets/rust/Types | 68 +++++++++++++++++++++++++++ sheets/rust/hello | 7 +++ sheets/scala/:main | 4 ++ sheets/scala/ControlStructures | 54 +++++++++++++++++++++ sheets/scala/DataStructures | 29 ++++++++++++ sheets/scala/Functions | 71 ++++++++++++++++++++++++++++ sheets/scala/ObjectOrientation | 76 ++++++++++++++++++++++++++++++ sheets/scala/Packages | 18 +++++++ sheets/scala/PatternMatching | 29 ++++++++++++ sheets/scala/Variables | 11 +++++ sheets/scala/hello | 9 ++++ sheets/sgdisk | 26 +++++++++++ sheets/xkb | 3 ++ sheets/xm | 82 ++++++++++++++++++++++++++++++++ sheets/xscreensaver | 2 + 60 files changed, 1557 insertions(+) create mode 100644 sheets/aspell create mode 100644 sheets/aws create mode 100644 sheets/azure create mode 100644 sheets/btrfs create mode 100644 sheets/bzr create mode 100644 sheets/curl create mode 100644 sheets/dict create mode 100644 sheets/dmesg create mode 100644 sheets/extundelete create mode 100644 sheets/fdisk create mode 100644 sheets/go/Arrays create mode 100644 sheets/go/Axioms create mode 100644 sheets/go/Channels create mode 100644 sheets/go/Declarations create mode 100644 sheets/go/Embedding create mode 100644 sheets/go/Errors create mode 100644 sheets/go/Interfaces create mode 100644 sheets/go/Maps create mode 100644 sheets/go/Operators create mode 100644 sheets/go/Pointers create mode 100644 sheets/go/Structs create mode 100644 sheets/go/for create mode 100644 sheets/go/func create mode 100644 sheets/go/go create mode 100644 sheets/go/hello create mode 100644 sheets/go/http create mode 100644 sheets/go/if create mode 100644 sheets/go/packages create mode 100644 sheets/go/print create mode 100644 sheets/go/range create mode 100644 sheets/go/slices create mode 100644 sheets/go/switch create mode 100644 sheets/go/types create mode 100644 sheets/ioreg create mode 100644 sheets/lvcreate create mode 100644 sheets/masscan create mode 100644 sheets/mutt create mode 100644 sheets/parted create mode 100644 sheets/pygmentize create mode 100644 sheets/redis-cli create mode 100644 sheets/rip create mode 100644 sheets/rust/Basics create mode 100644 sheets/rust/ControlFlow create mode 100644 sheets/rust/PatternMatching create mode 100644 sheets/rust/Pointers create mode 100644 sheets/rust/Types create mode 100644 sheets/rust/hello create mode 100644 sheets/scala/:main create mode 100644 sheets/scala/ControlStructures create mode 100644 sheets/scala/DataStructures create mode 100644 sheets/scala/Functions create mode 100644 sheets/scala/ObjectOrientation create mode 100644 sheets/scala/Packages create mode 100644 sheets/scala/PatternMatching create mode 100644 sheets/scala/Variables create mode 100644 sheets/scala/hello create mode 100644 sheets/sgdisk create mode 100644 sheets/xkb create mode 100644 sheets/xm create mode 100644 sheets/xscreensaver diff --git a/sheets/aspell b/sheets/aspell new file mode 100644 index 0000000..41169d6 --- /dev/null +++ b/sheets/aspell @@ -0,0 +1,8 @@ +# spell check a single file +aspell check ${somefile} + +# list mispelled words from standard input +cat ${somefile} | aspell list + +# check for known dictionary files +spell dicts diff --git a/sheets/aws b/sheets/aws new file mode 100644 index 0000000..6bd32dd --- /dev/null +++ b/sheets/aws @@ -0,0 +1,38 @@ +# install aws cli +pip install awscli + +# configure AWS CLI +aws configure + +# describe instances in the current account +aws ec2 describe-instances --instance-ids i-01234567 + +# list public IP addresses of instances +aws ec2 describe-instances \ + --query "Reservations[*].Instances[*].PublicIpAddress" \ + --output=text + +# start instance with the specified id +aws ec2 start-instances --instance-ids i-12345678c + +# copy directory to S3 +aws s3 cp ${directory} s3://${bucket}/${directory} --recursive + +# sync directory with S3 +aws s3 sync ${directory} s3://${bucket}/${directory} --exclude *.tmp + +# list s3 buckets +aws s3 ls + +# remove s3 bucket +aws s3 rb --force s3://${bucket_name} + +# get bucket logging +aws s3api get-bucket-logging --bucket ${bucket_name} + +# AWS cloudformation list stacks +aws cloudformation list-stacks \ + --stack-status-filter [ CREATE_COMPLETE | UPDATE_COMPLETE | etc.. ] + +# other useful commands: +# https://github.com/toddm92/aws/wiki/AWS-CLI-Cheat-Sheet diff --git a/sheets/azure b/sheets/azure new file mode 100644 index 0000000..795c4f8 --- /dev/null +++ b/sheets/azure @@ -0,0 +1,22 @@ +# install azure-cli +sudo apt-get install nodejs-legacy +sudo apt-get install npm +sudo npm install -g azure-cli + +# This will output an url and a device code for you to use browser to login +azure login + +# This will prompt for your password in the console +azure login -u + +# This will login in using a service principal +azure login -u "" -p "" --service-principal --tenant "" + +# List VMs disks +azure vm disk list + +# Remove all disks of VMs labeled with LABEL +for disk in $(azure vm disk list | grep LABEL | awk '{print $2}') +do + azure vm disk delete --blob-delete "$disk" +done diff --git a/sheets/btrfs b/sheets/btrfs new file mode 100644 index 0000000..b5dfae2 --- /dev/null +++ b/sheets/btrfs @@ -0,0 +1,55 @@ +# Create a btrfs file system on /dev/sdb, /dev/sdc, and /dev/sdd +mkfs.btrfs /dev/sdb /dev/sdc /dev/sdd + +# btrfs with just one hard drive, metadata not redundant +# (this is danegerous: if your metadata is lost, your data is lost as well) +mkfs.btrfs -m single /dev/sdb + +# data to be redundant and metadata to be non-redundant: +mkfs.btrfs -m raid0 -d raid1 /dev/sdb /dev/sdc /dev/sdd + +# both data and metadata to be redundan +mkfs.btrfs -d raid1 /dev/sdb /dev/sdc /dev/sdd + +# To get a list of all btrfs file systems +btrfs filesystem show + +# detailed df for a fileesystem (mounted in /mnt) +btrfs filesystem df /mnt + +# resize btrfs online (-2g decreases, +2g increases) +btrfs filesystem resize -2g /mnt + +# use maximum space +btrfs filesystem resize max /mnt + +# add new device to a filesystem +btrfs device add /dev/sdf /mnt + +# remove devices from a filesystem +btrfs device delete missing /mnt + +# create the subvolume /mnt/sv1 in the /mnt volume +btrfs subvolume create /mnt/sv1 + +# list subvolumes +btrfs subvolume list /mnt + +# mount subvolume without mounting the main filesystem +mount -o subvol=sv1 /dev/sdb /mnt + +# delete subvolume +btrfs subvolume delete /mnt/sv1 + +# taking snapshot of a subvolume +btrfs subvolume snapshot /mnt/sv1 /mnt/sv1_snapshot + +# taking snapshot of a file (copy file by reference) +cp --reflink /mnt/sv1/test1 /mnt/sv1/test3 + +# convert ext3/ext4 to btrfs +btrfs-convert /dev/sdb1 + +# convert btrfs to ext3/ext4 +btrfs-convert -r /dev/sdb1 + diff --git a/sheets/bzr b/sheets/bzr new file mode 100644 index 0000000..a980773 --- /dev/null +++ b/sheets/bzr @@ -0,0 +1,13 @@ +# Install bazaar fastimport plugin +cd ~/.bazaar/plugins +bzr branch lp:bzr-fastimport fastimport +# you can do it manually: +# pip install +# python setup.py build_ext -i +# mv ... ~/.bazaar/plugins +# probably you will need this patch: +# https://launchpadlibrarian.net/174264005/fix-1314771.debdiff + +# How to migrate from Bazaar to git: +git init +bzr fast-export --plain . | git fast-import diff --git a/sheets/curl b/sheets/curl new file mode 100644 index 0000000..d702cc3 --- /dev/null +++ b/sheets/curl @@ -0,0 +1,44 @@ +# Download a single file +curl http://path.to.the/file + +# Download a file and specify a new filename +curl http://example.com/file.zip -o new_file.zip + +# Download multiple files +curl -O URLOfFirstFile -O URLOfSecondFile + +# Download all sequentially numbered files (1-24) +curl http://example.com/pic[1-24].jpg + +# Download a file and pass HTTP Authentication +curl -u username:password URL + +# Download a file with a Proxy +curl -x proxysever.server.com:PORT http://addressiwantto.access + +# Download a file from FTP +curl -u username:password -O ftp://example.com/pub/file.zip + +# Get an FTP directory listing +curl ftp://username:password@example.com + +# Resume a previously failed download +curl -C - -o partial_file.zip http://example.com/file.zip + +# Fetch only the HTTP headers from a response +curl -I http://example.com + +# Fetch your external IP and network info as JSON +curl http://ifconfig.me/all/json + +# Limit the rate of a download +curl --limit-rate 1000B -O http://path.to.the/file + +# POST to a form +curl -X POST -F "name=user" -F "password=test" http://example.com + +# POST JSON Data +curl -H "Content-Type: application/json" -X POST -d '{"user":"bob","pass":"123"}' http://example.com + +# POST data from the standard in / share data on sprunge.us +curl -F 'sprunge=<-' sprunge.us diff --git a/sheets/dict b/sheets/dict new file mode 100644 index 0000000..dc93f84 --- /dev/null +++ b/sheets/dict @@ -0,0 +1,8 @@ +# A list of all the available dictionaries can be queried by executing +dict -I + +# translate "understand" to dutch +dict -d fd-eng-nld understand + +# show available dict databases +dict -D diff --git a/sheets/dmesg b/sheets/dmesg new file mode 100644 index 0000000..94a2527 --- /dev/null +++ b/sheets/dmesg @@ -0,0 +1,12 @@ +# Clear dmesg Buffer Logs +dmesg -c + +# Display the local time and the delta in human-readable format. Conversion to the local time could be inaccurate +dmesg -e + +# Print human-readable timestamps. +dmesg -T + +# Human-readable output (color + reltime) +dmesg -H + diff --git a/sheets/extundelete b/sheets/extundelete new file mode 100644 index 0000000..b74d3a9 --- /dev/null +++ b/sheets/extundelete @@ -0,0 +1,14 @@ +# to recover a file in /home/SomeUserName/, assuming /home is on its own partition, run: +extundelete /dev/sda4 --restore-file SomeUserName/SomeDirectory + +# Recover an entire directory +extundelete /dev/sda4 --restore-directory SomeUserName/SomeDirectory + +# For advanced users, to manually recover blocks or inodes with extundelete, +# debugfs can be used to find the inode to be recovered; +# Additional inodes to recover can be listed in an unspaced, comma-separated fashion. +extundelete --restore-inode inode + +# recover all deleted files from an entire partition +extundelete /dev/sda4 --restore-all + diff --git a/sheets/fdisk b/sheets/fdisk new file mode 100644 index 0000000..de31284 --- /dev/null +++ b/sheets/fdisk @@ -0,0 +1,8 @@ +# list partitions +fdisk -l /dev/sda + +# delete a partition +fdisk /dev/sda +Command (m for help): d +Partition number (1-9): XXX + diff --git a/sheets/go/Arrays b/sheets/go/Arrays new file mode 100644 index 0000000..2de7ad9 --- /dev/null +++ b/sheets/go/Arrays @@ -0,0 +1,12 @@ +// gives you the length of an array/a slice +// It's a built-in function, not a attribute/method on the array. +len(a) + +var a [10]int // declare an int array with length 10. Array length is part of the type! +a[3] = 42 // set elements +i := a[3] // read elements + +// declare and initialize +var a = [2]int{1, 2} +a := [2]int{1, 2} //shorthand +a := [...]int{1, 2} // elipsis -> Compiler figures out array length diff --git a/sheets/go/Axioms b/sheets/go/Axioms new file mode 100644 index 0000000..26e9933 --- /dev/null +++ b/sheets/go/Axioms @@ -0,0 +1,26 @@ +// - A send to a nil channel blocks forever +var c chan string +c <- "Hello, World!" +// fatal error: all goroutines are asleep - deadlock! + +// - A receive from a nil channel blocks forever +var c chan string +fmt.Println(<-c) +// fatal error: all goroutines are asleep - deadlock! + +// - A send to a closed channel panics +var c = make(chan string, 1) +c <- "Hello, World!" +close(c) +c <- "Hello, Panic!" +// panic: send on closed channel + +// - A receive from a closed channel returns the zero value immediately +var c = make(chan int, 2) +c <- 1 +c <- 2 +close(c) +for i := 0; i < 3; i++ { + fmt.Printf("%d ", <-c) +} +// 1 2 0 diff --git a/sheets/go/Channels b/sheets/go/Channels new file mode 100644 index 0000000..99cebd5 --- /dev/null +++ b/sheets/go/Channels @@ -0,0 +1,36 @@ +ch := make(chan int) // create a channel of type int +ch <- 42 // Send a value to the channel ch. +v := <-ch // Receive a value from ch + +// Create a buffered channel. +// Writing to a buffered channels does not block +// if less than unread values have been written. +ch := make(chan int, 100) +// Non-buffered channels block. +// Read blocks when no value is available, +// write blocks if a value already has been written but not read. + +close(ch) // closes the channel (only sender should close) + +// read from channel and test if it has been closed +v, ok := <-ch +// if ok is false, channel has been closed + +// Read from channel until it is closed +for i := range ch { + fmt.Println(i) +} + +// select blocks on multiple channel operations, +// if one unblocks, the corresponding case is executed +func doStuff(channelOut, channelIn chan int) { + select { + case channelOut <- 42: + fmt.Println("We could write to channelOut!") + case x := <- channelIn: + fmt.Println("We could read from channelIn") + case <-time.After(time.Second * 1): + fmt.Println("timeout") + } +} + diff --git a/sheets/go/Declarations b/sheets/go/Declarations new file mode 100644 index 0000000..b700864 --- /dev/null +++ b/sheets/go/Declarations @@ -0,0 +1,7 @@ +// Type goes after identifier! +var foo int // declaration without initialization +var foo int = 42 // declaration with initialization +var foo, bar int = 42, 1302 // declare and init multiple vars at once +var foo = 42 // type omitted, will be inferred +foo := 42 // shorthand, only in func bodies, omit var keyword, type is always implicit +const constant = "This is a constant" diff --git a/sheets/go/Embedding b/sheets/go/Embedding new file mode 100644 index 0000000..08fa4c2 --- /dev/null +++ b/sheets/go/Embedding @@ -0,0 +1,23 @@ +// There is no subclassing in Go. Instead, there is interface and struct embedding. + +// ReadWriter implementations must satisfy both Reader and Writer +type ReadWriter interface { + Reader + Writer +} + +// Server exposes all the methods that Logger has +type Server struct { + Host string + Port int + *log.Logger +} + +// initialize the embedded type the usual way +server := &Server{"localhost", 80, log.New(...)} + +// methods implemented on the embedded struct are passed through +server.Log(...) // calls server.Logger.Log(...) + +// the field name of the embedded type is its type name (in this case Logger) +var logger *log.Logger = server.Logger diff --git a/sheets/go/Errors b/sheets/go/Errors new file mode 100644 index 0000000..f4fd189 --- /dev/null +++ b/sheets/go/Errors @@ -0,0 +1,19 @@ +// There is no exception handling. +// Functions that might produce an error just declare an additional return value of type `Error`. +// This is the `Error` interface: +type error interface { + Error() string +} +// +// A function that might return an error: +func doStuff() (int, error) { +} +// +func main() { + result, error := doStuff() + if (error != nil) { + // handle error + } else { + // all is good, use result + } +} diff --git a/sheets/go/Interfaces b/sheets/go/Interfaces new file mode 100644 index 0000000..b6c2458 --- /dev/null +++ b/sheets/go/Interfaces @@ -0,0 +1,13 @@ +// interface declaration +type Awesomizer interface { + Awesomize() string +} +// +// types do *not* declare to implement interfaces +type Foo struct {} +// +// instead, types implicitly satisfy an interface +// if they implement all required methods +func (foo Foo) Awesomize() string { + return "Awesome!" +} diff --git a/sheets/go/Maps b/sheets/go/Maps new file mode 100644 index 0000000..a3eea9e --- /dev/null +++ b/sheets/go/Maps @@ -0,0 +1,16 @@ +var m map[string]int +m = make(map[string]int) +m["key"] = 42 +fmt.Println(m["key"]) + +// delete key from a map +delete(m, "key") + +// test if key "key" is present and retrieve it, if so +elem, ok := m["key"] + +// map literal +var m = map[string]Vertex{ + "Bell Labs": {40.68433, -74.39967}, + "Google": {37.42202, -122.08408}, +} diff --git a/sheets/go/Operators b/sheets/go/Operators new file mode 100644 index 0000000..017b23d --- /dev/null +++ b/sheets/go/Operators @@ -0,0 +1,40 @@ +// ### Arithmetic +// |Operator|Description| +// |--------|-----------| +// |`+` |addition | +// |`-` |subtraction| +// |`*` |multiplication| +// |`/` |quotient | +// |`%` |remainder | +// |`&` |bitwise and| +// |`|` |bitwise or | +// |`^` |bitwise xor| +// |`&^` |bit clear (and not)| +// |`<<` |left shift | +// |`>>` |right shift| +// +// ### Comparison +// |Operator|Description| +// |--------|-----------| +// |`==` |equal | +// |`!=` |not equal | +// |`<` |less than | +// |`<=` |less than or equal| +// |`>` |greater than| +// |`>=` |greater than or equal| +// +// ### Logical +// |Operator|Description| +// |--------|-----------| +// |`&&` |logical and| +// |`||` |logical or | +// |`!` |logical not| +// +// ### Other +// |Operator|Description| +// |--------|-----------| +// |`&` |address of / create pointer| +// |`*` |dereference pointer| +// |`<-` |send / receive operator (see 'Channels' below)| + + diff --git a/sheets/go/Pointers b/sheets/go/Pointers new file mode 100644 index 0000000..e6a1396 --- /dev/null +++ b/sheets/go/Pointers @@ -0,0 +1,7 @@ +p := Vertex{1, 2} // p is a Vertex +q := &p // q is a pointer to a Vertex +r := &Vertex{1, 2} // r is also a pointer to a Vertex + +// The type of a pointer to a Vertex is *Vertex +// new creates a pointer to a new struct instance +var s *Vertex = new(Vertex) diff --git a/sheets/go/Structs b/sheets/go/Structs new file mode 100644 index 0000000..c78cffd --- /dev/null +++ b/sheets/go/Structs @@ -0,0 +1,38 @@ +// There are no classes, only structs. Structs can have methods. +// A struct is a type. It's also a collection of fields + +// Declaration +type Vertex struct { + X, Y int +} + +// Creating +var v = Vertex{1, 2} +var v = Vertex{X: 1, Y: 2} // Creates a struct by defining values with keys +var v = []Vertex{{1,2},{5,2},{5,5}} // Initialize a slice of structs + +// Accessing members +v.X = 4 + +// You can declare methods on structs. The struct you want to declare the +// method on (the receiving type) comes between the the func keyword and +// the method name. The struct is copied on each method call(!) +func (v Vertex) Abs() float64 { + return math.Sqrt(v.X*v.X + v.Y*v.Y) +} + +// Call method +v.Abs() + +// For mutating methods, you need to use a pointer (see below) to the Struct +// as the type. With this, the struct value is not copied for the method call. +func (v *Vertex) add(n float64) { + v.X += n + v.Y += n +} + +// **Anonymous structs:** +// Cheaper and safer than using `map[string]interface{}`. +point := struct { + X, Y int +}{1, 2} diff --git a/sheets/go/for b/sheets/go/for new file mode 100644 index 0000000..98e4e8c --- /dev/null +++ b/sheets/go/for @@ -0,0 +1,9 @@ +// There's only `for`, no `while`, no `until` +for i := 1; i < 10; i++ { +} +for ; i < 10; { // while - loop +} +for i < 10 { // you can omit semicolons if there is only a condition +} +for { // you can omit the condition ~ while (true) +} diff --git a/sheets/go/func b/sheets/go/func new file mode 100644 index 0000000..afe8e41 --- /dev/null +++ b/sheets/go/func @@ -0,0 +1,84 @@ +// ### Functions +// a simple function +func functionName() {} + +// function with parameters (again, types go after identifiers) +func functionName(param1 string, param2 int) {} + +// multiple parameters of the same type +func functionName(param1, param2 int) {} + +// return type declaration +func functionName() int { + return 42 +} + +// Can return multiple values at once +func returnMulti() (int, string) { + return 42, "foobar" +} +var x, str = returnMulti() + +// Return multiple named results simply by return +func returnMulti2() (n int, s string) { + n = 42 + s = "foobar" + // n and s will be returned + return +} +var x, str = returnMulti2() + +// ### Functions As Values And Closures +func main() { + // assign a function to a name + add := func(a, b int) int { + return a + b + } + // use the name to call the function + fmt.Println(add(3, 4)) +} + +// Closures, lexically scoped: Functions can access values that were +// in scope when defining the function +func scope() func() int{ + outer_var := 2 + foo := func() int { return outer_var} + return foo +} + +func another_scope() func() int{ + // won't compile because outer_var and foo not defined in this scope + outer_var = 444 + return foo +} + + +// Closures: don't mutate outer vars, instead redefine them! +func outer() (func() int, int) { + outer_var := 2 + inner := func() int { + outer_var += 99 // attempt to mutate outer_var from outer scope + return outer_var // => 101 (but outer_var is a newly redefined + // variable visible only inside inner) + } + return inner, outer_var // => 101, 2 (outer_var is still 2, not mutated by foo!) +} + +// ### Variadic Functions +func main() { + fmt.Println(adder(1, 2, 3)) // 6 + fmt.Println(adder(9, 9)) // 18 + + nums := []int{10, 20, 30} + fmt.Println(adder(nums...)) // 60 +} +// By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters. +// The function is invoked like any other function except we can pass as many arguments as we want. +func adder(args ...int) int { + total := 0 + for _, v := range args { // Iterates over the arguments whatever the number. + total += v + } + return total +} + diff --git a/sheets/go/go b/sheets/go/go new file mode 100644 index 0000000..f71afb7 --- /dev/null +++ b/sheets/go/go @@ -0,0 +1,16 @@ +// Goroutines are lightweight threads (managed by Go, not OS threads). +// `go f(a, b)` starts a new goroutine which runs `f` (given `f` is a function). +// +// just a function (which can be later started as a goroutine) +func doStuff(s string) { +} +// +func main() { + // using a named function in a goroutine + go doStuff("foobar") + + // using an anonymous inner function in a goroutine + go func (x int) { + // function body goes here + }(42) +} diff --git a/sheets/go/hello b/sheets/go/hello new file mode 100644 index 0000000..155802b --- /dev/null +++ b/sheets/go/hello @@ -0,0 +1,11 @@ +// file: hello.go + +package main + +import "fmt" + +func main() { + fmt.Println("Hello Go") +} + +// to run: $ go run hello.go diff --git a/sheets/go/http b/sheets/go/http new file mode 100644 index 0000000..1de7a95 --- /dev/null +++ b/sheets/go/http @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "net/http" +) + +// define a type for the response +type Hello struct{} + +// let that type implement the ServeHTTP method (defined in interface http.Handler) +func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Hello!") +} + +func main() { + var h Hello + http.ListenAndServe("localhost:4000", h) +} + +// Here's the method signature of http.ServeHTTP: +// type Handler interface { +// ServeHTTP(w http.ResponseWriter, r *http.Request) +// } + diff --git a/sheets/go/if b/sheets/go/if new file mode 100644 index 0000000..3e44f02 --- /dev/null +++ b/sheets/go/if @@ -0,0 +1,23 @@ +func main() { + // Basic one + if x > 0 { + return x + } else { + return -x + } + + // You can put one statement before the condition + if a := b + c; a < 42 { + return a + } else { + return a - 42 + } + + // Type assertion inside if + var val interface{} + val = "foo" + if str, ok := val.(string); ok { + fmt.Println(str) + } +} + diff --git a/sheets/go/packages b/sheets/go/packages new file mode 100644 index 0000000..b6747a8 --- /dev/null +++ b/sheets/go/packages @@ -0,0 +1,8 @@ +// ## Packages +// * Package declaration at top of every source file +// * Executables are in package `main` +// * Convention: package name == last name of import path (import path `math/rand` => package `rand`) +// * Upper case identifier: exported (visible from other packages) +// * Lower case identifier: private (not visible from other packages) + + diff --git a/sheets/go/print b/sheets/go/print new file mode 100644 index 0000000..89d09d0 --- /dev/null +++ b/sheets/go/print @@ -0,0 +1,12 @@ +fmt.Println("Hello, 你好, नमस्ते, Привет, ᎣᏏᏲ") // basic print, plus newline +p := struct { X, Y int }{ 17, 2 } +fmt.Println( "My point:", p, "x coord=", p.X ) // print structs, ints, etc +s := fmt.Sprintln( "My point:", p, "x coord=", p.X ) // print to string variable + +fmt.Printf("%d hex:%x bin:%b fp:%f sci:%e",17,17,17,17.0,17.0) // c-ish format +s2 := fmt.Sprintf( "%d %f", 17, 17.0 ) // formatted print to string variable + +hellomsg := ` + "Hello" in Chinese is 你好 ('Ni Hao') + "Hello" in Hindi is नमस्ते ('Namaste') +` // multi-line string literal, using back-tick at beginning and end diff --git a/sheets/go/range b/sheets/go/range new file mode 100644 index 0000000..ff9d27f --- /dev/null +++ b/sheets/go/range @@ -0,0 +1,20 @@ +// loop over an array/a slice +for i, e := range a { + // i is the index, e the element +} + +// if you only need e: +for _, e := range a { + // e is the element +} + +// ...and if you only need the index +for i := range a { +} + +// In Go pre-1.4, you'll get a compiler error if you're not using i and e. +// Go 1.4 introduced a variable-free form, so that you can do this +for range time.Tick(time.Second) { + // do it once a sec +} + diff --git a/sheets/go/slices b/sheets/go/slices new file mode 100644 index 0000000..9d248f8 --- /dev/null +++ b/sheets/go/slices @@ -0,0 +1,19 @@ +var a []int // declare a slice - similar to an array, but length is unspecified +var a = []int {1, 2, 3, 4} // declare and initialize a slice (backed by the array given implicitly) +a := []int{1, 2, 3, 4} // shorthand +chars := []string{0:"a", 2:"c", 1: "b"} // ["a", "b", "c"] + +var b = a[lo:hi] // creates a slice (view of the array) from index lo to hi-1 +var b = a[1:4] // slice from index 1 to 3 +var b = a[:3] // missing low index implies 0 +var b = a[3:] // missing high index implies len(a) +a = append(a,17,3) // append items to slice a +c := append(a,b...) // concatenate slices a and b + +// create a slice with make +a = make([]byte, 5, 5) // first arg length, second capacity +a = make([]byte, 5) // capacity is optional + +// create a slice from an array +x := [3]string{"Лайка", "Белка", "Стрелка"} +s := x[:] // a slice referencing the storage of x diff --git a/sheets/go/switch b/sheets/go/switch new file mode 100644 index 0000000..f8ca78b --- /dev/null +++ b/sheets/go/switch @@ -0,0 +1,27 @@ +// switch statement +switch operatingSystem { +case "darwin": + fmt.Println("Mac OS Hipster") + // cases break automatically, no fallthrough by default +case "linux": + fmt.Println("Linux Geek") +default: + // Windows, BSD, ... + fmt.Println("Other") +} + +// as with for and if, you can have an assignment statement before the switch value +switch os := runtime.GOOS; os { +case "darwin": ... +} + +// you can also make comparisons in switch cases +number := 42 +switch { + case number < 42: + fmt.Println("Smaller") + case number == 42: + fmt.Println("Equal") + case number > 42: + fmt.Println("Greater") +} diff --git a/sheets/go/types b/sheets/go/types new file mode 100644 index 0000000..4778758 --- /dev/null +++ b/sheets/go/types @@ -0,0 +1,29 @@ +// ## Built-in Types +bool + +string + +int int8 int16 int32 int64 +uint uint8 uint16 uint32 uint64 uintptr + +byte // alias for uint8 + +rune // alias for int32 ~= a character (Unicode code point) - very Viking + +float32 float64 + +complex64 complex128 + +// ## Type Conversions + +var i int = 42 +var f float64 = float64(i) +var u uint = uint(f) + +// alternative syntax +i := 42 +f := float64(i) +u := uint(f) + + + diff --git a/sheets/ioreg b/sheets/ioreg new file mode 100644 index 0000000..a1a5fb7 --- /dev/null +++ b/sheets/ioreg @@ -0,0 +1,3 @@ +# find out the arch of the efi firmware in a Ma +ioreg -l -p IODeviceTree | grep firmware-abi + diff --git a/sheets/lvcreate b/sheets/lvcreate new file mode 100644 index 0000000..0bf8955 --- /dev/null +++ b/sheets/lvcreate @@ -0,0 +1,21 @@ +# lvcreate + +# Creates a logical volume in an existing volume group. +# A volume group is a collection of logical and physical volumes. + +# Create a logical volume of 10 gigabytes in the volume group vg1: +lvcreate -L 10G vg1 + +# Create a 1500 megabyte linear logical volume named mylv in the volume group vg1: +lvcreate -L 1500 -n mylv vg1 + +# Create a logical volume called mylv that uses 60% of the total space in volume group vg1: +lvcreate -l 60%VG -n mylv vg1 + +# Create a logical volume called mylv that uses all of the unallocated space in the volume group vg1: +lvcreate -l 100%FREE -n mylv vg1 + +# Create a snapshot (lvsnap) from a logical volume (/dev/vgA/lv1); +# snapshot size = 10G (total size of the changes) +lvcreate -L 10G -s -n lvsnap /dev/vgA/lv1 + diff --git a/sheets/masscan b/sheets/masscan new file mode 100644 index 0000000..da57820 --- /dev/null +++ b/sheets/masscan @@ -0,0 +1,5 @@ +# Usage is similar to nmap. To scan a network segment for some ports +masscan -p80,8000-8100 10.0.0.0/8 + +# scan the entire Internet excluding exclude.txt +masscan 0.0.0.0/0 -p0-65535 --excludefile exclude.txt --max-rate 100000 diff --git a/sheets/mutt b/sheets/mutt new file mode 100644 index 0000000..e4f967c --- /dev/null +++ b/sheets/mutt @@ -0,0 +1,80 @@ +# Send a mail with a subject, cc and an attachement +mutt -s "Site Backup" -a backup.tar -c user@example.com user2@example.com + +# Send a mail with a blind carbony copy (bcc) +mutt -s "hello" -b user2@example.com user@example.com + +# +# Select (tag) messages: shift+t (T) +# + = (string) + ~ (expression) +# + ~b expr (message with expr in body) + [b]body + [B]whole message + [f]rom + [c]c'ed + [C]c'ed or to + [h]eader +# + ~m from-to (range) + ~d from-to (date range) +# + ~N (new messages) + ~U (unread messages) + ~R (read messages) + ~A (all messages) + ~D (deleted messages) + ~p (message to you) + ~P (message from you) + ~= (duplicated messages) + ~$ (unref messages) +# +# Logical operators: +# + AND = ~P ~N (new messages from you) + OR = ~P | ~N (new messages of messages from you) + () = (~= ~$) | ~N +# +# +# DATES +# + DD/MM/YY + ~d 20/1/95-31/10/95 (from 20/01/95 to 31/10/95) + ~d -31/10/95 (before 31/10/95) + ~d 20/1/95- (after 20/01/95) + ~d 20/1/95 (only 20/01/95) + ~d 20/1/95*2w (two weeks around 20/01/95) + [w]eek + [d]day + [m]onth + [y]ear + can use *(around), +(after) or -(before) +# + ~d <1m (messages newer than 1 month) + ~d >1y (messages older than 1 year) + ~d =1d (exact one day) + + +# +# Keys +# + shift+d (D) : delete messages using pattern + shift+t (T) : select messages using pattern + shift+u (U) : undelete messages using pattern + ctrl+t : un-selected messages using pattern +# +# + d : delete message + N : mark as new + C : copy message to another folder(mailbox) + o, O : change sort, reverse sort + ctrl+ D, U : Deleted, Undelete a thread + ctrl+R : mark current thread as read + esc+t : select thread + esc+ v, V : collapse thread, collapse all threads + w,W : add, remove flags +# +T ~U ;WN ctrl+t . +mark unread msgs, remove its new flag, unselect them diff --git a/sheets/parted b/sheets/parted new file mode 100644 index 0000000..1829a73 --- /dev/null +++ b/sheets/parted @@ -0,0 +1,9 @@ +# create a new MBR/msdos partition table for BIOS systems +(parted) mklabel msdos + +# create a new GPT partition table for UEFI systems instead, use: +(parted) mklabel gpt + +# grow a partition +(parted) resizepart ${number} ${end} + diff --git a/sheets/pygmentize b/sheets/pygmentize new file mode 100644 index 0000000..907a6cc --- /dev/null +++ b/sheets/pygmentize @@ -0,0 +1,6 @@ +# highlight syntax: use go lexer, style monokai, 256 colors terminal +pygmentize -f terminal256 -l go -g -P style=monokai + +# use filter (keywordcase), will change keywords to upper case +pygmentize -f html -l pascal -F keywordcase:case=upper main.pas + diff --git a/sheets/redis-cli b/sheets/redis-cli new file mode 100644 index 0000000..8b0f1ce --- /dev/null +++ b/sheets/redis-cli @@ -0,0 +1,23 @@ +# redis-cli +# Opens a connection to a Redis server. + +# Connect to the local server: +redis-cli + +# Connect to a remote server on the default port (6379): +redis-cli -h host + +# Connect to a remote server specifying a port number: +redis-cli -h host -p port + +# Specify a password: +redis-cli -a password + +# Execute Redis command: +redis-cli redis_command + +# List Redis keys with prefix "prefix:" +redis-cli KEYS "prefix:*" + +# Delete Redis key abc +redis-cli DEL abc diff --git a/sheets/rip b/sheets/rip new file mode 100644 index 0000000..c877a5c --- /dev/null +++ b/sheets/rip @@ -0,0 +1,5 @@ +# regex into pattern + +# convert stream in JSON +ls | rip '(.*)\.(.*)' '{"name": "$1", "ext": "$2"}' + diff --git a/sheets/rust/Basics b/sheets/rust/Basics new file mode 100644 index 0000000..1583843 --- /dev/null +++ b/sheets/rust/Basics @@ -0,0 +1,85 @@ +// Functions +// `i32` is the type for 32-bit signed integers +fn add2(x: i32, y: i32) -> i32 { + // Implicit return (no semicolon) + x + y +} + +// Main function +fn main() { + + // Numbers // + // + // Immutable bindings + let x: i32 = 1; + + // Integer/float suffixes + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Type inference + // Most of the time, the Rust compiler can infer what type a variable is, so + // you don’t have to write an explicit type annotation. + // Throughout this tutorial, types are explicitly annotated in many places, + // but only for demonstrative purposes. Type inference can handle this for + // you most of the time. + let implicit_x = 1; + let implicit_f = 1.3; + + // Arithmetic + let sum = x + y + 13; + + // Mutable variable + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // Strings // + // + // String literals + let x: &str = "hello world!"; + // + // Printing + println!("{} {}", f, x); // 1.3 hello world + // + // A `String` – a heap-allocated string + let s: String = "hello world".to_string(); + // + // A string slice – an immutable view into another string + // This is basically an immutable pair of pointers to a string – it doesn’t + // actually contain the contents of a string, just a pointer to + // the begin and a pointer to the end of a string buffer, + // statically allocated or contained in another object (in this case, `s`) + let s_slice: &str = &s; + // + println!("{} {}", s, s_slice); // hello world hello world + + // Vectors/arrays // + // + // A fixed-size array + let four_ints: [i32; 4] = [1, 2, 3, 4]; + // + // A dynamic array (vector) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + // + // A slice – an immutable view into a vector or array + // This is much like a string slice, but for vectors + let slice: &[i32] = &vector; + // + // Use `{:?}` to print something debug-style + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuples // + // + // A tuple is a fixed-size set of values of possibly different types + let x: (i32, &str, f64) = (1, "hello", 3.4); + // + // Destructuring `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + // + // Indexing + println!("{}", x.1); // hello + +} diff --git a/sheets/rust/ControlFlow b/sheets/rust/ControlFlow new file mode 100644 index 0000000..4de0371 --- /dev/null +++ b/sheets/rust/ControlFlow @@ -0,0 +1,36 @@ + // `for` loops/iteration + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Ranges + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // prints `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` as expression + let value = if true { + "good" + } else { + "bad" + }; + + // `while` loop + while 1 == 1 { + println!("The universe is operating normally."); + } + + // Infinite loop + loop { + println!("Hello!"); + } diff --git a/sheets/rust/PatternMatching b/sheets/rust/PatternMatching new file mode 100644 index 0000000..87d3cff --- /dev/null +++ b/sheets/rust/PatternMatching @@ -0,0 +1,20 @@ + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), + } + + // Advanced pattern matching + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + // + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("The second number is Nothing!"), + } diff --git a/sheets/rust/Pointers b/sheets/rust/Pointers new file mode 100644 index 0000000..ec276ac --- /dev/null +++ b/sheets/rust/Pointers @@ -0,0 +1,33 @@ + // Owned pointer – only one thing can ‘own’ this pointer at a time + // This means that when the `Box` leaves its scope, it can be automatically deallocated safely. + let mut mine: Box = Box::new(3); + *mine = 5; // dereference + // Here, `now_its_mine` takes ownership of `mine`. In other words, `mine` is moved. + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // this would not compile because `now_its_mine` now owns the pointer + + // Reference – an immutable pointer that refers to other data + // When a reference is taken to a value, we say that the value has been ‘borrowed’. + // While a value is borrowed immutably, it cannot be mutated or moved. + // A borrow lasts until the end of the scope it was created in. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // Unlike `mine`, `var` can still be used + println!("{}", *ref_var); + // var = 5; // this would not compile because `var` is borrowed + // *ref_var = 6; // this would not either, because `ref_var` is an immutable reference + + // Mutable reference + // While a value is mutably borrowed, it cannot be accessed at all. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2 + + println!("{}", *ref_var2); // 6 , // var2 would not compile. + // ref_var2 is of type &mut i32, so stores a reference to an i32, not the value. + // var2 = 2; // this would not compile because `var2` is borrowed. diff --git a/sheets/rust/Types b/sheets/rust/Types new file mode 100644 index 0000000..cdf42fe --- /dev/null +++ b/sheets/rust/Types @@ -0,0 +1,68 @@ + // Struct + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // A struct with unnamed fields, called a ‘tuple struct’ + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // Basic C-like enum + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // Enum with fields + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // Generics // + + struct Foo { bar: T } + + // This is defined in the standard library as `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // Methods // + + impl Foo { + // Methods take an explicit `self` parameter + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // Traits (known as interfaces or typeclasses in other languages) // + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) diff --git a/sheets/rust/hello b/sheets/rust/hello new file mode 100644 index 0000000..ff84259 --- /dev/null +++ b/sheets/rust/hello @@ -0,0 +1,7 @@ +// to install rust: +// curl https://sh.rustup.rs -sSf | sh +// to compile: +// rustc main.rs +fn main() { + println!("Hello, world!"); +} diff --git a/sheets/scala/:main b/sheets/scala/:main new file mode 100644 index 0000000..4c2df01 --- /dev/null +++ b/sheets/scala/:main @@ -0,0 +1,4 @@ +# source: +# +# http://docs.scala-lang.org/cheatsheets/ + diff --git a/sheets/scala/ControlStructures b/sheets/scala/ControlStructures new file mode 100644 index 0000000..67f81d5 --- /dev/null +++ b/sheets/scala/ControlStructures @@ -0,0 +1,54 @@ +// conditional +if (check) happy else sad + +// conditional sugar +if (check) happy // same as +if (check) happy else () + +// while loop +while (x < 5) { println(x); x += 1} + +// do while loop. +do { println(x); x += 1} while (x < 5) + +// break +// slides: https://www.slideshare.net/Odersky/fosdem-2009-1013261/21 +import scala.util.control.Breaks._ +breakable { + for (x <- xs) { + if (Math.random < 0.1) break + } +} + +// for comprehension: filter/map +for (x <- xs if x%2 == 0) yield x*10 +// same as +xs.filter(_%2 == 0).map(_*10) + +// for comprehension: destructuring bind +for ((x,y) <- xs zip ys) yield x*y +// same as +(xs zip ys) map { case (x,y) => x*y } + +// for comprehension: cross product +for (x <- xs; y <- ys) yield x*y +// same as +xs flatMap {x => ys map {y => x*y}} + +// for comprehension: imperative-ish sprintf-style +// http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax +for (x <- xs; y <- ys) { + println("%d/%d = %.1f".format(x, y, x/y.toFloat)) +} + +// for comprehension: iterate including the upper bound +for (i <- 1 to 5) { + println(i) +} + +// for comprehension: iterate omitting the upper bound +for (i <- 1 until 5) { + println(i) +} + + diff --git a/sheets/scala/DataStructures b/sheets/scala/DataStructures new file mode 100644 index 0000000..36957ea --- /dev/null +++ b/sheets/scala/DataStructures @@ -0,0 +1,29 @@ +// tuple literal. (Tuple3) +(1,2,3) + +// destructuring bind: tuple unpacking via pattern matching. +var (x,y,z) = (1,2,3) + +// hidden error: each assigned to the entire tuple. +// BAD +var x,y,z = (1,2,3) + +// list (immutable). +var xs = List(1,2,3) + +// paren indexing. (slides) +// more on it: https://www.slideshare.net/Odersky/fosdem-2009-1013261/27 +xs(2) + +// cons. +1 :: List(2,3) + +// range sugar. +1 to 5 // same as +1 until 6 +1 to 10 by 2 + +// sole member of the Unit type (like C/Java void). +() //(empty parens) + + diff --git a/sheets/scala/Functions b/sheets/scala/Functions new file mode 100644 index 0000000..1416026 --- /dev/null +++ b/sheets/scala/Functions @@ -0,0 +1,71 @@ +// define function +// GOOD +def f(x: Int) = { x*x } +// BAD +// hidden error: without = it’s a Unit-returning procedure; causes havoc +def f(x: Int) { x*x } + +// define function +// GOOD +def f(x: Any) = println(x) +// BAD +// syntax error: need types for every arg. +def f(x) = println(x) + +// type alias +type R = Double + +// call-by-value +def f(x: R) +// call-by-name (lazy parameters) +def f(x: => R) + +// anonymous function +(x:R) => x*x + +// anonymous function: underscore is positionally matched arg. +(1 to 5).map(_*2) // vs. +(1 to 5).reduceLeft( _+_ ) + +// anonymous function: to use an arg twice, have to name it. +(1 to 5).map( x => x*x ) + +// anonymous function: bound infix method. Use 2*_ for sanity’s sake instead. +// GOOD +(1 to 5).map(2*) +// BAD +(1 to 5).map(*2) + +// anonymous function: block style returns last expression. +(1 to 5).map { x => val y=x*2; println(y); y } + +// anonymous functions: pipeline style. (or parens too). +(1 to 5) filter {_%2 == 0} map {_*2} + +// anonymous functions: to pass in multiple blocks, need outer parens. +def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x)) +val f = compose({_*2}, {_-1}) + +// currying, obvious syntax. +val zscore = (mean:R, sd:R) => (x:R) => (x-mean)/sd + +// currying, obvious syntax +def zscore(mean:R, sd:R) = (x:R) => (x-mean)/sd + +// currying, sugar syntax. but then: +def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd + +// need trailing underscore to get the partial, only for the sugar version. +val normer = zscore(7, 0.4) _ + +// generic type. +def mapmake[T](g:T=>T)(seq: List[T]) = seq.map(g) + +// infix sugar. +5.+(3); 5 + 3 +(1 to 5) map (_*2) + +// varargs +def sum(args: Int*) = args.reduceLeft(_+_) + + diff --git a/sheets/scala/ObjectOrientation b/sheets/scala/ObjectOrientation new file mode 100644 index 0000000..bd9939e --- /dev/null +++ b/sheets/scala/ObjectOrientation @@ -0,0 +1,76 @@ +// constructor params - private +class C(x: R) // same as +class C(private val x: R) +var c = new C(4) + +// constructor params - public +class C(val x: R) +var c = new C(4) +c.x + +class C(var x: R) { + // constructor is class body + assert(x > 0, "positive please") + // + // declare a public member + var y = x + // + // declare a gettable but not settable member + val readonly = 5 + // + // declare a private member + private var secret = 1 + // + // alternative constructor + def this = this(42) +} + +// anonymous class +new{ ... } + +// define an abstract class. (non-createable) +abstract class D { ... } + +// define an inherited class. +class C extends D { ... } +class D(var x: R) + +// inheritance and constructor params. (wishlist: automatically pass-up params by default) +class C(x: R) extends D(x) + +// define a singleton. (module-like) +object O extends D { ... } + +// traits. +trait T { ... } + +// interfaces-with-implementation. no constructor params +// mixin-able: http://docs.scala-lang.org/tutorials/tour/mixin-class-composition.html +class C extends T { ... } +class C extends D with T { ... } + +// multiple traits. +trait T1; trait T2 +class C extends T1 with T2 +class C extends D with T1 with T2 + +// must declare method overrides. +class C extends D { override def f = ...} + +// create object. +new java.io.File("f") + +new List[Int] // BAD type error: abstract type +List(1,2,3) // GOOD instead, convention: callable factory shadowing the type + +// class literal. +classOf[String] + +// type check (runtime) +x.isInstanceOf[String] + +// type cast (runtime) +x.asInstanceOf[String] + +// ascription (compile time) +x: String diff --git a/sheets/scala/Packages b/sheets/scala/Packages new file mode 100644 index 0000000..2594621 --- /dev/null +++ b/sheets/scala/Packages @@ -0,0 +1,18 @@ +// wildcard import. +import scala.collection._ + +// selective import. +import scala.collection.Vector +import scala.collection.{Vector, Sequence} + +// renaming import. +import scala.collection.{Vector => Vec28} + +// import all from java.util except Date. +import java.util.{Date => _, _} + +// declare a package. +package pkg // at start of file +package pkg { ... } + + diff --git a/sheets/scala/PatternMatching b/sheets/scala/PatternMatching new file mode 100644 index 0000000..7153248 --- /dev/null +++ b/sheets/scala/PatternMatching @@ -0,0 +1,29 @@ +// use case in function args for pattern matching. +(xs zip ys) map { case (x,y) => x*y } // GOOD +(xs zip ys) map( (x,y) => x*y ) // BAD + +// "v42" is interpreted as a name matching any Int value, and "42" is printed. +// BAD +val v42 = 42 +Some(3) match { + case Some(v42) => println("42") + case _ => println("Not 42") +} + +// "`v42`" with backticks is interpreted as the existing val v42, and “Not 42” is printed. +// GOOD +val v42 = 42 +Some(3) match { + case Some(`v42`) => println("42") + case _ => println("Not 42") +} + +// UppercaseVal is treated as an existing val, rather than a new pattern variable, because it starts with an uppercase letter. +// Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed. +// GOOD +val UppercaseVal = 42 +Some(3) match { + case Some(UppercaseVal) => println("42") + case _ => println("Not 42") +} + diff --git a/sheets/scala/Variables b/sheets/scala/Variables new file mode 100644 index 0000000..509257e --- /dev/null +++ b/sheets/scala/Variables @@ -0,0 +1,11 @@ +// variables +var x = 5 + +// constant +// GOOD +val x = 5 +// BAD +x=6 + +// explicit type +var x: Double = 5 diff --git a/sheets/scala/hello b/sheets/scala/hello new file mode 100644 index 0000000..19373e6 --- /dev/null +++ b/sheets/scala/hello @@ -0,0 +1,9 @@ +// to compile: scalac HelloWorld.scala +// or scalac -d classes HelloWorld.scala +// to execute: scala HelloWorld +// or scala -cp classes HelloWorld +object HelloWorld { + def main(args: Array[String]) { + println("Hello, world!") + } +} diff --git a/sheets/sgdisk b/sheets/sgdisk new file mode 100644 index 0000000..92559c1 --- /dev/null +++ b/sheets/sgdisk @@ -0,0 +1,26 @@ +# convert an MBR partition table to GPT, use sgdisk +sgdisk -g /dev/sda + +# convert GPT to MBR use the m option. +# it is not possible to convert more than four partitions from GPT to MBR +sgdisk -m /dev/sda + +# Sort GPT partitions +# when a new partition is created in the space between two partitions or a partition is deleted +sgdisk -s /dev/sda + + +# Using sgdisk you can create a binary backup consisting of the protective MBR, +# the main GPT header, the backup GPT header, and one copy of the partition table +sgdisk -b=sgdisk-sda.bak + +# Restore GPT/MBR backup: +sgdisk -l=sgdisk-sda.bak + +# Clone your current device's partition layout '/dev/sda' to another drive '/dev/sdc' +sgdisk -R=/dev/sdc /dev/sda + +# If both drives will be in the same computer, you need to randomize the GUID's after cloning +sgdisk -G /dev/sdc + + diff --git a/sheets/xkb b/sheets/xkb new file mode 100644 index 0000000..d8a0228 --- /dev/null +++ b/sheets/xkb @@ -0,0 +1,3 @@ +# Set the keyboard layout for the current X session +setxkbmap -layout "us,ru" +setxkbmap -option "grp:caps_toggle,grp_led:scroll,compose:ralt" diff --git a/sheets/xm b/sheets/xm new file mode 100644 index 0000000..52a67f0 --- /dev/null +++ b/sheets/xm @@ -0,0 +1,82 @@ +# Shows information about the Xen host +xm info + +# Shows information about doms (states include r for running, b for blocked, c for crashed, p for paused and the worse, d for dying). +xm list + +# Shows virtual interfaces for doms +xm network-list + +# Shows information from the Xen logs +xm log + +# Reboots a VM +xm reboot + +# Shows dom virtual processors +xm vcpu-list + +# Shows hosts and domains similar to how top works in *nix +xm top + +# Shows uptime +xm uptime + +# Shows the send message buffer +xm dmesg + +# Create a node called ${domain_name} +xm create ${domain_name} + +# Attach to the console of the ${domain_name} node +xm console ${domain_name} + +# Deletes that newly created ${domain_name} node +xm destroy ${domain_name} + +# Invoke an interactive shell environment of your xend +xm shell + +# Turn off a VM +xm shutdown + +# Rather than shut the VM down, just pause it (starts back up much faster), +# but if the host is rebooted then state is lost (otherwise use suspend) +xm pause + +# Suspends a VM, which writes the data to disk, so changes wouldn't be lost on restart. +xm suspend + +# Rename installed VMs +xm rename + +# If a VM is paused, fire it up +xm resume + +# Similar to suspend except with user definable state file +xm save + +# Similar to resume except restoreable with exports that used the save verb +xm restore + +# Dumps core per domain +xm dump-core + +# Sends system requests per domain +xm sysrq + +# Lists block devices per domain +xm block-list + +# Configure the maximum memory for a domain +xm mem-max + +# Configure the current memory allowance for a domain +xm mem-set + +# Configure active processors for a domain +xm vcpu-set + +# Move a domain to another server (e.g. using the -l operator to do so live) +xm migrate + diff --git a/sheets/xscreensaver b/sheets/xscreensaver new file mode 100644 index 0000000..39b4876 --- /dev/null +++ b/sheets/xscreensaver @@ -0,0 +1,2 @@ +# lock screen sver +xscreensaver-command -lock