teleren/devto huggingface dataset:
Is Preact worth checking in 2021?
Tags: programming, javascript, preact, react
Published: 2021-04-20 07:49:51


Preact is a framework that aims to be fast with a smaller size alternative React with the same API. Comparing to such a giant as React isn’t easy. Let’s see if Preact should be ashamed of that comparison!

---

## Features

Most of Preact features are the same as in React. Hooks, Portals, Suspense all of this are available in Preact. There are some small differences in Preact. You can read about it here [https://preactjs.com/guide/v10/differences-to-react](https://preactjs.com/guide/v10/differences-to-react "https://preactjs.com/guide/v10/differences-to-react").

So why you should consider picking Preact instead of React?

### Smaller size

Preact has a smaller footprint. According to [bundlephobia](https://bundlephobia.com/) Preact (with @preact/compat) is almost 4.5kB minified and gzipped. Comparing to React (with React DOM) which size is 42kB, Preact is **90% smaller**. That’s a huge difference. Here we need to remember that Preact is fully compatible with React apps and it can be replaced in most of the apps without changing the line of code.

## Preact is gaining popularity

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1dzlxau5nhmjthcvnr60.jpeg)

The trend is visible, people are reaching out more and more often. Wider community lead library authors to support not only react but also Preact. You can see here a community-made project using Preact.

[https://github.com/preactjs/awesome-preact](https://github.com/preactjs/awesome-preact "https://github.com/preactjs/awesome-preact")

## Preact is simpler

Look at this and see in-depth how Preact looks under the hood. This simplicity benefits!

This is code for **useState:**

    export function useState(initialState) {
     currentHook = 1;
     return useReducer(invokeOrReturn, initialState);
    }

And this one is for **useRef:**

    export function useRef(initialValue) {
     currentHook = 5;
     return useMemo(() => ({ current: initialValue }), []);
    }

Do you see how simple it is? Re-using other parts of well-designed code has so much impact.

## Summary

Simplicity and well-designed API are powerful. The small size means less code to run this led to faster apps. I made a chrome extension called [pullrequests-templates](https://github.com/ZBW-dev/pullrequests-templates) using preact. The developer experience was amazing and I’m considering starting all my new projects using Preact. Definitely recommend everyone to check it.

Answering the question in the title: **Yes!**
Authentication in React, Redux and JWT Video Tutorial | 2 hours 🚀
Tags: react, javascript, webdev, codenewbie
Published: 2021-04-20 07:47:18

In the following tutorial, we will cover authentication in React and Redux by consuming Node.js auth APIs. We will also make use of JWT to keep track of the logged-in users. 

The following are some of the main sections in the video.
* Sign Up
* Sign In
* Load User
* Sign Out
* Protect API endpoints
* Conditional Rendering

##AUTH in React 👇
{% youtube aMFClmsA9Xw %}
JS Clean Code
Tags: javascript, webdev
Published: 2021-04-20 07:46:22

# Intro
# Today's Agenda
Our today's agenda is how to write clean code with javascript.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08zc308h95fvchhwubv0.jpeg)

## Avoid Magic Numbers

Don't use random numbers in your code because your teammates may not be able to figure out what they are.

You should name them as descriptive constants.

### Example
```js
// bad
if (num >= 8 && num <= 20) {
  // ...
}

// Good
const MIN_PASSWORD_LENGTH = 8;
const MAX_PASSWORD_LENGTH = 20;

if (num >= MIN_PASSWORD_LENGTH && num <= MAX_PASSWORD_LENGTH) {
  // ...
}
```
## Avoid taking Boolean Flags in Function

When your function requires a boolean parameter to do something it means your function is doing more than one thing which not a good practice.

You can split your function into different functions. This way your code is easy to test and debug.

## Example
```js
const TAX =  0.05;
const PRO_TAX = 0.01;

// bad
function getPrice(item, isPro) {
  if (isPro) {
    return item.price + item.price  * PRO_TAX;
  } else {
    return item.price + item.price  * TAX;
  }
}

// good
function getPrice(item) {
  return item.price + item.price  * TAX;
}

function getProPrice(item) {
  return item.price + item.price  * PRO_TAX;
}

```

## Avoid Extra Context
When you create an `object`, then you should avoid adding additional context to it.

### Example
```js
// bad
const user = {
  userName: 'foo',
  userID: 'bar',
  isUserPro: false
}

// good
const user = {
  name: 'baz',
  ID: '443',
  isPro: true
}
```

## Declaring Variables
You can declare variables on the same line by separating them with a `,`.

### Example
```js
// bad
let a = 'baz';
let b = 'foo';

// good
let a = 'baz', b = 'foo';
```

## Using Async/Await
Promises are a very clean way of dealing with asynchronous code (if compared to callbacks).

But in modern JavaScript, we have an even cleaner way to handle asynchronous code i.e, Async/Await.

Async/Await is just syntactic sugar over the promise API.


```js
const API_URL = 'https://jsonplaceholder.typicode.com/todos/1';

// bad
fetch(API_URL)
  .then(res => res.json())
  .then(json => show(json))

// good
async function showTodo() {
    const data = await (await fetch(API_URL)).json()
    show(data)
}
```

# Conclusion
Here is a Github repo having tons of tips for writing clean with javascript.

{% github ryanmcdermott/clean-code-javascript no-readme %}

JavaScript does not enforces us to write good code. Due to this we often write that just works nobody knows how, but it just works.

But with tools like eslint and typescript, we prevent it to some extent. Here is a post to help write good code with eslint.

{% link saurabhggc/add-eslint-prettier-and-airbnb-to-your-project-3mo8 %}

_Share your favorite tips for writing clean code below._
Laravel Validation Image Example
Tags: laravel, php, validation
Published: 2021-04-20 07:24:04

Today, I will learn you to create validation image in laravel.we will show example of laravel validation image.The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).
more..
https://itwebtuts.blogspot.com/2021/04/laravel-validation-image-example.html
The best is the tabnine extension
Published: 2021-04-20 07:12:11

The best is the tabnine extension
I use that only I recommend u may use e tabnine only for python. it makes the work very simple 
https://gist.github.com/Rigved60/4c82dfb733e8ceca2f470f522b8afb37 this code I have made with the help of tabnine
ngOnDestroy in services - unsubscribe to avoid memory leaks in SSR Angular 💧
Tags: angular, ssr, memoryleak, 5days5blogposts
Published: 2021-04-20 07:11:43

**I believed that I don’t need to unsubscribe RxJs subscriptions created in Angular singleton services, but only in components. I changed my mind when saw memory leaks in SSR (Angular Universal).**

### One NodeJS process, but many rendered apps

The NodeJS process of the SSR server *on every http request*: bootstraps a fresh Angular app, sends the output HTML to the client, and destroys the app. This cycle is repeated for each request inside one shared long-living NodeJS process. So any pending subscription created in any app’s service survives even after the app is destroyed. And it causes memory leaks in the server. 

### Unsubscribe in services’ ngOnDestroy

Angular invokes in SSR the lifecycle method `ngOnDestroy` not only for components, but also *for every service*, when the app is destroyed. Therefore it’s a good place to unsubscribe any pending subscriptions created by the service.
HashChat - Chat with person with same interests as you
Tags: showdev, react, javascript
Published: 2021-04-20 06:59:10

I created a chat room where you can meet people with the same interests as you.

![Chat Window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/affyjw3kpl8ckgnfuamd.png)

Check it out at [hashchat.js.org](https://hashchat.js.org/)

The most interesting thing about HashChat is that every message before sending to server is encrypted with public key of your partner, where after receiving message only he can decrypt the message with his private key. 

I haven't seen any site yet which encrypts messages with bitcoin and this seems like a really interesting way to do it.
The bitcoin address with the keys is generated in your browser each time you access the site.
Only the public key and address is sent to your chat partner.

While writing this I got the idea that I could add importing own bitcoin keys.
TODO: Import your bitcoin key.

![Settings Window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0i0xyqbeuufijepl6p1.png)

To generate user avatars I use a site that has pretty much the same name as HashChat, it's robohash.org, and it generates a unique avatar based on the given name, so when you type your nickname on HashChat, you'll always have the same avatar.

Feel free to test HashChat, the whole project is completely OpenSource, you can be a member of the project, every line of code counts :)

 {% github skorotkiewicz/HashChat no-readme %} 

How do you like the idea and implementation?
Write in the comments what you think about HashChat.
Testing with Mocha – 4. Testing error handling
Tags: testingwithmocha, bdd, javascript, mocha
Published: 2021-04-21 12:08:55

---
title: Testing with Mocha – 4. Testing error handling
published: true
date: 2021-04-20 06:46:20 UTC
tags: TestingwithMocha,bdd,JavaScript,Mocha
canonical_url: https://www.danielwerner.dev/testing-with-mocha-4-testing-error-handling
---

In this post we will take a look how can we expect that an error is thrown and how to make sure no error is thrown when when everything should be fine.

## Asserting an error is thrown

Let’s take a look on how to make sure the expected error is thrown in case when we need it. As an example lets extend our generic collection class, and create a specific collection which can store only numeric values.

See the Pen [Testing with Mocha – Example 4.1](https://codepen.io/daniel-werner-the-decoder/pen/poRxjmG) by Daniel Werner ([@daniel-werner-the-decoder](https://codepen.io/daniel-werner-the-decoder)) on [CodePen](https://codepen.io).

<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>

As we can see in the example above, the numeric collection throws and error when we try to push a non numeric value in it.

```

    if (typeof item !== 'number') {
        throw new TypeError('Numeric collection can only store numbers!')
    }

```

In the test we make sure, that this specific error occurs when we try to push a string to our numeric collecion.

```

     assert.throws(
          () => collection.push("4"),
          TypeError
      );

```

## Asserting an error is not thrown

As we’ve seen in the previous example we can assert that a specific error is thrown when necessary. We can also make sure that the error is not thrown when everything should work fine. The following example shows that the numeric collection accepts an integer value without throwing the type error.

See the Pen [Testing with Mocha – Example 4.2](https://codepen.io/daniel-werner-the-decoder/pen/OJWBMJv) by Daniel Werner ([@daniel-werner-the-decoder](https://codepen.io/daniel-werner-the-decoder)) on [CodePen](https://codepen.io).

<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>

As you can see, this example is almost the same as the previous. The only important difference is that we pushed an integer to the numeric collection,

```

collection.push(4)

```

and we asserted that the code does not throw a TypeError:

```

         assert.doesNotThrow(
              () => collection.push(4),
              TypeError
          );

```

* * *

_Check out all posts in the series_ **[Testing with Mocha](https://www.danielwerner.dev/category/testing-with-mocha/)**_._

The post [Testing with Mocha – 4. Testing error handling](https://www.danielwerner.dev/testing-with-mocha-4-testing-error-handling/) appeared first on [Daniel Werner](https://www.danielwerner.dev).
5 useful VS Code 
Tags: webdev, productivity, beginners, vscode
Published: 2021-04-20 06:40:03

This is a curated list of the shortcuts you should learn as soon as possible. I really wish I knew them when I started coding. It would have saved me hours of manual typing.

Default shortcuts for Linux. Mac and Windows shortcuts are displayed below if different.

###**1. Ctrl + Shift + P: Displays the command pallete**
(Mac: Cmd + Shift + P)
Displays the command pallete where you can search for an action

![text](https://res.cloudinary.com/practicaldev/image/fetch/s--YTUQi0k3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://github.com/simonpaix/images/blob/main/OpenCommandPalatte.gif%3Fraw%3Dtrue)

###**2. Ctrl+Shift+E : Move to Explorer window**
(Mac: Cmd + Shift + E)
Move to Explorer window where you have your file tree and can navigate using the arrow keys.

![text](https://res.cloudinary.com/practicaldev/image/fetch/s--6Y4W_Xbj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://github.com/simonpaix/images/blob/main/ctrl%2520shift%2520E.gif%3Fraw%3Dtrue)

###**3. Ctrl + Shift + L: Multi cursor selection**

![text](https://res.cloudinary.com/practicaldev/image/fetch/s--7LhlnRyx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://github.com/simonpaix/images/blob/main/add_cursor_current_selection.gif%3Fraw%3Dtrue)

###**4. Ctrl + D : One by one selection**

![text](https://res.cloudinary.com/practicaldev/image/fetch/s--Ed0pzjX_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://github.com/simonpaix/images/blob/main/add_cursor_current_selection_one_by_one.gif%3Fraw%3Dtrue)

###**5. Ctrl + Shift + I: Formats the entire file**

![text](https://res.cloudinary.com/practicaldev/image/fetch/s--19micMiH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://github.com/simonpaix/images/blob/main/code_formatting.gif%3Fraw%3Dtrue)

###**Bonus: Wrap with Abbreviation.**
Helps you add that missing div tag to an HTML block for example. It is not enabled by default, you need to do it in keyboard shortcuts preferences. Use shortcut 2 listed here (yeah \0/) -> type Preferences:Open Keyboard Shortcuts -> search for Emmet: Wrap with Abbreviation -> choose a key to bind it. I use Alt + M.

![text](https://res.cloudinary.com/practicaldev/image/fetch/s--hxBtAbIk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://github.com/simonpaix/images/blob/main/Wrap-abbreviation.gif%3Fraw%3Dtrue)

I really hope that this little checklist will be useful for you and save you a few hours of manual typing. Thank you for reading.👩‍💻
How my React Native app died
Tags: reactnative, upgrade, maintenance, 5days5blogposts
Published: 2021-04-20 06:39:35

“Nah, gimme just this one feature, do not upgrade anything.” - Said a man who suddenly lost $5000 for a feature worth $50. This is a sad and, well, a bit of a fake story, because I was the sucker who promised to deliver a really small feature to a rotten app without proper research.

Now, WTF happened here? The story begins a long time ago but I remember it like it was today. Let’s go back in time to 1994.. I mean to 2018. Well, the technology world moves fast. It was early December when I started this project so it was a good old version `0.57` of React Native. Believe me. This. Is. Old. Really old.

So a man has an app which once in a year needs to be updated with some fresh info. You can guess if there was a budget for making it loading dynamically from the server. We were happily updating this very important info for 2 years. Each update required going through a publishing process in both of the stores. 

**But this time something happened.**

This time it was different. So I cloned this old app from the repo. Did I already say it was old? Nevermind. Okay let’s do it. `yarn install`, update the info, `git commit`, `git push`, send an invoice. This should be enough because I had a nice CI/CD in place.

**Nope.**

I couldn’t even do `yarn install` because I had too new version of node. But nvm. Or actually `nvm use v9.something.0`
This did the trick. I still had some issues running it but resolved it quickly with some help from my good buddy called Stack Overflow.
Damn! It was supposed to be a quick job and I’ve already spent over 2 hours on it.
Quick test on android and iOS, `git commit`, `git push` aaaand it’s done.

**Nope.**

The AppCenter build was successful. It still had the correct node version. What a nice surprise. But when it tried to deploy to stores.. A small, not looking very bad error occurred. I had to target higher versions of SDKs. These small, not looking very bad errors started being annoying. Let’s deal with it and forget about this nightmare.

**2 days later.**

I gave up. After fighting with all these still-not-compatible-with-something-elses. This is how it died. I went to the man, said I’m very sorry. We both cried. He said go and bury it in the woods.

Okay, this actually didn’t happen, but as you can guess there was no budget to properly fix it and make it great again.

### What’s the lesson here?

Remember to always remind your client how upgrading the app constantly is important. It’s not a big deal if you do this regularly. But if you do it once in a few years it may be very difficult and expensive to bring it back to life.
Hang Man in Python
Tags: pythonbeginner, pythonprojects, 100daysofcode, python
Published: 2021-04-20 06:40:44

---
title: Hang Man in Python
published: true
date: 2021-04-20 06:38:38 UTC
tags: pythonbeginner,pythonprojects,100DaysOfCode,Python
canonical_url: https://bharadwaj.hashnode.dev/hang-man-in-python
---

Hang Man is like an interesting, fun-filled time pass game. Where a random word is taken by computer and we need to guess the word by alphabets. We have 6 lives to guess the word. If all the lives are completed then we lose the game. If we somehow manage to guess the words before the completion of our lives then we win. Though it is really difficult to guess the word, still we can give it a try as it is very very interesting. You can check the official documentation of it here https://www.wikiwand.com/en/Hangman\_(game)

The flow chart for the game is as follows:

![Screenshot (74).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1618899550451/fuwihDgEr.png)As you can see above, Computer generates a random word and then generate as many blanks as letters in the word. Then it's our turn to guess the letter. For each guess, if it is in the blank then it replaces the blank with a letter else you will lose the life. This process continues until all blanks are filled or if you run out of lives.

Now, let's dive into code parts by parts.

1. Computer wants to guess the word.
```
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

```
2. Creation of blanks
```
display = []
for _ in range(word_length):
 display += "_"

```
3. Guessing the letter
```
guess = input("Guess a letter: ").lower()

```
4. 

Checking the guessed letter

```
for position in range(word_length):
    letter = chosen_word[position]

    if letter == guess:
        display[position] = letter

if guess not in chosen_word:
    print(f'You guesses {guess}, thats not in the list. You lost a life')
    lives -= 1
    if lives == 0:
        end_of_game = True
        print("You lose.")

print(f"{' '.join(display)}")

if "_" not in display:
    end_of_game = True
    print("You win.")

from hangman_art import stages
print(stages[lives])

```

That's it. If all these four steps are successfully completed then it's the end of the game.

To get the ASCII and a number of words then I will attach my project link below. The entire code snippet lies in main.py, ASCII lies in hangman\_art.py and the words lies in hangman\_words.py. The main advantage of replit is we can simply fork others code and try it for ourselves. So, just fork my code and test it by yourselves.

Link to my project is here: https://replit.com/@BharadwajV/HangMan#main.py
ArcGIS Survey123 Feature Report Generation with ArcPY Module
Tags: python
Published: 2021-04-20 06:30:07

ArcGIS is a geographical information system for working with maps and geographic information. ArcGIS was developed by Environmental Systems Research Institute aka ESRI. ArcGIS platforms initial release was 21 years earlier. ArcGIS is used for creating and using maps, compiling geographic data, analyzing mapped information, sharing and discovering geographic information, using maps and geographic information in a range of applications, and managing geographic information in a database.
Inside the ArcGIS application bundle, we have so many tools for data collection and data analytics. Survey123 is a very useful app to collect data from the field and it’s very easy to configure. Once we collected our data using survey123 we can generate reports and analyse data using inbuilt web gis tools. The use of web gis tools is very time consuming and hard to work with a big data set. So the ArcGIS have its python modules to work and generate reports with feature layers.
We can use the ArcGIS python module to access those inbuilt functionalities.

import arcgis
from arcgis.gis import GIS

now we have imported all the modules we need to get going.
next, we have to log in to the ArcGIS. I’m writing this code inside my main function.

def main():
    gis = GIS(username="USERNAME", password="PASSWORD")
The next step is to access our survey manager.
   survey_manager = arcgis.apps.survey123.SurveyManager(gis)
For future steps, we need to find our survey id.
  surveys = survey_manager.surveys
  p = [print(s.properties['id'], s.properties['title']) for s in  surveys]

this code will print the survey id and its title so you can find your relevant survey id for further steps. The next step is to access our survey using survey id.

survey_by_id = survey_manager.get("Survey_ID")

To ensure we have accessed our survey use the next code to print properties of the survey.

print(survey_by_id.properties)

This code will print the survey properties and the next step is to access our template to generate reports.

templates = survey_by_id.report_templates

this code will output a list and if we have uploaded a new template it will stay in templates[1]. The ArcGIS default template is templates[0]
Finally, we can generate our report. You can replace where parameter with your own column name and data to query a record and generate reports.

report = survey_by_id.generate_report(templates[1], where="column=data")

This will generate your report in Docx format and download it into C:\Users\Admin\AppData\Local\Temp\ folder.
For further customizations, you can use a dynamic where parameter.
ex:
Query_String = input("Enter Query String ")
Where_Parameter = f"Field_Name = {Query_String}"
report = survey_by_id.generate_report(templates[1], where=Where_Parameter)

Hope you got an idea about feature report generation in Survey123. Thank you!
Day 37 of 100 Days of Swift
Tags: swift
Published: 2021-04-20 06:18:08

I just completed day 37 of 100 days of SwiftUI. Today I worked on building the IExpense app. IExpense is an app for tracking user expenses.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zo1cuhjrt7aazhlhf4s1.png)![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l62qemzzcrf6x5daggpg.png)

Here's a link to the (github repo)[https://github.com/sanmiAde/IExpenses]