Merge pull request #99 from terminalforlife/master

More Comments & Code Tweaks & Additions
pull/103/head
Igor Chubin 5 years ago committed by GitHub
commit 4a1a6d1e77
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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

@ -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<double, double> functionName() {
return std::make_tuple( double1, double2 );
return std::make_tuple( double1, double2 );
}
pair<double,double> 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) {}

@ -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;
}

@ -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;

@ -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 (..)

@ -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

@ -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 <buffer size> unread values have been written.
ch := make(chan int, 100)
// Non-buffered channels block.

@ -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)

@ -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}

@ -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
nums := []int{10, 20, 30}
fmt.Println(adder(nums...)) // 60
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
total := 0
for _, v := range args { // Iterates over the arguments whatever the number.
total += v
}
return total
}

@ -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)

@ -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)
}
}

@ -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{"Лайка", "Белка", "Стрелка"}

@ -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": ...
}

@ -8,7 +8,7 @@ var newA = myArray.slice(0);
'<b>A</b>'.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

@ -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.
*)
*)

@ -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";

@ -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

@ -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

@ -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)

@ -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]

@ -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

@ -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')

@ -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();

@ -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)

@ -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
List(1,2,3).last //returns 3

@ -23,7 +23,7 @@ class C(var x: R) {
//
// alternative constructor
def this = this(42)
}
}
// anonymous class
new{ ... }

@ -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")
}

@ -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

@ -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,31 +16,36 @@ 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<NF; F++){if($F~/^\$[A-Z_]+$/){A[$F]++}}} END{for(I in A){X=substr(I, 2, length(I)); printf("%s\n", X)}}' [FILE]
# Output only lines from FILE between PATTERN_1 and PATTERN_2. Good for log files.
# Output only lines from FILE between PATTERN_1 and PATTERN_2. Good for logs.
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)}'

@ -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

@ -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

@ -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

@ -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:

@ -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`

@ -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

@ -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

@ -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

@ -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

@ -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)

@ -1,10 +1,5 @@
# 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]
# Usage:
# fdisk [options] <disk> change partition table

@ -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

@ -1,4 +1,4 @@
# identify
# identify
#
# describes the format and characteristics of one or more image files

@ -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

@ -58,7 +58,7 @@ jq 'flatten(1)'
# Converting to csv
jq '.[] | [.foo, .bar] | @csv' -r
#
#
# [{ "foo": 1, "bar": 2, "baz":3 }]
# => 1,2

@ -1,5 +1,5 @@
# jslint
#
#
# The JavaScript Code Quality Tool written by Dougls Crockford
# to install jslint

@ -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

@ -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

@ -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 {//} {}

@ -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

@ -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

@ -1,4 +1,4 @@
# objdump
# objdump
# program for displaying various information about object files
# Display the contents of the overall file header

@ -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

@ -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

@ -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:

@ -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

@ -12,3 +12,6 @@ cat /proc/<pid>/status
# See every file the process has open
ls -l /proc/<pid>/fd
# Display some useful memory statistics, often used by programs like htop(1).
cat /proc/meminfo

@ -10,10 +10,10 @@ python -m SimpleHTTPServer
# Python 3
python -m http.server 8000
# SMTP-Server for debugging, messages will be discarded, and printed on stdout.
# SMTP-Server for debugging, messages will be discarded, and printed on STDOUT.
python -m smtpd -n -c DebuggingServer localhost:1025
# Pretty print a json
# Pretty print a JSON
python -mjson.tool
# Zen of Python

@ -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

@ -1,5 +1,5 @@
# rustup
# The Rust toolchain installer
# The Rust toolchain installer
# update rustup toolchain
rustup update

@ -22,7 +22,7 @@ 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
# If both drives will be in the same computer, you need to randomize the GUIDs after cloning
sgdisk -G /dev/sdc

@ -1,7 +1,7 @@
# siteciphers (Bash-Snippets)
# Checks the available ciphers for the SSL of an https site.
# Checks the available ciphers for the SSL of an HTTPS site.
# Determine the available SSL ciphers for an https website
# Determine the available SSL ciphers for an HTTPS website
siteciphers github.com
# Determine the ciphers setting the delay between requests (default is 1 sec)

@ -1,6 +1,6 @@
# This is a shell builtin available in bash, but not in the Bourne Shell (`sh`).
# The contents of FILE (assuming shell script) will be sourced into the current
# session, allowing external use of things like its functions and variables.
# This is a shell built-in available in Bash, but not in the Bourne Shell
# (`sh`). The contents of FILE (assuming shell script) will be sourced into the
# current session, allowing external use of its functions, variables, etc.
source FILE
# The above can be written in short-hand, for the same effect:
. FILE

@ -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

@ -1,28 +1,30 @@
# svgo
#
# SVG Optimizer: a Nodejs-based tool for optimizing Scalable Vector Graphics files.
# It applies a series of transformation rules (plugins), which can be toggled individually.
# SVG Optimizer: a Node.js-based tool for optimizing Scalable Vector Graphics
# files. It applies a series of transformation rules (plugins), which can be
# toggled individually.
# Optimize a file using the default plugins (overwrites the original file):
# Optimize a file using the default plugins, overwriting the original file.
svgo test.svg
# Optimize a file and save the result to another file:
# Optimize a file and save the result to another file.
svgo test.svg test.min.svg
# Optimize all SVG files within a folder (overwrites the original files):
svgo -f path/to/folder/with/svg/files
# Optimize all SVG files within a directory, overwriting the original files.
svgo -f path/to/directory/with/svg/files
# Optimize all SVG files within a folder and save the resulting files to another folder:
svgo -f path/to/input/folder -o path/to/output/folder
# Optimize all SVG files within a directory and save the resulting files to
# another directory.
svgo -f path/to/input/dir -o path/to/output/dir
# Optimize SVG content passed from another command, and save the result to a file:
# Optimize SVG content passed from another command, then save result to a file.
cat test.svg | svgo -i - -o test.min.svg
# Optimize a file and print out the result:
# Optimize a file and print out the result.
svgo test.svg -o -
# Optimize a file making sure a given plugin is enabled:
# Optimize a file making sure a given plugin is enabled.
svgo --enable=plugin_name
# Show available plugins:
# Show available plugins.
svgo --show-plugins

@ -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

@ -1,10 +1,10 @@
# weather (Bash-Snippets)
# Provides a 3 day forecast on your current location or a specified location
# Provides a 3-day forecast on your current location or a specified location
# Get a 3 day forecast for your current location as determined by your ip address
# Get 3-day forecast for your current location as determined by your IP address
weather
# Get a 3 day forecast for any location
# Get 3-day forecast for any location
weather Tokyo
# Get the current moon phase

@ -1,5 +1,5 @@
# xfs_repair
# repair an XFS filesystem
# repair an XFS filesystem
# rapair a XFS filesystem
xfs_repair /dev/dm-0

@ -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"

@ -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

Loading…
Cancel
Save