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

@@ -88,7 +88,7 @@ CHEATSHEET C#
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();
@@ -135,7 +135,7 @@ CHEATSHEET C#
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
@@ -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

View File

@@ -149,7 +149,6 @@ 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

View File

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

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

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

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

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

@@ -71,7 +71,7 @@
| 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 |

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

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