sahilrajput03

🤺︎ Hi there 👋 Trying what I can !

A Pragmatic software developer.

Curiosità is defined by Micheal J. Geib and Leonardo as “an insatiable curious approach to life and an unrelenting quest for continuous learning.”

relaxing

Unwinding is hot no-sugar coffee!

Technologies I can’t believe exists today: trpc, hasura and onegraph (graphiql-explorer).

echo Hello world! > /dev/null
cat /dev/null

Benchmarks: React Project Size

# 10 Jul, 2022
# INIT NEW REACT APP #
vite: 41mb
bun: 70mb
cna: 187mb
cra: 335mb

Jump Starters

Click here

TODO

References:

Source: https://stackoverflow.com/a/3760547/10012446

// For example the following text would act as link in vscode: file://./scripts/deployKryptoBird.js

Event Hosting platform

https://www.zuddl.com/

Deleting nested modules?

alias findNodeModules='sudo find . -name 'node_modules' -type d -prune'
alias deleteNestedNodeModules="sudo find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +"

Creating MRE’s

https://stackoverflow.com/help/minimal-reproducible-example

Most Amaizng graphql client library

https://github.com/gqty-dev/gqty

insomnia vs. postman

https://gist.github.com/samoshkin/c0a2c0dd85b1d5b02d893a0f6ac0e93c

What is LOC?

image

what is sloc?

image

Add github comment system to your blog

React Giscus Component: Click here

image

image

Looks like a good cache library

Inspiration: https://github.com/simoneb/axios-hooks#manual-requests

https://github.com/isaacs/node-lru-cache

Get name and emails of all the authors of a git repo from the repository history

git log -s --format='%an %ae'
# %an is for author name
# %ae is for author email
# Read whole docs @ https://git-scm.com/docs/git-log
# Inspiration: https://stackoverflow.com/a/29876744

Fix cors errors without fixing backend in chrome

Chrome Extension: CORS Unblock

To test if cors get unblocked you can check via that page:

image

image

image

Google maps apis is paid

Source: https://developers.google.com/maps/documentation/javascript/get-api-key

image

Tip: Using github to edit repo files on mobile

Use chrome in desktop mode and then you’ll be able to add pictures as well, yo!

react native vs. flutter

https://youtu.be/3_FcxGCCnUs

Amazing article explaining nextjs’s middleware and netflify’s edge html rewriting

https://www.netlify.com/blog/rewrite-html-transform-page-props-in-nextjs/

Learn maps and sets

Source: Kyle

Maps are for objects, and sets are for arrays.

image

Sets store unique values only:

image image image

Array.slice returns a shallow copy: Remeber it

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

image

website performance analytics

source: https://pagespeed.web.dev/

image

Source: https://gtmetrix.com/

image

cli apps with react?

Github: https://github.com/vadimdemedes/ink

image

Lol

src

image

mutation observer

Generating real ssl certificate using letsencrypt on cli

image

using %s, %f, %d in javascipt

@mdn: https://developer.mozilla.org/en-US/docs/Web/API/console

image

making insecure requests with postman or curl

Case Scenario: Say you are running a flask server via:

flask run --cert=adhoc --host=0.0.0.0

so when if try to request from a curl or postman you wont’ see any response bcoz both of these (curl / postman) are not enabled for secure requests.

For curl you can make use ok -k option:

curl -k https://mynotifyservice.ddns.net:5000/

For postman:

image

We can have multiple developer tools open for a single tab as well

image

This is such a lifesaver from github

image

Why postgres/mongodb over firebase #jimmy_chae?

Firebase cons: ~Sahil (points I have currently in my mind)

image

image

module system nodejs

Source: https://stackoverflow.com/a/29262643/10012446

image

image

image

Browser developer tools

image

Files and blobs(binary object) in javascript

// text to binary object
const someData = new Blob(["hello world"])
// files
const readmeFile = new File('Run node src/index.js for a friendly greeting.', 'README.txt', { type: 'text/plain' })
const sourceFile = new File('console.log("hello, world")', 'src/index.js', { type: 'text/javascript' })

Filtering merged PR’s on a github repo

image

ml in action

Source: https://youtu.be/VwVg9jCtqaU

Source Code for rock-paper-scissor identification code: https://colab.research.google.com/github/lmoroney/io19/blob/master/Zero%20to%20Hero/Rock-Paper-Scissors.ipynb

Sample try out project on medium.com: https://blog.devcenter.co/developing-a-license-plate-recognition-system-with-machine-learning-in-python-787833569ccd

image

Q. How does flatten work in Keras ?

Ans. https://stackoverflow.com/questions/44176982/how-does-the-flatten-layer-work-in-keras

Color Depth: @wikipedia

Deal with race conditions easily

let flag = true

setTimeout(() => {
	flag = false
}, 500)


void (async function () {
	await new Promise(res => setTimeout(res, 1_000))
	console.log('Final:', flag) // Output: false
})()

flakey testing

A flaky test is an analysis of web application code that fails to produce the same result each time the same analysis is run.

Docs made easy

https://github.com/readthedocs/readthedocs.org used to make solidity docs.

futter market demand

https://www.monterail.com/blog/flutter-vs-react-native-mobile-development

learn js classes

class Animal {
	static belly = []
	eat() {
		Animal.belly.push('food')
	}
}
let a = new Animal()
a.eat()

console.log(Animal.belly[0]) // food

E.g., 2

let bear = {
	sound: 'roar',
	roar() {
		console.log(this.sound)
	},
}

bear.sound = 'grunt'
let bearSound = bear.roar
bearSound() // undefined
bear.roar() // grunt

what is e+ powers?

People in this earth is 8 Billion (8.0e+09)

what are opnionated softwares/frameworks

tldr; If a framework is opinionated, it lock or guides you into their way of doing things.

online timer apps

void usage in javascript

image

image

Source of below code: MDN

const output = void 1;
console.log(output);
// expected output: undefined

void console.log('expression evaluated');
// expected output: "expression evaluated"

void function iife() {
  console.log('iife is executed');
}();
// expected output: iife is executed

void function test() {
  console.log('test function executed');
};
try {
  test();
} catch (e) {
  console.log('test function is not defined');
  // expected output: "test function is not defined"
}

bandwidth and throughput?

image

image

unsigned means?

Dictionary - unsigned : not having a plus or minus sign, or a bit representing this.

Unsigned Integers (often called “uints”) are just like integers (whole numbers) but have the property that they don’t have a + or - sign associated with them. Thus they are always non-negative (zero or positive). We use uint’s when we know the value we are counting will always be non-negative.

#scroll #scrollto #scrollintoview

scrollTo - MDN scrollIntoView - MDN

s1 s2

Stakoverflows: 1

lastChild vs. lastElementChild

tldr; Use lastElementChild to get html node but use lastChild if you may want the some plain text or comment that is there in the last in that element.

Source: https://melvingeorge.me/blog/difference-between-lastchild-and-lastelementchild-element-property-javascript

How a system can answer some quetion about working of its own function?

Ans. If its implements a goal tree then it can! Source

image

Guide: Click here

Tldr: Press ctrl+shift+p and command starting with “Confgiure Recommended Extension..” and now use ctrl+space toggle up the possible extension inputs from your currently installed extension. YO!!

casting laptop screent to tv (chromecast)

image

image

dapps

Article - https://blog.itsrakesh.co/what-are-dapps-how-they-are-different-from-normal-apps

Article - https://blog.itsrakesh.co/what-is-blockchain-how-does-it-work

Don’t abuse arrow functions in 2022

https://javascript.plainenglish.io/its-2022-don-t-abuse-the-arrow-function-anymore-905862a9c668

Execute code on tab close

window.addEventListener("beforeunload", (e) => {
  e.preventDefault();
  e.returnValue = ""; // this value has to be other than null and undefined.
});

// for react, use reference: https://bobbyhadz.com/blog/react-handle-tab-close-event
// amazing blogger: https://bobbyhadz.com/

So when you try to close tab, browser will ask once again like that -

image

@mdn docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

image

builtin assertion library - nodjs

inspir

const { deepStrictEqual:dse } = require('assert');
let a = {x: 10, y: 10}
let b = {x: 10, z: 20}
dse(a,a)
dse(a,b)

Thats how colors work in nodejs

FYI; In node repl mode, src.

Finally, the optional argument colorize is a boolean that adds ANSI escape codes to the string output. When logged to a terminal window, it should be pretty printed with colors. ~ Same above source page of nodejs docs.

image

Named arguments for self knowledge - Javascript

let z = (a,b) => console.log({a,b})

z(first=10, second=20) // {a: 10, b: 20}
z(i=10, j=20) // {a: 10, b: 20}

Calling one express route from another route

Source: https://stackoverflow.com/a/38948889/10012446

I added answer to that question as well, here: https://stackoverflow.com/a/73001807/10012446

Hilarious and Feels stupid to think of this though now.

// @ts-nocheck
const app = require('express')()
const axios = require('axios')
const log = console.log

app.get('/', (req, res) => {
	res.json('yoy')
})

const listener = app.listen(async () => {
	const url = 'http://localhost:' + listener.address().port // IF you are using static port value you do not need `listener.address().port` and simply provide that port value here instead.
	log({url})

	let response = await axios.get(url)
	log('GOT DATA IN RESPONSE:', response.data) // yoy
})

If you are using it general case i.e., STATIC PORT value, you can do it like:

// @ts-nocheck
const app = require('express')()
const axios = require('axios')
const log = console.log

const PORT = 3000
const URL = 'http://localhost:' + PORT
const apiPath = (path) => URL + path

app.get('/a', (req, res) => {
	res.json('yoy')
})

app.listen(PORT, async () => {
	let response = await axios.get(apiPath('/a'))
	log('RESPONSE DATA:', response.data)
})

Object.is is better than === ? tldr Yes, a little bit.

Source: https://stackoverflow.com/a/30543212/10012446

image

what venv in python?

chmod +x run.sh
python -m venv env
source env/bin/activate
pip install -r requirements.txt
./run.sh



## thats how u use environment variables in python
email = os.environ['EMAIL']
password = os.environ['PASSWORD']

Above is a common setup to start start a python project( that is a flask project though). But in above commands,

# creates the virtualenv, you need to run that only once, its like `node_modules` in node. Source: https://docs.python.org/3/library/venv.html
python -m venv env

# source (activate) the virtual env in current bash shell
source env/bin/activate

nextAuth?

image

validation in javascript

If using typescript: https://github.com/colinhacks/zod (9k*)

If using javascript: https://github.com/jquense/yup (17.6k*)

parseInt() vs. Number()

console.log(Number(22.1)) // 22.1
console.log(parseInt(22.1)) // 22

Netlify acquired onegraph

Date: 17 Nov, 2021 - Click here

object to params ?

let a = {car: 10, bar: 20}

// src: https://stackoverflow.com/a/23639793/10012446
let objectToParams = (obj) => Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');

objectToParams(a) // 'car=10&bar=20'

toJSON in JSON.stringify function ?

Read messages and read contacts with pwa

https://youtu.be/2mX8hmefCRI?t=450

sleep

what is it to sleep @5am

mimic your voice with system ?

https://www.descript.com/lyrebird

~ Varun mayy, you can make text to sound of your own voice with that.

All-in-one audio & video editing, as easy as a doc.
https://www.descript.com/

Posthog - an opensource analytical tool

Github: https://github.com/PostHog/posthog

Used by Varun Mayyas he tells in this video.

Visit at: https://posthog.com/

ui sources - has all the screenshots of all the apps

https://www.uisources.com/home

~Varun mayya’s frined, src: here-timestamped

Reducing apk size of react-native apps?

A better and easy way to setup github credentials on local git

Source - Docs - Authenticating with GitHub from Git

image

Github opensource docs

Repo: https://github.com/github/docs

Source: Click here

image

Unicode symbols Website

https://www.amp-what.com/unicode/search/up%20arrow

Anatomy of html documents by mdn

https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started#anatomy_of_an_html_document

Labelled statement in javascript

Awesome: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

Src: https://youtu.be/AdNJ3fydeao?t=949

Awesome ni package mangager :LOL:

https://github.com/antfu/ni

Github’s Official .gitignore files for different enviornments

https://github.com/github/gitignore

https://github.com/github/gitignore/blob/main/Node.gitignore

Whats your ping?

image

Insert at in arrays in js

var arr = []
arr[0] = 'Jani'
arr[1] = 'Hege'
arr[2] = 'Stale'
arr[3] = 'Kai Jim'
arr[4] = 'Borge'

console.log(arr) // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, 'Lene')
console.log(arr) // Jani,Hege,Lene,Stale,Kai Jim,Borge

Community version of dalle 1 (free to use completely)

https://huggingface.co/

https://github.com/huggingface/transformers

Problem with token based authentication

Source: https://fullstackopen.com/en/part4/token_authentication#problems-of-token-based-authentication

image

React server components(still in development though) is used by Hydrogen developers(a shopify framework)

Source: https://shopify.engineering/how-we-built-hydrogen

Amazing guide on testing containing objects in an array, works 100%

Source: https://codewithhugo.com/jest-array-object-match-contain/

test('LEARN: array containing an object', () => {
	// src: https://jestjs.io/docs/expect#expectarraycontainingarray
	const expected = {name: 'sahil'}
	const received = [{name: 'sahil', lastname: 'rajput'}, {otherObjectsAnyShape: 'Rohit'}]

	// Src: https://codewithhugo.com/jest-array-object-match-contain/
	expect(received).toEqual(expect.arrayContaining([expect.objectContaining(expected)]))
})

Arranging date named objects in alphabetical order?

A good exerpt on that problem.

Save the migration code in the file migrations/20211209_00_initialize_notes_and_users.js. Migration file names should always be named alphabetically when created so that previous changes are always before newer changes. One good way to achieve this order is to start the migration file name with the date and a sequence number.

Did you know “We can get the number of parameters defined in its function definition ?

((a) => {}).length // 1
((a, b) => {}).length // 2
((a, b, c) => {}).length //3

Expressjs uses this to identify if the callback you specified has two or three OR four params in its definition and based on that it judges if the middles should be treated as a errorHandler or simple middleware. Yikes!

chai-http is like supertest

chaijs is assertion library like assert + http testing library like supertest

https://www.chaijs.com/plugins/chai-http/

Finally Intellgence as a service goona be paid

image

Scaling console.logs?

You can print the filename and linenumber of the console.log very easily using some stacktrace hack.

What I made out of this? Click here

# learn:
# src https://stackoverflow.com/a/14172822/10012446 (<< this answer has another link of stackoverflow answer i.e., src of this answer: https://stackoverflow.com/questions/11386492/accessing-line-number-in-v8-javascript-chrome-node-js)
# src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack


Creating .d.ts files in js/ts ?

Its a myth coz tsc generates this for its own use, but you can write your own for vanilla js projects typechecking as well using // @ts-check comment on top of .js files

Click here

Leadership Principles ~ Sequoya’s memo (src)

vscode cli options

image

Figjam for online flowcharts/diagramming

Youtube: https://www.youtube.com/watch?v=giCx1LPizXU

Promisification

https://javascript.info/promisify

https://www.tutorialspoint.com/node-js-util-promisify-method

https://nodejs.org/api/util.html#utilpromisifyoriginal

https://nodejs.org/api/fs.html#filehandlereadfileoptions

In nodejs: We have util.promisify buitin method basically takes a function as an input that follows the common Node.js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.

import { readFile } from 'node:fs';


let callback =  (err, data) => {
  if (err) throw err;
  console.log(data);
}

// Callback Usage:
readFile('/etc/passwd', callback); // OR 
readFile('/etc/passwd', 'utf8', callback);

// Making use of util.promisify
const util = require('node:util');

// Reading the file using a promise & printing its text
const readFileSync = util.promisify(fs.readFile);
readFileSync('./promisify.js', 'utf8') // Reading the same file
   .then((text) => {
      console.log(text);
   })
// Printing error if any
   .catch((err) => {
      console.log('Error', err);
});

Why tdd with backend development?

Structure for expressjs + sequelize setup (multi models + controllers setup)

https://github.com/fullstack-hy/part13-notes/tree/part13-2

Whatsapp chatbots made easy!

How to Create & Test your WhatsApp Chatbot (No Coding)

Pwa Install prompt?

image

image

Most of times apps can be pwa @ playstore:

Src: https://www.youtube.com/watch?v=cybhV88KLfI

image

This is pretty solid(coz it can generate apk{for playstore distributio}, appix{for windows stores} and ios packages as well for ios store ditribution, BUT USING MY OWN WAY OF APK DEVELOPMENT IS BEST ~ IMO ~ SAHIL): image

Using abort controller with react!

Source@timestamped

image

FYI-Using builtin abort controller in react-query

image

set input as numeric in forms?

Source: css-tricks

<input inputmode="numeric" type="text" name="creditcard">

Add a npm script via cli

Source

npm set-script prepare "husky install"

Handling spa with github pages

Source: Stackoverflow Answer, also from github - Github 404 Docs

Demo: https://spa-github-pages.rafgraph.dev/, Github: https://github.com/rafgraph/spa-github-pages

tldr; 404.htm file: Click here.

And script to be added in index.html file

Source: here

<head>
...
...
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // MIT License
      // https://github.com/rafgraph/spa-github-pages
      // This script checks to see if a redirect is present in the query string,
      // converts it back into the correct url and adds it to the
      // browser's history using window.history.replaceState(...),
      // which won't cause the browser to attempt to load the new url.
      // When the single page app is loaded further down in this file,
      // the correct url will be waiting in the browser's history for
      // the single page app to route accordingly.
      (function(l) {
        if (l.search[1] === '/' ) {
          var decoded = l.search.slice(1).split('&').map(function(s) { 
            return s.replace(/~and~/g, '&')
          }).join('?');
          window.history.replaceState(null, null,
              l.pathname.slice(0, -1) + decoded + l.hash
          );
        }
      }(window.location))
    </script>
	
</head>

Proxy and base-code-structure for any possible server-functions library

image

const target = {};

const handler3 = {
  get(target, prop, receiver) {
    return () => console.log('fun?:', prop)
  },
};

const proxy3 = new Proxy(target, handler3);

proxy3.a()
// VM583:5 fun?: a

proxy3.b()
// VM583:5 fun?: b

Create live expressions

image

This is magically amazing!!

magic code for edge caching (setting cache headers)

Source: https://trpc.io/docs/, Code @ https://github.com/KATT/typescript.careers

Source: https://youtu.be/-_GZJ3xwYOw

Learn: Endpoint caching is possible for get requests only (trpc uses get requests for all requests) and graphql uses post request for all requests so it makes it hard to cache any endpoint request.

image

image

What is save-exact in .npmrc ?

Source: https://stackoverflow.com/a/64507176/10012446

image

write on screen and copy/save the image

Press prtscr and press ctrl+a to select all the area on screen and now you can use pencil(P), arrow(A), line(D) and more tools in flameshot.

chalk usage

Struck at chalk - Error [ERR_REQUIRE_ESM]: require() of ES Module ??

Source: https://stackoverflow.com/a/70748594/10012446

npm uninstall chalk
npm i chalk@4.1.2

now you can use:

const chalk = require('chalk');
console.log(chalk.blue('Hello world!')); 

todo-read

how to do 10k concurrent or millions of RPS (Requests Per Second)

  1. https://stackoverflow.com/questions/34855352/how-in-general-does-node-js-handle-10-000-concurrent-requests

  2. https://www.quora.com/Is-it-possible-for-server-to-handle-around-100-000-requests-per-second-If-so-which-would-you-recommend

Learn about express-async-errors npm package

Go to https://github.com/sahilrajput03/learn-express

Complete command line solution for nodejs

Source: https://www.npmjs.com/package/commander

22.7k Github Stars, It has more than 73m weekly downloads(from npmjs.com)

Make you router page available on the public ip address

You can do this by mapping port of router ip (probably 192.168.18.1) to public ip in your router settings.

Using custom environment files i.e., .env.dev or .env.test

We use them by definig their file path in package.json file. Below project is here. Look for dev and dev2 scripts below and their respective comments as well.

image

FYI: To make the env file provided as argument is implemented via dotenv like this:

image

created flash-runner npm package

Browse @ https://www.npmjs.com/package/flash-runner

Github @ https://github.com/sahilrajput03/flash-runner-npm

npm i flash-runner

blockchain ?

https://stackoverflow.blog/2021/06/07/most-developers-believe-blockchain-technology-is-a-game-changer-3/

programming, scripting, and markup languages?

collaborative work management tool

image

recent comment backup

Originally posted here.

I am pretty noob js developer but I made something up that solves* this issue. And please don’t critize I just mean to present a solution for curious people by this comment.

* means solving with my own test runner not with jest runner.

flash is my test runner I created few days back, to test this you need below setup:

git clone https://github.com/sahilrajput03/flash
cd flash && npm link
cd ..

git clone https://github.com/sahilrajput03/learning-monogo-and-mongoosejs
cd learning-monogo-and-mongoosejs/mongoosejs-with-hot-flash
npm i && npm link flash
npm start

Now if you edit code in code.js, then you database connection won’t be thrown away but reused thus giving you a lightning fast TDD experience with no connection loosing on running tests while in watch mode.

Why and how I love and hate jest ?

Love: Bcoz its assertion i.e., expect and expect’s docs is open source. So this allows me to use their assertions in my own test runner library. Yikes!

I.e.,

npm i expect
const {expect} = require('expect')
expect('1').toBe('2') // throws error just like jest does!

Hate: Jest’s test runner has no capability to share values and module between tests suites in watch mode. Issue closed here. But it seems that work is going on this issue here.

Q. Anyway what are mockig really useful for like this library nock ? ~ Sahil

What is a/ and b/ in git diff command?

Source: https://stackoverflow.com/a/6764988/10012446

tldr;

a means before and b means after. You can remember it like when going from a -> b i.e., in chronogical manner ~Sahil.

How come a library like tailwindcss have 56.6 stars on github ?

https://github.com/tailwindlabs/tailwindcss

Find my own demo app @ https://github.com/sahilrajput03/cssDesignTrail/tree/master/learn-tailwindcss

Its revolutional for me personally!

Testing react apps with jest and react-testing-library (or enzyme)

Source: https://jestjs.io/docs/tutorial-react

The one stop solution for the confusion b/w localStorage vs. cookies decision in your website!

Source: https://academind.com/tutorials/localstorage-vs-cookies-xss . Wanna read about cors from same author ?. Mdn - Restrict access to cookies.

image

google.com cookes looks like this

image

Created a clone of lowdb

Browse @ https://codesandbox.io/s/low-db-clone-t4lbln?file=/src/App.js

Lowdb: https://github.com/typicode/lowdb

chokidar has also a cli version

https://github.com/open-cli-tools/chokidar-cli

Used by: https://github.com/typicode/xv - A test runnder by typicode.

lowdb rocks (a tool to manage localStorage most beautiful api)

Docs: https://github.com/typicode/lowdb

This library is from *typicode who is also creator of json-server, husky, jsonplaceholder and xv and all all of them are his github.*

Find out @ https://stackblitz.com/edit/react-fjnkr5?file=src%2FApp.js

Also, it is also useful with nodejs as it will write to json files on updating the data, yikes!

Yes you can change a variable’s value in the browser debugger as well

TESTED: Works 100%

image

Also works via terminal as well:

image

Documentation Generator in Javascript

https://github.com/TypeStrong/typedoc

This is used by kubernetes-client to generated docs for them @ https://github.com/kubernetes-client/javascript

Default values for functions

function a(c = 10) {
	return c
}

console.log(a(null))
// Output: null

console.log(a())
// Output: 10

Ml resources, neural networks

Make apk from a website now!

Deploy website to playstore-

  1. Hybrid web view app using Ionic (but downside is that we would need to )
  2. Use TWA (trusted web activites) REFER MY OWN REPO TO SEE THIS AWESOME WAY.

FYI:

Startup checkout?

global won’t work good in react project outside of components (see the codesandbox to understand that!)

Source: https://codesandbox.io/s/globalandglobalthis-o262ir?file=/src/App.js

image

FYI: Learn about globalThis: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

Ngrok docs

https://ngrok.com/docs

What is global in nodejs?

YES, global variables are supported in nodejs!! So this facilitates us to define variables, fucntion in one place and use them in different files without using module.exports at all. Yikes!

global.studentName = 'Kyle'

console.log(`Hello, ${ global.studentName }!`)
// Hello, Kyle!

console.log(`Hello, ${ studentName }!`)
// Hello, Kyle!

// src: https://stackoverflow.com/a/66293366/10012446

Also you can now access studentName in any module which is loaded after after we define global.studentName variable.

LEARN: nodejs docs: https://nodejs.org/api/globals.html#globals_global

LEARN: I used this global in my own testing library in tihs file: https://github.com/sahilrajput03/learn-express/blob/main/testing-with-my-testing-library/tests/_setup_test_globals.js#L30-L36

Sequnetial execution of aysnc calls

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await…of

Tags: #Parallel execution, #sequential execution, etc.

Why Flameshot?

live reload browser in sync with backend as well

https://dev.to/rajeshroyal/how-to-live-reload-node-js-server-along-with-hot-reloading-2im0

What is a=b=c in code?

let a,b,c
a = b = c = 10
console.log(a,b,c)
// Output: 10 10 10

Checkout my login flow diagram with mermaidjs

Find here.

React dev tools show react hooks state!

image

Yes its all there, but that changes in react state are reflected with a delay of like 500ms IMO ~Sahil.

Git submodules

Adding a github submodule

git submodule add "github_url" directory_path

How to fix submodule shit..?

Problem: If you accidentally did a git add . in any of your github repo where you had some nested repository, then git automatically adds that repository as a submodule to your existing (parent repository) and then you don’t get a live link in your github repo page.

How to FIX

Simply move your nested git repo elsewhere and do a commit to clean it for a while, and then move back the nestedGitRepo back to where it was and add it in proper way, followed by git commit. It looks like that:

mv someNestedGitRepo ../
git add . && git commit -m "Remove submodule."
# Now, move back the nestedGitRepo back to current repo and add it in proper way!
mv ../someNestedRepo .
git submodule add "github_url" directory_path
# Now, you get to commit, and its done!
git add . && git commit -m Fix submodule.

Sources for git submodules

To clone a git repo with all its nested submodules 🚴︎ 🚴︎

Just use

gclWithSubmodules
# gclWithSubmodules is aliased to `git clone --recurse-submodules -j8'

edited by cacher.

Using themes with github pages (via jekyll)

Re-add a revert commit?

https://stackoverflow.com/a/29975312/10012446

tldr;

You can simply revert the revert commit to undo the revert via git revert <revertCommitShaHere>. ~Sahil

What is NAT in vmware, virtualbox and kvm?

Network Address Translation (NAT) is the simplest way of accessing an external network from a virtual machine. Usually, it does not require any configuration on the host network and guest system. For this reason, it is the default networking mode in Oracle VM VirtualBox.

Source: Docs - Virtual Box

Learn programming through test driven process

Go (17.4k stars): https://quii.gitbook.io/learn-go-with-tests/

Go by example: https://quii.gitbook.io/learn-go-with-tests/

Official Go tourhttps://go.dev/tour/welcome/1

Official Go Playground: go.dev/play

Source: Hackerrank article

Source: [Golang Tutorial for Beginners Full Go Course by TechWorld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I) (An amazing video to watch for learning all the stuff of go including packaging/module stuff).

image

Setting size of image in github markdown

Source: https://gist.github.com/uupaa/f77d2bcf4dc7a294d109

![](https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png =250x250)
![](https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png | width=100)
<img src="https://camo.githubusercontent.com/..." data-canonical-src="https://gyazo.com/eb5c5741b6a9a16c692170a41a49c858.png" width="200" height="400" />

kvm wins over virtual box in software market and coz of its performance and robustness

Source: Q/A

ssh to virt-manager’s running container

**FYI: You can add bluetooth device in your kvm container very easily by going to settings and click “Add hardware” and then follow from there to “USB Host Device” option and choose your bluetooth device there. Yo!

image

Update (i.e., pull) a submodule in a git repo

Source: https://stackoverflow.com/a/8191375/10012446

git submodule update

why shebang is called shebang ?

Source: https://unix.stackexchange.com/a/149048/504112

forever a npm package to ensure ensure that a script is running forever

https://github.com/foreversd/forever#readme

Random number generation ?

Joke: https://xkcd.com/221/

Math Stackexchange: https://math.stackexchange.com/questions/255610/easy-way-to-generate-random-numbers

express js loop holes ?

	return res.status(200).json('ok') // FYI: This is valid json though!
// ^^^^^^^^^^^^^^ this actually sends status code 304 IDK why on earth!

	return res.status(200).send('ok') // FYI: This is valid json though!
// ^^^^^^^^^^^^^^ this actually sends status code 200.

vertical and horizontal pod scaling, what kind of constratins to consider?

# usefule text from: https://devopswithkubernetes.com/part-3/3-gke-features
# Scaling
Scaling can be either horizontal scaling or vertical scaling. Vertical scaling is the act of increasing resources available to a pod or a node. Horizontal scaling is what we most often mean when talking about scaling, increasing the number of pods or nodes. We'll focus on horizontal scaling.

There are multiple reasons for wanting to scale an application. The most common reason is that the number of requests an application receives exceeds the number of requests that can be processed. Limitations are often either the amount of requests that a framework is intended to handle or the actual CPU or RAM.

Figuring out autoscaling with HorizontalPodAutoscalers can be one of the more challening tasks. Choosing which resources to look at and when to scale is not easy. In our case, we only stress the CPU. But your applications may need to scale based on, and take into consideration, a number of resources e.g. network, disk or memory.

Difference between |, |>, > and >- in yaml ?

Key1: >
  Line 1
  LIne 2

# (no newline character after in the end)
Key2: >-
  Line 1
  Line 2

Key3: |
  Line 1
  LINE 2

#  (no newline character after in the end)
Key4: |-
  Line 1
  LINE 2

is converted to json

{
   "Key1": "Line 1 LIne 2\n",
   "Key2": "Line 1 Line 2",
   "Key3": "Line 1\nLINE 2\n",
   "Key4": "Line 1\nLINE 2"
}

Source: https://stackoverflow.com/a/3790497/10012446

Proof of convertion trial @ https://www.convertjson.com/yaml-to-json.htm

Using select menus in bash

learn-bash.md#using-select-menus-in-bash

Swithing to terminal to run a bash script or npm command very often?

Consider using a .vscode/tasks.json file (you can autogenerate this file with vscode very easily). I personally use ctrl+alt+r keybinding to launch run tasks, yo!!

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "shell",
			// "command": "pwd", // for testing.
			"command": "./fso-part13/curls/post_note.sh",
			"label": "post a note ~Sahil"
		},
		{
			"type": "shell",
			"command": "./fso-part13/curls/get_a_note.sh",
			"label": "Get a note ~Sahil"
		},
		{
			"type": "shell",
			"command": "./fso-part13/curls/resetNotes.sh",
			"label": "Reset notes table! ~Sahil"
		}
	]
}

json to xml converter

What is canaray releases ?

Canary release is a technique to reduce the risk of introducing a new software version in production by slowly rolling out the change to a small subset of users before rolling it out to the entire infrastructure and making it available to everybody.

Source: https://martinfowler.com/bliki/CanaryRelease.html

What is reverse psychology?

https://en.wikipedia.org/wiki/Reverse_psychology

retrieval practise

https://en.wikipedia.org/wiki/Testing_effect

serverless and utility computing

https://en.wikipedia.org/wiki/Serverless_computing

https://en.wikipedia.org/wiki/Utility_computing

firebase

At: console.firebase.google.com

Pricing: https://firebase.google.com/pricing

react-router, react-dom or react-router-dom, what the difference?

You can checkout that react-router is a dependency of react-router-dom @ npm’s package page.

FYI: react-router is also a dependency of react-router-native.

react-dom: This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as react to npm.

what is env cli ?

Linked quest: What is #/usr/bin/env bash or #/usr/bin/env node shebang in various scripts ?

From man env in terminal, I found:

Ans. env - run a program in a modified environment.

type env
# Output:
# env is hashed (/usr/bin/env)

env --help
# Output:
# Usage: env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]
# Set each NAME to VALUE in the environment and run COMMAND.
# 
# Mandatory arguments to long options are mandatory for short options too.
#   -i, --ignore-environment  start with an empty environment
#   -0, --null           end each output line with NUL, not newline
#   -u, --unset=NAME     remove variable from the environment
#   -C, --chdir=DIR      change working directory to DIR
#   -S, --split-string=S  process and split S into separate arguments;
#                         used to pass multiple arguments on shebang lines
#       --block-signal[=SIG]    block delivery of SIG signal(s) to COMMAND
#       --default-signal[=SIG]  reset handling of SIG signal(s) to the default
#       --ignore-signal[=SIG]   set handling of SIG signal(s) to do nothing
#       --list-signal-handling  list non default signal handling to stderr
#   -v, --debug          print verbose information for each processing step
#       --help     display this help and exit
#       --version  output version information and exit
# 
# A mere - implies -i.  If no COMMAND, print the resulting environment.
# 
# SIG may be a signal name like 'PIPE', or a signal number like '13'.
# Without SIG, all known signals are included.  Multiple signals can be
# comma-separated.
# 
# GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
# Full documentation <https://www.gnu.org/software/coreutils/env>
# or available locally via: info '(coreutils) env invocation'

man env
# Output: manual pages!

kubernetes hierarchy

Kubernetes cluster is a group of nodes!

A node can have a list of deployments.

A deployment controls a list of pods.

A pod has a list of containers.

Replicas (.spec.replicas) is no. of replicated pod which will be created.

A kubelet is an agent that runs on each node in the cluster. It makes sure that containers are running in a pod.

what?

https://en.wikipedia.org/wiki/Recursive_Bayesian_estimation helps to pick up abnormal activity say if people try to scrap off content from fb, they used this esimation to detect that and ban it.

Src: https://www.youtube.com/watch?v=xFFs9UgOAlE

memcache used by fb earlier

https://github.com/memcached/memcached

https://memcached.org/

flashcards website

Website: http://cram.com

Playstore App (free services): Click here

You may login with google simply. It has a playstore app as well.

send a file with express route

https://stackoverflow.com/a/17516733/10012446

downloading image with axios

Src: https://futurestud.io/tutorials/download-files-images-with-axios-in-node-js

bus factor

From Wikipedia, the free encyclopedia

The bus factor is a measurement of the risk resulting from information and capabilities not being shared among team members, derived from the phrase “in case they get hit by a bus”. It is also known as the bus problem, lottery factor, truck factor,[1] bus/truck number, or lorry factor.

In a sentence (from devopsiwthkubernetes): If your files don’t tell Kubernetes and your team what the state should be and instead you run commands that edit the state you are just lowering the bus factor for your cluster and application.

Why do one need a mock testing? : Click here to know.

Getting automated “Product experience insights” using https://www.hotjar.com/

(free to use)no-Code Website Builder: The Webflow Designer lets you build any website you can imagine with the full power of HTML, CSS, and Javascript in a VISUAL CANVAS. using https://webflow.com/. See customer stories of webflow users.

Schedule your meets with anybody ? Ans. *A perfect solution*: https://calendly.com/app/signup

things i kept doing doing..

I have a habit of looking for the best of best of the articles, courses, blogs, books, materials that I feel sometimes is a time taking process and I don’t follow or kind of forget like the official way of doing things me or anybody else must be doing, i.e., follow official documentation of softwares, libraries, tools, standards, ie., OFFICIAL documentation. One big mistake: “Not able to find the real production ready free template of coreui in previous job is this only”.

using auto-changelog

Source: https://www.npmjs.com/package/auto-changelog

Sample generated: Click here

Sample (this repository): Click here

Tip: You can use custom template as shown here in docs.

Add below to your package.json file and run npm run changelog to generate a CHANGELOG.md file. It simply generates list of all commit to the target file simply date wise.

    "changelog": "auto-changelog -p --commit-limit false"

FYI (using -p is important else you won’t get commits in your CHANGELOG.md file): -p, --package # use version from package.json as latest release

FYI: If you plan to execute it on npm version script, then you do it like (official docs of auto-changelog):

  "scripts": {
    "version": "auto-changelog -p && git add CHANGELOG.md"
  }

HENCE, whenever you run npm version patch/minor/major, your version script will be run as well. YO

monkeypatching ( or _hot fixes) ?

Source: https://en.wikipedia.org/wiki/Monkey_patch

A monkey patch is a way for a program to extend or modify supporting system software locally (affecting only the running instance of the program).

Etymology

The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime. The word guerrilla, homophonous with gorilla (or nearly so), became monkey, possibly to make the patch sound less intimidating.[1]

An alternative etymology is that it refers to “monkeying about” with the code (messing with it).

Despite the name’s suggestion, the “monkey patch” is sometimes the official method of extending a program. For example, web browsers such as Firefox and Internet Explorer used to encourage this, although modern browsers (including Firefox) now have an official extensions system.

get 1 day or some weeks ago git diff

Source: https://stackoverflow.com/a/9658178/10012446

# Get diff for only today
git diff 'HEAD@{1 day ago}'

# Get diff from 3weeks back
git diff 'HEAD@{3 weeks ago}'

cool alias

alias lsg='ls -a | grep -i'
# Usage:
lsg json
lsg -E '*json'
# NOTE: quotes are important.( double quotes work as well).

cool things about kentcdodds that i didn’t know

  1. He is 11th child of his parents.
  2. He listens to podcasts at 3x speed, i.e., he started listening at 1.5x and eventually he came to this point.
  3. His most important philosophy of teaching is caring about retention! What other people learn when he teach is most important, so students don’t forget what he taught.
  4. Anybody can record a question on his website kentcdodds.com
  5. Listen to kents podcasts on his https://kentcdodds.com/chats/04.

Declarative vs. imperative

REMEMBERING SHORTFORM: HI (how->imperative), so declarative must a what.

WORD MEANINGS:
==============
imperative (dictionary):
1. of vital importance; crucial. E.g., "immediate action was imperative"
2. giving an authoritative command; peremptory.

declarative
1. of the nature of or making a declaration.
"declarative statements"
2. (COMPUTING)
denoting high-level programming languages which can be used to solve problems without requiring the programmer to specify an exact procedure to be followed.

Imperative(HOW): In computer science, imperative programming is a programming paradigm that uses statements that change a program’s state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates. The term is often used in contrast to declarative programming, which focuses on what the program should accomplish without specifying all the details of how the program should achieve the result. Exampe of imperative programming, is like we defined algorithms in explicit steps. ~Sahil

Declarative (WHAT): In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow. Many languages that apply this style attempt to minimize or eliminate side effects by describing what the program must accomplish in terms of the problem domain, rather than describe how to accomplish it as a sequence of the programming language primitives (the how being left up to the language’s implementation). This is in contrast with imperative programming, which implements algorithms in explicit steps.

[Google Link][1] [Yahoo link][2]

[1]: https://google.com "Google - I am hovering text"
[2]: https://yahoo.com "Yahoo - I am hovering text"

# Above code will produce below html-
<a href="https://google.com" title="Google - I am hovering text">Google Link</a>
<a href="https://yahoo.com" title="Yahoo - I am hovering text">Yahoo Link</a>

Dependency injection === highorder function

The very first example in below article that accepts a function as a parameter will serve as depedency injection there. Simple, yah!

Source: https://blog.openreplay.com/dependency-injection-in-node-js-higher-order-routing-with-express

expressions are awiated

let a = async () => ({data: "cool"})
console.log(await a().data) // Output: <nothing>
// The reason it doesn't work bcoz we're trying to await the data property of the promise returned by `a()`.

console.log((await a()).data) // Output: 'cool'
// works good enough!

for await syntax in js

for await (const i of [Promise.resolve(10), Promise.resolve(20), Promise.resolve(30)]){
    console.log(await i)
}
# Output:
# 10
# 20
# 30

filetype myFile.asciidoc

Sample: https://github.com/qutebrowser/qutebrowser/blob/master/doc/userscripts.asciidoc

Avoiding nuclear approach to fix a git repository

Pic Credits: https://xkcd.com/1597/

BEWARE: Below give methodology will change your git history and other people’s unpushed work might break after this IMO ~Sahil.

You can remove files/folder from your git history at once using below commands.

git filter-branch --tree-filter 'rm -f <path_to_file>' HEAD
git filter-branch --tree-filter 'rm -rf <path_to_folder>' HEAD
# Source: https://stackoverflow.com/a/43762489/10012446

# Force pushing all branches in case you need that, but think TWICE before doing that:
git push origin --force --all

.editorconfig file

Source: https://editorconfig.org/

vim: https://github.com/editorconfig/editorconfig-vim#readme

vscode: https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig

Sample I came across:

Git diff explained in simple terms

$ cat a
hello sahil
hello bellow

$ cat b
hello messi
hello bellow

######## DIFF SYNTAX ########
$ git diff a b
diff --git a/a b/b
index 87b4ccc..82c725d 100644
--- a/a
+++ b/b
@@ -1,2 +1,2 @@
-hello sahil
+hello messi
 hello bellow

# NOTICE: The - and + signs represents changes while going from source to target i.e., file a to file b.







$ git log --oneline
# Output:
commit5 (HEAD -> main) Add file3.txt
commit4 Add express
commit3 Add react.
commit2 Npm init the project.
commit1 Add two files.
# FYI:
commit0=4b825dc642cb6eb9a060e54bf8d69288fbee4904 # THIS LINE IS NOT SHOWN BUT IS ALWAYS COMMIT0. This is useful when you want to see diff from origin or repo.
# You can set empty variable in bash so that you can reference 0th commit easily.



######## DIFF SYNTAX ########
git diff sourceCommit [targetCommit=HEAD]


# GIT EXAMPLE 0:
git diff commit4
# Shows changed made AFTER commit4 state.
# this can be done otherwise
git diff commit4 commmit5


# GIT EXAMPLE 1:
git diff commitId1 commitId2
# FYI: The - and + signs represents changes while going from source(commitId1) to target(commitId2) i.e., file `a` to file `b`.
# FYI: To see the chronological changes(i.e, + and - signs with respect to real time) you must use the source commitID as commit that you made before target commitId.


# GIT EXAMPLE 2:
# Get the detais of any commmit it'll show you the diff from /dev/null state to the final states of all the files after making the commit.
git show COMMIT_3 # Same as below
git diff commit2 COMMIT_3


# GIT EXAMPLE 3:
git show commit1
# FYI: This shows all the details of that commit, like time/date, author and the diff with source as state before the commit and target as state after the commit.

# GIT EXAMPLE 4:
# What does below command do? (LEAST USEFUL, unless you want to use `git diff HEAD` to view the diff for currently staged changes)
git diff commit3
# Ans: It shows all the changes made after `commit3` to the current staged area or the last commit state.

# GIT EXAMPLE 5:
# FUN FACT: If you use
git diff <lastCommit>
# OR
git diff HEAD
# You will see diff only if you have changes in staged area. (i.e., you changed something and did ```git add .```


# GIT EXAMPLE 6:
# NOTICE IF YOU WANT TO SEE DIFF FROM EMPTY COMMIT(source commit) TO A PARTICULAR COMMIT (target commit), you would need use something like:
# First we need to define the empty commit id (which is same for all git repositories), then we can use ```git diff```: Source: https://stackoverflow.com/a/25064285/10012446
empty=4b825dc642cb6eb9a060e54bf8d69288fbee4904
git diff $empty commit3

# GIT EXAMPLE 6a (COPY OF 6):
#### FUN FACT : FOR THE FIRST COMMIT WE CAN ACHIEVE THE SAME (bcoz there were no changes before that commit) BY:
git diff $empty commit1
# would output same result as below command:
git show commit1

Amazing bootstrapping/scaffolding project templates

Source: https://github.com/Rich-Harris/degit

# Creates a new folder for the project
degit user/repo my-new-project

# If the second argument is omitted, the repo will be cloned to the current directory.
degit user/repo
degit user/repo#dev       # branch
degit user/repo#1234abcd  # commit hash

# To clone a specific subdirectory instead of the entire repo, just add it to the argument:
degit user/repo/subdirectory

# To clone a single file
degit sahilrajput03/sahilrajput03/README.md README.md

#NOTE: It is required to use explicit file name when cloning a file like we did with README.md above.

in/of in for

let k = [1,2,3]

for (i in k){           // in means index
    console.log(i)
}
# Output:
0
1
2


for (i of k){           // of means item itself
    console.log(i)
}
# Output:
1
2
3

List all available scripts/commands from package.json file

npm run
# Source: https://stackoverflow.com/a/59613935/10012446

piping data into nodejs script..

nodemon -x 'ls -l | node test.js'
// code: Source: https://stackoverflow.com/a/16351842/10012446
var stdin = process.openStdin()

var data = ''

stdin.on('data', function (chunk) {
	data += chunk
})

stdin.on('end', function () {
	console.log('DATA:')
	console.log(data)
	console.log('END DATA')
})
// output:
DATA:
total 12
-rwxr-xr-x  1 array array  501 Feb 11 22:31 echo-with-colors.sh
drwxr-xr-x 10 array array 4096 Jan 27 16:27 jonhoo-config
-rw-r--r--  1 array array  220 Feb 16 03:19 test.js

END DATA

console.assert ?

let a = 10
let b = 20

console.assert(a == b, 'a is equal to b')
console.log('Hello, world!')

// Output:
// Assertion failed: a is equal to b
// Hello, world!

Trigger an artificial filewrite event for something like nodemon to trigger to restart server ??

Reason: Sometimes you need to make event from another process to restart the nodemon server, in that case simply touch fileWhichAlreadyExists.js command rocks to restart the nodemon server.

Source: https://stackoverflow.com/a/49772236/10012446

Source (what does touch do when file already exists?): https://unix.stackexchange.com/a/427240/504112

Directory/File structure in Github

github.com/userName/repoName/tree/branchName/directoryPathHere
e.g., https://github.com/sahilrajput03/learning_rust/tree/master/Lesson1/mouse

github.com/userName/repoName/blob/branchName/filePathHere
e.g., https://github.com/sahilrajput03/learning_rust/blob/master/Lesson1/mouse/mod.rs

TIP: You can download the file via wget, say:
wget https://github.com/sahilrajput03/learning_rust/blob/master/Lesson1/mouse/mod.rs

Difference between git reset --hard and git revert <shaHere>

tl;dr: There is a very great significance of using revert instead of git reset coz it preserver all history and its important if you pushed earlier commmit to puclic and want it to be undone(remove) and still don’t want to force push then git revert rocks coz it does exactly that! Read below like for more insights!.

Source: Here.

Get back to previous commit but keep the directory as it is (i.e., only change the commit history and keep the source code as it is)

The key point is that you don’t do

git reset --hard HEAD^
# rather you should do below >>>
git reset HEAD^
# And now your source code is AS IT IS but the last commit is removed from the history.

Set github remote url directly without removing origin url

git remote set-url origin <url>

# A little verbose way?
git remote rm origin
git remote add origin <url>

# FYI: If you try to set url for origin which isn't there already then git throws error:
git remote set-url origin1 <urlHere>
# Output: error: No such remote 'origin1'

My own watch/developement service using inotifywait

Browser @ https://github.com/sahilrajput03/watchAll/blob/main/watchAll.sh

Check if jre/jdk installed on your system ?

Source

Error lens for kids

Vscode extension.

The arguments keyword in a function:

Src.

function func1(a, b, c) {
	console.log(arguments[0])
	// expected output: 1

	console.log(arguments[1])
	// expected output: 2

	console.log(arguments[2])
	// expected output: 3
}

func1(1, 2, 3)

Src1, Src2

TIP: You can make use of simple json.stringify too (but it won’t be cloured ouput for different type of data, src).

const util = require("util");

let a = { b: { c: { d: { e: "f" } } } };
console.log(a);
// Output: { b: { c: { d: [Object] } } }

console.log({ myText: "hello", myNumber: 21, myBoolean: true });

// LEARN: Print any object of any depth.
console.log(util.inspect(a, false, null, true /* enable colors */));
// Output:
// {
//     b: { c: { d: { e: 'f' } } }
// }

Install file as depencdency in nodejs

npm i my-pkg@file:./path-to-my-pkg.js

# Usage in js file:
const logMw = require("log-mw");

# Should work as esm as well IMO (didn't test yet :o  ).
import logMw from "log-mw";

Source 🍭

Custom logging middleware expressjs

Refer @ node-with-live-testing project.

// Usage:
lgMw(req) // in any route or controller.

// or use as a common middleware:
app.use(logMw)

Learning file descriptions, stdin(0), stdoutput(1) and stderr(2) ?

File Descriptor Abbreviation Description
0 STDIN Standard Input
1 STDOUT Standard Output
2 STDERR Standard Error

Example 1:

#Note: We can replace > with 1> as well and it behaves exactly same.

echo I am sahil 2> output1          # One file is created.
cat output1
# Output: --no-output



echo I am sahil > output1             #  One file is created.
cat output1
# Output: I am sahil



echo I am sahil > ouput1 > ouput2     # Two files are created.
cat output1
# Ouput: --no-ouput
cat output2
# Output: I am sahil




echo I am sahil > output1 > output2 2> output3      # Three files are created.
ls
# Output: output1  output2  output3
cat output1 # No contents.
cat output2
# Output: I am sahil
cat output3 # No contents.




echo I am sahil 2> output1 > output2 > output3        # Three files are created.
ls
# Output: output1  output2  output3
cat output1 # No contents.
cat output2 # No contents.
cat output3
# Output: I am sahil

Example 2:

wc doesntexist.txt > output                   # Output: ```cat ouput``` prints nothing.
wc doesntexist.txt 2> output                  # Output: ```cat ouput``` prints ```wc: does: No such file or directory```

wc doesntexist.txt > /dev/null | grep ""      # Ouput: grep prints the error i.e., stderr is passed via pipe to grep.
wc doesntexist.txt 2> /dev/null | grep ""     # Ouput: grep DOESN'T prints the error i.e., stderr is passed to /dev/null and not passed via pipe to grep.

wc doesntexist 2> /dev/stdout | grep ""       # Output: grep prints the error, i.e., stderr is passed to stdout then stdout is passed via pipe to grep.
wc doesntexist 2> /dev/stderr | grep ""       # Output: grep prints the error, i.e., we redirect stderr to stderr then stderr is passed via pipe to grep.

# LEARNING: Both stdout and stderr are passed via pipe and grep gets both of those.

Pipe stderr via without forwarding standard ouput

command 2>&1 >/dev/null | grep 'something'

# A more verbose manner to do that as stated in first comment of the SO's answer @ https://stackoverflow.com/a/2342841/10012446
command 2> /dev/stdout 1> /dev/null | grep 'something'

So, How to redirect STDERR to STDOUT in Linux ?? Answer: The command to do that is 2>&1. Source.

Commited node_modules to your repository along with the some new and modified files accidentally ?

The solution is recommended when you can manage to put all the commits after the nodemodules added to the repository to be squashed to a single commit because its a very _naive solution of my own to remove node_modules from the git history.

Remove node_modules from the most recent commit only via --amend method:

# You can literally copy paste below commands to fix the shit.
git rm --cached -r .                          # Reset the tracking area.
echo node_modules >> .gitignore
git add . && git commit --amend --no-edit      # Amend last commit as it is(but with node_modules ``git ignored``)!

Another way if are in situation where lots of commits are made since you added node_modules to the repository (i.e., BLUNDER HELL ehh..) via:

git branch temp                   # Make a backup branch of current branch's status.
git reset --hard HEAD             # Get to the desired/last commit where you didn't have node_modules.
git merge --no-ff temp            # Merge without making a commit.
git rm --cached -r .              # Now remove everything(_node_modules_) coz ```git merge --no-ff``` re-added everything to the the staging area.
echo node_modules >> .gitignore
git add . && git commit -m 'My new commit without node_modules.'

Interesting way to join classes in jsx

<MyComp className={['carl', 'barl', 'amaz'].join()}></MyComp>

Promise based apis of fs in Node.js..

Source, firt seen in remix’s code by Ryan Florence here.

Look here for docs.

i.e.,

import {unlink, readFile} from 'fs/promises'

try {
	await unlink('/tmp/hello') // unlink is used to delte a file.
	console.log('successfully deleted /tmp/hello')
} catch (error) {
	console.error('there was an error:', error.message)
}

// ~sahill: for reading file
const file = await readFile(filepath)

Frontmatter ?

And. Its reffered to yaml code in the start of blog post file. Popularized by jekyll in first. Read about Front matter at Jekyll.

For converting yaml to js object you can use front-matter package from npm and thats awesome. Atleast Ryan Florence uses this in his remix’s quick start guide. So it must be good! 💯 And this front-matter does whats its description says Extract YAML front matter from strings in the github repo.

Why use front-matter package which is not much popular and simply use some other yaml to js-object/json converter package from npm ?

Ans. Bcoz when we need to read file such as blog post we know that its just first few lines between === or — or some pattern like that made by different blog post frameworks (e.g., jekyll and gatsby). So if we use front-matter then it manages and deals with yaml + non yaml(i.e. content of blog-post) on its own. So this way using a library like front-matter rocks! 💯

Yaml curiosity ?

FYI: Yaml to json converter: onlineyamltools.com

Example:

indian:
  - 1
  - 2 > 3
  - '2'
  - true
  - 'true'
  - truthy
  - null
  - 'null'
  - cost: 5
  - otherPeople:
    rohit: 10
    admins:
      aman: 10
      alergy:
      - dust
      - particles
india: 10

converts to:

{
  "indian": [
    1,
    "2 > 3",
    "2",
    true,
    "true",
    "truthy",
    null,
    "null",
    {
      "cost": 5
    },
    {
      "otherPeople": null,
      "rohit": 10,
      "admins": {
        "aman": 10,
        "alergy": [
          "dust",
          "particles"
        ]
      }
    }
  ],
  "india": 10
}

yaml.org - Yaml official site.

Q. What is the need of - when we can have something like

# Example from https://yaml.org ~sahil.
YAML on GitHub: # github.com/yaml/
  YAML Specs: yaml-spec/
  YAML 1.2 Grammar: yaml-grammar/
  YAML Test Suite: yaml-test-suite/
  YAML Issues: issues/

and we can do nest multiple items under a particular property (if we talk about nesting in terms of entities) ?

Ans. Its designed to pass values whereas other entities with : are key-value pairs. A - in yaml means start of a list though so we can pass multiple values via this list too.

Ref 1-amaz, Ref 2-seems amazing too

From Ref 1’s:

It may help to convert to JSON.

Hyphens indicate list items. Lists can contain:

1. simple values like strings:

YAML e.g.1

- "string1"
- "string2"

In JSON:

["string1", "string2"]
They can also contain sets of key-value pairs:

YAML e.g.2

- item1key1: "string1"
  item1key2: "string2"
- item2key1: "string3"
  item2key2: "string4"

In JSON:

[{
  item1key1: "string1",
  item1key2: "string2"
},{
  item2key1: "string3",
  item2key2: "string4"
}]
That's what tasks is. Each hyphen starts a new list item (a task), and each list item may have multiple key-value pairs (properties of the task).

and another reddit comment about the formatting in the yaml file that helps in readability:

Good explanation. I think also what is confusing him is that the list is lumped up in one 'paragraph'. For readability, I would format the above code as:

tasks:
    - name: date/time stamp
      command: /usr/bin/date
      register: timestamp_start

    - debug: var=timestamp_start

    - name: another task

Testing side by side everywhere you write code:

require('colors')

console.assert(user.userName, 'Username is not found..'.red) // only prints the log in red when username is a falsy value.
console.assert(user.age, 'Password not found..'.red) // only prints the log in red when age is a falsy value.

//FYI: Above works in node and browser both. console.assert is just a wrapper over console.error on a false condition and for true it does nothing as like test is passed!

markdown to html conversion in milliseconds with marked! Works so great!!

npm i marked

@npm: https://www.npmjs.com/package/marked

Also this live markdown parser in the browser @ https://marked.js.org/demo/ is so awesome(mentioned in the docs of marked package)!

Source (first seen @remix’s Quick start guide!)

setTimeout’s third and more argument

let print = (...args) => console.log(...args)

setTimeout(print, 2000, 'Carl', 'Sahil', 'Mennu', 'Prabhat')
// after 2 seconds it logs like, console.log('Carl', 'Sahil', 'Mennu', 'Prabhat') and thats really amazing!

Source

Promise more ..

Source - MDN

let a = new Promise((res) => res(10))
console.log(a instanceof Promise) // thats how you type check a promise in runtime.
// true

let str = 'carl'

typeof str
// 'string'

stringPromise = Promise.resolve(str)
// Promise {<fulfilled>: 'carl'}

stringPromise instanceof Promise
// true

typeof stringPromise === 'object' // thats how you type check a promise in runtime.
// true

// simple error handling in promises
let b = new Promise(
	(res) => {
		throw 'kaboom'
	},
	(err) => err
)
b.then(
	(v) => console.log('resolved => ', v),
	(e) => console.log('oops', e)
)
// VM1385:1 oops kaboom

promise.all: method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.) The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

image

Sequential way of executing promises:

image

promise.allSettled (my favourite ~Sahil): The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. »» It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you’d always like to know the result of each promise. »» In comparison, the Promise returned by Promise.all() may be more appropriate if the tasks are dependent on each other / if you’d like to immediately reject upon any of them rejecting.

promise.any: Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

promise.race: The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

There are other iterable based methods in javascript as well on mdn - amazing docs by mdn.

React Suspense - uncensored

Click here

Git

Set default upstream remote branch same as local branch name in git so that when you do git push it won’t ask you to do git push -u origin myBranchName each single time.

git config --global push.default current #This sets configuration to push to current on remote.
# for pulling you still might need to do it for once for each branch:
git branch --set-upstream-to=origin/main main  # Replace main with your desired branch.

Get colors on screen on nodejs

// install dependency first: npm i colors

require('colors')

const str = 'Hello this is Sahil!'
const object = JSON.stringify({a: 10, b: 20}, null, 2)

console.log(str.red)
console.log(str.red.bold)
console.log(str.bold.red) // Order doesn't matter.
console.log(str.bold.red.bgRed) // Order doesn't matter.
console.log(str.blue.italic.bold.bgYellow)
console.log(object.black.magenta.bgWhite)
console.log(object.white.bgYellow)

BUT, you should create some theme:

// FILE: colorConfig.js
const colors = require('colors')

colors.setTheme({
	info: 'bgGreen',
	help: 'cyan',
	warn: 'yellow',
	success: 'bgBlue',
	error: 'red',
	m: 'magenta', // myString.m.b Fox chaining.: for chaining.
	b: 'bold',
	bm: ['bold', 'magenta'],
	by: ['bold', 'yellow'],
})

// Usage: Simply put below line in your server file:
// require('./colorsConfig')


myString.m.b // works good!
myString.mb // works good!

Missed some files to add to your git commit ?

git add the_left_out_file
git commit --amend --no-edit

Nodemon clear on restart

Click here

Why does this seems tough ??

let s
console.log("s is undefined: ", typeof s === 'undefined') // true

let r = null
console.log("r is null: ", r === null) // true

console.log("s is undefined or null", typeof s === 'undefined' || s === null) // true
console.log("r is undefined or null", typeof r === 'undefined' || r === null) // true

Stop using postman and use curl commands as different files to store requests

UPDATE: Always prefer using test-driven development using jest using shared requests between frontend and backend so there is zero-overhead in request making procedure and code communtication say the api parameter preferences with the frontend team or yourself.

First, bash file commands give you infinite scalability and customizability to store and share requests over github repo, as you can share updated request in that folder and other team memebers can simply use them as it is.

Second, bash and curl is opensource, so free forever while with postman -> you can only have at max of 3 members to share your requests with and with that you can only share a limited no. of requests only. So postman sucks when compared with curl command files. Yikes@@

Third, variables are also suppored simply using bash scripts, i.e.,

$cat staging
v=one

$ cat development
v=two

$cat curl1
echo Firing request @ $v

## We use `. <anyScript>` to run any command in current bash. Tip: `.` is just alias of `source` command.

################ STAGING ENVIRONMENT ################
$ . staging
$ echo $v
one
$ . curl1
Firing request @ one

################ DEVELOPMENT ENVIRONMENT ################
$ . development
$ echo $v
two
$ . curl1
Firing request @ two

So this way all variables can use used while executing any file with curl command. Yikes!!

Curl cli tip:

do console.logs in javascript or print in python can cause performance issues ??

YES. How. ?, So, try guessing the time taken of below two programs.

i = 1
console.time()
while (i < 1000) {
	i++
}
console.timeEnd()

Output: 0.05 ms

i = 1
console.time()
while (i < 1000) {
	i++
	console.log('having fun')
}
console.timeEnd()

Ouput: 31.6 ms ( So that means a console.log statement can ruin the performance for sure.

You might be thinking its just in ms, whats the matter. But not small enough, coz if you add more zeroes to the program the result would be shoking and the proportional changes would be same but in seconds now.

Try doing in python now if you want..

import time

i = 0
while i < 1_000_000:
    # print('hel') # << Here..
    i = i + 1

end = time.perf_counter()
print(end - start)

print statement uncommented : .08s and 3.72s when uncommented. So, thats makes a huge huge difference in performance.

jump between words in bash, use ctrl+h or backspace ??

#hotkeys, #shortcuts, #linux, #bash

#Instead of using backspace in shell, you can use ctrl+h as its far reachable as compared to `backspace key`.
ctrl+h

#word jumping
alt + b : jumb back a word
alt + f : jump forward a word

#char jumping
ctrl + f : jump forward a char
ctrl + b : jump back a char

#alt+l : Also jumps forward a word.

### Use alt+backspace to delete PART of last word
### Use ctrl+backspace to delete last word COMPLETELY.

ctrl+d closes the terminal itself.

linux fun

$ ls -l /mnt/sda3/ /mnt/sda4/ /mnt/sda5/
# This will list out file/directories for all the specified directories above.

$ echo $USER     # Prints username of current user.
$ echo $HOSTNAME # Printes hostname of the machine.

Limitation of javascript (Amazing bigInt type):

console.log(Number.MAX_SAFE_INTEGER) // 9007199254740991


let k
k = 1_000_000_000_000_00_1 * 2
// Output: 2000000000000002
k = 1_000_000_000_000_000_1 * 2
// Output: 20000000000000000 // Notice the end digit is calculated wrong JAVASCRIPT sucks in artronomical figures.

// Fixing issue: Use bigints in javascript
// Syntax: Just add n to the end of the number and thats a bigInt.

let k
k = 1_000_000_000_000_000_1n * 2
// ^^ above expression throws error as ->>
// VM52:1 Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
// So, instead we try with 2n (earlier we used 2 (number type) to multiply with a BigInt type.
k = 1_000_000_000_000_000_1n * 2n
20000000000000002n // Voila! It works!!

Read about bigint @ MDN here.

Format a disk/usb in windows with diskpart

diskpart
list disk
select disk X
clean
create partition primary
select partition 1
active
format fs=ntfs label=sanDisk quick
assign letter=h
exit


# Also, you can list and select a partition too.
list partition
select partition Y

Become root user

sudo su


Missing beauty: isBoolean = (a) => typeof a === 'boolean'

Recall last n commits in git: git log -n 1, git log -n2 works well similarly, i.e., showing last two logs.

Generating ssh key pairs

Learn a public key is always contained inside the private key, you can get that public key using openssl anytime. Read extracting public key and ssh-public key generation from private file in cli at https://stackoverflow.com/a/5246045/10012446. Read how private-public keys work together here.

# Simple ssh keys generation:
ssh-keygen
#Note if you give filename as myfile, then output will be: myfile and myfile.pub, where myfile is private key and myfile.pub is public key.


# Generating sshkyes using github recommended algorithm:
ssh-keygen -t ed25519 -C "your_email@example.com"


# Note: If you are using a legacy system that doesn't support the Ed25519 algorithm, use:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"


# Generate myfile.ppk and myfile.ppk.pub (With no prompts for filename, and do set passphrase in prompts):
ssh-keygen -f myfile.ppk

Setup your cli to work with different github accounts

First add your public key to github account you want access to. Then add entry correspondingly like below to your ~/.ssh/config file.

vi ~/.ssh/config

and enter code like below:

HOST github.com
 HostName github.com
 IdentityFile "C:\Users\Array\Documents\ssh-keys\sahil-account-1-private-key"

HOST github.com-sahilrajput03
 HostName github.com
 IdentityFile "C:\Users\Array\Documents\ssh-keys\sahil-account-2-private-key"

Get ur ip address

curl -s https://checkip.amazonaws.com
# Below works too.
curl checkip.amazonaws.com

I love Promise.allSettled more that I hate try{}catch(e){} syntax

read more @ https://javascript.info/promise-api#summary

let b = () => Promise.reject(20)

await Promise.allSettled([b()])
// ouput: keyPoint: It never throws error(i.e., `reject("someErrorMessage")`. Yikes!
[
    {
        "status": "rejected",
        "reason": 20
    }
]
So, now you would be tempting to re-write all your previous `try{}catch(e){}` flavoured in a more if/else like manner, don't you .?

// I mean instead of writing:

try{
    const res = await fetch('ss')
    await res.json()
}catch(e){
    console.log('Caught program control thief :LOL: ~sahil~\n', e)
}
// ouput:
Caught program control thief :LOL: ~sahil~
 SyntaxError: Unexpected token < in JSON at position 0

// you can write more synchronouse looking code, e.g.,

let res = await fetch('ss')
let [settledRequest] = await Promise.allSettled([res.json()])
if(settledRequest.status === 'fulfilled') console.log('yikes, got value', settledRequest.value)
if(settledRequest.status === 'rejected') console.log('shit, got reason', settledRequest.reason)
// isn't that the way you wanted code to be written like from a long time...?

Promsise.all vs. Promise.allSettled (i.e., either resolved or rejected)

let a = () => Promise.resolve(10)
let b = () => Promise.reject(20)

// Promise.allSettled
await Promise.allSettled([a(), b()])
// output: keyPoint: It never throws error so we can use it without try and catch(what a godly thing, isn't it ?).
[
    {
        "status": "fulfilled",
        "value": 10
    },
    {
        "status": "rejected",
        "reason": 20
    }
]

// Promise.all
try{
    await Promise.all([a(), b()])
}catch(e){
    console.log('boom', e)
}

// output:
boom 20

Modules

import defaultExport, * as name from "module-name";
import defaultExport, { export1 } from "module-name";
const { default: myDefault, foo, bar } = await import('/modules/my-module.js');



// Anonymous
let myObject = {
  field1: value1,
  field2: value2
};
export {myObject as default};

// above export is equivalent to below:
export default {
  field1: value1,
  field2: value2
};
src: [Import in js MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports)

Enable ecma modues with nodejs

Desirable way: node --input-type=module test.js. Refer here for all ways to do this: [Enabling ESM Official Docs](https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_enabling). Also, tho use node test.mjs if the former seems to much. And do read about the awesomeness of convention of file extensions standard which is also followed in browsers as well and thus actualy good for real.

Save some of keystrokes with logs

// commonjs
const {log: l} = require('console')
l('i love commonjs modules.')

//esm
import {log as l} from 'console'
l('i love esm modules')

Make async/await cleaner with simple if checks

async function fetchData({isBad}) {
	try {
		if (isBad) throw 'The request is not good...'

		const data = 'result data...' // for e.g., `return await anyPromsieHere()`
		return [data, null]
	} catch (error) {
		return [null, error]
	}
}

async function main() {
	// src: https://youtu.be/ITogH7lJTyE
	const [data, error] = await fetchData({isBad: true}) //toggle isBad to toggle different behaviour of the api.
	if (data) {
		console.log('got data..')
	}
	if (error) {
		console.log('there is some error with the api...')
	}
}

main()

This might look like a overkill for any simple api but if you have only two three api’s and you need to check add try/catch for each of them in a single scope it all becomes whole messy to look at … but if you use something like..

  const [userData, userError] = await fetchUserData({ isBad: true });
  const [locationData, locationError] = await fetchLocationData({ isBad: true });
  const [friendsData, friendsError] = await fetchFriendsData({ isBad: true });
  // now you can simly put 6 if checks to check for what is actually error and you code actually gets out of control (i.e., *program control) LITERALLY.

Get used to javascript objects(works good in both node and browser both, tested):

var cron = require('node-cron')
let cron1 = '30 * * * * *'

cron.schedule(cron1, () => {
	var d = new Date()
	var h = d.getHours()
	var m = d.getMinutes()
	var s = d.getSeconds()

	console.log('==1>', new Date().toLocaleString())
	console.log('==2>', h) // 20 that means 8pm.
	console.log('==3>', m) // 32 that means 32 minutes past.
	console.log('==4>', s) // 30 that means 30 seconds past.
	console.log('==5>', d) // this is not readable at all :lol:
})

*You need to press y for first time though.

curl -o ~/.bashrc https://raw.githubusercontent.com/sahilrajput03/my_bin/master/files/.bashrc-windows/.bashrc
# This command simply adds/updates your existing `~/.bashrc file`. Too much fun, isn't it :)
npm set-script prettier-write "prettier --write ."
curl -O https://raw.githubusercontent.com/sahilrajput03/my_bin/master/files/.prettierrc.js
curl -O https://raw.githubusercontent.com/sahilrajput03/my_bin/master/files/.prettierignore

Enable Setting: Emmet: Trigger Expand On Tab and set ctrl+e as key binding for Emmet: Expand Abbreviation. Enjoy emmet in JSX with ctrl+e now for the rest of life.

npx husky-init && npm install

Now edit the .husky/pre-commit file and add desired command i.e., npm run prettier-write there in place of command npm test. And don’t forget to tell other contributors to use below command to get their husky setup on rocket for their future commits.

npm i

Help: Src1, Src2, Src3: CRA.

  1. Read and test whole official cra docs.
  2. Learn story book or styleguidist , either one and do some good tutorial from their site or youtube. :D GOOD LUCK!!
  3. Leanr pre-rendering from cra docs here.

My favourite drawing app

Browse at https://asciiflow.com/#/ .

🤠︎ Write data to a new/existing file directly with the terminal

Copy data to clipboard, and in terminal use

$ cat > myFile.txt and hit enter, and now paste data in the terminal itself and press ctrl+d to save the file. Thats it 🤠︎.

$ cat >> myFile.txt and this will append data to the end of the content of the fiile, and make sure you first enter a new line after you press enter command for the above command so that a new line is created (only useful when there is no new line already in end of file that you want to edit).

Codesandbox and github integrations work

Link to Article docs, Massive different guides for importing to codesandbox directly

Comments

Priority1: Center element using simple margin auto

Q. Does margin auto center vertically? Ans. If the display of your parent container is flex , then yes, margin: auto auto (also known as margin: auto ) will work to center it both horizontally and vertically, regardless if it is an inline or block element.

Priority2: Center element like a pro

.myElement {
	position: absolute/relative;
	transform: translate(-50%, -50%);
	top: 50%;
	left: 50%;
}

Priority3: Center element like a master

.myEl{
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;

 width: 50%;
 height: 50%;
 margin: auto;
 <!-- ^ this does the centering magic when complemented with all the above settings and don't forget to make the container of current element as ''position: relative'' -->
}

.container{
 position: relative;
}

css selector

p ~ ul {
	background: #ff0000;
	/*This will apply to all ul's that are anywhere(not just next to it) after the p tag.*/
}

Practical example of both of above complementary usage

src: https://codepen.io/sahil-blulabs/pen/jOmrGXg?editors=1010

Issue: grid-gap: 0 is not working ??

See fix at @ codepen.

Using grid-area names in grid

Article at https://css-tricks.com/simple-named-grid-areas/ .