diff --git a/README.md b/README.md index 5436080..cd2aa74 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ Feel free to take a look. You might learn new things. They have been designed to #### Javascript - [Adonis.js](backend/adonis.js) +- [Express.js](backend/express.js) - [Feathers.js](backend/feathers.js) - [Moleculer](backend/moleculer.js) - [Node.js](backend/node.js) diff --git a/backend/express.js b/backend/express.js new file mode 100644 index 0000000..d919bfb --- /dev/null +++ b/backend/express.js @@ -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)`; `// 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` \ No newline at end of file diff --git a/backend/node.js b/backend/node.js index a2a21e1..6bce482 100644 --- a/backend/node.js +++ b/backend/node.js @@ -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('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.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. diff --git a/languages/bash.sh b/languages/bash.sh index 4710b56..21204cd 100644 --- a/languages/bash.sh +++ b/languages/bash.sh @@ -46,6 +46,7 @@ CTRL+X then ( # start recording a keyboard macro CTRL+X then ) # finish recording 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+A then D # logout from screen but don't kill it, if any command exist, it will continue BACKSPACE # deletes one character backward DELETE # deletes one character under cursor @@ -54,6 +55,7 @@ history # shows command line history !! # repeats the last command ! # refers to command line 'n' ! # refers to command starting with 'string' +esc :wq # exits and saves script exit # logs out of current session @@ -87,8 +89,11 @@ readlink # shows where a symbolic links points to tree # show directories and subdirectories in easilly readable file tree mc # terminal file explorer (alternative to ncdu) touch # creates or updates (edit) your file -mktemp -t # make a temp file in /tmp/ which is deleted at next boot (-d to make directory) -cat # prints file raw content (will not be interpreted) +mktemp -t # make a temp file in /tmp/ which is deleted at next boot (-d to make directory) +cat # displays file raw content (will not be interpreted) +cat -n # shows number of lines +cat filename1 > filename2 # Copy filename1 to filename2 +cat filename1 >> filename2 # merge two files texts together any_command > # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout) more # shows the first part of a file (move with space and type q to quit) head # outputs the first lines of file (default: 10 lines) @@ -164,6 +169,7 @@ info # shows another documentation system for the specific c help # shows documentation about built-in commands and functions df # shows disk usage du # 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 # lists your last logins ps -u yourusername # lists your processes kill # kills the processes with the ID you gave @@ -179,8 +185,9 @@ whois # gets whois information for domain dig # gets DNS information for domain dig -x # reverses lookup host wget # downloads file +netstat # Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships -time # report time consumed by command execution +time # report time consumed by command execution ############################################################################## diff --git a/languages/golang.md b/languages/golang.md index 11e7dfd..fcb35fa 100644 --- a/languages/golang.md +++ b/languages/golang.md @@ -641,7 +641,7 @@ func TestSum(t *testing.T) { x, y := 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") } } diff --git a/languages/java.md b/languages/java.md index 7c9fd6a..48ccc1e 100644 --- a/languages/java.md +++ b/languages/java.md @@ -85,7 +85,7 @@ int c = a + b; double tan(double theta) //tangent of theta double toRadians(double degrees) // convert angle from degrees to radians 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 random() //random in [0,1) double sqrt(double a) //square root of a @@ -578,8 +578,8 @@ class MyClass extends MySuperClass implements YourInterface { ```java public class Queue implements Iterable - Queue() //create an emptyh queue - boolean isEmpthy() //return if the queue empthy + Queue() //create an empty queue + boolean isEmpty() //return if the queue empty 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 @@ -591,7 +591,7 @@ class MyClass extends MySuperClass implements YourInterface { //import Iterator import java.util.Iterator; -public class Queue implements Iterable { +public class Queue implements Iterable { //FIFO queue private Node first; @@ -627,9 +627,9 @@ public class Queue implements Iterable { * **SET DATA TYPE** ```java - public class SET> implements Iterable - SET() //create an empthy set - boolean isEmpthy() //return if the set is empthy + public class Set> implements Iterable + Set() //create an empty set + boolean isEmpty() //return if the set is empty 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 diff --git a/languages/python.md b/languages/python.md index d85910b..1eaf23e 100644 --- a/languages/python.md +++ b/languages/python.md @@ -70,15 +70,15 @@ | yield | yields values instead of returning (are called generators) | returning keyword | | import | import libraries/modules/packages | import | | from | import specific function/classes from modules/packages | import | -| try | this block will be tried to get executed | execption handling | -| execpt | is any execption/error has occured it'll be executed | execption handling | -| finally | It'll be executed no matter execption occurs or not | execption handling | -| raise | throws any specific error/execption | execption handling | -| assert | throws an AssertionError if condition is false | execption handling | +| try | this block will be tried to get 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 | +| raise | throws any specific error/exception | exception handling | +| assert | throws an AssertionError if condition is false | exception handling | | async | used to define asynchronous functions/co-routines | asynchronous programming | | await | used to specify a point when control is taken back | asynchronous programming | | 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 |
@@ -134,7 +134,7 @@ - Lists are created using square brackets: -```py +```python thislist = ["apple", "banana", "cherry"] ``` @@ -147,18 +147,31 @@ thislist = ["apple", "banana", "cherry"] - To determine how many items a list has, use the `len()` function. - A list can contain different data types: -```py +```python list1 = ["abc", 34, True, 40, "male"] ``` - 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 ``` +- 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 is a collection which is ordered and unchangeable. Allows duplicate members. - A tuple is a collection which is ordered and unchangeable. - Tuples are written with round brackets. -```py +```python thistuple = ("apple", "banana", "cherry") ``` - Tuple items are ordered, unchangeable, and allow duplicate values. @@ -168,25 +181,25 @@ thistuple = ("apple", "banana", "cherry") - 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: - Tuples allow duplicate values: -```py +```python thistuple = ("apple", "banana", "cherry", "apple", "cherry") ``` - To determine how many items a tuple has, use the `len()`function: -```py +```python thistuple = ("apple", "banana", "cherry") 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. -```py +```python thistuple = ("apple",) print(type(thistuple)) -#NOT a tuple +# NOT a tuple thistuple = ("apple") print(type(thistuple)) ``` - 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 print(thistuple) @@ -195,7 +208,7 @@ print(thistuple) ### Set - Set is a collection which is unordered and unindexed. No duplicate members. - A set is a collection which is both unordered and unindexed. -```py +```python thisset = {"apple", "banana", "cherry"} ``` - 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. - Duplicate values will be ignored. - To determine how many items a set has, use the `len()` method. -```py +```python thisset = {"apple", "banana", "cherry"} print(len(thisset)) ``` - Set items can be of any data type: -```py +```python set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} set4 = {"abc", 34, True, 40, "male"} ``` - 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 ``` +- 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 is a collection which is unordered and changeable. No duplicate members. - Dictionaries are used to store data values in key:value pairs. - Dictionaries are written with curly brackets, and have keys and values: -```py +```python thisdict = { "brand": "Ford", "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. -```py +```python thisdict = { "brand": "Ford", "model": "Mustang", @@ -246,11 +270,11 @@ print(thisdict["brand"]) - Dictionaries cannot have two items with the same key. - Duplicate values will overwrite existing values. - To determine how many items a dictionary has, use the `len()` function. -```py +```python print(len(thisdict)) ``` - The values in dictionary items can be of any data type -```py +```python thisdict = { "brand": "Ford", "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 -```py +```python if condition: pass elif condition2: @@ -278,7 +319,7 @@ thisdict = { #### While loop - 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 -```py +```python i = 1 while i < 6: 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. - 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"] for x in fruits: 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": -```py +```python adj = ["red", "big", "tasty"] 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. -```py +```python for x in [0, 1, 2]: pass ``` ### Function definition -```py +```python def function_name(): return ``` ### Function call -```py +```python function_name() ``` diff --git a/tools/git.sh b/tools/git.sh index 46573a0..c7048d0 100644 --- a/tools/git.sh +++ b/tools/git.sh @@ -4,15 +4,32 @@ git clone
# creates a git repo from given address (get the address fro git clone
-b # clones a git repo from the address into the given directory and checkout's the given branch git clone
-b --single-branch # Clones a single branch -git add file.txt # adds(stages) file.txt to the git +git add # adds(stages) file.txt 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 --hard # Throws away all your uncommitted changes, hard reset files to HEAD +git reset --soft # moves the head pointer +git reset --mixed # 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 # 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 --cached file.txt # only removes file.txt both from git index 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 -a # shows all the branches local and remote + git branch my-branch # creates my-branch git branch -d my-branch # deletes my-branch git checkout my-branch # switches to my-branch @@ -32,7 +49,13 @@ git remote add my-remote
# creates a remote (get the address from your git remote rm my-remote # Remove a remote 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=/, 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 --graph --decorate # shows the log of commits, each commit in a single line with graph +git log --since=