teleren/devto huggingface dataset:
Usando TypeScript com React: Melhorando a Qualidade e Produtividade do Seu Código
Published: 2024-03-16 23:13:32

No mundo do desenvolvimento de software, a busca por eficiência e qualidade é constante. A introdução do TypeScript no ecossistema React trouxe uma revolução na forma como construímos e gerenciamos aplicações front-end. Neste post, exploraremos como a combinação de TypeScript e React pode elevar a qualidade do seu código, tornando-o mais legível, seguro e fácil de manter.

## Por que TypeScript?

TypeScript, um superset tipado do JavaScript, oferece recursos poderosos como tipagem estática e inferência de tipos, que ajudam a detectar erros em tempo de desenvolvimento, antes mesmo que o código vá para produção. Esta antecipação de erros não apenas economiza tempo mas também reduz a quantidade de bugs no software final.

## Integração com React

A integração do TypeScript com React é relativamente simples e traz diversos benefícios:

1. **Componentes mais Claros**: A definição explícita de tipos para props e estados torna os componentes React mais previsíveis e fáceis de entender.
2. **Desenvolvimento mais Rápido:** A tipagem estática ajuda a acelerar o desenvolvimento através do autocompletar e da documentação inline no editor de código.
3. **Refatoração Segura:** Alterar código existente se torna menos arriscado, pois o TypeScript ajuda a identificar potenciais problemas decorrentes dessas mudanças.
4. **Melhor Colaboração:** Em equipes grandes, a tipagem explícita facilita a compreensão do código por todos os membros, independentemente do nível de familiaridade com o projeto.

## Começando com TypeScript em um Projeto React

Para começar a usar TypeScript em um novo projeto React, você pode utilizar o Create React App com um template TypeScript, executando o seguinte comando:

`npx create-react-app my-app --template typescript`

Para projetos existentes, a adição do TypeScript envolve a instalação de algumas dependências e a configuração do ambiente. A migração pode ser feita progressivamente, permitindo que você converta arquivos JavaScript para TypeScript no seu próprio ritmo.

## Dicas para um Uso Eficaz

- Utilize interfaces ou types para definir props de componentes.
- Aproveite os enums para melhorar a legibilidade de conjuntos de constantes.
- Use tipos genéricos para componentes reutilizáveis e funções.
- Aprenda a utilizar os utilitários de tipo do TypeScript para manipular tipos de maneira avançada.

A adoção do TypeScript em projetos React não é apenas uma tendência, mas uma estratégia comprovada para construir aplicações mais robustas e manuteníveis. Ao investir tempo para aprender e integrar o TypeScript, você e sua equipe se beneficiarão de um processo de desenvolvimento mais eficiente e agradável.
Converting HTML to Image. and GIF
Tags: node, javascript, softwareengineering, architecture
Published: 2024-03-16 22:55:39

## Introduction

Recently I created [pictify.io](https://pictify.io) a platform to convert HTML to Image and Gif. In this post I will try to give an overview of the working of it.

There are 4 main component of the system.
- The HTML code
- The server with puppeteer instance
- FFMPEG 
- AWS S3

## The Process

![Diagram of image generation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zswg9am2tej2hc1dbw8s.png)

The user sends the request to server with HTML code. The CSS and Javascript must be included in the HTML or should be a publicly accessible link. Once the server receives the request it renders the the page using puppeteer a famous headless browser. The puppeteer waits till there are no more than 0 network connections for at least 500 milliseconds.

Using `screenshot()` method provided by the API the image is being captured. The captured image is piped to `sharp` a nodeJS image processing library to compress it.

Then the image is uploaded to a S3 bucket which is then served by cloudfront CDN. The server responds with the cloudfront URL to user.

This process becomes a little challenging when converting an HTML file with animation to GIF.

## Creating GIF


![Diagram of gif generation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/173ia296vvsskv60k2yf.png)


The gif creation process is same as image till the html is rendered. Once the HTML is rendered the we identify the node from the DOM tree which has animation attached to it. Once we receive the animating node we start capturing image with the same `screenshot()` method but we also seek animation to get the next frame. We repeat this process till the animation is completed.

At the end of the process we have images as frames for the GIF. We then use FFMPEG to convert these images to GIF. Since GIFs are larger in size we use `sharp` to resize and compress the individual frame.

The process after this is same as for image. We upload the image to S3 bucket and send the cloudfront URL to the user.


Thanks for taking the time to read this. I hope this was helpful. If you have any doubt or what to know any process in details do let me know about it in comments.
PHP 8 News: "Never" Return Type
Tags: php
Published: 2024-03-16 22:25:53

### Understanding the "never" Return Type:

The "never" return type in `PHP 8.1` signifies that a function will never return normally. This could be due to various exceptional behaviors such as throwing an exception, causing a fatal error, or entering an infinite loop. By explicitly declaring a function's return type as "never", developers convey the intention that the function will not reach its normal completion.

This feature is particularly useful for expressing functions that have exceptional behavior or functions that are designed to halt the program's execution abruptly. By specifying the "never" return type, developers can make their code more expressive and convey the intended behavior more clearly to other developers and to automated tools such as static analysis tools or IDEs.

### Examples:

#### Throwing an Exception:

```php
function throwError(): never {
    throw new \Exception('This function always throws an exception.');
}
```
In this example, the function `throwError()` always throws an exception, making it impossible to reach the end of the function. Therefore, it is marked with a return type of "never".

#### Exiting Script Execution:

```php
function exitScript(): never {
    exit(); // Terminate script execution with exit.
}
```
The `exitScript()` function terminates the script's execution abruptly using the `exit()` function. Since the script never continues execution beyond this point, it is designated with a return type of "never".

#### Entering an Infinite Loop:

```php
function infiniteLoop(): never {
    while (true) {
        // Perform some operations...
    }
}
```
The `infiniteLoop()` function enters an infinite loop, causing the script to execute indefinitely. Since the function never exits the loop under normal circumstances, it is annotated with a return type of "never".

### Benefits of Using "never" Return Type:

1. **Improved Code Clarity:**
By explicitly stating that a function never returns normally, developers can easily understand the exceptional behavior of that function.

2. **Enhanced Static Analysis:**
Tools like static analyzers and IDEs can leverage the "never" return type information to perform more comprehensive code analysis, leading to better error detection and code optimization.

3. **Preventing Misuse:**
Using the "never" return type can help prevent accidental misuse of functions that are intended to have exceptional behavior, such as those meant to terminate script execution or raise fatal errors.

In conclusion, the "never" return type in `PHP 8.1` provides a clear and explicit way to denote functions with exceptional behavior that do not return normally. This feature enhances code readability, facilitates static analysis, and helps prevent unintended usage of such functions.
Pre-Wednesday Challenge for devs.
Published: 2024-03-16 21:26:37

Hello everybody. I know you're all excited about the dev challenge starting on Wednesday. Well, I'd like to offer you guys a challenge _now_.

It's also a great chance to be benevolent. Kinda like donating to a charity (except it costs a little time, instead of money). In a nutshell, I'm offering you all a chance to help a young developer and hone you Java Script skills at the same time.

Now, here are the rules of the challenge.

- *To enter:* simply comment at the bottom of the page. Comment like this: "I enter the contest."

- *To take the challenge:* click this link: [challenge link](https://codepen.io/Front-End-Learner/pen/poBNWKo). Then just follow the instructions.

- *The prize:* is two fold. 1st, I will click like on all your comments, 2nd, I will write a comment declaring you the winner.


##### The Small Print
Now, of course you will all want to know the identity of the struggling young developer. Well, I can answer your burning question with one word: me.

My thanks to all who participate.
AWS CLI Setup: IAM User Configuration & Command-Line Access
Tags: awsclisetup, iamuserconfig, cliinstallation, awscliconfiguration
Published: 2024-03-16 20:41:17

Assuming you've already navigated through the AWS Management Console and set up an IAM user using the AWS web console, as well as generated the essential access and secret keys for programmatic access, you're now ready to configure the AWS Command Line Interface (CLI) for seamless interaction with AWS services.

If you haven't completed these initial steps yet, don't worry! You can follow along with this hassle-free setup video [here](https://www.youtube.com/watch?v=66dm5_TnKTc). 

With your IAM user credentials in hand, let's proceed to install and configure the AWS CLI.

##1. Installing the AWS CLI
To start, you'll need to install the AWS CLI client on your system. Refer to the detailed installation process outlined in the AWS official documentation [here](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).

Once installed, you can verify that the CLI is accessible from your shell by using the following commands:

```bash
$ which aws
/usr/local/bin/aws 
$ aws --version
aws-cli/2.11.21 Python/3.11.3 Darwin/22.5.0 exe/x86_64 prompt/off
```

##2. Configuring the AWS CLI
Now that the AWS CLI is successfully installed, the next step is to configure it with your IAM user credentials. You can do this by running the `aws configure` command in your terminal and filling in the prompted fields with your access and secret keys.

```bash
$ aws configure
AWS Access Key ID [None]: <paste access key> -- generated in step 1 
AWS Secret Access Key [None]: <paste secret key> -- generated in step 1 
Default region name [None]:
Default output format [None]:
```
Remember, you can always update these configuration values by rerunning the `aws configure` command.

##3. Finding Your Default Region
To determine the appropriate value for the `Default region name` prompt, navigate to your AWS Management Console. Open the service you intend to access or make API calls to, and in the top-right corner of the screen, click on the second menu item to the left. Find the region that matches your desired location, such as `eu-west-1` as in the image below.

![AWS RDS screen showing the region where the service is sdeployed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9ajt0souyz9o3osrovy.png)

Note that you cannot obtain your service region from the IAM service, as it is a global service.

##Conclusion
With the AWS CLI now configured, you're all set to interact with AWS services seamlessly from your command line interface.
My first open source contribution for MongoDB
Tags: mongodb, opensource, contribution, bson
Published: 2024-03-16 20:19:25

Hi everyone,

It's been a while that I wanted to talk about that.

3 years ago, I contributed to an open source project:
https://github.com/mongodb/mongo-c-driver

I decided to contribute, to earn knowledge and feel relevant as a young developer.

My contribution was literaly **adding a line** to fix a current bug that they had.

I took really my time to understand how the repository was built and I got facinated by the **bson** **object**.

To know more about that data structure here is link:
https://bsonspec.org/spec.html

"Bson" means "binary json". Basically keys and values of the bson are structured in a way to earn space and memory. They use this as a way to communicate with the MongoDB database and to process data faster.

I hope you learned something today and I see you in the next one.

#mongodb 
#datastructure 
#client 
#bson
My last git command that I learned to use
Tags: git, branches, branch, code
Published: 2024-03-16 20:07:37

My last command that i learn is `git cherry pick <hash of the commit to use>`

Basically "cherry pick" help you to add a commit from another branch to your current branch.

Say you coded a piece of code that you need right now in your current branch, you can use `git cherry pick`.

Just make sure that both branches (one with commit to add and your current branch) have a **common root history**. However they don't need to have exactly the same history.
Tom Green Sugar Defender Reviews SCAM ALERT 2024 Don't Buy Until You Read Dangerous Health Risks and Ingredients!
Published: 2024-03-16 19:43:19

꧁༺✨❗Shop Now ❗✨༻꧂
https://worksupplement.com/tom-green-sugar-defender-buy 

Product Name :- Tom Green Sugar Defender

Main Benefits:- Tom Green Sugar Defender Helps you to Management of High Blood Pressure.

Composition:- Natural Organic Compound

Side-Effects:- NA

Rating:- ⭐⭐⭐⭐⭐

Availability:- Online

Where to Buy:- Official Website – {Buy Now Here — Click Here}

Tom Green Sugar Defender:-  has ingredients that lower blood sugar levels, make insulin work better, and balance blood sugar. By doing this, the Tom Green Sugar Defender liquid helps to prevent low energy, confusion, mood swings, and unwanted weight gain. The product (Tom Green Sugar Defender Diabetes) also helps to get rid of hard-to-lose weight.

Official Website:- https://worksupplement.com/tom-green-sugar-defender-buy 
Official Blogs:- 
Jimdo.Site:- https://tom-green-sugar-defender-usa.jimdosite.com/ 
Google.Site:- https://sites.google.com/view/tom-green-sugar-defender-usa/ 
Blog.Spot:- https://tom-green-sugar-defender-us.blogspot.com/2024/03/blog-post.html 
Pinterest:- https://in.pinterest.com/pin/1137862662094101869/ 
Sketch.fab.Site:- https://sketchfab.com/3d-models/tom-green-sugar-defender-reviews-scam-alert-9f24874a9166497c8e71dc0f87f8200d 
Group.Google:- https://groups.google.com/g/tom-green-sugar-defender-us/c/6p9pc-7Bbuc 
Myrtlebeastocr.Site:- https://www.myrtlebeastocr.com/group/gear-accessories/discussion/1c8c8bea-440c-479e-bd43-4f4f88297fb2 
Mystrikingly.Site:- https://tomgreensugardefender.mystrikingly.com/ 
Medium.Site:- https://medium.com/@danaowles/tom-green-sugar-defender-does-it-work-or-not-16a1be4a2036 
https://medium.com/@danaowles/tom-green-sugar-defender-reviews-fact-exposed-2024-beware-consumer-reports-price-scam-c3a431223a0a 
GoDaddy.Site:- https://tomgreensugardefender7.godaddysites.com/ 
Hashnoda.Site:- https://tom-green-sugar-defender.hashnode.dev/tom-green-sugar-defender-review-urgent-consumer-reports-2024-where-to-buy-tom-green-sugar-defender-ingredients-price-and-shocking-side-effects 
Gamma.Site:- https://gamma.app/docs/Tom-Green-Sugar-Defender-Reviews-UPGRADE-VERSION-2024-Tom-Green-S-at7pmk2e2su3h4c 
PDF.Site:- 
https://publuu.com/flip-book/435319/982846 
https://issuu.com/danaowles/docs/tom_green_sugar_defender 
https://flipbooklets.com/pdfflipbooklets/tom-green-sugar-defender-2#page1 
https://online.fliphtml5.com/wyhdd/fhyi/#p=1 
https://www.studocu.com/in/document/hansraj-college/company-law/tom-green-sugar-defender/87439631 
https://anyflip.com/edpvj/istm 
TeeShopper.Site:- https://teeshopper.in/products/tom-green-sugar-defender-us 
Scoop.It.Site:- https://www.scoop.it/topic/tom-green-sugar-defender-united-states
Feeling Stuck with DSA? 🤔 Open This! 🔥
Tags: algorithms, programming, beginners, productivity
Published: 2024-03-16 19:30:00

Data Structures and Algorithms are like tools in a toolbox you need to get a hand on to crack coding interviews.

But the reality is, it sometimes gets too complicated.

Well, not anymore.

Say _bye_ to the complex lectures you have been watching for hours and not getting anything.

Here are 4 DSA Platforms which will teach you _visually_.

***

### 1️⃣ Algorithm-visualizer

An interactive online platform that visualizes algorithms from code.

🔗 https://algorithm-visualizer.org

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

***

### 2️⃣ Visualgo

Visualizing data structures and algorithms through animation.

🔗 http://visualgo.net

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

***

### 3️⃣ Algoanim

A collection of computer science algorithm animations and visualizations.

🔗 http://algoanim.ide.sk

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

***

### 4️⃣ Sorting Algorithms

Illustrate how effectively data sets from different starting points can be sorted using different algorithms.

🔗 https://www.toptal.com/developers/sorting-algorithms

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

***

### 🙌 Final Thoughts

What resources do you use to learn when aiming for cracking interviews?

Tell me in the comments below!

I hope you liked the article! ❤️

Connect with me: [Linktree.](https://linktr.ee/arjuncodess/)

Happy Coding! 🚀
Thanks for 21688! 🤗
Easy access form value in Nextjs/React with TS
Tags: nextjs, react, typescript, form
Published: 2024-03-16 19:16:44

🎉 Unlocking the Power of TypeScript with Easy and Simple React or Nextjs Forms! 

Are you tired of handling form submissions in React with simple code? Say goodbye to manual form field extraction and embrace the elegance of TypeScript! 💻⚡️

With TypeScript's event type, I have included code for you.

🛠️ Example: Let's take a look at how easy it is to handle form submissions in React with TypeScript:

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

Now use for 🔍 Easy Accessing Form Data: 

🔗 #ReactForms #TypeScript #DeveloperExperience #StreamlinedDevelopment #TypeSafety
#Sarwar #full-stack-developer



# Direct code for public and open


```tsx
import React, { BaseSyntheticEvent } from 'react'

export default function SignUpForm() {

    const submitHandler = async (e: BaseSyntheticEvent<Event, EventTarget & HTMLFormElement>) => {
        e.preventDefault();
        const values = Object.fromEntries(new FormData(e.target))
        console.log('Form values:', values);

        ////! console  Form values:  { username: 'sarwarasik@gmail.com', password: '123456' }
    };

    return (
        <form onSubmit={submitHandler}>
            <div>
                <label htmlFor="username">Username:</label>
                <input type="text" id="username" name="username" />
            </div>
            <div>
                <label htmlFor="password">Password:</label>
                <input type="password" id="password" name="password" />
            </div>
            <button type="submit">Submit</button>
        </form>
    );
}
```


### see console 

```js
console  Form values:  { username: 'sarwarasik@gmail.com', password: '123456' }
```
Planet scale DB alternative
Tags: programming, devops
Published: 2024-03-16 19:09:38

Do you have a Postgres DB on Planetscale that you need to transfer over?

Well, I transferred over to Hostinger. 

Isn't Hostinger a website host? You are right but when you get website hosting you also get 2 Databases included!!

How does £3.99 per month sound compared to $39 per month? 

Why not sign up today [https://hostinger.co.uk](https://hostinger.co.uk?REFERRALCODE=1LUKEECARTW64).

Thank you for your time.
Loops and Vectorization in Python
Tags: pythton, datascience, developers, dataengineering
Published: 2024-03-16 19:07:42

Using Loops:

```
import time
start = time.time ()
# iterative sum
total =0
# iterating through 1.5 Million numbers
for item in range(0, 1500000) :
        total = total + item
        print('sum is:' + str(total))
end = time. time ()
print(end - start)

#1124999250000
#0.14 Seconds


```
Using Vectorization:


```
import numpy as np

start = time.time ()
# vectorized sum - using numpy for vectorization
# np.arange create the sequence of numbers from 0 to #1499999
print(np. sum(np.arange (1500000)))
end = time.time
print(end - start)

##1124999250000
##0.008 Seconds

```

Vectorization took ~18x less time to execute as compared to the iteration using the range function.

This difference will become more significant while working with Pandas DataFrame.
Thread Safety in Python Multithreaded Applications
Tags: python, developer, multithreading, learning
Published: 2024-03-16 19:06:10

🚀 **Ensuring Thread Safety in Multithreaded Applications: Leveraging Locks**


In the realm of multithreaded programming, concurrency issues like race conditions and data corruption can wreak havoc if left unchecked. 💥 That's where locks come into play, acting as the guardians of thread safety.


🔒 **What are Locks?**

Locks provide a mechanism for controlling access to shared resources in multithreaded applications. They ensure that only one thread can access a critical section (part of the code that modifies shared data) at a time, thereby preventing conflicts and maintaining data integrity.


⚙️ **Why Use Locks?**

Consider scenarios where multiple threads need to access shared data structures or resources simultaneously. Without proper synchronization, chaos can ensue, leading to unpredictable behavior and bugs. Locks serve as the gatekeepers, ensuring orderly access and preventing concurrency issues.


💡 **Example: Protecting Shared Resources**

Take the example of a shared counter in a multithreaded environment. By employing a lock, we can ensure that each thread safely increments the counter without interference, thus maintaining consistency and accuracy.


```python

import threading


# Shared counter variable

counter = 0


# Function to increment the counter using a lock

def increment_counter(lock):

   global counter

   lock.acquire()

   try:

       counter += 1

   finally:

       lock.release()


if __name__ == "__main__":

   lock = threading.Lock()

   threads = []

   for _ in range(5):

       thread = threading.Thread(target=increment_counter, args=(lock,))

       threads.append(thread)

       thread.start()

   for thread in threads:

       thread.join()

   print("Final Counter Value:", counter)

```


🛡️ **Conclusion: Ensuring Robust Multithreading**

Locks play a pivotal role in ensuring robust multithreaded applications by providing a means to synchronize access to shared resources. By embracing locks, developers can mitigate concurrency issues and foster a more stable and reliable software environment.