teleren/devto huggingface dataset:
🅳🆁🆈-🅾🅽-🆁🅴🅰🅲🆃 🎉
Tags: javascript, react, dry
Published: 2021-06-11 09:39:11

🅳🆁🆈-🅾🅽-🆁🅴🅰🅲🆃 🎉

Hi, I've just opened a public space to build up a useful collection of helper functions for ordinary and concurrent daily problems.

I'm a freelance Software Engineer, my stack is `Javascript` & `React`. After some time working on different projects, I found myself facing the same problems and solving them with the same pattern. This is a repository for saving valuable time and stay as DRY as possible while working.

> This open-source has his goal on stay as 🄳🅁🅈 (Don't Repeat Yourself) as possible.

## Example 1: phoneMask

How many times do I have to write a function to mask/format a mobile phone number input????

This is how I implemented 👇 
```javascript
// Parameter> $inputValue: string
// Output> "xxx-xxxx-xxxx"
export const phoneMask = (inputValue = "") =>
  inputValue
    .replace(/\D/g, "")
    .replace(/(\d{1,3})(\d{1,4})?(\d{1,4})?/g, function (_, a, b, c) {
      return c ? `${a}-${b}-${c}` : b ? `${a}-${b}` : `${a}`;
    });
``` 

## Example 2: useInputs
How do you handle user input changes on React? Still using the obvious useState?
I write a custom hook to handle user input changes trying to be clean on implement and effective at the same time.

This is how I implemented it👇 (Typescript + React hooks)

```typescript
import React, { useCallback, useReducer } from "react";

type DefaultValues = {
  [key: string]: string;
};
type UseInputsAction = {
  name: string;
  value: string;
};

function reducer<T>(state: T, action: UseInputsAction | null) {
  if (!action) {
    const initialState: any = {};
    Object.keys(state).forEach((key) => {
      initialState[key] = "";
    });

    return initialState;
  }

  return {
    ...state,
    [action.name]: action.value,
  };
}

export default function useInputs<T>(defaultValues: DefaultValues) {
  const [state, dispatch] = useReducer(reducer, defaultValues);
  const onChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
      dispatch({
        name: e.target.name,
        value: e.target.value,
      });
    },
    []
  );
  const onReset = useCallback(() => {
    dispatch(null);
  }, []);

  return [state, dispatch, onChange, onReset] as [
    T,
    typeof dispatch,
    typeof onChange,
    typeof onReset
  ];
}

/*

# Usage
import { useInputs } from "./dry";

.
.
.
// React component
const [form, onChange] = useInputs<MyFormType>({
    email: '',
    password: '',
});
.
.
.
// Render => Form JSX
<form>
  <input 
    type="email"
    name="email"
    value={form.email}
    onChange={onChange}
  />
  <input
    type="password"
    name="password"
    value={form.password}
    onChange={onChange}
  />
</form>

*/
```

#### SAME CODE to solve SAME PROBLEMS?
##### Contribute your grain of code👇
[![DRY-001](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jthtj9no2b1vhfrsl4p1.png)](https://github.com/filoscoder/dry-on-react)
Cross Account DynamoDB Table Replication
Tags: aws, dynamodb, replication, npm
Published: 2021-06-11 09:30:56

**Objective**

This is to migrate (one-time replication) DynamoDB table between different AWS accounts.

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17fmriz30v2rq28izt5t.png)

**Implementation Steps**

Prerequisite: npm installed

a. Download the scripts from below repo “core-dynamodb-replication”
[akrockz/core-dynamodb-replication] (https://github.com/akrockz/core-dynamodb-replication)

This module will allow you to copy data from one table to another using very simple API, Support cross zone copying and…github.com

b. In “execute.js”, update access key details for source and destination AWS accounts (IAM User: dynamodb-ce).

c. In “execute.js”, update DynamoDb table names for source and destination AWS account.
```
copy({
source: {
tableName: 'demo-dynamodb-poc-old-dynamodb', // required
config: sourceAWSConfig // optional , leave blank to use globalAWSConfig
},
destination: {
tableName: 'demo-dynamodb-poc-new-dynamodb', // required
config: destinationAWSConfig // optional , leave blank to use globalAWSConfig
},
```
d. Before executing the command, verify the source and destination DynamoDB and check for the table size.

e. Run “node execute.js” locally.

Command:
```
node execute.js
```
Sample output:
```
core-dynamodb-replication ak$ node execute.js
[AWS dynamodb 200 0.379s 0 retries] describeTable({ TableName: 'demo-dynamodb-poc-1-dynamodb' })
[AWS dynamodb 400 0.06s 0 retries] createTable({ AttributeDefinitions:
[ { AttributeName: 'ingest_date', AttributeType: 'S' },
{ AttributeName: 'record_id', AttributeType: 'S' },
[length]: 2 ],
TableName: 'demo-dynamodb-poc-new-dynamodb',
KeySchema:
[ { AttributeName: 'ingest_date', KeyType: 'HASH' },
{ AttributeName: 'record_id', KeyType: 'RANGE' },
[length]: 2 ],
BillingMode: 'PAY_PER_REQUEST',
SSESpecification: { Enabled: true } })
[AWS dynamodb 200 0.065s 0 retries] describeTable({ TableName: 'demo-dynamodb-poc-new-dynamodb' })
Creating Destination Table .[AWS dynamodb 200 0.07s 0 retries] scan({ TableName: 'demo-dynamodb-poc-1-dynamodb', Limit: 25 })
[AWS dynamodb 200 0.08s 0 retries] batchWriteItem({ RequestItems:
{ 'demo-dynamodb-poc-new-dynamodb':
[ { PutRequest:
{ Item:
{ ingest_date: { S: '2019-10-14' },
record_id: { S: 'R_00020191014' },
track: { S: '702' } } } },
{ PutRequest:
{ Item:
{ ingest_date: { S: '2019-10-12' },
record_id: { S: 'R_00020191012' },
track: { S: '704' } } } },
[length]: 2 ] } })
Copied 2 items{ count: 2, status: 'SUCCESS' }
core-dynamodb-replication ak$
```
f. Login to destination account and verify if the DynamoDB table has been created.
Configure SSL between RDS and Weblogic / DMS endpoint
Tags: aws, ssl, dms, encryption
Published: 2021-06-11 09:25:23

**Background**

Need to enable End to End encryption for connectivity between Apps to RDS DB.

**On Oracle RDS side**

When creating the Oracle instance, configure the Option group SSL setting like below.

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

**On weblogic side**

* After connection pool is created, update the below URL field. For example,
```
jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=<weblogic-host>)(PORT=2484))(CONNECT_DATA=(SERVICE_NAME=DEMOWLST)))
```
* In the connection Properties, add the following
```
user=wlsdbuser
databaseName=DEMOWLST
javax.net.ssl.trustStore=/prod/applc/wls/domain/base_domain/certs/trust.jks
javax.net.ssl.trustStoreType=JKS
javax.net.ssl.trustStorePassword=<password, default to Admin password>
```

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

**Creating trusted JKS/Wallet**

* To extract the RDS cert,
```
openssl s_client -showcerts -connect "{{ datasource.rdsHostName }}:{{ datasource.rdsSSLPort }}" </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/rds.pem
 
csplit -z -f tmpRDScert- /tmp/rds.pem '/-----BEGIN CERTIFICATE-----/' '{*}'
 
cp `ls -1 tmpRDScert-* | tail -1` /tmp/rdsRoot.pem
```
* To import the root cert to JKS keystore,
```
keytool -import -alias rds-rootcert -file /tmp/rdsRoot.pem -keystore /prod/applc/wls/domain/base_domain/certs/trust.jks -storepass {{ domain_password }} -noprompt
```

* To import the root cert to Oracle Wallet (DMS endpoint require this),
```
/prod/applc/wls/oracle_common/bin/orapki wallet create -wallet /tmp/ssl_wallet -auto_login_only
/prod/applc/wls/oracle_common/bin/orapki wallet add -wallet /tmp/ssl_wallet -trusted_cert -cert /tmp/rdsRoot.pem -auto_login_only
```
For Oracle DMS endpoint, you will need to select rds-oracle-wallet when enabling the SSL with “verify-ca” option and point the port to the SSL enabled port.
Password Hashing using bcrypt
Tags: javascript, beginners, programming
Published: 2021-06-11 09:15:07

---
title: Password Hashing using bcrypt
published: true
description: 
tags: javascript, beginner, programming
//cover_image: https://direct_url_to_image.jpg
---

Authentication is a very important aspect of web development, and as beginners, it can seem like a daunting task. In this brief tutorial, we would learn how to hash passwords during user signup/registration.

### Pre-requisites
1. Basic knowledge of JavaScript.
2. expressJS
3. bcrypt package

Create a folder on your local machine, and create a file `app.js`. we would put every code in this single file.
```javascript
const express = require("express");
const bcrypt = require("bcrypt")

const app = express(); // init express app

app.listen(5000, () => {
   console.log('Server listening on port 5000...')
})
```

We wouldn't be using a database in this tutorial but a array to pass the lesson across. We would create an async-await function for the password hash.

```javascript
const express = require("express");
const bcrypt = require("bcrypt")

const app = express(); // init express app

app.use(express.json()) // accepting json body-parsers

const users = [] // we would be using as local storage

// creating a function for the password hash
const hashPassword = async (password) => {
  try {
    const salt = await bcrypt.genSalt();
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  } catch (error) {
    console.error(error);
  }
};

// Server up and running
app.listen(5000, () => {
   console.log('Server listening on port 5000...')
})
```

Now, it is time to use the password hash function we created above to hash passwords. And the empty `users` array as our local storage.
```javascript
const express = require("express");
const bcrypt = require("bcrypt")

const app = express(); // init express app

app.use(express.json()) // accepting json body-parsers

const users = [] // we would be using as local storage

// creating a function for the password hash
const hashPassword = async (password) => {
  try {
    const salt = await bcrypt.genSalt();
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  } catch (error) {
    console.error(error);
  }
};

// sending a post request to create a user
app.post(async (req, res) => {
    const passwordHash = await hashPassword(req.body.password)
    try {
    const user = {username: req.body.username, password: 
               passwordHash}
    users.push(user);
    res.status(201).json(user); 
/*
would return the user if you are using postman, 
you can as well console.log(user) to see the result in the terminal
*/
    } catch (error){
      console.error(error)
    }
})

// Server up and running
app.listen(5000, () => {
   console.log('Server listening on port 5000...')
})
```

I believe things worked out on your own end, while following this tutorial.. 

#### Thanks for reading..
Doing the right thing for the wrong reasons
Tags: google, corewebvitals, seo, amp
Published: 2021-06-29 10:59:21

---
title: Doing the right thing for the wrong reasons
published: true
date: 2021-06-10 10:44:38 UTC
tags: google,corewebvitals,seo,amp
canonical_url: https://adactio.com/journal/18199
---

I remember trying to convince people to use semantic markup because it’s good for accessibility. That tactic didn’t always work. When it didn’t, I would add “By the way, Google’s searchbot is indistinguishable from a screen-reader user so semantic markup is good for SEO.”

That usually worked. It always felt unsatisfying though. I don’t know why. It doesn’t matter if people do the right thing for the wrong reasons. The end result is what matters. But still. It never felt great.

It happened with responsive design and progressive enhancement too. If I couldn’t convince people based on user experience benefits, I’d pull up [some](https://adactio.com/links/9681) [official](https://adactio.com/links/7728) [pronouncement](https://adactio.com/links/10353) from Google recommending those techniques.

Even AMP, a dangerously ill-conceived project, has one very handy ace in the hole. You can’t add third-party JavaScript cruft to AMP pages. [That’s useful](https://adactio.com/journal/12011):

> Beleaguered developers working for publishers of big bloated web pages have a hard time arguing with their boss when they’re told to add another crappy JavaScript tracking script or bloated library to their pages. But when they’re making AMP pages, they can easily refuse, pointing out that the AMP rules don’t allow it. Google plays the bad cop for us, and it’s a very valuable role.

AMP is currently dying, which is good news. Google have announced that [core web vitals will be used](https://adactio.com/journal/18040) to boost ranking instead of requiring you to publish in their proprietary AMP format. The really good news is that the political advantage that came with AMP has also been ported over to core web vitals.

Take [user-hostile obtrusive overlays](https://adactio.com/journal/16786). Perhaps, as a contientious developer, you’ve been arguing for years that they should be removed from the site you work on because they’re so bad for the user experience. Perhaps you have been met with the same indifference that I used to get regarding semantic markup.

Well, now you can point out how those annoying overlays are affecting, for example, the cumulative layout shift for the site. And that number is directly related to SEO. It’s one thing for a department to over-ride UX concerns, but I bet they’d think twice about jeopardising the site’s ranking with Google.

I know it doesn’t feel great. It’s like dealing with a bully by getting an even bigger bully to threaten them. Still. Needs must.
Comparing currency devaluation with Python
Tags: python
Published: 2021-06-11 09:06:14

As the old saying goes, "money makes the world go around". Sure enough, money is the easiest way to measure a country's economic health, or at least its purchasing power. 

Data about purchasing power is publicly available at statista. We can use matplotlib to plot a [line chart](https://pythonbasics.org/matplotlib-line-chart/) and compare the devaluation process of currencies.

For the [euro](https://www.statista.com/statistics/1055948/value-euro-since-2000/) the purchasing power data from 2000 to 2020 is:

```python
y = [ 1.39, 1.36, 1.33, 1.3, 1.28, 1.25, 1.22, 1.2, 1.16, 1.15, 1.13, 1.1, 1.08, 1.06, 1.06, 1.06, 1.06, 1.04, 1.02, 1.01, 1]
```

The code below plots the devaluation of the euro:

```python
import matplotlib.pyplot as plt
import numpy as np

y = [ 1.39, 1.36, 1.33, 1.3, 1.28, 1.25, 1.22, 1.2, 1.16, 1.15, 1.13, 1.1, 1.08, 1.06, 1.06, 1.06, 1.06, 1.04, 1.02, 1.01, 1]
x = range(0,len(y)) 

plt.figure()
plt.plot(x,y)

plt.show()
```

For the dollar the devaluation is:

```python
y = [ 1.51, 1.47, 1.45, 1.41, 1.38, 1.33, 1.29, 1.26, 1.21, 1.19, 1.16, 1.13, 1.12, 1.1, 1.1, 1.08, 1.06, 1.04, 1.02 ]
```

The numbers are not in the same range, so you need to normalize them.  I will normalize against the maximum, not normalize against the sum. To normalize against the maximum you can use

```python
norm = [float(i)/max(raw) for i in raw]
```

Ofcourse I add a [legend](https://pythonspot.com/matplotlib-legend/) to the plot to show the currency. 
That gives us this plot:

```python
import matplotlib.pyplot as plt
import numpy as np

eur = [ 1.39, 1.36, 1.33, 1.3, 1.28, 1.25, 1.22, 1.2, 1.16, 1.15, 1.13, 1.1, 1.08, 1.06, 1.06, 1.06, 1.06, 1.04, 1.02]

usd = [ 1.51, 1.47, 1.45, 1.41, 1.38, 1.33, 1.29, 1.26, 1.21, 1.19, 1.16, 1.13, 1.12, 1.1, 1.1, 1.08, 1.06, 1.04, 1.02 ]

x = range(0,len(eur))

y_eur = [float(i)/max(eur) for i in eur]
y_usd = [float(i)/max(usd) for i in usd]

plt.figure()
plt.plot(x,y_eur)
plt.plot(x,y_usd)

plt.ylabel("Purchasing power")
plt.xlabel("Year")
plt.legend(['eur','usd'])
plt.show()
```

![purchasing power](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tvbpuxjuerft8z3oshw5.png)

The trend is similar in both currencies. This program should work with any currency
Looking for FREE existing JS libraries for creating visual web organisational charts.
Published: 2021-06-11 09:00:32

Hello everyone,
I am working on a page for creating on dynamic organisational diagram of the employees in company. It needs to be something like this: https://www.slideegg.com/image/webp/preview/catalog/45487-organization%20chart%20ppt%20template%20download.webp
It needs also to be dynamic (if new employee starts, to be added on relevant position, if (s)he quit or be moved to other department, to reflect on the diagram). 
Please suggest some JS library with its pros and cons.
Thank you.
2D Vector in C++
Tags: cpp
Published: 2021-06-11 08:59:46

We can define 2D Vector as `Vector of Vector` followed by N number of rows where each of the row is individual a vector. in other words 2D vector is almost similar to a `array of vectors` but the difference is only in the dynamic properties.
##Syntex
`vector <vector<data_type>> vector_name;`
* `vector <vector<int>> vct`

___
## Initializition
![initialization of vector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/juta8itp5szdmyn4nm4v.png)
Here `vec` is the vector of vectors. where outer vector `vec` represent row as 2D matrix and every sub vectors represent column elements of particular row vector.

![limit vector initialization ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rcexv3yxkhb87pvz926t.png)
* N = Number of rows
* M - Number of columns
Here 2D vector contains `N` number sub vectors(row) and every sub vector has `M` number of elements vale of `0`
``` c++
// output of previous initialization 
{ 
  0 0 0 0 
  0 0 0 0
  0 0 0 0 
}
```
## Iteration on 2D vector

![Iteration on 2D vector on 2D vector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62xuspd1427zfq1kf7g6.png)
* `vect.begin()` – It returns an iterator to the first vector in a 2-D vector.
* `vect.end()` – It returns an iterator to the end of the 2-D vector.
* `vect.size()`– It returns number of elements in vector
![push and pop in vector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtma9p7w1e2el0t4qici.png)
* `v.push_back` – Add vector to the empty 2-D vector 
* `v.pop_back()` – Remove the last vector from a 2-D vector
The Satoshi Mindset | Bitcoin, a stoic response to a financial problem
Published: 2021-06-11 08:32:01

Satoshi Nakamoto is a symbol of hope.Not because the pseudonymous creator ofBitcoin birthed a brand new currency, a payment system, or even that he solved an ages old computer science problem, no it’s much deeper than that.

On January 03 2009, block 0 of a new distributed system was mined. Contained within, was a message, “The Times,03/Jan/2009, Chancellor on brink of second bailout for banks”, revealing some of the thinking behind its genesis.

Taking into account that this was in the midst of the financial crisis, and combining that with later writings, we can infer that Satoshi wasn’t happy with the economic system he found himself in.

What’s interesting though, is that instead of complaining,grumbling, whining, lobbying politicians, voting,protesting, occupying wall street, or any of that — ALL which I might add, never achieved any of their desired outcomes — he dared to create an alternative, and asked permission from no-one.He saw the problems of the world and what he could do about them without crying out or bawling out to anyone.

continued - https://vocal.media/theChain/the-satoshi-mindset
FAANG is dead 💀, FANMAG was a great idea 💡, but FANIMAGNET has to be how we describe big tech 🤣
Tags: discuss, webdev, watercooler, jokes
Published: 2021-06-11 07:53:13

If you haven't seen it there is a fun and interesting article by @endingwithali on how FAANG came to be and a better suggestion of FANMAG to describe big tech.

Go give it a read then come back here (their article is actually well written and informative...unlike this one)!

{% post https://dev.to/endingwithali/faang-is-over-it-s-a-fanmag-world-now-2j55 %}

Now if you can't tell this post is purely satire! Oh and if you don't quite get it there is a [section at the end explaining as it is a UK slang term.](#explanation)

## What is FANIMAGNET
FANIMAGNET is used to describe big tech. It stands for:

**F**acebook 
**A**mazon 
**N**etflix 
**I**ntel 
**M**icrosoft 
**A**pple 
**G**oogle 
**N**vidia 
**E**bay 
**T**oshiba

## Why should we use FANIMAGNET to describe big tech?
I mean:-
- you either want to be a FANIMAGNET or you are attracted to someone who identifies as a FANIMAGNET.
- It is far easier to remember 

Those are the reasons I can think of, aren't they good enough?

## How can I use FANIMAGNET in day to day conversations?
It's easy:

> "Look at Becca, they really get drawn to FANIMAGNETs" - used to describe someone who worships big tech!

> "John really wants to be part of the FANIMAGNET elite, but it isn't so easy to be accepted" - used to highlight the difficulty of getting into big tech


<a name="explanation"></a>
## I don't get the joke?
"Fanny" in the UK means vagina not bottom as in the USA. 

"Fanny magnet" is a term to describe a man or woman who attracts attention as they are extremely attractive / alluring / confident and people always seem to want to sleep with them. 

It also works for gay men as we then adopt the American meaning of Fanny, so it is an inclusive term too 😋

## Conclusion
Really? A conclusion...I suppose the conclusion is I said I wouldn't clutter your feed with sh*tposts but I am just too immature to let this pass.

I promise this will be the last useless post I write for a while, other than the "abusing the internet" series of course! In case you missed the latest instalment of that series here it is:

{% post https://dev.to/inhuofficial/i-built-a-3-page-interactive-spa-with-a-single-image-element-and-no-css-extreme-ssr-4knk %}

Oh and please, do not give this post any hearts or anything, it isn't something I want to see on "top posts of the week" 🤣

Have a great weekend everybody!
HackOnLisk | $33,000 in prizes 💰
Tags: javascript, hackathon, programming, dapps
Published: 2021-06-11 07:52:23


🛠️ Build your own blockchain application with the Lisk SDK in JavaScript. 

Blockchain applications can include industries such as DeFi, DAOs, Oracles, NFT Marketplace, Lending, etc.

💻 https://hackonlisk.devpost.com/

🧰 www.lisk.chat 

Over 200+ participants.
Why Web Developers Should Learn Digital Marketing
Tags: webdev, html
Published: 2021-06-11 07:35:37

Web Development is a competitive industry, with many talented individuals vying for the top spot. If you are looking to rise above your competitors and get better opportunities in this field, then you should consider learning digital marketing. Digital Marketing is not only about design skills anymore - it is an essential skill for web developers who want to be successful in their career!

Let's have a look at the advantages of learning digital marketing for web developers.

**1. The web developer is the one who builds and maintains a company's website, but they are not always in charge of marketing for the company.**

Marketing is getting more and more complex, with new tools coming out all the time to help you optimize your website for search engines or advertising campaigns.

Digital marketing skills are extremely important to a web developer because they can't be successful without them! If you know how SEO works, then it will be much easier for you when working on a company's website.

It will also help you understand the importance of analytics, and how to track your conversion rates with Google Analytics or similar tools.

When it comes to digital marketing skills for web developers, there are plenty! Web developers will need to learn about social media marketing, content marketing, and much more.

A web developer should also be trained in how to use Google AdWords because it is the best way of advertising for a business on the internet!

They'll have a better understanding of why you would want to do this instead of other options like Facebook ads or LinkedIn ads.

[Read Full Post Here](https://codewithghazi.com/why-web-developers-should-learn-digital-marketing/)