teleren/devto huggingface dataset:
React Hooks For Beginners : useState
Tags: react
Published: 2022-08-01 15:52:00

The useState hook allows us to create state variables in a React function component, also useState allows us to access and update certain values in our components over time. Finally, whenever we do create our useState hook we must give it a default value, and this can be any data type.

Before we start working with useState we must import it from React.


## Example:

```
import { useState } from 'react'
```
And just like that you have access to all of the wonderful things that useState has to offer. But now what if we wanted to use our useState hook in a real world scenario? 

## Example:

```
import { useState } from 'react'

function favoriteAvengers() {

const [avenger, setAvenger] = useState('Spider-man')

// avenger: a variable that stores the current value of our favorite avenger 'Spider-man'
// setAvenger: allows us to update or change the value of our avenger variable over time.
// useState('Spider-man'): is our default value of our variable 'avenger'
```

## Now let's add a button that changes our state to a different avenger when it's clicked:

```
import { useState } from 'react'

function favoriteAvengers() {

const [avenger, setAvenger] = useState('Spider-man')

return (

<h1>My favorite Avenger is {avenger}!</h1>

<button
type ='button'
onClick={() => setAvenger('Thor')}
>Change Avenger</button>
)}
```
Now this is just the tip of the iceberg on what you can do with state, but this gives you a basic and fundamental understanding of how useState works!
5 Top Open-source features and API for embedded systems and edge - Luos
Tags: opensource, microservices, api, luos
Published: 2022-08-01 15:49:50

A few days ago, we shared with you a selection of the 5 top open source features and APIs for embedded systems and edge.

⏩ https://www.luos.io/blog/5-top-open-source-features-and-api-for-embedded-systems-and-edge

If you haven't read it yet, it will be your evening reading 😉
Secure Your Rest APIs with Azure Active Directory
Tags: api, azure, azuread, restapi
Published: 2022-08-01 15:38:51

## Secure Your Rest APIs with Azure Active Directory
ASP.NET Core Web API 3.0 with Azure AD B2 Authentication, Swagger UI.

A sample test web application built in ASP.NET Core 3.0 to perform such tasks as:
- Authenticate users with Azure AD B2C( Single Sign In with Email, Facebook & Github)
- Protect Web APIs
- Redeem authorization code
- Call a protected Web API from Web Application


## Configuration

```
"Authentication": {
    "Authentication": {
    "AzureAd": {
      "Instance": "",
      "TenantId": "",
      "ClientId": "",
      "ClientSecret": "",
      "PostLogoutRedirectUri": "https://localhost:44397/",
      "ApiIdentifier": "",
      "B2C": {
        "SignInOrSignUpPolicy": "B2C_1_testsignupandsigninpolicy",
        "EditProfilePolicy": "B2C_1_TestProfileEditPolicy",
        "ResetPasswordPolicy": "B2C_1_password-reset"
      }
    }
  },
  "TestServiceOptions": {
    "BaseUrl": "https://localhost:44327/"
  } 
```

##  ASP.NET CORE Web API Authentication settings

```
"Authentication": {
    "Authentication": {
    "AzureAd": {
      "Instance": "",
      "TenantId": "",
      "Audience": "",
      "SignInOrSignUpPolicy": ""
    }
  }
```

## Swagger UI
```
Web API Swagger UI - https://localhost:44327/swagger
```

Complete Project:  [WEB API With Azure AD](https://github.com/masoodwasim/HOATestSample-AzureADB2C.git) 
`
Push to GitHub as a Pro
Tags: webdev, programming, devjournal, beginners
Published: 2022-08-01 15:31:00

GitHub is one of the most popular version control systems being used among developers for collaborations, future referencing, versioning, and other purposes.
This article illustrates one of many ways to commit and push changes to a remote repository.

## Requirements:

- Must have a GitHub account 
(signup on github here: https://github.com/ 
download and install git: https://git-scm.com/downloads
setting up git for the first time: https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup) 

- Visual Studio Code Editor (download and install vs code: https://code.visualstudio.com/download)

- Windows OS
PS: The steps can also be applied to other operating systems with slight difference in commands.

### CREATE A NEW REPO:

- login to github
- create a new repository
- give the repository a name
- tick the **add readMe** checkbox
- click on _Create repository_
- click on the **code** drop down (far right hand side)
- copy the https link provided

![set-up-repo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6umz8uxkn0pugpbbjamq.gif)

---


### ON THE LOCAL MACHINE (PC):
- select where to save the new repo
- click on the **_location path_** at the top section the screen
- type **_"powershell"_** on the path
- press enter key

### POWER SHELL CONSOLE
- type _git clone_ command and paste the copied link

```
git clone the_copied_github_link
```
- press the enter key
- change the directory to the newly cloned repository

```
cd the_name_of_the_repo
```
- press the enter key

### OPEN FOLDER IN VS CODE
- type on the console

```
code .
```
- press enter key


![clone-to-machine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c7lu7o2u87mntrqwya3.gif)

The only file in the repo is a README file, go ahead and create any file (like html, css, etc.) or folders in it.

---


### PUSH TO GITHUB

![add-new-file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mz3e2ci9e220vbjqbik6.gif)

- open the vs code terminal and type the following commands:
 1. To add the new changes

  ```
  git add .
  ```
 2. To commit the new entries

  ```
  git commit -m 'a descriptive message of what was done'
  ```
 3. To push to remote repository

  ```
  git push origin main
  ```

Visit the newly created remote repo. Voila! the new changes have been updated, Congratulations.
Orchestrate your Laravel application with Docker Swarm
Published: 2022-08-01 15:17:00

In the previous articles we have managed architecture for High Availability applications with Docker using GlusterFS Replicated Volume. Now it’s time to get into more specifics by Orchestrate Laravel application with Docker Swarm and then test if this setup is resilient to VM failure.

### Heading-1
We’re going to create a new docker image for the Laravel Project, and then define the entire stack configuration in a Docker Compose file that contains some services including the App/Laravel, Nginx, and MySQL database.

---

## Heading-2 Why who Why whoo Whooooooooooo
For those who don’t know what Docker is, let’s enjoy a brief overview. According to opensource.com:

> Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package.


	
	
	


| Field   | Description |
|------------|----------|
| `client_token`        | This is the token that the client uses to authenticate with Vault      |
| accessor      | An identifier or alias for the token    |
| value      | This field can contain the actual secret being sent as a response    |


```docker 
#Dockerfile

COPY laravel-app/composer.lock /var/www/
COPY laravel-app/composer.json /var/www/

WORKDIR /var/www

RUN apt-get update && apt-get install -y \
    build-essential libpng-dev libjpeg62-turbo-dev \
    libfreetype6-dev locales zip jpegoptim optipng pngquant gifsicle \
    vim unzip git curl

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
RUN docker-php-ext-configure gd --with-gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-png-dir=/usr/include/
RUN docker-php-ext-install gd

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
```

```tsx
// Tsx file
import * as React from 'react';

export interface ButtonProps {
  children: React.ReactNode;
}

export function Button(props: ButtonProps) {
  return <button>{props.children}</button>;
}

Button.displayName = 'Button';
```

We’re going to create a new docker image for the Laravel Project, and then define the entire stack configuration in a Docker Compose file that contains some services including the App/Laravel, Nginx, and MySQL database.
Top 5 CSS Animation Libraries🚀
Tags: css, webdev, programming, productivity
Published: 2022-08-01 15:12:19

If you want to include animation in your designs, animation libraries are an excellent place to start. An animation library is a third-party, open-source online resource of pre-made animation files.

> In this post, I'll introduce five of the greatest free animation libraries that I've chosen to help you create amazing animations in only a few clicks.

######So here are Top 5 CSS Animation Libraries :

##1. Animate.css

![Animate.css front page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gfp7doyh7q3scjfc7c6.gif)
  
**Home Page** - [Link](https://animate.style/)

**Animate.css** is a cross-browser library of CSS animations. As easy to use as an easy thing. Great for emphasis, home pages, sliders, and attention-guiding hints.

##2. Infinite
![Infinite front page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5is40p7zn4svgkklzh7.png)
 
**Home Page** - [Link](https://tilomitra.github.io/infinite/)

**Infinite** is a small set of useful infinite CSS animations that you can drop into your project.

##3. Micron.js
![Micron js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbto9ul1oau20g530dv4.png)
 
**Home Page** - [Link](https://webkul.github.io/micron/) 

**Micron.JS** is a micro interaction library which can be used to add Interactions to different DOM Elements. Micron.JS animates an element using CSS power and the interactive behaviours are controlled by JavaScript. Micron.JS is easy to adapt and can bring interactions to life using HTML5 data attributes or a chain of JavaScript methods.

##4. Animista
![Animista logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrjfoba0fbzfq2xzfkiq.jpg)

![Animista front page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/694zqe75zqivfjbkgpsd.png)
**Home Page** - [Link](https://animista.net/) 
 
**Animista** is a place where you can play with a collection of pre-made CSS animations, tweak them and get only those you will actually use.

##5. Motion UI
![Motion UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6jcz62uci4mnrw6q35m.jpg)

![front page Motion Ui](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0411f71al3senz7bzmzp.png)
 
**Home Page** - [Link](https://zurb.com/playground/motion-ui) 

**Motion UI** is one of the most powerful Sass library for creating CSS transitions and animations.

##Wind up
UI animation has grown in importance in the design, development, and delivery of enjoyable product experiences. UI animations elicit a natural feeling of involvement, transforming static layouts into lively interfaces and assisting users in focusing their attention on essential visual aspects.

##What’s next?

1. [Top 3 Ways to Center a DIV with CSS](https://dev.to/iarchitsharma/top-3-ways-to-center-a-div-with-css-2ch3)
2. [5 websites to take your front-end skills to the next level](https://dev.to/iarchitsharma/5-websites-to-take-your-front-end-skills-to-the-next-level-17gh)
3. [Top 4 VS Code Editing Tricks](https://dev.to/iarchitsharma/top-4-vs-code-editing-tricks-2hnb)
I feel trapped in my current position, please give me some advice
Tags: anonymous, discuss, help
Published: 2022-08-01 15:12:19

_This is an anonymous post sent in by a member who does not want their name disclosed. Please be thoughtful with your responses, as these are usually tough posts to write. Email sloan@dev.to if you'd like to leave an anonymous comment or if you want to ask your own anonymous question._ 

***

I've been working at the same company for almost 8 years. I did my internship at the current company I work at and stayed there until now. It's a friend's company in which I've been an important part, I've helped it go forwards in bad times and have benefited in the good times.

I feel like I owe them something and feel really trapped. The company is fairly small and I'm the front-end lead and know how everything works in the company. I'm almost a partner, so I feel I have the responsibility to stay. Even when going on holiday they get stuck and can't move forwards, as there's no other person that can do my job.

The thing is that I feel a big pressure and I feel trapped because the company has done a lot of stuff for me and has treated me very well.

The thing is I don't necessarily want to leave the company, but I would like to feel like I could and that I would not be letting them down or whatever.

I've been wanting to do leave of absence for a while, but I fear leaving, as I feel I'm letting them down or something... it's really bizarre and I don't fully understand why I feel this way... I almost feel like I am in a cult or something and owe them everything...

Maybe you can shine a light and help me get my thoughts together...

Thanks in advance!
JavaScript's true and false: Truthy and Falsy
Tags: javascript, frontend, webdev
Published: 2022-08-01 14:57:50

When you code, and you have to write an if statement like lines below:
```
if (x_value){
  //some code here
}
```
what do you think is logically correct value of the x_value? Either true or false, right?

In Javascript though, you'll see some condition where true and false is not used in a boolean context but something else. Look at this code for example:

```
let name='Alex';
if(name){
   console.log("Hi ",name);
}

```
in the line you see conditional statement if(name). While it requires boolean expression, name provided there is not a boolean value. It is a string, yet it is a valid expression. Why?

Because implicitly, Javascript do a type coercion, an implicit type conversion, so the string 'Alex' will be converted to boolean value, true.

An expression that will get type coercion to a true value is considered a Truthy value, while expression which will get type coercion to a false value is considered a Falsy value.

Bellow are some expression that Javascript consider as Truthy value when it comes to a boolean context:

```
//a non empty string
if ('false'){// 'false' is not an empty string, it has content 'false'
  //code here will be executed
}
//an object either with or without properties
if ({} /* or {value: 0} */){// object with no property
  //code here will be executed
}
//an array either empty or has some values
if ([] /* or [1,2,3] */){// array with no or some items
  //code here will be executed
}
//a number other than 0
if (-1 /* or 5 or 0.2 or -100 or Infinity or -Infinity */){// non zero number
  //code here will be executed
}```

In contrast to Truthy values, here are some sample expressions of Falsy value:

`if ("")//empty string
if (null)//null value
if (0 /* or -0 */) //zero number
if (undefined)//undefined value
if (0n)
if (NaN)
`
```
In practice you'll find yourself love the usage of Truthy and Falsy value because you can shorten your code and made them more clean as well. You'll also find this used a lot in people's code, so understand this concept will definitely help you grow better as a software developer.
Do you really understand JS functions? (part 1)
Tags: react, javascript, webdev, codenewbie
Published: 2022-08-01 14:40:00

As the book Effective JavaScript put it, “functions are JavaScript’s workhorse”, and one of the reasons I think that’s true is that while other languages resort to different techniques to manipulate data, JS functions alone plays the role of: procedures, methods, constructors, and even classes and modules. So having a deep understanding of JS functions and knowing how to use them effectively in different context will help you master a significant portion of JavaScript.

## What’s the difference between Function, Method, and constructor calls in JS?

In other languages that uses OOP we know that functions, methods, and class constructor or three different things, but in JavaScript they are just different patterns of one single construct: **functions**.

## Functions

 ```javascript
 function serverListen(port){
	 return `The server is listening at ${port}`;
 }```

## Methods

Meanwhile, methods in JavaScript are just functions that happen to be object properties.

```javascript
const server = {
	startServer: function(){
		try{
			serverConnexion(this.databaseName, this.serverPort);
			console.log(`The server has started listening on port: ${serverPort}`);
		}catch(error){
			throw new Error(error);
		}
	},

	databaseName: "auth_db",
	serverPort: 4937,
};


server.startServer(); // The server has started listening on port: 4937

```javascript
But using the this keyword on a nonmethod function is mostly unnecessary as it it would refer to the global object(or window object):

```
 function runServer(){
	return `The server is listening on port: ${this.serverPort}`
 }

console.log(runServer()); // The server is listening on port: undefined
```

Since there is no `serverPort` property on the global object it will be set to `undefined`.

A good practice in order to quickly catch this kind of mistakes is the use of **ES15**’s strict mode that sets the default binding of `this` to `undefined`.

```javascript

 function runServer(){
	"use strict"; // 👈
	return `The server is listening at port: ${this.serverPort}`
 }

console.log(runServer()); // error: cannot read property "serverPort" of undefined

```

## Constructors

Unlike functions a constructor passes a brand-new object as the value of this:

```javascript
function UserData(password, email){
	this.password = password;
	this.email = email;
}

const user = new UserData("@#*&*87*#IOI*&^", "will@gmail.com");

user.email; // will@gmail.com
```

The primary goal of a constructor call is to initialize an object, using the new keyword we are able to return a new Object.

# Thank you if you've read this far! 🎉🎉🎉
# Don't forget to follow me if you want to read the upcoming episodes 😉

 [Follow me on tweeter](https://twitter.com/JrMatanda)
How to Pass an Argument in Nodejs Command Line Application
Published: 2022-08-01 14:35:00

For those software engineers who have a lot of responsibilities the terminal is their home. It's very satisfying to create your own command line by using your favorite programming language. In this post, let me show you how to create a command line application using nodejs.

But before anything else. You need to install NodeJs. If your NodeJS are not install yet. You can download it [here](https://nodejs.org/en/download/).

Now, let us start.

Lets create your **index.js** file in your folder. Then inside index.js. type this code.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4i0w2x8rdc5fqxfzg9v.png)

Now, you can open your terminal and run it.

```
node index FirstArgument // output: FirstArgument
```

As you can see the  `process.argv[2]` is an array. Let us discuss some of the array of arguments below:

**process.argv[0]**  - is path where nodejs is located. In my case it is `/usr/local/bin/node`
 
**process.argv[1]** is a path where my index file is located. In my case it is `/home/thegreytangent/Desktop/dev.to/index`

**process.argv[2]** it is first argument on my script: `FirstArgument`

**process.argv[3]** - the second argument and so on.

What if you need all the arguments? No need to worry just loop it. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v2ea2mms7p8hjpnagpl7.png)

Now, run it in your terminal.

`node index FirstArg SecondArg ThirdArg`

The expected output should be:

```
Argument number: 0: /usr/local/bin/node
Argument number: 1: /home/thegreytangent/Desktop/dev.to/index
Argument number: 2: FirstArg
Argument number: 3: SecondArg
Argument number: 4: ThirdArg
```


### That's all for today!

In this post, we learn to add arguments in our nodejs CLI. Thanks for reading.  You can leave a like or a share if it is helpful and ask any questions in the comments below. (-:
Understanding OAuth and OIDC: Introduction
Tags: oauth, oidc, beginners, security
Published: 2022-08-01 14:31:17

## Series Introduction 
This series aims to clearly explain the concepts of OAuth and OpenID Connect, as briefly as possible.


## OAuth
Before I give you a standard definition for OAuth let's define what OAuth is not:

- OAuth is NOT authentication
- OAuth does not provide the identity of a user

OAuth is for authorization. For instance, let's say a third party application would like to access your Facebook profile data. Well, you can do exactly that using OAuth.

Let me illustrate this with a simplified diagram:



![Oauth-Flow-User-Redirected-To-Authorization-Server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7dhiu93ohxxhy96neyo7.jpg)


1 . The OAuth flow starts with the user (Resource Owner) being re-directed to the login page on the Authorization Server  (Facebook, in our case). The user then enters their credentials to authenticate.


![User-Receives-Access-Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9gh6jim8fuyc1htuel1.jpg)


2 . After successful authentication, the Authorization Server returns an access token to the Client Application.



![Client-Application-Uses-Access-Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8fj29s85kxbhyx5jo9l.jpg)


3 . The Client Application then uses the access token to retrieve the Protected Resource (Facebook profile).

The access token is meant to be used by the Protected Resource only. But it is often incorrectly used by the Client Application to identify the user, as an access token can sometimes contain user data. 

So how do we provide the identity of the user to the Client Application in a reliable way?

That's where OpenID Connect comes in.

## OpenID Connect

OpenID Connect (OIDC) is not a new protocol. It just extends OAuth by adding an identity layer on top of it. With OIDC, the client receives an ID token, in addition to the access token, at the end of the OAuth flow. 

The ID token contains details about the authentication event and optionally user information. OIDC also adds a couple of useful endpoints to OAuth, which can be used to retrieve user information and manage session.

## Next...
We will look at how OIDC provides authentication and user data to the client application


References:

- [OAuth RFC](https://datatracker.ietf.org/doc/html/rfc6749)
- [Getting Started with OAuth by Scott Brady
](https://www.pluralsight.com/courses/oauth-2-getting-started)
Starting project about Path Finding
Tags: pathfinding
Published: 2022-08-01 14:27:04

Game is one of my hobbies and I always wonder why do they have so many ideas that can lead people to keep playing and enjoying the game. I have seen vlog about making their own game using model but currently all I had is React and rails, so I decided to start by path-finding. It is the root to whatever games that needs a map.
I looked up online and found lots of people already had decent projects about path-finding, this is good because I have a lot of references to use. After watching several videos and reading some articles, I found the best topic to work on, path-finding algorithm visualization. To me algorithm itself is not that interesting, but understanding what problems can it solve really helps me get to know algorithm. Among all the method of understanding a algorithm, I found visualization the most direct and fitting all age-groups. The only drawback of this project is it is front-end heavy and I do need to fulfill the requirement for backend.
The ultimate goal is to do similar thing as Clément Mihailescu, his website and path-finding algorithm looks amazing. After watching his video of re-doing the website, I found it really hard. The amount of code needs to be done is massive and I only have limited time. The decision is still finishing the similar website as Clément's but simplify by not implementing partial features by myself. I will focus on implementing path-finding algorithm and visualization. But the first step is initialize the board and nodes.