teleren/devto huggingface dataset:
Code Snippet Series: Get Unique Values from Array
Tags: javascript, performance, algorithms, beginners
Published: 2020-08-04 00:55:56

Here are three ways to retrieve the unique set of primitive values from an array....

```JS
//a. Set-Array.from
const getUniq_ArrayFrom = a => Array.from(new Set(a));

//b. Set-Spread
const getUniq_Set = a => [...new Set(a)];

//c. good ol' Loop
const getUniq_Loop = a => {
  const o = {};
  for (let i = 0; i < a.length; i++) {
    o[a[i]] = true;
  }
  return Object.keys(o);
};


//@perfTests

timeInLoop("getUniq_ArrayFrom", 1, () => getUniq_ArrayFrom(aNums));
// getUniq_ArrayFrom: 1e+0: 513.777ms

timeInLoop("getUniq_Set", 1, () => getUniq_Set(aNums));
// getUniq_Set: 1e+0: 521.112ms

timeInLoop("getUniq_Loop", 1, () => getUniq_Loop(aNums));
// getUniq_Loop: 1e+0: 44.433ms
```

I think we have a clear winner here. :trophy:
The loop wins by over 10X

# Notes:

using an array of 10 million numbers between 1 and 100 (high duplication), the Loop idiom is 10X faster...
```JS
const aNums = genRandNums(1, 100, 1e7);
```

using an array of 10 million numbers between 1 and a million (low duplication), the Loop idiom is only 2X faster...
```JS
const aNums = genRandNums(1, 1e6, 1e7);
```

# TimeInLoop Source Code:
https://gist.github.com/funfunction/91b5876a5f562e1e352aed0fcabc3858
Invisible Unicode - Coding Deep Dive Episode #1
Tags: javascript, unicode, cdd
Published: 2020-08-04 00:52:49

This is an article I first published on Dev.to in March of this year over here: https://dev.to/emnudge/adventures-in-horrible-no-good-very-bad-variable-names-20ii

I figured that the way the article was formatted might work better as a video, so I wrote a script, did some more research, recorded it, and made it into a video. Took about 5 months, but here it is!

{% youtube vHkM6RwA7Wk %}
Learn how to Make your As and Bs in the forthcoming WAEC EXAM 
Published: 2020-08-04 00:15:44

#WAEC  #2020 #EXPO - WAEC 2020 AUGUST /SEPTEMBER WAEC RUNS Questions And Answers Expo Runz, WAEC 2020 EXPO! Subscription Is ON now For WAEC 2020 Midnight Answers. (A Day Before Exam) 💯 ✅
. 
WhatsApp Or SMS: 📞  
WhatsApp Direct Link: https://wa.me/2347041116516
Using Node.js to get useful GitHub data
Tags: github, showdev, node, womenintech
Published: 2020-08-04 00:02:58

The purpose of this project is to get key info about existing repos to show on my portfolio projects page. Instead of manual adding essential the same info in 2 places i.e. name, description and topics, I thought it would be worth looking into how to integrate with GitHub - Node.js style.

# Using the GitHub API?
I looked at using the GitHub API but found the documentation to be hard to understand and too extensive if that makes any sense... I wanted to do this quickly so maybe given more time it would have suited my needs.

***Please note this project is currently a work in progress and wanting to explore more.***

[Repo here](https://github.com/lornasw93/my-projects-api)

# Let's jump in 🏃‍♀️

Creating a new folder in my workspace called *my-projects-api* then `cd` into that and a cheeky `npm init` to start things off. I'm using a couple packages so to add them too.
 ```
 npm i express
 npm i cors
 npm i body-parse
 npm i axios
```

I have a *config.js* file to keep my secrets, you'll need to get a GitHub token if you haven't already.

```
var config = {};
 
config.githubToken = '################################';
config.githubUsername = 'lornasw93'; // not secret just saves putting in a few places

module.exports = config;
```

My aim at this point is to get a list of my repos, keeping it simple to start with. Something a bit odd too, or so I think, topics aren't included by default in the response. To include topics you need to add a `Accept` header (as shown below).

```
var express = require('express'),
    cors = require("cors"),
    app = express(),
    bodyParser = require('body-parser'),
    config = require('./config'),
    axios = require('axios');
 
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(cors());
 
app.get("/api/repos", (req, res) => {
    axios({
        method: "get",
        url: `https://api.github.com/users/${config.githubUsername}/repos`,
        headers: {
            Authorization: `Bearer ${config.githubToken}`,
            "Content-Type": "application/json",
            "Accept": "application/vnd.github.mercy-preview+json" // MUST ADD TO INCLUDE TOPICS
        }
    }).then(response => {
        res.send(response.data);
    }).catch(err => {
        res.send(err);
    });
});

const PORT = process.env.PORT || 3000;
module.exports = app.listen(PORT, () => {
    console.log('Server running on port %d', PORT);
})
```

# Result ✅

I call the above method, in my case, from my website's project service class like so *http://localhost:3000/api/repos* and a JSON object is returned. I don't need all that data just a few bits so, I loop round the repos and fetch out the interesting parts. *Note this particular change with using this new API isn't reflected on my current live site, only locally*. The data I'm displaying is:
- Name
- Description
- Topics
- Url
- Homepage (basically website URL)
- Updated at

With the end result looking like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/78h0p4xljfoc9kml5km5.PNG)
 
### Thanks for reading! 😀
Static methods in JavaScript
Tags: javascript
Published: 2020-08-04 00:00:00

---
  title: Static methods in JavaScript
  published: true
  tags: JavaScript
  date: Tue Aug 04 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/static-methods-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-6e7c0a4d39ad68d17e43c60f3ed54acb.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/static-methods-javascript)
  
Static methods are those methods which are directly attached to a class or a constructor function rather than being a method on an object.

Static methods are common to every object since they are attached directly to a class or constructor function

Let's understand,

```javascript
// create a class
class User {
  constructor() {
    // property name
    this.name = "User";
  }

  // method sayHello()
  sayHello() {
    console.log("Hey, I'm a user");
  }
}
```

Here we have created a class `User` with a property `name` and a method `sayHello()`.

We haven't created a static method yet.

To create a static method we have to use the `static` method in class syntax.

```javascript
// create a class
class User {
  constructor() {
    // property name
    this.name = "User";
  }
  // static method
  static iStandAlone() {
    console.log("I can be called without creating an instance of a class");
  }

  // method sayHello()
  sayHello() {
    console.log("Hey, I'm a user");
  }
}
```

Since static methods are directly attached to a class and not on the instances of a class, we can call the static methods without making an instance of a class ( or object of a class).

You can static methods by using the class name followed by a dot `.` and static method name like this `User.iStandAlone()`

```javascript
// create a class
class User {
  constructor() {
    // property name
    this.name = "User";
  }
  // static method
  static iStandAlone() {
    console.log(
      "I can be called without creating an instance or object of a class"
    );
  }

  // method sayHello()
  sayHello() {
    console.log("Hey, I'm a user");
  }
}

// iStandAlone() method can be called
// without craeting an instance or object of a class
User.iStandAlone();
```

In constructor function, static methods are made by attaching a function directly to it like this,

```javascript
// constructor function
const User = function () {
  // property name
  this.name = "User";
};

// method sayHello()
// attached to prototype chain
User.prototype.sayHello = () => {
  console.log("Hey, I'm a user");
};

// attach iStandAlone() method
// directly to constructor function
// not on prototype chain
User.iStandAlone = function () {
  console.log(
    "I can be called without creating an instance or object of a class"
  );
};

User.iStandAlone();
```

Now you may ask why do we even need static methods in a class.

The answer to that is if you want to create utility functions for objects or instances you make out of a class, declaring those methods as static methods is a good object-oriented approach.

### Feel free to share if you found this useful 😃.

---
Deep Dive into Container Security Scanning
Tags: docker, container, security
Published: 2020-09-03 04:55:36

---
title: Deep Dive into Container Security Scanning
published: true
date: 2020-08-04 00:00:00 UTC
tags: Docker,Container,Security
canonical_url: https://www.loginradius.com/engineering/blog/container-security-scanning/
---

At the heart of any image scanning tool is static analysis against a “Common Vulnerabilities and Exposures” (CVE) database. Each layer within the container image is analyzed and queried to discover known vulnerabilities.

   
[Read On](https://www.loginradius.com/engineering/blog/container-security-scanning/)
Flow to Source implementation with Akka streams
Tags: akka, scala, functionalprograming, streams
Published: 2020-08-03 23:58:30

---
title: Flow to Source implementation with Akka streams
published: true
description: Connecting an Akka streamflow with a source
tags: Akka, Scala, FunctionalPrograming, Streams
cover_image: https://blog.selectel.com/wp-content/uploads/2017/05/PR-2004-7.png
---

**NOTE:** This post requires previous knowledge of scala using the [Akka](https://akka.io/) framework specifically [Akka streams](https://doc.akka.io/docs/akka/current/stream/index.html).

#Akka streams structure

The Akka streams module of Akka provides a beautiful DSL that will help you to move data in an asynchronous way. The base of an Akka stream is composed of 3 main components:

```
Source ~> Flow ~> Sink
```
- Source:  Which is in charge of emitting the data through the stream, only have outputs ports
- Flow: receive the data, transform it and send it to the next component
- Sink: The end of the stream it will be the last step of any stream, only have input ports.

# The problem

So far so good but what happens when we need to get the data from a source and this receives the key on the fly? i.e we need to download a file but we don't know the name of the file which arrives frow a previous step and we are using a library to download the file which is a source.

### FlatMapConcat FTW

The FlatMapConcat flow allows us to transform any input element into a source this means we can connect a flow with a source, something like this:

```
Source ~> Flow ~> Source ~> Sink
``` 
A simple sample would look like this 
```
1    //Simple Source
2    val src = Source(List(1, 2, 3))
3
4    val fromSrc = b.add(Flow[Int].log("from-Src"))
5
6    //Emit new list per element received
7    val flow = b.add(Flow[Int].flatMapConcat{ element =>
8      Source(List(4, 5, 6))
9    })
10
11    //¯\_(ツ)_/¯ nothing to do, just for sample purposes
12    val map = b.add(Flow[Int].map{ element =>
13      element
14    })
15
16    src ~> fromSrc ~>flow ~> map ~> sink
```
At line 16 in the main flow, we can see the 3rd step of our process is a regular flow but digging into it at line 8 we notice this flow is actually a Source that receives data from the flow FromSrc and emits new data to the map flow. 🙌🏻

That's it we just connected a source in the middle of a stream that emits new data based on the received data. 

...
In case you want to run the sample check out my gist [here](https://gist.github.com/vianel/e9a0ac0ae8c542fe0a1709a1501cafc9)
Super, Sub, and Abstract Classes
Tags: java
Published: 2020-08-03 23:54:51

When we get into coding anyone who has been coding for any period of time knows we want to keep our code DRY. Whenever you see yourself copying methods and variables from one class to another we may want to set up a relationship between the classes. 

An easy way to look at this would be a vehicle. If someone was to ask you to draw a vehicle some people may draw a car, a truck, or a motorcycle. Similarly if I google a picture of a car it shows me pictures of hundreds of different types of cars. In this regard the more abstract the concept the higher in the class it should be, with vehicle being the upmost Super class in this case. Similarly the more specific it gets the more sub it would be with maybe 2017 Ford Mustang GT being the most specific so being the final subclass in the tree. 

When we look at Super and sub classes it is important to know what is inherited vs what is accessible/callable. As you know if you have been working with java for any amount of time we designate things _private, public, and protected_. A subclass inherits everything from a Superclass, but not everything is necessarily accessible in the subclass. If you have a _private_ method or variable you cannot call them directly in the subclass. As in other cases _public_ methods and variables are both accessible and are also inherited to the class. 

The biggest designation to get used to when using Super and subclasses would probably be _protected_. A _protected_ method or variable is inherited and callable in the subclass but is not callable in non related classes. For instant if we had a protected method in car it could not be accessed in boat for instance, but that method would be callable in Ford. 

So how do we set up these relationships in Java. In Java we use **_extends_** to set up the relationship between classes. the subclass extends the superclass to let the compiler know it is the sublcass of the super.

``` 
public class Car extends Vehicle { 

}
```

In this set up there is a flaw though we want to have the super class vehicle and we want a method drive in this super class but each subclass needs to implement drive in its own way and we don't want people to be able to create a vehicle because technically vehicles don't exist on their own. This is where abstract classes and methods come into play.

```

public abstract class Vehicle {

protected abstract void drive();

}
``` 

Above we have created the abstract class vehicle which contains the abstract method drive. It is import that any subclass of vehicle must implement the method drive. Any subclass that does not implement the abstract method will become an abstract class. 

Now there is a lot more we could go into depth to include constructors and how those are implemented but I will go over that more in a future post.
Testando um novo editor de código no NLW#2
Tags: webdev, html, css, javascript
Published: 2020-08-03 23:46:22

# O NLW#2

Nessa semana iniciou o [Next Level Week #2](https://nextlevelweek.com/inscricao/2). O NLW é uma semana criada pela Rocketseat onde iremos desenvolver uma aplicação do zero e assim poder descobrir na prática novas ferramentas e conceitos. O primeiro NLW foi de muito apredizado. O segundo também promete ser ótimo. A semana começou hoje 03 de agosto e vai até o dia 09 de junho.

# Novas ferramentas e o porquê da escolha

Meu notebook é velho e não é dos bons. Não consegui utilizá-lo para nada na semana passada. Ficou impossível utilizar o VSCode e Crhome ao mesmo tempo, por exemplo.

Depois de muitas tentativas de melhorar a situação, eu decidi desisntalar todos os programas do notebook e instalar outros bem mais leves. Não vou falar de todos aqui. Irei mencionar somente o editor de código. Eu queria algo mais leve e acabei decidindo por tentar o Vim. Eu sabia que não iria ser fácil mas não sabia que iria ser tão desafiador.

# Editor de textos Vim

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

O [Vim](https://www.vim.org) é um editor de texto que é executado dentro do terminal. Usamos bastante o teclado para manipulá-lo. Não tem interface gráfica, por isso nem se usa o mouse. Não vou me alongar no assunto aqui porque eu pretendo fazer um post falando só dele. Mas quero deixar uma imagem do meu Vim depois de algumas configurações e plugins instalados.

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/44ixwfo5z7qde93gmzqj.png)
Why unit test culture is broken
Tags: python, javascript, unittest, testing
Published: 2020-08-03 23:41:20

Write unit tests should be as fun as writing your feature code, no matter which language you're using, it's all code at the end of the day.

## How it can be improved
Sending the right message is key in my point of view to improve your unit test culture, you don't write unit tests because of the most advanced framework or the best methodology out there.

They exist as a tool to help you to achieve the goals, which is to have a stable, reliable and documented codebase.

## How the tools help
The framework will help you to mock calls to external sources that sometimes are 3rd party libraries, that we may don't need wanna include in your test cases.

The methodology let's say [TDD(Test-Driven Development)](https://en.wikipedia.org/wiki/Test-driven_development) is a really helpful one, but I don't think that it's the only way of doing it, depends on your project, if there's legacy code, the timing of task and so on. You may find yourself writing together or at the end of your feature code. 

## Let's have a bit of fun
Just to have some code here, and if you're at the beginning of your developer journey let's see how a simple test looks like in python.

A python class that prints the greetings message as ASCII art and return the base string. 

```python
from art import *

class HelloClass:

    def __init__(self):
        self.HELLO_MSG = "Hello world, "

    def greetings(self, name):
        msg = f"{self.HELLO_MSG}{name}"
        text_art = text2art(msg)
        print(text_art)
        return msg
```

Then its unit test will be like this one.
```python
import unittest
from python_class import HelloClass

class TestHelloClass(unittest.TestCase):

    def test_greetings(self):
        hello_class = HelloClass()
        self.assertEqual(hello_class.greetings('developer'), 'Hello world, developer')
```

## Conclusion
Make sure that you plan the right time for your task, a unit test can be sometimes 40% of it, adapt to your project's needs and if the culture is broken, include it step-by-step. 

It's not easy to unit test a whole codebase that hasn't been planned to have it before. That's my main point from the title, the unit test culture could be broken for a variate of reasons, but there's always a room for improvements.

Hope you enjoy it, that's my personal option about it and based on my experience.
Don't await in loops
Published: 2020-08-03 22:27:37

In software development, a very common task is to perform an operation on each element of an iterable:

```javascript
for (let i = 0; i < array.length; i++) {
  work(array[i]);
}
```

When introducing asynchronous operations, it's easy to write:

```javascript
for (let i = 0; i < array.length; i++) {
  const result = await work(array[i]);
  doSomething(result);
}
```

However, this is far from optimal as each successive operation will not start until the previous one has completed.

Imagine the `work` function takes 100ms more than its previous execution:

```javascript
const work = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

for (let i = 0; i < 10; i += 1) {
  await work((i + 1) * 100);
}
```

The first call will take 100ms, the second 200ms, and so on. The entire loop will be equal to the sum of the duration of each asynchronous operation, about 5.5 seconds!

Since `work` is asynchronous, we can use `Promise.all` to execute all the operations in parallel. All we need to do is add the promises to an array and call `Promise.all`

```javascript
const p = [];
for (let i = 0; i < 10; i += 1) {
  p.push(work((i + 1) * 100));
}
const results = await Promise.all(p);
```

Now the entire loop will be as slow as its slowest operation, in our case this is ~1 second, 5.5x faster!

**However, Promise.all does have one problem**. It will reject immediately upon any of the input promises rejecting.

```javascript
try {
  const p = [
    new Promise((resolve, reject) => setTimeout(() => reject(new Error('Failure!')), 200)),
  ];
  for (let i = 0; i < 10; i += 1) {
    p.push(work((i + 1) * 100));
  }
  const results = await Promise.all(p);
  console.log(results); // <- never executed !
} catch (error) {
  console.error(error.message); // Error: Failure!
}
```

There is only one little change needed to get all promises to run. We need to add a `catch` to each promise to handle the failures of the failed promises, and let the other promises resolve.

```javascript
const errorHandler = (e) => e;

const p = [
  new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error('Failure!')), 200);
  }).catch(errorHandler),
];
for (let i = 0; i < 10; i += 1) {
  p.push(work((i + 1) * 100).catch(errorHandler));
}
const results = await Promise.all(p);

results.forEach((result, i) => {
  if (result instanceof Error) {
    console.log(`Call ${i} failed`);
    return;
  }
  console.log(`Call ${i} succeeded`);
});
```

Notice how a `new Error` is passed to the reject callback. The handler simply returns the error, but this would also be a good place to log it. If in the handler the error were thrown instead, then we would default back to the previous behavior where the catch block would be entered.

We should always do our best to execute asynchronous operations in parallel, and we've seen that with proper error handling, it is possible to use `Promise.all` to execute a bunch of promises in parallel, even if one fails.

Happy coding!