From 9bda601ca8be601cfd3c38636f6b46b42284486e Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 22 Feb 2020 02:42:51 +0000 Subject: [PATCH 01/12] Tweak and add to `fdisk` and `df` --- sheets/df | 15 +++++++++------ sheets/fdisk | 13 ++++++------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/sheets/df b/sheets/df index ff63533..b404be6 100644 --- a/sheets/df +++ b/sheets/df @@ -1,14 +1,17 @@ -# Printout disk free space in a human readable format +# Print free disk space in a [h]uman-readable format. df -h -# Disk free space for ext2 file systems +# Free disk space for [t]ype EXT2 file systems. df -t ext2 -# Disk free space for file systems except ext2 +# Free disk space for filesystems, e[x]cluding EXT2. df -x ext2 -# Show inode usage +# Show [i]node usage. df -i -# Show information about a distinct file system /path -df /path +# Show information about a distinct filesystem path. +df [PATH] + +# List [a]ll filesystems, + unreadable, duplicates, pseudo, and inaccessible. +df -a diff --git a/sheets/fdisk b/sheets/fdisk index de31284..0705c71 100644 --- a/sheets/fdisk +++ b/sheets/fdisk @@ -1,8 +1,7 @@ -# list partitions -fdisk -l /dev/sda - -# delete a partition -fdisk /dev/sda -Command (m for help): d -Partition number (1-9): XXX +# List partitions on BLKDEV, such as `/dev/sda`. +fdisk -l [BLKDEV] +# Delete a partition. +fdisk [BLOCK_DEVICE] +# Once in the interactive prompt: +d [NUMBER] From d7473ac185bc4309b5d4aa55761233e974c5f80d Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 22 Feb 2020 02:47:54 +0000 Subject: [PATCH 02/12] Fix trailing whitespace on all files Tidy files; tidy soul! --- sheets/MegaCli | 2 +- sheets/_cpp/hello | 2 +- sheets/_elm/hello | 2 +- sheets/_go/Axioms | 2 +- sheets/_go/Channels | 2 +- sheets/_go/Pointers | 2 +- sheets/_go/func | 2 +- sheets/_go/go | 2 +- sheets/_go/switch | 2 +- sheets/_js/1line | 2 +- sheets/_mathematica/levelspec | 4 ++-- sheets/_perl/subroutines | 2 +- sheets/_perl6/hello | 2 +- sheets/_psql/tables | 2 +- sheets/_python3/classes | 4 ++-- sheets/_rust/threads | 2 +- sheets/_scala/DataStructures | 2 +- sheets/_scala/ObjectOrientation | 2 +- sheets/_scala/Variables | 2 +- sheets/az | 2 +- sheets/bonnie | 2 +- sheets/btrfs | 2 +- sheets/bzr | 2 +- sheets/curl | 2 +- sheets/dcfldd | 2 +- sheets/identify | 2 +- sheets/ioreg | 2 +- sheets/jq | 2 +- sheets/jslint | 2 +- sheets/julia | 2 +- sheets/launchctl | 4 ++-- sheets/libreoffice | 2 +- sheets/ncmpcpp | 2 +- sheets/objdump | 2 +- sheets/percol | 2 +- sheets/perl6 | 2 +- sheets/php | 2 +- sheets/rclone | 2 +- sheets/rustup | 2 +- sheets/sox | 2 +- sheets/systemd-sysvinit | 18 +++++++++--------- sheets/xfs_repair | 2 +- sheets/xkb | 2 +- sheets/xset | 4 ++-- 44 files changed, 56 insertions(+), 56 deletions(-) diff --git a/sheets/MegaCli b/sheets/MegaCli index 124bfc5..bfdda54 100644 --- a/sheets/MegaCli +++ b/sheets/MegaCli @@ -1,5 +1,5 @@ # MegaCli introduced by LSI as a command line administration of LSI MegaRaid controllers. -# With megacli we can create physical raids, gather info about raids and monitor raids. +# With megacli we can create physical raids, gather info about raids and monitor raids. # Install MegaCLI yum install MegaCli # CentOS diff --git a/sheets/_cpp/hello b/sheets/_cpp/hello index 0c7e255..8cabcb2 100644 --- a/sheets/_cpp/hello +++ b/sheets/_cpp/hello @@ -7,7 +7,7 @@ // To Compile w/ specific executable name: g++ my_script.cpp -o my.executable // To Execute: ./my.executable -int main() { +int main() { std::cout << "Hello" << endl; return 0; } diff --git a/sheets/_elm/hello b/sheets/_elm/hello index e7146c7..4449b86 100644 --- a/sheets/_elm/hello +++ b/sheets/_elm/hello @@ -7,7 +7,7 @@ # elm package install elm-lang/html # after that create Hello.elm in this directory # To start: -# elm reactor +# elm reactor # Read more here: # https://www.elm-tutorial.org/en/01-foundations/01-hello.html module Hello exposing (..) diff --git a/sheets/_go/Axioms b/sheets/_go/Axioms index 26e9933..455e675 100644 --- a/sheets/_go/Axioms +++ b/sheets/_go/Axioms @@ -21,6 +21,6 @@ c <- 1 c <- 2 close(c) for i := 0; i < 3; i++ { - fmt.Printf("%d ", <-c) + fmt.Printf("%d ", <-c) } // 1 2 0 diff --git a/sheets/_go/Channels b/sheets/_go/Channels index 99cebd5..95791a4 100644 --- a/sheets/_go/Channels +++ b/sheets/_go/Channels @@ -3,7 +3,7 @@ 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 +// 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. diff --git a/sheets/_go/Pointers b/sheets/_go/Pointers index e6a1396..c71ae57 100644 --- a/sheets/_go/Pointers +++ b/sheets/_go/Pointers @@ -4,4 +4,4 @@ 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) +var s *Vertex = new(Vertex) diff --git a/sheets/_go/func b/sheets/_go/func index afe8e41..b002a22 100644 --- a/sheets/_go/func +++ b/sheets/_go/func @@ -68,7 +68,7 @@ func outer() (func() int, int) { 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 } diff --git a/sheets/_go/go b/sheets/_go/go index f71afb7..a680137 100644 --- a/sheets/_go/go +++ b/sheets/_go/go @@ -1,4 +1,4 @@ -// Goroutines are lightweight threads (managed by Go, not OS threads). +// 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) diff --git a/sheets/_go/switch b/sheets/_go/switch index f8ca78b..821533e 100644 --- a/sheets/_go/switch +++ b/sheets/_go/switch @@ -10,7 +10,7 @@ default: fmt.Println("Other") } -// as with for and if, you can have an assignment statement before the switch value +// as with for and if, you can have an assignment statement before the switch value switch os := runtime.GOOS; os { case "darwin": ... } diff --git a/sheets/_js/1line b/sheets/_js/1line index 81cc675..5a476af 100644 --- a/sheets/_js/1line +++ b/sheets/_js/1line @@ -8,7 +8,7 @@ var newA = myArray.slice(0); 'A'.replace(/<[^>]+>/gi, ''); // Reverse a string -var str = "abc def ghi."; +var str = "abc def ghi."; str.split('').reverse().join(''); // '.ihg fed cba' // Reverse order of words in a string diff --git a/sheets/_mathematica/levelspec b/sheets/_mathematica/levelspec index f6ddc1b..ca01f3a 100644 --- a/sheets/_mathematica/levelspec +++ b/sheets/_mathematica/levelspec @@ -14,8 +14,8 @@ Map[f,l,{2,5}] (* The default levelspec is {1} *) Map[f,l]===Map[f,l,{1}] -(* +(* A positive level n consists of all parts of expr specified by n indices. A negative level -n consists of all parts of expr with depth n. Level 0 corresponds to the whole expression. -*) \ No newline at end of file +*) diff --git a/sheets/_perl/subroutines b/sheets/_perl/subroutines index 5ab5f48..95b04a5 100644 --- a/sheets/_perl/subroutines +++ b/sheets/_perl/subroutines @@ -28,7 +28,7 @@ named_params_example({ sub named_params_with_defaults { my ( $arg ) = @_; # Use my ( $self, $arg ) = @_; if you are in object land. - # + # # Set defaults # If option given Use options Else my $one = exists $arg->{one} ? $arg->{one} : "default1"; diff --git a/sheets/_perl6/hello b/sheets/_perl6/hello index 45c12ed..669b742 100644 --- a/sheets/_perl6/hello +++ b/sheets/_perl6/hello @@ -1,4 +1,4 @@ -# to install: +# to install: # (Debian/Ubuntu) apt-get install rakudo # (Fedora/CentOS) yum install perl6 (or rakudo) # to execute: perl6 my_script.pl diff --git a/sheets/_psql/tables b/sheets/_psql/tables index 15d6225..f324eef 100644 --- a/sheets/_psql/tables +++ b/sheets/_psql/tables @@ -22,7 +22,7 @@ ALTER TABLE table_name ALTER COLUMN [SET DEFAULT value | DROP DEFAULT] ALTER TABLE table_name ADD PRIMARY KEY (column,...); -- Remove the primary key from a table -ALTER TABLE table_name +ALTER TABLE table_name DROP CONSTRAINT primary_key_constraint_name; -- Rename a table diff --git a/sheets/_python3/classes b/sheets/_python3/classes index 186eee5..42fe515 100644 --- a/sheets/_python3/classes +++ b/sheets/_python3/classes @@ -3,13 +3,13 @@ class Dog: # __init__ is the constructor, run on instantiation # The 'self' parameter refers to the calling instance of the class. - # It's automatically provided to methods called on an instance of this + # It's automatically provided to methods called on an instance of this # class. It can be named anything, but 'self' is the convention. def __init__(self, name): self.name = name # Class methods (or static methods) are created by adding the staticmethod - # decorator. The 'self' parameter is not passed to these methods. + # decorator. The 'self' parameter is not passed to these methods. @staticmethod def unrelated_class_method(): print('this is not an instance method') diff --git a/sheets/_rust/threads b/sheets/_rust/threads index caef519..9e260f8 100644 --- a/sheets/_rust/threads +++ b/sheets/_rust/threads @@ -6,7 +6,7 @@ fn main() { let t = thread::spawn(|| { println!("In a new thread!"); }); - + // Wait for execution of spawned thread to join back up with main thread let result = t.join(); diff --git a/sheets/_scala/DataStructures b/sheets/_scala/DataStructures index 2fc575b..740cc8c 100644 --- a/sheets/_scala/DataStructures +++ b/sheets/_scala/DataStructures @@ -5,7 +5,7 @@ // This example would be a Tuple3 (1,2,3) -// tuple sugar +// tuple sugar // This example would be a Tuple2 (1 -> 2) //same as (1, 2) diff --git a/sheets/_scala/ObjectOrientation b/sheets/_scala/ObjectOrientation index bd9939e..1ff93d0 100644 --- a/sheets/_scala/ObjectOrientation +++ b/sheets/_scala/ObjectOrientation @@ -23,7 +23,7 @@ class C(var x: R) { // // alternative constructor def this = this(42) -} +} // anonymous class new{ ... } diff --git a/sheets/_scala/Variables b/sheets/_scala/Variables index 5080392..bf366da 100644 --- a/sheets/_scala/Variables +++ b/sheets/_scala/Variables @@ -9,7 +9,7 @@ val x = 5 // BAD x = 5 -// lazy value +// lazy value // immutable, evaluated once but only when called lazy val x = 5 diff --git a/sheets/az b/sheets/az index 06f9abe..bce8d50 100644 --- a/sheets/az +++ b/sheets/az @@ -5,7 +5,7 @@ curl -L https://aka.ms/InstallAzureCli | bash # create a resource group named "MyResourceGroup" in the westus2 region of Azure -az group create -n MyResourceGroup -l westus2 +az group create -n MyResourceGroup -l westus2 # create a Linux VM using the UbuntuTLS image, with two attached storage disks of 10 GB and 20 GB az vm create -n MyLinuxVM -g MyResourceGroup --ssh-key-value $HOME/.ssh/id_rsa.pub --image UbuntuLTS --data-disk-sizes-gb 10 20 diff --git a/sheets/bonnie b/sheets/bonnie index ea57bc9..66f08c3 100644 --- a/sheets/bonnie +++ b/sheets/bonnie @@ -1,4 +1,4 @@ -# Bonnie++ +# Bonnie++ # disk and file system benchmarking tool for measuring I/O performance # benchmark disk mounted at /tmp/; use `user` for that diff --git a/sheets/btrfs b/sheets/btrfs index b5dfae2..5317d11 100644 --- a/sheets/btrfs +++ b/sheets/btrfs @@ -1,7 +1,7 @@ # 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 +# 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 diff --git a/sheets/bzr b/sheets/bzr index a980773..fa53b7f 100644 --- a/sheets/bzr +++ b/sheets/bzr @@ -2,7 +2,7 @@ cd ~/.bazaar/plugins bzr branch lp:bzr-fastimport fastimport # you can do it manually: -# pip install +# pip install # python setup.py build_ext -i # mv ... ~/.bazaar/plugins # probably you will need this patch: diff --git a/sheets/curl b/sheets/curl index e599063..f2d6850 100644 --- a/sheets/curl +++ b/sheets/curl @@ -14,7 +14,7 @@ curl http://example.com/pic[1-24].jpg curl -L http://example.com/file # Download a file and pass HTTP Authentication -curl -u username:password URL +curl -u username:password URL # Download a file with a Proxy curl -x proxysever.server.com:PORT http://addressiwantto.access diff --git a/sheets/dcfldd b/sheets/dcfldd index 0d9daf3..c355d8f 100644 --- a/sheets/dcfldd +++ b/sheets/dcfldd @@ -1,4 +1,4 @@ -# enhanced version of GNU dd with features useful for forensics and security. +# enhanced version of GNU dd with features useful for forensics and security. # includes ability to have mulitple output targets # write file image to an SD card showing a progress bar based on filesize diff --git a/sheets/identify b/sheets/identify index a3f7d82..450a1ec 100644 --- a/sheets/identify +++ b/sheets/identify @@ -1,4 +1,4 @@ -# identify +# identify # # describes the format and characteristics of one or more image files diff --git a/sheets/ioreg b/sheets/ioreg index d4b49f2..48fca39 100644 --- a/sheets/ioreg +++ b/sheets/ioreg @@ -1,4 +1,4 @@ -# ioreg +# ioreg # show I/O Kit registry (Mac OS X) # find out the arch of the efi firmware in a Mac diff --git a/sheets/jq b/sheets/jq index 05be235..842203a 100644 --- a/sheets/jq +++ b/sheets/jq @@ -58,7 +58,7 @@ jq 'flatten(1)' # Converting to csv jq '.[] | [.foo, .bar] | @csv' -r -# +# # [{ "foo": 1, "bar": 2, "baz":3 }] # => 1,2 diff --git a/sheets/jslint b/sheets/jslint index f34ff30..3b13428 100644 --- a/sheets/jslint +++ b/sheets/jslint @@ -1,5 +1,5 @@ # jslint -# +# # The JavaScript Code Quality Tool written by Dougls Crockford # to install jslint diff --git a/sheets/julia b/sheets/julia index 9aec76d..6ec9e15 100644 --- a/sheets/julia +++ b/sheets/julia @@ -1,4 +1,4 @@ -# Julia +# Julia # high-level dynamic programming language designed to address the needs of high-performance numerical analysis # and computational science while also being effective for general-purpose programming diff --git a/sheets/launchctl b/sheets/launchctl index b2def36..1631f6d 100644 --- a/sheets/launchctl +++ b/sheets/launchctl @@ -9,11 +9,11 @@ # whenever the user logs in: launchctl load ~/Library/LaunchAgents/my_script.plist -# Activate an agent which requires root privileges to run +# Activate an agent which requires root privileges to run # and/or should be loaded whenever any user logs in (note the absence of ~ in the path): sudo launchctl load /Library/LaunchAgents/root_script.plist -# Activate a system-wide daemon to be loaded +# Activate a system-wide daemon to be loaded # whenever the system boots up (even if no user logs in): sudo launchctl load /Library/LaunchDaemons/system_daemon.plist diff --git a/sheets/libreoffice b/sheets/libreoffice index d5a0df8..1adf892 100644 --- a/sheets/libreoffice +++ b/sheets/libreoffice @@ -4,6 +4,6 @@ libreoffice --headless --convert-to pdf *.pptx # Save them to a different directory? libreoffice --headless --convert-to pdf *.docx --outdir ~/docs/ -# Convert files nested inside folders? +# Convert files nested inside folders? # This uses sharkdp/fd, you could use GNU find, xargs etc. fd -e doc -e docx -x libreoffice --headless --convert-to pdf --outdir {//} {} diff --git a/sheets/ncmpcpp b/sheets/ncmpcpp index 017fb66..7142b53 100644 --- a/sheets/ncmpcpp +++ b/sheets/ncmpcpp @@ -1,6 +1,6 @@ # ncmpcpp is an mpd client (compatible with mopidy) with a UI very similar to ncmpc, # but it provides new useful features such as support for regular expressions for library searches, -# extended song format, items filtering, the ability to sort playlists, and a local filesystem browser. +# extended song format, items filtering, the ability to sort playlists, and a local filesystem browser. # configure ncmpcpp mkdir ~/.ncmpcpp diff --git a/sheets/objdump b/sheets/objdump index 6ad979e..b1a97c0 100644 --- a/sheets/objdump +++ b/sheets/objdump @@ -1,4 +1,4 @@ -# objdump +# objdump # program for displaying various information about object files # Display the contents of the overall file header diff --git a/sheets/percol b/sheets/percol index a2fba69..999d087 100644 --- a/sheets/percol +++ b/sheets/percol @@ -1,6 +1,6 @@ # percol # -# adds flavor of interactive filtering to the traditional pipe concept of UNIX shell +# adds flavor of interactive filtering to the traditional pipe concept of UNIX shell # to install percol sudo pip install percol diff --git a/sheets/perl6 b/sheets/perl6 index 727a0a6..93eb50d 100644 --- a/sheets/perl6 +++ b/sheets/perl6 @@ -2,7 +2,7 @@ # The Perl 6 Language Implementation # to install perl6 (in Debian/Ubuntu) -apt-get install rakudo +apt-get install rakudo # To install rakudobrew and zef (perl 6 package management) git clone https://github.com/tadzik/rakudobrew ~/.rakudobrew diff --git a/sheets/php b/sheets/php index 9a815ed..3e5eaaf 100644 --- a/sheets/php +++ b/sheets/php @@ -1,4 +1,4 @@ -# PHP is a server-side scripting language designed primarily for web development +# PHP is a server-side scripting language designed primarily for web development # but also used as a general-purpose programming language # To view the php version: diff --git a/sheets/rclone b/sheets/rclone index 9f42c53..014dce6 100644 --- a/sheets/rclone +++ b/sheets/rclone @@ -11,7 +11,7 @@ rclone ls remote:path rclone copy /local/path remote:path # Sync /local/path to the remote -rclone sync /local/path remote:path +rclone sync /local/path remote:path # Server side Copy rclone copy s3:oldbucket s3:newbucket diff --git a/sheets/rustup b/sheets/rustup index 42df10f..a2f9198 100644 --- a/sheets/rustup +++ b/sheets/rustup @@ -1,5 +1,5 @@ # rustup -# The Rust toolchain installer +# The Rust toolchain installer # update rustup toolchain rustup update diff --git a/sheets/sox b/sheets/sox index d1e4079..4a5bb02 100644 --- a/sheets/sox +++ b/sheets/sox @@ -30,7 +30,7 @@ sox ${mono_wav} -c 2 ${stereo_wav} # Generate Different Types of Sounds # ${len} - length of audio to synthesize, hh:mm:ss.frac # ${freq} - frequencies at the beginning/end of synthesis in Hz -# ${type} is one of sine, square, triangle, sawtooth, trapezium, exp, +# ${type} is one of sine, square, triangle, sawtooth, trapezium, exp, # [white]noise, pinknoise, brown-noise # sox -n synth ${len} ${type} ${freq} sox -r 8000 -n output.wav synth 3 sine 300-3300 diff --git a/sheets/systemd-sysvinit b/sheets/systemd-sysvinit index a135cb9..fd90d94 100644 --- a/sheets/systemd-sysvinit +++ b/sheets/systemd-sysvinit @@ -1,7 +1,7 @@ # SysVinit to Systemd Cheatsheet # Services #------------------------------------------------------------------------------------------------------------------------------------------------- -# Sysvinit Command Systemd Command Notes +# Sysvinit Command Systemd Command Notes #------------------------------------------------------------------------------------------------------------------------------------------------- # service frobozz start systemctl start frobozz Used to start a service (not reboot persistent) # service frobozz stop systemctl stop frobozz Used to stop a service (not reboot persistent) @@ -10,19 +10,19 @@ # service frobozz condrestart systemctl condrestart frobozz Restarts if the service is already running. # service frobozz status systemctl status frobozz Tells whether a service is currently running. # ls /etc/rc.d/init.d/ systemctl Used to list the services that can be started or stopped -# (or) systemctl list-unit-files --type=service +# (or) systemctl list-unit-files --type=service # (or) ls /lib/systemd/system/*.service /etc/systemd/system/*.service # chkconfig frobozz on systemctl enable frobozz Turn the service on, for start at next boot, or other trigger. # chkconfig frobozz off systemctl disable frobozz Turn the service off for the next reboot, or any other trigger. # chkconfig frobozz systemctl is-enabled frobozz Used to check whether a service is configured to start or not in the current environment. -# chkconfig --list systemctl list-unit-files --type=service -# (or) ls /etc/systemd/system/*.wants/ +# chkconfig --list systemctl list-unit-files --type=service +# (or) ls /etc/systemd/system/*.wants/ # Print a table of services that lists which runlevels each is configured on or off -# chkconfig --list | grep 5:on systemctl list-dependencies graphical.target +# chkconfig --list | grep 5:on systemctl list-dependencies graphical.target # Print a table of services that will be started when booting into graphical mode -# chkconfig frobozz --list ls /etc/systemd/system/*.wants/frobozz.service +# chkconfig frobozz --list ls /etc/systemd/system/*.wants/frobozz.service # Used to list what levels this service is configured on or off -# chkconfig frobozz --add systemctl daemon-reload Used when you create a new service file or modify any configuration +# chkconfig frobozz --add systemctl daemon-reload Used when you create a new service file or modify any configuration # SysVinit to Systemd Cheatsheet # Runlevels/targets @@ -37,9 +37,9 @@ # runlevel4.target # multi-user.target # 3 runlevel3.target Multi-user, non-graphical. Users can usually login via multiple consoles or via the network. -# multi-user.target +# multi-user.target # 5 runlevel5.target Multi-user, graphical. Usually has all the services of runlevel 3 plus a graphical login. # graphical.target # 6 runlevel6.target Reboot # reboot.target -# emergency emergency.target Emergency shell +# emergency emergency.target Emergency shell diff --git a/sheets/xfs_repair b/sheets/xfs_repair index 25f74b0..65fb08a 100644 --- a/sheets/xfs_repair +++ b/sheets/xfs_repair @@ -1,5 +1,5 @@ # xfs_repair -# repair an XFS filesystem +# repair an XFS filesystem # rapair a XFS filesystem xfs_repair /dev/dm-0 diff --git a/sheets/xkb b/sheets/xkb index f604501..7f3456d 100644 --- a/sheets/xkb +++ b/sheets/xkb @@ -1,4 +1,4 @@ -# Set the keyboard layout for the current X session +# 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/xset b/sheets/xset index 9b733ee..28b5840 100644 --- a/sheets/xset +++ b/sheets/xset @@ -1,5 +1,5 @@ # xset -# user preference utility for X +# user preference utility for X # Disable screen saver blanking xset s off @@ -19,5 +19,5 @@ xset dpms force off # Standby screen xset dpms force standby -# Suspend screen +# Suspend screen xset dpms force suspend From 2ce193c0badeb252bd4756be2aca6ea84ecaf943 Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 22 Feb 2020 03:38:15 +0000 Subject: [PATCH 03/12] Fix typos, tidy formatting, & improve writing This is what late-night boredom does to you. lol --- sheets/awk | 24 ++++++++++++------------ sheets/python | 4 ++-- sheets/sgdisk | 2 +- sheets/siteciphers | 4 ++-- sheets/source | 6 +++--- sheets/svgo | 26 ++++++++++++++------------ sheets/weather | 6 +++--- 7 files changed, 37 insertions(+), 35 deletions(-) diff --git a/sheets/awk b/sheets/awk index 96b5f26..b6b3e6c 100644 --- a/sheets/awk +++ b/sheets/awk @@ -1,7 +1,7 @@ -# sum integers from a file or stdin, one integer per line: +# sum integers from a file or STDIN, one integer per line: printf '1\n2\n3\n' | awk '{ sum += $1} END {print sum}' -# using specific character as separator to sum integers from a file or stdin +# using specific character as separator to sum integers from a file or STDIN printf '1:2:3' | awk -F ":" '{print $1+$2+$3}' # print a multiplication table @@ -16,30 +16,30 @@ awk -v RS='' '/42B/' file # display only first column from multi-column text echo "first-column second-column third-column" | awk '{print $1}' -# Use awk solo; without the need for something via STDIN. +# Use AWK solo; without the need for something via STDIN. awk BEGIN'{printf("Example text.\n")}' -# Accessing environment variables from within awk. +# Accessing environment variables from within AWK. awk 'BEGIN{print ENVIRON["LS_COLORS"]}' # One method to count the number of lines; in this case, read from STDIN. free | awk '{i++} END{print i}' -# Output a (unique) list of available sections under which to create a DEB package. +# Output unique list of available sections under which to create a DEB package. awk '!A[$1]++{print($1)}' <<< "$(dpkg-query --show -f='${Section}\n')" -# Using process substitution (`<()` is NOT command substitution), with AWK and its -# associative array variables, we can print just column 2 for lines whose first -# column is equal to what's between the double-quotes. +# Using process substitution (`<()` is NOT command substitution), with AWK and +# its associative array variables, we can print just column 2 for lines whose +# first column is equal to what's between the double-quotes. awk '{NR!=1&&A[$1]=$2} END{print(A["Mem:"])}' <(free -h) -# While below is an easier and simpler solution to the above, it's not at all the -# same, and in other cases, the above is definitely preferable; more accurate. +# While below is an easier and simpler solution to the above, it's not at all +# the same, and in other cases, the above is definitely preferable. awk '/^Mem:/{print($2)}' <(free -h) -# Output a unique-d list of uppercase-only, sigil-omitted variables used in [FILE]. +# Output list of unique uppercase-only, sigil-omitted variables used in [FILE]. awk '{for(F=0; F Date: Sat, 29 Feb 2020 23:24:15 +0000 Subject: [PATCH 04/12] Tweak formatting & add another example --- sheets/dd | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/sheets/dd b/sheets/dd index 3faee39..9a5633a 100644 --- a/sheets/dd +++ b/sheets/dd @@ -1,26 +1,42 @@ # Read from {/dev/urandom} 2*512 Bytes and put it into {/tmp/test.txt} -# Note: At the first iteration, we read 512 Bytes. -# Note: At the second iteration, we read 512 Bytes. -dd if=/dev/urandom of=/tmp/test.txt count=512 bs=2 +# Note: both iterations each read 512 Bytes (the selected block size). +dd if=/dev/urandom of=/tmp/test.txt count=2 bs=512 -# Watch the progress of 'dd' -dd if=/dev/zero of=/dev/null bs=4KB &; export dd_pid=`pgrep '^dd'`; while [[ -d /proc/$dd_pid ]]; do kill -USR1 $dd_pid && sleep 1 && clear; done +# Watch the progress of dd(1). +dd if=/dev/zero of=/dev/null bs=4KB & +export dd_pid=`pgrep '^dd'` +while [[ -d /proc/$dd_pid ]]; do + kill -USR1 $dd_pid && sleep 1 + clear +done -# Watch the progress of 'dd' with `pv` and `dialog` (apt-get install pv dialog) -(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0 +# Watch the progress of dd(1) with pv(1) and dialog(1), both of which can be +# installed with the following command: apt-get install pv dialog +( + pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror +) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0 -# Watch the progress of 'dd' with `pv` and `zenity` (apt-get install pv zenity) -(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress +# Watch the progress of dd(1) with pv(1) and zenity(1), both of which can be +# installed with the following command: apt-get install pv zenity +( + pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror +) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress -# Watch the progress of 'dd' with the built-in `progress` functionality (introduced in coreutils v8.24) +# Watch the progress of dd(1) with the built-in `progress` functionality, - +# introduced in coreutils v8.24. dd if=/dev/zero of=/dev/null bs=128M status=progress # DD with "graphical" return dcfldd if=/dev/zero of=/dev/null bs=500K -# This will output the sound from your microphone port to the ssh target computer's speaker port. The sound quality is very bad, so you will hear a lot of hissing. +# This will output the sound from your microphone port to the ssh target +# computer's speaker port. The sound quality is very bad, so you will hear a +# lot of hissing. dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp # Show current progress without interruption (USR1) dd if=/dev/zero of=/dev/null & pid=$! kill -USR1 $pid + +# Create a 1GiB file with nothing but zeros, ready to mkswap(8) it. +dd if=/dev/zero of=/swapfile count=1048576 bs=1024 status=progress From 7d524d8205b2f7d7f80ef96c8319d3859693b2ad Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 29 Feb 2020 23:26:18 +0000 Subject: [PATCH 05/12] Capitalize abbreviations --- sheets/lshw | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/sheets/lshw b/sheets/lshw index 5d4a82e..d547973 100644 --- a/sheets/lshw +++ b/sheets/lshw @@ -1,33 +1,33 @@ # lshw # Get hardware information on Linux -# Generate full information report about all detected hardware +# Generate full information report about all detected hardware. lshw -# Display hardware information in short +# Display brief hardware information. lshw -short -# Display only memory information +# Display only memory information. lshw -short -class memory -# Display processor information +# Display processor information. lshw -class processor -# Display the disk drives with the disk class +# Display the disk drives with the disk class. lshw -short -class disk # Display information about the partitions and controllers also, -# specify the storage and volume class along with the disk class +# specify the storage and volume class along with the disk class. lshw -short -class disk -class storage -class volume -# Network adapter information +# Network adapter information. lshw -class network -# Display the address details of pci, usb, scsi and ide devices +# Display the address details of PCI, USB, SCSI and IDE devices. lshw -businfo -# Generate report in html format +# Generate report in HTML format. lshw -html > hardware.html -# Generate report in xml format +# Generate report in XML format. lshw -html > hardware.html From 2d32a8369c5fd5357513994f0ed52f1f55f2b898 Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 29 Feb 2020 23:32:19 +0000 Subject: [PATCH 06/12] Tweak formatting, code, & wording --- sheets/exec | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/sheets/exec b/sheets/exec index 0e6e030..b529914 100644 --- a/sheets/exec +++ b/sheets/exec @@ -1,17 +1,17 @@ # exec # # Shell builtin command -# It can start a new process to replace the shell, without a new process creation. -# It can make redirections take effect in the current shell +# It can start a new process to replace the shell, without a new process +# creation. It can make redirections take effect in the current shell -# Redirect the output of an entire shell script within the script itself -# Only stdout: +# Redirect all STDOUT from within a script to the given file. exec > foo.log -# Redirect the output of an entire shell script within the script itself -# Stdout and stderr: +# Redirect all of both STDOUT & STDERR from within a script to the given file. exec > foo.log 2>&1 +# Or, if on bash(1), this syntax is also viable: +exec &> foo.log -# Copy output to a log file +# Copy output to a log file, allowing the outputs to still work as usual. exec > >(tee -ia foo.log) exec 2> >(tee -ia foo.log >&2) From 6201e1c5889f8c1e7f670605dc0a0ef5435dab9f Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 29 Feb 2020 23:36:14 +0000 Subject: [PATCH 07/12] Add additional `printf` examples --- sheets/printf | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sheets/printf b/sheets/printf index 853e46a..30d350a 100644 --- a/sheets/printf +++ b/sheets/printf @@ -10,3 +10,9 @@ printf '%s\n' "$USER" # one million, in a human-readable kind of way, by appropriately # comma-separating the units. printf "%'d\n" {1..1000000} + +# Zero-pad a number in order to maintain a width of 3 characters. +printf '%#.3d\n' 12 +# As above, but instead, space-pad the number. Prefix the `3` with a hyphen +# (`-`) to left-align the number, causing the padding to occur on the right. +printf '%3d\n' 12 From 489af58ee99a9255b486e4a6d5e10d9532f482ef Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 29 Feb 2020 23:43:42 +0000 Subject: [PATCH 08/12] Add nifty Awk trick to fetch the total RAM --- sheets/awk | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sheets/awk b/sheets/awk index b6b3e6c..14d8944 100644 --- a/sheets/awk +++ b/sheets/awk @@ -44,3 +44,8 @@ awk '/PATTERN_1/,/PATTERN_2/{print}' [FILE] # Pretty-print a table of an overview of the non-system users on the system. awk -SPF ':' 'BEGIN {printf("%-17s %-4s %-4s %-s\n", "NAME", "UID", "GID", "SHELL")} $3>=1000 && $1!="nobody" {printf("%-17s %-d %-d %-s\n", $1, $3, $4, $7)}' /etc/passwd + +# Display the total amount of MiB of RAM available in the machine. This is also +# a painful but useful workaround to get the units comma-separated, as would be +# doable with Bash's own `printf` built-in. +awk '/^MemTotal:/ {printf("%'"'"'dMiB\n", $2 / 1024)}' From beb310e2aee2f89b463e8005d91d55140ce08bef Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 29 Feb 2020 23:44:02 +0000 Subject: [PATCH 09/12] Add basically a hint to a useful file in `/proc` --- sheets/proc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sheets/proc b/sheets/proc index df35807..1a60b2d 100644 --- a/sheets/proc +++ b/sheets/proc @@ -12,3 +12,6 @@ cat /proc//status # See every file the process has open ls -l /proc//fd + +# Display some useful memory statistics, often used by programs like htop(1). +cat /proc/meminfo From f8b7f7e3c4bfd43e14aa6d85c7541dca2f617a60 Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sat, 29 Feb 2020 23:53:25 +0000 Subject: [PATCH 10/12] Add examples of useless uses of `cat` --- sheets/cat | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sheets/cat b/sheets/cat index be43b06..a0b0dc8 100644 --- a/sheets/cat +++ b/sheets/cat @@ -1,2 +1,16 @@ # POSIX-ly correct way in which to cat(1); see cat(1posix). cat -u [FILE_1 [FILE_2] ...] + +# Output a file, expanding any escape sequences (default). Using this short +# one-liner let's you view the boot log how it was show at boot-time. +cat /var/log/boot.log + +# This is an ever-popular useless use of cat. +cat /etc/passwd | grep '^root' +# The sane way: +grep '^root' /etc/passwd + +# If in bash(1), this is often (but not always) a useless use of cat(1). +Buffer=`cat /etc/passwd` +# The sane way: +Buffer=`< /etc/passwd` From 4df5219c669f0f0ad96cac90e3278adaf44c47ad Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sun, 1 Mar 2020 00:02:13 +0000 Subject: [PATCH 11/12] Convert tabs to 4 spaces for consistency This was probably my fault to begin with, as I'm a big fan of tabs. My bad. It just occurred to that not only do I have my tabs set to 4 columns, but some people may have wonky formatting because of whichever setting we have for our tabs. --- sheets/dd | 8 ++++---- sheets/i3 | 12 +++++++----- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/sheets/dd b/sheets/dd index 9a5633a..5caa198 100644 --- a/sheets/dd +++ b/sheets/dd @@ -6,20 +6,20 @@ dd if=/dev/urandom of=/tmp/test.txt count=2 bs=512 dd if=/dev/zero of=/dev/null bs=4KB & export dd_pid=`pgrep '^dd'` while [[ -d /proc/$dd_pid ]]; do - kill -USR1 $dd_pid && sleep 1 - clear + kill -USR1 $dd_pid && sleep 1 + clear done # Watch the progress of dd(1) with pv(1) and dialog(1), both of which can be # installed with the following command: apt-get install pv dialog ( - pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror + pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror ) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0 # Watch the progress of dd(1) with pv(1) and zenity(1), both of which can be # installed with the following command: apt-get install pv zenity ( - pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror + pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror ) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress # Watch the progress of dd(1) with the built-in `progress` functionality, - diff --git a/sheets/i3 b/sheets/i3 index 31fb50c..f3b435a 100644 --- a/sheets/i3 +++ b/sheets/i3 @@ -101,17 +101,19 @@ bindsym $mod+4 workspace $ws4 bindsym $mod+Shift+R exec custom-script-in-path.sh --flag1 --flag2 bindcode 172 exec playerctl play-pause -# Always execute code when i3 starts: +# Execute code when i3 starts, but only once per session: exec --no-startup-id ~/.config/polybar/launch.sh +# Always execute code when i3 starts, even if it's simply restarted: +exec_always --no-startup-id ~/.config/polybar/launch.sh # One can make special modes (much like resize mode) set $gamingMode "gaming_mode" bindsym $mod+g mode $gamingMode mode $gamingMode { - # Insert declarations for this mode - # Useful when normal keybindings fight with keybindings of your games - # Don't forget to add option to return from this mode! - bindsym $mod+Escape mode default + # Insert declarations for this mode. Useful when normal keybindings fight + # with keybindings of your games. Don't forget to add option to return from + # this mode! + bindsym $mod+Escape mode default } # Move workspace between multiple monitors From ade78aaafbfafb5bf951134e818c7f613b972abc Mon Sep 17 00:00:00 2001 From: terminalforlife Date: Sun, 1 Mar 2020 00:21:26 +0000 Subject: [PATCH 12/12] Mass-replace tabs with 4-width spacing This seems to be the predominant choice, and matches the last commit I just made, so I went ahead and converted them all, and changed any, - for example, 2-space indents. Let me know if this is undesired. To understand why I chose to do this, please refer to the previous commit's message. --- sheets/_cpp/func | 15 +++---- sheets/_cpp/pointers | 21 ++++++--- sheets/_elm/hello | 8 ++-- sheets/_go/Structs | 2 +- sheets/_go/func | 18 ++++---- sheets/_go/if | 38 ++++++++-------- sheets/_go/slices | 34 +++++++++----- sheets/_python/func | 48 ++++++++++---------- sheets/_python/lambda | 24 +++++----- sheets/_python/loops | 64 +++++++++++++-------------- sheets/_scala/ManipulatingCollections | 18 ++++---- sheets/_scala/PatternMatching | 30 ++++++------- 12 files changed, 168 insertions(+), 152 deletions(-) diff --git a/sheets/_cpp/func b/sheets/_cpp/func index e75b27b..e619194 100644 --- a/sheets/_cpp/func +++ b/sheets/_cpp/func @@ -1,29 +1,28 @@ -// ### Functions -// a simple function +// ### Functions +// a simple function void functionName() {} // function with parameters of integers void functionName(int param1, int param2) {} -// return type declaration -int functionName() { +// return type declaration +int functionName() { return 420; } -// Return multiple values at once +// Return multiple values at once // (C++ uses pairs [ 2 values ] and tuple [ more than 2 values ]) // Please refer pairs and tuple respectively for more information std::tuple functionName() { - return std::make_tuple( double1, double2 ); + return std::make_tuple( double1, double2 ); } pair result = functionName(); std::cout << result.first << std::endl; std::cout << result.second << std::endl; -// Pass by reference (the caller and the callee use the same variable for the parameter) +// Pass by reference (the caller and the callee use the same variable for the parameter) int functionName(int &referenceName) {} // Pass by value (the caller and callee have two independent variables with the same value) int functionName(int valueName) {} - diff --git a/sheets/_cpp/pointers b/sheets/_cpp/pointers index 5cea4a7..8466cff 100644 --- a/sheets/_cpp/pointers +++ b/sheets/_cpp/pointers @@ -1,8 +1,15 @@ -int *int_Ptr; // Declare a pointer variable called iPtr pointing to an int (an int pointer) - // It contains an address. That address holds an int value. -double *double_Ptr; // Declare a pointer of type double. +// Declare a pointer variable called iPtr pointing to an int (an int pointer) +// It contains an address. That address holds an int value. +int *int_Ptr; -int a = 5; // Initializes a to the integer value 5 -int *int_Ptr = &a // Set int_Ptr which is an int pointer to the address of a -std::cout << int_Ptr; // Returns the address of a -std::cout << *int_Ptr; // Returns 5 because it dereference the pointer to retrieve the value of a. +// Declare a pointer of type double. +double *double_Ptr; + +// Initializes a to the integer value 5 +int a = 5; +// Set int_Ptr which is an int pointer to the address of `a`. +int *int_Ptr = &a +// Returns the address of `a`. +std::cout << int_Ptr; +// Returns 5 because it dereference the pointer to retrieve the value of `a`. +std::cout << *int_Ptr; diff --git a/sheets/_elm/hello b/sheets/_elm/hello index 4449b86..496aad4 100644 --- a/sheets/_elm/hello +++ b/sheets/_elm/hello @@ -2,12 +2,12 @@ # Go to http://elm-lang.org/install # and download the appropriate installer for your system. # To create a project: -# mkdir hello -# cd hello -# elm package install elm-lang/html +# mkdir hello +# cd hello +# elm package install elm-lang/html # after that create Hello.elm in this directory # To start: -# elm reactor +# elm reactor # Read more here: # https://www.elm-tutorial.org/en/01-foundations/01-hello.html module Hello exposing (..) diff --git a/sheets/_go/Structs b/sheets/_go/Structs index f77a88b..d26b6d0 100644 --- a/sheets/_go/Structs +++ b/sheets/_go/Structs @@ -34,5 +34,5 @@ func (v *Vertex) add(n float64) { // **Anonymous structs:** // Cheaper and safer than using `map[string]interface{}`. point := struct { - X, Y int + X, Y int }{1, 2} diff --git a/sheets/_go/func b/sheets/_go/func index b002a22..bad611c 100644 --- a/sheets/_go/func +++ b/sheets/_go/func @@ -66,19 +66,19 @@ func outer() (func() int, int) { // ### Variadic Functions func main() { - fmt.Println(adder(1, 2, 3)) // 6 - fmt.Println(adder(9, 9)) // 18 + fmt.Println(adder(1, 2, 3)) // 6 + fmt.Println(adder(9, 9)) // 18 - nums := []int{10, 20, 30} - fmt.Println(adder(nums...)) // 60 + 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 + total := 0 + for _, v := range args { // Iterates over the arguments whatever the number. + total += v + } + return total } diff --git a/sheets/_go/if b/sheets/_go/if index 3e44f02..76975c8 100644 --- a/sheets/_go/if +++ b/sheets/_go/if @@ -1,23 +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 - } + // 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) - } + // Type assertion inside if + var val interface{} + val = "foo" + if str, ok := val.(string); ok { + fmt.Println(str) + } } diff --git a/sheets/_go/slices b/sheets/_go/slices index 9d248f8..8ed1328 100644 --- a/sheets/_go/slices +++ b/sheets/_go/slices @@ -1,18 +1,28 @@ -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"] +// declare a slice - similar to an array, but length is unspecified +var a []int +// declare and initialize a slice (backed by the array given implicitly) +var a = []int {1, 2, 3, 4} +// shorthand +a := []int{1, 2, 3, 4} +// ["a", "b", "c"] +chars := []string{0:"a", 2:"c", 1: "b"} -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 +// creates a slice (view of the array) from index lo to hi-1 +var b = a[lo:hi] +// slice from index 1 to 3 +var b = a[1:4] +// missing low index implies 0 +var b = a[:3] +// missing high index implies len(a) +var b = a[3:] +// append items to slice a +a = append(a,17,3) +// concatenate slices a and b +c := append(a,b...) // create a slice with make -a = make([]byte, 5, 5) // first arg length, second capacity -a = make([]byte, 5) // capacity is optional +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{"Лайка", "Белка", "Стрелка"} diff --git a/sheets/_python/func b/sheets/_python/func index 1c69349..ca45aab 100644 --- a/sheets/_python/func +++ b/sheets/_python/func @@ -1,40 +1,40 @@ # Simple function def functionName(): - return True + return True # Function with parameters -def functionName(a, b): - if a < b: - return a - else: - return b +def functionName(a, b): + if a < b: + return a + else: + return b # Return multiple values -def functionName(a, b, c): - return a, b, c # Returns a tuple - return {'return_a':a, 'return_b':b ,'return_c':c } # Returns a dictionary +def functionName(a, b, c): + return a, b, c # Returns a tuple + return {'return_a':a, 'return_b':b ,'return_c':c } # Returns a dictionary # Function with default parameters -def functionName(a=0, b=1): - print(a, b) -functionName() # 0 1 -functionName(3) # 3 1 -functionName(3, 4) # 3 4 +def functionName(a=0, b=1): + print(a, b) +functionName() # 0 1 +functionName(3) # 3 1 +functionName(3, 4) # 3 4 # Calling parameters by name -def functionName(a, b, c): - print(a, b, c) -functionName(0, 1, 2) # 0 1 2 -functionName(a=2, c=3, b=4) # 2 4 3 -functionName(2, 3, c=4) # 2 3 4 +def functionName(a, b, c): + print(a, b, c) +functionName(0, 1, 2) # 0 1 2 +functionName(a=2, c=3, b=4) # 2 4 3 +functionName(2, 3, c=4) # 2 3 4 # Arbitrary number of parameters def functionName(*args): - ... -functionName(*[1, 2]) # Equivalent of functionName(1, 2) -functionName(*[1, 2, 3]) # Equivalent of functionName(1, 2, 3) + ... +functionName(*[1, 2]) # Equivalent of functionName(1, 2) +functionName(*[1, 2, 3]) # Equivalent of functionName(1, 2, 3) # Arbitrary number of parameters with arbitrary name def functionName(**kwargs): - ... -functionName(**{'a' : 3, 'b' : 4}) # Equivalent of functionName(a=3, b=4) + ... +functionName(**{'a' : 3, 'b' : 4}) # Equivalent of functionName(a=3, b=4) diff --git a/sheets/_python/lambda b/sheets/_python/lambda index f99e2ca..70ab719 100644 --- a/sheets/_python/lambda +++ b/sheets/_python/lambda @@ -1,33 +1,33 @@ # Lambda are anonymous functions in Python by using the keyword lambda -# Therefore they are not bound to a name +# Therefore they are not bound to a name -# Simple Lambda Function +# Simple Lambda Function a = lambda parameter: parameter + 40 # print (a(2)) # Outputs 42 # Lambda Functions Inside Real Functions -def subtract_func(n) : +def subtract_func(n) : return lambda x: x - n # a = subtract_func(1) # Sets n to 1 for a -b = subtract_func(2) # Sets n to 2 for b +b = subtract_func(2) # Sets n to 2 for b # print(a(-4)) # Outputs -5 ( -5 = -4 - 1 ) print(b(-2)) # Outputs -4 ( -4 = -2 - 2 ) -# Lambda Function with Multiple Parameters -f = lambda x, y : x + y +# Lambda Function with Multiple Parameters +f = lambda x, y : x + y # print( f(1,1) ) # Outputs 2 ( 1 + 1 ) # map() + lambda functions -a = [1, 2, 3, 4, 5] -b = [1, 2, 3, 4, 5] +a = [1, 2, 3, 4, 5] +b = [1, 2, 3, 4, 5] # -r = map(lambda x,y : x+y, a,b) # map() will return an iterator -r_list = list(r) # listify r -print(r_list) # prints [2, 4, 6, 8, 10] +r = map(lambda x,y : x+y, a,b) # map() will return an iterator +r_list = list(r) # listify r +print(r_list) # prints [2, 4, 6, 8, 10] # filter() + lambda functions # Program to filter out only the even items from a list @@ -35,4 +35,4 @@ my_list = [1, 5, 4, 6, 8, 11, 3, 12] # new_list = list(filter(lambda x: (x%2 == 0) , my_list)) # -print(new_list) # Output: [4, 6, 8, 12] +print(new_list) # Output: [4, 6, 8, 12] diff --git a/sheets/_python/loops b/sheets/_python/loops index 7771640..291b2b9 100644 --- a/sheets/_python/loops +++ b/sheets/_python/loops @@ -1,12 +1,12 @@ # Basic conditional: if x > 0: - print(x) + print(x) # 'if else' -if x > 0: - print(x) -else: - print(-x) +if x > 0: + print(x) +else: + print(-x) #ternary operator parity = 'even' if x % 2 == 0 else 'odd' @@ -14,69 +14,69 @@ parity = 'even' if x % 2 == 0 else 'odd' ''' # Equivalent of: if x % 2 == 0: - parity = 'even' + parity = 'even' else: - parity = 'odd' + parity = 'odd' ''' # multiple conditions: if x > 0: - print(x) + print(x) elif x == 0: - print(420) + print(420) elif x == 1: - print(421) + print(421) else: - print(-x) + print(-x) # Basic 'for' loop: for i in range(6): - print(i) #prints 0, 1, 2, 3, 4, 5 - + print(i) #prints 0, 1, 2, 3, 4, 5 +# for i in range(2, 6): - print(i) #prints 2, 3, 4, 5 - + print(i) #prints 2, 3, 4, 5 +# for i in range(3, 10, 2): - print(i) #prints 3, 5, 7, 9 + print(i) #prints 3, 5, 7, 9 # Iterating through collections: for i in [0, 1, 1, 2, 3, 5]: - print(i) #prints 0, 1, 1, 2, 3, 5 - + print(i) #prints 0, 1, 1, 2, 3, 5 +# for i in 'qwerty': - print(i) #prints q, w, e, r, t, y + print(i) #prints q, w, e, r, t, y # 'for else': for i in x: - if i == 0: - break + if i == 0: + break else: - print('not found') + print('not found') ''' # Equivalent of: flag = False for i in x: - if i == 0: - flag = True - break + if i == 0: + flag = True + break if not flag: - print('not found') + print('not found') ''' # Basic 'while' loop: x = 0 while x < 6: - print(i) - x += 2 + print(i) + x += 2 # prints 0, 2, 4 # No 'do while' loop in Python. # Equivalent with 'while' loop: x = 4 while True: - print(x) - x += 1 - if x >= 4: - break + print(x) + x += 1 + if x >= 4: + break # prints 4 diff --git a/sheets/_scala/ManipulatingCollections b/sheets/_scala/ManipulatingCollections index b2f6999..6b359b4 100644 --- a/sheets/_scala/ManipulatingCollections +++ b/sheets/_scala/ManipulatingCollections @@ -11,8 +11,8 @@ l map (_ * 2) //returns List(2,4,6,8,10) // allows the ability to provide different map functions for different discrete cases // this example will increment odd numbers by one, but double even numbers l map { //note: the curly brackets allow us to make the map multi-line and use 'case' statements (see PatternMatching) - case num if num % 2 == 0 => num * 2 - case other => other + 1 + case num if num % 2 == 0 => num * 2 + case other => other + 1 } //returns List(2,4,4,8,6) // filter @@ -26,7 +26,7 @@ l filter (_ % 2 == 0) //returns List(1,3,5) // this is like a combination of filter and map // this example shows that collect essentially filters by "i < 3" then maps with "_ + 20" l collect { //note: collect requires a partial function, so we have to use curly brackets and 'case' statements - case i if i < 3 => i + 20 + case i if i < 3 => i + 20 } //returns List(21, 22) // find @@ -66,12 +66,12 @@ List(List(1,2,3), List(4,5)).flatten //returns List(1,2,3,4,5) // maps then flattens in one function // in this example, we will map and flatMap a List[Int] using a function that turns each Int into a List[Int] List(1,2,3) map { - num => List(num, num) + num => List(num, num) } -// for this example, mapping returns List(List(1,1),List(2,2),List(3,3)) +// for this example, mapping returns List(List(1,1),List(2,2),List(3,3)) //vs List(1,2,3) flatMap { - num => List(num, num) + num => List(num, num) } // returns List(1,1,2,2,3,3) // isEmpty @@ -89,12 +89,12 @@ oneToSix diff (fourToNine) //returns List(1,2,3) fourToNine diff (oneToSix) //returns List(7,8,9) // intersect -// returns the "intersection" of two collections, these are the elements that exist in both collections +// returns the "intersection" of two collections, these are the elements that exist in both collections val oneToSix = List(1, 2, 3, 4, 5, 6) val fourToNine = List(4, 5, 6, 7, 8, 9) oneToSix intersect (fourToNine) //returns List(4,5,6) fourToNine intersect (oneToSix) //returns List(4,5,6) - + // union // returns the concatenation of the two lists val oneToSix = List(1, 2, 3, 4, 5, 6) @@ -199,4 +199,4 @@ List(1,2,3).tail //returns List(2,3), same as List(1,2,3).drop(1) // last -List(1,2,3).last //returns 3 \ No newline at end of file +List(1,2,3).last //returns 3 diff --git a/sheets/_scala/PatternMatching b/sheets/_scala/PatternMatching index 325cb2a..38d1db0 100644 --- a/sheets/_scala/PatternMatching +++ b/sheets/_scala/PatternMatching @@ -1,21 +1,21 @@ // 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 +(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") + 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") + 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. @@ -23,24 +23,24 @@ Some(3) match { // GOOD val UppercaseVal = 42 Some(3) match { - case Some(UppercaseVal) => println("42") - case _ => println("Not 42") + case Some(UppercaseVal) => println("42") + case _ => println("Not 42") } // Creating an alias for a match // This will maintain the original value passed into the match function, using the '@' symbol, and print "Matched Some(3)" Some(3) match { - case foundSome @ Some(_) => println("Matched " + foundSome) - case _ => println("Matched nothing") + case foundSome @ Some(_) => println("Matched " + foundSome) + case _ => println("Matched nothing") } // Case Classes // This method allows you to match on any combination of properties of a case class case class Example(a: Int, b: String, c: Boolean) Example(1, "word", true) match { - case Example(3, _, _) => println("Matches any Example where a = 3") - case Example(_, "foo", _) => println("Matches any Example where b = foo") - case Example(_, _, false) => println("Matches any Example where c = false") - case Example(1, "word", true) => println("Matches our Example") - case Example(_, _, _) => println("Matches any other Example") + case Example(3, _, _) => println("Matches any Example where a = 3") + case Example(_, "foo", _) => println("Matches any Example where b = foo") + case Example(_, _, false) => println("Matches any Example where c = false") + case Example(1, "word", true) => println("Matches our Example") + case Example(_, _, _) => println("Matches any other Example") }