teleren/devto huggingface dataset:
foldLeft, map and filter in Scala
Tags: scala, foldleft, map, filter
Published: 2021-08-14 19:49:25


What exactly are `foldLeft`, `map`, and `filter` in Scala? They are higher order functions, they operate on lists by taking in functions and applying these functions to a list(s).  These are a way of NOT writing loops, we don't need to think about the implementation of the loop. But, with these higher order functions, we are still thinking about what we want to do with each element in a list, and even though this method is not any faster, it's about 'expressivity' and can simplify what we want to say with our code.

Let's start with `foldLeft`, it is a useful method that takes a list, a function and a starting point and uses the function to operate on the list element by element.   

For example, how can we get the sum of a list using foldLeft? Note that 'a' here is what we are folding into, whereas the 'b' is the next element from the list.

//Get sum of a list using fold
`List(1,2,3).foldLeft(0)((a,b) => a+b)`

In another example, here I show how can we add 1 to a list using `foldLeft`:

//Add a 1 to the list using fold
`List(1,2,3).foldLeft(List[Int]())((a,b) => a++List(b+1))`

Here I show how can we return a list containing only even numbers using `foldLeft`:

//Return a list w/ only even numbers using fold
`List(1,2,3).foldLeft(List[Int]())((a,b) => if (b%2 ==0) a ++ List(b) else a)`

Looking at `map`, on the other hand, we see that it takes a list and a function, and returns another list made up from the result of the function applied to each element. `map` does not take a starting element. Here, 'a' is an element of the list, and 'a+1' is our operation.

//adding one to each element of a list using `map`
`List(1,2,3).map((a) => a+1)`

Now we look at `filter`. `filter` takes a list and a function, and the function takes an element from the list and returns a boolean. Here we have our list, we are using filter, using element 'a' and applying the modulo 2 in order to keep the even elements of the list.

//return a list of only even elements using filter
`List(1,2,3).filter((a) => (a%2 == 0))`

As can be seen, `foldLeft`, `map`, and `filter` are more about making our code more readable. We also see the concept 'expressivity', allowing us to more easily convey an idea to the reader of the code what we are trying to accomplish without necessitating a 'for' loop. Although so much of what I've learned has been about speed, this is a concept where the runtime speed is not decreased (or increased for that matter), but it does make the code more legible to the next person having to read it.
Generate random bytes of size n in Python 3.9
Tags: python, programming
Published: 2021-08-14 19:26:33

Generating random bytes was somewhat complicated in Python before the new version 3.9 finally introduced the `randbytes()` function.

Prior, we could rely on functions such as `os.getrandom()`, `os.urandom()` or `secrets.token_bytes()` but couldn't generate pseudo-random patterns.

Python version 3.9 introduced the new function, **randbytes(n)** which returns bytes of size "n". Let's take a look at how the function works!

In order to use the function, we have to import it from the **random module**. 

Let's try generating pseudo-random bytes of size 2:

```python
from random import randbytes

random_bytes = randombytes(2)

random_bytes

>>> b'\xf29' # Output
```
![Alt text of image](https://media.giphy.com/media/gITE7HxePLZOvDbWNQ/giphy.gif)

For the inexperienced, it may look like that the returned object is of type/class str, but it isn't. 

```python
type(random_bytes)

>>> <class 'bytes'>
```

The randbytes() shouldn't be used as a substitute for generating secret tokens as Python's official documentation advises against it
Javascript runtime interview question
Tags: javascript, runtime, codever, snippets
Published: 2021-08-14 18:56:59

I would definitely put the following question in an interview, if am interested in knowing if the candidate knows a bit about the **Javascript runtime**. 

What is the order in which the following texts are logged via `console.log`?

```javascript
console.log('1 - start');
setTimeout(() => console.log('2 - setTimeout1'), 0);
Promise.resolve('Success')
    .then(()=> console.log('3 - promise1'))
    .then(()=> console.log('4 - promise2'));
setTimeout(() => console.log('5 - setTimeout2'), 0);
console.log('6 - end');
```

> If you are not sure about the answer read this [In depth: Microtasks and the JavaScript runtime environment](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth) article before

<hr>


### Output

```javascript
1 - start// statement is executed directly in the script (first "Run script" task)
5 - end // part of the first "Run script" task gets executed too
3 - promise1 // placed in microTasks queue and executed between tasks, after first "Run script" task is ready
4 - promise2 // microtask added  during previous microtask execution  and executed immediately
2 - setTimeout1 // callback execution scheduled in another task in the "macroTasks" queue (also task queue), executed in the next interation of the event-loop
5 - setTimeout2 // callback execution scheduled in another task in the task queue, executed in the next iteration of event-loop
```

Usually it takes a couple of milliseconds in this case before scheduling and execution of the statements in `setTimeout`. So even  if you set the value ov `1` in the first `setTimeout`, it will still be shown before. Play around with it to see where is the limit for your system:

```javascript
console.log('1 - start');
const timeScheduled = Date.now();
setTimeout(() => console.log(`2 - setTimeout1 ${Date.now()-timeScheduled}ms have passed since I have been scheduled`), 1);
Promise.resolve('Success')
    .then(()=> console.log('3 - promise1'))
    .then(()=> console.log('4 - promise2'));
setTimeout(() => console.log(`5 - setTimeout2 ${Date.now()-timeScheduled}ms have passed since I have been scheduled`), 0);
console.log('6 - end');
```

<hr>

> Shared with :heart: from [Codever](https://www.codever.land/snippets/61169574f520065311390cd9/details). &nbsp; :point_right:  &nbsp; use the [**copy to mine**](https://www.codever.land/snippets/61169574f520065311390cd9/details) functionality to add it to your personal snippets collection.
JavaScript Program to Check Leap Year
Tags: javascript
Published: 2021-08-14 18:53:36

function isLeapYear(year) {
  if (year % 400 === 0) return true;
  if (year % 100 === 0) return false;
  return year % 4 === 0;
}
const isThatLeapYear = isLeapYear(2000);
if (isThatLeapYear == true) {
  console.log("Thi is is leap Year");
} else console.log("This is not Leap Year");
error message /Users/yyyyyy/.zshenv:.:1: no such file or directory: /Users/yyyyyy/.cargo/env
Tags: zsh, shel, macos
Published: 2021-08-14 18:33:58

**error message** ```/Users/yyyyyy/.zshenv:.:1: no such file or directory: /Users/yyyyyy/.cargo/env```

**any tips? need help. my Z shell .zsh and .zshenv went missing in MacOS Terminal. any ideas on how to resolve? it was there and then poofff👻**
When you need Database per Service ?
Tags: microservices, docker, redis, database
Published: 2021-08-14 18:33:32


```
Imagine opening a food ordering app.
                ||
                \/
       Selecting Dosai to eat.
                ||
                \/
       Three services spawns 
       //        ||        \\
      \/         \/         \/
   Ordering   Preparing   Delivery
```

>In a regular monolithic architecture three of these services share a single Food database.

Once the we select the food it arrives to Ordering service which intimates the hotel and updates the Food DB's Order table or collection.

Next( ), Food is been prepared at Preparing service (cooking & packaging) and updates the Food DB's Prepare table or collection.

Next( ), Food is been Delivered by Delivery service and updates the Food DB's Delivery table or collection.

###But a delivery app is not that simple to serve few hotels.

Thousands of hotels will be there.
 
Ordering has varities of style.

Preparing has lots of sub process in itself.

Delivery has lots of modes with communicating different people.

>Putting all these data in to single DB with several tables or collections, managing huge amount of data on these several tables and collections is sort of a pain when you want to scale and manage the service with less complexity.

>The main Complexity arises to whoever developes these services in the backend, also when finding bugs and fixing issues.

###How about each service has its own database ?

1. Ordering service has its own Order DB.
2. Preparing service has its own Prepare DB.
3. Delivery service has its own Delivery DB.

###Lets wrap them up in a container.

After wrapping OrderDB with Docker --> connect to

--> OrderingService

After wrapping PrepareDB with Docker --> connect to

--> PreparingService

After wrapping DeliveryDB with Docker --> connect to

--> DeliveryService


###Ok wait, now how do you synchronize these services ?

> The flow of process is not asynchronous.

>They need to be synchronized like,

```
 Order
  ||
  \/
Prepare
  ||
  \/
Deliver
```

>Somebody has to tell Preparing Service about the arrived Order. 

Next( )

>Somebody has to tell Delivery service about the food been prepared.

For this we need [Redis PUB/SUB](https://redis.io/topics/pubsub) to build a message broker between our OrderDB --> PrepareDB --> DeliveryDB.

>Order arrives, Ordering Service places order and updates OrderDB and says to the Preparing Service about the arrived order.

>After hearing about the Order, Preparing service prepares food and updates the PrepareDB and says to the Delivery Service about the Prepared food.

>After hearing about the prepared food, Delivery Service delivers food and updates DeliveryDB.

Now thats how Database per service will be utilized.
#100daysofcode [Day - 04]
Tags: javascript, programming, beginners, webdev
Published: 2021-08-14 17:54:30

#100daysofcode [Day - 04] ;

Today I have gained some knowledge about JS DOM (Document Object Model). Also, read some documentation about machine language and high-level programming language. also completed some real-time practice on DOM.



From the next day, I will share my daily practice via the GitHub link. Thank you all so much for supporting me.
Quais são os principais métodos HTTP?
Tags: beginners, ptbr
Published: 2021-08-14 17:53:39

Partindo do pressuposto que você saiba [o que é HTTP](https://dev.to/deborafelix/o-que-e-http-55jc) é necessário ver (ou rever) os métodos que compõem esse protocolo. 

#### GET
Um método de recuperação de recursos (como o HEAD), pode ter parâmetros ou não, mas tem apenas o intuito de retornar os dados requisitados. 

#### POST
É um método de alteração de recursos (como o PUT, PATCH, DELETE e OPTIONS), no POST algo é adicionado/anexado ao recurso especifico. 

#### PUT
Os métodos de alteração do recurso PUT e PATCH são irmãos, sendo PUT o mais rígido, ele vai alterar tudo, substituindo pelas novas informações que forem passadas.

#### PATCH
Já o PATCH é o irmão light, ele vai alterar apenas parcialmente os atributos, não substituindo. É importante gravar a diferença entre os dois para utilizar o que encaixa melhor na sua proposta.

#### DELETE
O método mais fácil se entender e o mais perigoso usar, ele remove adequando-se aos parâmetros passados, cuidado com esse durante o desenvolvimento!

#### HEAD
Esse método retorna os recursos, como o GET, sem o corpo da resposta. Ele pode ser bem útil na hora de procurar um problema em um serviço externo, onde não há a necessidade do body.

#### OPTIONS
Considerado alterador de recursos, usado para mudar as opções de comunicação do recurso de destino. 

#### CONNECT
Tanto o CONNECT quanto o TRACE são considerados métodos mais voltados para o ambiente. O CONNECT converte a requisição comunicação com o recurso estabelecendo um túnel. 

#### TRACE
Executa um teste, também chamado loop-back, que permite observar os pontos de falha de um  caminho até o recurso.

---

Esses são os mais conhecidos, porém não todos , existem muitos caminhos para aprofundar nesse assunto, o link que mais me ajudou a construir esse post: [Guia de métodos HTTP](http://www.intergate.net.br/blog/apis-guia-de-metodos-http-comuns/), link que aparentemente tem todos os [métodos HTTP](https://www.iana.org/assignments/http-methods/http-methods.xhtml) ou para descobrir mais sobre as versões do [HTTP](https://blog.neomind.com.br/diferencas-entre-http1-1-e-http2).
Javascript concept handbook for interviews
Tags: javascript, webdev, interview
Published: 2021-08-14 17:44:07


This series of questions and answers is all you need for all the concept and theory-based questions for your javascript interviews.

Various resources have been used for the reference of the answers of the following question and are mentioned as well for further reference.

Various forms/places you can get this blog.

PDF: https://drive.google.com/file/d/1MzoN4QZsSTOAY8naHCAQM47OTVlhe2E9/view?usp=sharing

Notion:
https://pratiktiwari.notion.site/Javascript-Questions-debadba90cf44b508f6553c444243945
Most Popular Web Dev Stacks
Published: 2021-08-14 17:32:59

A **Web stack** is the collection of software required for Web development.

## `LAMP`
LINUX
APACHE
MYSQL
PHP

## `LEMP`
LINUX
NGINX
MYSQL
PHP

## `MERN`
MONGODB
EXPRESS
REACT
NODEJS

## `MEVN`
MONGODB
EXPRESS
VUE
NODEJS

## `MEAN`
MONGODB
EXPRESS
ANGULAR
NODEJS

*`What stack do you Use?`*

+++++ Link +++++
Facebook: https://web.facebook.com/UnTalkCoding
Things to know about Flask as Beginners.
Published: 2021-08-14 17:23:48

## What is a Web Framework?

To understand Flask, we need to understand what is the traditional web framework.  A web application framework is a collection of libraries and modules which helps developers write the business layer without worrying about the protocol, thread management, etc. And Python’s Django follows a traditional web framework which is also called an enterprise framework. 

## What is Micro-framework?

In contrast to a traditional web framework, a micro-framework is a minimalistic framework where developers are provided with a lot of freedom to build the web application layer. As compared to an enterprise framework, a developer would not need to set up many things in a micro-framework to get the web app hosted and running. 

## What is Flask?

Now, we are well equipped to understand Flask. Flask is Python’s micro-framework for web app development. It was developed by Armin Ronacher, who led an international team of Python enthusiasts called Pocco. Flask consists of Werkzeug WSGI toolkit and Jinja2 template engine. Both were also developed by Pocco. It was initially released in April 2010. Currently, the latest version as of writing this article is 2.0.2. 

## What is WSGI?

Web Server Gateway Interface (WSGI) is the standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications.  

Werkzeug is one of the most advanced WSGI modules that contain various tools and utilities that facilitate web application development. Flask implements Werkzeug.

## What is Jinja 2?

Jinja 2 is a template rendering engine. It renders the web pages for the server with any specified custom content given to it by the webserver. Flask renders its HTML based templates using Jinja 2. 

## Why Flask?

Now, you would be able to understand, when we define Flask as a micro-framework that is built using WSGI and Jinja 2 template engine. 

Major advantages of Flask are: 

Ease of setup and use.
Freedom to build the structure of the web application. 
With freedom comes responsibility, similarly, Flask needs the developers to carefully structure it, since Flask doesn’t have “flask rules” to follow as compared to frameworks like Django. As the web app increases in complexity, this structuring is what is going to be the foundation.
What is Vanilla JS? Why Vanilla JS?
Published: 2021-08-14 17:01:48

The purpose of this post is to emphasize the importance of JavaScript fundamentals for every front-end developer. I’m going to tell you why you should have a good knowledge of pure (Vanilla) JavaScript. This means JavaScript without any additional frameworks or libraries.

## Why it is called Vanilla JS?

The term vanilla script is used to refer to the pure JavaScript (or we can say plain JavaScript) without any type of additional library. Sometimes people often used it as a joke "nowadays several things can also be done without using any additional JavaScript libraries".

The vanilla script is one of the lightest weight frameworks ever. It is very basic and straightforward to learn as well as to use. You can create significant and influential applications as well as websites using the vanilla script.

## List of Websites using Vanilla JS.
Facebook
Google
YouTube
Yahoo
Wikipedia
Windows Live
Twitter
Amazon
LinkedIn
MSN
eBay
Microsoft
Tumblr
Apple
Pinterest
PayPal
Reddit
Netflix

## Why should you learn vanilla JS?

There are several reasons for choosing the vanilla js to learn and use it in our projects.

### Web performance

Vanilla js code needs to be compiled and parsed, unlike HTML and CSS files, which are available to use only when they're downloaded.

### User experience

It provides an effortless but user-friendly developing experience.While developing an application or website using JavaScript, a developer just needs to open the text editor and can begin coding.

### It makes working with frameworks easier as well

In case, if any developer still wants to use any of the other frameworks, it makes working with them more comfortable as well.

### Interoperability

We can insert the JavaScript in any of the web-pages, but in another scripting language, we cannot do so.

### Server Load

Since we all know that the execution of the JavaScript is done on the client-sideso it reduces the overall demand for server use.

### Rich interfaces

With the help of JavaScript, we can create an excellent quality of features such as drag &drop, and components like a slider.

### Speed

Since its execution occurs on the client-side, it does not require any kind of external resources, its speed is excellent
How to add source map to the esbuild configuration
Tags: javascript, esbuild
Published: 2021-08-14 16:33:18

In this article, I'll show you how to add a source map to the setup we developed so far in [this series](https://how-to.dev/series/esbuild-tutorial).

# What is source map
As we introduce any bundling or compiling step to our application, we start to have a difference between what's in our source code & what's run on the browser. This is especially problematic in debugging, or error logs - the browser shows us the building code, while we try to fix the issue in the source. Source map allows the browser to map the code that it executes to the source.

# Enabling source map
To enable the source map, we need to add to `esbuild.config.js`:
```js
...

esbuildServe(
  {
    ...
    outfile: "www/main.js",
+   sourcemap: true,
  },
  { root: "www" }
);
```

With this in place, after we restart the server we can see the source in the development tool in the browser. Here example from firefox:

![source-map.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rylbifcbdtdxb2jlg4c2.png)

# Links
The [repo](https://github.com/marcin-wosinek/esbuild-tutorial), the [branch](https://github.com/marcin-wosinek/esbuild-tutorial/tree/step-6).

You can check out my [video course about esbuild](https://bit.ly/esbuild-course).

# Summary
We have seen how to add a source map to our setup. If you are interested in hearing when I have new esbuild content, you can sign up [here](https://landing.mailerlite.com/webforms/landing/b8k4x6).
Variable and Function Hoisting in JavaScript
Tags: javascript, hoisting
Published: 2021-08-14 16:16:04

##Let's understand the concept of Hoisting in functions and variables



This is beginner-friendly content. The only prerequisite we need would be a basic understanding of variables and functions.

Before we begin let’s understand how JavaScript works. Before running any program JavaScript goes through the entire program and creates a global execution context for the program. The execution context is where the JavaScript is executed. In this global execution context, we will have 2 phases.

The first phase is the memory phase or also called the variable environment. JavaScript allocates memory in the memory phase. To all the variables it allocates the placeholder 'undefined' and to all the functions it allocates the function body itself.

The second phase is the code execution phase. Here each line of command is executed in order.

##Keeping these things in mind let's dive into Hoisting

Hoisting is a phenomenon where you can access the variables and functions without any errors even before you have initialized them.

Let's walk through the below program.

```
console.log(a);
console.log(welcome);
welcome();
var a = 21;
function welcome() {
  console.log('Hoisting in JavaScript...');
}
```
Here in this program, we are accessing the variable 'a', function named 'welcome', and then we have the function call 'welcome'. We are doing all these things before we have initialized them.

In any other programming language, this would result in many errors. But this is not the case in JavaScript.

In JavaScript, the following lines are what you will be seeing in the console.

![Console Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu4fbc4vf2w436zyswr4.jpg)

Here's why you will see these above lines.

As I mentioned in the intro, JavaScript before executing the program it goes through the whole program and allocates memory to each variable, and functions in the memory phase.

To our program in the global scope ->

* JavaScript allocated the keyword 'undefined' to the variable 'a' as memory.

* For function 'welcome' it allocated the function body itself.

###Summary

JavaScript let's you access functions and variables even before they are initialized. Only function declarations are hoisted but not function expressions. Use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available.
Simple Video chat with WebRTC
Tags: javascript, webdev, webrtc, reactnative
Published: 2021-08-14 15:54:04

Reciently I find the existence of  WebRTC and sockets, also authentication. For me this was so interesting that I wanted to build something with that. No tutorials, only documentation an read a couple of books to understand the fundamentals. After several days of confusion and little frustation I just started to write code. Always something went wrong but in my way to see it that's the path in order to finish any project.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5wmm5w253zedl4q38moy.png)

I hope you like this simple video chat and maybe the design also like you. (I suck regarding UX/UI design)
Any suggestions please say everything, bad or good doesn't matter. I really want to improve my skills so go ahead. :)
Currently doesn't work with phones but I've been thinking to create it with React Native so if someone wants to join me in this journey... send me a message. :)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02mvdqhyyqrg4u9cf72e.png)

Repostitory: https://github.com/Josafath/simple-video-chat
Website: https://study-partner.herokuapp.com/

I you liked the project give it a star in GitHub or give it love to this post. 🤍