teleren/devto huggingface dataset:
Short intro to Git Hooks
Tags: git, devops, github, productivity
Published: 2021-12-28 16:13:45

Git-hooks = scripts with a "special" name, located in the **.git/hooks** directory inside the repository which are triggered every time a particular event occurs in the Git repository.

They allow you to customize Git's internal behavior and perform customizable actions at certain points in GIT's execution.


There are different types of commit hooks but we will cover some of the client-side workflow hooks:

- pre-commit (linting, spell-checks, code style stuff)
- prepare-commit-msg (alter the default commit message or create a complete a new one)
- commit-msg (invoked `git-commit` and `git-merge` and allow to perform a check of the commit message)
- post-commit (invoked `git-commit`, it takes no parameters, and is invoked after a commit is made)
- pre-rebase
- pre-push
- post-rewrite
- post-merge (invoked by `git-merge`, which happens when a `git pull` is done on a local repository)
- post-checkout (invoked when a `git-checkout` is run after having updated the worktree)

A complete list of git-hooks can be found [here](https://git-scm.com/docs/githooks#_hooks)

We will demonstrate the power of git-hooks by "enforcing" a certain standard with respect to the [commit messages](https://gist.github.com/robertpainsi/b632364184e70900af4ab688decf6f53). (e.g. the commit message should contain the task identifier e.g. `TASK-5463`)

This is a two step process.

1) Create our script, e.g. in the root of our repo we can create `commit-msg.py` file.
```python
#!/usr/bin/python

import sys
import re

def line_valid(line_no, line):
    """
    return True if line is ok according with the verification
    """
    if line_no == 0:
        # first line should have the task identifier e.g TASK-4351
        return re.match("^TASK-\d{1,5}.*", line)
 
def show_rules():
    """
    Rules for a great git commit message style
    """
    print("Please follow the rules add task/feature TASK-xxxx in the name of the commit msg""")

def main():
    print("Args are {}".format(sys.argv))
    # read commit-msg
    with open(sys.argv[1], "r") as fp:
        lines = fp.readlines()
        for line_no, line in enumerate(lines):
            #print(line_no,line)
            if not line_valid(line_no, line):
                show_rules()
                sys.exit(1)
    sys.exit(0)

if __name__=="__main__":
    main()
```

2) Create a symbolic link.
```bash
cd <REPO>/.git/hooks
ln -s <REPO>/commit-msg.py ./commit-msg
```
Using this simple hook, we managed to enforced (based on our regex) that a commit message should start with the task id

 
![Git msg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0sonj63rjssz7bar2pzb.PNG)

Important aspects:

- Git hooks are not checked into source control by default
- The user can bypass locally pre-commit and commit-msg hooks by passing ` --no-verify` flag
[BTY] Day 1: Server Monitoring Tools
Tags: betterthanyesterday, monitoring
Published: 2021-12-28 16:07:18

I have learned some tools to monitor the system when running apps in production. It saved me a lot from a ton of manual works. And they are: Portainer, Prometheus (Node Explorer and cAdvisor), and Grafana.

I followed this video of Christian from The Digital Life channel: [Server Monitoring // Prometheus and Grafana Tutorial](https://www.youtube.com/watch?v=9TJx7QTrTyo&list=PL0s6MZJVJ8HbDEsGl2WveQheFD9SVgX1w&index=11&t=2s).

It's very easy to understand and deploy (all in docker-compose with a little configuration).

If you have any trouble, you can ask him (the owner of this tutorial) or ask me instead if you like. I have installed and run it successfully.
Event loop in node js
Tags: node, eventloop, synchronous
Published: 2021-12-28 15:53:08


## What is an event loop?
JavaScript code runs in the sequence it is defined since it is synchronous. 
The event loop is what allows node js to perform non-blocking I/O operations(operations that allow a single process to perform multiple requests at the same time) despite the fact that JavaScript is single-threaded.

### How it works
The node js environment is made up of input/output terminals, the Call stack, node APIs and the Callback queue. if your program is synchronous you will only need to focus on the call stack.

With the non-blocking behavior, all the synchronous events are executed first while the asynchronous functions are processed in the background while waiting to be executed.

Suppose we have a program

```
console.log('Hello, I am first')
setTimeout(()=>{
 console.log('Finally, I get executed')
}, 0)
console.log('Let me wait for asynchronous function')

```
The output is as follows

```
Hello, I am first
Let me wait for asynchronous function
Finally, I get executed
```
When the program starts executing, an anonymous main() function is usually added to the call stack which wraps up the code. The first and last console.log are pushed to the call stack and executed in the output terminal since they are synchronous. The setTimeout function is asynchronous and is therefore not processed in the call stack but is added to the Node API where its events are registered and a callback function is waiting to be processed in the background.

### <u>Phases of the event loop</u>

![Phases of the event loop diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3z3rhs5iy1ljtpxebvo.PNG)

1. Timers
These are functions that execute callbacks after a set period of time. This module has two global functions, setInterval() and setTimeout() where you can define code that will execute after a certain time period.

2. I/O Callbacks
This phase allow for non-blocking I/O operations. Asynchronous I/O requests are recorded in the queue so that the main call stack can continue its operations.
code example

```
const {readFile} = require('fs')
console.log('first task has started')
// checking the file path and returning context of the text file
readFile('./myFile/text.txt', 'utf8',(err,result) => {
if (err) {
  console.log(err)
  return 
}
console.log(result)
console.log('First task has been completed')
})
console.log('starting my second task)
```
The output is as follows

```
first task has started
starting my second task
I am content inside the text file
First task has been completed
```
3. Idle
This is the phase where the event loop performs internal operations of any callbacks.

4. Poll phase
All JavaScript code written is executed from the beginning to end. The event loop manages the I/O workload, calling the functions in the queue until the queue is empty.

5. setImmediate()
This is a special timer in node js which runs as soon as the poll phase becomes idle.

6. Close events 
Is used to clean the state of the application when the event loop is wrapping up one cycle and is ready to move on to the next one.
Svelte stores: console-level & UI-level
Tags: svelte, store
Published: 2021-12-28 15:38:44

Vue has Vuex, React has Redux, Svelte has Store . Hereby I just want to stick to practice & share couple of real life examples in Svelte . One important thing to notice, that stores as are lazy , store won't sign contract i.e. won't publish until subscribed . 

---

> **NOTE** : In case codesanbox.com IDE would throw an error on initial load, just try to reload the IDE . It might be buggy sometimes tho !

<u>Svelte store console-level (no UI)</u>

{% codesandbox svelte-store--console-level-igh7n %}

---

<u>Svelte store UI-level</u>

{% codesandbox svelte-store--ui-level--implemented-99i2u %}

> I used module.export / require (CJS) with ESM export / import as a mixed case for store to import it as .js file , this works on codesandbox , but I somehow found it buggy to run if exported and executed locally , so be advised !

---

Thanks & see you in the next one!
AZ-900 Complete Guide | Resources | Strategy
Published: 2021-12-28 15:28:32

Hello & Welcome. My name is Sushant. In this post I’m going to talk about AZ-900 Exam. I recently passed out AZ-900 with just only 2 days preparation. In this post I’m going to tell How I prepared for AZ-900 and from where I go the resources for preparation. So without giving more intro let’s get started.

[Read Complete Post](https://crunchythings.xyz/2021/12/25/az-900-complete-guide-resources-strategy/)
Closures in JS
Tags: javascript, webdev, html, css
Published: 2021-12-28 15:26:31

**_What is Closure ?_**

- Before get into the closure, lets have a small discussion on lexical scope.

**_Lexical Scope_**:- Lexical scope is the ability for a function scope to access variables from the parent scope. **which parent** ? (nearest parent).

``` javascript
function x() {
	var a = 1;
	function y() {
	    var a=2;
	    console.log(a) //2
	  }
  y();
}
x();
```

``` javascript
function x() {
	var a = 1;
	function y() {
	    console.log(a) //1
	  }
  y();
}
x();
```
So now, hope we understood the basics of lexical scope.

**Then what is closure?**

- A function along with its lexical scope formed a closure.

according to that sentence only, we will write a code. so we can understood it better.

below code is as same as above code with little modifications (logixal scope code)

``` javascript
function x() { //closure start
  var a = 1;
  function y() {
      console.log(a)
    }
  return y;
}             // closure end

let z = x();  // it will contain y function
```
so z will contain y function.so if we invoke z(). what will be the expected output??

``` javascript
function x() { //closure start
  var a = 1;
  function y() {
      console.log(a)
    }
  return y;
}             // closure end

let z = x();  // it will contain y function
z() //1
```
Yes the output is 1, in z, not only function will store. along with a function. its lexical scope will also come into the picture.

_**So, what is closure?**_
A function along with its lexical scope formed a closure. (Sentence concluded).

That's it, thanks for reading!
Cheers!
8 Websites Every Web Developer Should Visit
Tags: webdev, css, html, productivity
Published: 2021-12-28 15:21:16

Hi all. In this post I'm gonna share some of the websites that I personally use daily that help me save time while developing websites. Hope you find them useful.

1.[Get Waves](https://getwaves.io)
Generate svg waves.

![Waves](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kj9z26e1szzs9ox00p2.png)

2.[Blobmaker](https://www.blobmaker.app)
Create and modify svg shapes.

![Blobs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qin6k7ahc38r2jwsno4p.png)

3.[FLEX](https://flexbox.malven.co)
Visualisation of flex box.

![Flex](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d605yzp2h3ebm926ocjm.png)

4.[Buttons Generator](https://markodenic.com/tools/buttons-generator/)
Select a button and click to copy the code.

![Buttons](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uev5ls7nchouljas79rx.png)

5.[CSS Generator](https://webcode.tools/generators/css)
The ultimate css generator.

![CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4l2xnnutv5uuklyrcoxb.png)

6.[Animate CSS](https://animate.style)
CSS library for animations.

![Animate](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3s9svwcp3qaafhj3sbej.png)

7.[CSS Code Generator](https://html-css-js.com/css/generator/)
Another source for generating css.

![CSS Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9udrwc8l4ny6nw1t0xk8.png)

8.[Daily.dev](https://app.daily.dev)
Latest developer news on browser.

![DailyDev](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tzpdrfv8z4y7bjkbxek.png)

---
**Follow me on**

- [GitHub](https://github.com/yigitsr)

- [CodePen](https://codepen.io/yigitsr)

- [Twitter](https://twitter.com/ziggywoxx)

- [Twitch](https://www.twitch.tv/lemmy_ace)

- [Instagram](https://www.instagram.com/ziggywoxx/)
Route Params in expressjs
Tags: javascript, node, tutorial, beginners
Published: 2021-12-28 15:20:51

## Introduction

> Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys. [Expressjs official Docs](https://expressjs.com/en/guide/routing.html)

Let's say we defined a route([see the previous article](/routing-in-express)) in our app in the example code:

```typescript
const express = require('express')
const app = express()

// a route that takes params:
app.get('/users/:userId/books/:bookId', (req, res) => {
  // we can extract parameters from the route from req.params object
  const userId = req.params.userId
  const bookId = req.params.bookId
  // use userId and bookId values to do something useful
})
```

Maps to something like this:
```typescript
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
```

### Important Note: 
It’s important to sanitize and validate any input coming from the client requests. Requests are user-constructed data and can contain anything. There are libraries that can be used to perform sanitization for every possible kinds of data.

## Summary
Route params are useful if we need to pass data to our app within a Request URL. From our app, we may extract these values and look up the item or more data  from a Redis store, etc and return meaningful data inside the HTTP Response

Always remember to sanitize and validate any data that comes in from a Request. Requests are user-constructed and may contain anything.

Next we shall dive into:
Next, we shall dive into:
1. Post Requests in detail
2. Route handlers
3. Middleware - How middlewares make Express robust.

All sample code is host at [github](https://github.com/naftalimurgor/express-serries)
Thanks for stopping by! Happy new year and may the energy be with you!
Routing in Expressjs
Tags: tutorial, beginners, node, javascript
Published: 2021-12-28 15:12:43



## Introduction

> Routing refers to how an application’s endpoints (URIs) respond to client requests. [Expressjs official Docs](https://expressjs.com/en/guide/routing.html)

You define routing using express `app` object corresponding HTTP methods `POST` and `GET` method.

### For example
The following code shows an example of a very basic route.
```typescript
const express = require('express')
const app = express() // express object

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})
```

### Route Methods

A route method is derived from one of the HTTP methods and is attached and called on `app` object, an instance of the  `express` class.

GET and POST Methods to the root off the app:
```typescript
// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

```
### Route Paths
These routes defined in the above code snippet will map to:
`http://localhost:3000/` when app is run locally and matching depends on whether client uses `POST` or `GET` method and vice versa.

```typescript
// GET method route
app.get('/about', function (req, res) {
  res.send('about route')
})
// 
```
The above route matches to `http://localhost:3000/about` when the app is run locally.

***

## Summary
We've learn't how to define `routes` in a very basic approach. In the next article, we shall learn about [Route Params](/express-route-params)
Why do we use react? will it be everlasting?
Tags: react, frontend, webdev, programming
Published: 2021-12-28 15:06:59

Now, the main question arises in front of us is why one should use React. There are so many open-source platforms for making the front-end web application development easier, like Angular. Let us take a quick look on the benefits of React over other competitive technologies or frameworks. With the front-end world-changing on a daily basis, it’s hard to devote time to learning a new framework – especially when that framework could ultimately become a dead end. So, if you're looking for the next best thing but you're feeling a little bit lost in the framework jungle, I suggest checking out React.
 
1. Simplicity
 
ReactJS is just simpler to grasp right away. The component-based approach, well-defined lifecycle, and use of just plain JavaScript make React very simple to learn, build a professional web (and mobile applications), and support it. React uses a special syntax called JSX which allows you to mix HTML with JavaScript. This is not a requirement; Developer can still write in plain JavaScript but JSX is much easier to use.
 
2. Easy to learn
 
Anyone with a basic previous knowledge in programming can easily understand React while Angular and Ember are referred to as ‘Domain-specific Language’, implying that it is difficult to learn them. To react, you just need basic knowledge of CSS and HTML.
 
3. Native Approach
 
React can be used to create mobile applications (React Native). And React is a diehard fan of reusability, meaning extensive code reusability is supported. So at the same time, we can make IOS, Android and Web applications.
 
4. Data Binding
 
React uses one-way data binding and an application architecture called Flux controls the flow of data to components through one control point – the dispatcher. It's easier to debug self-contained components of large ReactJS apps.
 
5. Performance
 
React does not offer any concept of a built-in container for dependency. You can use Browserify, Require JS, EcmaScript 6 modules which we can use via Babel, ReactJS-di to inject dependencies automatically.
 
6. Testability
 
ReactJS applications are super easy to test. React views can be treated as functions of the state, so we can manipulate with the state we pass to the ReactJS view and take a look at the output and triggered actions, events, functions, etc.

Will ReactJs Everlasting?

As long as , the community is rising with reactJs and this is going to be stay inthe long run. But The scalability in reactjs is increasing day by day. I hope this is going to be a approach if react team work with stable updates to the reactJs Libraries or efficient rendering.

I think the load time can be reduce in react , with that we can go in the long run. See if we do more research , there are bunch of amazing technology in the , market and the industry is growing higher everyday. In the frontend tech, React is not leaving so far. As long as ,Facebook backed reactjs .
How To Fix NPM Timeout Errors On Slow Internet Connections
Tags: node, npm, fix, timeout
Published: 2021-12-28 14:58:50

Sometimes when we work with slow or unstable Internet connections, `npm` often fails to complete its commands like `npm install` and `npm update` with a timeout error. For that kind of situation, we can simply change some `npm` configurations like `fetch-retries`, `fetch-retry-mintimeout`, `fetch-retry-maxtimeout` and `cache-min` to minimize these timeout errors.

## fetch-retries

This config controls the number of times `npm` try to connect to the registry when fetching packages. The default value is `2`, but you can increase it to 3~5 or even more if you like. Open a terminal window and run the following command with the desired number of retries at the end.

```
npm config set fetch-retries 3
```

## fetch-retry-mintimeout

This config controls the minimum time (in milliseconds) `npm` wait before timing out when fetching packages from the registry. The default value is 10000 milliseconds (10 seconds), change it to 100000 or more.

```
npm config set fetch-retry-mintimeout 100000
```

## fetch-retry-maxtimeout

This config controls the maximum time (in milliseconds) `npm` wait before timing out when fetching packages from the registry. The default value is 10000 milliseconds (10 seconds), change it to 600000 or more.

```
npm config set fetch-retry-maxtimeout 600000
```

## cache-min

This config controls the minimum time (in seconds) to keep items before re-checking the registry. The default value is 10 seconds, change it to 3600 seconds (1 hour) or more.

```
npm config set cache-min 3600
```

Finally, run this command to check whether all the configuration changes are successfully applied or not.

```
npm config ls -l
```

Now try to run some failing commands to check whether they are working. The duration values mentioned in this question was only for demonstration, you may try different values by increasing and decreasing them according to your situation. Visit [npm-config](https://docs.npmjs.com/cli/v7/commands/npm-config) documentation for more available configurations.

Feel free to visit [devtonight.com](https://devtonight.com?utm_source=dev&utm_medium=questions&utm_campaign=how-to-fix-npm-timeout-errors-on-slow-internet-connections) for more related content.
Favicons in 2022: you only need 1 SVG favicon
Tags: html, svg, favicon, icon
Published: 2021-12-28 14:57:41

The time has come to end the favicon craziness... Starting from 2022 it makes sense to **use only 1 favicon in SVG format**.

Is it a dream? No, it's real. This simple solution works for modern browsers.

Simply use an **SVG favicon**:

```
<link rel="icon" href="/icon.svg">
```

- [Supported by major browsers](https://caniuse.com/link-icon-svg) (except Safari in 2021) and [Living Standard](https://html.spec.whatwg.org/multipage/links.html#rel-icon)
- Only 1 short line of code and simple to remember
- Other attributes like `type` and `sizes` are not necessary
- Scales much better at any size compared to PNG
- Let's end the favicon craziness with hundreds of different sizes...

I have already used this strategy for our latest website ([cuber.cloud](https://cuber.cloud)) and it works perfectly on Chrome and other major browsers. You can test it yourself. Just 1 favicon for all browsers and all sizes!

For Apple Safari, the only missing browser, let's ask them to become standard-compliant... (btw, they are becoming the new IE). You can send a tweet to [@webkit](https://twitter.com/webkit) for feature requests (they suggest that on their official bug tracker).
Migrate a JS Project to Yarn Berry
Tags: javascript, typescript, yarn, vscode
Published: 2021-12-28 14:56:46

For this tutorial, you will need a starting project. The assumption is that there is no lock file and the project is not installed (i.e. no `node_modules` folder). I will be starting with a blank [Vite](https://vitejs.dev) project. You can create one by running the command below and following the prompts:
```sh
yarn create vite
```

If you don't have Yarn berry installed, run one of the following commands:
```sh
# Node >=16.10 - May have to run as admin
corepack enable
```
```sh
# Node <16.10
npm i -g corepack
```

Once completed, open the project. Now, run the following commands in sequence:

```sh
yarn set version berry
yarn
yarn dlx @yarnpkg/sdks vscode # If using vscode/vscodium
```

All done!