teleren/devto huggingface dataset:
[pt-BR] Consumindo conteúdo HTTP no Terraform
Tags: quick, intermediate, terraform, ptbr
Published: 2022-05-16 16:27:09

> Parte de uma série de posts curtos com conhecimentos que podem ser úteis no dia a dia e quero compartilhar. Muitas vezes eles exigem um conhecimento prévio da ferramenta ou da linguagem.
> 
> Esses textos curtos são publicados sob a tag #quick.

Existem situações em que você precisa armazenar o conteúdo de um endpoint ou de um arquivo que está online, e esse conteúdo não será modificado dentro daquele contexto.

Por exemplo, trabalhei num projeto em que a geração de tokens JWT era feita pelo AWS Cognito. Para validar o token recebido pelo client e garantir que ele era legítimo, permitindo a liberação do acesso à API, é necessário verificar se o token foi gerado com a mesma chave do Cognito.

Para isso, todo User Pool do Cognito gera um documento público que pode ser consumido pelo seu código. Esse documento fica em `https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json`

Como o conteúdo desse documento nunca será alterado, é um desperdício fazer uma requisição HTTP para esse endereço toda vez que precisarmos validar um token. Como a validação precisa ser rápida e, no contexto de um recurso serverless, somos cobrados pelos tempo de uso, esse acesso extra causa um aumento desnecessário de custos.

Para resolver isso, a requisição HTTP é feita uma única vez, durante o build da aplicação, e esse valor é passado para o código como uma variável de ambiente.

Usando Terraform, bastou fazer assim:

```terraform

# Aqui criamos o User Pool onde serão armazenadas 
# as credenciais dos usuários
resource "aws_cognito_user_pool" "exemplo" {
  name = "exemplo"

  # um monte de configurações
}

# Aqui armazenamos os dados da região AWS atual
data "aws_region" "current" {}

# E aqui fazemos a requisição HTTP, que terá os 
# parâmetros automaticamente atualizados se você
# mudar de região ou recriar seu User Pool
data "http" "cognito_jwks" {
  url = "https://cognito-idp.${data.aws_region.current.name}.amazonaws.com/${aws_cognito_user_pool.exemplo.id}/.well-known/jwks.json"

  request_headers = {
    Accept = "application/json"
  }
}

# Finalmente, exportamos o conteúdo da requisição 
# para que seja usada em outros módulos do seu projeto
output "cognito_jwks" {
  value = tostring(data.http.cognito_jwks.body)
}
```

E, no módulo onde você definiu a Lambda, você faz assim:

```terraform
# essa variável terá um valor atribuído
variable "cognito_jwks" {
  type = string
}

resource "aws_lambda_function" "exemplo" {
  environment {
    variables = {
      COGNITO_JWKS = var.cognito_jwks
    }
  }
```

Isso funciona com qualquer outro recurso que você criar, não precisa ser necessariamente uma Lambda. COGNITO_JWKS contém um texto e você pode usá-lo da maneira que for melhor para o seu caso.

Ao gerar a Lambda, o conteúdo do arquivo estará disponível como uma variável de ambiente, podendo ser acessado no código com `process.env.COGNITO_JWKS`, caso você esteja usando JavaScript.

![Variável de ambiente da AWS Lambda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ixvngb1n3cjxf4datmg5.png)
Introducing SpotCoders, a Free Coding Meetup
Tags: javascript, typescript, react, beginners
Published: 2022-05-16 16:25:16

[SpotCoders](https://www.meetup.com/spotcoders/) is a new virtual programming meetup that I'm starting! The meetup is open to anyone who wants to improve their JavaScript, TypeScript, and React skills by doing interview-style coding challenges in a small group environment. The problems will be targeted at beginner and intermediate level programmers.

The unique thing about SpotCoders is that it will be hosted in [Spot](https://spotvirtual.com), a virtual office & event platform. In addition to being more fun than Zoom, Spot also makes it much more intuitive to do things like splitting into smaller groups. All you have to do is walk to a separate room in the 3D virtual world! (I happen to be an employee at Spot, by the way. That said, this is a personal project of mine and the company isn't making money from the meetup.)

The [first meeting](https://www.meetup.com/spotcoders/events/285936343/) will be **Saturday, May 28th from 12:00 pm – 1:30 pm US Eastern Time**. Anyone who can make this time is welcome to attend! The meeting is limited to 12 attendees, so make sure to RSVP sooner rather than later if you want to come. I may open it up to more people in the future if the meeting fills up quickly. Once you RSVP, you'll be able to see the invite link for joining the Spot world.

Please read the [group description on Meetup](https://www.meetup.com/spotcoders/) to learn about the format of the meetings and what to expect. You can ignore where Meetup is showing Raleigh, NC as the location of the group — they require a physical location even for entirely virtual meetups like this one.

I hope to see you there!
Lunes de música... ¿Qué estás escuchando? 🎵 (16-mayo)
Tags: music, spanish, discuss, lunes
Published: 2022-05-16 16:23:37

> **"La música es para el alma lo que la gimnasia para el cuerpo."**
_Platón_

La música es parte importante de la vida de la mayoría de las personas y una vida no basta para poder escuchar todas las canciones que quisiéramos o conocer a todos los artistas, solistas o bandas.

Últimamente mis gustos musicales han sido muy estáticos y siento que necesito abrir mis horizontes y poder conocer nueva música interesante. 

Este post es la cuarta entrega de una serie semanal que lanzaré todos los lunes para que como comunidad podamos compartir y por qué no conocer nuevas melodías. 🎶

Puedes compartir tus sugerencias usando los *liquid tags* de Dev.to, por ejemplo:

* Para compartir un video desde youtube:
```js
{% youtube dQw4w9WgXcQ %} // dQw4w9WgXcQ es el id del video
```

* Para compartir una canción desde spotify:
```js
{% spotify https://open.spotify.com/track/7GBwTrOpTtsLdJN3Dc0U1C?si=ea737b51f47043b6 %} 
```

Mi sugerencia para esta semana es de Jarabe de palo y su canción titulada "Depende"

{% spotify https://open.spotify.com/track/689lBKIELtWGHfsPWpR6rv?si=574c1179b79f4818 %} 

---

Este post no sería posible sin mi amigo @michaeltharrington y su post:

{% link https://dev.to/michaeltharrington/music-monday-what-are-you-listening-to-4g1o %}

Los respectivos créditos a él por ser tan buena onda. 

{% user michaeltharrington%}

Y dime, ¿qué estás escuchando ahora? Te leo en los comentarios.
React Testing Library — My Notes
Published: 2022-05-16 16:20:03

Some quick answers to common RTL-related questions.

Run tests

- yarn run test

Where to usually place the tests?

- Inside a __test__ folder.

What is a common way to name tests?

- Component.test.tsx

What is usually needed to import in test files?
```
import React from “react”; //React
import Counter from “../Counter”; //The component to test
import { render } from “@testing-library/react”;
```
render is used for rendering the component in the virtual dom so you can then test what has been rendered. Due to this, it usually goes inside a beforeEach.

What would be an example of a basic test?
```
test(“header renders with correct test”, () => {
     const { getByTestId } = render(<Counter />);
     const headerEl = getByTestId(“header”);
     expect(headerEl.textContent).toBe(“My Counter”);
})
```
- The test's first argument would be the description.

- The second argument would be a function with the actions of the tests.

- expect is the function that actually does the test.

* It is not a good practice to use getByTestId. This is just an example.

What would be a general description of testing with RTL?

- You render a component.

- Then you look and select elements inside the component.

- Then you can:

- Execute actions on the element (like clicks) and then verify the expected results.

- Or just check the element to have the right values without executing any action before.

What would be an example of checking the right values in an element?

- Expects the text content inside the element ‘headerEl’ to be the specific string “My Counter”.
```
expect(headerEl.textContent).toBe(“My Counter”);
```
If you can’t find any way to select an element you want to, what is the last resource you can use?

getByTestId and the element need to be marked with the property:
```
data-testid
```
What is useful for simulating actions?

- The most used way is userEvent (because it is more similar to the user):
```
import userEvent from ‘@testing-library/user-event’; 
userEvent.dblClick(checkbox);
```
- But, fireEvent can also be used:
```
fireEvent.change(inputEl, {
     target: {
          value: “5”
     }
});
```
What can you do if you expect something not to have a certain value?

- With not.

expect(headerEl.textContent).not.toBe(“My Counter”);
How to output the code in the terminal?
```
screen.debug()
```
### That's all folks !!
Hi May!
Published: 2022-05-16 16:12:35

Hello everyone! I'm back!, and in this section we will explore the month of May with me as an intern.

```
WEEK 7 (April 29 - May 6, 2022) (Day 31 - 35)
```

Hi everyone! hope you have a wonderful day...
My week 7 is no difference with the other weeks yet I have different parts I finished in the website and some technical stuff I performed in other offices.

- Doing some edits on the done section on the website.

- Checking the functional and non-functional units in a department.

- Creating report about the ORC we've done.

- Reformatting computer units.

Pictures be uploaded soon (technical error)

```
WEEK 8 (May 7 - May 17, 2022) (Day 36 - 40)
```

Hello week 8! Hello readers! this week I did not work on the website for I wanna go out from the office and visit other departments for their concern. I do also some documents about the things we do. This week is a fun week aside from receiving some compliments, I feel happy every time I heard an appreciation words from clients or even from you seniors. So below is the stuff I did.

- Doing ORC Report for another department.

- Creating architectural mapping of the laboratory we visit.

- Attending command from seniors to the other departments.

- Learning how to clean the printer for ID's

Pictures be uploaded soon (technical error)

```
WEEK 9 (May 18 - May 24, 2022) (Day 41 - 45)
```
Hope you have a great week! This week is not so busy week, so I just sit back in my station and do some planning on how to continue the website. I also help on returning some toner to the company. As months goes by I have this thought that I wanna work in the department I am now after graduation. The reason behind is that the environment inside the office is not toxic, it won't add on to the stressed you experienced. 
So that's it for this week everyone and see you next week..


Pictures be uploaded soon (technical error)

```
Week 9 (May 25 - June 7, 2022) (Day 46 - 50)
```
Hi everyone! This week was really sad week for me. As you can see there is a big gap on the date. It is because I was absent for 1 week. I got sick and that sickness hold me from attending to my most awaited event which is the RICCI 2022. Anyway, even if I did not attend to that event I am very happy that our Instructors, Dean and personnel from the Research acknowledge me even if I was not there. So the big news there is that me and my partner won the Best in Podium award, and best in Poster Award. So for my OJT task, I am just focus on the website and they didn't let me do technical support task so that I can be focus on the Website.

So that's it for this week and see you on June! Thank you for reading :-)

Pictures be uploaded soon (technical error)


Please click the link below for the next part..

https://dev.to/naaamae/be-good-to-me-june-ff3
What do you use GPUs for?
Tags: machinelearning, deeplearning, datascience, python
Published: 2022-05-16 16:10:17


GPUs are becoming better to serve general purpose computing.🚀

With the help of parallel computing architecture, it is offering great speed ups for use cases like 3D rendering, machine learning, data science, crypto-mining and scientific computing.

That makes me wonder, **What do you use GPUs for today? 😀**

Often times the access to GPUs is very costly. Whether you build your own PC or run it on the cloud, the costs can burn a hole in your pocket. 

To solve this issue, we created [Q Blocks](https://www.qblocks.cloud) - A decentralized GPU computing platform for Machine learning ! 🎉

Using under-utilised computing systems to run ML drastically reduced the cost of GPU power access for ML devs. High-end GPUs are available on Q Blocks at upto 1/10th the cost.

If you had access to this much GPU power then what are you going to use it for? 🤔
I Created XOH-XAPI, a JavaSCript/TypeScript Library For Trading Financial Markets
Tags: forex, trading, javascript, typescript
Published: 2022-05-16 16:02:20

Hello there...

I created [XOH-XAPI](https://github.com/PeterNdomano/xoh-xapi/), a Javascript/Typescript version of XTB and X Open Hub API For Trading Financial markets. It works for both non-browser and browser based Javascript Environments, handling all the heavy-lifting for fetching market data, maintaining connection with the server, streaming real-time trading data as well as opening and closing positions.

It's a useful tool for those who want to create their own trading bots and indicators using Javascript. It's available on github - [XOH-XAPI](https://github.com/PeterNdomano/xoh-xapi/)

You can get a free demo account on [XTB](https://www.xtb.com/int/demo-account) to experiment with your scripts. 

Run `npm install xoh-xapi` to install and import it by `import Xapi from 'xoh-xapi'`

Then initialize it and run it as follows

```js
let x = new Xapi({
    accountId: "<your_account_id>", //you can get a demo account ID from XTB
    password: "<your_password>", //Your account password
    type: "<acc_type>", //account type, can be 'demo' or 'real'
    broker: "<broker>", // your broker, currently only 'xtb' (for XTB) and 'xoh' for X Open Hub are supported
  });

x.onReady(() => {

  //now you can communicate to the Trading server, retrieve candles, stream real-time data etc....

}, (error) => {
  //error is an instance of JS Error Object, this function is called when Xapi cannot connect to the server
  console.log("error: "+error.message);
})
```

[Read Detailed start guide on github](https://github.com/PeterNdomano/xoh-xapi/#xtb-and-x-open-hub-api).

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

This project is under constant development so welcome to use, test and submit issues. PRs are welcome too. Don't forget to star [XOH-XAPI on GitHub](https://github.com/PeterNdomano/xoh-xapi/) and follow me on github for more exciting stuffs to come. Thanks for reading to this far. Stay safe..
Resume editing will provide outstanding results!
Tags: career
Published: 2022-05-16 15:58:46

Best resume editing service, online resume writing services, top resume writing services are legal and available online so there is always someone, a writer ready to work on your resumes. Your own time is saved, professional services are delivered and they are near, you do not even have to come out but stay within home walls. 

Online [curriculum vitae editing services](https://resumeperk.com/resume-edit) with certified top uk custom writers who are able to edit a resume, a cv or a cover letter and the price you are to pay for the service is ridiculously low. This purchase is an excellent contribution to make your future brighter. The best help for you and me and everyone who needs it. Follow my advice, buy an order and get a job you have been dreaming of. 

## Affordable CV help online - hire a professional, get high-quality results!

According to professional recruiters, the most common mistakes in a CV/resume are made due to the fact that we do not understand well what the employer wants.

The truth of life is that - unstructured, overloaded with lyrics and CVs - definitely fall into the trash. A CV is a kind of visiting card of a person who wants to declare himself on the labor market. 

As a rule, the initial viewing of a CV takes no more than 2-3 minutes. A well-written resume can attract the attention of a potential employer or a recruiting company manager to your person, or it can work against you.
If you failed to attract attention, it means that the resume did not work.
In this case, the wait for job offers is delayed for many months.

So, when deciding to write your resume, remember that people reading it will form their idea of ​​your personality and your professional skills, relying solely on what they see and read. So how do I polish my cv to make it stand out?

## Important nuances for a correct CV/resume

- make a resume in the language that is most used in the place where you send it;
- in the description of the present work, use verbs in the present tense, for example, develop, control; accordingly, when describing previous jobs, use verbs in the past tense;
- make sure that your resume is designed in the same style; An example of correct formatting: the bulk of the text - in plain type (no more than 12), dates, names of companies and educational institutions - in bold; positions - with underlining; responsibilities - through dots;
- it is very important to fit your resume on one (if you are a young specialist) or at most two pages (if you are a specialist with extensive experience);
- check the text for errors. Spelling and stylistic mistakes can spoil the impression of your resume overnight.
- stylization, green font and colored paper - do not do this!

So, the resume is ready.
Congratulations!

You have taken the first important step in your job search.
[pt-BR] Convertendo callbacks em promises em JavaScript
Tags: quick, intermediate, javascript, ptbr
Published: 2022-05-16 15:39:33

> Primeiro de uma série de posts curtos com conhecimentos que podem ser úteis no dia a dia e quero compartilhar. Muitas vezes eles exigem um conhecimento prévio da ferramenta ou da linguagem.
>
> Esses textos curtos serão publicados sob a tag [#quick](https://dev.to/t/quick).

Existem situações em que você precisa fazer com que um código que foi pensado para ser executado assincronamente seja executado de forma síncrona. Ao usar _promises_, você faz isso com o uso da palavra chave `await`:

```javascript
await algoAssincrono
  .then(succeeded => console.log("Uhu!"))
  .catch(failed => console.error("Deu ruim"));
```
A execução do código vai aguardar até que a _promise_ seja finalizada para só então prosseguir.

Quando você está escrevendo um código que exige um comportamento síncrono, como uma [AWS Lambda](https://aws.amazon.com/lambda/) ou o equivalente de qualquer outro fornecedor de _Cloud_, você precisa garantir que todos os processos terminaram de ser executados antes do retorno da função:

```javascript
exports.handler = async (event) => {

  return await processoAssincrono(event)
    .then(response => {
      return {
        statusCode: 200,
        body: JSON.stringify(message: response)
      };
    })
    .catch(failure => {
      return {
        statusCode: 400,
        body: JSON.stringify(reason: failure)
      }
    })
}
```

A função `processoAssincrono` trata o evento recebido pela Lambda e, caso esteja tudo certo, retorna um status HTTP 200 e um conteúdo que será consumido pelo client, ou um status HTTP 400 caso não esteja tudo certo, com o motivo pelo qual a requisição falhou.

O nosso exemplo `processoAssincrono` foi pensado para ser assíncrono. Talvez ele consulte um banco de dados, uma API, ou qualquer recurso que poderia causar o bloqueio do _event loop_, então essa decisão faz todo o sentido, mas dentro de uma Lambda nós precisamos que o processo seja finalizado para só então retornarmos um valor. Com o uso de `await`, só retornamos um valor depois que a _promise_ terminar sua execução, garantindo que a execução seja síncrona.

Quando você usa um código feito com _callbacks_, não existe essa possibilidade:

```javascript
assincronoComCallbacks(
  function(succeeded) { 
    console.log("Funcionou");
  }, 
  function(failed) {
    console.error("Deu erro");
  }
);
```
Para resolver isso, podemos criar uma _promise_ que só segue em frente quando os callbacks forem executados:

```javascript
await new Promise((fulfill, reject) => {
  assincronoComCallbacks(
    succeeded => fulfill(succeeded),
    failed => reject(failed)
  });
})
.then(succeeded => console.log("Uhu!"))
.catch(failed => console.error("Deu ruim"));
```

A função com _callbacks_ continua sendo assíncrona, mas estará encapsulada numa _promise_, permitindo assim o uso de `await`, tornando o processo seja executado como se fosse síncrono.
🎬 Ball Catcher: Part 1 | Create a hard real-time system, across multiple electronic boards with Luos.
Tags: opensource, microservices, tutorial, luos
Published: 2022-05-16 15:30:53

In this new video, we'll introduce Luos' real-time capabilities and demonstrate their application through a cool, real-world project that Viktoria decided to create, called Ball Catcher.

{% embed https://www.youtube.com/embed/BtMSTrTEqqs %}

If you work on critical systems such as cars, spacecraft or nuclear power plants, you know how difficult it is to create a hard real-time system on several electronic boards.

This video is the first of a series, explaining the real time aspect of Luos.
Paracetamol.js💊| #117: Explica este código JavaScript
Tags: javascript, spanish, webdev, discuss
Published: 2022-05-16 15:30:35

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

```js
const promise = () => {
  let x = Promise.resolve("Hola");
  return x;
}

promise()
  .then((message) => console.log(message))
```

A. `SyntaxisError`
B. `Promise { <pending> }`
C. `Hola`
D. `TypeError`

Respuesta en el primer comentario.

---
You are the Wind Beneath my Wings!
Tags: rust, thank, stevemcquee
Published: 2022-05-16 15:26:53

> “If you want to lead them you must place yourself behind them.”- Lao Tzu

I really want to say thank you to all my followers and the community!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qb0xpddqzkndm71ap94.jpg)
My [previous article](https://dev.to/nathan20/the-hidden-power-of-rust-7ap) on Rust programming language was on the [Top 7 Featured DEV Post](https://dev.to/devteam/top-7-featured-dev-posts-from-the-past-week-fpb).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vn7ls5somgfsfnj8j8tf.png)
 
 
Do not hesitate to give me your ideas for future articles in the comments !

Join our discord server [https://discord.gg/UkUFYECC](https://discord.gg/UkUFYECC) , we talk about everything but particularly Rust and APIS
First look at Standalone Components in Angular
Tags: angular
Published: 2022-05-16 15:22:09

Over the weekend I recorded a short video about an upcoming feature in Angular called Standalone Components.

In the video I go through migrating a newly generated, NgModule-based Angular app to use Standalone Components — bootstrapping, creating a separate Standalone Component and using it in a template, and lazy-loading a route based on a Standalone Component.

{% embed https://www.youtube.com/watch?v=9spFqrI2NJw %}

---

Cover photo by Mark König (https://unsplash.com/@markkoenig).