teleren/devto huggingface dataset:
The dangers of each in Perl
Tags: perl
Published: 2023-05-14 08:23:05

It's been a very long time that I've made a post that wasn't related to [The Weekly Challenge](https://theweeklychallenge.org/), but it's about time I did :)

Today's post is about the unexpected output of a script when using the [each](https://perldoc.perl.org/functions/each) function in Perl inside a loop.

## Example script

Let's take a look at an oversimplified example:

```perl
#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

my %favorite = (
    Simon => 'blue',
    Tom   => 'brown',
    Dick  => 'brown',
    Harry => 'red',
);

OUTER: for (1 .. 5) {
    while (my($name, $color) = each %favorite) {
        next OUTER if $color eq 'brown';
    }

    say "Oh dear!";
    exit;
}
```

This seems straight forward enough. We have an outer loop that iterates five times. If any person has a favorite color of 'brown' we exit the inner loop, and 'Oh dear!' is never printed. So lets run that.

```bash
$ ./each.pl 
Oh dear!
```

## What went wrong

Even to an experienced Perl developer, this is probably not the expected result. So what happened?

Lets add some debugging output to the script

```perl
OUTER: for (1 .. 5) {
    say "count: $_";
    while (my($name, $color) = each %favorite) {
        say "name: $name, color: $color";
        next OUTER if $color eq 'brown';
    }

    say "Oh dear!";
    exit;
}
```

The output is

```bash
$ ./each.pl 
count: 1
name: Harry, color: red
name: Tom, color: brown
count: 2
name: Dick, color: brown
count: 3
name: Simon, color: blue
Oh dear!
```

What this shows is that even though we restart the outer loop, the inner `each` loop does not reset for each iteration.

This is documented in the each man page.

> The iterator used by each is attached to the hash or array, and is shared between all iteration operations applied to the same hash or array. Thus all uses of each on a single hash or array advance the same iterator location.

## Solution

The easiest solution is to always use the [keys](https://perldoc.perl.org/functions/keys) function when iterating over a hash inside a loop. Therefore a possible solution would be to write something like the below.

```perl
OUTER: for (1 .. 5) {
    foreach my $name (keys %favorite) {
        next OUTER if $favorite{$name} eq 'brown';
    }

    say "Oh dear!";
    exit;
}
```

This produces no output, as one would expect.

```bash
$ ./each.pl 
$
```
Mastering array iteration
Tags: webdev, javascript, codenewbie, programming
Published: 2023-05-14 08:19:36


_Introduction:_
JavaScript's array iteration methods are useful for working with arrays. They offer simple and efficient ways to manipulate arrays, making your code cleaner, easier to understand, and faster. Learning these methods is important for effectively manipulating arrays in JavaScript. Let's explore these methods and learn how to unleash the full potential of your array operations!

**1. forEach():**
The forEach() method in JavaScript allows you to perform actions on each item in an array. It simplifies iterating over an array and performing tasks on each element.

```
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
  console.log(number);
});
```

**2. map():**
The map() method in JavaScript creates a new array by applying a function to each element of the original array. It's useful for transforming and extracting specific values from arrays.

```
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
```

**3. filter():**
The filter() method in JavaScript creates a new array by selecting elements that meet certain conditions. It helps in refining and organizing data by picking specific elements.

```
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
```

**4. reduce():**
The reduce() method in JavaScript combines all elements of an array into a single value. It's useful for performing calculations or aggregating data.

```
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // Output: 15
```

**5. find():**
The find() method in JavaScript searches an array and returns the first element that matches a specific condition. It helps in finding specific elements in an array.

```
const numbers = [1, 2, 3, 4, 5];
const foundNumber = numbers.find((number) => number > 3);
console.log(foundNumber); // Output: 4
```

**6. some() and every():**
The some() and every() methods in JavaScript evaluate elements in an array based on a given condition. They help in determining if elements match specific criteria or if all elements satisfy a certain condition.

```
const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some((number) => number % 2 === 0);
console.log(hasEvenNumber); // Output: true

const allNumbersPositive = numbers.every((number) => number > 0);
console.log(allNumbersPositive); // Output: true
```

_Conclusion:_
JavaScript's array iteration methods provide efficient ways to manipulate arrays. They improve code readability and performance. Mastering these methods is crucial for effective array manipulation in JavaScript.
🔑 Key Habits of Successful Developers
Tags: webdev, beginners, programming, javascript
Published: 2023-05-14 08:07:51

1. Continuous Learning:
 The tech industry is always evolving. Successful developers make learning new technologies, languages, or tools part of their routine.

2. Problem Solving:
 Being a good developer is all about solving problems. It's essential to cultivate strong analytical thinking and problem-solving skills.

3. Understanding the Basics:
 Before jumping into frameworks and libraries, make sure you have a solid understanding of the fundamentals (HTML, CSS, and JavaScript for web developers).

4. Code Readability:
 Writing code that other humans can understand is just as important as writing code that machines can execute. Use clear naming conventions, keep functions small and focused, and always document your code.

5. Collaboration and Communication:
 Developers rarely work alone. Being able to work effectively in a team and communicate your ideas clearly is crucial.

6. Testing and Debugging:
 Learning how to efficiently debug your code and writing tests to prevent bugs is an essential skill.

7. Embracing Mistakes and Failure:
 Don't be afraid to make mistakes - they are an important part of the learning process. Learn from them and move on.

8. Building Projects:
 The best way to learn and improve as a developer is by building projects. They help consolidate your learning and give you something to show potential employers.

9. Staying Healthy:
 Spend time away from the screen. Regular exercise, a good diet, and sufficient sleep are important for everyone, including developers.

10. Joining a Community:
 Being part of a developer community can provide support, inspiration, learning opportunities, and even job prospects. Consider joining local meetups, online forums, or contributing to open-source projects.

Remember, everyone's journey in coding is unique, and success comes in many forms. Keep coding, keep learning, and most importantly, enjoy the process!
Install Google reCaptcha in your React/Next js app.
Tags: recaptcha, nextjs, react, form
Published: 2023-05-14 08:07:35

To prevent the bots from sending you thousand message a day from your contact form, you should use some system to detect if the visitor is a real human or a bot pretending to be a human.

To do so, you can use google reCaptcha. reCaptcha can determine if a visitor is a human or a bot using a score. Thats all done at their end so we do not have to worry about that. This article will show how we can add google reCaptcha v3 or invisible captcha into a reactjs/nextjs website. 

**Step 1:**
Install [**react-google-recaptcha-v3**](https://www.npmjs.com/package/react-google-recaptcha-v3) into your project by running this in your ternimal in vscode. 

```
npm i react-google-recaptcha-v3
```

**Step 2:**
Then go to the [admin console](https://www.google.com/recaptcha/admin/create) of the google reCaptcha. You have to login using your gmail account.

**Step 3:**
Register a new site

- Add a label (can be your site name or any name you prefer)
- Select recaotcha type to v3 (score based)
- Add your domain(s) 
- Agree to the terms and conditions and 
- Press Submit

**Step 4:**
You will get 2 keys under **reCaptcha Keys** section

**Step 5:**
Copy the site key because thats the key we need for this project

**Step 6:**
Go to your project in vscode, and go to file you want to add your google reCaptcha v3 (for this example we will add to the contact page where our form lives)

**Step 7:**
Import 2 utilities from the package we have installed in step 1 

```
import { GoogleReCaptcha, GoogleReCaptchaProvider } from "react-google-recaptcha-v3";
```

**Step 8:**
Wrap the entire component with the provider like this

```
const contact = () => {
    return (
        <GoogleReCaptchaProvider reCaptchaKey="<YOUR SITE KEY FROM STEP 5>">
            //rest of your code goes here
        </GoogleReCaptchaProvider>
    )
}
```

**Step 9:**
We need a state to store the reCaptcha value, so lets import the setState function from react and initiate a state.

```
const [captcha, setCaptcha] = useState(null);
```

**Step: 10**
Inside of your form, before the submit button add the capthca component we imported in step 7

```
<textarea {...register("Message", {})} placeholder="Your Message" className='message' />
<GoogleReCaptcha onVerify={(val) => setCaptcha(val)} />
<input type="submit" value="Send" className='submit' />
```
This will set the captcha value to the captcha state we made. 

**Step: 11**
Now inside your onSubmit function you can conditionally send the message or reject it based on the captcha value

```
const onSubmit = data => {
    if (captcha) {
        console.log(data);
        //send the mail
    }
}
```

Voilà! you are all set. Now bots can not annoy you with junk mails.
Visualize your GitHub repository statistics using GitHub Actions
Tags: githubhack23, githubactions, github, quickchart
Published: 2023-05-14 07:56:29

## What I built 
I built a custom GitHub Actions named **Quick Chart Report** that able to generate chart images that display repository statistics such as issues, pull requests, and more.

### Category Submission: 
Maintainer Must-Haves

### App Link
[Repository](https://github.com/minuth/quickchart-report)
[Marketpalce](https://github.com/marketplace/actions/quick-chart-report)

### Screenshots 

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

### Description 
The Quick Chart Report is an essential tool for GitHub users who want to easily visualize their repository statistics. The Quick Chart Report action automatically generate chart images that display repository statistics such as issues, pull requests, and more, when triggered by events such as opening or closing an issue or pull request, or other GitHub events, or by a schedule.


### Link to Source Code 
[https://github.com/minuth/quickchart-report](https://github.com/minuth/quickchart-report)

### Permissive License 
MIT

## Background (What made you decide to build this particular app? What inspired you?) 
My motivation for creating this project was to provide a convenient way for the maintainer to visualize the key statistics of the repository, such as the number of issues, pull requests and other metrics, in a single image that displays a chart.

### How I built it (How did you utilize GitHub Actions or GitHub Codespaces? Did you learn something new along the way? Pick up a new skill?) 
This project is a result of combining [Composite](https://docs.github.com/en/actions/creating-actions/creating-a-composite-action) Typescript GitHub Actions with my own utility GitHub Action called [Repository Report](https://github.com/minuth/report-action). The `Repository Report` action retrieves various statistics about a GitHub repository and outputs them as a JSON string. To visualize the JSON data as a chart image, I used [QuickChart](https://quickchart.io/), a tool that creates chart images from data. This project helped me learn about Composite GitHub Actions, which I was not familiar with before.

### Additional Resources/Info
- **Repository report**
  - [Repository](https://github.com/minuth/report-action) 
  - [Marketplace](https://github.com/marketplace/actions/repository-report)
- [QuickChart](https://quickchart.io/)
- [QuickChart limitations](https://quickchart.io/documentation/faq/#how-reliable-is-quickchart)
- [Example project](https://github.com/minuth/readme-chart-report-example) that used **Quick Chart Report** to generate the chart image and display it in README file.
Linux top 15 shell commend.
Tags: zobaidulkazi, kali, beginners, programming
Published: 2023-05-14 07:43:19

## Linux shell commands are commands that are executed in a command-line interface (CLI) in a Linux operating system. Here are some commonly used Linux shell commands:
<be />
`ls`: lists the files and directories in the current directory
`cd`: changes the current directory to the specified directory
`mkdir`: creates a new directory
`rm`: removes a file or directory
`cp`: copies a file or directory
`mv`: moves a file or directory
`cat`: displays the contents of a file
`grep`: searches for a pattern in a file or output
`ping`: tests connectivity to a network host
`ssh`: logs in to a remote server via Secure Shell (SSH) protocol
`top`: displays system information and processes in real-time
`df`: shows the amount of disk space used and available on a file system
`chmod`: changes the permissions of a file or directory
`chown`: changes the ownership of a file or directory
`tar`: archives files and directories into a tarball.

<br />
These are just a few examples of the many Linux shell commands that are available. To learn more about Linux shell commands, you can explore the Linux man pages, which provide detailed documentation and usage examples for each command.
Deploy a Python Flask App on Amazon EC2 - Part 1
Published: 2023-05-14 07:42:20

In this series of blogs, we'll be deploying a Python Flask application on Amazon EC2 instances.

When we in our development stages of writing a Python Flask App, we are commonly running it on our local computer as the server and entering eg. `localhost:5000` into our browser to see the changes. Now that the app is ready for deploying, how do we deploy it to the cloud?

**End Goal**
<< Insert Gif >>

**Agenda**
**Part 1: What is Flask, WSGI, Nginx?**
Part 2: Create an EC2 instance and accessing it
Part 3: Create Flask App and install Nginx on EC2 instance
Part 4: Configure Auto Scaling Group on AWS
Part 5: Making changes to our Flask App
How we designed and coded our Product Service
Tags: designpatterns, webdev, design, programming
Published: 2023-05-14 07:01:10

🚀 This is our third blog in the series of Low Level Design. Today we are going to design and see the sample code of our Product Service for an E-commerce company.

![Low level design meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3oeew90twktm8rvmz454.png)

> For the people who don't know, we are running an Open Source Project named NoMise (An E-Commerce customizable store) which is started for the people (Beginner friendly) to jump into the world of Open-Source.

## 📍 Let's start

So, here is how we designed our Product Service.

📌 For any E-Commerce app, one thing that they are most focused on are Products. So, we'll see How to design a Product Service which is capable of:-

- Create, Update a Product
- Get Products by Offer, Festival Sale etc
- Giving products to the frontend based on various strategies 
- Acquiring a lock to make sure if two admins are working on the same product then a lock will ensure only one atomic operation

So, to achieve these functionalities we should start from the Product itself.

![Product Entity](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjykawcf77ngjuxtv9fd.png)

📌 Now, to manage the Products we have Product Manager and to get API requests we have ProductResource which will request ProductService Component to do all the things. ProductService will consume ProductRepository class which will have only one function to perform and that is to do CRUD to Database (We are using AWS RDS Database here in our project)

![Product Manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yee53cgtg8loisd5c1e.png)

📌 Now, to get Products on the frontend we can have different strategies like Get Product by 25% Off, Get Product by festival sale etc. We are using Strategy pattern here.

![Product Strategy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yodehl083ruxkgv6eofy.png)
----------
So, our complete design of the service is:- 

![Product Service Design](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlwyq4ales1u91g93i7q.png)

For a clear picture, click [here](https://drive.google.com/file/d/1Lz4aK11B6bkeAC0d-3ZbYWrFBeFXomJp/view?usp=sharing)
-------

> To code this service, you can use any Programming language. We are using Java alongwith SpringBoot so that in future we can scale our application easily.

Code can be found here in this [repo](https://github.com/AlphaDecodeX/nomise_inventory/tree/master). Feel free to contribute.

Note: To contribute in NoMise's Frontend, Follow this [Repo](https://github.com/AlphaDecodeX/NoMise_Store)

You can follow this [board](https://github.com/users/AlphaDecodeX/projects/1) to actively see who is working on which issue. And raise an issue to contribute or Join our [Whatsapp](https://chat.whatsapp.com/B7CwSOLkl8wIzLMn8GRNst) group to join the focused community of contributors.

![Progress Board](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzlxtgz3mslav2g42obi.png)
VR Wonderlands: What Kind of Experience Would You Create?
Tags: discuss, beginners, codenewbie
Published: 2023-05-14 07:00:00

If you were given the opportunity to design a VR experience, what kind of captivating world would you bring to life?

---
Follow the [CodeNewbie Org](https://dev.to/codenewbieteam) and [#codenewbie](https://dev.to/t/codenewbie) for more awesome discussions and online camaraderie!

*{% embed* [https://dev.to/codenewbieteam](https://dev.to/codenewbieteam) %}
What's the Most Obscure Coding Language You've Ever Encountered?
Tags: discuss
Published: 2023-05-14 07:00:00

Malbolge, anyone? Let's dive into the depths of programming folklore and share our encounters with the most enigmatic, perplexing, and mind-bending languages out there. 

---
Follow the DEVteam for more awesome discussions and online camaraderie!

{% embed [https://dev.to/devteam](https://dev.to/devteam) %}
RubyMine. How to Open a Folder with a Single Click
Tags: ruby, jetbrains, opensource
Published: 2023-05-14 06:52:32

Jetbrains gave me a license for developing my OpenSource project.


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


To make my development experience better I set up the option - **Open files with Single Click**

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

Surprisingly there is no an option to do the same with Folders

https://youtrack.jetbrains.com/issue/IDEA-142105


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

Fortunately there is an old but old plugin to manage it

https://plugins.jetbrains.com/plugin/12778-quick-file-preview


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

Now everything works like I want.

Happy Coding!
anagram program in java
Tags: list, java, interview, strings
Published: 2023-05-14 06:52:31

For Explanation watch the video
{% embed https://youtu.be/BIIkDUA99A0 %}

code :: 

```
import java.util.*;
import java.lang.*;
class Demo{
	public static void main(String[] args){
		String s1 = "keepp";
		String s2 = "peek";
		char[] ch1 = s1.toCharArray();
		char[] ch2 = s2.toCharArray();
		Arrays.sort(ch1);
		Arrays.sort(ch2);
		String ss1 = new String(ch1);
		String ss2 = new String(ch2);
		if(ss1.equals(ss2)){
			System.out.println("anagram");
		}else{
			System.out.println("not anagram");
		}
	}
}
```
Ensuring Data Consistency in Concurrent API Requests: Introducing the AbortController
Tags: javascript, webdev, programming, api
Published: 2023-05-14 06:31:28

Let's say you are working on a project and in that project you want to get the data of the user's friends. Let's say you requested to fetch the data of Adam's friends. But Adam has a lot of friends so the API request takes time to fetch the list of friends. Now before the API has responded you decided that you want to fetch the friend list of Eve and Eve's friend list is short so the API responded quickly with the friend list of Eve and now as the API responded you display the data on the screen. But wait what about the API request of Adam's friend's list? As the API call is in progress when this API is going to complete it will override the result of Eve's friend list and instead of showing the right data we will be displaying the data of Adam's friends instead of Eve's.

You see the bug in the above explanation. So to get rid of the bug we need to abort the API of Adam's friend list. There are many ways to achieve this but for this blog, I will cover the AbortController.

AbortController

The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.

We will use the AbortController in the use effect like this 

useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;
             
    fetch('my-resource', { signal })
  	  .then(res => res.json())
      .then(res => setFriendsList(res))
      .catch(console.log);

    return () => controller.abort();
  }, []);

But how exactly this AbortController works? 

When the abort method on the controller is called, the fetch operation and every subsequent then methods are discarded, and the catch method is executed. 

If you are doing anything in the catch block, then you might need to add a new check to make sure that you set the errors in the right scenario. So to check if the API is aborted mid execution you can check if controller.abort.signal is set to true, If it is then the API is aborted mid-execution.

Happy hacking!