teleren/devto huggingface dataset:
Run a function periodically in vanilla Javascript
Tags: javascript, webdev, node, beginners
Published: 2019-11-18 19:33:47

---
title: Run a function periodically in vanilla Javascript
published: true
description: How to run a function after fixed intervals in vanilla Javascript
tags: javascript, webdev, nodejs, beginners
canonical_url: https://ranvir.xyz/blog/running-a-function-after-quick-intervals-in-vanilla-javascript/
---

This post was originally posted on [my blog.](https://ranvir.xyz/blog/running-a-function-after-quick-intervals-in-vanilla-javascript/)

In a production system, we run a lot of scripts periodically either to sync data from some third-party source or spit data to some source. Although there are a lot of solutions to achieve such periodic behavior, in this post we are going to discuss one such solution using vanilla JavaScript.

## Use cases

* Taking backups of the database.

Taking a backup of the database can be done once or twice a day depending upon the use case. 

If you get a lot of users you can take this backup multiple times a day.

**AWS** takes automatic backups so you don't have to worry about it.

* Sending newsletters to your customers.

Sending newsletters to customers can also be one of the use cases of running things periodically.

## Possible Solutions

### Crontab

Most of the organizations tend to use crontab for handling any such requests for running periodic tasks.

Each and every language has it's own implementation of handling periodic tasks.

## Periodic task in Vanilla JavaScript

Let's write a simple function that can log the current time after every minute.

```javascript
const tellTime = async function () {
    console.log(new Date());
}

const minutes = 1;
const interval = minutes * 60 * 1000;

setInterval(function() {
    // catch all the errors.
    tellTime().catch(console.log);
}, interval);
```

First of all, we declare an `async` function `tellTime` which logs the time whenever it is called.

It is important to declare this function `async` so that we can run `.then` or `.catch` after this function.

`setInterval` is the inbuilt function that can run any statements after every given interval.

It takes two arguments, first is the definition of the function being run itself and next is the interval after which we want to run the function again( **In milliseconds**).

In this example, we have set the interval to one minute.

Here is how the output is going to look like

```javascript
2019-11-18T18:40:27.286Z
2019-11-18T18:40:57.293Z
...
```

Although this is a pretty straight forward example you can extend this to do anything that you want.
Build/Deploy from the Beginning
Tags: automation, deployment, build, release
Published: 2019-11-19 14:08:25

---
layout: post
title: Build/Deploy from the Beginning
category: [ automation, deployment, build ]
tags: [ automation, deployment, build, release ]
published: true
---

When I start a project, I like to follow a few steps to speed things along later. The first is to get the basic project compiling successfully and the next step is to set up the automated build and deployment infrastructure (bonus points if the build/release can be put into version control with the codebase). Some of the benefits of setting up the build/deploy infrastructure early on include automated feedback, easier deployment, and informed design choices.

## Automated Feedback

Setting up an automated build/deploy provides an early feedback mechanism for those working on the codebase. This feedback provides extraordinarily valuable feedback to those working on the codebase. This feedback includes if the merged code builds and if all of the new and existing tests are passing. While this all _should_ be confirmed locally, people make mistakes and sometimes things slip. 

## Easier Deployment

Building on the _Automated Feedback_, changes can be made to the codebase freely without impacting the ability to deliver the software. A symptom of spending excessive amounts of time developing code is a rough and lengthy process figuring out how to deploy that code. By allowing the build/deploy process to grow with the codebase, the necessary changes to build and deploy the product will be included as the codebase grows. This allows the person with the greatest understanding of the change to make the incremental changes to the build/release process.

## Informed Design Choices

As the product's codebase grows, more and more design choices are made and each of those choices involves trade offs, incurring [opportunity cost](https://en.wikipedia.org/wiki/Opportunity_cost). The earlier these choices are made, the greater the impact is to the whole system. Having build and deployment infrastructure from the beginning forces decisions involving deployment to be considered as the changes are being made. This way changes that incur an unacceptable amount of deployment pain can be either avoided, or reverted with much less pain since there aren't any dependent changes yet.

## Conclusion

In the end, the goal is to be able to produce and deliver excellent, quality software with as little pain as possible. Setting up build/deploy infrastructure early on can alleviate the pain of developing a product and then figuring out how to release it.
Good morning, Ethereum [1: Smart Contracts ]
Tags: database, blockchain, sql, javascript
Published: 2019-11-19 07:37:01

This is a daily morning publication on the ins and outs of Ethereum smart contracts, an important component of Ethereum and other blockchains.

This article will not include analysis of other smart contract languages apart from solidity but it will list other popular programming languages that smart contracts can be written in.

Smart contracts are the next big thing. As more people realize this, an increasing number of smart contracts have been developed in different languages. 



The most popular languages to write smart contracts in includes:

- Solidity
- Golang
- JavaScript
- C++
- Java
- SQL

I think it would be great to delve deeper into the ins and outs of the abovementioned languages and their suitability for cryptocurrencies. 

I was slightly worried about the use of some of the languages. I began to worry about the risks tied to using a language such as SQL for the development of blockchain technology. The first thing that came to mind was SQL injection attacks. I would like to, over the next few articles, provide analysis of the risks and benefits of using the programming languages to create smart contracts. I will analyze the programming languages using an ascending order of the list of programming languages.

I welcome your views and thoughts in the comment section below as I carry out research to inform the analysis in the next article.
Remove multiple div's in reactJS
Tags: react
Published: 2019-11-19 19:14:04

Hi,

I am trying to remove the multiple div's generated via the add button. 
I'm having trouble in understanding how can I send the parent div's id into delete method passed from the child div. Also, if I can store the div's id into a state to perform deletion process. My code is as follows. I appreciate your inputs and suggestions.

constructor(props) {
    super(props);
    this.state = {
      names: [],
      inputValue: '',
      id: [],
      count: 1,
      hostname: '',
      devname: '',
      sellID: '',
    }
    this.addRow = this.addRow.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.deleteRow = this.deleteRow.bind(this)
  }

addRow() {
    this.setState({ count: this.state.count + 1 })
    console.log(`Increase count: ${this.state.count}`)
  };

  renderDivs() {
    let count = this.state.count, uiItems = [];
    var { names } = this.state;
    let options2 = names.map(name2 => {
      return { value: name2.name, label: name2.name };
    })
    while (count--)
      uiItems.push(
        <div className="newHost" id="dynamic">
          <div className="hostInput">
            <input type="text" placeholder="Enter Name"
              onChange={this.handleChangeHN.bind(this)}
            />
          </div>
          <div className="hostInput">
            <Select
              placeholder="Pick Dev Name..."
              styles={colourStyles}
              options={options2}
              onChange={this.handleChangeDN}
            />
          </div>
          <div className="hostInput">
            <button className="btn btn-danger" type="button" onClick={this.deleteRow}>Remove</button>
          </div>
        </div>
      )
    return uiItems;
  }

  deleteRow(currentID) {
    // const changedID = this.state.id.filter(i => i.id !== currentID)
    // this.setState({changedID});
    // console.log(`Clicked: ${currentID}`);
    // this.setState({ count: this.state.count - 1 })
    console.log("delete");
  };
Quick Progress Bars in python using TQDM
Tags: python, cli
Published: 2019-11-19 19:58:08

tqdm is one of my favorite general purpose utility libraries in python.  It allows me to see progress of multipart processes as they happen.  I really like this for when I am developing something that takes some amount of time and I am unsure of performance.  It allows me to be patient when the process is going well and will finish in sufficient time, and allows me to 💥 kill it and find a way to make it perform better if it will not finish in sufficient time.

> Quick aside, this is a crosspost from my personal blog https://waylonwalker.com/blog/quick-progress-bars-in-python-using-tqdm/

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/uni8skpd329yq29qsb6w.gif)
> for more gifs like these follow me on twitter [@waylonwalker](https://twitter.com/_WaylonWalker)

**Add a simple Progress bar!**
```python
from tqdm import tqdm
from time import sleep

for i in tqdm(range(10)):
	sleep(1)
```

**convenience**

TQDM also has a convenience function called trange that wraps the range function with a tqdm progress bar automatically.

```python
from tqdm import trange
from time import sleep

for i in trange(range(10)):
	sleep(1)
```


**notebook support**

There is also notebook support.  If you are bouncing between ipython and jupyter I recomend importing from the auto module.

```python
from tqdm.auto import tqdm
from time import sleep

for i in tqdm(range(10)):
	sleep(1)
```
Finding a programming language to call home
Tags: clojure, learning, productivity, watercooler
Published: 2019-11-20 14:44:09

I've been programming for many years.  Started out on my Amstrad CPC464 with BASIC.  Back then programming was a hobby, and I absolutely loved it.

Over the years I've used many different languages.  But I've always felt like none of them quite did it for me.  I never found one I could call home.

Now, this isn't going to be a post about bashing languages.  There are reasons why people use certain languages.  These reasons could be purely economical (language X has a great prospect for career progression), they could be purely technical (language Y is great for doing concurrency for example).

I'm the sort of person that will read a programming language book for relaxation.  I might not even use the language.  I might just read about a language, out of curiosity.  One of the main reasons is so that I am able to have a view on what languages are out there, and what they're suitable for.

But deep down, there is another reason I look at different languages.  I want to find one that I can call home.

Now, for years, I've been programming in a variety of Object Oriented Languages.  I've never really felt OOP, as a paradigm, really did it for me.  I remember when I first learnt it, and my University Tutor was insisting that this is how the world *IS*.  It just didn't fit in how I thought about the world.  But I accepted it, and just went with it.  First in C++ then in Java.

Over the last few years I've gotten the Functional bug.  So I've toyed around with Haskell, Elixir, Elm, oCaml... and then someone said to me that I should try Lisp.  Now Lisp is a language that's been on my radar for many many years.  But I just didn't get it.  I really didn't.  But something has clicked.  Something over the last few weeks.  It's like a light has turned on.  I feel born again!.  I've started to learn Clojure - and it feels really good.  It feels pretty wonderful!

I think I might have found a programming language I can call home....

Watch this space.
Links in a React application
Tags: react, javascript, reactrouter
Published: 2019-11-20 14:29:55

---
title: Links in a React application
published: true
description: How to smoothly navigate between components
tags: reactjs, javascript, react-router
cover_image: https://ferrariwebdevelopment.s3.us-east-2.amazonaws.com/assets/20191006-links.jpeg
---

## How to smoothly navigate between components

We have seen how to use the `BrowserRouter` and `Route` components to display different React components in different views.
We have seen how we can access different views by entering URLs in the browser address bar.

But users typically expect to be able to click on links to go to different web pages, so I am going to show how to implement this functionality in our web application.
It's very simple.

The `react-router-dom` library that handles routes also makes available a component called `Link` that we can use to create hyperlinks in our documents.
We must first import `Link` from the library.

```js
import { Link } from 'react-router-dom';
```

Let's suppose we want to create a link to the path `/pokemons` that displays the `Pokemons` component.
First we need to make sure we have a route for the `/pokemons` path. The route would look like this:

```js
<Route path="/pokemons" component={Pokemons} />
```

Then we add the link to this path with the `Link` component. We can do it in this way:

```js
<Link to="/pokemons" >Pokemons</Link>
```

The `Link` component has a to prop that is set to the path we want to load in our application. We would use the same value as the Route component path prop.
Link will create an HTML `<a>` tag on our page and set the href property of the `<a>` tag to the location we specify.

### The `exact` prop

One thing to note is that the `Link` and `Route` components use regular expressions to match paths. This may lead to confusion if we have more than one path in our application with the same string in it.

For example, we may have these two links in our application (and relative routes):

```js
<Link to="/pokemons" >Pokemons</Link>
<Link to="/pokemons/pikachu" >Pikachu</Link>
```

When we click on the second link, we might expect to see the Pikachu page, but we will see the Pokemons page instead. Why?

Because the regular expression engine will try to match the string `/pokemons` and this string is present in *both* routes, so the first one will be matched first and the wrong component will be loaded.

We have a way to specify an *exact* match, though, so the correct route will be taken.

We simply include the `exact` prop in our links. This will make the regular expression match only if the exact path is matched, so it will eliminate any ambiguity.
Here's how we use the `exact` prop:

```js
<Link exact to="/pokemons" >Pokemons</Link>
```

If we specify the link this way, only the route with the exact path of `/pokemon` will be matched and we will be able to reach both the Pokemons and the Pikachu pages correctly.
Ionic 4/Angular Modals Tutorial – Passing & Receiving Data
Tags: ionic, angular, angularpassingreceivingdata
Published: 2020-02-07 10:03:10

---
title: Ionic 4/Angular Modals Tutorial – Passing & Receiving Data
published: true
date: 2019-11-19 20:41:19 UTC
tags: Ionic,Angular, Angular Passing & Receiving Data
canonical_url: https://www.positronx.io/ionic-angular-modals-tutorial-passing-receiving-data/
---

The post [Ionic 4/Angular Modals Tutorial – Passing & Receiving Data](https://www.positronx.io/ionic-angular-modals-tutorial-passing-receiving-data/) appeared first on [positronX.io](https://www.positronx.io).

**In this Ionic 4 tutorial, we are going to learn how to use modal popover in an Ionic 4 Angular application. We will also learn how to pass data and receive the data response in Ionic 4 modals.**

[click here to read more](https://www.positronx.io/ionic-angular-modals-tutorial-passing-receiving-data/)
Remove duplicates from an Array the short & sweet way!
Tags: javascript, tutorial
Published: 2019-11-22 03:28:26

## **tldr;**

```js
const numbers = [1,2,2,3,3,3,4,4,4,4]
console.log([...new Set(numbers)]) //output:  [1,2,3,4]
// OR
console.log(Array.from(new Set(numbers))) //output: [1,2,3,4]
```

## **The long version**
lets start by looking at what a `Set` is...

According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#Description)

> Set objects are collections of values. You can iterate through the elements of a set in insertion order. `A value in the Set may only occur once;` it is unique in the Set's collection.

What we can understand from the above is that Sets are like Arrays, in the sense that they are a collection of values that you can iterate through but the prime difference lies in the fact that is highlighted above i.e

> `A value in the Set may only occur once;`

The above property of a Set is what we will be leveraging to expell duplicates from our array.

#### Let's now cut to the chase and see some code,
![Talk is cheap, show me the code](https://quotefancy.com/media/wallpaper/3840x2160/1700728-Linus-Torvalds-Quote-Talk-is-cheap-Show-me-the-code.jpg)
 
so, consider an array riddled with duplicates

```js
const numbers = [1,2,2,3,3,3,4,4,4,4]
```

We're going to divide the process into two steps

### 1. Converting Array to Set
```js
console.log(new Set(numbers)) //output: {1,2,3,4}
``` 
As you may have noticed, The duplicates have been eliminated! also another thing to notice is that eventhough Sets and Arrays have their similarities, the notation they use are different.

### 2. Converting Set to Array
There are two ways of going about this
#### a) Using `spread operator`
```js
console.log([...new Set(numbers)]) //output: [1,2,3,4]
``` 
#### b) Using `Array.from()`
```js
console.log(Array.from(new Set(numbers))) //output: [1,2,3,4]
``` 

### Liked the post? Show some ❤️

## Resources
1. [MDN Web Docs — Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
Top 8 Technology Trends for 2020
Tags: python, javascript, java, tutorial
Published: 2019-11-21 10:12:00

1. Python

A programming language used in software development, infrastructure management and data analysis.

2. React (web)

A JavaScript library for building user interfaces.

3. Angular

A JavaScript-based open-source front-end web framework.

4. Machine learning

The scientific study of algorithms and statistical models.

5. Docker

An open-source platform used to create software packages called containers.

6. Django

A Python-based free and open-source web framework

7. CompTIA

A professional tech organization that has four IT certification series ranging from entry-level to expert.

8. Amazon AWS

A certification that validates cloud expertise.

9. Deep learning

A class of machine learning based on artificial neural networks.

10. React Native (mobile)

An open-source mobile application framework created by Facebook to develop apps for Android, iOS, Web and Universal Windows Platform.
Single Responsibility Principle
Tags: solid, java, singleresponsibilityprinciple
Published: 2019-11-21 11:42:07

---
title: Single Responsibility Principle
published: true
description: 
tags: SOLID, Java, single responsibility principle
---

The first concept in SOLID principles is the single responsibility principle. According to Robert Martin's Agile Software Development: Principles, Patterns and Practices, it is defined as: 

> A class should have only one reason to change 

The definition is simple enough, but let's look at an example to really solidify its meaning. 

{% gist https://gist.github.com/Naomi-Dennis/181a86612ee6acd1c856251f78947236 %}

Despite the class looking relatively simple, there is actually a lot going on. `Game` controls how the board is rendered, how the player's turn is carried out, if a winner is found and the main game loop. If the way the board is rendered changes, `#renderBoard()` will have to change. If the rules of the game changes how a player should conduct their turn, `#playerTurn()` and possibly `#detectWinner()` will have to change. If we decided to create a more complicated game, where an Ai or some other high level action has to happen, `#start()` would have to change. 

The easiest way to separate responsibility is to separate the functions into classes depending how on they change in respect to one another. `#renderBoard()` can be separated into its own class, because changing how the board is rendered doesn't necessitate changing the game's loop or the game's rules. It only cares about the medium the board is rendered on; for example, a phone app or command line. `#playerTurn()` and `#detectWinner()` can be separated from `Game`, but kept together. The rules of the game dictates how the player conducts their turn and how a player wins. If the rules of the game changes, both `#detectWinner()` and `#playerTurn()` changes. 

{% gist https://gist.github.com/Naomi-Dennis/f594a623bb59923e7e725778d065f1fd %}

With these changes, the only behavior left in `Game` is the main game loop.

### In Conclusion 

When determining how to separate responsibility, look for what Robert Martin calls, "an axis of change". For example, if `#detectWinner()` and `#startPlayerTurn()` behavior weren't related, we could segregate `#detectWinner()` into its own class. However, for our example, this is unnecessary. Be sure not to introduce needless complexity.
React vs React Native
Tags: react, reactnative
Published: 2020-03-16 01:15:24

Recently I’ve been doing most of my programming with React. I love the streamlined set up and ease of creating complex and rich webpages. Having always wanted to create a mobile app of my own, I decided to try to utilize my React knowledge to build an iOS app with React Native. Both frameworks build on JavaScript. Going in, I expected the overlap to make things pretty straightforward. I would soon learn that several key differences made for a good challenge.

First is navigation. Unlike React, React Native does not allow for simple browser client-side routing. Instead, React Native utilizes different types of navigation - stack navigation, drawer navigation, tab navigation... Ultimately I used a combination of these navigation options to achieve the user experience I wanted. The most challenging aspect of this was getting the iOS native buttons and headers to appear as desired. With many possible modifications to each navigation type, setting this up is unique to each app implementation.

The next challenge was HTML and CSS - the absence of both to be precise. While React builds on JavaScript, HTML & CSS to allow for reusable components, React Native combines JavaScript with native mobile building blocks. React Native has many built-in tools, but there are also many available libraries as well as Apple/Android native tools. 

Lastly, testing in React is awesome. Load your local server, and see changes to your DOM as you modify your code. React Native also offers instantaneous updates, though the interface is not quite as nice or efficient as a browser. I used a combination of a platform called Expo and Xcode's simulator to run and test my app on my computer and, while it was cool to see my app running on a simulated device, it was not as fast as testing in Chrome.

Ultimately, my experience coding with React Native was a lot of fun. Mobile apps have transformed the way society functions and getting to peek under the hood was both challenging and exciting. I plan to refine my React Native skills and look forward to learning more!