teleren/devto huggingface dataset:
Writing as a form of learning new concepts
Tags: javascript, writing, programming, career
Published: 2023-01-14 06:00:00

---
title: Writing as a form of learning new concepts
published: true
description: 
tags: #javascript #writing #programming #career
cover_image: https://images.pexels.com/photos/372748/pexels-photo-372748.jpeg
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-14 09:00 +0000
---
This year one of my main goals is to "put myself out there". Naturally I tend to be less audible, do my job and avoid the spotlight as much as possible but this year I want to step out of the comfort zone a little (it's gotten a bit too comfy in there) and try out writing. I do this for two main reasons:

1. Connecting with new people 
2. Enhancing my knowledge on a topic 

You see there's a mainstream quote that goes something like

> when one teaches, two learn.

which I think is a brilliant quote because for one it forces the `teacher` to solidify their knowledge before passing it down to another and secondly it creates an avenue for the `teacher` to also learn if there happens to be an aspect of the topic that they don't _**understand**_ quite well.
 
I'm starting to learn [nodejs](https://nodejs.org) in depth - not [express](https://expressjs.com), not [nestjs](https://nestjs.com/), just raw and unfiltered nodejs and writing about my learnings would not only expose my knowledge gaps to a wider community who would be quick to call out on my errors, but also serve as a reference point if I was to forget such concepts later down the line. 
I think the mistake most developers make when transitioning into backend development with nodejs is to immediately pick up frameworks after a few lessons on creating a server or reading contents from a file which to be honest I don't view as such a horrible act, I mean here is a snippet on how to send a "hello world" message using both nodejs and express as a server

nodejs

```javascript
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/plain', 
  });
  res.end('Hello world')
});

server.listen(3000);
```

express 

```javascript
const app = require('express')();
app.use('/', (req, res) => res.send('hello world')
app.listen(3000)
```

I mean it's immediately obvious why you would want to use express right off the bat but this creates a huge knowledge gap into the underlying workings of nodejs and if a deep technical problem was to surface (memory leaks anyone? :eyes:), I don't think stack overflow would be enough to save you.

But naturally you get to a stage in your career where you move on from using existing frameworks and libraries to either wanting to contribute to them or creating your own entirely whether that be for internal or public use and at that point you will find yourself running back to the basics -- very much like I am right now :sweat_smile:

So here's to more learning AND writing this year :clinking_glasses:



>  Based opinion but for me a good measure of when to know you don't understand a technical topic quite well is when you can't educate a non-technical person on how it works or it's concept
The Sequelize library simplifies developer life.
Tags: node, mysql, postgres, javascript
Published: 2023-01-14 05:59:58

- **Sequelize** is an Object-Relational Mapping (ORM) library for **Node.js** that allows developers to interact with databases using JavaScript. It supports multiple database systems, including **MySQL**, **PostgreSQL**, **SQLite**, and **MSSQL**, and provides a powerful set of tools for working with data, including querying, validation, and associations. It can be used to perform common database operations, such as inserting, updating, and retrieving data, without having to write raw SQL statements.

- To use **Sequelize**, you would first need to install it in your Node.js project using npm:

```
npm install sequelize
```
Then, you would need to create a connection to your database by importing the library and initializing it with the connection details, like this:

```
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});
```

Once the connection is established, you can define your data models using the **define** method on the **sequelize** instance. For example, to define a **User** model with a name and email field:
```
const User = sequelize.define('User', {
  name: Sequelize.STRING,
  email: Sequelize.STRING
});
```

You can use the define method to define relationship between the tables.

- After defining your models, you can then use the **sync** method to create the corresponding tables in the database:
```
sequelize.sync();
```
To perform CRUD operations, you can use the various methods provided by the model instances, such as **create**, **findAll**, **update**, and **destroy**.

- For example, to create a new user:

```
User.create({ name: 'John Doe', email: 'johndoe@example.com' });
```

- To retrieve all users from the database:
```
User.findAll().then(users => {
  // do something with the users
});
```
- These are just a few examples of how to use **Sequelize**. It's a powerful library with many other features and options for working with databases in Node.js. You can refer to the official [documentation](https://sequelize.org/) for more information and examples.

Thanks..!!
FileOrganizer: Organize your files in a simple command
Tags: javascript, productivity, node
Published: 2023-01-14 05:38:27

I created this nodejs cli program to organize your files. 

## The Problem:

Every day at the end of the day my downloads folder gets messy and unorganized. So I used to reorganize the folders. and after a while, I didn't want to do it manually. that is why I created this program.

## The Planning:

After a little analyzing, I came to the conclusion that if I can put my files in the same file type folder and add a date to them, I can easily manage them.

## The Solution

I know there may be other libs like this available. But I wanted to create my own. and with little knowledge of the batch script, I started the first version in a batch script. but I had problems making this work in other operating systems. That was when I started using javascript and node js.

So now i present you [FileOrganizer](https://github.com/plsankar/fileorganizer-cli).

Do Like, Share your feedback 🙌 and contributions are welcome.

Feel free to connect with me 👍
7 Principles in Software Testing You Should Know. ( Explained)
Tags: webdev, beginners, programming, tutorial
Published: 2023-01-14 04:56:52

Become a Automation Rockstar : https://thetestingacademy.com


In this tutorial, we are discussing 7 important software testing principle that you should know as QA. These principles provide  us clear view about the Software testing life cycle. 

Software Testing is process of executing a program with the aim to find errors or bug.

{% embed https://youtu.be/NWlFl4XtrUc
 %}

Join Facebook Group :  http://bit.ly/learntesting2019

Website:   https://scrolltest.com

Website:   https://thetestingacademy.com

Twitter: https://twitter.com/itstechmode


#automationtesting #manualtesting #testautomation #thetestingacademy #scrolltest
🚀 Tools and services I recommend:
Some of the courses that I recommend to become better Automation Tester 🙌🙌

✅Selenium Training and Certification -
https://scrolltest.com/go/edureka


✅Learn Jenkins for QA -
https://bit.ly/learnjenkins-p1


✅Programming Java -
https://bit.ly/learnjava2020-p1


✅Test Automation - 
https://bit.ly/learnautomation2020


✅API Testing - 
https://www.learnapitesting.com


✅Cypress Tutorial with LIVE Projects -
http://cypresstutorial.com
1061. Leetcode Solution in cpp
Tags: cpp, challenge, chiki1601, beginners
Published: 2023-01-14 05:34:00

```cpp
class UnionFind {
 public:
  UnionFind(int n) : id(n) {
    iota(begin(id), end(id), 0);
  }

  void union_(int u, int v) {
    const int i = find(u);
    const int j = find(v);
    if (i > j)
      id[i] = j;
    else
      id[j] = i;
  }

  int find(int u) {
    return id[u] == u ? u : id[u] = find(id[u]);
  }

 private:
  vector<int> id;
};

class Solution {
 public:
  string smallestEquivalentString(string s1, string s2, string baseStr) {
    string ans;
    UnionFind uf(26);

    for (int i = 0; i < s1.length(); ++i)
      uf.union_(s1[i] - 'a', s2[i] - 'a');

    for (const char c : baseStr)
      ans += 'a' + uf.find(c - 'a');

    return ans;
  }
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/lexicographically-smallest-equivalent-string/
1061. Lexicographically Smallest Equivalent String
Tags: java, leetcode, problemoftheday, 100daysofcode
Published: 2023-01-14 05:14:34

**Problem Statement:**

You are given two strings of the same length s1 and s2 and a string baseStr.

We say s1[i] and s2[i] are equivalent characters.

For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.
Equivalent characters follow the usual rules of any equivalence relation:

**Reflexivity:** 'a' == 'a'.
**Symmetry:** 'a' == 'b' implies 'b' == 'a'.
**Transitivity:** 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'.
For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr.

Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.

 

**Example 1:**

**Input:** s1 = "parker", s2 = "morris", baseStr = "parser"
**Output:** "makkek"
**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek".

**Example 2:**

**Input:** s1 = "hello", s2 = "world", baseStr = "hold"
**Output:** "hdld"
**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".

**Example 3:**

**Input:** s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
**Output:** "aauaaaaada"
**Explanation:** We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".
 

**Constraints:**

- 1 <= s1.length, s2.length, baseStr <= 1000
- s1.length == s2.length
- s1, s2, and baseStr consist of lowercase English letters.

**Solution:**

**Algorithm:**
1. Initialize parent array with 26 elements, each element is its index.
2. Iterate through s1 and s2, find the parent of each character, if they are not the same, set the parent of the larger one to the smaller one.
3. Iterate through baseStr, find the parent of each character, and append the character to the result.
4. Return the result.
**Code:**
```
1. Initialize parent array with 26 elements, each element is its index.
2. Iterate through s1 and s2, find the parent of each character, if they are not the same, set the parent of the larger one to the smaller one.
3. Iterate through baseStr, find the parent of each character, and append the character to the result.
4. Return the result.

```
**Time Complexity:**
 O(n), where n is the length of baseStr.
**Space Complexity:**
O(1), we only use constant extra space
Resolving GraphQL/ExtractType rubocop offense in mutation type rails
Tags: rails, rubocop, graphql
Published: 2023-01-14 05:00:00

Before we do any refactoring, currently, my project’s mutation root looks like the below in schema:

```graphql
type Mutation {
  adminCreateCategory(
    input: AdminCreateCategoryInput!
  ): Category

  adminCreateKind(
    input: AdminCreateKindInput!
  ): Kind

  adminCreateVendor(
    input: AdminCreateVendorInput!
  ): Vendor

  adminLogin(
    input: AdminLoginInput!
  ): AdminLoginPayload
}
```

Also, the `mutation_type.rb` looks like this:
```ruby
module Types
  # Path: app/graphql/types/mutation_type.rb
  class MutationType < Types::BaseObject
    description "The mutation root of this schema"

    field :admin_login, mutation: Mutations::AdminLogin, description: "Admin login"

    field :admin_create_category, mutation: Mutations::AdminCreateCategory, description: "Create a new category"

    field :admin_create_kind, mutation: Mutations::AdminCreateKind, description: "Create a new kind"

    field :admin_create_vendor, mutation: Mutations::AdminCreateVendor, description: "Create a new vendor"
  end
end 
```

My rubocop says:
```bash
Consider moving admin_login, admin_create_category, admin_create_kind, admin_create_vendor to a new type and adding the `admin` field instead (convention:GraphQL/ExtractType)
```

To resolve this offense, we will move to a separate common field, `admin,` in the mutation type.

## Solution:

Create a new file `app/graphql/types/admin_mutation_type.rb` with the following text:
```ruby
module Types
  # Admin mutation root
  class AdminMutationType < Types::BaseObject
    description "The admin mutation root of this schema"

    field :login, mutation: Mutations::AdminLogin, description: "Admin login"

    field :create_category, mutation: Mutations::AdminCreateCategory, description: "Create a new category"

    field :create_kind, mutation: Mutations::AdminCreateKind, description: "Create a new kind"

    field :create_vendor, mutation: Mutations::AdminCreateVendor, description: "Create a new vendor"
  end
end
```

Update `app/graphql/types/mutation_type.rb` with the following code:
```ruby
module Types
  # Path: app/graphql/types/mutation_type.rb
  class MutationType < Types::BaseObject
    description "The mutation root of this schema"

    field :admin, Types::AdminMutationType, null: false, description: "Admin mutations"

    def admin
	  Types::AdminMutationType
    end
  end
end
```

Now the new schema will be changed as follows:
```graphql
type Mutation {
  admin: AdminMutation!
}

type AdminMutation {
  createCategory(
    input: AdminCreateCategoryInput!
  ): Category

  createKind(
    input: AdminCreateKindInput!
  ): Kind

  createVendor(
    input: AdminCreateVendorInput!
  ): Vendor

  login(
    input: AdminLoginInput!
  ): AdminLoginPayload
}
```

Now refactor test cases according to the new changes. We can also create a separate type for `create` for mutation of create in the admin.  
  
The same procedure can also be done in `query_type.rb` while refactoring.

---- 
Happy Coding!
How to Become a Perfect Automation Tester || (Do This)
Tags: webdev, programming, tutorial, beginners
Published: 2023-01-14 04:51:48

What Is Required to Become a Perfect Automation Tester?
Do you believe that Perfect Automation Tester exist?
According to the definition of word Perfect
Perfect : having all the required or desirable elements, qualities.
This is not possible, right?
No, one going to have all the required qualities of Automation,
But still, 
Let's understand what makes an Automation Tester good and How You can too leverage these skills and traits which can make you a great automation tester.

{% embed https://youtu.be/rFeIqCGRn7s %}

Traits of Perfect Automation Tester.
Mindset.
To become a Perfect Automation Tester, You have to think and act like that you already are a Perfect Automation Tester.
- You can start automating your daily manual small task with scripts.
- You should have a clear understanding of what can be automated or what can't.
- You will start checking the ROI of the automation task. 
Technical Knowledge.
Command Over Automation
Decent Knowledge about the Trending Tools
Expert in Manual Testing.
In this video, I have given 5 step process to Become a Better Automation Engineer.


Join Facebook Group :  http://bit.ly/learntesting2019

Website:   https://scrolltest.com

Website:   https://thetestingacademy.com

Twitter: https://twitter.com/itstechmode


#automationtesting #manualtesting #testautomation #thetestingacademy #scrolltest

🚀 Tools and services I recommend:
Some of the courses that I recommend to become better Automation Tester 🙌🙌

✅Selenium Training and Certification -
https://scrolltest.com/go/edureka


✅Learn Jenkins for QA -
https://bit.ly/learnjenkins-p1


✅Programming Java -
https://bit.ly/learnjava2020-p1


✅Test Automation - 
https://bit.ly/learnautomation2020


✅API Testing - 
https://www.learnapitesting.com


✅Cypress Tutorial with LIVE Projects -
http://cypresstutorial.com
Host a static website on AWS
Tags: staticwebapps, devops, cloud, serverless
Published: 2023-01-14 04:39:19


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ku8dgx7o4k3gzmao5fdt.png)
To host a static website on Amazon S3 and use a custom domain with Amazon Route 53, you can follow these steps:
Sign up for an AWS account if you don't already have one:

Go to the AWS homepage and click the "Create a new AWS account" button.
Follow the on-screen instructions to create your account.

2. Create a new S3 bucket:
Sign in to the AWS Management Console and open the Amazon S3 console.
Click the "Create bucket" button.
Give your bucket a unique name, select a region, and click "Create."

3. Upload your website's files to the bucket:
Select the bucket you just created, and click the "Upload" button.
Drag and drop your website's files into the upload window, or use the "Add files" button to select them manually.
Click "Next" to continue.
On the next screen, you can set permissions and other options for your uploaded files. When you're ready, click "Next" again.
Review your settings and click "Upload" to start the upload process.

4. Make the bucket accessible as a website:
In the Amazon S3 console, select the bucket you just created.
Click the "Properties" button, and then click the "Static website hosting" option.
Select the "Use this bucket to host a website" option and enter the "Index document" and "Error document" for your website. The index document is usually called "index.html" or "index.php."
Click "Save" to apply the changes.

5. Set up a custom domain with Amazon Route 53:
In the AWS Management Console, navigate to the Amazon Route 53 console.
Click the "Create Hosted Zone" button.
Enter your domain name and click "Create."
Route 53 will create a hosted zone for your domain and display a list of name servers.
Go to your domain registrar's website and update the name servers for your domain to the ones provided by Route 53. This will allow Route 53 to manage the DNS for your domain.
In the Route 53 console, click the "Create Record Set" button.
In the "Name" field, enter the subdomain you want to use for your website (e.g., www).
For the "Type," select "A - IPv4 address."
For the "Value," enter the endpoint URL for your S3 website, which you can find in the S3 console under "Properties" > "Static website hosting."
Click "Create" to create the record set.

6. Test your website:
In the Amazon S3 console, click the "Properties" button and then click the "Static website hosting" option.
Copy the "Endpoint" URL shown in the Static website hosting panel and paste it into a web browser. Your website should now be accessible at this URL.
If you set up a custom domain, you can use that instead of the endpoint URL to access your website.

That's it! Your static website should now be live and accessible at your custom domain. If you run into any issues or have any questions, feel free to ask.
Recursive Fetching In Javascript
Tags: beginners, javascript
Published: 2023-01-14 04:28:19

For my latest project, I am working on finding degrees of separation between a given player, and the top ranked group, known as "Challenger"(which consists of the top 200) in the game League of Legends. All of this is made possible by the [RiotAPI](https://developer.riotgames.com/).

The process I had in mind was to look up other players from the 10 most recent games, find the highest ranked player, and repeat the process with said player if they are not a "Challenger" rank. The basic structure of the process would be:

```
function findChallenger(playerID){
    //lookup recent games with playerID
    //lookup players from those games
    //find the rank information on those players
    //sort the players by rank
    if (highestRankedPlayer.tier!== "CHALLENGER"){
        findChallenger(highestRankedPlayer.id)
    }
}
```
In order to implement this with data from the API, fetch requests need to be made. Not only that, but the data for each fetch is reliant on the data from the previous fetch. In order for this to work we need to made the 2nd fetch after the promise of the first is resolved, like so:
(using "data1.url" as an example of how the data of the first fetch is necessary towards making the 2nd)
```
fetch(url1)
.then(response1=>response1.json())
.then(data1=>{
    fetch(data1.url)
    .then(response2=>response2.json()
    .then(data2=>/*process data2*/)
    }
)
```
In this manner I "nested" fetch requests in order to reach all the API endpoints necessary for the functionality of my project on github [here](https://github.com/AlexMcD-git/lol-degrees-of-separation), and the specifics of making these calls are available on [this](https://github.com/AlexMcD-git/lol-degrees-of-separation/blob/main/client/src/components/SummonerForm.js) particular file. The particular point of recursion is where, within "findChallenger(){}" (after the best player from your 10 most recent games is found)
```
if (bestPlayer.tier ==="CHALLENGER"){
    return
}
else{
    summonerLookup(bestPlayer.summonerName)
}
```

I would recommend anyone looking to try out an API requiring authentication give the RiotAPI a go (being familiar with League of Legends, Valorant, or Legends of Runeterra is also helpful) due to the generous rate limits, intuitive end points, and ease of applying for an increase.
Contêiner React usando Docker
Tags: docker, react
Published: 2023-01-14 04:23:59

Estou iniciando meus estudos em react e a primeira coisa que  fiz foi configurar o ambiente de desenvolvimento. 

Mas configurar o ambiente de desenvolvimento às vezes é uma tarefa cansativa. Quem nunca teve problemas com versões incompatíveis? Muita coisa que pode dar errado.

Por isso optei por utilizar o [docker](https://www.docker.com/). Antes de mais nada você precisa ter 3 coisas instaladas para finalizar esse tutorial com sucesso:

- Docker [ Clique aqui para mais detalhes](https://docs.docker.com/engine/install/)

- Editor de código

- Terminal

Crie um diretório com o nome de sua preferencia, como estou fazendo um curso na [Alura](https://www.alura.com.br/) vou criar com o nome do projeto que estou desenvolvendo. No caso, o diretório será: /home/sistemas/alura-books.

Entre no diretório criado pelo terminal e execute o seguinte comando:

```
docker run --rm --volume "/home/sistemas/alura-books:/srv/alura-books" --workdir "/srv/alura-books" --publish 3000:3000 -it node:18.12.1 bash

```
Segue uma breve explicação sobre os parâmetros deste comando:

- --volume "/home/sistemas/alura-books:/srv/alura-books": Cria um link entre a pasta do computador hospedeiro (/home/sistemas/alura-books) com a pasta do contêiner (/srv/alura-books).

- --workdir "/srv/alura-books": Diretório inicial quando o container for iniciado.

- --publish 3000:3000: Cria um link entre a porta 3000 do contêiner com a porta 3000 do computador hospedeiro.

- -it: Cria um link entre o terminal do contêiner com o terminal do computador hospedeiro.

- -rm: Remove antigos contêineres (muito útil depois da primeira execução).

Pronto agora você tem um contêiner temporário e pode executar comandos como o `npx create-react-app .` 

Na primeira vez que você executar o docker run, o docker precisara baixar a imagem do [node:18.12.1](https://hub.docker.com/_/node). 

Fique atento ao Owner da pasta /home/sistemas/alura-books no computador hospedeiro. No meu caso eu precisei alterar o Owner da pasta e seus arquivos, uma vez que eles foram criados por dentro do contêiner.

Quem estiver usando Linux é só executar este comando no computador hospedeiro:

```
sudo chown -R <USERNAME> /home/sistemas/alura-books
```

Muito obrigado pela sua atenção. Espero ter ajudado um pouco de alguma forma.