teleren/devto huggingface dataset:
Criando Crons no Nestjs
Tags: javascript, beginners, todayilearned
Published: 2022-06-02 19:59:15

Crons são jobs programados para automaticamente rodar em determinado intervalo de tempo ou em uma data especificada. 

Para criar as crons utilizei como base a documentação do [nestjs](https://docs.nestjs.com/techniques/task-scheduling)

comecei instalando os pacotes recomendados

```bash
$ npm install --save @nestjs/schedule
$ npm install --save-dev @types/cron
```

E no modulo principal do app adicionei o ScheduleModule importado de dentro do `@nestjs/schedule` 

```bash
@Module({
  imports: [
    ScheduleModule.forRoot()
  ],
})
```

o `forRoot` serve para inicializar o scheduler e registrar os jobs da cron, setar timeouts e intervalos.

para definir a função que vai ser rodada com a cron basta usar o decorator `@Cron` e passar como parâmetro quanto tempo é o intervalo da cron, o intervalo pode ser definido utilizando alguns padrões mas nessa caso usei o de asteriscos

```
* * * * * *
| | | | | |
| | | | | dia da semana
| | | | mês
| | | dia do mes
| | horas
| minutos
segundos
```

onde por exemplo:
`45 * * * * *` no segundo 45 de cada minuto
`0 30 11 * * 1-5` significa de segunda a sexta as 11:30

porem o modulo do nestjs também prove um enum onde tem as patterns de crons mais comuns `CronExpression.EVERY_30_SECONDS` ou também pode passar um objeto de Date para o decorator mas fazendo assim a cron vai ser executada somente uma vez na data especificada. Como um teste inicial declarei a seguinte Cron

```js
  @Cron(CronExpression.EVERY_10_SECONDS, { name: 'Console.log cron' })
  register() {
    console.log(`cron executada em ${new Date()}`);
  }
```
Ela foi executada assim que o serviço iniciou e então de 10 em 10 segundos a partir dai.

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

Com isso podemos fazer qualquer tipo de job recorrente por exemplo enviar e-mails para clientes de forma semanal ou enviar notificações ou gerar um relatório por exemplo ou até mesmo para [automatizar o readme do github](https://dev.to/yanpiing/automatizando-o-readme-do-github-5cpj)
onde definimos uma cron que roda através do github actions para buscar meu blogposts mais recentes e colocar no meu readme
How to send Forgot Password Email in Laravel 9?
Tags: laravel, webdev, programming, tutorial
Published: 2022-06-02 19:42:27

## Send Forgot Password EMAIL to reset password.
We have already covered [Laravel installation](https://dev.to/shanisingh03/how-to-install-laravel-9-25c4) and [Laravel Auth Scaffolding](https://dev.to/shanisingh03/how-to-make-login-registration-in-laravel-9-1p2n).

Next We will cover forgot password flow using [Laravel/UI](https://github.com/laravel/ui).

## Step 1
Gather SMTP Details, you can use any SMTP but for this tutorial i am going to use [MailTrap](https://mailtrap.io/), this is a email testing tool you can use while developing any SMTP feature.

The Detail we require are
```php
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=#############
MAIL_PASSWORD=############
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="test@test.com"
MAIL_FROM_NAME="${APP_NAME}"
```

We have to update these details in `.env` file.

## Step 2
Now go to password reset route `/password/reset` you will see the reset password page.

![Reset Password](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gua0ktv9du68zh1behem.png)

Now enter the registered email address and click on Send Password Link.


![Email Link Sent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auy6l3j5srd6uts6n9lz.png)

You should get an email in MAILTRAP Inbox.

![Reset Email Look Like](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwd9imgzb4nrw10e5ahp.png)

Once you click on Reset Password Button from Email you will land to Change password screen.

![Reset Password Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmkek9k8bd9meuy213kc.png)

After you enter new password you will redirect to homepage.


![Reset Password Success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxf7ab149vgdxhnfgbuo.png)

The Complete Video Tutorial is below in the video.

{% youtube Y54cfciVQaM %}

If you face any issue while implementing, please comment your query.

Thank You for Reading

Reach Out To me.
[Twitter](https://twitter.com/techtoolindia)
[Instagram](https://www.instagram.com/techtoolindia/)
[YouTube](https://www.youtube.com/c/TechToolIndia)
Laravel 9 Forgot Password Email
Tags: laravel, beginners, programming, tutorial
Published: 2022-06-02 19:36:10

## Send Forgot Password EMAIL to reset password.
We have already covered [Laravel installation](https://dev.to/shanisingh03/how-to-install-laravel-9-25c4) and [Laravel Auth Scaffolding](https://dev.to/shanisingh03/how-to-make-login-registration-in-laravel-9-1p2n).

Next We will cover forgot password flow using [Laravel/UI](https://github.com/laravel/ui).

## Step 1
Gather SMTP Details, you can use any SMTP but for this tutorial i am going to use [MailTrap](https://mailtrap.io/), this is a email testing tool you can use while developing any SMTP feature.

The Detail we require are
```php
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=#############
MAIL_PASSWORD=############
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="test@test.com"
MAIL_FROM_NAME="${APP_NAME}"
```

We have to update these details in `.env` file.

## Step 2
Now go to password reset route `/password/reset` you will see the reset password page.

![Reset Password](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gua0ktv9du68zh1behem.png)

Now enter the registered email address and click on Send Password Link.


![Email Link Sent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auy6l3j5srd6uts6n9lz.png)

You should get an email in MAILTRAP Inbox.

![Reset Email Look Like](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwd9imgzb4nrw10e5ahp.png)

Once you click on Reset Password Button from Email you will land to Change password screen.

![Reset Password Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmkek9k8bd9meuy213kc.png)

After you enter new password you will redirect to homepage.


![Reset Password Success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxf7ab149vgdxhnfgbuo.png)

The Complete Video Tutorial is below in the video.

{% youtube Y54cfciVQaM %}

If you face any issue while implementing, please comment your query.

Thank You for Reading

Reach Out To me.
[Twitter](https://twitter.com/shanisingh03)
[Instagram](https://www.instagram.com/shanisingh03/)
[YouTube](https://www.youtube.com/c/TechToolIndia)
Broken Calculator
Tags: leetcode, dsa, theabbie
Published: 2022-06-02 19:30:41

There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:

*   multiply the number on display by `2`, or
*   subtract `1` from the number on display.

Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.

**Example 1:**

**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.

**Example 2:**

**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.

**Example 3:**

**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.

**Constraints:**

*   `1 <= startValue, target <= 109`

**SOLUTION:**

    class Solution:
        def brokenCalc(self, startValue: int, target: int) -> int:
            if startValue >= target:
                return startValue - target
            if target % 2 == 0:
                return 1 + self.brokenCalc(startValue, target // 2)
            else:
                return 2 + self.brokenCalc(startValue, (target + 1) // 2)
install wsl on different drive
Tags: wsl, tutorial
Published: 2022-06-02 19:23:33

I followed the instruction on this website:  ` https://vpraharsha3.medium.com/installing-wsl-distro-to-a-different-custom-location-30d101f04113 `
The only trouble I got into is I cannot find the *.exe (ubuntu.exe in my case) file and neither the install.tar.gz file after I unzip the ubuntu2004. I was able to find these files in [ubuntu1804](https://aka.ms/wsl-ubuntu-1804) system and that is current work around.
Quart-Nextcord
Tags: nextcord, discord, python, webdev
Published: 2022-06-02 19:21:47

# Quart-Nextcord - Discord OAuth2 extension for Quart using nextcord.

Quart-Nextcord is an extension for [nextcord](https://pypi.org/project/nextcord).


## Related links
- [Quart-Nextcord PyPi](https://pypi.org/project/Quart-Nextcord)
- [Quart-Nextcord GitHub Repository](https://github.com/InvalidLenni/Quart-Nextcord)
- [Quart-Nextcord Documentation](https://quart-nextcord.rtfd.io)

## Example
 ```python 
 from quart import Quart, redirect, url_for 
 from quart_nextcord import DiscordOAuth2Session, requires_authorization, Unauthorized 
  
 app = Quart(__name__) 
  
 app.secret_key = b"random bytes representing quart secret key" 
  
 app.config["DISCORD_CLIENT_ID"] = 490732332240863233  # Discord client ID. 
 app.config["DISCORD_CLIENT_SECRET"] = ""  # Discord client secret. 
 app.config["DISCORD_REDIRECT_URI"] = ""  # URL to your callback endpoint. 
 app.config["DISCORD_BOT_TOKEN"] = ""  # Required to access BOT resources. 
  
 nextcord = DiscordOAuth2Session(app) 
  
  
 @app.route("/login/") 
 async def login(): 
     return await nextcord.create_session() 
  
  
 @app.route("/callback/") 
 async def callback(): 
     await nextcord.callback() 
     return redirect(url_for(".me")) 
  
  
 @app.errorhandler(Unauthorized) 
 async def redirect_unauthorized(e): 
     return redirect(url_for("login")) 
  
  
 @app.route("/me/") 
 @requires_authorization 
 async def me(): 
     user = await nextcord.fetch_user() 
     return f""" 
     <html> 
         <head> 
             <title>{user.name}</title> 
         </head> 
         <body> 
             <img src='{user.avatar_url}' /> 
         </body> 
     </html>""" 
  
  
 if __name__ == "__main__": 
     app.run() 
 ```


# Ideas?
Go to https://github.com/InvalidLenni/Quart-Nextcord/discussions

# You found issues?
Go to https://github.com/InvalidLenni/Quart-Nextcord/issues/new


# Contribution
You can make contributions too for helping us! 😃
how can i improve the popularity of my site?
Tags: discuss, help, javascript, showdev
Published: 2022-06-02 19:05:43

About 8 months ago I published https://devportfolios.net/ a platform where only developers can upload their portfolio for free. No web agencies, designers sites etc... are accepted.

The problem is that only few developers have submitted their website and only few people a day are visiting the website.
What can I do to improve the popularity? 
Has someone some suggestions?
Design HashMap
Tags: leetcode, dsa, theabbie
Published: 2022-06-02 19:00:45

Design a HashMap without using any built-in hash table libraries.

Implement the `MyHashMap` class:

*   `MyHashMap()` initializes the object with an empty map.
*   `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
*   `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`.
*   `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`.

**Example 1:**

**Input**
\["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"\]
\[\[\], \[1, 1\], \[2, 2\], \[1\], \[3\], \[2, 1\], \[2\], \[2\], \[2\]\]
**Output**
\[null, null, null, 1, -1, null, 1, null, -1\]

**Explanation**
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now \[\[1,1\]\]
myHashMap.put(2, 2); // The map is now \[\[1,1\], \[2,2\]\]
myHashMap.get(1);    // return 1, The map is now \[\[1,1\], \[2,2\]\]
myHashMap.get(3);    // return -1 (i.e., not found), The map is now \[\[1,1\], \[2,2\]\]
myHashMap.put(2, 1); // The map is now \[\[1,1\], \[2,1\]\] (i.e., update the existing value)
myHashMap.get(2);    // return 1, The map is now \[\[1,1\], \[2,1\]\]
myHashMap.remove(2); // remove the mapping for 2, The map is now \[\[1,1\]\]
myHashMap.get(2);    // return -1 (i.e., not found), The map is now \[\[1,1\]\]

**Constraints:**

*   `0 <= key, value <= 106`
*   At most `104` calls will be made to `put`, `get`, and `remove`.

**SOLUTION:**

    class MyHashMap:
    
        def __init__(self):
            self.size = 107
            self.arr = [[] for i in range(self.size)]
            
        def hfn(self, key):
            key = ((key >> 16) ^ key) * 0x45d9f3b
            key = ((key >> 16) ^ key) * 0x45d9f3b
            key = (key >> 16) ^ key
            return key % self.size
    
        def put(self, key: int, value: int) -> None:
            self.remove(key)
            self.arr[self.hfn(key)].append((key, value))
    
        def get(self, key: int) -> int:
            curr = self.arr[self.hfn(key)]
            val = -1
            for k, v in curr:
                if k == key:
                    val = v
                    break
            return val
    
        def remove(self, key: int) -> None:
            k = len(self.arr[self.hfn(key)])
            for i in range(k):
                if self.arr[self.hfn(key)][i][0] == key:
                    self.arr[self.hfn(key)][i] = self.arr[self.hfn(key)][-1]
                    self.arr[self.hfn(key)].pop()
                    break
    
    
    # Your MyHashMap object will be instantiated and called as such:
    # obj = MyHashMap()
    # obj.put(key,value)
    # param_2 = obj.get(key)
    # obj.remove(key)
We are hiring!
Tags: hiring, startup, programming, career
Published: 2022-06-02 18:31:00


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

Get a remote job that you will love with better compensation and career growth.

We’re Lemon.io — a marketplace where we match you with hand-picked startups from the US and Europe. 

**Why work with us:**

- We’ll find you a team that respects you. No time-trackers or any micromanagement stuff
- Our engineers earn $5k - $9k / month. We’ve already paid out over $10M.
- Choose your schedule. We have both full- and part-time projects.
- No project managers in the middle — only direct communications with clients, most of whom have a technical background
- Our customer success team provides life support to help you resolve anything.
- You don’t have to look for clients and or negotiate anymore: just do what you do best and leave us the rest.

**We’re constantly on the hunt for senior devs with 3+ years of experience who work with the following stacks:**

- Node.js 
- React 
- React+Node.js Senior 
- Backend + Typescript 
- Any JS framework + Typescript
- React/Angular/Vue+Python, or Python only 
- React Native
- React+Ruby, or Ruby 
- Flutter

But even if you didn’t find your stack in the list, apply anyway. We receive absolutely different requests every day, so who knows — maybe tomorrow your stack will be in the highest demand! 

**Examples of recent projects:**

- An app that gives independent workers access to financial products that optimize their income, provides cash advances for rainy days, and tax management.
- An app that easily turns podcasts sound files into plain texts. 
- A technology to make every web app fast and easy to learn via a cmd+k interface 

**What engineers value about Lemon.io:**

- “The company provides full flexibility. You are able to choose any project based on your skills, time, and location. They do not have any bureaucracy and it is easy to start working with them.”
- “The interview process was extensive but fast. Within a day, I was connected with a client for the second interview, and the next day, I started working.”
- “Worked on a pretty interesting project with all the modern technologies I wanted to catch up on.”

You can find the rest of them here:

- [Glassdoor](https://www.glassdoor.com/Reviews/Lemon-io-Reviews-E4522943.htm)
- [Dou](https://jobs.dou.ua/companies/lemon-io/reviews/)

[Apply](https://lemon.io/escape-the-matrix/?utm_source=devto&utm_medium=job_ad&utm_campaign=supply_en_community_jun_2022_job_ad)today, and our team will get back to you within 48 hours!
Minimum Sum of Four Digit Number After Splitting Digits
Tags: leetcode, dsa, theabbie
Published: 2022-06-02 18:30:40

You are given a **positive** integer `num` consisting of exactly four digits. Split `num` into two new integers `new1` and `new2` by using the **digits** found in `num`. **Leading zeros** are allowed in `new1` and `new2`, and **all** the digits found in `num` must be used.

*   For example, given `num = 2932`, you have the following digits: two `2`'s, one `9` and one `3`. Some of the possible pairs `[new1, new2]` are `[22, 93]`, `[23, 92]`, `[223, 9]` and `[2, 329]`.

Return _the **minimum** possible sum of_ `new1` _and_ `new2`.

**Example 1:**

**Input:** num = 2932
**Output:** 52
**Explanation:** Some possible pairs \[new1, new2\] are \[29, 23\], \[223, 9\], etc.
The minimum sum can be obtained by the pair \[29, 23\]: 29 + 23 = 52.

**Example 2:**

**Input:** num = 4009
**Output:** 13
**Explanation:** Some possible pairs \[new1, new2\] are \[0, 49\], \[490, 0\], etc. 
The minimum sum can be obtained by the pair \[4, 9\]: 4 + 9 = 13.

**Constraints:**

*   `1000 <= num <= 9999`

**SOLUTION:**

    class Solution:
        def minimumSum(self, num: int) -> int:
            digits = sorted([int(d) for d in str(num)])
            return 10 * (digits[0] + digits[1]) + (digits[2] + digits[3])
Early Returns/Exits - Code Patterns in JavaScript
Tags: javascript, webdev, tutorial
Published: 2022-06-02 17:46:15

Code Patterns in JavaScript
{% embed https://www.youtube.com/embed/MTj2edmBJsI %}
_See this and many other articles at [lucaspaganini.com](lucaspaganini.com)_

Suppose you have a function that should only run if a given condition is true.

You could wrap your implementation in an if statement.

```ts
const onSubmit = (form) => {
  if (form.valid) {
    // Do something here
  }
};
```

But a clearer approach is to use an early return if the condition is false.

```ts
const onSubmit = (form) => {
  if (form.valid === false) {
    return;
  }

  // Do something here
};
```

See, instead of running if the condition is true, you can invert the logic and refuse to run if the condition is false.

Those if statements are called guards because they prevent your code to run. And you can have as many guards as you want.

```ts
const onSubmit = (form) => {
  if (form.valid === false) {
    return;
  }

  const userData = form.value;
  if (isValidUser(userData) === false) {
    return;
  }

  if (emailIsTaken(userData.email)) {
    return;
  }

  // Do something here
};
```

That avoids unnecessary layers of nesting and makes it very clear to anyone reading your code what are the requirements for it to run.

## Early Exits

This pattern is called “early returns”, but I don’t really like that naming because it seems to only apply to `return` statements and that’s not what this is about.

A better name for it is “early exits”, after all, you can exit your code in other ways.

For example, if you’re not expecting those conditions to be `false`, you can `throw` instead of returning.

```ts
const onSubmit = (form) => {
  if (form.valid === false) {
    throw Error('Form is invalid');
  }

  const userData = form.value;
  if (isValidUser(userData) === false) {
    throw Error('Invalid user data');
  }

  if (emailIsTaken(userData.email)) {
    throw Error('Email is already taken');
  }

  // Do something here
};
```

## Conclusion

References are in the references.

<p>If you enjoyed the content, you know what to do. We have many other short and informative articles on our site. <app-newsletter-modal-trigger>Subscribe</app-newsletter-modal-trigger> if you’re interested in that.</p>

Have a great day and see you soon.

## References

1. [Replace Nested Conditional with Guard Clauses by Martin Fowler](https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html)
2. [Refactoring - Improving the Design of Existing Code by Martin Fowler, with Kent Beck](https://martinfowler.com/books/refactoring.html)
DATA SCIENCE
Tags: beginners, career, machinelearning, datascience
Published: 2022-06-02 18:18:38

**Topics**

- Data science
- Data Engineering
- Data Analytics

## Data science
Data science is the systematic study of the structure and behavior of data to quantifiably understand past and current occurrences and predict the future behavior of that data.

### Data Scientist Typical Traits

- Degree in a quantitative field
- Programmers
- Curious and tenacious personalities
- Previous experience: BI reporting, data analysis, and data-driven decision-making
- Interested in why over how: They are looking for the patterns and the correlations and the trends that, basically, indicate why something is happening, not how it's happening. They are looking to make predictions.
- Spends hours analyzing complex questions
- Data scientists derive insights from data, including big data (data from engineered systems). Big data just means data of many different structures, many different velocities, and many different varieties.
- Uncover correlations and accusations in business data to support business decision-making
- These people generate predictions from data and communicate predictions through data visualization

### Data Scientist Typical Competencies
- STEM degree, with advanced math
- Coding: Python, R, SQL, Spark, machine learning

## Data Engineering
Data engineering is the design, construction, and maintenance of data systems.

### Data Engineer Typical Tasks
- Data engineers design systems to collect, handle, and store big datasets
- Data engineers build modular, scalable platforms for data processing
- These people design, build, and maintain systems that store and move big data

### Data Engineer Typical Compentencies
- Computer science, Software engineering
- Coding: Java, C++, Python

## Data Analytics
Data analytics are data products that describe data and how it behaves. These data products are generated from data analysis and visualization processes.

### Analytics Specialist Typical Traits
- Use applications to analyze data
- Solid in basic math
- Understand the inner workings of a business very well
- Enjoys using data insights to improve business
- Not into deep analyses

### Analytics Specialist Typical Tasks
- Generates predictive, prescriptive, and descriptive data insights.
- Uncover correlations and accusations in business data to support business decision-making.
- Deploys analytics technologies: analytics software applications.
Automatically Detect Security Bugs in your App/API
Published: 2022-06-02 18:15:17

There are no good options for security testing applications/APIs. Most options are commercial and require complex setup and configurations.

We decided to build a free and open tool for instant App/API security testing. No sign-up is required. No complicated setup is needed either.

Point towards your API and get an instant report. The report helps your detect and fix security vulnerabilities in your APIs. These vulnerabilities could have led to data breaches and punitive damages.

Here is the tool link:
https://apisec-inc.github.io/pentest/