teleren/devto huggingface dataset:
GitHub Action using pre-installed Postgres
Tags: githubactions, rails, postgres, github
Published: 2023-01-22 14:05:25

Until now I used something like this for Postgres in GitHub Actions:

```yaml
jobs:
  the_job_that_needs_postgres:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:latest
        env:
          POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }}
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432

    steps:
      # your steps
```

Then I saw that the [GitHub's Ubuntu Runner Image](https://github.com/actions/runner-images/) actually comes with a pre-installed Postgres version, but the service is not activated by default.

So instead of using the `postgres:latest` image as a service, we could use that pre-installed Postgres.

In order to make that work, we have to add one step to the CI job that starts the `postgresql.service` and one step that creates a `runner` user in the database, so that the workflow's session user can connect to the database.

```yaml
jobs:
  the_job_that_needs_postgres:
    runs-on: ubuntu-latest

    steps:
      - name: Start PostgreSQL
        run: |
          sudo systemctl start postgresql.service
          pg_isready
          sudo -u postgres createuser -s -d -r -w runner

      # your steps
```

Here's what the `createuser` flags do:

* `-s` : User will be a superuser
* `-d` : User can `CREATE DATABASE`
* `-r` : User can `CREATE ROLE`
* `-w` : It won't prompt for a password.

This approach **takes only a few seconds (3 - 5 seconds) to startup** whereas the former setup takes between 20 - 30 seconds.

On the downside **you can't specify the Postgres version**, you have to live with the version that comes with the runner image.

At the time of writing `ubuntu-22.04` contains Postgres `14.6`.

## Database config for Rails

For Rails projects this is how a minimal `database.yml` could look like using the setup above:

```yaml
test:
  adapter: postgresql
  encoding: unicode
  database: github_actions_ci_db
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: runner
```

Behold:

* `username` is set to `runner`
* `hostname` is not required

(It might even **not** work if you provide the `hostname`, like `localhost` or `127.0.0.1`.)

## Credits

(Cover photo by [Nathan Queloz](https://unsplash.com/@nathan030997?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/photos/peXYfMaIDh8?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText))
How to Setup/Enable BitBucket Terminal Access on a Mac
Tags: ssh, bitbucket, git, mac
Published: 2023-11-12 04:17:29

---
title: How to Setup/Enable BitBucket Terminal Access on a Mac
published: true
date: 2023-01-22 14:00:42 UTC
tags: #ssh #bitbucket #git #mac
canonical_url: https://blog.mikaeels.com/how-to-setup-bitbucket-terminal-access-on-mac
---

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

Setting up an SSH key can be a confusing and tedious process, but it doesn't have to be. This blog post will show you a simple and straightforward method for installing an SSH key on your Mac.

### Step 1: Generate the SSH Key

To generate your SSH key, open a Terminal window and type:

```
~ ssh-keygen
```

Press enter a few times to go through the prompts. This will create two files in a hidden folder in your home directory, called "`id_rsa`" & "`id_rsa.pub`." You can verify that the files have been created by typing:

```
~ ls ~/.ssh
```

`id_rsa id_rsa.pub`

in the Terminal.

### Step 2: Add the Key to SSH-Agent

To ensure that macOS remembers to use your SSH key after a restart, you will need to add it to the SSH-Agent. To do this, type:

```
~ eval ssh-agent
```

`Agent pid xxxx`

in the Terminal, then:

```
~ ssh-add -K ~/.ssh/id_rsa
```

to add the key to the agent.

### Step 3: Remember After Restart

To make sure that your config file is set up correctly, type:

```
~ touch ~/.ssh/config
```

and

```
~ open ~/.ssh/config
```

in the Terminal. This will open the config file in a text editor. Ensure the config file includes the following lines:

```
Host * 
UseKeychain yes
```

### Step 4: Add Public Key to BitBucket

To add your public key to BitBucket, copy the key to the clipboard by typing:

```
~ pbcopy < ~/.ssh/id_rsa.pub
```

in the Terminal. Then, go to this URL: [**https://bitbucket.org/account/settings/ssh-keys/**](https://bitbucket.org/account/settings/ssh-keys/) and click "`Add Key.`" Paste the key into the textbox and add a label (e.g. "MacBook Key").

### Step 5: Verify Everything Works

To verify that your SSH key is working correctly, type:

```
~ ssh -T git@bitbucket.org | grep logged
```

in the Terminal. If everything is set up correctly, you should see the message "`logged in as [YOUR USERNAME].`"

Following these simple steps, you can easily set up an SSH key on your Mac and start accessing your BitBucket repositories through the terminal. No more confusion or long-winded instructions!
5 passos pra ser um dev melhor
Tags: beginners, programming, javascript, webdev
Published: 2023-01-22 13:55:43

Você quer se tornar um desenvolvedor de software melhor? Ótimo, você veio ao lugar certo! Aqui estão 5 passos infalíveis para se tornar um gênio da programação em questão de minutos.

1. Organize seu código como se sua vida dependesse disso. Isso inclui não apenas deixar o código limpinho e bem formatado, mas também usar nomes de variáveis e funções que possam ser lidos por extraterrestres e adicionar comentários que possam ser entendidos por crianças de 5 anos. Lembre-se: se você não consegue entender o que escreveu há 5 minutos, imagine outra pessoa tentando entender daqui a 5 anos.

2. Testes unitários são como a escova de dentes dos desenvolvedores. Você não precisa gostar de fazer, mas precisa fazer para ter saúde. E não se preocupe, eles não doem. Eles apenas ajudam a garantir que suas mudanças não afetem outras partes do sistema e que você não precise explicar por que o sistema parou de funcionar para o seu chefe às 3 da manhã.

3. Depuração de código é como ir ao dentista. Não é divertido, mas é necessário.
Use ferramentas de depuração para identificar e corrigir problemas no código rapidamente e evitar ter que explicar para o seu chefe por que o sistema parou de funcionar às 3 da manhã.

4. Tecnologias estão mudando mais rápido do que as tendências de moda. Fique por dentro das novidades e esteja 
disposto a aprender. Isso inclui aprender novas linguagens de programação, frameworks e bibliotecas. Lembre-se: se você não estiver aprendendo, estará perdendo.

5. Compartilhe conhecimento e absorva feedbacks. Não tenha medo de pedir ajuda, dar feedbacks ou explicar algo para alguém. Lembre-se: você não sabe tudo e é sempre possível aprender algo novo. E não se esqueça de compartilhar o conhecimento que você adquirir, afinal, o conhecimento é como a pizza: melhor compartilhada.

Em resumo, esses são os 5 passos infalíveis para se tornar um desenvolvedor de software melhor. Lembre-se de organizar o código, fazer testes unitários, usar ferramentas de depuração, ficar por dentro das novidades e compartilhar conhecimento e absorver feedbacks.
Who will win the AI chatbot wars: Sparrow or ChatGPT?
Tags: openai, gpt3, chatgpt, ai
Published: 2023-01-22 13:53:03

Businesses are always seeking for ways to innovate and enhance as the world depends more and more on technology. Artificial intelligence (AI) is one sector that has grown significantly in recent years, and OpenAI's ChatGPT is one key player in this industry. This AI chatbot has generated a lot of buzz in the tech community, and there are even discussions about it perhaps dislodging Google's search engine in the future.

Google has declared a "code red" and directed some teams to concentrate on developing AI products in response to this threat. However, it appears that the company may already have a solution in the form of **Sparrow**, a chatbot that DeepMind is creating.

DeepMind, which was acquired by Alphabet (Google's parent company) for $500 million in 2014, is one of the world's leading AI labs. They are most notable for their software platform AlphaFold, which has solved the "protein folding problem" and is considered one of the most important achievements in modern science.

**Sparrow** , which was introduced in September 2022, is similar to ChatGPT in that it is trained with human feedback to make it more helpful, accurate, and harmless. However, what sets **Sparrow** apart is its access to the internet through Google, allowing it to integrate up-to-date information into its responses and provide sources. This could potentially change the way 4.3 billion people work and use the internet on a daily basis if it gets integrated into all Google apps, such as Google Docs, Android, YouTube, and Gmail.

{% embed  https://twitter.com/AiBreakfast/status/1613696625142280193?gpt-killer-ai-sparrow-soon-all-you-need-to-know %}

{% embed https://twitter.com/DanFitzTweets/status/1615758252691841026?r-need-to-know %}

But, there's a catch. Google is facing the Innovator's Dilemma, which is a phenomenon where established companies have difficulty adopting new technologies or business models that disrupt their traditional markets. An AI-powered chatbot like **Sparrow** could potentially disrupt Google's traditional search market, as they make around 60% of their revenue from search. So, the only thing stopping Google from winning the AI race is Google itself.

It will be interesting to see how this plays out in the coming months and years. Will Google be able to overcome the Innovator's Dilemma and fully embrace the potential of **Sparrow** ? Only time will tell.

References : 
[Improving alignment of dialogue agents via targeted human judgements](https://arxiv.org/pdf/2209.14375.pdf)

[Building safer dialogue agents](https://www.deepmind.com/blog/building-safer-dialogue-agents)

[Google may use Deepmind’s Sparrow as ChatGPT competitor](https://the-decoder.com/google-may-use-deepminds-sparrow-as-chatgpt-competitor/)
JS puro é melhor que usar framework? Reinventar a roda é legal ?
Tags: javascript, beginners, programming, productivity
Published: 2023-01-22 13:50:02

Ah, você acha que é um verdadeiro desenvolvedor porque prefere fazer tudo com JavaScript puro? Por favor, acorde para a realidade, o mundo evoluiu e agora é tudo sobre frameworks. Quem tem tempo para escrever código manualmente quando você pode usar uma já feita e testada? E você acha mesmo que alguém vai esperar você terminar de escrever manualmente todas as funcionalidades antes de adicionar um framework? Isso é tão ultrapassado quanto usar uma máquina de escrever.

## Desvantagens em usar JS puro
Usar JavaScript puro para projetos complexos pode ser problemático por várias razões. Algumas delas incluem:

1. Falta de estrutura: Quando você está trabalhando com JavaScript puro, você precisa criar sua própria estrutura para organizar o código e garantir que ele seja escalável e fácil de manter. Isso pode ser difícil de fazer e levar a códigos bagunçados e desorganizados.
2. Reusabilidade de código: Quando você está trabalhando com JavaScript puro, é difícil criar componentes ou funcionalidades que possam ser facilmente reutilizadas em outras partes do seu projeto. Isso pode levar a muito tempo e esforço para desenvolver recursos similares novamente e pode aumentar a complexidade do projeto.

3. Gerenciamento de estado: Gerenciar o estado de aplicativos complexos pode ser desafiador quando você está trabalhando com JavaScript puro. Isso pode levar a códigos confusos e difíceis de manter.

4. Falta de recursos: frameworks e bibliotecas oferecem uma variedade de recursos e ferramentas para ajudar a desenvolver aplicativos modernos e de alta qualidade, enquanto ao trabalhar com javascript puro você precisa desenvolver essas ferramentas sozinho.

5. Acessibilidade e compatibilidade: Ao trabalhar com javascript puro, é mais difícil garantir que o seu aplicativo seja acessível para todos os usuários e compatível com todos os navegadores.

Enquanto é possível desenvolver projetos complexos com javascript puro, é muito mais fácil e eficiente usar frameworks e bibliotecas para ajudar a gerenciar esses desafios.



## Conclusão
Bom... Só falta me dizer também que prefere escrever SQL puro? Num mundo onde query builders e ORMs dominam. Quem tem tempo para escrever comandos SQL manualmente quando você pode usar uma alternativa bem mais direta? E você acha mesmo que alguém vai esperar você terminar de escrever manualmente todas as consultas antes de usar uma query builder ou ORM? Bem vindo a 2023!
Refactoring RATOM with HTMX
Tags: email, htmx, django, react
Published: 2023-01-22 13:39:53

### What am I doing?

I am going to refactor the [RATOM server application](https://github.com/StateArchivesOfNorthCarolina/ratom-server) into an [SSR app using HTMX](https://github.com/JeremyGibson/ratom_htmx). The `ratom-server` application was developed a few years ago, before HTMX really hit the scene.

My idea here is to have a series of posts where I track the progress of my efforts to both really dig in and understand how to fully leverage HTMX, but also to refactor `ratom-server` so it no longer depends on [react-web](https://github.com/StateArchivesOfNorthCarolina/ratom-web) and is: simpler, easier to maintain, easier to deploy, easier to use, and has testing that ensures confidence in changes made in the future.

Don't get me wrong the app that my colleagues and I developed was and is a very cool and useful product. But like all react apps it requires a thousand hoops and tons of tooling to link the front end to the back end.

I don't know if I will succeed, but I am certain that I will learn a little more about how to create a modern, powerful app that applies the principles of HATEOS.

Wish me luck!
How to install Terraform for Mac and get started using it
Tags: terraform, beginners, iac
Published: 2023-01-22 13:29:28

In this blog, I write how to install Terraform for Mac and get started using it.

1. Install Terraform on Mac
2. Verify that Terraform is installed
3. Basic commands of Terraform

#### 1. Install Terraform on Mac
To install, run the following two commands:
```
% brew tap hashicorp/tap
% brew install hashicorp/tap/terraform
```
But for my Mac, I got the following error message.
```
Error: No developer tools installed.
Install the Command Line Tools:
  xcode-select --install
Error: 'git' must be installed and in your PATH!
```
By installing xcode and git, I was able to fix the error message.
```
% xcode-select --install
% brew install git
```
### 2. Verify that Terraform is installed
Now I may have managed to get Terraform to install completely.
So I need to check if this is the case with the following commands.
```
% terraform --version
Terraform v1.3.7
on darwin_arm64
```
### 3. Basic commands of Terraform
1. Initialise Terraform
You need to initialise Terraform before using it.
```
% terraform init
Terraform initialized in an empty directory!
```
2. Check the status of Terraform
To check the current status of your infrastructure resources, use the following command
I get an error because I have nothing configured at the moment.
```
% terraform plan
│ Error: No configuration files
```
3. Apply Terraform
Apply Terraform to make changes to the infrastructure.
```
% terraform apply
│ Error: No configuration files
```
4. Deleting Terraform
You can use the following commands to delete an infrastructure resource.
```
% terraform destroy
```
5. Managing Terraform Status
You can use the following commands to check and manage your current state.
```
% terraform state list 
% terraform state show <resource_name>
% terraform state mv <resource_name> <new_name>
% terraform state pull
% terraform state push
```
I have nothing to configure at the moment. I will use these commands when I create my infrastructure resource.
Publish Angular Library to NPM
Tags: angular, library, npm
Published: 2023-01-22 13:26:56

Install Angular cli to create Angular project

```bash
npm install -g @angular/cli
```

Run the cli command to create new Angular Project 

```bash
ng new test-library-angular
```

Navigate to the project

```bash
cd test-library-angular
```

Next generate library using cli command

```bash
ng generate library ng-library-log
```

Import `NgLibraryLogModule` into `app.module.ts`

```tsx
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgLibraryLogModule } from 'projects/ng-library-log/src/public-api';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgLibraryLogModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

Update `package.json` from `dist/ng-library-log` as shown below

```tsx
{
  "name": "ng-library-log",
  "version": "0.0.1",
  "author": {
    "name": "Manthan Ank"
  },
  "keywords": [
    "angular",
    "javascript"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/manthanank/test-libary-angular.git"
  },
  "description": "Test Library in angular",
  "peerDependencies": {
    "@angular/common": "^15.1.0",
    "@angular/core": "^15.1.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "sideEffects": false,
  "module": "fesm2015/ng-library-log.mjs",
  "es2020": "fesm2020/ng-library-log.mjs",
  "esm2020": "esm2020/ng-library-log.mjs",
  "fesm2020": "fesm2020/ng-library-log.mjs",
  "fesm2015": "fesm2015/ng-library-log.mjs",
  "typings": "index.d.ts",
  "exports": {
    "./package.json": {
      "default": "./package.json"
    },
    ".": {
      "types": "./index.d.ts",
      "esm2020": "./esm2020/ng-library-log.mjs",
      "es2020": "./fesm2020/ng-library-log.mjs",
      "es2015": "./fesm2015/ng-library-log.mjs",
      "node": "./fesm2015/ng-library-log.mjs",
      "default": "./fesm2020/ng-library-log.mjs"
    }
  }
}
```
Build the library generated

```bash
ng build ng-library-log
```

Navigate to the folder built

```bash
cd dist/ng-library-log
```

To publish to NPM enter the command mentioned below

```bash
npm publish
```

Structure of Project

![project-structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47uzyp1qkj8ccbkpq1yp.png)

Link to Package: [ng-library-log](https://www.npmjs.com/package/ng-library-log)
Introduction to VPC ☁️
Tags: aws, vpc
Published: 2023-01-22 13:18:23

VPC is Virtual Private Cloud in simpler words your own private data center but in cloud. VPC lets you take control over networking of your resources by Route tables, subnets, internet gateway & Security groups.
Let's dig more on these basic term I have mentioned here:

**Subnets**
_Subnets let us divide a network into little chunks & those chunks(subnets) can be allocated to different team over an organization to make networking more efficient & secure._

**Route Tables**
_Route tables look after Who can talk to what? Route table allow routes/IP by which VPC will be connected. We can set up rules(routes) to allow directing of traffic._

**Internet Gateway**
_Internet Gateway allows the communication between VPC & internet. Without IGW resources within a VPC won't be able to talk to internet._

**Security Groups**
_We can say Security Groups are firewall around instances. They regulate access to ports & control inbound/ outbound traffic from other instances.
By default all outbound traffic is allowed & all inbound is block by default._

AWS provides a number of efficient, secure connectivity options to help you get the most out of AWS when integrating your remote networks with Amazon VPC. Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources into a virtual network that you’ve defined. This virtual network closely resembles a traditional network that you’d operate in your own data center, with the benefits of using the scalable infrastructure of AWS.

_Happy Cloud Engineering☁️_
Form validation with react hook form and yup
Tags: javascript, react, beginners
Published: 2023-01-22 13:18:10

## Installation
Let's install the code dependencies
```javascript
npm install react-hook-form @hookform/resolvers yup

```

## Implementation
Create the schema for validation

```javascript
import * as yup from "yup";

const Schema = yup
  .object({
    name: yup.string().required("Name is required."),
    model: yup.string().required("Model name is required."),
  })
  .required();
```

Get the following from the useForm() hook

```javascript
import { FieldValues, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(Schema),
  });
```

Let's create a simple form
```javascript
<form
    className="bg-white"
    onSubmit={handleSubmit(onSubmitHandler)}
    encType="multipart/form-data"
    id={formId}
  >
    <div className={formInputClass}>
      <Label label="Product Name" htmlFor="name" isRequired />
      <input
        className={customFieldStyle}
        id="name"
        {...register("name")}
        type="text"
        placeholder="Enter the product name"
      />
      <FormErrorText errorMsg={errors?.name?.message} />
    </div>

    <div className={formInputClass}>
      <Label label="Model" htmlFor="model" isRequired />
      <input
        className={customFieldStyle}
        id="model"
        {...register("model")}
        type="text"
        placeholder="Enter the model name"
      />
     <FormErrorText errorMsg={errors?.model?.message} />
    </div>
  </form>
```

Our submit handler which also resets our form after submission:

```javascript
const onSubmitHandler = (values: FieldValues) => {
    console.log({ values});
    // after submit code
    reset();
  };
```

Our form looks like this


![Product Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vlcatqi1bf24dsa07cvk.png)

When we submit without filling out required fields we show these
validation messages:


![Form errors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztmid5p6d9nj9rcocjr3.png)
SaaS for SME or mid- size enterprises?
Tags: saas, startup
Published: 2023-01-22 13:04:26

#discuss

This is defenitely a funding winter. But as founders, we need to stay strong and learn from all the mistakes.


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



Are you a founder building a SaaS solution？What do you think will be the difference of building and selling your SaaS to SMEs (headcounts 1-99) versus to Mid-size enterprises (headcounts 100-999)?

Share your thoughts and learning with us below.
02: The Product...
Published: 2023-01-22 12:46:47

We'll build an eShop for startup 'FakeST' that sells T-shirts with bespoke designs. So we are looking at a couple of services.

- Client mobile app (android)
- Client web app (react, time permitting)
- API gateway (spring boot; web)
- Identity microservice (postgres, spring boot)
- Catalog microservice (postgres, spring boot)
- Ordering microservice(postgres, spring boot)
- Cart microservice(redis, spring boot)
- Payment microservice(postgres, spring boot)
- Email microservice (redis, spring boot; batch)
- Design Service (postgres, spring boot, S3)
- Event bus (RabbitMQ)

And on the OPs side,

- Gitops
- Image Registry
- Kubernetes
- Helm
- Istio
- Grafana 
- Prometheus
- Loki
- Zipkin
- Backups