teleren/devto huggingface dataset:
Debugging HAProxy containers
Tags: devops, docker
Published: 2020-05-02 03:32:37

HAProxy is a popular solution for load balancing and reverse proxy needs. So I will cut to the chase and show you how you can get more insights into your HAProxy container. 

In this guide, I am assuming the you are running the [offical HAProxy image](https://hub.docker.com/_/haproxy). 

In order to debug your HAProxy container you need to have this program `socat` installed on your HAProxy container. Using this program you can have insights related to the running instance of HAProxy inside the container. 

In your `Dockerfile`, add the following line to install `socat` into your container.

```
RUN apt-get update && apt-get install -y socat && rm -rf /var/lib/apt/lists/*
```

Now build and start your container normally. Once started, log into the container by issuing the following command.
```
docker exec -it <haproxy_container_id> sh
```

After you are logged into the container, you can start the `socat` program in interactive mode like this.

```
socat /var/run/haproxy.sock stdio

prompt
```

Now you can issue commands like `show acl`, `show info`, `show errors`, `show env` etc., to get more information about the running process. You can head over to this [document](https://www.youtube.com/channel/UCUmQhjjF9bsIaVDJUHSIIKw) to see the full list of available commands.

I hope someone will find this quick guide useful. Thanks for reading and check me out on [YouTube](https://www.youtube.com/channel/UCUmQhjjF9bsIaVDJUHSIIKw) as I love sharing more development related tips.
Use `getpwnam` to get uid by user's login name - C Lang
Tags: c, linux
Published: 2020-05-02 03:30:45

We can use `getpwnam` to get user's system UID by its login name, the function is:

```c
#include <pwd.h>

struct passwd* getpwnam(const char*name);
```
And the passwd struct is:
```c
struct passwd {
  char* pw_name;    // login name (username) 
  char* pw_passwd;  // Encryped password
  uid_t pw_uid;     // User ID
  gid_t pw_gid;     // Group ID
  char* pw_gecos;   // Comment
  char* pw_dir;     // Initial working (home) dir
  char* pw_shell;   // login shell
}
```

Example:
```c
#include <stdio.h>
#include <pwd.h>
#include <string.h>

int main() {
    char name[30] = {0};
    struct passwd* pwd;
    size_t nread = 0;
    while (1) {
        printf("Query UID for login name: ");
        fgets(name, sizeof(name), stdin);

        nread = strlen(name);
        if (name[nread-1] == '\n') {
            name[strlen(name)-1] = 0;
        }
        // or use: name[strcspn(name, "\n")] = 0;
        
        if (strcmp(name, "quit") == 0) {
            break;
        }
        pwd = getpwnam(name);
        if (pwd == NULL) {
            printf("Cannot find UID for name %s\n", name); 
            continue;
        }
        printf("UID: %ld, Login Shell: %s\n", 
               (long)pwd->pw_uid, pwd->pw_shell);
    }
    return 0;
}
```

Compile `gcc main.c -o main` and run:

```
Query UID for login name: root
UID: 0, Login Shell: /bin/bash
Query UID for login name: nobody
UID: 65534, Login Shell: /usr/sbin/nologin
Query UID for login name: quit
```
Walthrough Numero Dos of Clipper (Using Google Cloud Vision + Twilio to Turn Screenshots into Video Clips)
Tags: twiliohackathon, python
Published: 2020-05-02 03:16:46


Walking through the code behind my Twilio Hackathon project for DevTo.

{% youtube GW1ttSVbikE %}

Thanks a ton to Twilio and DevTo for putting this on. This was very fun to make and I learned a bunch. Hope to share that with some others.
36: Does being good at maths help in programming?
Published: 2020-05-02 03:15:38

Programming is basically about logic and maths are the backbone of all the logic.

If one is familiar with mathematical concepts, then programming is all about packaging that logic in correspondence of some constraints called Syntax.

So, all we need to do is first understand the logic behind the problem statement and develop that logic (algorithm) and then trying it out for 2–3 sample cases. If it works, then just rewrite it with proper syntax.

---
Maths is very important for programming but in programming it’s different, and from your question, I can sense that you are a beginner, just always remember one thing that “a good programmer is not a person who knows many languages but a person who can give the best solution for the problem”.

To solve any problem first you have to find the fastest and the best solution for the problem and for that, you need more than basics knowledge of maths. So I will suggest you to start learning a programming language ( i would say python ) and then start practicing algorithms (this is where you will need maths).

---
It totally depends on the type of programming language that you are choosing!

For example :

* Example 1: If you are good at Category Theory, Go for any pure functional programming because it is an implementation of maths only!

* Functional Programming like Haskell, Scala(up to some extent) is totally dependent on the Concepts that you learned in Category Theory.

* Side Note: The world is moving towards Functional Programming because it is less error-prone and is very much easy for a person coming from a Mathematical background!

* Example 2: If You are good at statistics and want your career as a Data Scientist( the most exotic job in 21’ st century ) Then go for R. It is the way to go for you.

--- 
*Hence to summarize: If you are good at mathematics, it will be easier for you to grasp a language, but that depends upon what programming language you are choosing!*
Svelte: Aprenda Svelte em 16 curtos vídeos no Scrimba
Tags: ptbr, svelte, beginners, webdev
Published: 2020-05-02 02:55:22

A plataforma [Scrimba](https://scrimba.com/) tem uma abordagem interessante para o ensino virtual.

É uma fusão de vídeo interativo e exercícios práticos. Nessa semana, revisei o básico e realizei o curso gratuito "Learn Svelte", que são 16 vídeos em torno de 5 minutos cada,

- https://scrimba.com/playlist/pG6X6UG

Está em inglês, mas é bem prático de se acompanhar.

Recomendo para quem está interessado em Svelte!
Walthrough Numero Uno of Clipper (Using Google Cloud Vision + Twilio to Turn Screenshots into Video Clips)
Tags: twiliohackathon, python
Published: 2020-05-02 02:48:29

Walking through the code behind my Twilio Hackathon project for DevTo.

{% youtube ALQplkOYchY %}

Thanks a ton to Twilio and DevTo for putting this on. This was very fun to make and I learned a bunch. Hope to share that with some others.
Introduction to Ncurses (Part 1)
Tags: cpp, ncurses, linux
Published: 2020-05-02 02:45:33

Welcome to the series of Ncurses library in C++. In this, you will learn basics and some tidbits of ncurses.

NCurses is a programming library that provides an application programming interface that allows the programmer to write text-based user interfaces in a terminal independent manner.

To use ncurses we use `ncurses.h` header

```cpp
#include <ncurses.h>
```

Some functions that must be used in all ncurses 
+ initscr()
  + initializes screen
  + sets up memory and clean the screen
+ refresh()
  + refreshes the screen to match what's in the memory on the screen
+ endwin()
  + deallocates memory and ends ncurses
+ getch()
  + waits for user input
  + returns the ASCII value of that key

To compile we must link the libncurses while compilation.

```sh
$ g++ <program file> -lncurses -o <output file name>
```

An obligatory `hello-world` program in ncurses

```c++
#include <ncurses.h>
using namespace std;

int main(int argc, char ** argv)
{
	// init screen and sets up screen
	initscr();
	
	// print to screen
	printw("Hello World");
	
	// refreshes the screen
	refresh();
	
	// pause the screen output
	getch();

	// deallocates memory and ends ncurses
	endwin();
	return 0;
}
```

![](https://i.ibb.co/88bCTkQ/image.png)

Before using ncurses make sure it's installed in your system
Programs using NCurses

+ [Installing in Linux](https://www.ostechnix.com/how-to-install-ncurses-library-in-linux/)
+ [Installing in Windows](https://www.youtube.com/watch?v=DtHO5DBZQHw)

Here are some tools and IDE using ncurses library
+ HTop
+ GNU Nano Text Editor
My first VS Code Theme: Metzi
Tags: vscode, theme, setup, metzi
Published: 2020-05-02 02:37:00

Hello, this is my very first post, I'm so excited to share with you this vs code theme.

Something I can't find in any other theme was _"italic strings"_ and the use of fewer colors, or I didn't search enough, and the tipping point was this post [What Does Your IDE/Code Editor Look Like?](1), where I release my setup wasn't something I would like to call "ideal".

## Naming

As developers every day we give names to files, vars, functions, it could be easier every time but not always is true, not to me at least, naming is one of the most important things. With Metzi as name for this theme I want to share my roots and also something to represent darkness, since I'm from Mexico and this will be a dark theme.

Metzi comes from Metztli, she was the God of the Moon for Aztecs, and as we know when the moon is over us: _"the night is dark and full of terrors"_, that's what make this name oddly perfect. Here we go, let me introduce:


## Metzi

[A dark theme for vs code with fewer colors and good contrast](2).

![vscode explorer screen with Metzi as theme](https://dev-to-uploads.s3.amazonaws.com/i/gj160qbqiiion6opiv56.png)

## My Ideal Setup

![vscode with my installed extensions and term](https://dev-to-uploads.s3.amazonaws.com/i/wnfutt7yz6a1utbldwxg.png)

Editor/IDE: VS Code 🤣
VSCode Theme: Metzi
Shell: Fish

## VS Code extension 

Here are the extensions I use that add something visual to vs code. 

### Bracket Pair Colorizer 2

Lets you set the color for brackets I set all to white... almost white

### Power Mode

Add particles while you type, it's so funny! 🤯

### Material Icon Theme

Finally icons for explorer. A lot of icons, almost an icon even for every name you give to folders.

## Conclusion

[Create your theme](3) for vs code it's not so complex as I thought, and publish your theme it's also easy.

So far this is not the end, or a final version this is the beginning, you can install Metzi from the marketplace. 

I'll appreciate any feedback, so let's share how Metzi looks with your favorite language and extensions you use.

Til next mi Amigo!

[1]: https://dev.to/emmabostian/what-does-your-ide-code-editor-look-like-550e
[2]: https://marketplace.visualstudio.com/items?itemName=quowtf.metzi
[3]: https://code.visualstudio.com/docs/getstarted/themes#_creating-your-own-color-theme
Integração continua com Travis-CI, NodeJS/NestJS
Tags: javascript, typescript, node, testing
Published: 2020-05-02 02:23:06

Hey, 

Em tempos de Coronavírus eu e o meu amigo e colega de trabalho [Rogério dos Santos](https://www.linkedin.com/in/rogeriosantos92/) decidimos escrever uma série de artigos para mostrarmos um Backend feito em NodeJS desenvolvido com carinho e boas práticas.  

Nesse artigo vamos falar um pouco da primeira versão do nosso CI utilizando Travis.

#### Motivação
Sou um desenvolvedor de Software que tem uma paixão enorme pelo que faz. Como gostamos muito da comunidade Javascript/Typescript resolvemos fazer um projeto onde abordaremos boas práticas para produtos, são essas: 
- S.O.L.I.D;
- TDD;
- DDD [Domain-driven design];
- Clean Code.

Agora que explicado a nossa motivação let's talk code.

Actually, ainda não, antes vou falar pouco do Travis. Travis é um serviço de CI que automatiza os testes do seu código. 

Para usar o Travis é simples o que, a meu ver, é excelente. Vou fazer um passo-a-passo para ajudar vocês.

### Passo 1 - Criando uma conta e instalando Travis no GitHub
Crie uma conta no [Travis](https://travis-ci.org/) e logo após a criação da sua conta você será redirecionado(a) para a página de getting started, lá você ativará o Travis no repositório desejado ou você pode instalar no seu GitHub inteiro.

### Passo 2 - Configurando Travis para um App NodeJS
Agora no repositório do projeto crie um arquivo com o nome `.travis.yml`
e pode ser aplicada as seguintes configurações: 
```
language: node_js
node_js:
# Versão do node que é utilizada no projeto.
  - 12

# Script que tem que ser executado antes do antes do script "principal"
before_script:
# Pode ser usado npm ou yarn, escolhemos usar yarn.
  - yarn install

# Script "principal"
script:
# Script de teste encontrado no package.json
  - yarn test
# Script dos testes end-to-end
  - yarn run test:e2e

# Caso necessário você pode settar configurações para serem excutadas depois do script "principal" com a configuração # after_script #
```
### Passo 3 - Final Step
Depois de tudo configurado é só dar `git push` e ir para `https://travis-ci.com/github/usuario/repositorio` para ver sua pipeline executando em toda sua perfeição. 

Projeto: https://github.com/moviandev/geekLounge

E é isso pessoal, muito obrigado e até a próxima.

[GitHub](https://github.com/moviandev/)
[LinkedIn](https://www.linkedin.com/in/matheusviana/)
Rails Backend: Initializing an instance with a default value
Tags: rails
Published: 2020-05-02 02:18:11

Imagine we are building a quiz app and we'd like all users to start out with 0 points. We can achieve it with a number of ways, one of which would be setting a default value to the user instance. 

##1. In the User class, create `init` method
This method will set the default value only if it's `nil`:

```
  def init
    self.points = 0 if self.points.nil?
  end
```

##2. Trigger the `init` method after initialization
Add an `after_initialization` method at the User class. Now your code should look as follows:

```
class User < ApplicationRecord
  after_initialize :init

  def init
    self.points = 0 if self.points.nil?
  end

end
```
World of WoqlCraft - Ep.6 recap and wrap up Schame.org schema, start OpenFlights.org data
Tags: database, schema, python, opendata
Published: 2020-05-02 02:09:51

---
title: World of WoqlCraft - Ep.6 recap and wrap up Schame.org schema, start OpenFlights.org data
published: true
description: We finish off the Schema.org schema by recapping what we have done in the past weeks. Then we started a new project with OpenFlights.org data. We started with a fairly simple set of data and aim to build some application form there.
tags: database, schema, python, open data
---
We finish off the Schema.org schema by recapping what we have done in the past weeks. Then we started a new project with OpenFlights.org data. We started with a fairly simple set of data and aim to build some application form there.

Find the source code from our [tutorial repo](https://github.com/terminusdb/terminus-tutorials).

Join the TerminusDB community at [Discord](https://discord.gg/Gvdqw97)
How you can better work from home during pandemic with Docker. 
Tags: docker, container, devops, workfromhome
Published: 2020-05-02 01:38:09

With everything that is going on outside we are forced to adapt and change the way we used to work. Some of us already work from home full time, but many of us are in this situation where we have to completely rethink our workflow. With this post, I hope I can help with you.

As developers, the issue is that we often rely on multiple components to be able to fully work on our projects. I am talking about runtime, dependencies, an API and even maybe a database. Sometimes theses things are not even on your computer but on a server somewhere on your company’s network, which makes it hard to bring with you everywhere.

So, what is the solution? Containers!  I am sure everyone has at least heard of this at this point. If not, please get out of your home! (Wait after quarantine though) Because of this, I won’t explain in details the basics of containerization, but it’s a very interesting topic and there is plenty of resources online to learn more about it. Docker is super useful for solving a lot of problems and it's a great fit for solving our issues today. 

So, you want to be able to work from home or everywhere else, but all the stuff needed to run your application is a mess to install and is not available on your operating system. With Docker you can replicate all of that on your laptop using a couple of Docker images with Docker-compose to “orchestrate” all of this locally.

Your environment will reside in a Docker-compose file that stays within your git repository and allows you to spin it up or down with ease everything that you need to work. You can declare your complete dev environment as code and stop worrying about having the right version, the right dependencies, and the right server every time. Adopting Docker in your development workflow will improve your time to market greatly and later, you can even use it in production with something like Kubernetes to modernize your infrastructure as well. 

I know that this can be intimidating at first, especially if you never played with Docker. But the industry is already massively going into that direction and I have seen plenty of people do it and now they stopped troubleshooting their laptops and can finally focus on their code.

If you are looking for an exemple, I invite you to take a look at our project on Github to see how we've done it. You will see that we have more than one service running and they are all integrated in containers. 

(Open the docker-comopose.yml file)
https://github.com/Com2Kube/Com2Kube
How to handle Kafka schema management among many developers?
Tags: discuss, help, kafka
Published: 2020-05-02 01:08:56

On a project with many developers and different environments (local, develop, qa, production), what kind of processes/tools need to be implemented in order to avoid compatibility issues either during CI or later when making release?

I can't seem to find any guidelines/best practices about this on the web.

I am leaning towards a solution where developers validate and register new schemas against production Schema Registry. Maybe even creating some web application using Schema Registry REST API to show all schema versions and having ability to edit schema, validate changes (syntax and compatibility) and register new version. Then somehow replicate all new schema versions to other qa and develop environments.

There are other approaches like keeping schemas inside git repository.

What do you think?
Construindo do zero um backend NodeJS com NestJS + Design Patterns - parte um (1/3)
Tags: javascript, typescript, node, testing
Published: 2020-05-02 01:00:56

Olá humano!

Co-escrevo esse artigo em meio a quarentena do Coronavírus com meu amigo e colega Matheus Viana (https://www.linkedin.com/in/matheusviana/). Na verdade, se trata de uma série de artigos que planejamos fazer para mostrar um Backend feito em NodeJS tendo em mente boas práticas de desenvolvimento ágil de software.

Neste primeiro artigo, vamos discutir sobre o que nos levou a escrevê-lo em primeiro lugar, e quais diretrizes nos guiam por essa jornada.

Motivação:

Trabalho com Node há cerca de 5 anos, e adoro a comunidade e a linguagem JavaScript e seu superset TypeScript. Existem inúmeras (de verdade!) formas de se construir um backend em Node, por isso quero focar aqui mais nos conceitos do que nas ferramentas, pois os conceitos e o valor que eles agregam são mais importantes, e são independentes de bibliotecas e frameworks!

Dito isso, o que queríamos atingir aqui é a construção de um Backend com esses requisitos em mente:

Seguir Padrões de Projeto e boas práticas reconhecidamente eficientes nos projetos empresariais, como:

* Domain Driven Design
* S.O.L.I.D.
* Clean Code
* DRY (Não se repita, em tradução livre)

Estes princípios e padrões acima nos norteiam na organização de nosso código, visando principalmente um código que possa escalar e não perca sua  clareza, que fique se mantenha, ao longo do tempo, limpo e eficiente.

Partimos da visão de que escrevemos código para outras pessoas lerem, e não somente para máquinas.

Dito isso, vamos lá!

Partimos com o NestJS por ele ser um framework que já nos dá algumas coisas de prontidão, como:

* Injeção de dependências
* TypeScript
* Testes de unidade e integração com o Jest!

Começamos a partir do próprio template do Nest, que também provê uma interface de linha de comando (CLI) bem útil:

```
// instala globalmente a CLI do Nest
npm i -g @nestjs/cli
```

```
// cria uma nova aplicação Nest com nome geekLounge
nest new geekLounge
```

após isso, editamos o README pra refletir a descrição do nosso projeto, um backend de um site de críticas de filmes chamado Geek Lounge. Definimos este contexto para podermos trabalhar em um domínio rico durante os artigos.

Foi incluído um passo antes dos commits que executam os testes de unidade e integração, a fim de manter a qualidade do código a cada commit!

```
yarn add -D husky
```

Assim, damos um ponto de partida pra essa jornada, e começamos nossa API.

Pra quem veio esperando ver muito código nesse primeiro post, peço paciência rs começamos pensando NO QUE queremos construir e PORQUÊ, que pra mim é o mais importante, pra aí então pensarmos no COMO!

Também configuramos uma esteira no Travis CI para todo o processo rolar com TDD e Continuous Integration.

Aqui está o link pro projeto: https://github.com/moviandev/geekLounge

Acompanhe-nos nas redes sociais pra receber as próximas postagens!

github: @dontpanicroger
twitter: @lifeaholicroger
FizzBuzz JavaScript
Tags: challenge, javascript, algorithms
Published: 2020-05-02 00:59:29

One of the classic interview question! I will show you how to resolve it in JavaScript.

**Challenge**
*Write a program that console logs the numbers from 1 to n. For multiples of three print "fizz" instead of the number and for the multiples of five print "buzz". For number which is multiples of both three and five console log "fizzbuzz"*


If you know how to calculate a multiple of the number in JavaScript will make this challenge much easier to understand. This example use modulo operator (%). With modulo, we can determine a reminder of the number during division.
Essentially we want to do is take a number that we are trying to use the modulo operator with the number that we are using as the multiple and the real question is whether or not the results to that are equal(===) to zero(0).


*Example*
```javascript
12 % 3 === 0    //true
11 % 3 === 0   // false

```
So in practice, you're going to test for each number from 1 to n (the number that we pass in as an argument) if a given number(n) modulo(%) 3 is equal(===) to zero(0) and if a given number(n) modulo(%) 5 is equal(===) to zero(0).

First, we will set up for loop to iterate from 1 
to <= n, and each time we will increment by one(1)
```javascript
function fizzBuzz(n) {
  for (let i = 1; i<= n; i++){}
}
```
Then we will check if the number is multiple by three and five then we want to console log statements that are required.
```javascript
function fizzBuzz(n) {
  for (let i = 1; i<= n; i++){
   if (i % 3 === 0 && i % 5 === 0) {
     console.log('fizzbuzz')     
      }  
    }
  }
```
Next, we will check if we have a multiple of three and print out 'fizz'

```javascript
function fizzBuzz(n) {
  for (let i = 1; i<= n; i++){
   if (i % 3 === 0 && i % 5 === 0) {
     console.log('fizzbuzz')     
      } else if (i % 3 === 0) {
        console.log('fizz')
      } 
    }
  }
```
Else, if we have a multiple of five we will print out 'buzz', and if we failed all of this else of statements we will print out a number.

```javascript
function fizzBuzz(n) {
  for (let i = 1; i<= n; i++){
   if (i % 3 === 0 && i % 5 === 0) {
     console.log('fizzbuzz')     
      } else if (i % 3 === 0) {
        console.log('fizz')
      } 
       else if (i % 5 === 0) {
        console.log('buzz')
      } else {
       console.log(i)
      }
    }
  }
```
If you run console.log(fizzBuzz(10)) this will be output:
```javascript
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz

``` 
I hope this method will be helpful!