teleren/devto huggingface dataset:
Custom order with sortBy() -- Bonus Livewire implementation
Tags: laravel, php, beginners
Published: 2020-03-15 06:29:42

I recently ran into an issue where I wanted to order a list of users by their role. The problem is the roles don't have any kind of order built in, and they're not alphabetical.

## Problem
**Teams** have a many-to-many relationship with **Users**. On the pivot table we have a `role` attribute.

Users can be one of 4 roles within a Team: Owner, Admin, Moderator, or Member.

We want to list members of a team in the above order.

## Solution

In the `->sortBy()` return a Closure with the array of keys you'd like to order by, and return their index.

```php
return $this->team->users()->withPivot('role')->get()->sortBy(function ($item, $key) {
    $order = ['owner', 'admin', 'moderator', 'member'];
    return array_search($item['pivot']['role'], $order);
})
```


## Bonus: Building this list in Livewire 

![Changing user roles](https://dev-to-uploads.s3.amazonaws.com/i/9f6abmts8ehdfb3q9947.gif)

```php
// livewire/Teamwork/MemberList.php
class MemberList extends Component
{
    public $team;

    protected $listeners = [
        'membersUpdated' => 'updateList',
        'roleUpdated' => 'updateList'
    ];

    public function mount($team)
    {
        $this->team = $team;
    }

    public function updateList()
    {
        //
    }

    public function render()
    {
        return view('livewire.teamwork.member-list', [
            'members' => $this->team->users()->get()->sortBy(function ($item, $key) {
                $order = ['owner', 'admin', 'moderator', 'member'];
                return array_search($item['pivot']['role'], $order);
            })
        ]);
    }
}
```

### Wrapping Up

So this works great for me and I was happy to find a way to create a custom order. I'd like to hear from someone with more experience about alternate ways to accomplish this.
Avoid deeply nested imports with path mapping in typescript
Tags: typescript, productivity, beginners
Published: 2020-03-15 06:06:50

![image from unsplash](https://images.unsplash.com/photo-1531771923027-5f4232d48279?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1575&q=80)
<figcaption>Photo by Lukas Beran on Unsplash</figcaption>

Importing modules with relative paths can be such a pain as your codebase grows and you start splitting large files into smaller reusable modules. Files get nested very deep so much you stare at your folder structure perplexed. Consider the following folder structure:
```json
root/
   tsconfig.json
   types.d.ts
   .env
   src/
      server.ts
      database/
      models/
      routes/
         posts/
         comments/
      controllers/
         posts/
         comments/
         media/
      utils/
         database/
            seed.ts
         workers/
            publisher.ts
```
Say you want to import a function from a module in `src/utils/workers` into the post controller, it's already looking like a mess: `import { function } from "../../utils/workers/publisher.ts"`. This can get even messier when file locations change and you need to update everywhere you imported that file.

One way to tackle this is to use typescript path mapping. You define a namespace in your tsconfig mapping it to a specified path by declaring a `paths` field in your `tsconfig.json` under `compilerOptions` like so:
```json
{
   "compilerOptions": {
      "baseUrl": ".",
      "paths": {
         "@workers/*": ["src/utils/workers/*"],
         "@mediaControllers/*": ["src/controllers/media/*"]
      }
   }
}
```
Here, we set the baseUrl to the root directory, which is **necessary** for creating path maps. We create a namespace "@workers" which maps to the path "src/utils/workers/". The '@' symbol is not necessary, it's just there to easily standout and make it recognizable as a namespace.

Now if we want to import a module from `workers`, we simply use the namespace. i.e `import { function } from "@workers/publisher.ts"`. We don't have to worry about relative paths anymore, and when we move files from their original location, we just simply update the path map. So problem solved! 😁️.

**Note** that typescript resolves paths relative to `baseUrl` so keep that in mind when creating path maps.
I feel like creating my own PHP CMS
Published: 2020-03-15 06:01:34

Hey everyone, 
I'm <a href="https://www.naijaprey.com.ng/author/np-staff/">Vadoh</a> and I needed a small kind of advice, will it be nice if I start creating my own PHP Script Content Management System...

Or I should just by a PHP Script from Code Canyon!

Your answers and advice will be appreciated!
Understanding how to use Redux using React Hooks in 5 minutes
Tags: react, redux, hooks
Published: 2020-03-15 05:59:17

If you have been using Redux, and wonder how it can be used with React Hooks, this is how it is done:

Traditionally, this is how a component is connected to the Redux store:

```javascript
import React from 'react';
import { connect } from 'react-redux';

function Count(props) {
  return (
    <div>
      <button onClick={props.increment}> + </button>
      {props.count}
      <button onClick={props.decrement}> - </button>
    </div>
  );
}

const mapStateToProps = state => ({
  count: state.count
});

const mapDispatchToProps = dispatch => ({
  increment: () => dispatch({ type: 'INCREMENT' }),
  decrement: () => dispatch({ type: 'DECREMENT' })
});

export default connect(mapStateToProps, mapDispatchToProps)(Count);
```
Note that the `Count` component gets the state and the dispatch functions by `props`. But now, using React Hooks, we can get them by using `useSelector()` and `useDispatch()`:

```javascript
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

function Count() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();

  const increment = () => dispatch({ type: 'INCREMENT' });
  const decrement = () => dispatch({ type: 'DECREMENT' });

  return (
    <div>
      <button onClick={increment}> + </button>
      {count}
      <button onClick={decrement}> - </button>
    </div>
  );
}

export default Count;
```
That's it.  `useSelector()` is similar to `mapStateToProps()`, and `useDispatch()` is similar to `mapDispatchToProps()`. All the other files stay the same, and that's how you can use Redux using React Hooks. 

We can think of it this way:
- there are two things we need
- if we don't have redux, but just a React component, we are familiar with the fact that we need (1) the state to display the data, and (2) we need a callback to make the change of state to happen.
- Now, with Redux, similarly, we need:
- (1) is the state from the "one and only store", which is the redux store
- (2) we need a dispatch function to dispatch an action, so that the reducer can create a brand new shiny state for us
- so we can get the state by `useSelector()`
- and we can get the `dispatch` function by `useDispatch()`
- and then, the rest will follow: we have the state to display, and we have the mechanism to change the state if there is a need, using the `dispatch()`.

For further details, check out the [official Redux Hooks](https://react-redux.js.org/api/hooks) page.
How to inject DLL scripts into html with HtmlWebpackPlugin?
Tags: dll, webpack, htmlwebpackplugin
Published: 2020-03-15 05:55:55

---
title: How to inject DLL scripts into html with HtmlWebpackPlugin?
published: true
description: This article tell you how to use HtmlWebpackPlugin's hooks to inject DLL scripts (event other scripts) into html.
tags: DLL, webpack, HtmlWebpackPlugin
---

As a way to speed up building of webpack, DLL is an almost mentioned way. But when we use HtmlWebpackPlugin to auto inject scripts into html, the dll scripts will not be injected. So, do we have a way to do this?

Yes!

HtmlWebpackPlugin has hooks which can help us to implement this. In my solution, I create a shared plugin called `InjectDllHtmlWebpackPlugin`, and the source code:

```js
class InjectDllHtmlWebpackPlugin {
  constructor(options) {
    this.options = options
  }
  apply(compiler) {
    compiler.hooks.compilation.tap('InjectDllHtmlWebpackPlugin', (compilation) => {
      compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync(
        'InjectDllHtmlWebpackPlugin',
        (data, cb) => {
          data.assets.js.unshift(...this.options.files)
          cb(null, data)
        }
      )
    })
  }
}
```

I used webpack v4.x, and HtmlWebpackPlugin version 3.2.0 whose hooks may change in version 4.x which is now in beta.

Let's look into HtmlWebpackPlugin's source code [here](https://github.com/jantimon/html-webpack-plugin/blob/v3.2.0/index.js#L54). The author add some hooks for webpack v4, so that we can use htmlWebpackPluginBeforeHtmlGeneration hook to change `assets.js` option for the plugin to generate scripts tags.

Next, we use the previous plugin in webpack together with HtmlWebpackPlugin:

```
{
  plugins: [
    new DllReferencePlugin(...),
    new HtmlWebpackPlugin(...),
    // InjectDllHtmlWebpackPlugin should must come after HtmlWebpackPlugin
    new InjectDllHtmlWebpackPlugin({
      files: [
        'react.dll.js', // notice, this is the src url of script tag
      ],
    })
  ],
}
```

This is the way to auto add your dll scripts into your html. You can get my source code from project [nautil](https://github.com/tangshuang/nautil-cli/blob/master/plugins/inject-dll-html-webpack-plugin.js).
Understanding the Key Concepts of Compilation in JavaScript 
Tags: javascript
Published: 2020-03-15 05:17:32

JavaScript can be best described as a compiled language. One may ask, "What is a compiled language?" Simply put, compilation is when code is transformed, through a series of steps, into instructions that your computer can then execute. During compilation, the entirety of the code is changed all at once. JS programs are run through two phases: compilation and execution. The programs are compiled before they are executed.

Compilation is important to consider and learn because it is during compilation that scope is determined. The scope, in turn, affects how the program is executed. Compilation broadly consists of three stages: Tokenizing/lexing, parsing, and code generation. 

First, tokenizing/lexing is when the code is split up into meaningful chunks. For example, `var c = 0` can be split up into the tokens `var`, `c`, `=`, `0`.

Parsing is when these tokens are collected and formed into the Abstract Syntax Tree (AST). The AST can be describes as the grammatical structure of the program. According to Wikipedia, it is "a tree representation of the abstract syntactic structure of source code written in a programming language." To simply put, it represents the structure of the code. Lastly, during code generation, the AST is transformed into executable code. 

So what exactly is the significance of compilation on how code is executed? Is there actual proof of compilation? Consider the code below. 

```javascript
var month = "It is March, 2020.";

console.log(month);

var month = ."It is March 14, 2020.";
// SyntaxError: unexpected token .
``` 
When this program is run, the console.log statement is in fact, not executed. This is because of the syntax error, which comes from the period, in the redeclaration of `var month`. This shows how the code is first compiled and then executed. Otherwise, the console.log statement would have been executed and then the error would have appeared.
What is Machine Learning?
Tags: machinelearning, ai, machinelearningmodel
Published: 2020-03-15 04:44:34

Machine learning is a method of data analysis that automates analytical model building. It is a branch of artificial intelligence based on the idea that systems can learn from data, identify patterns and make decisions with minimal human intervention.

Why is Machine Learning important?

The iterative aspect of Machine Learning is important because as models are exposed to new data, they are able to independently adapt. They learn from previous computations to produce reliable, repeatable decisions and results.

What’s required to create good machine learning systems?

-Data preparation capabilities.
-Algorithms-basic and advanced.
-Automation and iterative processes.
-Scalability.
-Ensemble modelling.

What is a machine learning model?

A Machine Learning Model can be a mathematical representation of a real-world process. The learning algorithm finds patterns in the training data such that the input parameters correspond to the target. The output of the training process is a machine learning model which you can then use to make predictions.


What is a machine learning algorithm?

Machine learning algorithms build a mathematical model based on sample data, known as “training data”, in order to make predictions or decisions without being explicitly programmed to perform the task.
Differentiating RPA from traditional automation
Tags: begineers, rpa, automation, robotics
Published: 2020-03-15 03:44:47

Not too long ago, I wrote a post about [demystifying RPA](https://dev.to/itsthuya/demystifying-rpa-robotic-process-automation-lmh).  Since then, I have been asked numerous times about how do RPA processes differ from traditional automation? Hence, I decided to write a post about it too for the benefit of others who have a similar curiosity.

Before getting into the similarities and differences, let's recap on the definitions of RPA and traditional automation. If you do a quick google search, you will find various posts that define them adequately. Too much work? Don't worry. I have summarized them for you so that you don't have to.

Traditional automation is an umbrella term for all form of automation that automate repetitive tasks. Though, RPA (robotic process automation) is just a form of automation technology that automate repetitive business processes through existing user interfaces by mimicking a user (a human). 

Did you get it? Great! If not, let's go a little deeper. Hopefully, by the end of this post, you have a clear understanding of it. 

The main selling point of RPA is that it does not require any changes to the underlying IT infrastructure. It can just augment with the existing systems and processes. Most of the time, the identified processes to automate are the business processes that are being carried out by the human counterpart day-to-day anyway. The next point is that RPA does not require a team of IT professional to work on new systems to migrate from or integrate with the existing systems. Hence, it saves time and overall labour needed. 

Traditional automation, on the other hand, it requires some changes to be implemented to the underlying IT infrastructure to get the most out of it. Instead of automating the existing process flows through user interfaces, it probably requires to implement APIs (Application Programming Interfaces) and expose back-end database connections for seamless automation. For those reasons, it needs more labour and time compare to RPA processes. 

In summary, RPA automates processes through existing user interfaces just like a human would where traditional automation approaches it by modifying to and integrating with the underlying systems. I hope this clear thing up. Please let me know your thoughts in the comment section. Constructive feedback is always appreciated.
Animation with vanilla css
Published: 2020-03-15 02:55:21


![A map shaking](https://media.giphy.com/media/YnNgiVoHgtjDrVPbES/giphy.gif)

Animation makes our app look a little exciting and it is very easy to do it with plain css. The first thing we need is the  `@keyframes` css keyword. what that keyword does is that it lets us control an element on the dom. We can tell the dom to do a certain action in exact intervals. We measure intervals in percentages. 


```
  @keyframes shake {
    0% { transform: translate(1px, 1px) rotate(0deg); }
    10% { transform: translate(-1px, -2px) rotate(-1deg); }
    20% { transform: translate(-3px, 0px) rotate(1deg); }
    30% { transform: translate(3px, 2px) rotate(0deg); }
    40% { transform: translate(1px, -1px) rotate(1deg); }
    50% { transform: translate(-1px, 2px) rotate(-1deg); }
    60% { transform: translate(-3px, 1px) rotate(0deg); }
    70% { transform: translate(3px, 1px) rotate(-1deg); }
    80% { transform: translate(-1px, -1px) rotate(1deg); }
    90% { transform: translate(1px, 2px) rotate(0deg); }
    100% { transform: translate(1px, -2px) rotate(-1deg); }
  }
```

The whole animation is considered 100%.If the change we want should happen in the beginning we put it at 0%. If we want it to be halfway through the animation, we put it at 50% and at 100%, if that is the last thing we want done. We started from the beginning(0%) and told the element to move 1px on the x-axis and 1px on y-axis and rotate 0 deg and so on and so forth.

The next thing we have to do is bind the function to an element.

```
#map:hover {
    /* Start the shake animation and make the animation last for 0.5 seconds */
    animation: shake 0.5s;
  
    /* When the animation is finished, start again */
    animation-iteration-count: infinite;
  }
```
I put an event listener on the map, so when someone hovers over it this css blocks get triggered. `animation: shake 0.5s;` There are three arguments on this line, first is the animation keyword, then it is the name of the function we wrote above  and the length of how long it should run.A thing to note, the percentages are of the time we mention in this command. 50% in keyframes is 50% of 0.5s in our example.

There are many things possible with @keyframes. We could even change the colors programmatically
```
@keyframes colorChange {
  0%   {background-color: red;}
  25%  {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}
```
We can use negative numbers to make it look like the animation was already playing and if leave out 0% and 100% it will automatically make those two points equal to the beginning state of the element and it will start and end the animation at the same state

Yay!! Now you know how to add animation using css. Hopefully it will bring as much joy to your projects as it did to mine
Instalando ROracle en R/Rstudio para Windows
Tags: r, rstudio, oracle, spanish
Published: 2020-03-15 02:51:37

---
title: Instalando ROracle en R/Rstudio para Windows 
published: true
description: Una pequeña guía para instalar el driver de Oracle en R e interactuar con Oracle RMDB desde R/Rstudio
tags: R, Rstudio, oracle, spanish
---

# RStudio con ROracle en Windows
El siguiente es un instructivo para la instalación de ROracle en R/Rstudio, para poder acceder desde dichas herramientas a bases de datos Oracle.

## R
R es un lenguaje de programación pensado para las personas que necesiten una herramienta eficaz para el análisis de datos estadísticos.

## RStudio
RStudio es un IDE (Entorno de Desarrollo) que utiliza R como base. El mismo extiende el uso del lenguaje para poder utilizar ciertas herramientas extras que para mejorar la experiencia de usuario al momento de trabajar con el lenguaje

## RTools
Paquete extra para R que permite compilar código fuente de manera más eficiente. Es requisito de algunos componentes utilizados en R, y es crucial para la utilización de ROracle

## ROracle
Es el conector de R al motor de base de datos Oracle.

## Prerequisitos para instalación
### R

### RStudio

### RTools
Se puede descargar desde [aquí](https://cran.r-project.org/bin/windows/Rtools/)

### Oracle Client
- Basic Package
- SDK Package
Se pueden descargar desde este [link](https://www.oracle.com/database/technologies/instant-client/winx64-64-downloads.html).


## Instrucciones de Instalación:
1. Instalar R.
2. Instalar Rtools.
3. Instalar Rstudio.
4. Descomprimir los ZIP de Oracle Client y Oracle Client SDK en la unidad C (C:\\ ).
5. Colocar el archivo **ociver.h** (C:\instantclient_19_5\sdk\include\ociver.h) en la carpeta **include** de la instalación de R (C:\Program Files\R\R-3.6.2\include).
6. Creamos la variable de entorno OCI_LIB64 y le colocamos el valor de la ruta del cliente de Oracle (C:\instantclient_19_5).
7. Modificamos la variable del sistema PATH agregandole un nuevo valor con la ruta del cliente de Oracle (C:\instantclient_19_5).
8. Procedemos a instalar el driver de Oracle para R llamado ROracle:
- Dentro de R y o RStudio ejecutamos la siguiente línea de comando:
```
install.packages("ROracle")
```

Esto procederá a descargar el paquete y el mismo se compilará.
Streaming Corona Posts from Reddit to Slack
Tags: database, inthirtyseconds, architecture
Published: 2020-03-15 01:57:17

This is my thought process to implement a streaming flow that just downloaded Corona related posts from Reddit into my personal SLACK using KStream library. If I get decent number of impressions I will walk you through the actual implementation.
<a data-flickr-embed="true" href="https://www.flickr.com/photos/183481767@N07/49657448546" title="Corona-Slack"><img src="https://live.staticflickr.com/65535/49657448546_1c115bac07_6k.jpg" width="2038" height="6144" alt="Corona-Slack"></a><script async src="//embedr.flickr.com/assets/client-code.js" charset="utf-8"></script>
Why people want to be a programmer
Tags: javascript, tutorial, softskill
Published: 2020-03-15 01:11:18

Why do people want to be a programmer? I think 99% percent of them heard that programmers earn a lot of money :) Yep it's true but not everyone. I have friends who are programmers but they earn just 4k per month. 4k PLN so it's like 1K USD! 

So why they earn so small? Because they stay in place. They don't do any courses or tutorials to improve their skills. They settle down on a nice, comfortable job where they do boring tasks day by day ... such o shame? Not really. They are happy so I think it's ok for them. But should it be? Not really. I think every one of us on Earth should have some mission. To make this world better. I know it's so philosophical but WHY programmers focus mainly on hard skills forgettable about soft skills like WHY we code? What do we want to do? Just make money? For me, programming is a mission that's why I teach programming newbie.

Next reason that why people want to be a programmer is remote work. Ok but it's not for everyone. Do you have self-discipline? If you don't it's not for you. Most of us don't have enough self-discipline to work remotely. 99% percent of junior developers want to work remotely. How do you get knowledge from more experienced teammates? Working face2face when you have the possibility to ask a question is the most efficient way to get more experience and additional knowledge if you are a newbie.

What do you think about a newbie in IT (spacially programming) world?
Hell world - I'm Wojtek
Tags: javascript, python, tutorial
Published: 2020-03-15 00:58:25

Hi crew!

Wojtek here! I'm from Poland - CRACOW! People say I'm Full-Stack Developer :D Maybe I am ... I worked with PHP now I work with Python but always I work with JS, HTML, CSS. 

If you have any questions or ideas for content please let me know in comments. I <3 share knowledge but I have one big problem ... I don't know what's interesting to YOU! Just tell me and I will help you!
Shouldn't We Have an Agile Tag?
Tags: discuss
Published: 2020-03-15 00:48:14

I see a lot of great tags on dev.to. However, I am surprised we do not have an agile tag. I think the community will benefit greatly by having this tag.

I know agile can differ from team to team even within a single organization. That's because some things work better for some teams than others. I think that we could have an agile tag where folks can share their experiences with agile. This will help others learn from other people's experiences.

What do you think?