teleren/devto huggingface dataset:
How to test your gem in a Rails application
Tags: ruby, rails, testing
Published: 2020-02-02 22:33:46

![image](https://fakeimg.pl/950x300/?text=dummy%20tests)

Many gems in [RubyGems](https://rubygems.org/) require Rails to work as well and many of them are developed to use together with a Rails application like a [plugin](https://guides.rubyonrails.org/plugins.html). How is known, the best way to ensure that some code is working as well is writing unit tests for it. But, for gems that depend or work together Rails, there is a nice way to test it into a Rails application, the name of it is **Dummy tests**.

The meaning of the word dummy is a kind of mannequin or replica of humans, but in ruby context, it's a kind of scope for you test your gem, in this case, a Rails application. I've added recently dummy tests in my gem [rails-healthcheck](https://github.com/linqueta/rails-healthcheck) in this [pull request](https://github.com/linqueta/rails-healthcheck/pull/26) to check if this gem is rightly imported and have responded in success and failure cases as is waited.

These are the steps to add dummy tests into your gem using RSpec:

### Create a Rails application into folder /spec:

```shell
rails new spec/dummy --skip-gemfile --skip-git --api
```

### Require your gem in the dummy application:

A Rails application will require all gems into Gemfile's environments blocks using bundler, but, here we wanna test your local gem:

{% gist https://gist.github.com/linqueta/a29c40beb3712ebdb5e046e6b0b342ef.js %}

If your gem requires to run some setup, it's the moment to do it.

### Add the gem [rspec-rails](https://github.com/rspec/rspec-rails) as a development dependency:

{% gist https://gist.github.com/linqueta/a84e5a108ec91412ec6ff9cb11d15d1a.js %}

### Require dummy files and rspec-rails in tests:

{% gist https://gist.github.com/linqueta/f310f109c52a69c8410b6a1c05b9f342.js %}

### Code your test:

For this example, my gem provides the method `rgb_to_hex` and it is used in the dummy's model Color. This model has the attributes red, green and blue.

{% gist https://gist.github.com/linqueta/2d861a2406d07a4b8efee52fbee2d113.js %}

### Run rspec to test them:

```shell
rspec spec/color_spec.rb # or just rspec for all tests

# Color
#   #configure
#     with Dim Gray color
#       is expected to eq "3B3638"
#     with White Smoke color
#       is expected to eq "F9F7F7"
# Finished in 0.05234 seconds (files took 3.83 seconds to load)
# 2 examples, 0 failures
```

This example is so basic, but with dummy test you can test routes, controllers, helpers any what you want in a Rails application, for example, in the gem  rails-healthcheck was tested all responses of `Healthcheck::HealthcheckController#check` mounted in the route `/healthcheck` or any route set in the initializer.

Watch my [blog](https://linqueta.com) to see more posts.
Python: no more need for range(len(...))
Tags: python
Published: 2020-02-02 22:03:39

I was practising my algorithm writing skills on CodeSignal and one of the problems is how to sum up a matrix where there are certain conditions placed on the columns and rows.

What's neat about CodeSignal is that you can view and up-vote or down-vote other people's solutions after you have submitted your solution. Even in small algorithm problems, you can see how others are making use of clever tricks and libraries within the programming language used.

For instance, I used [the Python `enumerate` function](https://docs.python.org/3.5/library/functions.html#enumerate) to traverse the rows and columns of the matrix:

```python
for i, row in enumerate(matrix):
    for j, col in enumerate(row):
        print('matrix[{}][{}] = {}'.format(i, j, col))
```

I noticed that other solutions to the problem were using this pattern:

```python
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        print('matrix[{}][{}] = {}'.format(i, j, matrix[i][j]))
```

This is something that makes sense in languages like C, C++ or JavaScript or even in Java. However, if there are iterators available that give you both the index and value, you should use them and match the idioms of the language.

Although, you do have to remember that when iterating over a slice of an array, you will need to set the starting index that `enumerate` starts at:

```python
string = 'awesome'
for i, c in enumerate(string):
    print(i, c) # prints 0, a to 6, e
for i, c in enumerate(string[1:]):
    print(i, c) # prints 0, w to 5, e
for i, c in enumerate(string[1:], 1):
    print(i, c) # prints 1, w to 6, e
```

On the flip side, I found a solution that was clever and used a combination of [Python's itertools `takewhile` function](https://docs.python.org/3.5/library/itertools.html#itertools.takewhile), and the built-in `sum` and `map` functions.

There's a lot that all developers can learn, even in the smallest problems.
How to automate a deploy in a VPS with GitHub actions via SSH
Tags: deploy, github, vps
Published: 2020-02-02 21:19:20

Hi everyone.
Some time ago I hired a VPS server to host my portfolio and do tests, but I had a problem. Every time I wanted to push a change to the server, I had to do it manually. The steps I followed were the following:
* Connect to VPS via SSH
* Move to project directory
* Make a `git pull` to have the new changes on my web
* Typical things of the framework used (Clear cache, etc...)

But with the appearance of Github actions, these steps changed.
Now we can write a script to tell GhActions 'do this deploy for me'.

This is very easy. Just we should create a `yml` file on `project/.github/workflows/`. For example `/my_project/.github/workflows/ci.yml`
And in this file, we can write something like this:
```
name: CI

on: [push]

jobs:
  deploy:
    if: github.ref == 'refs/heads/master'
    runs-on: [ubuntu-latest]
    steps:
      - uses: actions/checkout@v1
      - name: Push to server
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SERVER_IP }}
          username: ${{ secrets.SERVER_USERNAME }}
          password: ${{ secrets.SERVER_PASSWORD }}
          script: cd ${{ secrets.PROJECT_PATH }} && git pull
```

* The `on` line says that this job is launched on `push` event.
* The `jobs` block defines what jobs will be executed.
    * The `if` line says that this job will only run in a push to the master branch.
    * The `runs-on` line says that this job will run on latest ubuntu distro.
    * And the `steps` block says what are the steps that we are going to execute.
        * `uses: actions/checkout@v1`. This is a GitHub Action for executing remote ssh commands. 
        * Finally, in the `with` block we configure the parameters for the SSH connection.
            * In the `Script` label, we can write the commands that we want to run on our server, for example `cd our-project-path/ && git pull`

**Note that I use the GitHub secrets to keep important information hidden.**

Once we have this file in our repository, the next time we push the master branch, it will automatically be deployed to our server.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/eb42dap5o6t9h35j8m0h.png)

**\*It is always important to maintain good test coverage in our application to avoid unwanted errors\***
iOS StackOverflow Deep Dive: Retain Cycle in Closure
Tags: ios, swift, beginners
Published: 2020-02-02 21:03:54

Take a look at this [StackOverflow question](https://stackoverflow.com/q/59531298/3937) (don't read the answers or comments) -- see if you can see the problem.

Here are the clues I saw:

1. The title of the question says there is a retain cycle in a closure. It's not always good to trust the questioner, but ....
2. They show a screen capture of the memory debugger that does show that that a closure is holding a strong reference to something holding it (causing the cycle)
3. In all of the code shown, there is only one closure. Again, it's not always right to trust the questioner, but still a place to start.

Here's the closure:

```
   coord.deinitIfNeeded = { [weak self] in
        guard let self = self else { return }
        self.free(coord)
    }
```

And here is the definition of Coordinator (the class of coord)

```
class Coordinator {
    var deinitIfNeeded: (() -> ())?
```

Ok -- this is enough to solve the problem, if you want to try.

Before I get to the answer: I want to give some advice to new programmers: Unless you know better, trust the tools (like the compiler and memory debugger). I'm not saying they are always right, but I am saying they are much more likely than you to be right. While you are learning, start by assuming your code is wrong.

Ok, so the closure is holding a reference to something that is holding a reference to it.  The only thing holding reference to it is `coord`, in the code: `coord.deinitIfNeeded = ...`. So, is the closure holding `coord` strongly?

Yes, it is.

It captured `coord` in the body and `coord` is not specified to be a weak capture.  Think about how to fix this and then check your work by [looking at the answer](https://stackoverflow.com/a/59531728/3937).
Discussion anything about backend engineering
Tags: discuss, codenewbie, python
Published: 2020-02-02 20:25:26

Hi guys, i want to learn about Best-pratice in backend. i have used django and flask. give me suggest about learning a few things


1. I heard 12 factor is the best way to make app.

2. Playing container such as docker and k8s. sometimes make me dizzy

3. i trust clean code. but what difference with oop?


or maybe you could add more...



thank yoy all

regards, Bimo
A flexible and durable strategy for archiving open source projects.
Tags: github, opensource, microclubusthb
Published: 2020-02-02 20:03:50

### A couple of hours only left to save your code to future generation!

> By the time this article is published, less than 2 hours are left for the first snapshot.
![alt text](https://www.pixenli.com/image/qNgkBRwg "Countdown")

Today, February 2nd 2020 at midnight GitHub will capture a snapshot of the existing state of all active public repositories of its platform in order to preserve them in the Arctic Code Vault in Svalbard, Norway.

#### What's the GitHub Arctic Code Vault?
Just like Svalbard Global Seed Vault, where a wide variety of plant seeds from all over the world are stored and preserved in the remote Arctic Svalbard archipelago (1300 Km from North Pole), GitHub initiated a similar project in order to store and preserve open source projects in its Arctic Code Vault for future generations to the next **1000 years**!

The open source projects will be stored on silver halide film reel with data encoded on 8.8 million pixels/frame with a 1000 years lifespan durability!

#### GitHub Arctic Code Vault {% youtube fzI9FNjXQ0o %} 

#### How do you get your project stored in the arctic archive?
Every public open source project on GitHub that is active will be archived, if you're pushing commits to your projects between the date of announcement at the GitHub Universe **[November 13th, 2019 and today, February 2nd, 2020]** and if your repo has got between 1 to 250 stars, it will be included in the **02/02/2020** snapshot and stored in the archive of the **Arctic Code Vault!**

Make sure your repos are stared and push one last commit to ensure it gets archived!

Check out my little pokédex project on GitHub and give it a star or contribute to it, I appreciate it!
{% github IndigoWizard/Pokedex %}
##### (ps: my first article to DEV.to)
___
For more information, you can visit the links bellow:
> **GitHub:** https://github.com
> **GitHub Archive Program:** https://archiveprogram.github.com
> **Piql film:** https://www.piql.com/wp-content/uploads/What-we-do-behind-the-scenes.pdf
Exit in Golang
Tags: go, beginners
Published: 2020-02-02 19:24:48

<a href="https://golang.org/">Go</a> is a popular programming language, that at first glance seems a bit like C/Java. The famous hello world program looks like this:

```go
package main
import "fmt"

func main() {
	fmt.Println("Hello, World")
}
```

You may wonder, where is *return* or *exit*? How does exit work in Golang?

## Exit program

If you want to quit your golang program, you can use os.Exit. This is part of the os module.

From the <a href="https://golang.org/pkg/os/#Exit">golang docs</a>:

*"Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run."*

## Example

*os.Exit* exits the program immediately with a given status. 

```go
package main
import (
 "os"
)

func main() {
  os.Exit(4)
}
```

Shown below the output:

    > go run test.go
    exit status 4

The status is shown in the terminal like this. *os.Exit()* can be used to exit the program normally without an error like this:

```go
package main
import (  
 "os"
)
    
func main() {
  os.Exit(0)
}
```

This returns to the terminal without showing anything.

**Related links:**
* <a href="https://golang.org/">Go Programming Language</a>
* <a href="https://golangr.com/">Golang tutorial</a>
Career Changes into Software Development
Tags: career, discuss, beginners
Published: 2020-02-02 19:11:30

Hi everyone, 

I'd love to hear any stories about how any of you guys successfully transitioned from your old jobs into software development. 

This would be great inspiration for new programmers or those preparing to break into the industry.

Tell us:

1) What you used to do?

2) What your first job entailed ie where, what technologies you worked with, your roles, and what type of development ie front end, web dev, etc

3) What your journey was to get from where you were to securing that first job.

4) Would be great to hear what you are doing right now, what you working on? How have you progressed?

5) And what are your plans for the future?

Can't wait to hear you guys' stories ❤😁
Why do Java containers (docker) take so much memory?
Tags: explainlikeimfive, docker, java, memory
Published: 2020-02-02 18:24:33

I might be doing something wrong, I was just testing how to "dockerize" a spring boot **FatJar**

First I tried a simple Eureka server, docker showed around **350 mb** memory usage.

I went ahead to dockerize a simple hello world, it has nothing else on it, yet it was taking around **150 mb** memory.

Is this normal? why does it need that much? I don't get it
WSL2 Issue: Rolling back from Build 19555 to resolve issue
Tags: tutorial, ubuntu
Published: 2020-02-02 18:19:11

If you're like me, you have opted to be apart of the Windows 10 Insiders Preview Track because you're 100% loving WSL2. Yes, it does come with some risks, but the reward of WSL2 is just so darn sweet. 

## The Problem

Well, if you've updated to 19555.1001 you will, unfortunately, see ann error connecting to WSL2 no matter how you try to launch it. 

```
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
```

After going to the WSL Github repo and looking at the issue, I found the reported issue https://github.com/microsoft/WSL/issues/4860. So at least I know it's not just me.

## The Solution

Luckily the issue is super straight forward! You can roll back to the previous version, allowing you to get back on track.

Go to `Start -> Settings -> Update and Security -> Recovery -> Go back to the previous version of Windows 10`

Click through all the prompts, and about 10 minutes later, your back in action on a previous build it had worked.

## The Takeaway

The beautiful thing about this solution is that it should be super helpful if you come across any other issues in future Insider track builds.

Yes, the Insiders track comes with the obvious risk but its great knowing we can rollback to easily.
Scratch Your Own Itch (Ruby edition)
Tags: ruby
Published: 2020-02-02 17:55:54

---
title: Scratch Your Own Itch (Ruby edition)
published: true
description: Creating Ruby gems to develop with more comfort.
tags: ruby
---

> If you feel perfectly comfortable using a tool it means that you haven't used it enough. - me

This is why I'm creating some tools (Ruby gems) to help me feel more comfortable when developing software.

[Scratch](https://source.olisti.co/olistik/mu-result) 👏 [your](https://source.olisti.co/olistik/mu-json) 👏 [own](https://source.olisti.co/olistik/mu-rest-client) 👏 [itch](https://source.olisti.co/olistik/mu-hash) 👏.

![Comfy gif here](https://dev-to-uploads.s3.amazonaws.com/i/se7u8tfe7cmsm914keyk.gif)
Styling Excel cells with mso-number-format CSS attribute
Tags: css, html, productivity
Published: 2020-02-02 17:41:56

If you need to create a Microsoft Excel spreadsheet, it is very easy to create an `HTML` with a `<table>` styled using the `mso-number-format` `CSS` attribute.

I compiled these some time ago. Below there’s an example `HTML` showing how to use these classes and an image with the output.

| Attribute           | Description |
|---------------------|-------------|
|mso-number-format:"0"|NO Decimals  |
|mso-number-format:"0\.000"|3 Decimals|
|mso-number-format:"\#\,\#\#0\.000"|Comma with 3 dec|
|mso-number-format:"mm\/dd\/yy"|Date7|
|mso-number-format:"mmmm\ d\,\ yyyy"|Date9|
|mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM"|D -T AMPM|
|mso-number-format:"Short Date"|01/03/1998|
|mso-number-format:"Medium Date"|01-mar-98|
|mso-number-format:"d\-mmm\-yyyy"|01-mar-1998|
|mso-number-format:"Short Time"|5:16|
|mso-number-format:"Medium Time"|5:16 am|
|mso-number-format:"Long Time"|5:16:21:00|
|mso-number-format:"Percent"|Percent - two decimals|
|mso-number-format:"0%"|Percent - no decimals|
|mso-number-format:"0\.E+00"|Scientific Notation|
|mso-number-format:"\@"|Text|
|mso-number-format:"\#\ ???\/???"|Fractions - up to 3 digits (312/943)|
|mso-number-format:"\0022£\0022\#\,\#\#0\.00"|£12.76|
|mso-number-format:"\#\,\#\#0\.00_ \;\[Red\]\-\#\,\#\#0\.00\ "|2 decimals, negative numbers in red and signed (1.56 -1.56)|

## Example `HTML` content.

Save the following content as myfile.xls :

```html
<html>
    <head>
        <style>
            td.three-decimals {mso-number-format: "0\.000"}
            td.thousands-separator {mso-number-format: "\#\,\#\#0\.000"}
            td.fractions {mso-number-format: "#\ ???/???"}
            td.negative-red {mso-number-format: "#,##0.00_ ;[Red]-#,##0.00\ "  }
        </style>
    </head>
    <body>
        <table>
            <tr>
                <td>3 decimals</td>
                <td class="three-decimals">3.45</td>
            </tr>
            <tr>
                <td>+Thousands sep</td>
                <td class="thousands-separator">4560</td>
            </tr>
            <tr>
                <td>Fraction</td>
                <td class="fractions">0.125</td>
            </tr>
            <tr>
                <td>Negatives red</td>
                <td class="negative-red">-5</td>
            </tr>
            <tr>
                <td>Negatives red</td>
                <td class="negative-red">5000</td>
            </tr>
        </table>
    </body>
</html>
```

When you open the `myfile.xls` (in whatever version of MS Excel) you should see the cells formatted as intended. See the image below.

Notice how cool that the value `0.125` has been converted to its fractional representation!

![Alt Cells are being formatted with the `mso-number-format` CSS attribute](https://i.postimg.cc/ZqLjxk4k/styling-html-excel-example.png)
<figcaption>Cells are being formatted with the `mso-number-format` CSS attribute</figcaption>

<hr />

Do you have comments or suggestions?
[Tutorial] Instalando o VS Code no Linux (Ubuntu/Mint/distros derivadas do Debian) pelo terminal
Tags: linux, vscode, tutorial, womakerscode
Published: 2020-02-02 17:34:39

Primeiramente é preciso verificar a arquitetura do processador através do comando:

```
$ uname -m
```

- **$** indica que você deve usar o **usuário comum** para fazer essa operação.

- **uname** serve para mostrar informações do sistema.

- o parâmetro **-m** indica o uname que queremos a arquitetura da máquina.

No meu caso, é um sistema de 64 bits.

Para baixar o pacote, digite:

```
$ wget "https://go.microsoft.com/fwlink/?LinkID=760868" -O vscode.deb
```

> Para verificar o link da última versão do VS Code, visite a [página oficial](https://code.visualstudio.com/).

- O comando **wget** serve para fazer downloads de arquivos.

- Os parâmetros **-O vscode.deb** para nomear o arquivo que está sendo baixado. **-O** O maiúsculo vem de output, seguido do nome do arquivo e sua extensão.

Para instalar o pacote digite no diretório onde o arquivo foi baixado:

```
$ sudo dpkg -i vscode.deb
```

- **sudo** serve para pedir permissões de administrador temporariamente.

- **dpkg** é o gerenciador de pacotes das distribuições baseadas em Debian.

- **-i** é o comando que indica instalação

Caso precise corrigir dependências, digite o comando:

```
$ sudo apt install -f
```

- **apt** do inglês, *Advanced Package Tool*, em português, Ferramenta de Empacotamento Avançada; é a ferramenta que nos ajuda na instalação, atualização e desinstalação de programas, entre outras funções.

- **install** é o comando de instalar, indicando ao apt o que fazer.

- o **-f** é um atalho para o comando **--fix-broken** que tenta fazer as correções de pacotes e dependências.
Project Ideas and Career Development
Tags: html, java, css, career
Published: 2020-02-02 17:31:49

Hi everyone, 

I'm new to DEV.to this is only by second post on here and I'm a beginner developer.

I'm planning to break into dev. Industry sometime in the 2021. 

I've been coding for some time now but feel frustrated as I've not really built any substantial projects or software other than a few small console applications.

In the last year I've got a few certs in HTML5, CSS3 and I've just got my first Java cert OCA. But no personal projects to showcase my skills.

Any ideas on some small, simple apps I can create and also what is the best way to showcase these projects to potential employers. I hear GitHub is the best way to do this.

Any thoughts?

Thanks 

Bobby
Java OCP - nested classes
Tags: discuss, java
Published: 2020-02-02 17:19:44

Hi, any Java developers... I've just got my OCA certificate and am moving onto OCP prep now... First concept, is nested classes and I'm struggling to understand how these are applied in the real world. What are some of there use cases for each type:

- member inner classes
- static member inner classes
- local inner classes
- anonymous inner classes

Thanks in advance!! 

Bobby