teleren/devto huggingface dataset:
Music Monday — What are you listening to? (Tunes from Your Teenage Days Edition)
Tags: watercooler, discuss, music
Published: 2023-03-06 15:03:40

_cover image source: [The White Stripes](https://giphy.com/gifs/thewhitestripes-jack-white-the-stripes-seven-nation-army-yy5i1YOzAzzD2ph0QL)_

**Alright, alright! We're back with another Music Monday and this time the focus is "tunes from your teenage days" — props to @fdocr for the excellent suggestion. 🙌 So, let's bust out those jams from our highschool days... tastes change, so if you're embarrassed by what you used to listen to, it's all good! And if you're feeling self-conscious about revealing your age, please don't be. This thread is a judgement free zone — y'all help me to keep it that way!**


![Andre 3000 playing guitar and smiling from the music video for "Hey ya"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7aeaszo7zcy148141x1t.gif)

***

## How we do 

In this weekly series, folks can chime in and drop links to whatever it is they've been listening to recently + browse others suggestions.

If you like talking about music, consider following the org [#music discussions](https://dev.to/music-discussions) for more conversations about music!

{% embed https://dev.to/music-discussions %}

***

Alright, lemme hear those tunes from your teenage years! _Note: you can embed a link to your song using the following syntax `{% embed https://... %}`. This should work for most common platforms!_

Really looking forward to listening to y'all's suggestions! 🎶
Enviando SMS utilizando Python e Twilio
Published: 2023-03-06 14:54:48

Olá pessoal tudo bem?, neste pequeno post irei mostrar para vocês como podemos automatizar o envio de SMS utilizando o Twilio !!

Site para acesso ao [Twilio ](https://www.twilio.com/pt-br/)

Então vamos lá, primeiro passo devemos criar nossa conta junto a plataforma Twilio .

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


Após criar nossa conta e escolhermos os serviços desejados tal como, utilizar aplicações para bot e envio de SMS com python.

Vamos fazer a seguinte estruturação:

- Acessar a plataforma da Twilio e buscar nossas credenciais chaves de API

- Ao acessarmos a conta seremos direcionados para o painel principal, ao qual devemos buscar nossa Account SID e também nossa 
Auth Token (como mencionamos outras vezes, tokens, podem ser estilo Bearer, e afins).

E buscar também nosso Twilio Phone, para podermos disparar as mensagens.

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


Feito isto, vamos abrir nosso VSCODE, e vamos criar dois arquivos chamados : 

- Keys.py e Main.py

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


- No arquivo Key.py vamos estruturar todas as nossas chamadas e também onde iremos adicionar nossa Account SID e também o AuthToken


vamos começar da seguinte forma:

```
account_sid = 'Insira aqui sua Account SID'
auth_token = 'Insira aqui sua Seu Token'

twilio_number = 'Insira aqui o registro do seu número twilio'
target_number = 'Insira aqui o número ao qual deseja enviar a SMS'

```

Ficando então da seguinte forma: 

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

Agora vamos ao conteúdo MAIN.PY

Vamos primeiro efetuar a instalação da lib twilio

```
pip install twilio
```

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

- Feito isto, vamos agora montar nossa estrutura:

```
from twilio.rest import Client

import keys


client = Client(keys.account_sid, keys.auth_token)
message = client.messages.create(
    
    body="Insira aqui o que deseja que seja enviado ao destinatário",
    from_=keys.twilio_number,
    to=keys.target_number
    
    
    
)

print(message.body)
```

Feito isto agora iremos enviar nossa SMS 

Ao executar, caso tenha feito corretamente verá da seguinte forma:


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


E em seu celular chegará desta forma:


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

E ao acessarmos o Twilio novamente podemos verificar todas as mensagens enviadas:

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


Obrigado, por lerem e acompanharem este passo a passo.
Active Record Validations - Ruby on Rails
Published: 2023-03-06 14:45:10

Validations are used to make sure that only valid data is saved to the database and Ruby on Rails provides us with a [helpful guide](https://guides.rubyonrails.org/active_record_validations.html). There a two types of validations, standard validations that rails gives us and also custom validations. Rails provides a number of commonly used validations. I will be covering how to implement both standard active record validations and custom validations.  

Rails provide a us with a number of validation helpers that are commonly used. For example, in this method we have below, it checks if the instance we are trying to create has all of the attributes that we need. We want to make sure that it validates the presence of the name, and the numericality of the capacity:

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

There are a vast variety of different validations that could be implemented. You can also add a message that will come up if the validations are done incorrectly. Active record validations are really simple and easy to use with the help of the Ruby on Rails guide.

Custom Validations
To validate something that cannot be validated using by the Rails docs, you would have to use a custom validation method.
When you want to implement custom validations, you will use validate instead of validates (which is very important to remember) and add the method name that you will declare below it. Say, for example, you want to validate a users email we would create a custom validation.

To start, create a new folder in your app folder, app\validators. Inside of the new folder, create a new file, the name should describe what this specific code is supposed to do. Next, inside of the new file write a class that inherits from ActiveModel::EachValidator. Then, You will use the validators in the user model. It would look something like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eorrhxe7sunm1xwg4kgk.png)

Now we can start to write out our method in ActiveModel::EachValidator. We will use the value parameter to check the email:

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


Now this is what the final code should look like in the end.

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

Both the standard active record validations and the custom validations are quite simple to use.
Great Analogy To Explain ID Tokens Vs Access Tokens
Tags: security, node, programming, identity
Published: 2023-03-06 14:34:33

## Analogy For ID Token

Imagine you're planning to attend a fancy party at a private club. Before you can enter the club, you need to show the bouncer your ID to prove that you're on the guest list. In this analogy, the **bouncer** represents the **server** that's responsible for controlling access to the club, and your **ID** represents your **ID token**.

## What Is ID Token
An ID token is a type of token that's used in authentication protocols like OAuth 2.0 and OpenID Connect. It's a JSON Web Token (JWT) that contains information about the authenticated user, such as their user ID and email address. When a user logs in to an application using a third-party identity provider (like Google or Facebook), the identity provider sends an ID token to the application server to verify the user's identity. The application server can then use the information in the ID token to create a user account or grant access to certain resources.

## Analogy For Access Token
Now let's say you're inside the club and you want to order a drink from the bar. You need to show the bartender your membership card to prove that you're allowed to order drinks. In this analogy, the bartender represents the server that's responsible for controlling access to the club's resources (like drinks), and your membership card represents your access token.

## What is Access Token
An access token is a type of token that's used in authorization protocols like OAuth 2.0. It's a string of characters that represents a user's permission to access certain resources. When a user logs in to an application using a third-party identity provider, the application can request an access token that allows the user to access certain resources (like their Google Drive files). The application can then include the access token in API requests to prove that the user has permission to access those resources.

So, to summarize:

1. ID tokens are like IDs that prove your identity and allow you to enter the party (authenticate).
2. Access tokens are like membership cards that grant you permission to access certain resources (authorize).

Don't forget to leave a comment if you found this interesting. 😎
useCallback vs useMemo
Tags: webdev, javascript, beginners, react
Published: 2023-03-06 14:33:12


**useCallback** and **useMemo** are both React hooks that can be used to optimize the performance of your React application by remembering calculated values ​​in components but there is a slight difference in terms of Return Value, Dependency array. Below is good comparison of both.


1. **Use case**: The main use case of useCallback is to remember a function, while the main use case of useMemo is to remember a value.

2. **Return value**: useCallback returns a memorized function, while useMemo returns a memorized value.

3. **Dependencies Array**: 

- useCallback takes a dependency array as the second argument, which specifies the values ​​on which the stored function depends. The function will only be recalculated if any value in the dependencies array changes. On the other hand, 

- useMemo also takes an array of dependencies as the second argument, but it specifies the values ​​on which the remembered value depends. The value will only be recalculated if any value in the dependencies array changes.




**Performance Considerations**: If you have a computationally expensive function that you need to pass as a prop to a child component, you should use useCallback to remember that function. This will prevent the child component from rendering unnecessarily. If you have a computationally expensive value that you need to use in a component, you should use useMemo to remember that value. This will prevent the value from being unnecessarily recalculated on every new render.



![useCallback vs useMemo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hecgus433x4fp1z88n8j.png)

In this example, we use both useMemo and useCallback to remember a value and a function respectively. Expensive value is remembered by useMemo and expensive function is remembered by useCallback. Both hooks depend on the value of the count state and will only recalculate if the count value changes. This can help optimize component performance.
Resolvendo problemas no HackerRank: Escolhendo números.
Tags: javascript, beginners, programming
Published: 2023-03-06 14:22:58

Olá, seja bem vindo a mais uma etapa do Resolvendo problemas no Hacker-Rank,nessa sessão iremos resolver uma série de arrays. Nosso objetivo é retornar um input onde dentro de um parâmetro retornará diversos outros arrays menores e a subtração entre eles seja maior que 1.

**Picking Numbers -**

As regras para esse problema são as seguintes:

- A primeira linha contém um único inteiro `n`, o tamanho do array `a`.

- A segunda linha contém números inteiros separados por espaços, cada um com a[i] .

Vejamos um exemplo:

```
6
4 6 5 3 3 1

input: 3
```
Foi escolhido o array pegando [4,3,3], a subtração de pares: 4-3 e 3-3 dão respectivamente 1 e 0. Então imprimimos o valor escolhido.

Vejamos como resolver esse caso:

```
function pickingNumbers(a) {
    // Write your code here
  a.sort((a, b) => a - b);
    let counter = 0;
    let tmpCounter = 0;
    let maxSubSum = 0;
    for (let i = 0; i < a.length; i++) {
        if (a[i] != a[i - 1]) {
            if (a[i] == a[i - 1] + 1) {
                tmpCounter = counter;
                counter = 0;
            }
            else{
                tmpCounter = 0;
                counter = 0;
            }
        }
        counter++;
        if (tmpCounter + counter > maxSubSum) {
            maxSubSum = tmpCounter + counter
        }
    }
    return maxSubSum;
}
```

Este código implementa a função "pickingNumbers", que recebe um array "a" de inteiros e retorna a maior quantidade de elementos do array que podem ser selecionados, de modo que a diferença absoluta entre quaisquer dois elementos selecionados seja no máximo 1.

O código começa ordenando o array "a" em ordem crescente usando a função de ordenação "sort". Em seguida, são definidas três variáveis: "counter", "tmpCounter" e "maxSubSum".

O loop for percorre o array "a" e conta quantas vezes cada número aparece consecutivamente no array (ou seja, quantos números consecutivos têm uma diferença absoluta de no máximo 1). Se um novo número é encontrado, a variável "counter" é reiniciada e a variável "tmpCounter" é atualizada com o valor anterior de "counter" se o novo número é consecutivo ao número anterior. Se o novo número não é consecutivo, ambas as variáveis "tmpCounter" e "counter" são reiniciadas.

A cada iteração do loop for, é verificado se a soma das variáveis "tmpCounter" e "counter" é maior do que o valor atual da variável "maxSubSum". Se for o caso, o valor de "maxSubSum" é atualizado.

Por fim, a função retorna o valor de "maxSubSum".

Com isso finalizamos mais uma sessão da série: Resolvendo problemas no HackerRank:. Até a próxima
How to Solve Jodit editor overlapping with my navbar
Tags: react, jodit, css, webdev
Published: 2023-03-06 14:14:54


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


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


I have already tried z index but still not working
Paracetamol.ts💊| #26: Explica este código TypeScript
Tags: typescript, javascript, spanish, webdev
Published: 2023-03-06 14:00:00

## **<center>Explica este código TypeScript</center>**
#### <center>**Dificultad:** <mark>Intermedio</mark> </center>

```ts
const x:(number | string)[];
```

¿Cuál de los siguientes arreglos es asignable a `x`?

- A. `[1, 2, 3]`
- B. `["1", "2", "3"]`
- C. `[1, "2", 3]`
- D. `Todos los anteriores`
- E. `Ninguno de los anteriores`

{% spoiler **Respuesta** %} 

✅ D. `Todos los anteriores`

La sintaxis `(number | string)[]` quiere decir que podemos crear:
* Arreglos de **solo** de números.
* Arreglos de **solo** de cadenas de texto.
* Arreglos mixtos: de números y cadenas de texto.

Cualquier otro valor fuera de los mencionados producira un error. 

{% endspoiler %}

---

Puedes ver el último reto acá:

{% link https://dev.to/duxtech/paracetamolts-25-explica-este-codigo-typescript-222f?preview=da5b4bc81d8858e4b6408df695bf46f0b81383df814547f969e8c2d6ef68d0cb6c7f5f880e68753f4f1a143dee8e255be30aad9a3922774243984174 %}
Get UUID from iOS devices
Tags: ios, mobile
Published: 2023-03-06 13:51:30

An easy way to get a UUID from your iPhone device (or other iOS device) is using the xcrun CLI.

Just connect your device with a data USB cable, when the device asks you to trust on connected device click "Yes". 
Now on your Mac open the terminal and type:

```bash
xcrun xctrace list devices
```

![Returned devices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tr8efhohoknj9idkp0zm.png)

{% embed https://twitter.com/Tuliocalil/status/1630298894306271233 %}
SSH keep Alive !
Tags: ssh, linux, terminal
Published: 2023-03-06 13:50:29

Usualy we need a live connection when working with **ssh** .
Here is short description. Note you can use **'*'** to apply all hosts:
`mkdir -p ~/.ssh`
```
cat > ~/.ssh/config << EOF 
Host host_or_ip
ServerAliveInterval 120 
EOF
Work smarter, not harder (how to use the "rails g resource" command)
Tags: ruby, rails, beginners
Published: 2023-03-06 13:44:30

Ruby on Rails is a popular web application framework that simplifies web development by providing a set of conventions and tools. One of the most powerful features of Rails is the ability to generate code quickly using the built-in generators. In this blog, we will focus on the `rails g resource` command, which generates a set of files for a new resource in your application.

A resource in Rails is a representation of a model, controller, and views that work together to provide CRUD (Create, Read, Update, Delete) functionality for a specific type of object. For example, if you were building a blog application, you might have a resource for posts, which would include a Post model, a Posts controller, and views for displaying, editing, and creating posts.

To use the `rails g resource` command, you'll need to open up your terminal and navigate to the root directory of your Rails application. From there, you can run the command followed by the name of your resource, like this:


```
rails g resource Post
```

You can also define the details of your table directly in the terminal. The type "string" is inferred, so those datatypes do not need to be defined: 

```
rails g resource Post title content author likes:integer
```

This will generate a set of files for the Post resource, including:

A **migration** file: This file is used to create the database table for the Post model. The migration includes columns for the various attributes of a post, such as title, content, author, and likes.

A **model** file: This file defines the Post class, which inherits from `ActiveRecord::Base`. It also includes validations and associations with other models, if applicable.

A **controller** file: This file defines the PostsController class, which handles HTTP requests and responses for the Post resource. It includes methods for creating, reading, updating, and deleting posts.

**Views**: The generator creates views for the various actions of the PostsController, such as index, show, create, update, and destroy. 

A **serializer** file: _if you have the serializer gem installed_, the `rails g resource` command will also generate a corresponding serializer file.

Once the generator has finished running, you can run migrations to create the Post table in your database:


```
rails db:migrate
```

And that's it! You now have a fully functional resource for Posts in your Rails application. Of course, you'll need to customize the generated files to fit your specific requirements, but this generator can save you a lot of time and effort in setting up the basic structure of your application.

Happy coding 💻
Type vs Interface no TypeScript: Qual a melhor opção?
Tags: typescript, type, interface, webdev
Published: 2023-03-06 13:32:58

O TypeScript é uma linguagem de programação que tem sido amplamente adotada pela comunidade de desenvolvimento web nos últimos anos. Uma das principais razões para isso é a capacidade do TypeScript de adicionar tipos aos códigos JavaScript, fornecendo assim maior segurança e confiabilidade ao código.

Ao trabalhar com o TypeScript, você encontrará duas opções para definir tipos: Type e Interface. Mas qual a melhor opção a escolher? Neste post, vamos explorar as diferenças entre Type e Interface e quando usar cada um deles.

Type e Interface no TypeScript
Type e Interface são duas maneiras de definir tipos no TypeScript. Type é usado para definir um tipo primitivo, como uma string, número, booleano ou qualquer outro tipo primitivo. Por outro lado, Interface é usado para definir objetos e suas propriedades.

Por exemplo, aqui está um exemplo de Type:

```typescript
type User = {
  name: string,
  age: number,
  email: string,
  isActive: boolean
}
```

E aqui está um exemplo de Interface:

```typescript
interface IUser {
  name: string,
  age: number,
  email: string,
  isActive: boolean
}
```

Ambas as declarações definem um objeto com as mesmas propriedades.

Diferenças entre Type e Interface
Embora pareçam semelhantes, há diferenças sutis entre Type e Interface. Aqui estão algumas delas:

- Herança: As interfaces podem ser estendidas e, portanto, podem herdar propriedades de outras interfaces. Já os tipos não podem ser estendidos.
- Reutilização: As interfaces permitem reutilização de código, pois podem ser usadas para definir objetos em vários lugares. Já os tipos são mais limitados nesse sentido.
- Extensibilidade: Os tipos permitem a definição de tipos de união, intersecção e tipos literais. Já as interfaces não têm essa flexibilidade.

## Quando usar Type e Interface
Em geral, Type é a melhor opção quando se trata de tipos primitivos e tipos literais. Por outro lado, Interface é mais adequado para definir objetos e suas propriedades. Além disso, se você precisar estender ou herdar propriedades de outras interfaces, deve usar uma Interface.

## Resumo
Type e Interface são duas maneiras de definir tipos no TypeScript. Embora sejam semelhantes, cada uma tem suas próprias vantagens e desvantagens. Em geral, é melhor usar Type para tipos primitivos e literais, e Interface para objetos e suas propriedades. No entanto, a escolha depende do contexto e das necessidades do seu projeto.
useDebounce Hook 🚀
Tags: react, usedebounce, javascript, performance
Published: 2023-03-06 13:26:11

I'll tell you about the use of **Debounce Function** as **useDebounce Hook** in React, which positively affects search request performance and which I also use frequently.

Firstly, let's create a react project in a simple way with the following command lines.

```
npx create-react-app my-app
```

Then you can create and use useDebounce as in the code blocks below.

> useDebounce.js

```React
import { useState, useEffect } from "react";

const useDebounce = (val, delay) => {
    const [ debounceVal, setDebounceVal ] = useState(val);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebounceVal(val);
        }, delay);

        return () => {
            clearTimeout(handler);
        }
    }, [val]);

    return debounceVal;
}

export default useDebounce;
```

> App.js

```React
import { useState, useEffect } from "react";
import useDebounce from "./useDebounce";

const DATA_LIST = [
  "Luke Skywalker",
  "C-3PO",
  "R2-D2",
  "Darth Vader",
  "Leia Organa",
  "Owen Lars",
  "Beru Whitesun lars",
  "R5-D4",
  "Biggs Darklighter",
  "Obi-Wan Kenobi",
];

function App() {
  const [results, setResults] = useState([]);
  const [text, setText] = useState("");

  const debounce = useDebounce(text, 500);

  useEffect(() => {
    const data = DATA_LIST.filter((el) => el.toLowerCase().includes(debounce));
    setResults(data);
  }, [debounce]);

  return (
    <div className="app">
      <h1>search</h1>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <div className="search-result">
        {results.length > 0 ? (
          results.map((item, i) => (
            <div key={i} className="result-item">
              {item}
            </div>
          ))
        ) : (
          <p>No Result</p>
        )}
      </div>
    </div>
  );
}

export default App;

```

You can also review this example from my github repo: https://github.com/cagatay-unal/useDebounce-hook

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