Compare commits

..

4 Commits

Author SHA1 Message Date
Raul Villora Valencia
049441ac0c Merge 7f1144c56a into 2aee46f169 2024-05-23 02:37:52 -03:00
Raúl Villora Valencia
7f1144c56a Create java.txt
Java Cheatsheet
2019-01-23 12:29:20 +01:00
Raúl Villora Valencia
8840648ff4 Created a cheatsheet for the Haskell language. 2019-01-18 16:48:15 +01:00
Raúl Villora Valencia
52d590f1c3 Merge pull request #1 from LeCoupa/master
Update from original
2019-01-18 16:40:35 +01:00
15 changed files with 947 additions and 253 deletions

View File

@@ -16,69 +16,3 @@ GRANT ALL PRIVILEGES ON prospectwith.* TO 'power'@'localhost' WITH GRANT OPTION;
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; # Create user CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; # Create user
mysql -u root -pmypassword -e "MY SQL QUERY" &>> query.log & disown # Run SQL query in the background mysql -u root -pmypassword -e "MY SQL QUERY" &>> query.log & disown # Run SQL query in the background
# *****************************************************************************
# Database and Table Operations
# *****************************************************************************
CREATE DATABASE database_name; # Create a new database
DROP DATABASE database_name; # Delete a database
CREATE TABLE table_name (column1 datatype, column2 datatype, ...); # Create a new table
DROP TABLE table_name; # Delete a table
SHOW TABLES; # Display all tables in the current database
DESCRIBE table_name; # Show the structure of a table
# *****************************************************************************
# Data Manipulation
# *****************************************************************************
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...); # Insert data into a table
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; # Update existing data in a table
DELETE FROM table_name WHERE condition; # Delete data from a table
SELECT column1, column2, ... FROM table_name WHERE condition; # Select data from a table
# *****************************************************************************
# Backup and Restore
# *****************************************************************************
mysqldump -u username -p database_name table1 table2 > file.sql # Backup specific tables
mysql -u username -p database_name < file.sql # Restore specific tables
# *****************************************************************************
# User Management and Security
# *****************************************************************************
REVOKE privilege_type ON database_name.table_name FROM 'username'@'hostname'; # Revoke privileges from a user
DROP USER 'username'@'hostname'; # Delete a user
ALTER USER 'username'@'hostname' IDENTIFIED BY 'newpassword'; # Reset a user's password
# *****************************************************************************
# Performance and Maintenance
# *****************************************************************************
OPTIMIZE TABLE table_name; # Optimize a table
ANALYZE TABLE table_name; # Analyze a table for key distribution and storage optimization
CHECK TABLE table_name; # Check a table for errors
REPAIR TABLE table_name; # Repair a corrupted table
# *****************************************************************************
# Advanced Queries
# *****************************************************************************
SELECT ... FROM table1 JOIN table2 ON table1.column = table2.column; # Perform a join operation between two tables
SELECT ... FROM (SELECT ... FROM table_name) AS subquery; # Use a subquery within another query
SELECT column, COUNT(*) FROM table_name GROUP BY column; # Group results and use aggregate functions
# *****************************************************************************
# System Information
# *****************************************************************************
SELECT VERSION(); # Show the current version of MySQL
SELECT User, Host FROM mysql.user; # List all current MySQL users
# *****************************************************************************
# Miscellaneous
# *****************************************************************************
SET GLOBAL general_log = 'ON'; # Enable query logging
SHOW FULL PROCESSLIST; # Show the last queries executed in MySQL

View File

@@ -3,7 +3,7 @@ CHEATSHEET C#
1. Data Types 1. Data Types
Primitive Size Example Primitive Size Example
String 2 bytes/char s = "reference"; String 2 bytes/char s = "reference";
bool b = true; bool b = true;
char 2 bytes ch = 'a'; char 2 bytes ch = 'a';
@@ -16,20 +16,20 @@ CHEATSHEET C#
decimal 16 bytes val = 70.0M; decimal 16 bytes val = 70.0M;
2. Arrays 2. Arrays
2.1 Declaration 2.1 Declaration
//Initiliazed using a list defined with curly braces //Initiliazed using a list defined with curly braces
int[] nameArray = {100, 101, 102}; int[] nameArray = {100, 101, 102};
//Define an empty array //Define an empty array
int[] nameArray = new int[3]; // 3 rows and 2 columns int[] nameArray = new int[3]; // 3 rows and 2 columns
//To access a specific item in the array //To access a specific item in the array
int[] nameArray = new int[10]; int[] nameArray = new int[10];
int firstNumber = nameArray[0]; int firstNumber = nameArray[0];
nameArray[1] = 20; nameArray[1] = 20;
//Multidimensional arrays //Multidimensional arrays
int [,] matrix = new int [2,2] int [,] matrix = new int [2,2]
matrix[0,0] = 1; matrix[0,0] = 1;
@@ -40,26 +40,26 @@ CHEATSHEET C#
int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } }; int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } };
2.2 Array Operations 2.2 Array Operations
//Sort ascending //Sort ascending
Array.Sort(nameArray); Array.Sort(nameArray);
//Sort begins at element 6 and sorts 20 elements //Sort begins at element 6 and sorts 20 elements
Array.Sort(nameArray,6,20); Array.Sort(nameArray,6,20);
//Use 1 array as a key & sort 2 arrays //Use 1 array as a key & sort 2 arrays
string[] values = {"Juan", "Victor", "Elena"}; string[] values = {"Juan", "Victor", "Elena"};
string[] keys = {"Jimenez", "Martin", "Ortiz"}; string[] keys = {"Jimenez", "Martin", "Ortiz"};
Array.Sort(keys, values); Array.Sort(keys, values);
//Clear elements in array (array, first element, # elements) //Clear elements in array (array, first element, # elements)
Array.Clear(nameArray, 0, nameArray.Length); Array.Clear(nameArray, 0, nameArray.Length);
//Copy elements from one array to another //Copy elements from one array to another
Array.Copy(scr, target, numOfElements); Array.Copy(scr, target, numOfElements);
3. String Operations 3. String Operations
//To concatenate between strings, use the plus operator: //To concatenate between strings, use the plus operator:
string firstName = "Erin"; string firstName = "Erin";
string lastName = "Roger"; string lastName = "Roger";
@@ -68,27 +68,27 @@ CHEATSHEET C#
//To add one string to another, use the += operator: //To add one string to another, use the += operator:
string secondLastName = "Green"; string secondLastName = "Green";
string fullName += secondLastName; string fullName += secondLastName;
//ToString function //ToString function
//It converts an object to its string representation so that it is suitable for display //It converts an object to its string representation so that it is suitable for display
Object.ToString(); Object.ToString();
//String formatting //String formatting
//Each additional argument to the function can be referred to in the string using the brackets operator with the index number. //Each additional argument to the function can be referred to in the string using the brackets operator with the index number.
String.Format(String format, Object arg0); String.Format(String format, Object arg0);
format - A composite format string that includes one or more format items format - A composite format string that includes one or more format items
arg0 - The first or only object to format arg0 - The first or only object to format
//Substring //Substring
//Returns a part of the string, beginning from the index specified as the argument. Substring also accepts a maximum length for the substring //Returns a part of the string, beginning from the index specified as the argument. Substring also accepts a maximum length for the substring
String.Substring(beginAt); String.Substring(beginAt);
String.Substring(beginAt, maximum); String.Substring(beginAt, maximum);
//Replace //Replace
string newStr = oldStr.Replace("old","new"); string newStr = oldStr.Replace("old","new");
//IndexOf //IndexOf
//Finds the first occurrence of a string in a larger string //Finds the first ocurrence of a string in a larger string
//Returns -1 if the string is not found //Returns -1 if the string is not found
String.IndexOf(val, start, num) String.IndexOf(val, start, num)
val - string to search for val - string to search for
@@ -102,7 +102,7 @@ CHEATSHEET C#
String.Split(Char[]); String.Split(Char[]);
//ToCharArray //ToCharArray
//Places selected characters in a string in a char array //Places selected characteres in a string in a char array
String str = "AaBbCcDd"; String str = "AaBbCcDd";
//create array of 8 vowels //create array of 8 vowels
var chars = str.ToCharArray(); var chars = str.ToCharArray();
@@ -132,11 +132,11 @@ CHEATSHEET C#
DateTime nextYear = DateTime.AddYears(1); DateTime nextYear = DateTime.AddYears(1);
6. TimeSpan 6. TimeSpan
6.1 TimeSpan Constructor 6.1 TimeSpan Constructor
TimeSpan(hour, minute, sec) TimpeSpan(hour, minute, sec)
TimeSpan timeS = new TimeSpan(10, 14, 50); TimeSpan timeS = new TimeSpan(10, 14, 50);
TimeSpan timeS_Hours = TimeSpan.FromDays(3640); TimeSpan timeS_Hours = TimeSpan.FromDays(3640);
@@ -144,8 +144,8 @@ CHEATSHEET C#
Format item syntax: {index[,alignment][:format string]} Format item syntax: {index[,alignment][:format string]}
index - Specifies element in list of values to which format is applied index - Specifies element in list of values to which format is applied
alignment - Indicates minimum width (in characters) to display value aligment - Indicates minimun width (in characters) to display value
format string - Contains the code which specifies the format of the displayed value format string - Contains the code which specififes the format of the displayed value
7.1 Numeric 7.1 Numeric
@@ -168,7 +168,7 @@ CHEATSHEET C#
csc -define:DEBUG -optimize -out:File2.exe *.cs -> Compiles all the C# files in the current directory with optimizations enabled and defines the DEBUG symbol. The output is File2.exe csc -define:DEBUG -optimize -out:File2.exe *.cs -> Compiles all the C# files in the current directory with optimizations enabled and defines the DEBUG symbol. The output is File2.exe
csc -target:library -out:File2.dll -warn:0 -nologo -debug *.cs -> Compiles all the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed csc -target:library -out:File2.dll -warn:0 -nologo -debug *.cs -> Compiles all the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed
csc -target:library -out:Something.xyz *.cs -> Compiles all the C# files in the current directory to Something.xyz (a DLL) csc -target:library -out:Something.xyz *.cs -> Compiles all the C# files in the current directory to Something.xyz (a DLL)
8.1 Compiler Options Listed 8.1 Compiler Options Listed
Option Purpose Option Purpose
@@ -260,21 +260,21 @@ CHEATSHEET C#
10. Loop 10. Loop
10.1 While 10.1 While
while (condition) {body} while (condition) {body}
10.2 Do while 10.2 Do while
do {body} while condition; do {body} while condition;
10.3 For 10.3 For
for (initializer; termination condition; iteration;) { for (initializer; termination condition; iteration;) {
//statements //statements
} }
10.4 For each 10.4 For each
foreach (type identifier in collection) { foreach (type identifier in collection) {
//statements //statements
} }
@@ -293,7 +293,7 @@ CHEATSHEET C#
[access modifier] className (parameters) [:initializer] [access modifier] className (parameters) [:initializer]
initializer -base calls constructor in base class. initializer -base calls constructor in base class.
this calls constructor within class. this calls constuctor within class.
public class nameClass : Initializer { public class nameClass : Initializer {
public className(dataType param1 , dataType param2, ...) : base(param1, param2) public className(dataType param1 , dataType param2, ...) : base(param1, param2)
@@ -313,8 +313,8 @@ CHEATSHEET C#
abstract must be implemented by subclass abstract must be implemented by subclass
Passing parameters: Passing parameters:
1. By default, parameters are passed by value 1. By default, parametres are passed by value
2. Passing by reference: ref, in and out modifiers 2. Passing by reference: ref, in and out modifers
To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier
@@ -331,9 +331,9 @@ CHEATSHEET C#
12. Struct 12. Struct
12.1 Defining a structure 12.1 Defining a structure
[attribute][modifier] struct name [:interfaces] { struct-body } [attribute][modifier] struct name [:interfaces] { struct-body }
12.2 Class vs Structure 12.2 Class vs Structure
-> Classes are reference types and structs are value types -> Classes are reference types and structs are value types
@@ -378,7 +378,7 @@ CHEATSHEET C#
//To declare an event inside a class, first a delegate type for the event must be declared. //To declare an event inside a class, first a delegate type for the event must be declared.
public delegate string MyDelegate(string str); public delegate string MyDelegate(string str);
//The event itself is declared by using the event keyword //The event itself is declared by using the event keyword
event MyDelegate MyEvent; event MyDelegate MyEvent;

View File

@@ -31,11 +31,11 @@ Preprocessor directives:
Create and execute a program Create and execute a program
In Linux systems: In Linux systems:
1. Open up a terminal 1. Open up a terminal
2. Create the program: nano nameProgram.c 2. Create the program: nano nameProgram.c
3. Write the program and save it 3. Write the program and save it
4. gcc -o nameExecutable nameProgram.c 4. gcc -o nameExecutable nameProgram.c
32 Reserved words 32 Reserved words
@@ -106,8 +106,8 @@ Operators
( ) grouping parenthesis, function call ( ) grouping parenthesis, function call
[ ] array indexing, also [ ][ ] etc. [ ] array indexing, also [ ][ ] etc.
-> selector, structure pointer -> selector, structure pointer
. select structure element . select structure element
! relational not, complement, ! a yields true or false ! relational not, complement, ! a yields true or false
~ bitwise not, ones complement, ~ a ~ bitwise not, ones complement, ~ a
++ increment, pre or post to a variable ++ increment, pre or post to a variable
@@ -149,11 +149,10 @@ Operators
^= bitwise exclusive or and store ^= bitwise exclusive or and store
|= bitwise or and store |= bitwise or and store
, separator as in ( y=x,z=++x ) , separator as in ( y=x,z=++x )
; statement terminator.
Operator precedence Operator precedence
More precedence More precedence
LR ( ) [ ] -> . x++ x-- LR ( ) [ ] -> . x++ x--
@@ -203,7 +202,7 @@ Function definition
type function_name(int a, float b, const char * ch,...) { function_body } type function_name(int a, float b, const char * ch,...) { function_body }
/* only parameters passed by address can are modified*/ /* only parameters passed by address can are modified*/
/* in the calling function, local copy can be modified*/ /* in the calling function, local copy can be modified*/

View File

@@ -11,7 +11,7 @@ XML uses a DTD to describe the data.
So the XML is a **Complement** to HTML. So the XML is a **Complement** to HTML.
* HTML: is used to format and display the same data. * HTML: is used to format and display the same data.
XML does not carry any information about how to be displayed. The same XML data can be used in many different presentation scenarios. XML does not carry any information about how to be displayed. The same XML data can be used in many different presentation scenarios.
Because of this, with XML, there is a full separation between data and presentation. Because of this, with XML, there is a full separation between data and presentation.

View File

@@ -46,7 +46,7 @@ CTRL+X then ( # start recording a keyboard macro
CTRL+X then ) # finish recording keyboard macro CTRL+X then ) # finish recording keyboard macro
CTRL+X then E # recall last recorded keyboard macro CTRL+X then E # recall last recorded keyboard macro
CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands
CTRL+A then D # logout from screen but don't kill it, if any command exist, it will continue CTRL+A then D # logout from screen but don't kill it, if any command exist, it will continue
BACKSPACE # deletes one character backward BACKSPACE # deletes one character backward
DELETE # deletes one character under cursor DELETE # deletes one character under cursor
@@ -94,7 +94,7 @@ cat <filename> # displays file raw content (will not be interpret
cat -n <filename> # shows number of lines cat -n <filename> # shows number of lines
nl <file.sh> # shows number of lines in file nl <file.sh> # shows number of lines in file
cat filename1 > filename2 # Copy filename1 to filename2 cat filename1 > filename2 # Copy filename1 to filename2
cat filename1 >> filename2 # merge two files texts together cat filename1 >> filename2 # merge two files texts together
any_command > <filename> # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout) any_command > <filename> # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout)
more <filename> # shows the first part of a file (move with space and type q to quit) more <filename> # shows the first part of a file (move with space and type q to quit)
head <filename> # outputs the first lines of file (default: 10 lines) head <filename> # outputs the first lines of file (default: 10 lines)
@@ -203,14 +203,14 @@ echo $$ # prints process ID of the current shell
echo $! # prints process ID of the most recently invoked background job echo $! # prints process ID of the most recently invoked background job
echo $? # displays the exit status of the last command echo $? # displays the exit status of the last command
read <varname> # reads a string from the input and assigns it to a variable read <varname> # reads a string from the input and assigns it to a variable
read -p "prompt" <varname> # same as above but outputs a prompt to ask user for value read -p "prompt" <varname> # same as above but outputs a prompt to ask user for value
column -t <filename> # display info in pretty columns (often used with pipe) column -t <filename> # display info in pretty columns (often used with pipe)
let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, % let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, %
export VARNAME=value # defines an environment variable (will be available in subprocesses) export VARNAME=value # defines an environment variable (will be available in subprocesses)
export -f <funcname> # Exports function 'funcname' export -f <funcname> # Exports function 'funcname'
export var1="var1 value" # Export and assign in the same statement export var1="var1 value" # Export and assign in the same statement
export <varname> # Copy Bash variable export <varname> # Copy Bash variable
declare -x <varname> # Copy Bash variable declare -x <varname> # Copy Bash variable
array[0]=valA # how to define an array array[0]=valA # how to define an array
array[1]=valB array[1]=valB
@@ -507,9 +507,9 @@ function returntrap {
trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing
############################################################################## ##############################################################################
# COLORS AND BACKGROUNDS # COLORS AND BACKGROUNDS
############################################################################## ##############################################################################
# note: \e or \x1B also work instead of \033 # note: \e or \x1B also work instead of \033
# Reset # Reset
Color_Off='\033[0m' # Text Reset Color_Off='\033[0m' # Text Reset
@@ -524,14 +524,14 @@ Cyan='\033[0;36m' # Cyan
White='\033[0;97m' # White White='\033[0;97m' # White
# Additional colors # Additional colors
LGrey='\033[0;37m' # Light Gray LGrey='\033[0;37m' # Ligth Gray
DGrey='\033[0;90m' # Dark Gray DGrey='\033[0;90m' # Dark Gray
LRed='\033[0;91m' # Light Red LRed='\033[0;91m' # Ligth Red
LGreen='\033[0;92m' # Light Green LGreen='\033[0;92m' # Ligth Green
LYellow='\033[0;93m'# Light Yellow LYellow='\033[0;93m'# Ligth Yellow
LBlue='\033[0;94m' # Light Blue LBlue='\033[0;94m' # Ligth Blue
LPurple='\033[0;95m'# Light Purple LPurple='\033[0;95m'# Light Purple
LCyan='\033[0;96m' # Light Cyan LCyan='\033[0;96m' # Ligth Cyan
# Bold # Bold
@@ -566,6 +566,6 @@ On_White='\033[47m' # White
# Example of usage # Example of usage
echo -e "${Green}This is GREEN text${Color_Off} and normal text" echo -e "${Green}This is GREEN text${Color_Off} and normal text"
echo -e "${Red}${On_White}This is Red test on White background${Color_Off}" echo -e "${Red}${On_White}This is Red test on White background${Color_Off}"
# option -e is mandatory, it enable interpretation of backslash escapes # option -e is mandatory, it enable interpretation of backslash escapes
printf "${Red} This is red \n" printf "${Red} This is red \n"

View File

@@ -397,8 +397,8 @@ d, t := doubleAndTriple(5)
_, t := doubleAndTriple(3) _, t := doubleAndTriple(3)
// t = 9 // t = 9
// Functions can defer commands. Deferred commands are // Functions can defer commands. Defered commands are
// ran in a stack order after the execution and // runned in a stack order after the execution and
// returning of a function // returning of a function
var aux = 0 var aux = 0
@@ -488,7 +488,7 @@ person3.Age // 0
## Maps ## Maps
Maps are data structures that holds values assigned to a key. Maps are data structures that holds values assigneds to a key.
```go ```go
// Declaring a map // Declaring a map
@@ -508,7 +508,7 @@ newYork // "EUA"
// Delete // Delete
delete(cities, "NY") delete(cities, "NY")
// Check if a key is set // Check if a key is setted
value, ok := cities["NY"] value, ok := cities["NY"]
ok // false ok // false
value // "" value // ""
@@ -600,7 +600,7 @@ Go doesn't support `throw`, `try`, `catch` and other common error handling struc
```go ```go
import "errors" import "errors"
// Function that contain a logic that can cause a possible exception flow // Function that contain a logic that can cause a possible exception flow
func firstLetter(text string) (string, error) { func firstLetter(text string) (string, error) {
if len(text) < 1 { if len(text) < 1 {
return nil, errors.New("Parameter text is empty") return nil, errors.New("Parameter text is empty")
@@ -632,7 +632,7 @@ func Sum(x, y int) int {
} }
// main_test.go // main_test.go
import ( import (
"testing" "testing"
"reflect" "reflect"
) )
@@ -676,7 +676,7 @@ func main() {
blocking2: 0 blocking2: 0
blocking2: 1 blocking2: 1
blocking2: 2 blocking2: 2
done done
*/ */
// Go routines are a function (either declared previously or anonymous) called with the keyword go // Go routines are a function (either declared previously or anonymous) called with the keyword go

479
languages/haskell.txt Normal file
View File

@@ -0,0 +1,479 @@
CHEATSHEET HASKELL
Use HASKELL
Documentation
- Haskell API search: http://www.haskell.org/hoogle/
- Haskell reference: ftp://ftpdeveloppez.com/cmaneu/langages/haskell/haskellreference.zip
Basics
- Load file :load filename
- Reload file :reload
- Launch file editor with current file :edit
- Get information about a function :info command
Comments
A single line comment starts with -- and extends to the end of the line.
Multi-line comments start with {- and extend to -}. Comments can be nested.
Reserved words
!
'
''
-
--
-<
-<<
->
::
;
<-
,
=
=>
>
?
#
*
@
[|, |]
\
_
`
{, }
{-, -}
|
~
as
case, of
class
data
data family
data instance
default
deriving
deriving instance
do
forall
foreign
hiding
if, then, else
import
infix, infixl, infixr
instance
let, in
mdo
module
newtype
proc
qualified
rec
type
type family
type instance
where
Data types
All the data types must start by a capital letter.
Int: Integer number with fixed precision
Integer: Integer number with virtually no limits
Float: Real floating point with single precision
Double: Real floating point with double the precision
Bool: Boolean
Char: Character, have to placed between quotes
String: A list of Chars
Type redefinition
Type NewTypeName = TypeValue
Example: Type String = [Char]
List & Numbers
[] Empty list
[1,2,3,4] List of four numbers
1 : 2 : 3 : 4 : [] - Write a lists using cons (:) and nil ([])
[1..100] - List of number 1,2,3..,100
[100..] - Infinite list of number 100,101,102,103,..
[0,-1 ..] - Negative integers 0,-1,-2,..
(h:q) - h stands for the first element of the list and q for the result
(f:s:t:q) - f is the first element, s is the second elemnt, t is the third and q is the rest of the elements of the list.
It can be added the element e to the list l with e:l
Basic functions for lists
list1++list2 append two list
list!!n return element n
head takes a list and returns its head. The head of a list is basically its first element.
tail takes a list and returns its tail. In other words, it chops off a list's head.
last takes a list and returns its last element.
init takes a list and returns everything except its last element.
length takes a list and returns its length, obviously.
null checks if a list is empty.
reverse reverses a list.
take takes number and a list. It extracts that many elements from the beginning of the list.
drop works in a similar way as take, only it drops the number of elements from the beginning of a list.
maximum takes a list of stuff that can be put in some kind of order and returns the biggest element.
minimum returns the smallest.
sum takes a list of numbers and returns their sum.
product takes a list of numbers and returns their product.
elem takes a thing and a list of things and tells us if that thing is an element of the list. It's usually called as an infix function because it's easier to read that way.
Function for infinite lists:
cycle: takes a list and cycles it into an infinite list. If you just try to display the result, it will go on forever so you have to slice it off somewhere.
repeat: takes an element and produces an infinite list of just that element. It's like cycling a list with only one element.
replicate: takes the number of the same element in a list.
List comprehension
List comprehension is the process of generating a list using a mathematical expression.
[body | generator]
Examples: [x*a | a <- [1..3]] = [2,4,6]
[x*y | x <- [1..5], y <- [9..5] ]
[x | x <- [1,10,14,16,18], x>5 ]
Tuples
(1,"a") - 2-element tuple of a number and a string
(last, 4, 'b') - 3-element tuple of a function, a number and a character
Note that the empty tuple () is also a type which can only have a single value: ()
Basic functions for Tuples
fst: takes a pair and returns its first component.
snd: takes a pair and returns its second component.
zip: takes two lists and then zips them together into one list by joining the matching elements into pairs.
Note: these functions operate only on pairs. They won't work on triples, 4-tuples, 5-tuples, etc.
Typeclasses
A typeclass is a sort of interface that defines some behaviour.
If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes.
If you come from OPP you can think of them kind of as Java interfaces, only better.
Everything before the => symbol is called a class constraint.
Eq is used for types that support equality testing. Eq class constraint for a type variable in a function, it uses == or /= somewhere inside its definition
Ord is for types that have an ordering. Ord covers all the standard comparing functions such as >, <, >= and <=
Show can be presented as strings. show takes a value whose type is a member of Show and presents it to us as a string.
Read is sort of the opposite typeclass of Show. The read function takes a string and returns a type which is a member of Read.
Enum members are sequentially ordered types, they can be enumerated. Types in this class: (), Bool, Char, Ordering, Int, Integer, Float and Double.
Bounded members have an upper and a lower bound. All tuples are part of Bounded. Types in this class: Bool, Int and Char.
Num is a numeric typeclass. Types in this class: Int, Integer, Float and Double.
Integral is also a numeric typeclass. In this typeclass are Int and Integer.
Floating includes only floating point numbers. Types in this class: Float and Double.
Functions
Functions are defined by declaring their name, any arguments, and an equals sign.
Declare a new function starting with explicit type declaration (optional)
functionName :: inpuntType1 [ -> inputTypeN ] -> outputType
Declare a new function with pattern matching
intToChar 1 = "One"
intToChar 2 = "Two"
Declare a new function with guards
intToChar x
| x==1 = "One"
| x==2 = "Two"
Declare a new function with guards and pattern matching
allEmpty _ = falsePart
allEmpty [] = truePart
alwaysEven n
| otherwise = False
| n 'div' 2 == 0 = True
Declare a new function with record syntax
Being this data type:
data Color = C { red,
, blue
, yellow :: Int }
It can only be match on blue only:
isBlueZero (C { blue = 0 }) = True
isBlueZero _ = False
Defining a PixelColor type and a function replace values with non-zero blue components.
Where and let
Let must always be followed by in. The in must appear in the sale column as the let keyword.
In the following example, mult multiples its argument n by x, which passed to the original multiples.
multiples x =
let mult n = n * x
in map mult [1..10]
Where is similar to let. The scope of a where definition is the current function.
In the following example, the function result below has a different meaning depending on the arguments given to the function strlen:
strlen [] = result
where result = "No string given!"
strlen f = result ++ " characters long!"
where result = show (length f)
It is important to know that let ... in ... is an expression, that is, it can be written wherever expressions are allowed.
In contrast, where is bound to a surrounding syntactic construct, like the pattern matching line of a function definition.
Advantage of where
Suppose you have the function
f :: s -> (a,s)
f x = y
where y = ... x ...
and later you decide to put this into the Control.Monad.State monad.
However, transforming to
f :: State s a
f = State $ \x -> y
where y = ... x ...
will not work, because where refers to the pattern matching f =, where no x is in scope. In contrast, if you had started with let, then you wouldn't have trouble.
f :: s -> (a,s)
f x =
let y = ... x ...
in y
This is easily transformed to:
f :: State s a
f = State $ \x ->
let y = ... x ...
in y
Advantage of let
Because "where" blocks are bound to a syntactic construct, they can be used to share bindings between parts of a function that are not syntactically expressions.
For example:
f x
| cond1 x = a
| cond2 x = g a
| otherwise = f (h x a)
where
a = w x
In expression style, you might use an explicit case:
f x
= let a = w x
in case () of
_ | cond1 x -> a
| cond2 x -> g a
| otherwise -> f (h x a)
or a functional equivalent:
f x =
let a = w x
in select (f (h x a))
[(cond1 x, a),
(cond2 x, g a)]
or a series of if-then-else expressions:
f x
= let a = w x
in if cond1 x
then a
else if cond2 x
then g a
Anonymous Functions
They are functions without names and can be defined at any time like so.
Example: \x -> x + 1
Case expressions
case is to a switch statement in C# and Java. However, it can match a pattern.
Example:
data Choices = First String | Second | Third | Fourth
case can be used to determine which choice was given
whichChoice ch =
case ch of
First _ -> "1st!"
Second -> "2nd!"
_ -> "Something else."
Conditionals
Identify ==
Non identify /n
Comparatives where the type must a subclass of Ord <,>,<=,>=
The if statement has this “signature”: if-then-else :: Bool -> a -> a -> a
Maps and filters
map takes a function and a list and applies that function to every element in the list, producing a new list.
Examples:
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
filter is a function that takes a predicate and nd a list and then returns the list of elements that satisfy the predicate
Examples:
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs)
| p x = x : filter p xs
| otherwise = filter p xs
Folds
foldl function folds the list up from the left side.
foldr works in a similar way to the left fold, only the accumulator eats up the values from the right.
The foldl1 and foldr1 functions work much like foldl and foldr, only you don't need to provide them with an explicit starting value.
scanl and scanr are like foldl and foldr, only they report all the intermediate accumulator states in the form of a list.
Function application with $
The $ function has the lowest precedence and the function with $ is rigth-associate
Default
Default implementations can be given for function in a class.
The default is defined by giving a body to one of the members' functions.
Example == can be defined in terms of /=:
(==) a b = not (a/b)
Data
Algebraic data types can be declared as: data MyType = MyValue1 | MyValue2
Note that type and constructor names must start with a capital letter. It is a syntax error otherwise.
Constructors with arguments
Constructors that take arguments can be declared, allowing more information to be stored.
data Point = TwoD Int Int
| ThreeD Int Int Int
Notice that the arguments for each constructor are type names, not constructors.
Type and constructor names
Both names can be the same since they will never be used in a place that would cause confusion.
data User = User String | Admin String
Using this type in a function makes difference clear:
whatUser (User _) = "normal user"
whatUser (Admin _) = "admin user"
Type Variables
Plymorphic data types are easy to be declared just by adding type varialbe in the declaration:
data Slot a = Slot1 a | Empty1
It can also be mix type variable and specific types in constructors:
data Slot2 a = Slot2 a Int | Empty2
Record syntax
Constructors arguments can also be declared by using record syntax which gives a name to each argument.
For example:
data Contact = Contact { ctName :: String
, ctEmail :: String
, ctPhone :: String }
Note: Multiple constructors of the same type can use the same accessor function name for values of the same type.
Deriving
The capabilities to convert to and from strings, compare
for equality, or order in a sequence are defined as Typeclasses and Haskell provides the deriving keyboard to automatically implement the typeclass on the associated type supported which are: Eq, Read, Show, Ord, Enum, Ix, and
Bounded.
Two forms of deriving are possible.
The first is used when a type only derives one class:
data Priority = Low | Medium | High
deriving Show
The second is used when multiple classes are derived:
data Alarm = Soft | Loud | Deafening
deriving (Read, Show)
Class constraint
In any case, the syntax used is:
data (Num a) => SomeNumber a = Two a a
| Three a a a
This declares a type SomeNumber which has one type variable argument.
Valid types are those in the Num class.
Do
Do indicates that the code to follow will be in a monadic context.
Statements are separated by newlines, the assignment is indicated by <, and a let form is introduced which does not require the in the keyboard.
If, Then, Else
This function tests if the string is given starts with a lower case letter and, if so, convert it to upper case:
sentenceCase (s:rest) =
if isLower s
then toUpper s : rest
else s : result
sentenceCase _ = []
Deconstruction
The left-hand side of a let definition can also destructive its argument, in case sub-components are to be accessed.
Examples:
firstThree str =
let (a:b:c:_) = str
in "Initial three characters are: " ++
show a ++ ", " ++
show b ++ ", and " ++
show c
Note that this is different than the following, which only works if the string has exactly three characters:
onlyThree str =
let (a:b:c:[]) = str
in "The characters given are: " ++
show a ++ ", " ++
show b ++ ", and " ++
show c
Modules
A module is a compilation unit which export functions, tyñes, classes, instances, and other modules.
To make a Haskell file a module just add at the top of it:
module MyModule where
Imports
To import everything (functions, data types and constructors, class declarations, and even other modules imported) exported by a library, just use the module name:
import Text.Read
To import selectively:
import Text.Read (readParen, lex)
To import data types and no constructors:
import Text.Read (Lexeme)
To import data types and one or more constructors explicitly
import Text.Read (Lexeme(Ident, Symbol))
To import all constructors for a given type:
import Text.Read (Lexeme())

View File

@@ -204,7 +204,7 @@ a \|= b; //a is the variable name; b is the variable name; this expression is an
} }
``` ```
**Example:** **Example:**
```java ```java
for (int i = 0; i <= n; i++) { for (int i = 0; i <= n; i++) {
System.out.println(i); System.out.println(i);
} }
@@ -254,10 +254,10 @@ for(dataType item : array) {
**Example:** **Example:**
```java ```java
int i=1; int i=1;
do{ do{
System.out.println(i); System.out.println(i);
i++; i++;
}while(i<=10); }while(i<=10);
``` ```
@@ -308,7 +308,7 @@ for(dataType item : array) {
//Declare a variable, object name //Declare a variable, object name
String s; String s;
//Invoke a constructor to create an object //Invoke a contructor to create an object
s = new String ("Hello World"); s = new String ("Hello World");
//Invoke an instance method that operates on the object's value //Invoke an instance method that operates on the object's value
@@ -361,13 +361,13 @@ class MyClass {
// four methods // four methods
public void setCadence(int newValue) { public void setCadence(int newValue) {
cadence = newValue; cadence = newValue;
} }
public void setGear(int newValue) { public void setGear(int newValue) {
gear = newValue; gear = newValue;
} }
public void applyBrake(int decrement) { public void applyBrake(int decrement) {
speed -= decrement; speed -= decrement;
} }
public void speedUp(int increment) { public void speedUp(int increment) {
speed += increment; speed += increment;
} }
@@ -531,13 +531,13 @@ class MyClass extends MySuperClass implements YourInterface {
```java ```java
interface print{ interface print{
void printPaper(); void printPaper();
} }
public class A4 implements print{ public class A4 implements print{
public void printPaper(){ public void printPaper(){
System.out.println("A4 Page Printed. "); System.out.println("A4 Page Printed. ");
} }
} }
``` ```

344
languages/java.txt Normal file
View File

@@ -0,0 +1,344 @@
Java Cheatsheet
HELLO WORLD
//Text file name HelloWorld.java
public class HelloWorld {
// main() is the method
public static void main (String[] arfs)
//Prints "Hello World" in the terminal window.
System.out.pritn("Hello World");
}
DATA TYPES
Type Set of values Values Operators
int integers between -2^31 and + (2^31)-1 + - * / %
double floating-point numbers real numbers + - * /
boolean boolean values true or false && || !
char characters
String sequences of characters
DECLARATION AND ASSIGNMENT STATEMENTS
//Declaration statement
int a,b;
//Assignment statement
a = 13212; //a is the variable name; 13212 is the literal which is assign to the variable a
//Initialization statement
int c = a + b;
COMPARISON OPERATORS
Operation Meaning
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal
PRINTING
void System.out.print(String s) //print s
void System.out.println(String s) //print s, followed by a newline
void System.out.println() //print a newline
PARSING COMMAND-LINE ARGUMENTS
int Integer.parseInt(String s) //convert s to an int value
double Double.parseDouble(String) //convert s to a double value
long Long.parseLong(String s) // convert s to a long value
MATH LIBRARY
Public Class Math
double abs(double a) // absolute value of a
double max(double a, double b) //maximum of a and b
double min(double a, dobule a) //minimum of a and b
double sin(double theta) //sine of theta
double cos(double theta) //cosine of theta
double tan(double theta) //tangent of theta
double toRadians(double degrees) // convert angle from degrees to radians
double toDegreestouble radians) // convert angle from radians to degrees
double exp(doube a) // exponential (e^a)
double pow(double a, double p) //raise a to the bth power (a^b)
double random() //random in [0,1)
double sqrt(double a) //square root of a
EXAMPLES OF TYPE CONVERSION
Expression Expression type Expression value
(1 + 2 + 3 + 4) / 4.0 double 2.5
Math.sqrt(4) double 2.0
"123343" + 99 String "12334399"
11 * 0.25 double 2.75
(int) 11 * 0.25 double 2.75
11 * (int) 0.25 int 0
(int) (11 * 0.25) int 2
ANATOMY OF AN IF STATEMENT
if (x>y) { // x > y is the boolean expression
//Sequence of statements
x = y;
}
IF AND IF-ELSE STATEMENT
if (BOOLEAN EXPRESSION) {
//Sequence of statements
} else {
//Sequence of statements
}
ANATOMY OF A WHILE LOOP
//Initialization is a separate statement
int power = 1;
while ( power <= n/2 ) // power <= n/2 is an example of the loop-continuation condition
{
//Statements
}
ANATOMY OF A WHILE LOOP
//Initialize another variable in a separate statement
int power = 1;
for (declare and initialize a loop control variable; loop-continuation condition/s; increment or decrement of the variable of control)
{
//Statement
}
Example:
for (int i = 0; i <= n; i++) {
//Statement
}
DO-WHILE LOOP
do{
//Statement
} while(lopp-continuation condition);
SWITCH STATEMENT
switch (VARIABLE TO EVALUATE ITS VALUE) {
case value: Statement; break;
...
default: Statement; break;
}
Example:
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
ARRAY DECLARATION
int[] ai; // array of int
short[][] as; // array of array of short
short s, // scalar short
aas[][]; // array of array of short
Object[] ao, // array of Object
otherAo; // array of Object
Collection<?>[] ca; // array of Collection of unknown type
DECLARATION OF ARRAY VARIABLE
Exception ae[] = new Exception[3];
Object aao[][] = new Exception[2][3];
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
'S', 't', 'r', 'i', 'n', 'g' };
String[] aas = { "array", "of", "String", };
FUNCTIONS
public static double sum (int a, int b) { //double is the return type, sum is the method's name, a and b are two arguments of type int;
int result; //local variable
result = a + b;
return result;//return statement;
}
USING AN OBJECT
//Declare a a variable, object name
String s;
//Invoke a contructor to create an object
s = new String ("Hello World");
//Invoke an instance method that operates on the object's value
char c = s.chartAt(4);
INSTANCE VARIABLES
public class Charge {
//Instance variable declarations
private final double rx, ry;
private final double q;
}
//private, final and public are access modifiers
CONSTRUCTORS
//A class contains constructors that are invoked to create objects from the class blueprint.
//Constructor declarations look like method declarations—except that they use the name of the class and have no return type
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
DECLARING CLASSESS
class MyClass {
// field, constructor, and
// method declarations
}
Example:
public class Bicycle {
// the Bicycle class has
// three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
DECLARING CLASSESS IMPLEMENTATING AN INTERFACE
class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and
// method declarations
}
// MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
STACK DATA TYPE
public class Stack<Item> implements Iterable <Item>
Stack() //create an empty stack
boolean isEmpthy() //return if the stack empthy
void push(Item item) // push an item onto the stack
Item pop() //return and remove the item that was inserted most recently
int size() //number of item on stack
QUEUE DATA TYPE
public class Queue<Item> implements Iterable<Item>
Queue() //create an emptyh queue
boolean isEmpthy() //return if the queue empthy
void enqueue(Item item) // insert an item onto queue
Item dequeue() //return and remove the item that was inserted least recently
int size() //number of item on queue
ITERABLE
//import Iterator
import java.util.Iterator;
public class Queue<Item> implements Iterable <Item> {
//FIFO queue
private Node first;
private Node last;
private class Node {
Item item;
Node next;
}
public void enqueue (Item item)
...
public Item dequeue()
...
}
SYMBOL TABLE DATA TYPE
public class ST<Key extends Comparable<Key>, Value>
ST() //create and empthy symbol table
void put(Key key, Value val) //associate val with key
Value get(Key key) //value associated with key
void remove(Key key) //remove key (and its associated value)
boolean contains (Key key) //return if there is a value associated with key
int size() //number of key-value pairs
Iterable<Key> keys() // all keys in the symbol table
SET DATA TYPE
public class SET<Key extends Comparable<Key>> implements Iterable<Key>
SET() //create an empthy set
boolean isEmpthy() //return if the set is empthy
void add (Key key) //add key to the set
void remove(Key key) //remove key from set
boolean contains(Key key) //return if the key is in the set
int size() //number of elements in set

View File

@@ -95,9 +95,3 @@ arr.reduce(callback[, initialValue]) // Apply a function against
arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function. arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function.
arr.values() // Returns a new Array Iterator object that contains the values for each index in the array. arr.values() // Returns a new Array Iterator object that contains the values for each index in the array.
// String methods
String.charAt(index) // Returns the character at the specified index in a string.
String.indexOf(character) // Returns the index of the first occurrence of a specified value in a string.
String.substring(starting_index, ending_index) // Returns a new string that is a subset of the original string.
String.substring(starting_index) // Returns a substring from starting index to last index of string.

View File

@@ -1,8 +1,8 @@
<?php <?php
// Exit the file, string inside get's echo'ed // Exit the file, string inside get's echo'ed
die("This file is not meant to be ran. ¯\_(ツ)_/¯"); die("This file is not ment to be ran. ¯\_(ツ)_/¯");
exit("This file is not meant to be ran. ¯\_(ツ)_/¯"); exit("This file is not ment to be ran. ¯\_(ツ)_/¯");
/** /**
* Printing * Printing
@@ -17,7 +17,7 @@ var_dump($arr); // Print anything, with type hints for any value and sizes
$string = 'Awesome cheatsheets'; $string = 'Awesome cheatsheets';
str_contains($string, 'cheat'); // Find if the string contains the specified string (PHP >= 8.0) str_contains($string, 'cheat'); // Find if the string contains the specified string (PHP >= 8.0)
str_replace('Awesome', 'Bonjour', $string); // Replace all occurrence str_replace('Awesome', 'Bonjour', $string); // Replace all occurence
strcmp($string, 'Awesome cheatsheets'); // Compare two strings strcmp($string, 'Awesome cheatsheets'); // Compare two strings
strpos($string, 'a', 0); // Get position in the string strpos($string, 'a', 0); // Get position in the string
str_split($string, 2); // Split the string str_split($string, 2); // Split the string
@@ -189,7 +189,7 @@ $argc; // Number of arguments passed into terminal
$myObject?->getName()?->startWith('A'); $myObject?->getName()?->startWith('A');
/** /**
* Class * Class
* http://php.net/manual/en/language.oop5.basic.php * http://php.net/manual/en/language.oop5.basic.php
*/ */
class NormalClass extends AbstractClassName implements InterfaceName class NormalClass extends AbstractClassName implements InterfaceName
@@ -200,7 +200,7 @@ class NormalClass extends AbstractClassName implements InterfaceName
// --> PROPERTY TYPES <-- // --> PROPERTY TYPES <--
/** /**
* Public property, everyone can access this property. * Public property, everyone can access this property.
* @var Type * @var Type
*/ */
public $property; public $property;
@@ -251,7 +251,7 @@ class NormalClass extends AbstractClassName implements InterfaceName
protected function protectedFunction(Type $var = null): Type protected function protectedFunction(Type $var = null): Type
{ {
} }
/** /**
* Static function, doesn't need an instance to be executed. * Static function, doesn't need an instance to be executed.
* @param Type * @param Type
@@ -541,7 +541,7 @@ u Pattern is treated as UTF-8
\w Any "word" character (a-z 0-9 _) \w Any "word" character (a-z 0-9 _)
\W Any non "word" character \W Any non "word" character
\s Whitespace (space, tab CRLF) \s Whitespace (space, tab CRLF)
\S Any non whitespace character \S Any non whitepsace character
\d Digits (0-9) \d Digits (0-9)
\D Any non digit character \D Any non digit character
. (Period) - Any character except newline . (Period) - Any character except newline

View File

@@ -44,7 +44,7 @@
- As of python3.8 there are 35 keywords - As of python3.8 there are 35 keywords
| Keyword | Description | Category | | Keyword | Description | Category |
|---------- | ---------- | --------- | |---------- | ---------- | --------- |
| True | Boolean value for not False or 1 | Value Keyword| | True | Boolean value for not False or 1 | Value Keyword|
| False | Boolean Value for not True or 0 | Value Keyword | | False | Boolean Value for not True or 0 | Value Keyword |
| None | No Value | Value keyword | | None | No Value | Value keyword |
@@ -58,7 +58,7 @@
| else | this block will be executed if condition is false | conditional | | else | this block will be executed if condition is false | conditional |
| for | used for looping | iteration | | for | used for looping | iteration |
| while | used for looping | iteration | | while | used for looping | iteration |
| break | get out of loop | iteration | | break | get out of loop | iteration |
| continue | skip for specific condition | iteration | | continue | skip for specific condition | iteration |
| def | make user defined function | structure | | def | make user defined function | structure |
| class | make user defined classes | structure | | class | make user defined classes | structure |
@@ -71,8 +71,8 @@
| import | import libraries/modules/packages | import | | import | import libraries/modules/packages | import |
| from | import specific function/classes from modules/packages | import | | from | import specific function/classes from modules/packages | import |
| try | this block will be tried to get executed | exception handling | | try | this block will be tried to get executed | exception handling |
| except | is any exception/error has occurred it'll be executed | exception handling | | except | is any exception/error has occured it'll be executed | exception handling |
| finally | It'll be executed no matter exception occurs or not | exception handling | | finally | It'll be executed no matter exception occurs or not | exception handling |
| raise | throws any specific error/exception | exception handling | | raise | throws any specific error/exception | exception handling |
| assert | throws an AssertionError if condition is false | exception handling | | assert | throws an AssertionError if condition is false | exception handling |
| async | used to define asynchronous functions/co-routines | asynchronous programming | | async | used to define asynchronous functions/co-routines | asynchronous programming |
@@ -135,7 +135,7 @@
- Lists are created using square brackets: - Lists are created using square brackets:
```python ```python
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
``` ```
- List items are ordered, changeable, and allow duplicate values. - List items are ordered, changeable, and allow duplicate values.
@@ -157,14 +157,14 @@ thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
- pop() function removes the last value in the given list by default. - pop() function removes the last value in the given list by default.
```python ```python
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
print(thislist.pop()) # cherry print(thislist.pop()) # cherry
print(thislist.pop(0)) #apple print(thislist.pop(0)) #apple
``` ```
### Tuple ### Tuple
@@ -291,14 +291,14 @@ thisdict = {
"model": "Mustang", "model": "Mustang",
"year": 1964 "year": 1964
} }
x = car.pop("model") x = car.pop("model")
print(x)# Mustang print(x)# Mustang
print(car)#{'brand': 'Ford', 'year': 1964} print(car)#{'brand': 'Ford', 'year': 1964}
``` ```
### Conditional branching ### Conditional branching
@@ -378,5 +378,5 @@ function_name()
``` ```
* We need not to specify the return type of the function. * We need not to specify the return type of the function.
* Functions by default return `None` * Functions by default return `None`
* We can return any datatype. * We can return any datatype.

View File

@@ -2,7 +2,7 @@
# DOCKER # DOCKER
############################################################################## ##############################################################################
docker init # Creates Docker-related starter files
docker build -t friendlyname . # Create image using this directory's Dockerfile docker build -t friendlyname . # Create image using this directory's Dockerfile
docker run -p 4000:80 friendlyname # Run "friendlyname" mapping port 4000 to 80 docker run -p 4000:80 friendlyname # Run "friendlyname" mapping port 4000 to 80
docker run -d -p 4000:80 friendlyname # Same thing, but in detached mode docker run -d -p 4000:80 friendlyname # Same thing, but in detached mode

View File

@@ -21,7 +21,6 @@ cat /proc/<process_id>/maps # Show the current virtual memory usage of a Linux
ip r # Display ip of the server ip r # Display ip of the server
lsof -i :9000 # List process running on port 9000 lsof -i :9000 # List process running on port 9000
kill -9 $(lsof -t -i:PORT) # Kill the process running on whichever port specified
journalctl -u minio.service -n 100 --no-pager # List last 100 logs for specific service journalctl -u minio.service -n 100 --no-pager # List last 100 logs for specific service

View File

@@ -1,6 +1,6 @@
############################################################################## ##############################################################################
# VIM CHEATSHEET # VIM CHEATSHEET
# WEBSITE: http://www.vim.org/ # WEBSITE: http://www.vim.org/
# DOCUMENTATION: https://vim.sourceforge.io/docs.php # DOCUMENTATION: https://vim.sourceforge.io/docs.php
############################################################################## ##############################################################################
@@ -20,15 +20,13 @@ e jump to end of words (punctuation considered words)
E jump to end of words (no punctuation) E jump to end of words (no punctuation)
b jump backward by words (punctuation considered words) b jump backward by words (punctuation considered words)
B jump backward by words (no punctuation) B jump backward by words (no punctuation)
ge jump backward to end of a word ge jump backward to end of words
gE jump backwards to the end of a word (words can contain punctuation)
0 (zero) start of line 0 (zero) start of line
^ first non-blank character of line ^ first non-blank character of line
$ jump to the end of the line $ end of line
g_ jump to the last non-blank character of the line - move line upwards, on the first non blank character
- move line upwards, on the first non-blank character + move line downwards, on the first non blank character
+ move line downwards, on the first non-blank character <enter> move line downwards, on the first non blank character
<enter> move line downwards, on the first non-blank character
gg go to first line gg go to first line
G go to last line G go to last line
ngg go to line n ngg go to line n
@@ -40,6 +38,10 @@ nG go To line n
} move the cursor a paragraph forwards } move the cursor a paragraph forwards
]] move the cursor a section forwards or to the next { ]] move the cursor a section forwards or to the next {
[[ move the cursor a section backwards or the previous { [[ move the cursor a section backwards or the previous {
CTRL-f move the cursor forward by a screen of text
CTRL-b move the cursor backward by a screen of text
CTRL-u move the cursor up by half a screen
CTRL-d move the cursor down by half a screen
H move the cursor to the top of the screen. H move the cursor to the top of the screen.
M move the cursor to the middle of the screen. M move the cursor to the middle of the screen.
L move the cursor to the bottom of the screen. L move the cursor to the bottom of the screen.
@@ -47,16 +49,6 @@ fx search line forward for 'x'
Fx search line backward for 'x' Fx search line backward for 'x'
tx search line forward before 'x' tx search line forward before 'x'
Tx search line backward before 'x' Tx search line backward before 'x'
CTRL-y moves screen up one line
CTRL-e moves screen down one line
CTRL-u moves cursor & screen up ½ page
CTRL-d moves cursor & screen down ½ page
CTRL-b moves screen up one page, cursor to last line
CTRL-f moves screen down one page, cursor to first line
zz shift current line to middle of screen
z. same as zz but also jumps to the first non-black character
zt shift current line to top of screen
zb shift current line to bottom of screen
############################################################################## ##############################################################################
@@ -68,15 +60,8 @@ zb shift current line to bottom of screen
ma make a bookmark named a at the current cursor position ma make a bookmark named a at the current cursor position
`a go to position of bookmark a `a go to position of bookmark a
'a go to the line with bookmark a 'a go to the line with bookmark a
`0 go to the position where Vim was previously exited
`" go to the position when last editing this file
`. go to the line that you last edited `. go to the line that you last edited
`` go to the position before the last jump
g, go to newer position in change list
g; go to older position in change list
# Tip: To jump to a mark you can either use a backtick (`) or an apostrophe (').
# Using an apostrophe jumps to the beginning (first non-blank) of the line holding the mark.
############################################################################## ##############################################################################
# INSERT MODE # INSERT MODE
@@ -85,13 +70,10 @@ g; go to older position in change list
i start insert mode at cursor i start insert mode at cursor
I insert at the beginning of the line I insert at the beginning of the line
gi return to insert mode where you inserted text the last time
gI like "I", but always start in column 1
a append after the cursor a append after the cursor
A append at the end of the line A append at the end of the line
o open (append) blank line below current line o open (append) blank line below current line
O open blank line above current line O open blank line above current line
CTRL-o Temporarily enter normal mode to issue one normal-mode command(while in insert mode)
Esc exit insert mode Esc exit insert mode
@@ -102,25 +84,10 @@ Esc exit insert mode
r replace a single character (does not use insert mode) r replace a single character (does not use insert mode)
R enter Insert mode, replacing characters rather than inserting R enter Insert mode, replacing characters rather than inserting
J join line below to the current one with one space in between J join line below to the current one
gJ join line below to the current one without space in between
cc change (replace) an entire line cc change (replace) an entire line
cw change (replace) to the end of word (same as ce) cw change (replace) to the end of word
2cw change (replace) repeat cw twice C change (replace) to the end of line
ciw change (replace) word under the cursor
caw change (replace) word under the cursor and the space after or before it
ci" change (replace) word inside ""
cit change (replace) html tag content
cat change (replace) html tag
cis change (replace) sentence under the cursor
cas change (replace) sentence under the cursor and the space after or before it
cib change (replace) inside a block with ()
cab change (replace) a block with ()
ciB change (replace) inside a block with {}
caB change (replace) a block with {}
C change (replace) to the end of line(same as c$)
cG change (replace) to the end of the file
cgg change (replace) from first line to current line
ct' change (replace) until the ' character (can change ' for any character) ct' change (replace) until the ' character (can change ' for any character)
s delete character at cursor and substitute text s delete character at cursor and substitute text
S delete line at cursor and substitute text (same as cc) S delete line at cursor and substitute text (same as cc)
@@ -135,7 +102,6 @@ guiw make current word lowercase
gU$ make uppercase until end of line gU$ make uppercase until end of line
gu$ make lowercase until end of line gu$ make lowercase until end of line
>> indent line one column to right >> indent line one column to right
>i{ indent everything in the {}
<< indent line one column to left << indent line one column to left
== auto-indent current line == auto-indent current line
ddp swap current line with next ddp swap current line with next
@@ -144,7 +110,6 @@ ddkP swap current line with previous
:r [name] insert the file [name] below the cursor. :r [name] insert the file [name] below the cursor.
:r !{cmd} execute {cmd} and insert its standard output below the cursor. :r !{cmd} execute {cmd} and insert its standard output below the cursor.
# Tip: Instead of b or B one can also use ( or { respectively.
############################################################################## ##############################################################################
# DELETING TEXT # DELETING TEXT
@@ -153,15 +118,10 @@ ddkP swap current line with previous
x delete current character x delete current character
X delete previous character X delete previous character
dw delete (cut) to the end of word (same as de) dw delete the current word
diw delete (cut) word under the cursor
daw delete (cut) word under the cursor and the space after or before it
dap delete (cut) a paragraph
dd delete (cut) a line dd delete (cut) a line
dt' delete (cut) until the next ' character on the line (replace ' by any character) dt' delete until the next ' character on the line (replace ' by any character)
dG delete (cut) to the end of the file D delete from cursor to end of line
dgg delete (cut) from first line to current line
D delete (cut) from cursor to end of line (same as d$)
:[range]d delete [range] lines :[range]d delete [range] lines
@@ -176,10 +136,6 @@ yy yank (copy) a line
y$ yank to end of line y$ yank to end of line
p put (paste) the clipboard after cursor/current line p put (paste) the clipboard after cursor/current line
P put (paste) before cursor/current line P put (paste) before cursor/current line
gp put (paste) the clipboard after cursor and leave cursor after the new text
gP put (paste) before cursor and leave cursor after the new text
"+y yank into the system clipboard register
"+p paste from the system clipboard register
:set paste avoid unexpected effects in pasting :set paste avoid unexpected effects in pasting
:registers display the contents of all registers :registers display the contents of all registers
"xyw yank word into register x "xyw yank word into register x
@@ -191,12 +147,6 @@ gP put (paste) before cursor and leave cursor after the new tex
"xgP just like "P", but leave the cursor just after the new text "xgP just like "P", but leave the cursor just after the new text
:[line]put x put the text from register x after [line] :[line]put x put the text from register x after [line]
# Tip: if you are using vim extension on vs code, you can enable
"vim.useSystemClipboard": true
in setting.json, this will allow to Use system clipboard for unnamed register.
############################################################################## ##############################################################################
# MACROS # MACROS
@@ -207,7 +157,6 @@ qa start recording macro 'a'
q end recording macro q end recording macro
@a replay macro 'a' @a replay macro 'a'
@: replay last command @: replay last command
@@ repeat macro
############################################################################## ##############################################################################
@@ -223,11 +172,9 @@ CTRL-v start visual block mode
O move to other corner of block O move to other corner of block
aw mark a word aw mark a word
ab a () block (with braces) ab a () block (with braces)
aB a {} block (with brackets) ab a {} block (with brackets)
at a block with <> tags
ib inner () block ib inner () block
iB inner {} block ib inner {} block
it inner <> block
Esc exit visual mode Esc exit visual mode
VISUAL MODE COMMANDS VISUAL MODE COMMANDS
@@ -247,7 +194,6 @@ v% selects matching parenthesis
vi{ selects matching curly brace vi{ selects matching curly brace
vi" selects text between double quotes vi" selects text between double quotes
vi' selects text between single quotes vi' selects text between single quotes
gv reselect the last selected area
############################################################################## ##############################################################################
# SPELLING # SPELLING
@@ -294,7 +240,7 @@ set ic ignore case: turn on
set noic ignore case: turn off set noic ignore case: turn off
:%s/old/new/g replace all old with new throughout file :%s/old/new/g replace all old with new throughout file
:%s/old/new/gc replace all old with new throughout file with confirmation :%s/old/new/gc replace all old with new throughout file with confirmation
:argdo %s/old/new/gc | wq open multiple files and run this command to replace old :argdo %s/old/new/gc | wq open multiple files and run this command to replace old
with new in every file with confirmation, save and quit with new in every file with confirmation, save and quit
@@ -337,6 +283,7 @@ CTRL-w < increase window width
CTRL-w > decrease window width CTRL-w > decrease window width
CTRL-w = equal window CTRL-w = equal window
CTRL-w o close other windows CTRL-w o close other windows
zz Centers the window to the current line
############################################################################## ##############################################################################
@@ -359,14 +306,12 @@ clast display the last error
% show matching brace, bracket, or parenthese % show matching brace, bracket, or parenthese
gf edit the file whose name is under the cursor gf edit the file whose name is under or after the cursor
gF edit the file whose name is under the cursor and jump to the line number
gd when the cursor is on a local variable or function, jump to its declaration gd when the cursor is on a local variable or function, jump to its declaration
'' return to the line where the cursor was before the latest jump '' return to the line where the cursor was before the latest jump
gi return to insert mode where you inserted text the last time
CTRL-o move to previous position you were at CTRL-o move to previous position you were at
CTRL-i move to more recent position you were at CTRL-i move to more recent position you were at
:set nu display numbers (short for :set number)
:set nonu hide numbers (short for :set nonumber)
############################################################################## ##############################################################################
@@ -540,7 +485,7 @@ CTRL-n jump to the next empty tag / attribute
cs'" change surrounding quotes to double-quotes cs'" change surrounding quotes to double-quotes
cs(} change surrounding parens to braces cs(} change surrounding parens to braces
cs({ change surrounding parens to braces with space cs({ change surrounding parens to braces with space
ds' delete surrounding quotes ds' delete surrounding quotes
dst delete surrounding tags dst delete surrounding tags
@@ -648,7 +593,7 @@ jj exit insertion mode
<leader>/ clear the search register <leader>/ clear the search register
<leader>h toggle hidden characters <leader>h toggle hidden characters
<leader>W strip all trailing whitespace <leader>W strip all trailing whitespace
@@ -716,5 +661,5 @@ CTRL-y go to next tag of attribute in sparkup plugin
<leader>g toggle Gundo window <leader>g toggle Gundo window
IMG<CR> show image browser to insert image tag with src, width and height IMG<CR> show image browser to insert image tag with src, width and height
b insert image tag with dimensions from NERDTree b insert image tag with dimensions from NERDTree
(http://stackoverflow.com/questions/5707925/vim-image-placement) (http://stackoverflow.com/questions/5707925/vim-image-placement)