teleren/devto huggingface dataset:
The Magic of Event Loop
Tags: javascript
Published: 2021-07-09 19:40:01

JavaScript is a single threaded language. This means it has one call stack and one memory heap. It executes code in the order and must finish executing a piece of code before moving onto the next.

JavaScript engine creates the global execution context before it starts to execute any code.
Global execution context holds information about the environment within which the current code is being executed.

## Now let's see how stack works:

When the JavaScript engine first encounters your code, it creates a global execution context and pushes it to the stack. Whenever there is a function invocation, it creates a new execution context for that function and pushes it to the top of the stack.

The function's execution context which is at the top of the stack is executed first. When this function completes, its execution stack is popped off from the stack.

If you have a function that takes a long time to execute, it blocks all the interactions with web page such as mouse click. These functions are called blocking functions.

```
function task(message) {
   let n = 10000000000;
   while (n > 0){
      n--;
   }
console.log(message);
}
console.log('Start');
task('Run the task');
console.log('Done');
```

### Output: 
Start
Run the task
Done

In this example, we have a big while loop inside the task() function that runs a time-consuming task. The task() function is a blocking function.

The JavaScript engine first places the console.log() on top of the stack and executes it. Then, JavaScript places the task() function on top of the call stack and executes the function.

However, It take some time to complete the task() function. Therefore, you will see the message 'Run the task.' a little time later. After the task() function completes, the JavaScript engine pops it off the call stack.

Finally, the JavaScript engine places the console.log('Done') function on top of the stack and executes it.

This can we avoided with the help of Callback functions.

```
console.log('Start');
setTimeout(() => {
   task('Run the task');
}, 1000);

console.log('Done');
```

###Output
Start
Done
Run the task

This asynchronous behavior is not part of the JavaScript language, But they are built on top of the JavaScript language in the browser and accessed through the Web APIs.

some examples of these async functions are setTimeout, setInterval, Event listeners etc.
 
##The Magic of Event loop

![event_loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mcpmnbbjg9qw2hdzmfe.PNG)
 
The functions are pushed into the call stack in order. But the functions belonging to Web API's are sent to the browser to perform the task.
Meanwhile, the functions in callstack are executed without any delay. The functions which are executed by the browser are sent to Callback queue. The Event loop continuously check if the callstack is empty. If the callstack is empty, the functions in callback queue which are waiting to be executed are pushed into the callstack in order.

This is how the JavaScript runs asynchronous code without interrupting other activities.  

Happy Learning!
Create one Docker image of Angular + Nginx with dynamic API url
Tags: angular, docker, nginx, tutorial
Published: 2021-07-09 19:37:52

In this tutorial, I explain one workaround that I did to create one Docker image of one Angular application which has one dynamic API URL.

The article [How To Build An Angular App Once And Deploy It To Multiple Environments - Solution 4: Override environment file values](https://www.mokkapps.de/blog/how-to-build-an-angular-app-once-and-deploy-it-to-multiple-environments#solution-4-override-environment-file-values) explains how you can do this.

But, as I'm far from a Docker expert, I spent some time to create the Dockerfile to do this :)

Just quoting the [article](https://www.mokkapps.de/blog/how-to-build-an-angular-app-once-and-deploy-it-to-multiple-environments#solution-4-override-environment-file-values):

> The idea is to use Angular’s environment.ts (for local development) and environment.prod.ts (for all other stages) with placeholder values which are overwritten per deployment:
```ts
export const environment = {
  apiUrl: 'MY_APP_API_URL',
  stage: 'MY_APP_STAGE',
};
```

> If our pod is started we can then run the following script, for example in a Dockerfile, that overrides these placeholder values:

```bash
#!/bin/sh
# replace placeholder value in JS bundle with environment specific values
sed -i "s#MY_APP_API_URL#$API_URL#g" /usr/share/nginx/html/main.*.js
```

## My contribution

Here is the Dockerfile I created to run this workaround:

```Dockerfile
FROM nginx:latest

COPY dist/your-app-name /usr/share/nginx/html

CMD ["/bin/bash", "-c", \
"echo API_URL=[$API_URL], && \
sed -i s#MY_APP_API_URL#$API_URL#g /usr/share/nginx/html/main.*.js && \
nginx -g 'daemon off;'"]
```

Build your project:
```
$ ng build
```

Place this Dockerfile into your Angular root folder and run this to build your image:
```
$ docker build -t angular/your-app-name .
```

After this, just run your container passing the `API_URL` variable:
```
$ docker run -p 80:80 --name your-app-name -e API_URL=http://localhost:8080 angular/your-app-name
```
Programmatic access to EhCache in Spring Boot
Tags: java, programming, springboot
Published: 2021-07-09 19:37:40

This guide assumes that you have already configured Ehcache, and is specifically concerned with programmatic addition and removal of elements.

## Get a cache
```java
@Autowired
private CacheManager cacheManager;

[...]

public Ehcache getCache(String name) {
    return cacheManager.getCache(name);
}
```

In the above example I have “wired in” the cache manager and called the `getCache()` method on it. This takes a String which is the name of the cache you wish to retrieve.

## Populate a cache
```java
private void updateCache() {
    getCache("example").put(new Element(entity.getName(), entity));
}
```

Once we have retrieved the cache, we can call `put()` on it. This method takes the type `Element` which encapsulates the key and value to be stored in the cache. The key can consist of one or more values that will uniquely identify the element in the specified cache.

## Remove an element from a cache
```java
public void remove(String name, Collection<Object> key) {
    Ehcache cache = getCache(name);

    if (cache.isKeyInCache(key)) {
        cache.remove(key);
    }
}
```

To remove an element from a cache we first need to built the key. This is a collection of type “Object” which will contain one or more values that will uniquely identify the element. First we will check that the key exists in the cache. If it does, we can call the `remove` method on the cache. This method takes the key as an argument.

```java
private void removeFromCache(ApplicationHealth health) {
    remove("health", Arrays.asList(health.getName()));
}
```
Getting started with a project written by another developer
Tags: productivity, codenewbie, python, javascript
Published: 2021-07-09 19:25:24

## Lets get into this
I have been there and if you are not a newbie, you have probably been there but if you haven't been there, don't worry you will be there. There will always be a time in your life when you inherit code that was written by another developer. If the developer is smarter than you, that's a problem and if they are not, well that's a huge problem. This is a problem most developers face when they start a new job at a different company.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9k41x9qf46u8o10rs3o.jpg)

## How did we get here?
Recently I was given a task to maintain a project that was written by another developer using a programming language that I am not familiar with. This article has some few things that helped me get up to speed with this new project as well as explaining these ways in case you encounter the same problem.

## You have been given a project written by another Developer. What should you do?  
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tr2s5kqldtl4x1mryb84.jpg
)
**_We don't run away from the code, we run the code_**

#### Study the programming language used
The first thing you have to do before trying to add functionality to a project written by someone else is to understand the programming language that was used to write the project. Most people say programming languages are the same, learn one and you are good with all of them. I disagree, programming languages are different in terms of syntax but they use the same concepts like , OOP, if statements exception handling etc. Take your time to understand the syntax of the language before you try changing some lines of code in a project and this will save you a lot of time. This applies to all programming languages, Python, JavaScript, PHP, C# etc.

#### Study the source code
Once you get an understanding of the programming language, take your time to read through the project code. Go through the code as much as you can if possible from line 1 to line n, file 1 to file n. Going through the code thoroughly will help you understand the way the developer structures their code, their commenting style, strength and weaknesses. This will also help you know where to edit when you want to edit any features of the project. 

#### Experiment with the project
Experiment with the project, make a backup then break it and fix it. If you break the project you will suffer, the suffering is necessary because it will help you understand the concepts and technologies used in the project when you are trying to fix the project. This will also help you to understand several modules of the project and their connection.

**NB:** There are several ways that can help one to get started with a project that was written by another developer but this is what worked for me.
Minhas impressões sobre o livro: "14 Hábitos de desenvolvedores altamente produtivos"
Tags: productivity, books, programming, habits
Published: 2021-07-09 19:18:33

Hoje terminei a leitura do livro “14 Hábitos de desenvolvedores altamente produtivos” do programador brasileiro Zeno Rocha traduzido por Caroline Moreschi que está disponível em formato ebook e impresso na Amazon.

Confesso que fiquei um pouco assustado com o título do livro, é claro que todo desenvolvedor almeja ser altamente produtivo, porém esse já tem se tornado um jargão quando o assunto é livro sobre sucesso profissional. Mas como não se julga um livro pelo título, resolvi dar uma chance e para minha surpresa fiquei muito impressionado com seu conteúdo.

Podemos dizer que o livro se trata de um compilado de opiniões sobre grandes desenvolvedores ao redor do mundo, contando com pessoas da Google, Yahoo, Amazon, Github, além de trazer a vivência do autor e as dicas com os hábitos direcionados aos programadores.

A verdade é que apesar de cada capítulo tratar de um hábito, ele não se refere somente a isso, como se fosse uma receita de bolo, ele vai muito além trazendo vivências do autor mesclados com uma boa dose de inspiração e mensagens de incentivo e bom senso. Mas sem dúvida o ponto alto do livro são as entrevistas que Zeno fez com os mais diversos programadores de sucesso ao redor do mundo, ele faz uma pergunta a eles com base no capítulo do livro, e traz a opinião de cada um desses programadores a respeito do assunto, por fim faz uma breve avaliação e dá dicas de qual seria a melhor maneira de encarar cada tema debatido.

O livro também traz sessões de to-do, para o leitor exercitar aquilo que acabou de aprender, além de links úteis sobre o assunto, o que faz com que a leitura não se torne monótona e se restrinja somente ao conteúdo passado nos parágrafos do livro.
Posso dizer que é uma leitura dinâmica, sem enrolação e que compartilha da opinião de várias pessoas especialistas no desenvolvimento de software, isso faz com que você veja que, mesmo pessoas que hoje ocupam as mais importantes funções nas maiores empresas do ramo de software algum dia já passaram ou ainda passam pelos mesmos problemas e dificuldades que você e como eles lidam com isso e isso para mim amplia muito os nossos horizontes, pois percebemos que todos os obstáculos que permeiam nossa área podem ser vencidos se adotarmos alguns hábitos que alguns programadores altamente produtivos adotaram. 

Bem essa é a minha impressão sobre o livro, eu recomendo muito para qualquer tipo de programador e também para outras profissões pois muitas dicas são genéricas e não se restringem somente a área de desenvolvimento de sistemas.
 
Photo by <a href="https://unsplash.com/@giisilveira?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Giovanna Gomes</a> on <a href="https://unsplash.com/s/photos/blue-arara?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
What is the Consumer in a lambda function?
Tags: java, codenewbie, beginners, braziliandevs
Published: 2021-07-09 19:03:11

Well, this can seem well consolidated in the community but I think it important to create something about this and help me learn more.

Initially, we will create the example code.

```Java
Car car1 = new Car("Porsche 911");
Car car2 = new Car("Ferrari 458");
Car car3 = new Car("Lamborghini Urus");

List<Car> cars = Arrays.asList(car1, car2, car3);

cars.forEach( (c) -> System.out.println(c.getName));
```

To explain the Consumer interface I will use the method forEach().

Since Java 8, we have a function lambda that receives an Interface function that stays responsible to organise this iteration that will occur. To execute a function lambda we have to have an Interface function to accomplish the action.

In the case we have the Interface function Consumer is part of the package Function of java and allows use with a function.

To stay more clear we will create a class anonymous that implements a class Consumer.

```Java

Consumer<Car> show = new Consumer<Car>() {
    public void accept(Car c) {
        System.out.println(c.getName);
    }
}

cars.forEach(show);
```

The Consumer class has a unique method called Accept that stays responsible to receive the function that receives a value that will be consumed with some action, but not returns anything. This way of presenting the function is not conventional, but he introduces what occurs when using a function lambda, for example, to understand what occurs when creating a function. Now we will refactor this code.


```Java

cars.forEach( (c) -> System.out.println(c.getName));

```


We can see in that refactoring as in the first example, not we initialize the object C this occurs because the compiler understands that we assigning a Consumer<Car> thus abstracting this information, between having -> that is an identifier of a function lambda, another point is that not have the method Accept he is inferred during the process of compilation, then the method forEach receive a Consumer and send an action to be executed with each iteration. So we briefly understand how the functional interface works by streams in Java.
The "safe" star rating & the ONE star unlimited rating
Tags: html, css, webdev, beginners
Published: 2021-07-09 19:00:47

After [my scalable star rating](https://dev.to/afif/scalable-star-rating-without-js-and-no-svg-or-image-for-the-star-2mef) and [my ONE star rating](https://dev.to/afif/the-one-star-rating-system-the-future-of-rating-4jl8), Here I am with more rating systems.

This time I will perform a 2x combo providing not one, but two star rating systems:

#### [1. The "safe" star rating](#the-safe-star-rating)
#### [2. The ONE star unlimited rating](#the-one-star-unlimited-rating)

----

## The "safe" star rating

Everyone is talking about accessibility but no one is talking about safety which is a very important subject. Nowadays, everyone is using touch screens to navigate and as you know stars have spikes and they are dangerous for your fingers!

Each year, 20% of the kids between 8 years and 14 years get hurt by star spikes while navigating their phones. A recent study has claimed that 89% of the star rating on the web aren't safe!

Luckily, I am here for the rescue providing a "safe" star rating. No more dangerous spikes but smooth and rounded edges instead.

{% codepen https://codepen.io/t_afif/pen/abWZQQY %}

Similar to my first rating system, it's scalable and is made with pure CSS (no JS and no SVG).

Keep people safe by adopting this rating system.

---

## The ONE star unlimited rating

The first version of the ONE star rating was good but it has a few drawbacks:

* Only limited to a 0-5 rating
* Not very intuitive

I have improved it and this version is now called the: **ONE star unlimited rating**.

Unlimited because it can work with any rating. Only one star holds all the ratings.

Let's start with the classical 0-5 rating:

{% codepen https://codepen.io/t_afif/pen/zYwBXpM %}

A simple click on the star will increase the rating. More intuitive and also informative since I am showing the rating.

You can search in the code but you will find no JS logic in there. All is done with CSS.

Want more ratings? We simply add more inputs and we adjust the scaling step:


{% codepen https://codepen.io/t_afif/pen/RwVRzLq %}

By simply adjusting 2 variables we can control both the size and the rating range while still having a unique star.

The first version can also be updated to include the rating:

{% codepen https://codepen.io/t_afif/pen/poPEjmR %}


### What about `<label>`?

Someone said my code is missing labels. Guess what, you can easily add them without affecting the code.

{% codepen https://codepen.io/t_afif/pen/JjNRjJO %}

I simply updated 2 rules where I am using the `+` selector (replacing `+` with `+ * +` to consider the label), nothing more. The same can be done with all my star ratings and you don't have to touch the code of the others because I am not using the `+` selector. test it and see.

----

Now you have 4 different star rating systems. Notice that all of them use the same HTML code and I am changing only the CSS. You can easily switch to any star rating without too much complexity.

Is this my last star rating?

![we will see](https://media.giphy.com/media/zndou9tOk63LIthccc/giphy.gif)
Express Middlewares
Tags: javascript, express, node, webdev
Published: 2021-07-09 18:44:08

Middlewares play a very important part in the request-response  lifecycle. The middlewares are placed between the Server and the response.

The main role of middleware is to process the request in the middle before it is received by the Route Handler. The processing could be related to a variety of things such as :

* Logging all requests coming to the server (Morgan is a very popular middleware used for this purpose)

* To verify if the request has ` auth token ` or not (Passcode JS is a popular middleware for this purpose)

These are basically functions that can access request object, response object as well as the next middleware function in the application's request-response lifecycle (Next middleware function is commonly denoted by a variable named next).

If the current middleware does not end the request-response cycle, it must call next() to pass control to the next middleware function, or the request will be left hanging.

Middlewares can be of various types, depending upon the different needs that are required by the programmer in the request.

Following are some of the types of Middlewares that are available based on your requirements:

* Application Level Middleware
* Router Level Middleware
* Error Handling Middleware
* Built-in Middleware
* Third Party Middleware

Let us take an example of an application level middleware : 

```
var express = require('express')
var app = express()

app.use(function (req, res, next){

 console.log('Time', Date.now())
 next()

})

```

The above middleware is executed every time the app receives a request.


## Mounting the middleare to a path:

```

app.use("/products/:id", function(req,res,next){
 console.log('Request Type: ', req.method)
 next()

})

```

The above middleware is executed every time a request is received at the "products/:id" path.

## Mounting to a path for a specific request:

```
app.get("/products/:id", function(req,res,next){
 res.send('product')
 next()

})

```

The above middleware is executed every time we receive a GET request at the "products/:id" path.

## Let us go in more depth about ` next() ` :

next() is used to propogate the request ahead. Calling next() is very important, if not called then it's basically a route handler and not a middleware.

One very important thing about middlewares is the order of the program or where the middleware has been used matters for the routes to effectively use it.

for eg:

```

app.use("/categories",categories)

app.use(middleware)

```

Here the requests at "/categories" route will not be processed by the middleware hence for it to work properly we should define and use it at the top of all routes where we want the middleware to process the requests.

So we can say that middlewares provide a lot of help in implementing DRY and may be used at greater advantages to take some load off the server.
9 Developer Tutorials You Should Read from June 2021
Tags: ibmcloud, tutorial, video, beginners
Published: 2021-07-13 18:46:31

---
title: 9 Developer Tutorials You Should Read from June 2021
published: true
date: 2021-07-09 18:36:39 UTC
tags: IBMCloud, tutorial, video, beginner
canonical_url: https://maxkatz.org/2021/07/09/9-developer-tutorials-you-should-read-from-june-2021/
---

I want to share developer articles, tutorial and videos from [IBM Developer](http://developer.ibm.com) North America team. These resources offer high-quality developer education so I believe you will find them valuable.

[![IBM Cloud Functions](https://katzmax.files.wordpress.com/2021/07/articles_june2021.png?w=1024)](https://katzmax.files.wordpress.com/2021/07/articles_june2021.png)<figcaption>IBM Cloud Functions benefits</figcaption>

📖[IBM Cloud Deployment 4 Ways](https://dev.to/ibmdeveloper/ibm-cloud-deployment-4-ways-3770) by [Jenna Ritten](https://twitter.com/jritten)

📖[Code Engine Auto-Scales, Even to Zero](https://dev.to/ibmdeveloper/code-engine-auto-scales-even-to-zero-2peh) by [Jenna Ritten](https://twitter.com/jritten)

📖[IBM Cloud Code Engine Dev Setup in 6 Easy Steps!](https://dev.to/ibmdeveloper/ibm-cloud-code-engine-dev-setup-in-6-easy-steps-j8f) by [Jenna Ritten](https://twitter.com/jritten)

📖[Deploy a Health Insurance App w the Code Engine CLI in 3 Easy Steps!](https://dev.to/ibmdeveloper/deploy-a-health-insurance-app-w-the-code-engine-cli-in-3-easy-steps-chl) by [Jenna Ritten](https://twitter.com/jritten)

📺[Why You Aren’t Getting That Development Promotion?](https://dev.to/bradstondev/why-you-aren-t-getting-that-development-promotion-ji9) by [Bradston Henry](https://twitter.com/BradstonDev)

📖[The Simple Basics of Cloudant NoSQL DB](https://dev.to/ibmdeveloper/the-simple-basics-of-cloudant-nosql-db-57a1) by [Bradston Henry](https://twitter.com/BradstonDev)

📖[Creating your First Cloudant NoSQL Database in Just 5 Minutes](https://dev.to/godspowercuche/creating-your-first-cloudant-nosql-database-in-just-5-minutes-4d3f-temp-slug-5882945) by [Bradston Henry](https://twitter.com/BradstonDev)

📺[What is Best Programming Language for Beginners? | Dev Community Speaks](https://dev.to/bradstondev/what-is-best-programming-language-for-beginners-the-dev-community-speaks-3ach) by [Henry Brads-to](https://twitter.com/BradstonDev)n

📖[Deploying Scalable Java Microservices to Enterprise Kubernetes using Red Hat OpenShift](https://dev.to/drnugent/deploying-scalable-java-microservices-to-enterprise-kubernetes-using-red-hat-openshift-546b) by [Dave Nugent](https://twitter.com/drnugent)

One more thing. If you are looking to join our live online meetups, you will find weekly developer education events on our [Crowdcast channel](http://crowdcast.io/ibmdeveloper).