teleren/devto huggingface dataset:
Tutorial: Cómo crear un custom snackbar
Tags: android, kotlin, ux, snackbar
Published: 2019-10-27 18:13:49

##¿Qué es una snackbar?

Según la propia documentación de google

>Las snackbars proporcionan mensajes breves sobre los procesos de la aplicación en la parte inferior de la pantalla.

![Ejemplo de snackbar](https://thepracticaldev.s3.amazonaws.com/i/q5ff0ns2njg6r95nxlkt.png)

##Uso

Gracias a este tipo de vistas podemos informar al usuario facilmente de algún tipo de acción que se acaba de realizar, por ejemplo, un elemento se ha eliminado de nuestro listado.


>Los Snackbars informan de un proceso que una aplicación ha realizado o realizará. Aparecen temporalmente, hacia la parte inferior de la pantalla. No deben interrumpir la experiencia del usuario, y no requieren acción del usuario para desaparecer.

Para implementar este tipo de vistas android nos proporciona la clase *Sanckbar* la cual con unos pocos parametros somos capaces de mostrar este tipo de mensajes.

```kotlin
Snackbar.make(clContainer, "Hola mundo", Snackbar.LENGTH_LONG).show()
```

##Customizando un snackbar

En ocasiones el diseño proporcionado por Google se queda corto a nuestras necesidades, yo mismo tuve la necesidad no hace mucho asi que tocó investigar un poco como realizar la tarea. Desde la propia documentación de [material component] (https://github.com/material-components/material-components-android/blob/master/docs/components/Snackbar.md) nos proponen la solución, implementar la clase BaseTransientBottomBar.


## Pasos

Nos creamos nuestra clase CustomSnackbar que extienda de BaseTransientBottomBar. En el init de la clase vamos a cambiar las propiedades padding y backgroundColor ya que por defecto nos mete unos márgenes a la vista y el propio color del tema heredado.

{% gist https://gist.github.com/rulogarcillan/fff464b2a3a70914783631fbdb6f2ceb %}

Nuestra nueva clase necesitará de tres parámetros, el contenedor padre donde se mostrará la vista, nuestro custom layout y un callback que podremos utilizar para agregar alguna animación o detectar cuando aparace y desaparece el CustomSnackbar.


{% gist https://gist.github.com/rulogarcillan/292ac179193beb01aa2ecef75e65f843
 %}

Y aquí nuestro custom layout

{% gist https://gist.github.com/rulogarcillan/1cda60e0cc07bcc7042142bf7361abb9
 %}

Por último para seguir la línea que google proporciona a la hora de crear los snackbar vamos a replicar los métodos de creación, para ello nos crearemos una serie de métodos estáticos que funcionen como fábrica.


{% gist https://gist.github.com/rulogarcillan/98b9f02a090ca0c9c2b96bb9aaa62092
 %}



Ensamblamos todo en una app de prueba y el resultado es el siguiente:


CustomSnackbar tipo 1             |  CustomSnackbar tipo 2
:-------------------------:|:-------------------------:
<img src="https://thepracticaldev.s3.amazonaws.com/i/47wpm9e0fplht5lezidn.png" width="250" height="250">  |  <img src="https://thepracticaldev.s3.amazonaws.com/i/lxq6fb879dxuvvh3x4o1.png" width="250" height="250">


Puedes descargarte el código completo en github  

{% github https://github.com/rulogarcillan/android-customsnackbar %}
Creating an Animated Bar Chart – Using React (Hooks) with D3
Tags: react, dthree, beginners, svg
Published: 2019-10-27 17:54:43

{% youtube LQHt0wr3ybw %}

This is part 4 of my Using React (Hooks) with D3 series, and in this one, I am showing how to create an animated bar chart!

You can checkout the code here:
https://github.com/muratkemaldar/using-react-hooks-with-d3/tree/04-bar-chart-animated

Hope you like it.
Enjoy!
What is Git & Why Does it Make Me Sweat
Published: 2019-10-27 16:49:01


Git is a modern version control system that gives full access to a projects source code and all its changes, branches, and iterations. Git allows individuals and teams to create, modify, share, and collaborate on projects together. It tracks changes that were made, when the changes were made, and by whom they were made. It also allows you to run tests, fix bugs, and contribute code without disturbing the master file by being able to create and work on local branches created off the master code. This way numerous individuals from anywhere can simultaneously work on the project without time or location constraints. 

A Git repository contains the entire collection of a project’s files and folders and all the revision history of each file. This helps to keep projects protected and organized. There are a couple of different ways to use Git. You can use the command line of your systems native terminal to directly execute specific commands to copy, change, combine, or create code. You can also use an application like Github to execute specific commands and certain text editors like Atom come with basic Git and Github integration built in. 

I think all of this sounds fantastic. It makes sense and I can understand the importance of what this kind of version control has done for developers. I even understand the basic theory behind it but I am finding it hard to learn how to use! I have used it five times recently to try and push my personal website through Git into Github and have caused my personal website project to burn villages down exactly those five times. I’ve used it to make pull requests successfully but for some reason each time I try to navigate inside of Git to commit and push changes to my Github project I end up sweating and swearing. Builds character right? I can tell by the fearful and concerned looks on my classmates faces as I flail about that my personal struggle with Git is also helping them build character. 

Here are a few of the unintended results of me tripping around in Git. Yesterday, I somehow accidentally cloned a version of my project within itself causing everything but the title of my personal site to disappear. And the font that my title reverted to made me want to delete the whole thing and hide until the spring. What was interesting was that all of my code was still there in my text editor but the css all of sudden decided that it was broken and wouldn’t let anything communicate with it. I’ve accidentally merged older commits to the master branch overriding all the changes I spent hours on and created expletive inducing mayhem when trying to revert/reset/undo those merges. I trip around in there so often I’m not even sure of what I’m talking about! 

But I am determined to learn how to successfully use Git. So determined that I signed up to give a little talk about Git in class next week. It will be like performance art. Nobody will know what I’m talking about but the sincerity will be intense!
Using PostgreSQL and pgAdmin4 in docker
Tags: postgres, docker, database
Published: 2019-10-27 15:47:54

I wrote a docker-compose.yml. If you want to practice Postgresql and pgAdmin in docker.
 
Here is [docker-compose.yml](https://gist.github.com/tingwei628/8584ddefc5d8e85f73566d5ab96bdc84)

Enjoy it ~
Class components in React
Published: 2019-10-27 15:20:39

---
title: Class components in React
published: true
description: How to use state with React class components
tags: 
cover_image: https://ferrariwebdevelopment.s3.us-east-2.amazonaws.com/assets/class-components-react.jpeg
---

## How to use state with React class components

We have already seen functional components in React, which are simply Javascript functions. Class components, on the other hand, are Javascript classes.
We define them with this syntax:

```
class Student extends React.Component {
  render() {
    return (
      <div>
        <p>This is a class component</p>
      </div>
    )
  }
}
```

Note that the class component extends (inherits from) the base class `React.Component`
`React.Component` gives our component all the functionalities needed by React to work correctly.

In functional components we simply return JSX that is displayed by React.
Class components behave a little differently. To display the component, React will call a `render()` method on an instance of the class, so we need to define a `render()` method inside our class component. The `render()` method will return what needs to be displayed by the component.

The code above is the most basic class component. But the real purpose of class components in React is to hold `state`.
To have the class component deal with its own state, we need to make some extra configuration.

In a Javascript class we can define a `constructor()` method that gets called when an instance of the class is initialized.
In React, we use the `constructor()` method to hold the initial state of the component.

So, if we have a `students` array, with `student` objects in it, we can define the initial state of our component inside the `constructor` method by assigning the `students` array to a property of the state object.
We can call this property `myStudents`.
As you can see in the code below, we create the `state` object on the instance of the class, using the keyword this, which inside a class refers to the object being instantiated.

```
class Students extends React.Component {
  constructor() { 
    super();
    this.state = {                  
      myStudents: students          
    }                               
  }                                 
}
```

This code will create a `state` object and add a `myStudents` property to it that can be called with `this.state.myStudents`
This property holds the `students` array and the data in this array will be available to the component and its children through `props`.

So, when we display the data, we just call `this.state.myStudents` and do something with the data in it, like iterate on it and display a `Student` component for each student.

```
this.state.myStudents.map( student => {
    // ... do something with the data and return it
    return <Student student={student} />
  })
```

How do we update state in a class component?
We will look at state updates tomorrow.
Blocking feature? 
Tags: question
Published: 2019-10-27 14:57:53

---
title: Blocking feature? 
published: true
description: 
tags: question
---

I have seen that we can now block users in case they are spam. At least I think is a new feature I had not seen it before. 

Lately I have been noticing tons of articles from non English writers that I can't read nor do I wanna see. Some span for like 10+ articles one after another.

Even after blocking user I am still seeing their articles, what can I do to minimize this issue on my feed?
Compile and run C/C++ code using Notepad++
Tags: notepad, compile, c, cpp
Published: 2019-10-27 14:44:01

---
title: Compile and run C/C++ code using Notepad++
published: true
description: How to compile and run C/C++ (using MinGW or Visual C as compilers) using Notepad++
tags: notepad++, compile, c, cpp
---

For compiling and running using MinGW:
```
npp_save
cd "$(CURRENT_DIRECTORY)"
gcc -o "$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"
"$(NAME_PART).exe"
```

For compiling and running using Visual C:
```
npp_save
cd "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build"
vcvarsall.bat x64 && cl "$(FULL_CURRENT_PATH)" /Fo$(CURRENT_DIRECTORY)\ /link /out:"$(CURRENT_DIRECTORY)\$(NAME_PART).exe"
cd $(CURRENT_DIRECTORY)
"$(NAME_PART).exe"
```

More info on Visual C vcvars scripts:
https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=vs-2019
Difference between rush wars and previous work
Published: 2019-10-27 08:17:27

Rush Wars, compared with the previous work, the biggest difference is that four grand branch tasks are added, but the triggering conditions of these tasks are actually hidden. In order to unlock more gems in Rush Wars, you need to talk with specific NPC randomly generated between ports (you need to refresh around 400 times in each port), or use the wonderful way of keyboard input to answer more than 30 questions. About the knowledge of ancient navigation - simply put, if you don't look at the strategy in advance, you have no possibility to open these branches. Therefore, players can only curse at the same time, pain and happiness only when using [rush wars hack gems](https://clf2018.org/rush-wars-hack/) tool. This cynicism in Rush Wars global version has made many Russian developers pay for themselves. Meanwhile, the booming piracy industry has also hit the crazy artists head-on. Paradoxically, the period when these developers were disbanded and closed down in large numbers, i.e. 2008-2009, was actually the time when Supercell's economy was booming. What's particularly striking is that the biggest impact on the game industry is precisely the growing cultural needs of domestic players themselves.
How to Install GalliumOS on a Chromebook using Chrx
Tags: linux, beginners
Published: 2019-10-27 14:39:07

[This post was originally on [my blog](https://write.privacytools.io/connor).]  

**Note**: to do this, all your chromeOS data will be wiped. I recommend reading through all of this post before starting.

This post is about how I got my chromebook dual booting galliumOS.

![my galliumOS](https://i.postimg.cc/Kjggpd08/galliumos.png)

## **Step one**: go into Developer mode.

Developer mode is a setting that lets you do development. It's not on by default because it also makes it easier to install a malicious package. (APKs, or android packages, can't be opened without developer mode.)

To turn on developer mode, hold down the `esc` and `reload` key, then tap the `power` key. You will be greeted by a very scary popup saying "CHROMEOS IS MISSING OR DAMAGED." Hit `control-D`, and then it will say something along the lines of "START DEVELOPER MODE? all your data will be wiped." press `enter`. It will start.

## **Step two**: login

Your computer will restart and say "OS VERIFICATION IS OFF." Press `control-D`.

since starting Developer mode wiped all your data, you will have to log in again, etc. If you don't want to that, you can just go into guest mode.

## **Step two**: install [Chrx](https://chrx)

You will have to install and run Chrx, which is really easy. Just one curl command:

```
cd ; curl -Os https://chrx.org/go && sh go
```
Copy and paste that command in chrosh shell (`ctrl-alt-T` and then type `shell`.)

Go through the install script. At the bottom, it will have a "diagnosis." If it says it will only succeed if it has a firmware update keep that in mind. Reboot.

## **Step two.two**: Update firmware

If you need to update your firmware, you will have to download [MrChromebox](https://mrchromebox.tech). Type this in the crosh shell:

```
cd; curl -LO https://mrchromebox.tech/firmware-util.sh && sudo bash firmware-util.sh
```

You will see this menu:

![MrChromebox menu](https://mrchromebox.tech/images/fwutil_main.png)

Press 1 to update the firmware. (When you do this, you will install BIOS [Basic Input/Output System]).

## **Step three**: repeat "step six"

Type this command in chrosh (again):

```
cd ; curl -Os https://chrx.org/go && sh go
```
That will install GaliumOS.

## **Step four**: Get into GalliumOS

Reboot. This time, when you have to type `control-D`, type `control-L`. It will go into BIOS, then GalliumOS. Username is `chrx` and password is `chrx`.
VimでPythonプログラミングを快適にするWindows環境の作り方 [gVim/Windows10編]
Published: 2019-10-27 14:04:26

VimをWindows 10で利用したいが、なかなか苦労しているというユーザーは多いのでは無いでしょうか。 本記事で、Windows 10 上で gVim を使った快適なプログラミング環境を構築する方法について、ご紹介し

つづきは[こちら](https://vim.blue/vim-python-windows10-howto/)。
[https://vim.blue/vim-python-windows10-howto/](https://vim.blue/vim-python-windows10-howto/)
Best way to glue Graphql APIs with Apollo Federation
Tags: graphql, docker, javascript, react
Published: 2019-10-27 14:02:07

Apollo federation is sure the best way to glue together many graphql services, to add support for apollo federation is super easy:
```js
const { ApolloServer, gql } = require("apollo-server");
const { buildFederatedSchema } = require("@apollo/federation");

const typeDefs = gql`
  ...
`;

const server = new ApolloServer({
  schema: buildFederatedSchema([
    {
      typeDefs,
      resolvers: {
        Query: {
          // ...
        },
      }
    }
  ])
});

server.listen({ port: 80 }).then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});
```

The server above can then be integrated in a gateway using apollo server with many other related services, the Query and Mutation types will be merged and the types with same name will be glued together in the unified schema gateway.

But how should i create this gateway?
You could write one yourself using the `@apollo/gateway` npm library only to find out that you should also handle the forwarding of headers and restart the service when other services schema changes.

Well you don't need to waste your time because i already wasted mine just for you.
You can use my reusable docker image with `docker-compose` as follows:

```yml

version: '3'

services:
    a:
        build: ./a # one service implementing federation
    b:
        build: ./b
    gateway:
        image: xmorse/apollo-federation-gateway
        ports:
            - 8000:80
        environment: 
            CACHE_MAX_AGE: '5' # default cache
            ENGINE_API_KEY: '...' # to connect to the apollo engine
            POLL_INTERVAL: 30 # to update services changes
            URL_0: "http://a"
            URL_1: "http://b"
            # you can also add other services outside docker
```

Please star the [github](https://github.com/remorses/apollo-federation-gateway) repo if you are using the image so i can fulfil my pathological stars thirst.
Taking n first elements from a list in Clojure
Tags: clojure, todayilearned
Published: 2019-10-27 13:53:17

## Faster than a hadron collider 🤓
![](https://media.giphy.com/media/3oriNYQX2lC6dfW2Ji/giphy.gif)
We have a list of orders and want to get the first 2 elements

How we can do that?
```clojure
(def order [
 {:id 15 :quantity 3 :price 5}
 {:id 3 :quantity 24 :price 1}
 {:id 7 :quantity 6 :price 9}])

(println (take 2 order)) ;take [0, 1] from list of elements
(println (nth order 2)) ;better than (get _ _) to get elements from a list 

```
![](https://media.giphy.com/media/dQkcf8GANR0ps57oBH/giphy.gif)


Thanks for your time 🤗
Coding while being recorded is harder than it looks.
Tags: tailwindcss, vue
Published: 2019-10-27 13:11:25

---
title: Coding while being recorded is harder than it looks.
published: true
description: You know that strange feeling when you're doing something and someone starts staring at you and all of a sudden you make stupid mistakes?
tags: tailwind, vue
---

I've just finished recording my first screencast, and while I was reviewing it I got surprised by the low quality of it.

Rather, I got surprised by the high quality of videos out there, which makes mine seem really low-end.

It's true, recording audio through hangouts on my phone whilst recording the screen on my computer isn't the best idea, but I haven't invested into a mic yet.

Anyways I hope to watch this in a couple of months and feel proud of my progress.

Check it out and let me know what you think!

{% youtube tOnQVX_7W6s %}
[Para iniciantes] Entenda o que é JavaScript e ECMAScript
Published: 2019-10-27 12:48:40

Este artigo é para você que está iniciando agora no mundo de Front-end e ainda não conhece o JavaScript e/ou o ECMAScript.

## JavaScript
Popularmente conhecida como JS, é uma linguagem de programação client-side criada inicialmente para o Netscape Navigator por Brendan Eich em 1995. Por mais que o nome seja similar, JavaScript e Java são coisas totalmente diferentes.

Se você realmente não faz ideia do que é JS, isto é para você:
> "JavaScript é uma linguagem de programação que permite a você implementar itens complexos em páginas web - toda vez que uma página da web faz mais do que simplesmente mostrar a você informação estática - mostrando conteúdo que se atualiza em um intervalo de tempo, mapas interativos ou gráficos 2D/3D animados, etc. - você pode apostar que o JavaScript provavelmente está envolvido. É a terceira camada do bolo das tecnologias padrões da web, sendo HTML e CSS as outras duas."

Leia o artigo "[O que é JavaScript?](https://medium.com/r/?url=https%3A%2F%2Fdeveloper.mozilla.org%2Fpt-BR%2Fdocs%2FLearn%2FJavaScript%2FFirst_steps%2FO_que_e_JavaScript)" completo no site da MDN.

O JavaScript recebeu várias novas versões ao longo dos anos, mas se manteve sem grandes alterações até o ano de 2009 com o lançamento da versão ES5. Vários anos depois, em 2015 foi lançado a popular versão ES6. Que foi um marco na evolução da linguagem e de grande importância para o que hoje consideramos "JavaScript Moderno". A versão mais recente é a ECMAScript 2018.

## ECMAScript
Muita gente faz confusão sobre o que é de fato o ECMAScript. Para facilitar o entendimento, vamos voltar um pouco no tempo.

Quando o Javascript ainda era um protótipo, foi chamado de Mocha e posteriormente batizado de LiveScript em seu lançamento na então versão 2.0 beta do navegador Netscape. Este último nome não se manteve por muito tempo, em um comunicado de imprensa a Sun Microsystems e a Netscape Communications Corporation anunciaram a linguagem como JavaScript (acredita-se que essa mudança foi uma estratégia de marketing para aproveitar a fama de outra linguagem, o Java).

No ano de 1996 a Netscape submeteu a linguagem para a Ecma International como padrão industrial. Uma vez que a Sun Microsystems havia patenteado o nome JavaScript, esta nova versão padronizada foi batizada de ECMAScript.
Portanto é certo afirmar que o nome oficial de JavaScript é ECMAScript. Inclusive o nome das versões de JS contém referência ao nome da especificação como, por exemplo, "ES6" ou "ECMAScript 2015".

Este artigo foi uma breve introdução da história da linguagem e curiosidades sobre a mesma. Se você quiser saber mais sobre, eu recomendo o excelente artigo "[Afinal, Javascript e ECMAScript são a mesma coisa?](https://medium.com/trainingcenter/afinal-javascript-e-ecmascript-s%C3%A3o-a-mesma-coisa-498374abbc47)" do Alexandre Malavasi.