1
1
mirror of https://github.com/namibia/awesome-cheatsheets.git synced 2024-11-23 21:27:40 +00:00

Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets

This commit is contained in:
Julien Le Coupanec 2021-12-09 19:58:00 +01:00
commit 55afd60d33
11 changed files with 409 additions and 50 deletions

View File

@ -54,6 +54,7 @@ Feel free to take a look. You might learn new things. They have been designed to
#### Javascript #### Javascript
- [Adonis.js](backend/adonis.js) - [Adonis.js](backend/adonis.js)
- [Express.js](backend/express.js)
- [Feathers.js](backend/feathers.js) - [Feathers.js](backend/feathers.js)
- [Moleculer](backend/moleculer.js) - [Moleculer](backend/moleculer.js)
- [Node.js](backend/node.js) - [Node.js](backend/node.js)

226
backend/express.js Normal file
View File

@ -0,0 +1,226 @@
/* *******************************************************************************************
* API
* http://expressjs.com/en/api.html
* ******************************************************************************************* */
`npm i express --save` or`yarn add -D express``(-D saves it as a dev dependency)`
`yarn add -D @types/express``(Installing for TS)`
const express = require("express"); // Importing the express library.
const app = express(); // Intializing the imported express application
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://expressjs.com/en/api.html#express.json
* ******************************************************************************************* */
```Methods```;
`express.json([options]);`
options: `
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
reviver // It is passed directly to JSON.parse as an second argument
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.raw([options]);`
options: `
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.Router([options]);`
options: `
caseSensitive //Enables case sensitivity
mergeParams //if param names of child and parent are conflicted then the child takes the precedence
strict // Enables Strict routing
`;
`express.static(root, [options]);`
options: `
dotfiles // determines how dotfiles are used
etag // Operates etag generation
extensions // Operates file extension fallback
fallthrough // Enable or disable the immutable directive in the Cache-Control response header
index // sends the specified directory index file
LastModified // sets the Last-Modified header to the last modified date
setHeaders // Function for setting HTTP headers to serve with the file
`;
`express.text([options]);`
options: `
defaultCharset // Sets the default charset for the text context.
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.urlencoded([options]);`
options: `
extended // it allows to choose between parsing the URL-encoded data or the qs library
parameterLimit // It controls the no of params.
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
```Application`````;
Properties```app.local`;
`app.locals.title = "My Cheatsheet";
console.dir(app.locals.title)`; `// Creating objects with local variables`
app.mountpath`
``app.mountpath``const admin = express()
admin.get('/', function(req,res){
console.log(admin.mountpath)
res.send('Admin Homepage')
})
app.use('<admin dir>', admin)`; `// Mounting a sub - app`
``Event``
`admin.on('mount', (parent){
console.log('Admin Mounted')
})` `// Mounting on a parent app`
``Methods``
`app.get('/', function(req, res){
res.send('GET request to message')
})` `// get requests to the specified path`
`app.post('/', function(req,res){
res.send('POST request to a webpage')
})` `// post request to the specified path`
`app.put('/', function(req,res){
res.send('PUT request to a webpage')
})` `// post request to the specified path`
`app.delete('/', function(req,res){
res.send('DELETE request to a webpage')
})` `// delete request to the specified path`
`app.all('/', function(req,res,next){
console.log('Accessing the secret section....')
next()
})` `// Routing all types of HTTP request`
`app.param('user', function(req,res,next){
User.find(id, function(err, user){
if(err){
next(err)
} else if (user){
req.user = user
next()
} else {
next(new Error('Failed to load user'))
}
})
})` `// Adding callback trigger to route parameters`
`app.use(function(req,res,next){
res.send('Hey There!')
})` `// To Invoke the middleware layer that you want to add`
```Request```
``Methods``
`req.get('content-type')` `// Returns the specified HTTP req header`
`req.accepts('html')` `// Checks if the specified content types are available or not`
`req.is('json')` `// Requests the matching content-type`
`var range = req.range(1000)
if (range.type === 'bytes'){
range.forEach(function(r){
// Your code
})
}` `// Range header parser`
``Properties``
`req.param('name')` `// Requests the param name when present`
`app.post('/', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})` `// Data submitted in the request body`
`console.dir(req.cookies.name)` `// Contains cookies sent by the request`
`console.dir(req.query.q)` `// Query string parameter in the route`
`console.log(req.route)
res.send('GET')` `// Outputs all the layer, methods, path`
`console.dir(req.signedCookies.user)` `// Logs all the signed cookies sent by the request`
```Response```
``Methods``
`res.redirect('https://google.com')` `// Redirects to the intended page`
`res.send({message: 'Awesome Stuffs'})` `// Response to the webpage`
`res.json({alert: 'awesomecheatsheets'})` `// Response in JSON type`
`const file = req.params.name;
res.sendFile(file, options, function(err){
if(err){
next(err)
}else{
console.log('Sent:', file)
}
})` `// Sends file to the intended path`
`res.render('index')` `// Rendering the intended file`
```BodyParser```
`const BodyParser = require('body-parser')
app.use(BodyParser.json())
app.use(BodyParser.urlencoded({
extended: true
}))` `// Parses incoming request bodies`

View File

@ -436,7 +436,7 @@ request.on('connect', function(response, socket, head) { }); // Emitted each t
request.on('upgrade', function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed. request.on('upgrade', function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
request.on('continue', function() { }); // Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body. request.on('continue', function() { }); // Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); // This sends a chunk of the response body. If this merthod is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers. response.write(chunk, [encoding]); // This sends a chunk of the response body. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
response.writeContinue(); // Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. response.writeContinue(); // Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the request. response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the request.
response.setTimeout(msecs, callback); // Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object. response.setTimeout(msecs, callback); // Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.

View File

@ -46,6 +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
BACKSPACE # deletes one character backward BACKSPACE # deletes one character backward
DELETE # deletes one character under cursor DELETE # deletes one character under cursor
@ -54,6 +55,7 @@ history # shows command line history
!! # repeats the last command !! # repeats the last command
!<n> # refers to command line 'n' !<n> # refers to command line 'n'
!<string> # refers to command starting with 'string' !<string> # refers to command starting with 'string'
esc :wq # exits and saves script
exit # logs out of current session exit # logs out of current session
@ -88,7 +90,10 @@ tree # show directories and subdirectories in easilly r
mc # terminal file explorer (alternative to ncdu) mc # terminal file explorer (alternative to ncdu)
touch <filename> # creates or updates (edit) your file touch <filename> # creates or updates (edit) your file
mktemp -t <filename> # make a temp file in /tmp/ which is deleted at next boot (-d to make directory) mktemp -t <filename> # make a temp file in /tmp/ which is deleted at next boot (-d to make directory)
cat <filename> # prints file raw content (will not be interpreted) cat <filename> # displays file raw content (will not be interpreted)
cat -n <filename> # shows number of lines
cat filename1 > filename2 # Copy filename1 to filename2
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)
@ -164,6 +169,7 @@ info <command> # shows another documentation system for the specific c
help # shows documentation about built-in commands and functions help # shows documentation about built-in commands and functions
df # shows disk usage df # shows disk usage
du <filename> # shows the disk usage of the files and directories in filename (du -s give only a total) du <filename> # shows the disk usage of the files and directories in filename (du -s give only a total)
resize2fs # ext2/ext3/ext4 file system resizer
last <yourUsername> # lists your last logins last <yourUsername> # lists your last logins
ps -u yourusername # lists your processes ps -u yourusername # lists your processes
kill <PID> # kills the processes with the ID you gave kill <PID> # kills the processes with the ID you gave
@ -179,6 +185,7 @@ whois <domain> # gets whois information for domain
dig <domain> # gets DNS information for domain dig <domain> # gets DNS information for domain
dig -x <host> # reverses lookup host dig -x <host> # reverses lookup host
wget <file> # downloads file wget <file> # downloads file
netstat # Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
time <command> # report time consumed by command execution time <command> # report time consumed by command execution

View File

@ -641,7 +641,7 @@ func TestSum(t *testing.T) {
x, y := 2, 4 x, y := 2, 4
expected := 2 + 4 expected := 2 + 4
if !reflect.DeepEqual(sum(x, y), expected) { if !reflect.DeepEqual(Sum(x, y), expected) {
t.Fatalf("Function Sum not working as expected") t.Fatalf("Function Sum not working as expected")
} }
} }

View File

@ -85,7 +85,7 @@ int c = a + b;
double tan(double theta) //tangent of theta double tan(double theta) //tangent of theta
double toRadians(double degrees) // convert angle from degrees to radians double toRadians(double degrees) // convert angle from degrees to radians
double toDegrees(double radians) // convert angle from radians to degrees double toDegrees(double radians) // convert angle from radians to degrees
double exp(doube a) // exponential (e^a) double exp(double a) // exponential (e^a)
double pow(double a, double p) //raise a to the bth power (a^b) double pow(double a, double p) //raise a to the bth power (a^b)
double random() //random in [0,1) double random() //random in [0,1)
double sqrt(double a) //square root of a double sqrt(double a) //square root of a
@ -578,8 +578,8 @@ class MyClass extends MySuperClass implements YourInterface {
```java ```java
public class Queue<Item> implements Iterable<Item> public class Queue<Item> implements Iterable<Item>
Queue() //create an emptyh queue Queue() //create an empty queue
boolean isEmpthy() //return if the queue empthy boolean isEmpty() //return if the queue empty
void enqueue(Item item) // insert an item onto queue void enqueue(Item item) // insert an item onto queue
Item dequeue() //return and remove the item that was inserted least recently Item dequeue() //return and remove the item that was inserted least recently
int size() //number of item on queue int size() //number of item on queue
@ -627,9 +627,9 @@ public class Queue<Item> implements Iterable <Item> {
* **SET DATA TYPE** * **SET DATA TYPE**
```java ```java
public class SET<Key extends Comparable<Key>> implements Iterable<Key> public class Set<Key extends Comparable<Key>> implements Iterable<Key>
SET() //create an empthy set Set() //create an empty set
boolean isEmpthy() //return if the set is empthy boolean isEmpty() //return if the set is empty
void add (Key key) //add key to the set void add (Key key) //add key to the set
void remove(Key key) //remove key from set void remove(Key key) //remove key from set
boolean contains(Key key) //return if the key is in the set boolean contains(Key key) //return if the key is in the set

View File

@ -70,15 +70,15 @@
| yield | yields values instead of returning (are called generators) | returning keyword | | yield | yields values instead of returning (are called generators) | returning keyword |
| 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 | execption handling | | try | this block will be tried to get executed | exception handling |
| execpt | is any execption/error has occured it'll be executed | execption handling | | except | is any exception/error has occured it'll be executed | exception handling |
| finally | It'll be executed no matter execption occurs or not | execption handling | | finally | It'll be executed no matter exception occurs or not | exception handling |
| raise | throws any specific error/execption | execption handling | | raise | throws any specific error/exception | exception handling |
| assert | throws an AssertionError if condition is false | execption 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 |
| await | used to specify a point when control is taken back | asynchronous programming | | await | used to specify a point when control is taken back | asynchronous programming |
| del | deletes/unsets any user defined data | variable handling | | del | deletes/unsets any user defined data | variable handling |
| global | used to access variables defined outsied of function | variable handling | | global | used to access variables defined outside of function | variable handling |
| nonlocal | modify variables from different scopes | variable handling | | nonlocal | modify variables from different scopes | variable handling |
<br> <br>
@ -134,7 +134,7 @@
- Lists are created using square brackets: - Lists are created using square brackets:
```py ```python
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
``` ```
@ -147,18 +147,31 @@ thislist = ["apple", "banana", "cherry"]
- To determine how many items a list has, use the `len()` function. - To determine how many items a list has, use the `len()` function.
- A list can contain different data types: - A list can contain different data types:
```py ```python
list1 = ["abc", 34, True, 40, "male"] list1 = ["abc", 34, True, 40, "male"]
``` ```
- It is also possible to use the list() constructor when creating a new list - It is also possible to use the list() constructor when creating a new list
```py ```python
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
``` ```
- pop() function removes the last value in the given list by default.
```python
thislist = ["apple", "banana", "cherry"]
print(thislist.pop()) # cherry
print(thislist.pop(0)) #apple
```
### Tuple ### Tuple
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members. - Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- A tuple is a collection which is ordered and unchangeable. - A tuple is a collection which is ordered and unchangeable.
- Tuples are written with round brackets. - Tuples are written with round brackets.
```py ```python
thistuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry")
``` ```
- Tuple items are ordered, unchangeable, and allow duplicate values. - Tuple items are ordered, unchangeable, and allow duplicate values.
@ -168,16 +181,16 @@ thistuple = ("apple", "banana", "cherry")
- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. - Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
- Since tuple are indexed, tuples can have items with the same value: - Since tuple are indexed, tuples can have items with the same value:
- Tuples allow duplicate values: - Tuples allow duplicate values:
```py ```python
thistuple = ("apple", "banana", "cherry", "apple", "cherry") thistuple = ("apple", "banana", "cherry", "apple", "cherry")
``` ```
- To determine how many items a tuple has, use the `len()`function: - To determine how many items a tuple has, use the `len()`function:
```py ```python
thistuple = ("apple", "banana", "cherry") thistuple = ("apple", "banana", "cherry")
print(len(thistuple)) print(len(thistuple))
``` ```
- To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. - To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
```py ```python
thistuple = ("apple",) thistuple = ("apple",)
print(type(thistuple)) print(type(thistuple))
@ -186,7 +199,7 @@ thistuple = ("apple")
print(type(thistuple)) print(type(thistuple))
``` ```
- It is also possible to use the tuple() constructor to make a tuple. - It is also possible to use the tuple() constructor to make a tuple.
```py ```python
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple) print(thistuple)
@ -195,7 +208,7 @@ print(thistuple)
### Set ### Set
- Set is a collection which is unordered and unindexed. No duplicate members. - Set is a collection which is unordered and unindexed. No duplicate members.
- A set is a collection which is both unordered and unindexed. - A set is a collection which is both unordered and unindexed.
```py ```python
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
``` ```
- Set items are unordered, unchangeable, and do not allow duplicate values. - Set items are unordered, unchangeable, and do not allow duplicate values.
@ -206,27 +219,38 @@ thisset = {"apple", "banana", "cherry"}
- Sets are unchangeable, meaning that we cannot change the items after the set has been created. - Sets are unchangeable, meaning that we cannot change the items after the set has been created.
- Duplicate values will be ignored. - Duplicate values will be ignored.
- To determine how many items a set has, use the `len()` method. - To determine how many items a set has, use the `len()` method.
```py ```python
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
print(len(thisset)) print(len(thisset))
``` ```
- Set items can be of any data type: - Set items can be of any data type:
```py ```python
set1 = {"apple", "banana", "cherry"} set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3} set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False} set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"} set4 = {"abc", 34, True, 40, "male"}
``` ```
- It is also possible to use the `set()` constructor to make a set. - It is also possible to use the `set()` constructor to make a set.
```py ```python
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
``` ```
- frozenset() is just an immutable version of Set. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
```python
set1 = {"apple", "banana", "cherry"}
frzset=frozenset(set1)
print(frzset)
```
### Dictionary ### Dictionary
- Dictionary is a collection which is unordered and changeable. No duplicate members. - Dictionary is a collection which is unordered and changeable. No duplicate members.
- Dictionaries are used to store data values in key:value pairs. - Dictionaries are used to store data values in key:value pairs.
- Dictionaries are written with curly brackets, and have keys and values: - Dictionaries are written with curly brackets, and have keys and values:
```py ```python
thisdict = { thisdict = {
"brand": "Ford", "brand": "Ford",
"model": "Mustang", "model": "Mustang",
@ -234,7 +258,7 @@ thisdict = {
} }
``` ```
- Dictionary items are presented in key:value pairs, and can be referred to by using the key name. - Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
```py ```python
thisdict = { thisdict = {
"brand": "Ford", "brand": "Ford",
"model": "Mustang", "model": "Mustang",
@ -246,11 +270,11 @@ print(thisdict["brand"])
- Dictionaries cannot have two items with the same key. - Dictionaries cannot have two items with the same key.
- Duplicate values will overwrite existing values. - Duplicate values will overwrite existing values.
- To determine how many items a dictionary has, use the `len()` function. - To determine how many items a dictionary has, use the `len()` function.
```py ```python
print(len(thisdict)) print(len(thisdict))
``` ```
- The values in dictionary items can be of any data type - The values in dictionary items can be of any data type
```py ```python
thisdict = { thisdict = {
"brand": "Ford", "brand": "Ford",
"electric": False, "electric": False,
@ -259,9 +283,26 @@ thisdict = {
} }
``` ```
- pop() Function is used to remove a specific value from a dictionary. You can only use key bot the value. Unlike Lists you have to give a value to this function
```python
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.pop("model")
print(x)# Mustang
print(car)#{'brand': 'Ford', 'year': 1964}
```
### Conditional branching ### Conditional branching
```py ```python
if condition: if condition:
pass pass
elif condition2: elif condition2:
@ -278,7 +319,7 @@ thisdict = {
#### While loop #### While loop
- With the `while` loop we can execute a set of statements as long as a condition is true. - With the `while` loop we can execute a set of statements as long as a condition is true.
- Example: Print i as long as i is less than 6 - Example: Print i as long as i is less than 6
```py ```python
i = 1 i = 1
while i < 6: while i < 6:
print(i) print(i)
@ -296,7 +337,7 @@ while i < 6:
- This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. - This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
- With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. - With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
```py ```python
fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]
for x in fruits: for x in fruits:
print(x) print(x)
@ -310,7 +351,7 @@ A nested loop is a loop inside a loop.
- The "inner loop" will be executed one time for each iteration of the "outer loop": - The "inner loop" will be executed one time for each iteration of the "outer loop":
```py ```python
adj = ["red", "big", "tasty"] adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]
@ -320,19 +361,19 @@ for x in adj:
``` ```
- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. - for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
```py ```python
for x in [0, 1, 2]: for x in [0, 1, 2]:
pass pass
``` ```
### Function definition ### Function definition
```py ```python
def function_name(): def function_name():
return return
``` ```
### Function call ### Function call
```py ```python
function_name() function_name()
``` ```

View File

@ -4,15 +4,32 @@ git clone <address> # creates a git repo from given address (get the address fro
git clone <address> -b <branch_name> <path/to/directory> # clones a git repo from the address into the given directory and checkout's the given branch git clone <address> -b <branch_name> <path/to/directory> # clones a git repo from the address into the given directory and checkout's the given branch
git clone <address> -b <branch_name> --single-branch # Clones a single branch git clone <address> -b <branch_name> --single-branch # Clones a single branch
git add file.txt # adds(stages) file.txt to the git git add <file_name> # adds(stages) file.txt to the git
git add * # adds(stages) all new modifications, deletions, creations to the git git add * # adds(stages) all new modifications, deletions, creations to the git
git reset file.txt # Removes file.txt from the stage git reset file.txt # Removes file.txt from the stage
git reset --hard # Throws away all your uncommitted changes, hard reset files to HEAD git reset --hard # Throws away all your uncommitted changes, hard reset files to HEAD
git reset --soft <commit_id> # moves the head pointer
git reset --mixed <commit_id> # moves the head pointer and then copies the files from the commit it is now pointing to the staging area,
# the default when no argument is provided
git reset -hard <commit_id> # moves the head pointer and then copies the files from the commit it is now pointing to the staging area
# and working directory thus, throw away all uncommitted changes
# git reset
# 1. Move HEAD and current branch
# 2. Reset the staging area
# 3. Reset the working area
# --soft = (1)
# --mixed = (1) & (2) (default)
# --hard = (1) & (2) & (3)
git rm file.txt # removes file.txt both from git and file system git rm file.txt # removes file.txt both from git and file system
git rm --cached file.txt # only removes file.txt both from git index git rm --cached file.txt # only removes file.txt both from git index
git status # shows the modifications and stuff that are not staged yet git status # shows the modifications and stuff that are not staged yet
git branch # shows all the branches (current branch is shown with a star) git branch # shows all the branches (current branch is shown with a star)
git branch -a # shows all the branches local and remote
git branch my-branch # creates my-branch git branch my-branch # creates my-branch
git branch -d my-branch # deletes my-branch git branch -d my-branch # deletes my-branch
git checkout my-branch # switches to my-branch git checkout my-branch # switches to my-branch
@ -32,7 +49,13 @@ git remote add my-remote <address> # creates a remote (get the address from your
git remote rm my-remote # Remove a remote git remote rm my-remote # Remove a remote
git log # shows the log of commits git log # shows the log of commits
# git log by default uses less command so you can use these: f=next page, b=prev page, search=/<query>, n=next match, p=prev match, q=quit
git log --no-pager # shows the log of commits without less command
git log --oneline # shows the log of commits, each commit in a single line git log --oneline # shows the log of commits, each commit in a single line
git log --oneline --graph --decorate # shows the log of commits, each commit in a single line with graph
git log --since=<time> # shows the log of commits since given time
git log -- <file_name>
git log -p <file_name> # change over time for a specific file git log -p <file_name> # change over time for a specific file
git log <Branch1> ^<Branch2> # lists commit(s) in branch1 that are not in branch2 git log <Branch1> ^<Branch2> # lists commit(s) in branch1 that are not in branch2
git log -n <x> # lists the last x commits git log -n <x> # lists the last x commits
@ -40,6 +63,9 @@ git log -n <x> --oneline # lists the last x commits, each commit in single l
git grep --heading --line-number '<string/regex>' # Find lines matching the pattern in tracked files git grep --heading --line-number '<string/regex>' # Find lines matching the pattern in tracked files
git log --grep='<string/regex>' # Search Commit log git log --grep='<string/regex>' # Search Commit log
git reflog # record when the tips of branches and other references were updated in the local repository.
git ls-files # show information about files in the index and the working tree
git commit -m "msg" # commit changes with a msg git commit -m "msg" # commit changes with a msg
git commit -m "title" -m "description" # commit changes with a title and description git commit -m "title" -m "description" # commit changes with a title and description
git commit --amend # combine staged changes with the previous commit, or edit the previous commit message without changing its snapshot git commit --amend # combine staged changes with the previous commit, or edit the previous commit message without changing its snapshot
@ -50,6 +76,9 @@ git revert <commit-id> # Undo a commit by creating a new commit
git show # shows one or more objects (blobs, trees, tags and commits). git show # shows one or more objects (blobs, trees, tags and commits).
git diff # show changes between commits, commit and working tree git diff # show changes between commits, commit and working tree
git diff HEAD #show changes between working directory vs last commit
git diff --staged HEAD #show changes between stage area vs last commit
git diff --color # show colored diff git diff --color # show colored diff
git diff --staged # Shows changes staged for commit git diff --staged # Shows changes staged for commit
@ -61,7 +90,8 @@ git push --delete my-remote v1.0 # deletes the tag in my-remote (be carefore to
git push my-remote my-branch v1.0 # push v1.0 tag to my-remote in my-branch git push my-remote my-branch v1.0 # push v1.0 tag to my-remote in my-branch
git fetch --tags # pulls the tags from remote git fetch --tags # pulls the tags from remote
git pull my-remote my-branch # pulls and tries to merge my-branch from my-remote to the current branch git pull my-remote my-branch # pulls and tries to merge my-branch from my-remote to the current branch git pull = git fetch && get merge
git stash # stashes the staged and unstaged changes (git status will be clean after it) git stash # stashes the staged and unstaged changes (git status will be clean after it)
git stash -u # stash everything including new untracked files (but not .gitignore) git stash -u # stash everything including new untracked files (but not .gitignore)
@ -83,18 +113,63 @@ git clean -f # clean untracked files permanently
git clean -f -d/git clean -fd # To remove directories permanently git clean -f -d/git clean -fd # To remove directories permanently
git clean -f -X/git clean -fX # To remove ignored files permanently git clean -f -X/git clean -fX # To remove ignored files permanently
git clean -f -x/git clean -fx # To remove ignored and non-ignored files permanently git clean -f -x/git clean -fx # To remove ignored and non-ignored files permanently
git clean -d --dry-run # shows what would be deleted
git config --global --list # lists the git configuration for all repos git config --global --list # lists the git configuration for all repos
git config --global --edit # opens an editor to edit the git config file git config --global --edit # opens an editor to edit the git config file
git config --global alias.<handle> <command> # add git aliases to speed up workflow , eg. if handle is st and command is status then running git st would execute git status git config --global alias.<handle> <command> # add git aliases to speed up workflow , eg.
# if handle is st and command is status then running git st would execute git status
git config --global core.editor <editor_name> # config default editor
git archive <branch_name> --format=zip --outpute=./<archive_name>.zip # create an archive of files from a named tree
.gitignore .gitignore
# is a file including names of stuff that you don"t want to be staged or tracked. # is a file including names of stuff that you don"t want to be staged or tracked.
# You usually keep your local files like database, media, and etc here. # You usually keep your local files like database, media, etc here.
# You can find good resources online about ignoring specific files in your project files. # You can find good resources online about ignoring specific files in your project files.
# .gitignore is also get ignored # .gitignore is also get ignored
.git .git
# is a hidden directory in repo directory including git files. It is created after "git init". # is a hidden directory in repo directory including git files. It is created after "git init".
# Some useful notes:
# Better Commit messages:
# Key to Effective Debugging
# For the commit message to help in debugging effectively, ensure that it is short and use an imperative
# mood (spoken or written as if giving a command or instruction) when constructing them.
# Also use feature tense for commit messages.
# The first word in your commit message should be one of these:
# Add
# Create
# Refactor
# Fix
# Release
# Document
# Modify
# Update
# Remove
# Delete etc...
# About resetting:
# Use git revert instead of git reset in shared repositories
# git revert creates a new commit that introduces the opposite changes from the specified commit.
# Revert does not change history the original commit stays in the repository
# Difference between ~ and ^ in git:
# > ^ or ^n
# >no args: == ^1: the first parent commit
# >n: the nth parent commit
# > ~ or ~n
# >no args: == ~1: the first commit back, following 1st parent
# >n: number of commits back, following only 1st parent
# note: ^ and ~ can be combined
# Some tools to improve git skill by visualizing it:
# https://git-school.github.io/visualizing-git/
# https://learngitbranching.js.org/

View File

@ -165,7 +165,7 @@ server {
# The majority of SSL options depend on what your application does or needs # The majority of SSL options depend on what your application does or needs
server { server {
listen 443 ssl; listen 443 ssl http2;
server_name example.com; server_name example.com;
ssl on; ssl on;

View File

@ -215,6 +215,7 @@ z= suggest word
:q quit Vim. This fails when changes have been made. :q quit Vim. This fails when changes have been made.
:q! quit without writing. :q! quit without writing.
:cq quit always, without writing. :cq quit always, without writing.
:w save without exiting.
:wq write the current file and exit. :wq write the current file and exit.
:wq! write the current file and exit always. :wq! write the current file and exit always.
:wq {file} write to {file}. Exit if not editing the last :wq {file} write to {file}. Exit if not editing the last

View File

@ -54,12 +54,18 @@
- [`Gitignore`](https://marketplace.visualstudio.com/items?itemName=codezombiech.gitignore): An extension for Visual Studio Code that assists you in working with .gitignore files. - [`Gitignore`](https://marketplace.visualstudio.com/items?itemName=codezombiech.gitignore): An extension for Visual Studio Code that assists you in working with .gitignore files.
- [`GitLens`](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens): Visualize code authorship, code lens, seamlessly Git blame annotations and more.
- [`Gitmoji`](https://marketplace.visualstudio.com/items?itemName=Vtrois.gitmoji-vscode): An emoji tool for your git commit messages.
### Themes ### Themes
- [`Material Icon Theme`](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme): Material Design Icons for Visual Studio Code. - [`Material Icon Theme`](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme): Material Design Icons for Visual Studio Code.
- [`Palenight Theme`](https://marketplace.visualstudio.com/items?itemName=whizkydee.material-palenight-theme): An elegant and juicy material-like theme for Visual Studio Code. - [`Palenight Theme`](https://marketplace.visualstudio.com/items?itemName=whizkydee.material-palenight-theme): An elegant and juicy material-like theme for Visual Studio Code.
- [`Office Theme`](https://marketplace.visualstudio.com/items?itemName=huacat.office-theme) A Microsoft Office theme for Visual Studio Code.
### Handy ### Handy
- [`Better comments`](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments): Improve your code commenting by annotating with alert, informational, TODOs, and more! - [`Better comments`](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments): Improve your code commenting by annotating with alert, informational, TODOs, and more!
@ -96,6 +102,8 @@
- [`Wrap Console Log`](https://marketplace.visualstudio.com/items?itemName=midnightsyntax.vscode-wrap-console-log): Wrap to console.log by word or selection. - [`Wrap Console Log`](https://marketplace.visualstudio.com/items?itemName=midnightsyntax.vscode-wrap-console-log): Wrap to console.log by word or selection.
- [`Bracket Pair Colorizer`](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer): Allows matching brackets to be identified with colours.
## My Settings ## My Settings
```javascript ```javascript