teleren/devto huggingface dataset:
Replacing React with Preact. It was easy and worth it.
Tags: react, preact, webdev, javascript
Published: 2020-01-17 10:47:35

---
title: Replacing React with Preact. It was easy and worth it.
published: true
description: A short summary of replacing React with Preact on SaaSHub
tags: react, preact, webdev, javascript
cover_image: https://thepracticaldev.s3.amazonaws.com/i/hd3wxjfcshl74zo1xbck.jpg
---
I had been considering [preact](https://preactjs.com/) for quite some time. After all, the sell is easy:

* 100% compatible with the React ecosystem (kind of)
* Much smaller (js bundle size)
* Faster (performance)

About two years ago, I went to a local meet-up in Sydney where the presenter was sharing how they were integrating Preact successfully in some parts of Qantas. That was interesting. And he was convincing. Yet, given that everyone is using React, I thought it was a daunting task and never put the time to research it further. Until recently.

I was working on optimizing the page-load speed of SaaSHub, and one of the paths was decreasing the JS bundle size. I played a bit with **webpack-bundle-analyzer** and **source-map-explorer**, and it was apparent that 35% of all the libs were taken by React & react-select. Then I remembered **preact**... and decided to review it again.

It happened that that task was more scary than difficult. After going through the docs, the whole switch to preact consisted of adding it to **packages.json**, adding the relevant aliasing to webpack's build configs:

```javascript
environment.config.resolve.alias = {
  "react": "preact/compat",
  "react-dom/test-utils": "preact/test-utils",
  "react-dom": "preact/compat",
  // Must be below test-utils
}

module.exports = environment
```

and importing 'preact/debug' somewhere in the app: ```import 'preact/debug'```

That was all. So simple. Everything worked without touching another line of code. Of course, the process could be more complicated for web apps with more sophisticated code.

What are the benefits:
* [SaaSHub](https://www.saashub.com)'s JS bundle file-size decreased with 20%: from 577k down to 460k
* Faster JS (although I haven't benchmarked that, neither have felt it being slow)

In the end, if you are working on optimizing your JS, and you don't have super complicated setup, I'd highly recommend giving **preact** a go. It might be easier than you think.

p.s. the next step will be replacing **react-select** with [downshift](https://github.com/downshift-js/downshift). I've already implemented one small component with it, and it is amazing. Unfortunately, that migration will require a lot more code changes.
SCP between two hosts with non-standard ports
Tags: scp, bash, bsd, snippet
Published: 2020-01-17 14:16:32

_Originally posted on January 10th, 2020_ ([more info](https://dev.to/adamkdean/migrating-to-dev-to-190))

This applies to the BSD version of SCP, so that means MacOS.

When using SCP to transfer files between two remote hosts which both have non-standard ports, the -p and -P flags will not help you. For this, you need to use the scp protocol format. In addition, you have to pass the -3 arg, which transfers the files indirectly through your local machine, rather than directly between the source and destination machines.

```
scp -3 \
  scp://<user>@<source_hostname>:<port>/<path> \
  scp://<user>@<dest_hostname>:<port>/<path>
```
JS Flashcards
Tags: javascript, beginners, vue
Published: 2020-01-17 21:27:52

---
title: JS Flashcards
published: true
description: learn JS with flashcards
tags: js, beginner, Vue
canonical_url: https://mccarville.dev/js-flashcards
cover_image: https://thepracticaldev.s3.amazonaws.com/i/1xwv1c0jypg11w2286wg.png
series: JS Flashcards
---
# Learn JS With Flashcards

I built a site using Vue and Tailwind to create flashcards for learning JS. I have been working on the site the last few weeks and it is ready to check out. You can find it [here.](https://jsflashcards.netlify.com)  It is currently a work in progress, but the first two sections are complete. I plan to work on it on a weekly basis and add more sections and content.

## Why I built the site

I built the site for 2 reasons.

1. The first reason was to create a Vue project that was my own idea.  This has allowed me to practice both my Vue and general front end skills.  

2. The second reason was was to create flashcards to help other people learn JS while also solidifying my own learning. The process of trying to figure out what and how much content to put on the cards has been a great exercise, strengthening my own understanding. It's definitely true that one of the best ways to make sure that you understand something is to try and teach it to someone else.

## Article Series

Over the next few weeks I will be posting an article series explaining how I put together some of the elements and detailing how I overcame the challenges that I came across. Here is a list of some of topics that I will be covering:

1. **Design and Color scheme** - how I went about choosing the design and colors for the project
2. **Nav bar** - using flexbox to have one element on the opposite side of the others
3. **Mobile Nav** - hamburger menu and hiding on larger screens
4. **Flipping cards** - adding content and animating
5. **Modals** - show and hide on click
6. **Buttons** - click buttons on flipping card without the card flipping
7. **Style with Tailwind CSS** - extend theme in tailwind.config.js

## Make your own flashcards

I used Vue as the framework and JS as the topic, but you could use any framework or subject and make your own flashcards. You can either stay tuned for the articles or check out the project now on [Github.](https://github.com/jamiemccarville/js-flashcards)

Comments and suggestions are welcome. 

Thanks for checking out the project!
Instalar extensões PHP através do PECL
Tags: php, ptbr, pecl
Published: 2020-01-17 17:55:20

---
title: Instalar extensões PHP através do PECL
published: true
description: Instalar extensões PHP através do PECL
tags: php,pt-br,pecl
series: [PHP]
---

# PECL

Algumas vezes necessitamos instalar pacotes para que nosso PHP se comporte de uma forma esperada. Para certas situações podemos usar o PECL. 

## O que é o PECL
É um repositório de extensões PHP

## Ambiente
Os testes foram feitos no ambiente:

* Fedora 31 - 5.4.8-200.fc31.x86_64
* PHP 7.3.13 (cli) (built: Dec 17 2019 10:29:15) ( NTS )

## Instalação
O PECL necessita do PEAR instalado, assim, devemos prosseguir com,
```
dnf install php-pear php-devel
```

## Extensões
Vocẽ pode encontrar diversas [extensões](https://pecl.php.net/packages.php) no próprio site do PECL https://pecl.php.net/packages.php

Outra opção é utilizar o terminal para a pesquisa de extensões. Suponhamos que necessitamos instalar a extensão "memcache". No seu terminal digite:
```
pecl search memcache
```
para a pesquisa realizada teremos o retorno,
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/d35kki9weg7v381re2ph.png)

## Instalação
Depois de encontrar a extensão, devemos fazer a instalação, para isso, utilizaremos o comando:
```
pecl install memcache
```
o próximo passo será habilitar a extensão em nosso PHP, o pecl já nos informa o parâmetro a ser adicionado no php.ini

```
Build process completed successfully

Installing '/usr/lib64/php/modules/memcache.so'
install ok: channel://pecl.php.net/memcache-4.0.5.2

configuration option "php_ini" is not set to php.ini location
You should add "extension=memcache.so" to php.ini
```

## Configuração
Podemos inserir o parãmetro "extension=memcache.so" diretamente no php.ini, ou criar um novo arquivo, exemplo memcache.ini, na pasta de pacotes do php, no meu caso em /etc/php.d/

Agora é somente reiniciar o serviço
```
systemctl restart php-fpm.service
```
e utilizar o recurso instalado.
Jan. 17, 2020: What did you learn this week?
Tags: weeklylearn, discuss, weeklyretro
Published: 2020-01-17 18:44:46

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

<center>

![Homer Simpson studying](https://media.giphy.com/media/IPbS5R4fSUl5S/giphy.gif)

</center>

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}

And remember, if something you learnt was a big win for you, then you know where to drop it as well.👇👇🏻👇🏼👇🏽👇🏾👇🏿

{% link https://dev.to/jess/what-was-your-win-this-week-39ib %}

<center>

![Bender from Futurama dancing](https://media.giphy.com/media/mIZ9rPeMKefm0/giphy.gif)

</center>
CSS Goey footer
Tags: codepen
Published: 2020-01-18 01:15:29

<p>I'm a little late to the blob party, but I'm having fun<br>
Do not use this for real projects with this amount of blobs, use 24 of them or less 😛<br>
_  </p>

<p>Made using GistPad <a href="https://aka.ms/gistpad" target="_blank">https://aka.ms/gistpad</a><br>
Pen available as a Gist: <a href="https://gist.github.com/oauo/ecdf56c499e809ad671c4d85d5c2b90a" target="_blank">https://gist.github.com/oauo/ecdf56c499e809ad671c4d85d5c2b90a</a> </p>

{% codepen https://codepen.io/z-/pen/zYxdRQy %}
?signin=true
Implementing context menu using react hooks
Tags: javascript, react, reacthooks
Published: 2020-01-18 08:18:41

---
title: Implementing context menu using react hooks
published: true
description: 
tags: javascript, react, reacthooks
---

Sometimes you want to override the browsers default context menu in your react app. You can easily do this with a simple custom react hook. Such custom hook should tell you the X and Y position of the context menu and boolean to say whether you should render the component.

Here is a simple implementation of such custom react hook

```javascript
import { useEffect, useCallback, useState } from "react";

const useContextMenu = outerRef => {
  const [xPos, setXPos] = useState("0px");
  const [yPos, setYPos] = useState("0px");
  const [menu, showMenu] = useState(false);

  const handleContextMenu = useCallback(
    event => {
      event.preventDefault();
      if (outerRef && outerRef.current.contains(event.target)) {
        setXPos(`${event.pageX}px`);
        setYPos(`${event.pageY}px`);
        showMenu(true);
      } else {
        showMenu(false);
      }
    },
    [showMenu, outerRef, setXPos, setYPos]
  );

  const handleClick = useCallback(() => {
    showMenu(false);
  }, [showMenu]);

  useEffect(() => {
    document.addEventListener("click", handleClick);
    document.addEventListener("contextmenu", handleContextMenu);
    return () => {
      document.removeEventListener("click", handleClick);
      document.removeEventListener("contextmenu", handleContextMenu);
    };
  }, []);

  return { xPos, yPos, menu };
};

export default useContextMenu;
```

The hook adds two event listener one to intercept the right click and other to intercept the click event.

1. When you right click you can get X and Y position of the click using **event.pageX** and **event.pageY**
2. When you left click you toggle the menu so that it gets hidden

Here is a Menu component that uses that hook

```javascript
import React from "react";

import useContextMenu from "./useContextMenu";

const Menu = ({ outerRef }) => {
  const { xPos, yPos, menu } = useContextMenu(outerRef);

  if (menu) {
    return (
      <ul className="menu" style={{ top: yPos, left: xPos }}>
        <li>Item1</li>
        <li>Item2</li>
        <li>Item3</li>
      </ul>
    );
  }
  return <></>;
};

export default Menu;
```

You render the Menu component based on the boolean and you pass the X and Y position as inline styles.

[Here](https://rafi993.github.io/use-context-menu/) is the demo of the custom hook and [here](https://github.com/Rafi993/use-context-menu) is corresponding source code.
node express pug & html2pug 
Tags: node, webdev, productivity
Published: 2020-01-18 10:55:37

there a number of different ways to create a node express pug template from an existing html file

https://www.npmjs.com/package/html2pug

* https://html2pug.now.sh/ an online version
* https://html-to-pug.com/ an online version
* https://www.npmjs.com/package/html2pug via npm build 

see https://dev.to/osde8info/node-webdev-would-be-easier-if-3551 for an npm build example
IBM Data Science and AI Programs Free for 30 Days
Tags: tutorial, machinelearning, aws, database
Published: 2020-01-18 12:50:42

The tech giant, IBM is offering Data Science and Artificial Intelligence Programs on Coursera free for first 30 days until 30th of June 2020. 

The offer currently applies to select Data Science and AI specializations only. Scroll down to see the list of IBM programs this offer applies to.

I highly recommend that you check that out! Here's a list of all the IBM programs and certificates this offer applies to: 
[List of Coursera IBM DS, AI Programs with free access](https://onlinecoursesgalore.com/ibm-data-science-ai-coursera/)

Let me know what you think about this!
CKAD - Security Notes
Tags: kubernetes, devops, linux, docker
Published: 2020-01-18 18:13:28

To perform any action in Kubernetes cluster we need to access the API and go through three main steps:

* Authentication
* Authorisation (RBAC or ABAC)
* Admission Control

See the [official documentation](https://kubernetes.io/docs/reference/access-authn-authz/controlling-access/#admission-control) for more details:
![diagram](https://d33wubrfki0l68.cloudfront.net/673dbafd771491a080c02c6de3fdd41b09623c90/50100/images/docs/admin/access-control-overview.svg)

## Authentication

* Authentication is done with certificates, tokens or basic auth
* Users are *not* created by the API and should be managed by external system
* [Service accounts](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/) are used by processes to access the API *(a service account provides an identity for processes than run in a pod)*

## Authorisation

Once a request is authenticated, it needs to be authorised to be able to proceed through the Kubernetes system. There are three main modes of authorisation:

* ABAC (attribute based access control)
* RBAC (role based access control)
* WebHook

## Admission Controller

Accesses the contents of the objects being created by the requests. It can modify the content or validate it and potentially deny the request.


# Security Context

A security context defines privilege and access control settings for a Pod or Container so we can limit what processes running in containers can do. For example we can limit:

* the user ID of the process (UID)
* the Linux capabilities
* filesystem groups

If we want to enforce that containers cannot run their process as root user we can add **runAsNonRoot: true** to the pod spec. Or we can define a PodSecurityPolicy to that effect.

**To automate the enforcement of security contexts, we can define [PodSecurityPolicies (PSP)](https://kubernetes.io/docs/concepts/policy/pod-security-policy/)**

Pod Security Policies are cluster-level rules that govern what a pod can do, what they can access, what user they run as...

For a PSP to be enabled we must first configure the admission controller of the **controller-manager** to contain **PodSecurityPolicy**.

# Network Security Policy

A network policy is a specification of how groups of pods are allowed to communicate with each other and other network endpoints.

NetworkPolicy resources use labels to select pods and define rules which specify what traffic is allowed to the selected pods.
What you need to know before you include Python in your software stack in 2020
Tags: python, scripting, django, flask
Published: 2020-01-19 12:53:41

It’s the year 2020 and as usual, you will see a lot of blogs and conversations around ‘top 20 programming languages to master in 2020, what a full stack software engineer needs to know in 2020… how to earn the 6-figure salary in 2020… etc., I am not bringing a different message too 😉 I am just here to share my piece of cake too. Python. 
I fell in love with Python right from my introductory course to Computer Science not only because it is arguably the best language for beginners, but it’s also extremely powerful. 

Why Python? 
 >The underlying principles of the design of the python language focuses on clarity and simplicity.

>Python’s rapid and robust development capabilities can be applied in projects of any size- from the start-ups to already established corporations. 

>The use of python saves on time and money; you can quickly build MVP, do fast iterations, implement new features when necessary, integrate with other software and build a scalable business with a varying number of team members. PS: when working with python, you just need a small but strong team size for fast and efficient collaborations.

What can you do with Python?
Some the world’s biggest corporations such as Facebook, Google, Spotify, Netflix, Instagram, IBM and Quora have placed a bet on python. 
 	
There are 3 major applications of Python in the real world: web and app development, scripting, and data science. 

(i) Python for Scripting
Python has been designed with modules that help scripting basic functionalities quite easy. You can use python scripts to build email automation services, SMS features, data extraction from excel sheets, decrypting pdf files, reading and writing files, web scraping, etc. 
I recently discovered a book by  AL Sweigart, Automate the Boring Stuff with Python which is very good for practical scripting for both beginners and intermediate developers. 

(ii) Python for Web and app development 
The two most popular python frameworks, Django and Flask are quite useful when developing web and apps. Django has a more general use while Flask is mostly useful in relatively smaller projects.

(iii) Python for Data Science
Python is a very crucial language when it comes to AI development, in this case Data Science which includes machine learning, data visualization, and data analysis. Python has been supported by a number of libraries and frameworks such as TensorFlow, scikit-learn, matplotlib, seaborn, which are powered by machine learning algorithms to build smart systems. Most of the AI-powered applications such as recommender systems and business intelligence analytics have a great improvement on customer behavior and results in businesses. 

In conclusion…

If you want to python to be part of your software stack in 2020, you could decide on which aspect you want to focus on either as a scripting language, web development or data science. It wouldn’t take much to focus on all the 3 too if you are up for the task 😉 Whichever path you choose, I wish you a safe ride 😊
Set up a new React project with TypeScript, ESLint and Prettier
Tags: react, typescript, tutorial, eslint
Published: 2020-01-19 17:28:41

This is my workflow when I set up a new project, it should only take a few minutes to get everything up and running.

## Create React App

The easiest way to create a new React project is to use the [create react app](https://create-react-app.dev/docs/adding-typescript/), and you can easily have it set up with TypeScript too.

```bash
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript
```

## ESLint

Next, you will want to install ESLint, and plugins for TypeScript:

```bash
yarn add -D eslint eslint-plugin-react @typescript-eslint/eslint-plugin @typescript-eslint/parser 
```

Then in your project directory, create `.eslintrc.js`:

```javascript
module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  rules: {},
  settings: {
    react: {
      version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
    },
  },
  env: {
    jest: true,
  },
};
```

Now, you will have basic linting rules for TS:
![ESLint](https://thepracticaldev.s3.amazonaws.com/i/uazkzj9knk3kguj0am6o.gif)


## Prettier

Install Prettier for formatting your code:

```bash
yarn add -D prettier eslint-plugin-prettier eslint-config-prettier 
```

Create `.prettierrc.json`, and add the following:

```json
{
  "trailingComma": "es5",
  "printWidth": 100,
  "semi": true,
  "singleQuote": true
}
```

Then modify the `eslintrc.js`, and add these two lines:

```javascript
extends: [
  ...
  'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
  'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
```

With the [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) extension installed in VS Code, it will show any formatting errors:
![Prettier linting warnings](https://thepracticaldev.s3.amazonaws.com/i/uf1nlw1cq1arde3msues.png)

## VS Code

I would recommend turning on `formatOnSave`, and fix all ESLint error on save, to make your life even easier:

```json
{
   "editor.formatOnSave": true,
   "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
  },
}
```

## Finally

I hope you found it useful, please let know if you have any feedback.
Testing, Automation, Writing Articles 
Tags: testing
Published: 2020-02-16 04:38:30

I am having a hard time creating a focused article related to testing and automation. Maybe by laying out this challenge I will have an easier time having a focus. 

When discussing automation and testing, generally, this is in reference to building out a regression suite. However you can have the computer assist by crunching numbers or gather/organizing information. 

When discussing testing you could be referring to, checking/verification, regression, or exploration/learning. But regression testing could include both the verification of existing knowledge or explanation to find new areas not previously covered. I've already written some thoughts on regression. 

{% link https://dev.to/jessekphillips/full-regression-4jm7 %}

What is so hard about writing an article is defining which combination of these items is being discussed. I could start by defining which one I am speaking to. But in that case I'm ignoring all the others and since you need to do all of the above to have good testing trying to isolate doesn't matter, except it does.
it turns out that linuxlite isnt the pefect desktop distro for ex win 7ers :(
Published: 2020-01-19 21:46:55

last week i posted https://dev.to/osde8info/what-is-the-perfect-dev-env-desktop-distro-for-web-devs-3gk3 but just remembered to check some of my old linuxliteos wordpress posts

old linuxlite problems
REDACTED

and found a new problem
* linuxlite installs/uses leafpad instead of mousepad

so i feel i should downgrade its rating to 'almost perfect'
Day33:and_then,map_or,unwrap_or - 100DayOfRust
Tags: rust
Published: 2020-01-20 03:50:10

We can apply `and_then`, `map_or`, `unwrap_or` functions to an Option value:

* and_then: take the wrapped value as parameter if `Some`, return another Option value; or return `None` if `None`
* map_or: return a fallback value if `None`, and run a mapping function for `Some`
* map_or_else: run a fallback function if `None`, and a mapping function for `Some`
* unwrap_or: return a fallback value if `None`, or unwrap the value if `Some`
* unwrap_or_else: run a fallback function if `None`, or unwrap the value if `Some`


### Example


```rust
fn main() {
    let x = Some(4);
    
    // calculate 2*x + 3
    // we can and_then functions
    let result = x.and_then(|v| {
        Some(v * 2)
    }).and_then(|v| {
        Some(v + 3)
    });
    println!("#1: {}", result.unwrap());
    
    // map_or and map_or_else
    println!("#2: {}", result.map_or(42, |v| {
        v * v
    }));
    println!("#3: {}", result.map_or_else(
        || {42}, 
        |v| {v * v}
    ));
    
    // unwrap_or and unwrap_or_else
    println!("#4: {}", result.unwrap_or(42));
    println!("#5: {}", result.unwrap_or_else(|| {42}));
    println!("#6: {}", None.unwrap_or(42));
}
``` 

Result:

```
#1: 11
#2: 121
#3: 121
#4: 11
#5: 11
#6: 42
```

### Reference

* https://doc.rust-lang.org/std/option/enum.Option.html