teleren/devto huggingface dataset:
Setup ActiveRecord model tests in RSpec which don't depend on Rails
Tags: ruby, rails, rspec
Published: 2020-05-19 16:01:33

---
title: Setup ActiveRecord model tests in RSpec which don't depend on Rails
published: true
description: Sometimes when we build a gem that depends on ActiveRecord, we want to set up RSpec to load ActiveRecord and some tables are ready in our integration tests
tags: ruby, rails, rspec
---

Sometimes when we build a gem that depends on ActiveRecord, we want to set up RSpec to load ActiveRecord and some database migration to be ready for our integration tests. We can generate a dummy Rails application to load in your tests, but I feel it needs a lot of setups and have unnecessary files are generated which we don't need.

Below is a setup to load ActiveRecord with SQLite in-memory database which is easy to set up database migration and run it.

```ruby
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
    t.string :title
  end
end

class Post < ActiveRecord::Base
end

RSpec.configure do |config|
  config.around do |example|
    ActiveRecord::Base.transaction do
      example.run

      raise ActiveRecord::Rollback
    end
  end
end

RSpec.describe "ActiveRecord Tests" do
  it "works with activerecord" do
    Post.create(title: "foobar")
    
    expect(Post.count).to eq(1)
  end
end
```
A lightweight, thread safe general cache library developed with swift 5
Published: 2020-05-19 15:51:06

Hello, I developed a lightweight general cache library with swift 5. If you happen to use swift to develop IOS projects, if you need to use the cache library, maybe you can try swiftlycache, which I developed, and maybe you will like it
https://github.com/hlc0000/SwiftlyCache
What JS Libraries Have You Made?
Tags: discuss, javascript, webdev, node
Published: 2020-05-19 15:43:30

---
title: What JS Libraries Have You Made?
published: true
description: share your repositories
tags: discuss, javascript, webdev, node
---
* What libraries are you proud of?  
* What did they seek to accomplish?  
* How successful do you think they are?  
* What did you learn?

Share the repository links below:
What makes these borders beautiful?
Tags: Neumorphism, design, css, webdev
Published: 2020-05-19 15:40:25


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nbpma2shl6i03hi7v6e0.png)

**Beauty** is in the eye of the **beholder**. 

Are you in the camp that feels these borders are beautiful?

These designs are increasingly seen in modern design and in the design community, they are known as **Neumorphism**. They add extra polish to dashboards and dark mode mobile app designs. I certainly feel these are gorgeous. Let's take a closer look at these.

## A tale of two shadows

These borders are created using two complimentary shadows. One lighter and one darker having complimentary offsets. They are professionally hand-crafted to give this soft UI look. The offset and blur of the shadow depend on the size of the element.

For example, 

* To create a pressed surface create two inset shadows with the slightly darker and lighter surface shades

![Inner Shadow](https://dev-to-uploads.s3.amazonaws.com/i/ufkstqtt4xc7hvmlmwtt.png)

* To create an elevated surface create two shadows again with slightly darker and lighter surface shades

![Outer Shadow](https://dev-to-uploads.s3.amazonaws.com/i/5chq3wtf8kkm07b62ggw.png)


## Start here

A great starting point is https://neumorphism.io/

Use in moderation. 

Next time you see a neomorphic design, you know they are nothing but, the play of 2 shadows. 

--------------------------------------

Please find my other writings here:

1. [One side rounded rectangle using SVG](https://medium.com/@dennismphil/one-side-rounded-rectangle-using-svg-fb31cf318d90)
1. [Automated End to End tests made easy](https://dev.to/dennismphil/automated-end-to-end-tests-made-easy-180m)
1. [Automate your node dependency update](https://dev.to/dennismphil/automate-your-node-dependency-updates-4aga)
1. [Visual Studio Code — Debug Mode](https://medium.com/@dennismphil/debugging-node-js-using-visual-studio-code-c30e5eeb9e38)
1. [I want TypeScript to succeed.](https://medium.com/@dennismphil/i-want-typescript-to-succeed-d421d00fd856)
1. [What’s in my laptop?](https://medium.com/@dennismphil/whats-on-my-laptop-2cc2619aa55f)
1. [CoffeeScript’s most loved feature soon in JavaScript](https://medium.com/@dennismphil/coffeescripts-most-loved-feature-soon-in-javascript-b2f6740c2dc7)
1. [Extend your wireless signal with an old router](https://dev.to/dennismphil/extend-your-wireless-signal-with-an-old-router-2lfd)
Type error in react
Published: 2020-05-19 08:17:28

I'm trying to add a canvasjs chart component into another component called dashboard. Sometimes, the data is getting loaded and working fine, sometimes the data is not getting loaded and an error is thrown.

The error goes like this and it points to the doughnutchart.js page and not to dashboard.js page: TypeError: Cannot read property '0' of undefined

47 | indexLabelPlacement: "outside",
  48 | dataPoints: [
  49 |   {
> 50 |     name: this.props.data.labels[0],
     | ^  51 |     y: this.props.data.datasets[0].data[0],
  52 |   },
  53 |   {
DoughnutChart.js :

import React, { Component } from "react";
import CanvasJSReact from "../../../assets/canvasjs.react";
var CanvasJSChart = CanvasJSReact.CanvasJSChart;

class DoughnutChart extends Component {
  constructor(props) {
    super(props);
    console.log(this.props.data);
    window.alert(JSON.stringify(this.props.data));
    this.state = {
      options: {},
    };
  }

  componentWillReceiveProps(nextProps) {
    console.log("componentWillReceiveProps", nextProps);
    //console.log(this.props.data);
    // if (this.props !== nextProps) {
    //   this.setState(nextProps);
    // }
    //console.log(nextProps.data.labels[0]);
    console.log(this.props.data);

    let options = {
      animationEnabled: true,
      theme: "light2",
      // title: {
      //   text: "Customer Satisfaction",
      // },
      subtitles: [
        {
          // text: "71% Positive",
          // verticalAlign: "center",
          fontSize: 24,
          dockInsidePlotArea: true,
},
      ],
      data: [
        {
          type: "doughnut",
          radius: "90%",
          innerRadius: "50%",
          showInLegend: true,
          indexLabel: "{y}%",
          //yValueFormatString: "#,###'%'",
          toolTipContent: "{name}: <strong>{y}%</strong>",
          indexLabelPlacement: "outside",
          dataPoints: [
            {
              name: this.props.data.labels[0],
              y: this.props.data.datasets[0].data[0],
            },
            {
              name: this.props.data.labels[1],
              y: this.props.data.datasets[0].data[1],
            },
            {
              name: this.props.data.labels[2],
              y: this.props.data.datasets[0].data[2],
            },
          ],
        },
      ],
    };

    this.setState({
      options,
    });
  }

  render() {
    //let options = {};

    return (
      <div>
        <CanvasJSChart
          options={this.state.options}
          /* onRef={ref => this.chart = ref} */
        />
        {/*You can get reference to the chart instance as shown above using onRef. This allows you to access all chart properties and methods*/}
      </div>
    );
  }
}

export default DoughnutChart;
How to stack HTML elements
Tags: html, css
Published: 2020-05-19 15:25:58

---
title: How to stack HTML elements
published: true
description: A quick guide on how to stack HTML elements on top of each other.
tags: html, css
---

I recently had to build this. It's a button with a separate image behind it, providing a cool background effect to the container the button is in.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6egrk8qk2vxfmxp10kww.png)

At first, I didn't have a clue what to do. I'm familiar with `z-index` but I'd never used it to stack elements directly on top of each other like that.

After a bit of Googling and speaking to a colleague, here's what I ended up doing.

```
<div class="container">
   <img class="image" src="">
   <a href="" target="_blank" class="btn">Button</a>
</div>
```

###The container
```
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  float: left
}
```
I'm using flexbox here along with `align-items: center` and `justify-content: center` so that my image and button are both centred inside the parent container. Depending on your needs this may not be the right solution for you. You can read more on flexbox by following the link at the bottom of the page.

`float: left` here isn't needed for the actual stacking of elements, but in my case it was needed to ensure that the component is left-aligned relative to some text above it, but also that the image stays centred behind the button.

###Image
```
.image {
    z-index: 1;
    position: absolute;
}
```
I've given the image `z-index: 1` and `position: absolute`. Absolute positioning essentially pulls the element out of the normal document flow meaning that surrounding elements won't be affected by this element. 

###The Button
```
.btn {
    z-index: 2;
}
```
With `z-index: 2`, and absolute positioning on the image this means the button is nicely stacked on top of the image.

##Wrapping up

These basic properties should give you a button stacked nicely on top of an image. This is because the button is now acting as if the image wasn't even there. So rather than getting positioned next to it, it is now on top of it.

If you'd like to learn more about flexbox, absolute position or relative position then check out these great MDN links.
https://developer.mozilla.org/en-US/docs/Glossary/Flexbox
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning

I'm keen to hear if there are any other ways this could be tackled, or any ways my implementation could be improved. So please leave a comment!
Trampas en los sistemas distribuidos
Tags: sistemasdistribuidos, distributedsystems
Published: 2020-05-19 14:34:04

---
title: Trampas en los sistemas distribuidos
published: true
description: Errores que uno asume como ciertos cuando empieza a desarrollar sistemas distribuidos
tags: sistemas distribuidos, distributed systems
---
# Pitfalls
Desarrollar en sistemas distribuidos es una tarea formidable, hay que considerar muchos problemas al mismo momento que la complejidad parece ser la solución.
Los sistemas distribuidos difieren del software tradicional porque sus componentes están dispersos a través de la red. No tener en cuenta esta dispersión durante el tiempo de diseño es lo que hace que muchos sistemas sean innecesariamente complejos y da como resultado fallas que deben repararse más adelante. Peter Deutsch, cuando trabajaba en Sun Microsystems, formuló estas fallas como las siguientes suposiciones falsas que todos hacen al desarrollar una aplicación distribuida por primera vez:
- La red es confiable.
- La red es segura.
- La red es homogénea.
- La topología no cambia.
- La latencia es 0.
- El ancho de banda es infinito.
- El costo de transporte es 0.
- Hay un administrador.
Windows 10 - Deleting Data
Tags: bugs, windows, update
Published: 2020-05-19 15:13:49

***DISCLAIMER:*** *I am not the person with the issue, that will be from a person who I talked to after they made complaints in a Telegram group about their day. I do not have a complete picture, and only information from this person, so some things might be incomplete or incorrect*

Below is proof I got permission to write this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jguj3vr6ilutb90wu4sa.png)

----

Today, I got word that a Windows 10 forced update installed itself on people's machines, might not be everyone but people will soon, or have already, deal with the update. I saw information that this update of Windows 10 might delete files. After hearing complaints from a Windows user in a Telegram group, I have a couple things to quote.

The person in question is named Dean, however, they recently complained about a Windows 10 update that started without prompt, the person saying "Windows just deleted my personal information. I've lost my Documents and my Pictures..." without prompt because this would be the cause of a bad day.

They sent a picture along with their complaints.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dry7bifwzddoq86hwfyx.jpg)

Dean has made it clear that he is furious as he lost pictures of his dog from his machine, even saying he will switch to Ubuntu after the update caused trouble.

His specifications for his hardware show no fault with Windows 10's hardware and even saying that everything else but his documents and photos is fine, but if his mom wasn't an "information hog", he would have lost memories that were close to him.

I wrote this article not as a reason to switch to Linux, but understand you should at least back up your data just in case this happens to you in the update! Keep online, in-house, and off-site backups of your data JUST IN CASE something like this happens, as it might not be an OS update that causes it!
A simple way to configure Eslint to TypeScript
Tags: typescript, tutorial, beginners
Published: 2020-05-19 15:11:42

On this article, I will show you to configure `eslint` with `typescript` in a quick way.

I'll use `yarn` on the examples below, but it can be done with `npm` too.

First of all, you need to install `eslint` in your project by using the following command:

```bash
$ yarn add -D eslint
```

## Start the Configuration

To create your configuration file and set `TypeScript` as enabled, you need to execute the following command in your project:

```bash 
$ yarn eslint --init
```

After that, you will need to choose some options for the following questions:

### How would you like to use ESLint?
1. To check syntax only;
2. To check syntax and find problems;
3. To check syntax, find problems, and enforce code style;

Choose option `3`.

### What type of modules does your project use?
1. JavaScript modules (import/export);
2. CommonJS (require/exports);
3. None of these;

Choose option `1 - JavaScript modules (import/export)`.

### Which framework does your project use?
1. React;
2. Vue.js;
3. None of these;

In this case, to use NodeJS + TS, I'll choose option `3 - Node of These`.

### Does your project use TypeScript?
```bash
(y/N) - The option N is selected as a default
```

To accept `TypeScript` in your `eslint` configure, set `y`.

### Where does your code run?
1. Browser;
2. Node;

If you enable the two options you can work in both.

In this example, I chose `2 - Node` and disabled `1 - Browser`.

_Note: You can use the `spacebar` to enable/disable options in this section._

### How would you like to define a style for your project?
1. Use a popular style guide;
2. Answer questions about your style;
3. Inspect your JavaScript file(s);

Personally, I like to use `1. Use a popular style guide` and `Standard`.

### What format do you want your config file to be in?
1. JavaScript;
2. YAML;
3. JSON;

I like to use the `JavaScript` format because it's easier when you need to import external files.

### Would you like to install them now with npm?
```bash
(Y/n) - The option Y is selected as a default
```

Just press enter to install.

_Note: Because I commonly use `yarn`, I wait to install the packages in this last part. After that, I delete the `node_modules` and install again using `yarn` to guarantee consistency._

## Wrapping Up

I use this process in some projects of mine and this is the easiest way to configure and use the most updated packages to enable `eslint` in projects.

Was this process helpful to you? Feel free to comment below.
create a shortcut to toggle paste mode with Vim
Tags: vim, beginners, productivity
Published: 2020-05-19 14:50:38

![copy cat](https://media.giphy.com/media/3oKIPnAiaMCws8nOsE/giphy.gif) 

Vim has a paste mode you can toggle on or off - `:set paste` and `:set nopaste`. What if you can do this with less keystrokes?

Essentially, these commands prevent weird formatting when pasting text into your editor.

I will say - copy/pasting isn't a trivial action. Expect to perform copy/paste tenfold throughout your career. Typing out these commands gets cumbersome. If only we can shortcut this to improve your workflow.

Below is a [leader command](https://stackoverflow.com/questions/1764263/what-is-the-leader-in-a-vimrc-file) to which you can add to`.vimrc` (config file). Leader commands are merely a fancy shortcut native to Vim.

#### .vimrc
```vim
function! TogglePaste()
    if(&paste == 0)
        set paste
        echo "Paste Mode Enabled"
    else
        set nopaste
        echo "Paste Mode Disabled"
    endif
endfunction

map <leader>p :call TogglePaste()<cr>
```

No Vimscript knowledge necessary. Just "copy/paste" this snippet to your `.vimrc`.

Ensure your terminal shell of choice knows about your updates. I either restart my terminal session or [source my `.vimrc`.](https://stackoverflow.com/questions/803464/how-do-i-source-something-in-my-vimrc-file) 

**Toggle on paste mode:** hit the key combination `\` + `p`. If this doesn't work... ensure you're in Vim normal mode (not insert or visual).

**Toggle off paste mode:**  `\` + `P`.
Exacta - lightweight JS benchmarking 🏆
Tags: javascript, testing, webdev, node
Published: 2020-05-19 14:40:24

> tldr; Introducing [Exacta](https://github.com/kraiovsky/exacta) 🏆 - lightweight, zero-dependencies benchmarking utility you can run as part of your test suite.

## Motivation
Whether you are playing with challenges on [Codewars](https://www.codewars.com/) or [LeetCode](https://leetcode.com/), or just need to compare which method of finding duplicates in array for your project is faster, eventually you need to benchmark performance of your code.

Libraries like [Benchmark.js](https://benchmarkjs.com/) do really good job and I do not mean to compete with full-blown benchmarking suite. I was, however, looking for something simpler and lighter where I'd have more control and be able to run it as part of unit tests.

## Solution
Here comes **Exacta** - lightweight, zero-dependencies benchmarking utility you can run as part of your test suite.

[https://github.com/kraiovsky/exacta](https://github.com/kraiovsky/exacta)

Here's an example:
```
const Race = require('exacta')

const fn1 = require('./fn1')
const fn2 = require('./fn2')

const param1 = [1, 2, 3]
const param2 = 'your string'

test(`benchmark`, () => {
  new Race()
    .setRuns(100000) // optional, defaults to 1000
    .addFn(fn1) // add functions to run...
    .addFn(fn2) // ...as many as you have, one at a time
    .setParams(param1, param2) // add parameters that functions take
    .run() // and finally let them run
})
```
it will output something like this:
```
--= Race results =--

# of runs: 100000
Parameters: [[1,2,3],"your string"]

Function                Run time [↓]
====================================
🏆 fn1()                10 ms
------------------------------------
   fn2()                20 ms
------------------------------------
```

## Why Exacta?

_Exacta_ stands for a method of betting, as on a horserace, in which the bettor must correctly pick those finishing in the first and second places in precisely that sequence. [](https://www.thefreedictionary.com/exacta)

[https://github.com/kraiovsky/exacta](https://github.com/kraiovsky/exacta)
Pimping up your Mac terminal with 5 basic steps
Tags: terminal, productivity, mac
Published: 2020-05-19 11:43:27

---
title: Pimping up your Mac terminal with 5 basic steps
published: true
description: Pimping up your Mac terminal with 5 basic steps which helps me in everyday work
tags: terminal, productivity, Mac
image: https://barcelonacodeschool.com/blog-pics/2020/pimping-up-mac-terminal.png
---

<img class='art' src="https://barcelonacodeschool.com/blog-pics/2020/pimping-up-mac-terminal.png">

I'd like to chime in with my two cents, it's all about terminal this time. This stuff really helps me and maybe will work great for you too.

1: Oh My Zsh –– https://ohmyz.sh — you can set it up with plugins you want to do things much faster in the terminal, my favourites are: 
    `gaa` instead of `git add .`
    `gcmsg 'amazing commit'` instead of `git commit -m 'amazing commit'`
    and of course `gp` instead of `git push` 😂

2: Another terminal upgrade is npm package `git open` –– https://www.npmjs.com/package/git-open –– once installed from any local repo run this command and it will open up the current repo url in the browser. Me like it. 

3: Making shortcuts for terminal commands you run every day. For example, I start the curriculum app every day and it is in some specific folder, so instead of going into this folder and running `npm start` from there I've created a shortcut so that I can now run `startcur` –– my custom command –– from anywhere in the terminal and it will go into this particular folder and execute npm start from there. The way it works is that you need to open `~/.bash_profile` file on Mac and add shortcut there, for example like this:

```
export PATH=/usr/local/bin:$PATH
alias startcur='open -a "Google Chrome" http://localhost:13666 && cd /Users/you/path && npm start'
```
And once changed do not forget to reload your bash profile by running `source ~/.bash_profile`

4: When creating a new git repo in the terminal with git init you can also create a remote repo from the same terminal! After `git init`, `git add .` and `git commit -m 'banana'` run 

```
git push --set-upstream https://gitlab.com/YOUR_GITLAB_USERNAME/NAME_OF_NEW_REPO.git master
```

It will create the remote repo and also push your commit there to the master branch. 

5: I like all of my terminal windows to be in tabs so that essentially I have one terminal open and all the different processes are in separate tab -- imho it's easier to navigate and keep track of all open windows. To do this in Dock Preferences you can choos "Always" for "Prefer tabs when opening documents" selector and new new terminal windows including ones opened with cmd+N will go into a new tab instead of window. 

> Extra:
Checking hidden/system folders in terminal is easy with `ls -A` and displaying them in Finder could be activated with `defaults write com.apple.Finder AppleShowAllFiles TRUE` from your terminal.