teleren/devto huggingface dataset:
Getting started with Infrastructure as Code (IaC)
Tags: infrastructure, terraform, ansible, cloud
Published: 2022-10-08 16:05:13

Infrastructure as Code (IaC) tools allow you to manage your infrastructure using configuration files rather than through a graphical user interface. IaC allows you to build, modify, and manage your infrastructure in a secure, consistent, and repeatable way by defining resource configurations that you can version, reuse, and share.

Currently, in the tech world, there are many IaC tools and These are a few popular choices:

- Chef
- Otter
- Puppet
- Ansible
- Pulumi
- Terraform

![IaC Tools](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wn5xl8rzjcy6p9rg5m1n.png)

There are 2 different approaches for Infrastructure as Code tools,

1. A **declarative approach** defines the desired state of the system, including what resources you need and any properties they should have, and an IaC tool will configure it for you.

2. An **imperative approach** instead defines the specific commands needed to achieve the desired configuration, and those commands then need to be executed in the correct order.

Along with the approaches, there are 2 methods

1. **Push**: The control server sends the configuration to the target system
2. **Pull**: The configured server pulls its configuration from the control server


![IaC Details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8nm0qoawrpbln2y8nqjf.png)

The advantages of IaC tools are,

- Reduce expenses and other related costs
- Faster deployment speeds
- Error Reduction
- Consistent Infrastructures
- Eliminate configuration drift
- Allows infrastructure to be easily integrated into version control systems
- Provides the ability to introduce extensive automation for infrastructure management
- Eliminates the need for manual infrastructure provisioning and management

## IaC vs IaaS

IaC is not a derivative of infrastructure as a service (IaaS). These are two completely different concepts.

**Infrastructure as a Service** is one of the core cloud services: virtualised computing resources—servers, networking infrastructure, storage, etc.—are provided via the cloud service.

**Infrastructure as Code** is a tool that can be used to provision and manage infrastructure. It is not limited to only cloud-based resources. In fact, you apply IaC to a wide variety of environments, including on-premises.

References:

1. https://www.redhat.com/en/topics/automation/what-is-infrastructure-as-code-iac
2. https://learn.hashicorp.com/tutorials/terraform/infrastructure-as-code?
3. https://en.wikipedia.org/wiki/Infrastructure_as_code
4. https://www.bmc.com/blogs/infrastructure-as-code/
One Minute Notes: Master-Slave Database Replication
Tags: database, webdev, oneminutenotes
Published: 2022-10-08 15:58:10

I am staring a new section in my blog — the **One Minute Notes**, short notes on some important IT topics that will take only one minute to read and get a brief understanding of the concept. In this episode of **One Minute Notes**, let’s talk about two types of Master-Slave database replication.

⚡

**Data replication** is a process of copying data between application’s databases. This is done for consistency, reliability, and performance of a service. 

When replicating, the node where the data is modified and copied from is called **master,** and the node that receives data copy — a **slave.**

There are two types of data replication.


**Single Master** is the type of replication where data is modified on one (master) node only. After the changes are performed, the data from master database is replicated to slave database(s) that have read-only access for its clients.

This is the simple configuration of Master-Slave replication model, as it excludes any risk of conflicts.   

Single Master replication is useful when you want to achieve safe data reading or have an always up-to-date database backup.

Some of Single Master replication’s weaknesses are the difficulty of write requests’ scale up and the need of manual failover handling. 

**Multi Master**, in turn, is the configuration where data updating is available for multiple master nodes, that at the same time act as slaves for each other as well. As the data is modified and replicated everywhere “at the same time”, it enhances data’s availability in case one of the masters fail.

In this case it’s important to handle possible conflicts with concurrent changes on system level.

Multi Master replication is useful when you want to improve data writing and provide your service with a quick failover option. 

One of main Multi Master replication’s weaknesses is the risk of losing some of transaction in case of one of master nodes failure.

---
Did you find this **One Minute Note** helpful? Hit like and follow me to read more of them later🙂
How to Setup elasticsearch on Windows
Tags: elasticsearch, windows, tutorial, beginners
Published: 2022-10-08 15:35:44

Hi guys and welcome to another episode of the Elasticsearch series. In case you missed my previous series on How to Create a Full Autocomplete Search Application with Elasticsearch and NestJS, you can catch up [here](https://dev.to/airscholar/how-to-create-a-full-autocomplete-search-application-with-elasticsearch-and-nestjs-part-1-27k4).

In this article, I will be showing you how to setup elastic search on Microsoft Windows. PS: This process works on Microsoft Windows 8 and above :).

## Running Elasticsearch on Windows
Navigate to the [elasticsearch download page](https://www.elastic.co/downloads/elasticsearch) and choose windows from the dropdown, then click on the Download button (as shown below)

![elasticsearch download page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cs6sun6bf4hu5gudbh0.PNG)

Extract the downloaded file and navigate into the elasticsearch-8.4.3 folder (your version may be higher, but the process remains the same!)

![extracting elasticsearch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dd7txlil98l9j957fbk1.png)

In the bin folder, click on elasticsearch.bat
![elasticsearch bin folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xgj80d09weyoz71wfuc8.png)

Once you've done that, you should see something like this:
![Elastic password and enrolment token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wzm6pa4za5aq3n44wld.png)

On your browser, navigate to https://localhost:9200, you will be asked for username and password. By default username is **elastic** and password is shown on your terminal above

![navigating to elasticsearch on browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awak90serw2fjrlixkye.png)

Once you input the right username and password, you should see this welcome page. This page shows you some information about elasticsearch installed on your computer.
![Welcome page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/enfpui12sop0dqydeatb.png)

That's it! 

Elasticsearch is up and running on your windows machine! Yay!

Thanks for reading.
NestJs: สร้าง Unit test สำหรับทดสอบ Service ที่ใช้ typeorm + mysql
Tags: nestjs, testing, typescript, typeorm
Published: 2022-10-08 14:49:35

ใน `task.service.ts` ใช้ `Repository<Task>` ตามแบบของ Typeorm

```ts
// task.servic.ts

@Injectable()
export class TaskService {
  constructor(
    @InjectRepository(Task)
    private readonly taskRepository: Repository<Task>,
  ) {}
  ...
}
```
เราสามารถ config `TypeOrmModule.forRoot` และ `TypeOrmModule.forFeature` แบบเดียวกับที่ทำใน AppModule ได้เลย และจะให้ Clean ก็แยกออกมาอีก 1 file เพื่อจะได้ใช้ test กันส่วนอื่นๆ ด้วย

สร้าง `src/test-utils/TypeORMMySqlTestingModule.ts` 
```ts
// src/test-utils/TypeORMMySqlTestingModule.ts

import { TypeOrmModule } from '@nestjs/typeorm';

export const TypeORMMySqlTestingModule = (entities: any[]) => [
  TypeOrmModule.forRoot({
    type: 'mysql',
    host: process.env.MYSQL_HOST || 'localhost',
    port: 3306,
    username: process.env.MYSQL_USERNAME || 'nest',
    password: process.env.MYSQL_PASSWORD || 'nest',
    database: process.env.MYSQL_DATABASE || 'test',
    entities: [...entities],
    synchronize: true,
  })
  TypeOrmModule.forFeature([Task]),
];

```

imports เข้าไปใน TestingModule 

```ts
// task.service.spac.ts
...
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [...TypeORMMySqlTestingModule([Task])],
      providers: [TaskService],
    }).compile();

    service = module.get<TaskService>(TaskService);
  });
...
```

Run test เลย

```sh
$ yarn test src/task/task.service.spec.ts
```

_enjoy your test_

### Ref
- https://stackoverflow.com/a/55717767
- https://dev.to/webeleon/unit-testing-nestjs-with-typeorm-in-memory-l6m
Angular Dart 基礎 -- Part 01 マウスイベントの処理
Tags: angular, dart
Published: 2022-10-08 14:48:10

## 前提

前回の記事で環境構築ができていること。

Angular Dart はマイナーで、
Web 上でさくっと実行できるサイトがないので

---

## エレメントにマウスが被さった時(ホバー)

https://gray-code.com/javascript/event-list-of-mouse/

Angular Dart の記事はなかったが、
HTML 要素の記事を参考に調べた。

enter と leave
overt と out

これらのイベントが書けるのを確認した。

```html
<h1
    (mouseenter)="mouseEnter()"
    (mouseleave)="mouseLeave()"
    >ホバーされるエレメント enter or leave
</h1>
```

```dart
  mouseEnter() {
    print("mouseEnter");
  }
  mouseLeave() {
    print("mouseLeave");
  }
```

```html
<h1
    (mouseover)="mouseOver()"
    (mouseout)="mouseOut()"
    >ホバーされるエレメント2 over or out
</h1>
```

```
  mouseOver() {
    print("mouseOver");
  }
  mouseOut() {
    print("mouseOut");
  }
```

こうやってネストされていないコンポーネントの場合は、
mouse\over, mouse\out 
であろうとも反応するが、

要素がネストになっている場合は、
mouse\enter, mouse\leave
これらのみ反応する。

自分の環境では未検証。

---

## エレメントがクリックされた時

https://angulardart.xyz/guide/user-input#binding-to-user-input-events

```html
<h1
    (click)="(handleClick)"
    >クリックされるエレメント
</h1>
```

```dart
  handleClick() {
    print("Clicked");
  }
```

このように、click に () をつけて関数名を渡せば
クリックされた時に dart 側に定義した関数が実行できる。

---

## エレメントからカーソルが外れて外部がクリックされた時(ブラー)

https://angulardart.xyz/guide/user-input#on-blur

```html
<input
  (blur)="(handleBlur)"
  placeholder="外がクリックされるエレメント"
>
```

```dart
  handleBlur() {
    print("Clicked Outside");
  }
```

こちらは入力できるエレメントのみ、
エレメントからカーソルが外れて外部がクリックされた時に発動できる。

フォームに入力していて、外側をクリックしたら保存されて欲しい時に便利そう。
Hacktoberfest 2022 t-shirt
Tags: hacktoberfest, programming, opensource, github
Published: 2022-10-08 14:33:40

This preview t-shirt hacktoberfest 2022

Dark Design

![Hacktoberfest 2022 t-shirt dark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7anw52scivv9nrhgmsk0.png)

Light Design

![Hacktoberfest 2022 t-shirt light](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkuak9iekdeimu5k30z6.png)

Which do you think is better?
Angular Dart 基礎 -- Part 00 環境構築と Hello World
Tags: angulardart, dart
Published: 2022-10-08 14:27:16


## dart のインストール

```php
asdf plugin add dart
asdf list all dart
asdf install dart 2.13.4
asdf global dart 2.13.4
```

asdf で dart 2.13.4 は取ってきて、
グローバルでのデフォルトにしてある

---

## webdev と ngdart を有効化。

https://angulardart.xyz/guide/setup#create-a-starter-project

angular dart の公式の doc を参考に

```php
dart pub global activate webdev

Package webdev is currently active at version 2.7.5.                                                        
Resolving dependencies... (2.3s) 

+ args 2.3.1                                                                                                
+ async 2.8.2 (2.9.0 available)                                                                             
+ browser_launcher 1.1.1 

Activated webdev 2.7.5.
```

dart pub global activate で
webdev に必要なライブラリを取ってきて、有効化し

```
dart pub global activate ngdart
```

ngdart も同様に有効化する[


これで webdev と ngdart がこのプロジェクトで有効になった。

もうひとつ、PATH を通す必要が有る。

```sh
  export PATH="$PATH":"$HOME/.pub-cache/bin"
```

これを .zshrc などに入れることで、2つのコマンドが使えるようになる。

---

## ngdart でプロジェクト作成

```php
ngdart create testApp

[Info] Creating project...
[SUCCESS] Created project "testapp"

[Info] Running 'pub get' in the project folder... 6.0s
[SUCCESS] Completed!
```

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

これで Angular Dart のアプリが作成される。

---

## webdev でプロジェクト起動

```php
❯ webdev serve 
[INFO] Building new asset graph completed, took 2.0s
[INFO] Checking for unexpected pre-existing outputs. completed, took 2ms
[INFO] Serving `web` on http://127.0.0.1:8080
...
[INFO] Succeeded after 55.4s with 6322 outputs (13311 actions)
```

起動に 55 秒かかって

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

デフォルトの TODO アプリが起動した。

----

## App Component の中身を付け足す

```dart
@Component(
  selector: 'my-app',
  styleUrls: ['app_component.css'],
  templateUrl: 'app_component.html',
  directives: [TodoListComponent],
)
class AppComponent {
  // Nothing here yet. All logic is in TodoListComponent.
}
```

css と html が記載されている Component と

ロジックを書く クラスが入っている

```html
<h1>My First AngularDart App</h1>

<h2> {{ message }} </h2>

<todo-list></todo-list>
```

html に message を付け足し

```dart
class AppComponent {
  var message = "Hello Angular Dart";
}
```

dart に定義する

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

これで Hello World できた！！！

---

## まとめ

Angular Dart でのフロントエンド環境を作るためには

Dart をインストールして、
dart コマンドで ngdart, webdev をインストールして
ngdart でプロジェクトを作り
webdev でプロジェクトを起動する。

Hello World は React の App.js のように
app_component.{dart,html} に書く。
I got my Hacktoberfest2022 Badge 🎉
Tags: hacktoberfest, badge, html, opensource
Published: 2022-10-08 14:25:07

Today I got my Holopin badge of which i participated in hacktoberfest fest. It was my first ever fest. I feel very overwhelmed about it. 🎉🎊
![@varshithvh's Holopin board](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w668y7s0ylpfla4oyg48.png)
- Thank you holopin and hacktoberfest for the badge 👍🎊🔥
Top 5 Free Websites to Learn HTML for Beginners
Tags: html, webdev, beginners, tutorial
Published: 2022-10-08 14:02:32

Yeah, I would have started with a joke or something else but let's dive in.
Let me guess, you've been searching for learning HTML for free to be a boss in it. You've come to the right place.

I'll show you 5 (five) places on the web to learn HTML for free and trust me you'll be perfect but before that.

## What is HTML?
HTML stands for HyperText Markup Language and it looks like this.


```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
	<script src="index.js"></script>
  </body>
</html>
```

You'll learn about it in the resources I'll be sharing.

### Resources


#### 1. [freeCodeCamp](https://www.freecodecamp.org/)
freeCodeCamp is a non-profit organization that consists of an interactive learning web platform, an online community forum, chat rooms, online publications and local organizations that intend to make learning web development accessible to anyone.

This is where I learnt HTML and I have been good at it with everyday improvements. It covers everything necessary for you to be up to speed. You also get a certificate upon completion of projects.


#### 2. [W3Schools](https://www.w3schools.com/)
W3Schools is a freemium educational website for learning to code online. Initially released in 1998, it derives its name from the World Wide Web but is not affiliated with the W3 Consortium. W3Schools offers courses covering all aspects of web development. W3Schools also publishes free HTML templates.

From learning to templates, W3Schools covers it all. You can also forward your Web Development journey with W3Schools.


#### 3. [Geeksforgeeks](https://www.geeksforgeeks.org/html/?ref=ghm)
A Computer Science portal for geeks. It contains well-written, well thought and well-explained computer science and programming articles including tutorials. 
They also provide practice quizzes if you want to test yourself.


#### 4. [ValleyOfCode](https://thevalleyofcode.com/html/)
The Valley of Code is a project by Flavio Copes. This site exists to provide you with helpful resources to learn how to code with a particular focus on Web Development and its technologies including HTML. 😁
You can also download his HTML handbook at the link above.


#### 5. [Learn-HTML](https://learn-html.org/)
Learn HTML provides an interactive tutorial that explains how to build HTML & CSS websites step by step.


> I hope you find an amazing resource for you to learn on/with. My name is [Efosa Collins EVBOWE](https://github.com/efecollins) and I will write to you next week.

You can follow me on Twitter @ [Efe Collins](https://twitter.com/EfeCollins7). Do have a nice week!
Binary Tree Level Order Traversal
Tags: javascript, leetcode
Published: 2022-10-08 14:00:54

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Solution 1 : keeping seperate row & then pushing rows in level
```js
const levelOrder = (root) => {
  // BFS Level Order
  // Learning this method will help with all level order problems, graphs and trees

  if (!root) return []; // Edge case if root is null

  // First we have a queue intialized with the root
  let q = [root];
  let res = []; // our result array

  while (q.length) {
    // BFS continues till the queue is empty
    const len = q.length; // We need a helper variable for our inner level for loop, this helps us only process for this level

    // This loop is for processing all queue items on each LEVEL of the tree
    const levelArray = []; // Used to hold all values from this level
    for (let i = 0; i < len; i++) {
      const n = q.shift(); // We get first item in queue
      levelArray.push(n.val); // Push node value to the levelArray

      // We need to queue up all the children of the current node, if they exist
      n.left && q.push(n.left);
      n.right && q.push(n.right);
      // The above is the same as:
      // if(n.left) q.push(n.left)
    }

    // Once we process all nodes for this level, push levelArray to result array
    res.push(levelArray);
  }

  return res;
};

```
Solution 2 : keeping same array levels & by default keeping empty & pushing element in empty level
```js
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
 if (!root) return [];
  let queue = [root];
  let levels = [];
  while (queue.length > 0) {
    let levelSize = queue.length;
    levels.push([]);
    for (let i = 0; i < levelSize; i++) {
      let curr = queue.shift();
     levels[levels.length - 1].push(curr.val);

      if (curr.left) queue.push(curr.left);
      if (curr.right) queue.push(curr.right);
    }
  }

  return levels;
};
```

solution 3: via recurssion

```js
var levelOrder = function(root) {
    let result = [];
    let level = 0;
    const readNode = function(node, level) {
        if (!node) return;
        if (!result[level]) {
            result.push([node.val]);
        } else {
            result[level].push(node.val);
        }
        readNode(node.left, level + 1);
        readNode(node.right, level + 1);
    }
    readNode(root, level);
    return result;
};

```
Trabalhando com interfaces em Go
Tags: go, tutorial
Published: 2022-10-06 20:58:39

Interface é um tipo de dado que define um conjunto de métodos.
Por exemplo, podemos criar uma interface chamada `FormaGeometrica` que todas as formas geométricas deverão implementar pois todas elas possuem um perímetro e uma área.

```go
type FormaGeometrica interface {
    Perimetro() float32
    Area() float32
}
```

Podemos criar, por exemplo, o tipo `Circulo` que implementa essa interface da seguinte forma:

```go
type Circulo struct {
	raio float32
}

func NewCirculo(raio float32) Circulo {
	return Circulo{
		radius: raio,
	}
}

func (c Circulo) Perimetro() float32 {
	return 2 * math.Pi * c.raio
}

func (c Circulo) Area() float32 {
	return math.Pi * c.raio * c.raio
}
```

Note que não tem nenhuma indicação explícita indicando que o tipo `Circulo` implementa a interface `FormaGeometrica`. Isso ocorre porque em Go isso é feito de forma implícita, ou seja, se um tipo implementa os métodos contidos em uma interface, esse tipo automaticamente implementa essa interface.

Como não especificamos explicitamente que um tipo implementa uma interface específica, não é possível gerar um erro de compilação caso o tipo não implemente essa interface, mas isso pode ser resolvido com um truque simples. Podemos adicionar a seguinte linha no nosso código:

```go
var _ FormaGeometrica = NewCirculo(3)
```

Aqui estamos usando o identificador em branco para definir uma variável que nunca será utilizada no código. Como essa variável é do tipo da interface que criamos, teremos um erro de compilação caso a `struct Circulo` não implementar essa interface. Fazendo isso, conseguimos forçar nossos tipos a implementar alguma interface em específica.

Outro ponto importante é saber que existe a `interface{}` que nada mais é do que uma interface que não possui nenhum método, ou seja, todos os tipos de dados implementam essa interface. Isso significa que se algum método receber  um parâmetro do tipo `interface{}`, qualquer variável poderá ser enviado nesse parâmetro, independente do tipo.

Vamos criar agora mais um tipo para exemplificar:

```go
type Quadrado struct {
	lado float32
}

func NewQuadrado(lado float32) Quadrado {
	return Quadrado{
		lado: lado,
	}
}

func (c Quadrado) Perimetro() float32 {
	return 4 * c.lado
}

func (c Quadrado) Area() float32 {
	return c.lado * c.lado
}
```

Agora podemos usar esses tipos em variáveis do tipo interface de `FormaGeometrica`. No código abaixo está sendo criada uma slice do tipo `FormaGeometrica` que pode armazenar variáveis tanto do tipo `Circulo` quanto do tipo `Quadrado`. Ao iterar sobre os elementos dessa slice, não precisamos saber qual o tipo concreto de cada elemento, basta utilizar os métodos definidos pela interface.

```go
package main

import "fmt"

type FormaGeometrica interface {
	Perimetro() float32
	Area() float32
}

func main() {
	var formas []FormaGeometrica
	circulo := NewCirculo(2)
	quadrado := NewQuadrado(2)
	formas = append(formas, circulo)
	formas = append(formas, quadrado)

	for _, f := range formas {
		fmt.Println(f.Perimetro())
	}
}
```
PostgresSQL unit-2
Tags: postgres, sql, javascript, database
Published: 2022-10-08 13:58:45

> ## 2-dars

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


Table yaratish

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


Jadval yaratish qonun qoidalari

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

Jadval o'chirish qonun qoidalari

```
DROP TABLE users;
```

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



> Best prictise creating table

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