teleren/devto huggingface dataset:
Explanation of useRef Hooks in React js!
Published: 2023-11-05 09:15:56

The `useRef` hook in React is a built-in hook that provides a way to create and manage references to DOM elements and other values in functional components. It is often used to interact with the DOM or to store mutable data that doesn't trigger component re-renders when it changes. Here's how it works:

1. **Creating a Ref:**
   To create a ref, you can use the `useRef` hook and assign it to a variable. For example:

   ```javascript
   import React, { useRef } from 'react';

   function MyComponent() {
     const myRef = useRef();
     // You can also initialize the ref with an initial value:
     // const myRef = useRef(initialValue);

     // ...
   }
   ```

   Now, `myRef` is a reference object that you can use to access and manipulate DOM elements or other values.

2. **Attaching Refs to DOM Elements:**
   You can attach a ref to a DOM element by using the `ref` attribute in your JSX. For example:

   ```javascript
   function MyComponent() {
     const myRef = useRef();

     const handleClick = () => {
       // Access the DOM element using the ref
       myRef.current.focus();
     }

     return (
       <div>
         <input ref={myRef} />
         <button onClick={handleClick}>Focus Input</button>
       </div>
     );
   }
   ```

   In this example, when the button is clicked, it uses the `myRef` to focus on the input element.

3. **Accessing and Manipulating Refs:**
   You can access and manipulate the value of a ref using the `current` property of the ref object. For example:

   ```javascript
   const value = myRef.current;
   myRef.current = newValue;
   ```

   It's important to note that when you change the `current` property of a ref, it won't trigger a re-render of your component.

4. **Storing Other Values:**
   `useRef` is not limited to just DOM elements; you can use it to store any mutable value. This value persists across re-renders and does not trigger component updates. For example:

   ```javascript
   function MyComponent() {
     const count = useRef(0);

     const increment = () => {
       count.current += 1;
       console.log('Count:', count.current);
     }

     return (
       <div>
         <button onClick={increment}>Increment</button>
       </div>
     );
   }
   ```

   In this example, `count` is a ref that stores a mutable value (an integer) and persists across re-renders without causing the component to update.

`useRef` is a versatile hook that is commonly used for managing DOM elements, creating timers, storing previous values for comparison, and other scenarios where you need to maintain mutable state without causing re-renders.
Introduction to C Programmig
Tags: programming, coding
Published: 2023-11-05 08:53:18


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pzv3hnmlbc0hie96kbm.jpeg)C is a **procedural** programming language, mainly developed as a system programming language to write the **Unix** operating system. Some of the main features of C language include; 

- Fast speed

- Clean syntax

- Low-level memory access

- General Purpose and Portable
Most of the recent programming languages have borrowed syntax from the C language. Some of them include PHP, JavaScript and Java.

**Basic syntax structure**

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

1. **#include stdio.h** is the header file.
2. **int main()** is the declaration of the main function. It 
    is the entry point of a C Progam.
3. **The pair of curly braces** encloses the body of the 
     program.

**How to Execute the  above program**
To execute the program we need to first compile it using a compiler  and then we can run generated executable. 

_Thats basically a simple introduction of C Programmig language._


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qs12xzciydf4lmpv5xv7.jpeg)
ELI5: Account Abstraction (AA)
Published: 2023-11-05 08:31:35

##Introduction

Account Abstraction (AA) is simply a blend of a smart contract's ability to validate its own transactions alongside offering an intuitive user experience. In Ethereum for instance, Account Abstraction enables the use of smart contract wallets without needing a private key or maintaining an ETH balance for gas fees. Account Abstraction focuses on improving both the accessibility and security of assets in a non-custodial wallet.

Reasons why this technology has been developed, includes:

**- Improved security**: Smart contracts can be programmed to be more secure than Externally Owned Accounts (EOAs) and can be used to implement features such as multi-signature wallets and social recovery.

**- Greater flexibility**: Smart contracts can be used to create new types of wallets and account management systems, with features that are not possible with EOAs.

**- Reduced costs**: Smart contracts can be used to optimize gas costs for transactions, and can also be used to implement features such as batching and payment splitting.

####Here is a simple analogy to help you understand account abstraction:

Imagine that you are the President of the Federal Republic of Nigeria, and obviously Nigeria is endowed with a lot of money and resources. You don't want to manage all of this yourself, so you appoint Cabinet Ministers to oversee these resources and do the "dirty work" for you. The Minister of Finance, Budget & Planning would be responsible for keeping track of your money and possessions and making sure that everything is in order.

Account abstraction works in a similar way. The smart contract wallet is like a "Minister of Finance" for your Ethereum account. It manages your ETH and all of your transactions so that you don't have to worry about it.

####Other benefits of account abstraction include:

**- Improved user experience**: Account abstraction can make it easier and more convenient for people to use dApps. For example, users could interact with dApps without having to worry about managing their private keys or gas fees.

**- Increased security**: Account abstraction can make it more difficult for hackers to steal users' funds. For example, users could use account abstraction to create wallets that are more resistant to phishing attacks.

**- New possibilities for developers**: Account abstraction can enable developers to create new and innovative types of wallets and applications. For example, developers could create wallets that allow users to pay for goods and services with multiple cryptocurrencies at once.

####Some of the challenges of account abstraction are:

**- Complexity**: Account abstraction is quite a broad technology and it could be difficult at the initial stage to understand, for both users and developers.

**- Security risks**: There are some potential security risks associated with account abstraction. For example, if a smart contract that is used for account abstraction is hacked, it could give the hacker access to users' funds.

**- Scalability**: Account abstraction could add some overhead to a blockchain, which could make it less scalable.
Weekly reading digest #12
Tags: php, symfony, backend, ddd
Published: 2023-11-05 08:31:08

[People who say “PHP is insecure” are uninformed](https://hakluke.com/people-who-say-php-is-insecure-are-uninformed/)

[Collateral behavior changes with PHP 8.0 switch()](https://www.exakat.io/en/php-8-changes-in-switch/)

[Mastering the (array) Cast Operator in PHP: A Comprehensive Guide](https://www.exakat.io/en/mastering-the-array-cast-operator-in-php-a-comprehensive-guide/)

[PHP: Never type hint on arrays](https://peakd.com/php/@crell/php-never-type-hint-on-arrays)

[On the use of enums](https://peakd.com/hive-168588/@crell/on-the-use-of-enums)

[PHP-TUI Progress](https://www.dantleech.com/blog/2023/11/03/php-tui-progress/)

[Unorthodox Eloquent II](https://muhammedsari.me/unorthodox-eloquent-2)

[How to Autowire Multiple Instances of Same Type in Symfony and Laravel](https://tomasvotruba.com/blog/how-to-autowire-multiple-instances-of-same-type-in-symfony-laravel)

[Treezor: a serverless banking platform](https://bref.sh/docs/case-studies/treezor)

[[Docker] Migrate to Compose V2](https://docs.docker.com/compose/migrate/)

[Domain model purity vs. domain model completeness (DDD Trilemma)](https://enterprisecraftsmanship.com/posts/domain-model-purity-completeness)

[Domain model purity and the current time](https://enterprisecraftsmanship.com/posts/domain-model-purity-current-time/)

[Domain model purity and lazy loading](https://enterprisecraftsmanship.com/posts/domain-model-purity-lazy-loading/)
9 ways you can stop spam on your website
Tags: webdev, web3, website, spam
Published: 2023-11-05 08:19:45

Pro Tip: [Stop Website Spam With Captcha](https://veilmail.io) MailVeil.io is a great free tool that will hide your email address behind a captcha ( stops web crawlers,bots etc. and makes sure you are human)


If you've published your email address on your website and are receiving unwanted spam, you can take several steps to reduce or eliminate this issue. Here are nine ways to stop getting unwanted spam to your publicly available email address:

1. Use an Email Obfuscation Tool:
   Consider using an email obfuscation tool or plugin to hide your email address from email harvesting bots. These tools can encode your email address in a way that's still visible to humans but not easily readable by automated scripts.

2. Replace Text with Images:
   Instead of displaying your email address as text on your website, you can create an image of your email address and use that on your site. Spambots typically can't interpret text within images.

3. Implement CAPTCHA:
   Incorporate CAPTCHA challenges on your contact forms to ensure that only real people can submit messages. This can help prevent automated bots from sending you spam.

4. Utilize a Contact Form:
   Instead of displaying your email address directly, use a contact form on your website. This way, visitors can send you messages without seeing your email address, making it less susceptible to spam.

5. Set Up Email Filtering:
   Use your email service's filtering capabilities to automatically move potential spam messages to a separate folder. This won't stop the spam, but it will keep your inbox cleaner.

6. Enable Email Verification:
   On your contact form or subscription page, add an email verification step where users must confirm their email address by clicking a link sent to them before they are added to your list or contact you.

7. Use a Dedicated Email Address:
   Consider creating a dedicated email address specifically for your website, which is different from your primary personal or business email. This way, spam won't clutter your primary inbox.

8. Avoid Displaying Email in Clear Text:
   If you must display your email address, avoid using the standard "mailto" HTML link, which is easily scraped by spambots. Instead, write it out with additional text, like "contact [at] yourdomain [dot] com."

9. Periodically Change Your Email Address:
   If the spam becomes overwhelming, you might consider changing your publicly displayed email address periodically. Update your website and inform your regular contacts of the change.

These steps can significantly reduce the amount of unwanted email you receive. Be proactive in protecting your email address and consider a combination of these methods to discourage spammers.

PRO TIP: Use VeilMail.io to [hide email address from spammers](https://veilmail.io) VeilMail.io is a great free tool that will hide your email address behind a captcha ( stops web crawlers,bots etc. and makes sure you are human)

Check out MailVeil.io for sure
A Hands-On learning with Scikit-Learn
Published: 2023-11-05 07:09:35

Introduction

Machine learning has become an integral part of data analysis and predictive modeling. Scikit-Learn, also known as sklearn, is a powerful and widely-used Python library that provides simple and efficient tools for data analysis and modeling. In this article, we'll explore the fundamentals of Scikit-Learn and demonstrate how to use it for various machine learning tasks with code snippets.

Installing Scikit-Learn

Before we dive into using Scikit-Learn, make sure you have it installed on your machine. You can install it using pip:

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

Once Scikit-Learn is installed, we can begin exploring its capabilities.

Data Preparation

Machine learning typically starts with data preprocessing. In Scikit-Learn, datasets are typically represented as 2D arrays (or matrices) where each row represents an instance, and each column represents a feature. Let's load a sample dataset and prepare it for modeling.
AWS CLI - Command Completion
Tags: aws, cloud, devops, beginners
Published: 2023-11-05 06:57:10

> In this article we will look how we can enable command completion for AWS CLI.

### Prerequisites

Install AWS CLI on the Ubuntu distribution.

```bash
$ aws --version
aws-cli/2.13.32 Python/3.11.6 Linux/6.2.0-1012-aws exe/x86_64.ubuntu.22 prompt/off
```

Check out my article on installing AWS CLI.

{% embed https://dev.to/iamunnip/installing-and-updating-aws-cli-on-linux-2dpp %}

### Configuration

Verify the path of `aws_completer` in our system.

```bash
$ which aws_completer
/usr/local/bin/aws_completer
```

Verify the shell of our system.

```bash
$ echo $SHELL
/bin/bash
```

Add the location of `aws_completer` in the PATH.

```bash
$ vi ~/.bash_profile
    export PATH=/usr/local/bin/:$PATH
```

Enable the command completion by adding the below entry in `.bashrc` file.

```bash
$ vim .bashrc
    complete -C '/usr/local/bin/aws_completer' aws
```

Reload the profile to take the new changes.

```bash
$ source ~/.bash_profile

$ source ~/.bashrc
```

Verify the command completion.

```bash
$ aws dynamodb d<TAB>
delete-backup                           describe-contributor-insights           describe-import                         describe-time-to-live
delete-item                             describe-endpoints                      describe-kinesis-streaming-destination  disable-kinesis-streaming-destination
delete-table                            describe-export                         describe-limits
describe-backup                         describe-global-table                   describe-table
describe-continuous-backups             describe-global-table-settings          describe-table-replica-auto-scaling
```

### Reference

[https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-completion.html](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-completion.html)
Block Users from Specific Countries using Hono Ultrafast Web Framework and Vercel Edge Functions
Tags: webdev, javascript, tutorial, programming
Published: 2023-11-05 06:46:32

In this tutorial, we'll explore how to block users from specific countries using the [Hono](https://hono.dev/) Ultrafast Web Framework in conjunction with Vercel [Edge Functions](https://vercel.com/docs/functions/edge-functions). By the end, you'll have a setup in place to filter and handle users based on their country of origin.

## Creating a Hono App with Vercel Template

Let's kick things off by setting up a Hono app with the Vercel template. This will serve as the foundation for our country-based blocking feature.

```bash
npm create hono@latest my-app
```

After running the command above, select the `Vercel` template option.

```bash
? Which template do you want to use?

❯   vercel
```

Then navigate into your app's directory and install the dependencies:

```bash
cd my-app
npm i
```

## Obtaining the Request Header

To identify the country of the incoming request, we'll make use of the `x-vercel-ip-country header` provided by `Vercel Edge Functions`. Here's how to access this header in your Hono app:

```typescript
// File: api/index.ts

// ...

app.get('/', (c) => {

  // Read more about this header on https://vercel.com/docs/edge-network/headers
  const INCOMING_COUNTRY_CODE = c.req.header('x-vercel-ip-country')

// ...
```

## Blocking Users

Now that we have the country code, let's create conditional responses based on the user's country. You can define a list of blocked country codes and handle requests accordingly:

```typescript
// File: api/index.ts

// ...

const BLOCKED_COUNTRY_CODES = ['US', 'FR']

app.get('/', (c) => {
  // ...
  if (!INCOMING_COUNTRY_CODE) return c.html(`Detected Country: ${INCOMING_COUNTRY_CODE}`)

  // If the user is from a blocked country, return a specific response
  if (BLOCKED_COUNTRY_CODES.includes(INCOMING_COUNTRY_CODE.toUpperCase())) {
    return c.html(`Detected Country: ${INCOMING_COUNTRY_CODE}, I have blocked users from this country.`)
  }

  // Else, return your actual response
  return c.html(`Detected Country: ${INCOMING_COUNTRY_CODE}, Redirecting you to our main website...`)
})

// ...
```

## Got latency concerns? It's heck fast.

To measure the latency of such a middleware, I measured the performance of the endpoint from different locations, using [SpeedVitals](https://speedvitals.com) Batch Report. Here's what it has to show about it 👇🏻

![TTFB Endpoint Around World](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3q3gqfu8afmq8g8b0uxh.png)

Batch Report Link: https://speedvitals.com/result/TZSKWkx9/

The average TTFB being 33ms around the world! One would love to have such a powerful middleware on the edge for such a speed.

## You're Done!

With these steps in place, you've learned how to effectively block users from specific countries based on their IP addresses. This can be a valuable feature for enhancing security and user experience on your website.
Preserving Special Characters in Query Parameters: A React Journey
Tags: javascript, react, webdev, opensource
Published: 2023-11-05 06:32:58

**Introduction**

In the world of web development, handling query parameters and URLs is a fundamental task. However, there are situations where special characters within these parameters can lead to unexpected challenges. One such issue I encountered involved the loss of special characters within a `redirect_uri`. In this article, I'll walk you through the problem, the solution, and how to implement it in your React application.

**The Problem**

Imagine you have a URL like this: 

```
http://localhost:3001/en/auth/login?servicename=Grant&redirect_uri=http://localhost:3000/bsmrnt/buy-ticket?code=ETN&start_time=10:00:00

```
In this URL, the `redirect_uri` contains special characters, specifically the & symbol. When extracting this parameter in a React app using `queryParams`, you might run into issues as the `&` character separates query parameters.

**The Initial Approach**

My initial approach was to use the common method of extracting query parameters in React: 

```
const queryParams = new URLSearchParams(window.location.search);
const redirectUri = queryParams.get('redirect_uri');
```
However, this approach resulted in `redirectUri` containing only part of the URL:

```
http://localhost:3000/bsmrnt/buy-ticket?code=ETN

```
As you can see, the `&start_time=10:00:00` part is missing.

**The Solution**

To preserve the complete `redirect_uri`, I found a creative solution using JavaScript's regular expressions and `window.location.href`. Here's the code:


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

- We first obtain the complete URL using `window.location.href`.
- Then, we use a regular expression to extract the `redirect_uri` and capture everything that follows it.
- Finally, we ensure that we have the complete `redirect_uri` by checking both the regular expression match and the `queryParams`.

**Implementation**

To implement this solution in your React app, follow these steps:

1. Retrieve the `currentURL` and use the regular expression to capture the complete `redirect_uri`.

2. Use the captured `redirectUri` as needed in your application.

Here's a sample implementation inside a `useEffect`:


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

This ensures that you store the complete `redirect_uri` without losing any special characters.

**Conclusion**

Handling special characters in query parameters can be tricky, but with the right approach, you can ensure they are preserved. In this article, we explored a real-world problem and a creative solution using JavaScript and React. By implementing this technique, you can preserve the integrity of your URLs and provide a seamless user experience.

If you've ever struggled with lost query parameters, give this solution a try. Let's solve the mystery of preserving special characters in query parameters together!
Installing and Updating AWS CLI on Linux
Tags: aws, cloud, beginners, devops
Published: 2023-11-05 05:59:40

> In this article we will look how we can install and update AWS CLI on Ubuntu distribution.

### Prerequisites

Create an Ubuntu 22.04 LTS instance.

```bash
$ cat /etc/issue
Ubuntu 22.04.3 LTS \n \l
```

Install some prerequisite packages. These packages are included by default in most major distributions of Linux.

```bash
$ sudo apt update

$ sudo apt install unzip glibc-source groff less
```

### Installing the CLI

Download the latest AWS CLI zip file.

```bash
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
```

Extract the downloaded zip file.

```bash
$ unzip awscliv2.zip
```

Run the install program using elevated privileges.

```bash
$ sudo ./aws/install --bin-dir /usr/local/bin --install-dir /usr/local/aws-cli
```

Verify the version of CLI.

```bash
$ aws --version
aws-cli/2.13.32 Python/3.11.6 Linux/6.2.0-1012-aws exe/x86_64.ubuntu.22 prompt/off
```

### Updating the CLI

Download the latest AWS CLI zip file. Here we are using the same zip file downloaded earlier.

```bash
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
```

Extract the downloaded zip file with `-u` flag. This will automatically update existing files and create new ones as needed.

```bash
$ unzip -u awscliv2.zip
```

Run the install program using elevated privileges with `--update` flag.

```bash
$ sudo ./aws/install --bin-dir /usr/local/bin --install-dir /usr/local/aws-cli --update
```

Verify the version of CLI.

```bash
$ sudo ./aws/install --bin-dir /usr/local/bin --install-dir /usr/local/aws-cli --update
Found same AWS CLI version: /usr/local/aws-cli/v2/2.13.32. Skipping install.
```

### Reference

[https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)