teleren/devto huggingface dataset:
A (somewhat) Universal approach to lazy sequence manipulation
Tags: lazy, stream, collection, manipulation
Published: 2021-05-29 16:54:39

Fellow developers, how many times have you transformed
```javascript
array.map(mapper).filter(predicate)
```

into
```javascript
array.reduce(() => {
    // Oh my god what do I do?
}, [])
```

just to avoid the added cost of N loops?

Most of those who, like me, absolutely love how expressive these methods can be, have found solutions in our respective languages:
* C++'s [Range V3](https://github.com/ericniebler/range-v3) or [C++20 Ranges](https://en.cppreference.com/w/cpp/ranges)
* JavaScript's [sequency](https://github.com/winterbe/sequency)
* Java 8's [Stream API](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)
* Kotlin's [sequences](https://kotlinlang.org/docs/sequences.html)
* Rust's [iter](https://doc.rust-lang.org/std/iter/index.html#laziness)
* Haskell's lists, sequences, etc...

That's all nice but they all have completely different interfaces, some harder to extend, etc...

What if, we could just have one way of doing things?

Let me introduce to you my attempt at a unified interface across programming languages: the [Universal Couroutine Based Lazy Sequence Manipulation](https://github.com/Voltra/UniversalCoroutineBasedLazySequenceManipulation).


These fancy words mean that if your language has support for generators (or even better, coroutines!) then you will probably be able to implement this by adapting the pseudocode into your language of choice.

For those of us who are less fortunate and do not have access to generators or coroutines, there is a way to adapt this library to only use iterators instead.

Now, for the example:

```javascript
const results = Stream.range(10)
    .skip(5)
    .take(100)
    .map(x => 3*x - 5)
    .filter(x => x % 4 === 0)
    .map(x => x * 2)
    .take(5)
    .toArray();

console.log(results); // [32, 56, 80, 104, 128]

//// Strictly equivalent (in complexity) to

const results = [];
let count = 0;

for(const item of someMagicalIteratorRangeToSavePerformances(10, 115)){
  if(count >= 5)
    break;

  const alpha = 3*item - 5;
  if(alpha % 4 === 0){
    const beta = alpha * 2;
    results.push(beta);
    count++;
  }
}

console.log(results);
```

Easier to write, more readable, everything we love.


I aim to make it as usable as possible so writing a library is really simple and straightforward. Any contribution is appreciated.
WebdriverIO v7 Crash Course (Sync Mode)
Tags: javascript, testing, webdev, tutorial
Published: 2021-05-29 16:41:49

Check out this crash course on WebdriverIO v7 using the sync mode - 

{% youtube IT_0E-fFqZc %}

---

### Please review the below info to follow along with this video using sync mode:
- Along with installing all the packages in the video, you will also need to install the sync package - `npm i @wdio/sync` to support the sync mode
- You will notice async/await in the auto-generated code by WebdriverIO. Simply remove async-await and just follow along with the video.

You also need to ensure you are NOT using Node v16 or above so that sync mode can be still supported. For all the other resources, check out the video description. 

**Note:** Since sync mode will no longer be supported with Node v16, you should ideally start using async mode with WebdriverIO for new projects.

---

📧 Subscribe to my [mailing list](https://automationbro.com/mailing-list) to get access to more content like this 

👍 Follow [automationbro](https://twitter.com/automationbro) on Twitter for the latest updates

...

I love coffees! And, if this post helped you out and you would like to support my work, you can do that by clicking on the button below and buying me a cup of coffee -

<a href="https://www.buymeacoffee.com/automationbro">![Buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/i/4aw2ub3f4qkyjk0ivwt4.png)</a>

You can also support me by liking and sharing this content.

Thanks for reading!
Java ‘length’ dilemma: String.length() vs Array.length
Published: 2021-05-29 16:27:22

## Summary
A very common mistake during the development time is .length or .length() for array and string. Okay, now we try to understand and remember it so that we can remember it easily.
### For array, length is a property.
It is a property and we pre-define it, and we only once can initialize an array size so, it is actually a final value.
### For string, length is a function.
We can not access a string’s length as property because it is not pre-defined like array, java needs to calculate the length for string… !!!
## Deep Drive
Interestingly java string is backed by array implementation actually (byte array). In that case, Sun Microsystem could use array’s length for string. Besides in Java, String is immutable, so there is no chance of length modification(!). But what is the philosophy behind this length function?

Mainly for maintaining encapsulation philosophy,(hide direct access of length variable). Moreover, the String class implements CharSequence, and length() came from it (Historically, String API is older than CharSequence !).
### String.length() => O(1) or O(n)?
Order O(1), because it just returns the underlying byte array’s length.

### Is this good practice: for(int i = 0; i < string.length(); i++) ?
Yes, it is ok, if we consider modern compiler’s are smart enough and they optimize code and remove function call.
Function call has some extra overheads so, I do not prefer this coding style. It is better to save the length value in other variables in case of this type of iteration.
...
*Medium Link: https://khabib97.medium.com/java-length-dilemma-string-length-vs-array-length-ff0552ba7968*
Proxy VS Reverse Proxy (less theory)
Published: 2021-05-29 16:22:09

> *Okay, it was a very common scenario during your university life, there were some friends who gave our attendance.*

That actually means, during roll call, our friends respond on behalf of us. Simply, this is a proxy.

### In Computer Science?
Things are almost similar. But need some extra explanations.

Before starting a discussion, we need to clarify 2 terms.
1. **Proxy** means actually **forward-proxy**. So, we should always remember it.
2. **Reverse-Proxy** means **reverse-proxy**.

### Forward-Proxy aka Proxy
In the client-server model sometimes clients need to hide their identity (from the server or …).

Sometimes some governments block Facebook/Instagram/Twitter in their countries, but people somehow manage to visit these sites. In most cases, it is the proxy who plays the main role(VPN is not proxy, we will discuss it next time)

* **General Scenario**: User → Facebook = Successfully Access
* **Blocked Scenario**: User → **Government Block** →Facebook = Access Denied
* **Proxy Scenario**:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhnjc9bt3dfrf3dv09p6.png)

> **You**: Hey Proxy Server, I need to visit Facebook.
**Proxy-Server**: Ok, don't worry. I will communicate on behalf of you.

Your actual request(primary request) to a proxy server, inside the request there is another request(secondary-request) for the proxy server to access Facebook on behalf of you(!). So, blocakage does not work, your primary request is not for accessing Facebook. Additionally, you hide your actual IP from Facebook.

Actually, using forward-proxy, clients(users) hide their identities.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ca6bwksxqci5shfnlplx.jpeg)

### Reverse-Proxy
>Sometimes it is necessary for a server to hide its identity (!!! Seriously)

So, when a server hides its identity, it is call reverse-proxy.

It sounds wired. But true.

This time user has no idea about the actual server. He knocks on the middleware server for any service. This server works as a broker, it knows the internal handover logic when a new request arrives. It handovers the request to the actual designated server. There will be one or multiple servers to serve the request. It is totally unknown to the users(clients), they only know the middleware(reverse-proxy) server. This way servers hide their identity from users(malicious users!!!). Besides, there are lots of very useful usages of reverse-proxy like load balancing, caching…(discuss next time)

...

### Final image

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8orekcl9kqbaalctlsyk.png)

*First Published: https://khabib97.medium.com/proxy-vs-reverse-proxy-less-theory-f72988f51267*
JavaScript tips: The labeled statement
Tags: javascript, productivity, programming, typescript
Published: 2021-05-29 15:47:36

What if you type in the console something like this?
```js
label: {}
```
You won't have any errors. This is valid JS!

It turns out you can reference loops in Javascript. This was something I did not know a few days ago, but is a really cool and helpful feature in Javascript. In the following video, I explain you with examples how to use labeled statements.

{% youtube YosGqtogIo0 %}
Recommendation Systems by Matrix Factorization and Collaborative Filtering
Tags: aipool, ai, machinelearning, python
Published: 2021-05-29 15:39:06

### Introduction  
  We're all using any platform which has some items and these items are made for us, for users. In general, we use some of them and get suggestions for other items as well, but what suggestions are they, how do they even know what to suggest, which type of items each user likes and what is the probability, that they are going to like something platform suggests?

Recommendation systems are created just for this. Let's take **Netflix** as an example. It has a lot of movies and users watch them on their platform. When each user watches any movie, **Netflix** suggests other movies relevant to the user or the item, which the user has watched.

Nowadays almost all platforms like **Facebook**, **Youtube**, **Twitter**, **Pinterest**, **Amazon**, etc. use recommendation systems, to suggest relevant content to their users. It gives good growth in terms of revenue or other business metrics, which is important to the company.

Now let's formulate a recommendation system and show how it's going to suggest content relevant to users.

![image](https://files.ai-pool.com/a/eca7d9d969c4b56e58bdfeeda5e6a8c4.png)

### Recommendation Systems, Problem Formulation
  Let's assume we have multiple users and movies. Each user has watched any movie and liked it. It means different movies can be liked by the same person and different users can like the same movie. It kind of like a matrix for users and items. This matrix will contain users and movies as rows and columns and each (i,j) position of the matrix will correspond to the rating of the movie or user has liked it or not. Something like this.

![image](https://files.ai-pool.com/a/8ccc261ef0bb339e4f923b22ab06a42c.png)

It is a sparse matrix. If the user has not watched the movie, then the corresponding place of this matrix will be undefined. Our goal is to find a model, which will fill all missing places in the matrix we showed above.

Find more about collaborative filtering and matrix factorization in the [Following Article](https://ai-pool.com/a/s/recommendation-systems-by-matrix-factorization-and-collaborative-filtering)

### Other Resources
* [Finding an Optimal Number of Clusters With Elbow Method](https://ai-pool.com/a/s/finding-an-optimal-number-of-clusters-with-elbow-method)
* [Linear and Logistic Regression](https://ai-pool.com/a/s/linear-and-logistic-regression)
* [AlexNet](https://ai-pool.com/m/alexnet-1564424451)
How to find which test warns unhandledPromiseRejection in jest
Tags: javascript, jest, testing
Published: 2021-05-29 15:30:34

![unhandledPromiseRejectionWarning](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0b4lopdro445rr5h6egw.png)

From the above image can you tell which test suite is warning about `unhandledPromiseRejection`. Is it the one above the warning message or one below the warning message?

As most of you, me too wrongly guessed the test suite above the warning message warns about `unhandledPromiseRejection`. That eat up quite sometime since every time I re-run the tests, the warning seems to happen in different test suite module. 

How did I figure out the it is the test suite below the `unhandledPromiseRejection` warning message is one that suffers?

I have added the following code in the jest's `setupFilesAfterEnv` file:

```javascript
process.on('unhandledRejection', reason => {
  throw reason
})
```
which logged the error trace
when I run the tests with 
```shell
node --trace-uncaught node_modules/.bin/jest --runInBand --no-cache
```
Copiando com Javascript - Clipboard API
Tags: javascript, clipboardapi, webapis, braziliandevs
Published: 2021-05-29 15:16:05

---
title: Copiando com Javascript - Clipboard API
published: true
description: _Como copiar com Javascript utilizando Clipboard API._ Imagem de [Sigmund](https://unsplash.com/@sigmund)
tags:
  - javascript
  - ClipboardAPI
  - WebAPIs
  - braziliandevs
cover_image: https://giovanisleite.dev/static/395b4265d10368ec94b0b6d38117ba6a/a7c53/banner.webp
canonical_url: https://giovanisleite.dev/copiando-com-javascript
---

TL;DR

```javascript
let textToCopy = "Eu quero copiar esse texto aqui"

function afterSuccess() {
    console.log('Copiado com sucesso!')
}

function afterFailure(error) {
    console.error('A Cópia falhou!', error)
}

window.navigator.clipboard
    .writeText(textToCopy)
    .then(afterSuccess, afterFailure)
```

Numa era pré [ClipboardAPI](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API), a solução para copiar e colar algum texto que eu mais vi envolvia adicionar à página um input com o texto que você quer copiar, colocar o foco naquele input, selecionar o texto e enviar o comando `document.execCommand("copy")`. E em muitos casos essa ainda é a melhor solução dependendo de quais browsers a sua aplicação deve-se manter compatível. Você pode comparar o suporte dessa feature utilizando o [caniuse.com](caniuse.com). Suporte a [document.execCommand](https://caniuse.com/document-execcommand) x Suporte a [Clipboard API write text](https://caniuse.com/mdn-api_clipboard_writetext). [Em caso de IE, não tem jeito, vai ter que usar `document.execCommand`](https://stackoverflow.com/a/46118025/7838074).

Para o uso do Clipboard API, além de conhecer a API em si, temos que respeitar algumas regras por questão de segurança. Uma delas, por exemplo, é que o clipboard.writeText vai falhar caso o usuário não esteja com foco na aba. Você pode ver esse erro acontecendo, testando o código no console do seu browser (isso no Chrome). Em alguns outros browsers, esse código só funciona caso esteja num código sendo executado em resposta a uma ação do usuário, como um click por exemplo. Então, tenha isso em mente ao utilizar essa API.

O código é simples, a função `window.navigator.clipboard.writeText` retorna uma [`Promise`](https://medium.com/trainingcenter/entendendo-promises-de-uma-vez-por-todas-32442ec725c2), ou seja, ele é assíncrono, logo após a sua execução pode ser que ele ainda não tenha terminado de copiar. Por isso, nós utilizamos o `.then`, para que quando essa `Promise` seja resolvida, ou seja, o comando tenha de fator terminado de copiar ou dado erro, no caso de sucesso execute a nossa função `afterSuccess` e em caso de erro execute nossa outra função, `afterFailure`. E é isso, assim que aparecer a mensagem de sucesso, já estamos livres pra sair colando nossa mensagem.

Esse text foi originalmente postado em https://giovanisleite.dev/copiando-com-javascript
The Vim Cheat Sheet
Tags: vim, linux
Published: 2021-05-29 14:53:48

[Vim](https://en.wikipedia.org/wiki/Vim_(text_editor)) is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems.

Vim is often used by programmers on [Linux](https://bsdnerds.org/what-is-linux-shell/). But it can be used on Mac OS X and Windows too.

![vim text editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0e6dlbe8t96rm5oa3k07.gif)

Vim is a powerful text editor that runs in a terminal, yet can be used to edit any kind of file. It's old, it's weird, and it's hard to learn but also one of the most powerful tools for editing code on any operating system.

So what about commands?

## Vim commands

Here's a handy cheat sheet to help you get started with the editor. 

| Cursor Movement | |
|---|---|
| h | move cursor left |
| j | move cursor down |
| k | move cursor up |
| l | move cursor right |
| w | jump forwards to the start of a word |
| b |  jump backwards to the start of a word |

To write and to use commands press `ESC` for command mode or `i` for insert mode.

To save, open and quit a file:

| Basic editor commands ||
|---|---|
| :e filename  |	edit a file in a new buffer |
| :w 	| write (save) the file, but don't exit |
| :wq 	| write (save) and quit |
| :x 	| write (save) and quit |
| :q 	| quit (fails if there are unsaved changes) |
| :q! 	| quit and throw away unsaved changes |
| :qa 	| quit all buffers and windows |
| ZZ 	| write (save) current file, if modified, and quit |
| ZQ 	| quit without checking for changes |

You can copy and paste text too:

| Cut and Paste ||
|---|---|
| yy 	| yank (copy) a line |
| 2yy 	| yank (copy) 2 lines |
| p 	| put (paste) the clipboard after cursor |
| P 	| put (paste) before cursor |
| dd 	| delete (cut) a line |
| 2dd 	| delete (cut) 2 lines |

There are quite a few commands you have to memorize to use Vim effectively, which can be overwhelming when you’re learning. 

You can use [these exercises](https://vim.is) to memorize commands.
::before / ::after in css
Tags: css, html, webdev
Published: 2021-05-29 15:14:06

Insert some text/image etc before of after and after an element without adding html elments

**Use case**


![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/msdv9ut5wbtuf9z4nnso.png)

Sometimes we need to style element like above in such case we can use before and after like below

**html**

```
<p>This is paragraph</p> 
```

**css**


```
p {
    display: flex;
    align-items: center;
  }

  p::before {
    content: "";
    margin-right: 10px;
    flex: 1;
    border-bottom: 1px solid #ccc;
  }

  p::after {
    margin-left: 10px;
    content: "";
    flex: 1;
    border-bottom: 1px solid #ccc;
  }
``` 


Thanks for reading this if you have any other suggestions to do this better please comment below

For react beginner you can follow me on youtube ( If you want )

React/Javascript Videos (IN Hindi)  : 

{% youtube NKotnxP6wdk %}
Pug Responsive Navbar
Tags: webdev, pug, css, welcome
Published: 2021-05-29 15:12:55

Navbar is a powerful part of the website to show features and branding. So here made Navbar in Pug cli with the help of CSS and javascript.

In this element, we used font awsome in the responsive side on toggle click. Also, we used jquery to make this element clickable on the toggle view side. Here we used an external file for CSS, js with CDN for jquery. This is a responsive table and mobile-friendly user interface.

Make it yours now by using it, downloading it, and please share it. we will design more elements for you.

[Source Code](https://w3hubs.com/pug-responsive-navbar/)
Bias-Variance Tradeoff in Machine Learning
Tags: aipool, ai, machinelearning, math
Published: 2021-05-29 14:54:23

### Hypothesis Space
  Before speaking about bias and variance, let's understand what hypothesis set is and how we are going to define it. First of all, when you train a model, you are seeking a hypothesis function over the entire space. It does not matter you train a linear regression, logistic regression or a deep network, you always have to understand what a hypothesis set is and how you're going to find a function you are looking for. 

If we create a model to approximate the given target function, it means we define a hypothesis set. Our trained model is a point from it, which can be far or close to the target function.

Now let's define our hypothesis set. Let's assume we have chosen a model, which defines hypothesis set **H**.

### Bias-Variance Tradeoff
  There is an optimal point, where bias and variance are in a good position and their values are reasonable. To find that optimal point, we need to draw the curves for every value, which depends on the complexity of the model. By saying the complexity of the model, we mean the complexity of the hypothesis set, the size of it.

![image](https://files.ai-pool.com/a/c457c503205d0740d3efc553bdb74b0b.png)

Our goal is to minimize the total loss, which consists of bias, variance, and small noise. These curves show that increasing the complexity of the model, will decrease the bias, but the variance will increase and as a result, the total loss will be high.
We can't take a too simple model, which can't even approximate the target function and can't take too big one either, because it has high variance.

![image](https://files.ai-pool.com/a/492989098d60c7a2e6a592efb70804f7.jpg)

This is a known problem in the machine learning sphere, specifically in deep learning. Every specialist knows about Underfitting or High Bias and Overfitting or High Variance. These are the main problems everybody faces and there are a lot of approaches to fix them. People tried to solve this in the following ways.

* **Regularization**
* **Model Selection / Early Stopping**
* **Cross-Validation**
* **Normalization Functions**
* **Augmentation Techniques**
* **Others**

You can find more in the [Following Article](https://ai-pool.com/a/s/bias-variance-tradeoff-in-machine-learning)

### Other Resources

* [Confidence Interval Understanding](https://ai-pool.com/a/s/confidence-interval-understanding)
* [Introduction of Fast Fourier Transformation (FFT)](https://ai-pool.com/a/s/introduction-of-fast-fourier-transformation--fft)
* [Why network overfits too early?](https://ai-pool.com/d/why_network_overfits_too_early_)
* [Give some suggestions to avoid overfitting](https://ai-pool.com/d/give_some_suggestions_to_avoid_overfitting)
Getting Started in Azure [TechTalks #1]
Tags: azure, cloud, microsoft
Published: 2021-05-29 14:51:32

{% youtube rm6MpG7YfZw %}

## Resources

- Meetup Group - [meetingplace.io/groups/azureall](https://meetingplace.io/groups/azureall)
- Youtube Channel - [youtube.com/c/TechTalksWriju](https://www.youtube.com/c/TechTalksWriju?sub_confirmation=1)
- LinkedIn - [linkedin.com/in/wrijughosh/](https://www.linkedin.com/in/wrijughosh/)
- Twitter - [@wrijugh](https://twitter.com/wrijugh)
- Facebook Page - [www.facebook.com/groups/azureforall](https://www.facebook.com/groups/azureforall)
- Blog - [dev.to/wrijugh](https://dev.to/wrijugh)
- Blog - [wriju.wordpress.com](https://wriju.wordpress.com/)