teleren/devto huggingface dataset:
Well-Architected AWS 
Tags: aws
Published: 2021-05-10 05:32:11

Recently, I got started with Well-Architected labs for AWS.  
https://wellarchitectedlabs.com/
It is regarded as a guide for Best Practices to AWS deployments and administration.  I will be going through the main parts of Operational Excellence here.

The first part of any AWS journey should be to not use your root user account to perform your tasks.  Head on over to IAM to make a new user and new group to add them to.  The group permissions should be set to include AdministratorAccess policy at the least.

Next part is a bit tricky.  Go to Key Pair and make a new public and private key pair.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8iuaq0uxyo67yprueg3v.png)

A pem file is usually the best choice.  You can later access the EC2 machines via SSH.
*ssh -i PEMFILE.pem username@IPorDomain*

With access now secure and delegated to a user we can start the deploy process.
The lab gives you a template CloudFormation Script that is used to deploy multiple machines and the necessary networking infrastructure.  You can enter it on:
https://console.aws.amazon.com/cloudformation/

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bhe7bl0tins5j6q0b5qr.png)
 
The important part of this deployment is to make your KeyName you made earlier so your pem file will work when you ssh to here later.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2t4iovgoipua6o0fata.png)
 
The nifty part of CloudFormation is the Designer tool that gives you a flowchart map of the different parts you are deploying:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/er34mexwnqluwkm7s8xf.png)

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eirwx4cbel2qca47ijl4.png)
  
You can go into EC2 and see the different machines and add optional settings like Tags or Security Group details.  These help with admin tasks and can save you headaches later.

Once you are done we can add a feature that is useful called Systems Manager.  But first we need to go back to IAM and add a role:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kynew2qn0wj5pba4xocz.png)
 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4or49yoydpkpi1ka5u6h.png)
Once that is done, head back to EC2 and modify IAM roles of the instances.  Actions > Security > Modify IAM role
 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vv5l0dh3yl2ngwvaku3z.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34b5ifxhssp2ohb6xkpz.png)
 
 You should be able to see Metadata from the instances you just modified and this will help going forward.

This is just the first part of the Well-Architected Labs and I may keep going on this if schedule allows.  In any case, check out the labs and follow along.  You will learn a lot.

https://wellarchitectedlabs.com/
Resolvendo erro de build no projeto de arquitetura Intel para arquitetura Apple Silicon (M1)
Tags: ios, swift, xcode, braziliandevs
Published: 2021-06-09 21:29:41

Resolvendo "error: module was created for incompatible target arm64-apple-ios9.0"

Meu primeiro dia de trabalho foi bem interessante, ainda não tínhamos testado o projeto em um computador Mac com Apple Silicon (M1), com isso, tivemos um erro subindo o projeto. 

Uma informação que nos ajudará a entender o problema é que, com essa nova plataforma teremos o macOS baseado em arm64, seus simuladores também serão executados em arm64, ao contrário da atual arquitetura x86/64 baseada na Intel.

O projeto do trabalho, que havia sido criado com arquitetura x64, tem algumas dependências que não suportam a nova arquitetura dos MacBooks, então foi preciso mexer em uma configuração.

Como podemos ver abaixo, foi assim que ficou o **Build Settings** após fazer as alterações, fomos em **Excluded Architectures**, depois em **Debug** e **Release** adicionamos a arquitetura que queremos excluir quando subirmos o projeto no simulador **(Any iOS Simulator)**.

![Um código excluindo a arquitetura arm64 quando rodar o projeto no simulador](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s9pjss7qo0hod54qf8jf.png)

Nesse vídeo eu mostro como configurei, porém em outro projeto que estava mexendo. 

https://www.youtube.com/watch?v=l3Cmcyqbvxg

Lembrando que eu não rodo o projeto em um celular, e sim no simulador do Xcode mesmo.

Fazendo isso, pode acontecer com que o build fique mais lento, porque ele praticamente faz a transcrição do código com a arquitetura x64 (Intel) para a arm64 (Apple Silicon), mas isso resolveu o problema, já que iremos evitar as dependências que não suportam essa nova arquitetura de nos impedir de subir o projeto. 

O M1 consegue executar códigos feitos na arquitetura Intel com o Rosetta 2. Um link interessante sobre isso [aqui](https://eclecticlight.co/2021/01/22/running-intel-code-on-your-m1-mac-rosetta-2-and-oah/) 

E um agradecimento final ao meu líder que conseguiu me explicar isso pacientemente e me ajudar a solucionar o problema. Obrigada, Felipe!
Deploying Golang API to Heroku
Tags: heroku, go, api, rest
Published: 2021-06-09 21:24:23

## Deploying a Go API on Heroku

## To deploy it on Heroku.

I'll assume you have Heroku cli installed and logged in.
or you can start here.
[Install heroku cli](https://devcenter.heroku.com/articles/heroku-cli)

- Create a Procfile that points to our binary with one line
  and place it in the root of the directory

```
// Profile
web: bin/Intersect_api
```

- Run the app locally to test using

```
heroku local
```

- Create a heroku app

```
heroku create intersect-api-v2
```

- Then commit our changes on git

```
git add .
git commit -m '💪'
```

- And at the end, simply deploy our app using

```
git push heroku heroku-deploy:master
```

- (Optional) Subsequent change can be commit using

```
git push heroku master
```

Extra

- You can read the logs from with

```
heroku logs
```

That's about it.
Now we can check our server at,

https://intersect-api-v2.herokuapp.com
Verifying an Object's Constructor with instanceof
Tags: javascript, devops, tutorial, beginners
Published: 2021-06-09 21:22:50

* Continued
* Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the `instanceof` operator. `instanceof` allows you to compare an object to a constructor, returning `true` or `false` based on whether or not that object was created with the constructor. 

* Here's an example:
```
function Dog(name, color) {
  this.name = name;
  this.color = color;
  this.numLegs = 4;
}

let goldenRetriever = new Dog("Naruto", orange);

goldenRetriever instanceof Dog; // will display true
```
* This `instanceof` method would return `true`.
* If an object is created without using a constructor, `instanceof` will verify that it is not an instance of that constructor:
Deploy a MicroK8s cluster with cloud-init
Tags: devops, kubernetes, cloud
Published: 2021-06-09 21:21:47

If you need to run Kubernetes, today very frequently you just pick one managed in some cloud provider. However this option is frequently expensive. A cheaper option is to get a bunch of virtual machines and install Kubernetes in it.

Creating a Kubernetes cluster actually today is pretty simple, using tools like [MicroK8s](https://microk8s.io/) but there are still some manual actions to take.

To make cluster building even simpler, you can use for example [cloud-init](https://cloudinit.readthedocs.io/en/latest/), the standard for cloud image initialization. So I decided to write a cloud-init that can automatically build a cluster for you.

The result is [here](https://bit.ly/microk8s-init), you can download it with this command:

```
curl -sL bit.ly/microk8s-init >microk8s-init.yaml
```

To entirely automate the cluster generation I had to use a couple of tricks.

First I assigned statically an IP address to virtual machines. I assign ips to virtual machines using a number that is expected to be included in the hostname. Second I generate "programmatically" a token to join the cluster.

There are hence a couple of parameters you may need to customize before using it. You may need to change the `NET` parameter.  All the virtual machines will get an IP in that network according to the host name. For example, the virtual machine  `kube1` will get the address `10.0.0.1`.  Also note that the `1` virtual machine is always the one used to join the cluster

Also for security you may want to change the `PASS` parameter that is the  password used to generate the unique token for joining the cluster.

The script can be used in many different environments. The low hanging fruit  to use it is wth [`multipass`](https://multipass.run/), another handy tool from Ubuntu to launch virtual machines in multiple environments.

Microk8s requires at least 2gb of memory to run and 2 vcpu. You can hence test the script with the following commands to create the first node of a local cluster:

```
multipass launch -nkube1 -m3g -c2 --cloud-init microk8s-init.yaml
```

Sometimes it will time out during the initialization so you may need to wait for it to complete with

```
multipass exec kube1 -- sudo cloud-init status --wait
```

You can then launch more instances and wait for them:

```
multipass launch -nkube2 -m2g -c2 --cloud-init microk8s-init.yaml
multipass exec kube2 -- sudo cloud-init status --wait
multipass launch -nkube3 -m2g -c2 --cloud-init microk8s-init.yaml
multipass exec kube3 -- sudo cloud-init status --wait
```

You can finally extract the configuration file and check for the cluster status with:

```
multipass transfer kube1:/etc/kubeconfig ~/.kube/config
kubectl get nodes
```
The Best SvelteKit YouTube Tutorials
Tags: svelte, tutorial
Published: 2021-06-09 21:19:14

Here is my list of the best SvelteKit YouTube video tutorials:

## [James Q Quick](https://www.youtube.com/watch?v=UU7MgYIbtAk&t=2676s)

{% youtube UU7MgYIbtAk %}

&nbsp;

## [Brayden Girard](https://www.youtube.com/watch?v=P6gEnVlJPOc&list=PLPkJj9BR9B925L3K05PfIkDeU4sEIhj0n)

{% youtube P6gEnVlJPOc %}

[Full Playlist](https://www.youtube.com/playlist?list=PLPkJj9BR9B925L3K05PfIkDeU4sEIhj0n)

&nbsp;

## [Svelte Mastery ](https://www.youtube.com/watch?v=j4AV2Liojk0&t=6s&ab_channel=SvelteMasterySvelteMastery)

{% youtube j4AV2Liojk0 %}

&nbsp;

## [WebJeda](https://www.youtube.com/watch?v=Gtg4yG8Bhcs&list=PLm_Qt4aKpfKjf77S8UD79Ockhwp_699Ms&index=1&t=137s&ab_channel=WebJedaWebJeda)

{% youtube Gtg4yG8Bhcs %}

[Full Playlist](https://www.youtube.com/playlist?list=PLm_Qt4aKpfKjf77S8UD79Ockhwp_699Ms)
                                                                                               
&nbsp;

## [David Parker](https://www.youtube.com/watch?v=qmwJTI-vH6w&list=PLPqKsyEGhUnaq0FiYab4JlcQNedSlDylq&index=1&t=148s&ab_channel=DavidParkerDavidParker)

{% youtube qmwJTI-vH6w %}

[Full Playlist](https://www.youtube.com/playlist?list=PLPqKsyEGhUnaq0FiYab4JlcQNedSlDylq)
How to create a CloudWatch metric alarm for AppSync with Terraform?
Tags: aws, cloudwatch, appsync, terraform
Published: 2021-06-09 21:18:33

---
title: How to create a CloudWatch metric alarm for AppSync with Terraform?
published: true
description: 
tags: aws,cloudwatch,appsync,terraform
//cover_image: https://direct_url_to_image.jpg
---

CloudWatch metrics & alarms are quite often the first choose when it comes to monitor AWS cloud based applications, it's always come up not only to collect metadata about the performance, but also to preemptively be alerted when things start to go sideways.

Recently I have been working extensively with AppSync to build a high available GraphQL API and have run into the need to create alarms with Terraform on top of the built-in metrics exposed by CloudWatch (4XX, 5XX and latency)

### Basic syntax

To create a metric alarm with Terraform, the resource `aws_cloudwatch_metric_alarm` should be used, below an example of how it should be look like:

```javascript
resource "aws_cloudwatch_metric_alarm" "appync_500_error" {
  alarm_name                = "appsync-500-error"
  
  alarm_description         = "This metric monitors AppSync 500 errors"
  comparison_operator       = "GreaterThanOrEqualToThreshold"
  threshold                 = "1"
  evaluation_periods        = "1"
  actions_enabled           = false
  alarm_actions             = []
  tags = var.config.tags
}
```

More details about each attribut can be found on [Terraform documentation.](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm)

### CloudWatch metric alarm for AppSync syntax

It’s not complicated, this is all i need to crate an alarme on 5xx errors and send a message to an Amazon SNS topic:

```javascript
resource "aws_cloudwatch_metric_alarm" "appync_500_error" {
  alarm_name                = "appsync-500-error"
  
  alarm_description         = "This metric monitors AppSync 500 errors"
  comparison_operator       = "GreaterThanOrEqualToThreshold"
  threshold                 = "1"
  evaluation_periods        = "1"
  actions_enabled           = true
  alarm_actions             = [aws_sns_topic.appync_500_error_topic.arn]

  metric_query {
    id          = "error500"
    return_data = "true"
    metric {
      metric_name = "5XXError"
      namespace   = "AWS/AppSync"
      stat        = "Sum"
      period      = "300"

      dimensions = {
        GraphQLAPIId = "YOUR_API_ID"
      }
    }
  }
  
  tags = var.config.tags
}
```

It’s effortless and self-explanatory!

However, keep in mind that if you specify at least one `metric_query`, you may not specify a `metric_name`, `namespace`, `period` or `statistic` directly on the root of the resource `aws_cloudwatch_metric_alarm`.

All CloudWatch metrics for AppSync are emitted in one dimension `GraphQLAPIId`. This means that you can filter a specific API like that:

```javascript
dimensions = {
   GraphQLAPIId = "YOUR_API_ID"
}
```
Hello grandma!
Tags: career, devjournal, codenewbie, beginners
Published: 2021-06-09 20:31:38

**Who are we as devs?**

We are R. and E., and both of us are working in non-programming fields. Our goal is to ditch our current jobs and become software developers. 

**What are we doing?**

We are doing a full stack web development boot camp based in London. As full-stack devs, we are learning back-end (Ruby on Rails, SQL) and front-end (HTML, CSS and Javascript) web development concepts.

**Goals?**

- To allow our grandmas to deploy the next Airbnb killer app;
- To keep it simple and accessible (especially for our dear grandmas);
- We, as aspiring developers, want to learn through teaching.

**Timetable?** 

The plan is to share what we have learned in the Bootcamp (grandma, thanks for the big loan). We will do it by publishing various programming topics in a digestible format. Next week we will start from scratch discussing Terminal and Git.

```
puts "Stay tuned!"
```
Deploying to Production using Containers but without Kubernetes
Published: 2021-06-09 20:27:06

What would be the approach to deploy a traditional web application with a SQL database (PostgreSQL) using containers?

I heard that though Docker compose makes deploying more convenient, it's not the best choice due to the lack of scaling. The better option is Kubernetes but there's not enough ramp up time before our deployment and there's also the question of support -- will I know enough to maintain the cluster?

Are there alternatives?

Thanks! :)
Day 87 of 100 Days Of SwiftUI
Tags: swift, 100daysofcode
Published: 2021-06-09 20:14:00

I just completed day 87 of 100 days of SwiftUI. Today I learnt how to perform an action repeatedly using the `Timer` class. I also learnt how to be notified when your app goes to the background.

In order to know when your app goes to the background, you have to Apple's Notification Center API. Notification Center is internal message system. It allows the system notify us of events. It also let us send events between different parts of our application. 
For example, to know when your app in the background, you can do this
```swift
Text("Hello, World!")
    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
        print("Moving to the background!")
    }
```
XSS Attack - Is your Application Vulnerable? - npm packages can make you vulnerable!!!
Tags: xss, security, webdev
Published: 2021-06-09 19:32:32

In this video I'll show you a XSS attack and how you can protect your applications.

{% youtube HfxYlrOR26k %}

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
A minimal CMS for jamstack blogging
Tags: writing, jamstack, vanillajs, github
Published: 2021-06-09 19:29:56

---
title: A minimal CMS for jamstack blogging
published: true
description: A tool to write and publish a blog form anywhere using the web browser.
tags: writing, jamstack, vanillajs, github
---

## The problem the project tries to solve
I made my homepage using a static page generator [11ty](https://www.11ty.dev/). The blogs and project documentations are written in a Markdown [about markdown](https://www.markdownguide.org/). These documents the page generator transforms into static HTML. 

It is super easy to write them in my code editor connected to github. Sometimes I would like to write & publish on the go using my tablet or iPhone.

## The solution
- an responsive web app written in vanilla JS. It connects to your github using github's [octokitjs](https://github.com/octokit/core.js/) library.

### Printscreens 
 
![Login to github](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/38kfy2mfii5yw0tvxe8y.png)

![Editing a blog entry](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pczri365wx4smn0w9gzo.png)
 
![Mobile view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a78v3heywvixkt63lzq1.png)
 
## Prerequisites
1. A github based project (basically a new commit triggers a new deployment)
2. Personal access tokens has been generated [Guide to create one](https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token)
3. nodejs installed


## Usage
1. as of now you would need to clone the repository: 
`git clone https://github.com/LadislavSzolik/cms4devs.git`
2. install dependencies with node: 
`npm isntall`
3. adapt the repository settings to your needs 
4. build it for production: 
`npm run build`
5. copy the generated output to your project

## Feedback
THis project is work in progress. However if you find it useful for you, let me know about the challenges you while using it. 

Thanks
A tal da alta coesão e baixo acoplamento
Tags: oop, ptbr
Published: 2021-06-09 19:24:16

Quando tive os primeiros contatos com a Orientação a Objetos, eu ouvia a frase "Alta coesão e baixo acoplamento" diversas vezes. O problema é que aquilo ficava vago, pois não era mostrado como obter essas vantagens. 

O acoplamento é o grau de ligação entre classes, se o acoplamento for alto as classes são engessadas, logo estão limitadas. Para ter baixo acoplamento entra em jogo as abstrações possibilitando trocar as implementações entre objetos.

O conceito de coesão é utilizado para definir o quanto as operações presentes em um objeto estão relacionadas umas com as outras. Basicamente, um objeto é coeso quando faz exatamente o que se propõe, sem ir além disso. Ou seja, é quando ele que possui operações que estão focadas em compor uma determinada responsabilidade, sem misturar conceitos que não estão relacionados entre si.

Por exemplo, [um objeto feito para salvar um cadastro no banco de dados e também gerar mensagens de log não é coeso, pois a responsabilidade de gerar uma mensagem de log não deveria estar nele.](https://raphael-da-silva.github.io/responsabidade-coesa/) Para que esse objeto fosse coeso, ele deveria ter somente métodos relacionados ao cadastro no banco de dados e os detalhes necessários para realizar esse tipo de operação. Já o log deveria ter uma classe própria para ele.

Na minha visão, a frase "alta coesão e baixo acoplamento" usa palavras rebuscadas e complexas que não ajudam muito os iniciantes. Talvez se a frase "Alta coesão e baixo acoplamento" fosse traduzida por "Objetos flexíveis e com responsabilidades limitadas" as coisas seriam mais intuitivas logo de início. 

Ou melhor, se a frase fosse traduzida por "use abstrações como parâmetros e mantenha só uma responsabilidade" tudo ficaria ainda mais evidente. 

### O papel da linguagem (não a de programação)

O propósito desse artigo foi fazer essa simplificação didática que evita o uso desses termos complexos e pouco intuitivos para quem inicia a aventura de entender melhor a Orientação a Objetos. 

A linguagem rebuscada e complexa dos termos do paradigma foi uma barreira que encontrei no começo, ou seja, a barreira não foi a linguagem da programação, mas sim a linguagem usada entre programadores no seu vocabulário.