teleren/devto huggingface dataset:
STOP using require() in node backend
Tags: node, javascript, esm, programming
Published: 2022-05-11 04:26:53

To all the node developer you need to stop using require() in your new project. The node has already support for modules and this tutorial will tell you difference between them and what to use instead of require() and also will deep down into module a bit more.

What are you using 
```javascript
const express = require('express') // common js
```
What you should use 
```javascript
import express from 'express' // es module
```

Did you see ?? how much the better code look in second one. The first one is commonjs syntax which is present in node from its origin for importing libraries , the second one was first introduced in browser and then it came to node.

It makes code so much readable , modern and non - verbose.

## How to use it ?
Its easy.
1. Initialise new node project.
1. Go to your package.json.
1. Add following to it.
    ```json
    "type" : "module" ,
    ```
1. By default when you initialise your project its set to commonjs.
1. That's it now start using modern javascript.

## Common patterns
Instead of explaining it I am going to show you commonjs code implemented in module format, so that you can start it immediately , also comeback to this article in future when you are confuse how to do certain things in module format. 

### Importing
```javascript
// cjs
const express = require('express')
// mjs
import express from 'express'
``` 

```javascript
// cjs
const express = require('express')
const Router = express.Router
// mjs
import express , { Router } from 'express'
```

```javascript
//cjs
const clientRouter = require('express').Router
// mjs
import { Router as clientRouter } from 'express'
```

### Exporting
```javascript
// cjs
module.exports = express
// mjs
export default express
``` 

```javascript
// cjs
module.exports = {
	router : {...} ,
	utils : {...}
}
// mjs
export {
	router : {...},
	utils : {...}
}
```

### Some more exporting pattern that may come handy

```javascript
// mjs
export default function hello() {...}
export const bye = "bye"
```
Create an Object in java
Tags: javascript, webdev, beginners, programming
Published: 2022-05-11 04:17:15

In Java, an object is created from a class.
To create an object of Main, specify the class name, followed by the object name, and use the keyword new:

public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main obj= new Main();
    System.out.println(obj.x);
  }
}
How does ElasticSearch work?
Tags: elasticsearch, database, computerscience
Published: 2022-05-11 04:13:18

ElasticSearch is a search engine technology used by many companies for use-cases like: full-text search, autocomplete suggestions, data analytics, etc.

It is a document-oriented database. The high level architecture of ElasticSearch is as follows (bottom-up):

## Document
Documents are the basic units of information you can store in ElasticSearch. You store the data in the form of a JSON document. Every document has a unique ID which is used for reverse indexing the data (discussed at the end).
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qz9c8kufgn0pnvgq1rns.png)
 
 

## Index
An index is a collection of the similar type documents. An index is analogous to the database in relational databases. When you query in ElasticSearch, you query against a particular index.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sblf4pg73vhhbfl2lu8e.png)
 

## Node and Cluster
An ElasticSearch cluster is a collection of nodes connected together.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pgaa1fq6feit8lvgulk.png)
 

## Shard
It is not necessary that an index in ElasticSearch cluster need to be present only on a single node. It could be broken down into parts and shared among multiple nodes to achieve horizontal scalability. Each part of an index present on a node is called a Shard.
**Example:**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2wlso1elavawtbzezxy.png)
users index has 10k documents which are shared between node1 and node2. Each part of 5k documents is called a shard.

Now that we understand high level architecture of ElasticSearch, let's have a look at how it internally works.

## Reverse Indexing
ElasticSearch uses a special data structure called reverse index. Every term in the data is indexed against the document IDs of documents containing the term.
Let's understand this through an example below:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vu7t4kd8fy5o2ghlceq.png)
 
Consider 2 documents as stated above with IDs: 1 and 2. When these documents are indexed(loaded into the index), every term from the document is taken and it is mapped to the document ID. When you query for a certain term, it is like a lookup in the dictionary. This is what primarily makes ElasticSearch very fast.

More articles to follow in this series of ElasticSearch articles. Please comment down if you want me to write an article about a specific topic.
The art of the create anything
Tags: beginners, programming, devjournal, writing
Published: 2022-05-11 03:24:10

Hello world, one time more I am walking here to practice my English and write a little. Improving this skill does not easy but it is very funny.

Excuse me for my errors ;)

Today I want to talk about the awesome skill to create that the programmers have us. It is magical how we can build anything from nothing, this is the concept that captivated me when I watched code first time.

These strange symbols with many colors create things just with thoughts. **Our thoughts**. They do not need any more (well, maybe a computer and internet) to start a project that could become something unprecedented.

I cannot think of another profession with this particularity, this gives us an opportunity world. Both a boy who only has a computer as the company that is being inaugurated they can build the future with code and one idea.

You who are reading this now no matter if you know to program or if you have never written one code line in your life because everybody can learn this. And that is where its magic is, the code is not exclusive to anybody.

And every time our world moves with more and more code (I know it, I am not saying new anything), things we didn't think possible today are, and we can create them with the right knowledge and a bit more.

But although this knowledge is available to many that the reality is that human knowledge grows faster than our capacity to learn. Maybe in the future all this called technology now it will be dark magic, understood by few. 

However, it is exciting to see all the road until arriving at that point. Nobody knows, you and I maybe be sorcerers in that future.

Anyway, I just wanted to ramble about my love for the code and practice my English on this post.  I wait not to have a lot of mistakes and that you enjoy this post.
Angular 13 Detect Width and Height of Screen Tutorial
Tags: angular, typescript, html
Published: 2022-05-11 03:16:42

**Update TypeScript Template**
Import HostListener API from `@angular/core` package, define variables get screen width and getScreenHeight, use the HostListener to bind window to resize event to get the screen size and width on window resize.

Update the code in `src/app/app.component.ts` file.

```typescript
import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  
  public getScreenWidth: any;
  public getScreenHeight: any;
  
  ngOnInit() {
      this.getScreenWidth = window.innerWidth;
      this.getScreenHeight = window.innerHeight;
  }
  
  @HostListener('window:resize', ['$event'])
  onWindowResize() {
    this.getScreenWidth = window.innerWidth;
    this.getScreenHeight = window.innerHeight;
  }
  
}
```


**Update HTML Template**
In this step, you have to open the angular HTML template file and define the variables using the double curly braces to print the screen or window size on the browser.

Please update the code in `src/app/app.component.html` file.

```typescript
<div class="container text-center mt-5">
  <p>Window width: <strong>{{ getScreenWidth }}</strong></p>
  <p>Window height: <strong>{{ getScreenHeight }}</strong></p>
</div>
```

**Reference:**
[https://www.positronx.io/angular-detect-width-and-height-of-screen-tutorial/](https://www.positronx.io/angular-detect-width-and-height-of-screen-tutorial/)
Google Line Chart Example in Laravel 8
Tags: laravel, php, google, chart
Published: 2022-05-11 03:15:26

In this article, we will see a google line chart example in laravel 8. Google charts use to visualize data on your website. Here we will see the line chart example or google chart in laravel 8. A line chart can also be used to compare changes over the same period of time for more than one group. So, here we will learn how to use google chart in laravel 8.

So, lets' see laravel 8 google line chart tutorial, how to use google chart in laravel 8, google chart in laravel 8, google charts example.

```
Step 1 : Install Laravel 8

Step 2 : Create Migration

Step 3 : Add Route

Step 4 : Create Controller and Model

Step 5 : Create Blade File and Add Google Line Chart
```

---

> **_[Read More : Google Line Chart Example in Laravel 8](https://techsolutionstuff.com/post/google-line-chart-example-in-laravel-8)_**
Bash function to edit scripts faster
Tags: bash
Published: 2022-05-11 02:25:02

---
canonical_url: https://waylonwalker.com/til/ewhich/
cover_image: https://images.waylonwalker.com/til/ewhich.png
published: true
tags:
- bash
title: Bash function to edit scripts faster
---

I am often editing my own scripts as I develop them. I want to make a better workflow for working with scripts like this.

## Currently

Currently I am combining `nvim` with a `which` subshell to etit these files like this.

> for now lets use my todo command as an example

``` bash
nvim `which todo`
```

## First pass

On first pass I made a bash function to do exactly what I have been doing.

```bash
ewhich () {$EDITOR `which "$1"`}
```

The `$1` will pass the first input to the which subshell.  Now we can edit our todo script like this.

```bash
ewich todo
```

>  Note, I use bash functions instead of aliases for things that require input.

## Final State

This works fine for commands that are files, but not aliases or shell functions.  Next I jumped to looking at the output of `command -V $1`.

* if the command is not found, search for a file
* if its a builtin, exit
* if its an alias, open my `~/.alias file to that line`
* if its a function, open my `~/.alias file to that line`

``` bash
ewhich () { case `command -V $1` in
    "$1 not found")
        FILE=`fzf --prompt "$1 not found searching ..." --query $1`
        [ -z "$FILE" ] && echo "closing" || $EDITOR $FILE;;
    *"is a shell builtin"*)
        echo "$1 is a builtin";;
    *"is an alias"*)
        $EDITOR ~/.alias +/alias\ $1;;
    *"is a shell function"*)
        $EDITOR ~/.alias +/^$1;;
    *)
        $EDITOR `which "$1"`;;
esac
```

## a bit more ergo, and less readable

To make it easier to type, at the sacrifice of readability for anyone watching I added a single character `e` alias to ewhich.  So when I want to edit anything I just use `e`.

```bash
alias e=ewhich
```

## Results

Here is a quick screencast of how it works.

<video autoplay="" controls="" loop="true" muted="" playsinline="" width="100%">
     <source src="https://images.waylonwalker.com/ewhich.webm" type="video/webm">
     Sorry, your browser doesn't support embedded videos.
</video>
Offlex - Video Streaming Platform (Day 1/3)
Tags: appwritehack, node, react, typescript
Published: 2022-05-11 02:22:40

series: ["Offlex - Video Streaming Platform"]

## Project Description

The idea of the project is to build a video streaming platform, somewhat like youtube, netflix and twitch.

I am just starting the project today May 10th, so I'm running short on time and will try to keep the posts short to properly work on the project.

## Wireframe

1. Homepage
  ![Homepage](https://share.balsamiq.com/c/5rpqgebTxTePmBRgTSehHb.png)

2. Video
  ![Video](https://share.balsamiq.com/c/nzLk1KieCcKkdhBHhj4fe.png)

3. Live Video
  ![Live Video](https://share.balsamiq.com/c/xv5Rj7PyDkR4bhhQNHwQre.png)

## Planned Features
- [ ] Login with Email
- [ ] Social Login
- [ ] Publish Video
  - [ ] Compress video for different resolutions
- [ ] Following Users
- [ ] Liking Videos
- [ ] Live Video
- [ ] Comments
- [ ] Starring / Adding to Favorites
- [ ] Sharing

## Project Structure

The project will consist of a React App and a Node.js Backend making use of AppWrite
Moving on to round 2 - New Years Resolution - Dev Log 32
Tags: startup, webdev, beginners, programming
Published: 2022-05-11 02:10:06

Unfortunately, I have been trying to reach the Google Ads department for 2 weeks now about getting my account unsuspended. I believe at this point that it is a lost cause. I will continue to make attempts and believe that I will one day have the account back since it was suspended wrongly. For now, though I am moving on to project number 2.

Since my first project is web-based, I figure maybe going the mobile route might be a fun learning experience. I am about to dive headfirst into React Native. My goal will be to learn how to use the technology properly and then build a type of management content system for content creators. After doing loads of research, I feel that the content creator space is a great target for a mobile app that allows them to more easily find which content works and which they could save themselves the time on producing. I apologize for not making an update last week, I have been sick lately and while it is not serious, some of the symptoms have been annoyingly sticky. Either way, I am moving on to probably the only other project I will have time to seriously attempt for the rest of the calendar year. This means that this next one is my last shot at completing my New Year's resolution. Let's hope it turns out to be a winner.
Correção e ajustes após a atualização de Bibliotecas
Published: 2022-05-11 02:07:53



Alguns erros são mostrados no próprio terminal ao inciar o servidor e outros foram evidenciados pelo console do navegador, e alguns deles informam o link para consultar a documentação facilitando o processo de correção, já outros foi um pouco mais trabalhosos, eu tive que debugar e entender que o problema estava em um componente da lib do react-bootstrap.

Seguintes correções foram feitas:

### Switch não é mais utilizado na versão 6 do react-router-dom :

https://reactrouter.com/docs/en/v6/upgrading/v5#upgrade-all-switch-elements-to-routes

```jsx
`// Antes
import { **Switch**, Route } from "react-router-dom";
<Route path="/" component={Home} />

// Depois 
import { **Routes**, Route } from "react-router-dom";
<Route path='/welcome' element={<Home/>} />
```

### ReactDOM.render não é mais usado na versão 18 do React

```jsx

// Antes

import { render } from 'react-dom';

const container = document.getElementById('app');

render(<App *tab*="home" />, container);

// Depois

import { createRoot } from 'react-dom/client';

const container = document.getElementById('app');

const root = createRoot(container); // createRoot(container!) if you use TypeScript

root.render(<App *tab*="home" />);
```

### Atualização do react-bootstrap de v1 para v2.

https://react-bootstrap.github.io/migrating/#popover

**Popover**

renomear 'Content' prop para  'Body'

renomear 'Title' prop para  'Header'

```jsx
`// Antes

`
<Popover>
	<Popover.**Title**></Popover.**Title**>
	<Popover.**Content**>
	</Popover.**Content**>
</Popover>
`

// Depois
`
<Popover>
	<Popover.**Header**></Popover.**Header**>
	<Popover.**Body**>
	</Popover.**Body**>
</Popover>
`
```
Build and Deploy a REST API for any Cloud
Tags: tutorial, aws, node, opensource
Published: 2022-05-11 02:03:42

In this video, we use the Nitric framework to easily build, test, and deploy REST APIs for AWS, Google Cloud, or Azure.

Follow the written guide here: https://nitric.io/docs/guides/serverless-rest-api-example

🔗  Resources
AWS Provider Setup: https://nitric.io/docs/reference/aws


👋  Have feedback?
Github: https://github.com/nitrictech/nitric
Twitter: https://twitter.com/nitric_io

----

Nitric is an open source framework for rapid development of cloud-native and serverless applications. Define your apps in terms of the resources they need, then write the code for serverless function based APIs, event subscribers and scheduled jobs.

Apps built with Nitric can be deployed to AWS, Azure or Google Cloud all from the same code base so you can focus on your products, not your cloud provider.
React Hooks
Tags: javascript, programming, tutorial, react
Published: 2022-05-11 01:59:58

**REACT HOOKS**
Es una característica que salió en la versión 16.8 en febrero de 2019.Los ***Hooks*** vienen a cambiar la forma de desarrollo en React.⠀Vienen a resolver problemas ligados a React, como la complejidad de los componentes, no se podía compartir la lógica de estado entre componentes, *Component Hell*, etc.

Los ***Hooks*** presentan una alternativa al desarrollo con clases, ya que estos vienen a trabajar con funciones.

## ¿Qué es un *Hook*?

Un ***Hook*** es una función especial que nos permitirá conectarnos a características de React, para trabajar con métodos especiales, los cuales nos permitirán manejar el estado de mejor forma sin depender de clases.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ptyuj44u4l7f5lbcrz0.png)
Nested where condition in Mongoose
Tags: mongoose
Published: 2022-05-11 01:26:09

example data structure

```
{
    "name":"John",
    "contact":{
        "phone":"123",
        "email":"abc@gmail.com"
    }
}
```

Where condition example:

```
this.user.findOne({
"contact.phone": "123"
})
```
How to Format Numbers in JavaScript using Intl.NumberFormat
Published: 2022-05-11 00:19:10

---
title: How to Format Numbers in JavaScript using Intl.NumberFormat
published: true
description: How to Format Numbers in JavaScript using Intl.NumberFormat
tags: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7x6km7fk0shl9fr780fu.png
canonical_url: https://www.jenniferbland.com/how-to-format-numbers-in-javascript-using-intl-numberformat/
---

If you ever wanted to format a number in JavaScript you were forced to use `.toLocaleString()`. The only challenge was this does not actually support locales. It uses the system locale. Now with the `Intl.NumberFormat()` to format any number into a currency value and format it based on a locale.

Here is an example of how we use to format numbers using `.toLocaleString()`:

```
const money = 1000;

money.toLocaleString('en-US', { 
    style: 'currency', currency: 'USD' 
}); // $1,000.00
```

Now with ES6 JavaScript gives us the `Intl` object which is the ECMAScript Internationalization API. This API provides language sensitive number formatting.

Here is the same example as above:

```
new Intl.NumberFormat('en-US', { 
    style: 'currency', currency: 'USD' 
}).format(money); // $1,000/00
```

## Formatting Currency in Different Locales

Here are several examples of formatting money using the Euro and the Japanese Yen:

```
new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
}).format(money); // '€ 10,000.00'

new Intl.NumberFormat('jp-JP', {
  style: 'currency',
  currency: 'JPY',
}).format(money); // 'JP¥ 10,000'
```

## Syntax for Intl.NumberFormat

Here are the syntax options available:

```
new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)
```

## Parameters

- `locales` - (optional) A string with a BCP 47 language tag, or an array of such strings. Can provide multiple locales where the best-supported locale will be favored in the order provided by the array. Locales is the language and region setting. It is made up of language code and the country code.
- `options` - (optional) Provides settings indicating how a number should be formatted to a string. There are tons of options and you can [review them on the documentation page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat).
How to add a Blank Directory to your Git Repository
Tags: git, webdev, tutorial, bash
Published: 2022-05-11 00:13:24

Sometimes in Git, we want to preserve a directory for use within a repository, but keep it empty of files. There are many reasons why you'd want to do this, but perhaps either **the folder is used to store files the person cloning the repository needs to create**, or **a script creates custom files to put into that folder**.

If we want to create a blank directory, we can do that easily, but it won't be pushed when we use `git push` to push to our remote. As such we need to do something slightly different.

## Creating a blank directory in a Git Repository

The easiest way to do this is by creating a `.gitignore` file within the directory you want to maintain.

```
- index.html
- myRepository <-- Empty directory
- myCss
--- style.css
--- main.css
```

We want to push `myRepository` to our git repository. To do that, create a new file in `myRepository` called `.gitignore`. In that file, put the following code:
```
*
*/
!.gitignore
```

This will **ignore all files, folder and subdirectories**, but include the `.gitignore` file itself. That means the file will be pushed, and we can keep the directory while not keeping any of its contents.

Next, just push your git repository as you would usually do by running the following commands:
```
git add .
git commit -m "Added .gitignore"
git push
```

Your directory will now persist in your repository, while the contents of the directory will not.