teleren/devto huggingface dataset:
Don't use async await with forEach in javascript
Published: 2022-05-26 18:58:46

If you are using async await in loop, then please use for...of or for(...;....;...) instead of forEach.

Because, Array.prototype.forEach can not be used in async code or has not been designed for this. I did not know this before I faced weird behaviour of forEach loop in async code.

Let's have a look with an example code:

```javascript
const fruits=["mango","apple","banana","grape"];

fruits.forEach(async(fruit)=>{
  console.log(await Promise.resolve("I am first promise"));
  console.log(await Promise.resolve("I am second promise"));
});
```
 
So, in the above code snippet we are looping through the fruits and and trying to resolving two promises one by one with await keyword to run them one by one.

We are actually expecting the result as follows :

```
"I am first promise"
"I am second promise"
"I am first promise"
"I am second promise"
"I am first promise"
"I am second promise"
"I am first promise"
"I am second promise"
```

But, We are actually getting the result as follows:

```
"I am first promise"
"I am first promise"
"I am first promise"
"I am first promise"
"I am second promise"
"I am second promise"
"I am second promise"
"I am second promise"
```
This happens because forEach does not wait for each promise to resolve. 

Reasons behind such problem:
(a) forEach is not designed keeping async await in mind
(b) forEach accepts a callback function that does not return any promise 

N.B. We can use map, reduce, flatMap and reduceRight with async await  but not forEach and filter as well
Introduction to Consumer Driven Contract Tests
Tags: cdc, eventdriven, microservices
Published: 2022-05-26 18:49:19



## CDCs short for Consumer Driven Contract Tests. 

They involve writing test cases for other systems. These systems are the ones that we communicate with. Since their is a contract involved during event driven communication, it is highly imperative to ensure that this contract stays as it is even during feature developments, refactoring or any kind of code development on the other system.

### Why we need CDCs

Lets say we our System A and we consume messages from System B using a contract. Since our functionality depends on System A.

We need to ensure that if System B unintentionally changes their code and the contract is affected, they KNOW that System A will fail since it will no longer be able to consume the messages/ event as the contract has been changed. 

An effective way to ensure this is to write CDC or tests on our project that will be provided to System B to run. If during development of System B, they change this contract, and try to build it, the CDC by System A will fail and System B will know to rollback changes or to inform System A to take care of that change on our side. Hence, CDC helps to maintain proper communication between multiple Systems ensuring contract changes are properly communicated and maintained.

#### How to implement?

We write CDCs in our code base as simple as a JAVA Unit Test. These are then be wrapped into a docker image to be easily shared. This docker image can be shared via docker registry. The other System is informed that they have to run this CDC as we are using their contract. 

Hence, they on their side, in their build pipeline, pull this docker image from registry and run it. If it runs successfully we know the contract is alive, if not, they need to inform us to incorporate the change.

If multiple Systems our consuming our contract, and we want to change it, we know whom to communicate the change to.
Some AWS Networking concepts
Tags: aws, vpc, cloud
Published: 2022-05-26 18:44:01

1. VPC is like a container for holding multiple resources together bound by a private CIDR. Can be cross AZs.

2. Subnet is sub-part of VPC for isolationg reources within VPC, like EC2 instance or DB.

3. VPC can have one CIDR, and each of its subnet use a part of it and all should be non overlapping.

4. VPC has security groups as firewall (which require config only for one way traffic, reply traffic is already configured) and route tables to connect to NAT, IG, or other VPC or even intra-traffic. Security Grp rules evaluated ascending first.

5. Subnet has its own route table, which inherits from VPC (basic one) if not specified, it has to have at-least intra-traffic by default. Subnet also have Network Access Control List as its own firewall where you have to configure for reply traffic as well unline VPC's security group. NACL rules are evaluated from ascending. Hence always add local traffic as first.

7. NAT- Network Address Translation, used when connecting VPC to outside world. It converts the internal IP address to public IP address.

8. Elastic IP- when we reboot an instance the public IP changes, hence we use Elastic IP to configure it to a static IP address.

9. IG- internet gateway to allow access to Internet. Has to configure same in route tables.

10. VPC peering- create a connection for connecting VPC -to-VPC.

11. NAT instance- a ec2 instance which is in public subnet and connected to a private subnet as well as NAT gateway for allowing private subnet to access outside world. We use similar setup for bastion host, or jump host to connect to private subnet DB.

RPC 1918 specification recommends us to use 10.0.0.0 or 172.168.0.0 similar CIDR for local CIDR when attaching to VPC.
A Simple Overview of JavaScript Object Destructuring
Tags: javascript, flatiron, beginners, tutorial
Published: 2022-05-26 18:42:42

As I have just finished my first phase of study with Flatiron School, it occurred to me that I should display a portion of what I learned for others to benefit from. 

For this, I have chosen **object destructuring**. 

**Summary:** Here we'll explore some JavaScript object destructuring methods that assign properties of an object to individual variables.

Let's say we have an object containing someone's elemental makeup reading, taken by an oriental philosopher. [Follow this link to learn more.]
(https://www.nationsonline.org/oneworld/Chinese_Customs/five_elements.htm)

`let johnsElementalMakeup = {
  wood: "13%",
  fire: "17%",
  earth: "23%",
  metal: "22%",
  water: "25%"
};`

![Basic Object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmnw0ndit3h5966erstd.png)

The traditional way (before ES6) to assign properties of the johnsElementalMakeup object to variables was the following:

`let wood = elementalMakeup.wood;
let earth = elementalMakeup.earth;`

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

Since ES6, we can now use the following:

`let { wood: wo, fire: f, earth: e, metal: m, water: wa } = johnsElementalMakeup
`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4qlt59g91ks98w4hn0s.png)

Here, the variables of wo, f , e, m , and wa would be assigned to the values of wood, fire, earth, metal and water, respectively. 

The basic syntax for this is:

`let { key1: variable1, key2: variable2 } = object;
`

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

The identifier before the colon (:) is the key/property of the object and the identifier after the colon is the variable.

If the variables should have the same names as the keys of the object, we can simplify as shown:

`let { wood, fire, earth, metal, water } = johnsElementalMakeup
console.log(wood, fire, earth) // "13%", "17%", "23%"`

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

Each of the key names within johnsElementalMakeup are now variable names which are assigned to the respective percentage values. 

Adding in a key name that doesn't exist within the object would result in that variable being assigned "undefined".

For more, including how to destructure nested arrays, I suggest you check out the documentation at MDN: [Here.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
I'm a newbie In Dev.to From Iran 😁
Published: 2022-05-26 18:41:03

hey guys , how you doing?
my name is alireza fazeli. I'm Front-end developer from the beautiful country name is (Iran).
I would be happy if you want connect with me.
my Github : https://github.com/alirezafazeli8
linkedin : https://linkedin.com/in/alirezafazeli
Windows 10: Ubuntu terminal, the lazy way
Tags: opensource, ubuntu, windows, merico
Published: 2022-05-26 18:25:16

Sometimes you need a working Ubuntu terminal in Windows. Old way was to install a Docker, but now it is even simplier.

Basically, in Windows 10 you can install Ubuntu terminal from Microsoft Store
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s12i39xw2hv5lpzspdn2.png)
 

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

Now you can easily build #OSS projects like https://bit.ly/3NxR9Si , even if there are only instructions for Mac and Linux

Isn't that cool, @maximwheatley ?
TechTwitter Boosts:- Rick
Published: 2022-05-26 18:16:55

Hi. My name’s Rick.

I’m an iOS software Developer with an unusual background. I went to prison at 18. I was a senior in high school. I was involved in a street fight and stabbed a man who later died at the hospital. It was a horrible decision by a foolish teenager.

I thought I was protecting my friends, but the truth is, I was simply a fool acting irrationally in the heat of the moment. I wish I could undo that night but I can’t. I haven’t been in trouble since but obviously that fateful decision has shaped my life.

In prison I discovered that I liked programming. It kinda save me by giving me a life and career I probably couldn’t have in many other industries. Since I was hired as a developer, I’ve been teaching others from similar backgrounds in hopes that it does the same for them.

Out of that interest grew a passion project turned non-profit called [Underdog Devs](https://www.underdogdevs.org/) that helps the formerly incarcerated become software engineers. For many getting out, there are obstacles that make reintegration difficult.

With a skill and a potential career, the odds of acclimating back to the society as a productive member are greatly increased. If you are interested in helping us through mentoring/pair programming, financially sponsoring mentees, or some other form of support, reach out. If you are looking for skilled diverse developers, reach out.

We’ve done the vetting and training process for you. These developers are gritty, smart, and overlooked. Web, iOS and Android. There is no placement fee. We do ask that you consider sponsoring the next cohort though.
Amazon S3 Buckets
Tags: aws, cloud, computerscience, programming
Published: 2022-05-26 18:14:54

An Amazon S3 bucket is a scalable, high speed web-based resource available on Amazon Web Services(AWS). S3 stands for Simple Storage Service and it is designed for online backup and archiving data and applications on AWS. It is built to store, protect and retrieve data from “buckets” at any time, from anywhere, on any device. It is just like a file folder and stores objects which consists of data and its descriptive metadata.

## How to use an S3 bucket

An Amazon s3 client initially creates a bucket in the AWS region of his/her choice and gives it a globally unique name. AWS usually advises clients to choose regions with closer proximity in order to reduce latency and costs. After creating the bucket, the user selects a tier of the data, alongside other S3 tiers with different levels of redundancy, prices and accessibility. This means that one S3 bucket can store objects from different S3 storage tiers. After that, the user can specify access privileges for the objects stored in a bucket through AWS IAM(Identity and Access Management) bucket policies and access control lists. A client can interact with an S3 bucket via the AWS Management Console, the AWS Command Line Interface or through APIs.

## S3 bucket features

AWS offers several features for S3 buckets like versioning, set-up server access logs, object-level API logs, tags and encryption and transfer acceleration. 

## S3 bucket limits and pricing

There is no limit to the amount of objects a client can store in a bucket(although buckets cannot exist in others). No matter how many buckets an individual creates, S3 performance remains the same. Each AWS account can create 100 buckets but an unlimited number of objects, and the account that creates a bucket is the admin of that bucket, and administration is not transferable. An S3 customer can delete a bucket but another user can claim that unique name. To request an increase in number of buckets above 100, visit the service Quotas Console.

AWS charges customers for storing objects in a bucket and for the movement of objects in and out of buckets. The pricing varies by region.
Ethernaut系列-Level 13(GatekeeperOne)
Published: 2022-05-26 03:19:27

## LEVEL 13 （GatekeeperOne）:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import '@openzeppelin/contracts/math/SafeMath.sol';

contract GatekeeperOne {

  using SafeMath for uint256;
  address public entrant;

  modifier gateOne() {
    require(msg.sender != tx.origin);
    _;
  }

  modifier gateTwo() {
    require(gasleft().mod(8191) == 0);
    _;
  }

  modifier gateThree(bytes8 _gateKey) {
      require(uint32(uint64(_gateKey)) == uint16(uint64(_gateKey)), "GatekeeperOne: invalid gateThree part one");
      require(uint32(uint64(_gateKey)) != uint64(_gateKey), "GatekeeperOne: invalid gateThree part two");
      require(uint32(uint64(_gateKey)) == uint16(tx.origin), "GatekeeperOne: invalid gateThree part three");
    _;
  }

  function enter(bytes8 _gateKey) public gateOne gateTwo gateThree(_gateKey) returns (bool) {
    entrant = tx.origin;
    return true;
  }
}
```
## 通关要求
  entrant=player

##要点
  1.tx.origin和msg.sender的区别，这个前面有讲
  2.gas费用的设置
https://docs.soliditylang.org/en/v0.8.14/control-structures.html?highlight=gas%3A#external-function-calls
  3.类型转换和位值
https://docs.soliditylang.org/en/v0.8.14/types.html#conversions-between-elementary-types

##解题思路
gateOne:在自己的合约调用其他合约，则tx.origin和msg.sender就会不一样

gateTwo:要先了解下gasleft()和合约是如何消耗gas,如何指定调用的最大gas
可以通过console.log打印出对应合约大体的gasLeft()+ （8191的倍数）即可
这个gasLeft()线上和本地的不一定完全一样，可能是有没开启优化的关系，故可以加个循环gas+1不断尝试

gateThree:
  这个要了解单位转换的截取和补齐，详见代码备注

contracts/13GatekeeperOneRun.sol
```solidity
 function run(address _runAddress) external  {
    //gas = 254+8191; (用console.log打印出gas剩余,本地测算是254，不过线上可能有些许差异可能是有带优化参数,所以可以调小254进行循环测试)
    uint256 gas = 254+81910;
   
    /**
     *  
     *  1.require(uint32(uint64(_gateKey)) == uint16(uint64(_gateKey)), "GatekeeperOne: invalid gateThree part one");
     *  2.require(uint32(uint64(_gateKey)) != uint64(_gateKey), "GatekeeperOne: invalid gateThree part two");
     *  3.require(uint32(uint64(_gateKey)) == uint16(tx.origin), "GatekeeperOne: invalid gateThree part three"); 
     *  gateKey三个条件都满足才能通过
     *  分析：
     *  首先要把address转成对应的uint160,gateKey是byte8对应uint64
     *  根据条件3：tx.origin的0-16跟gateKey的0-16是一样
     *  根据条件1：16-32位要全是0 （不然截取后不会相等）
     *  根据条件2：32-64位不全是0  (不然截取后会相等)
     *  所以uint64(uint16(uint160(tx.origin))，把address转成160后截取成16再转成64位后，自动满足条件1和3，但不满足条件2，故再加上0x1_00_00_00_00即可（把33设为1）
     *       
     */
    bytes8 gateKey = bytes8(uint64(uint16(uint160(tx.origin))+0x100000000)); 
    while (true) {
      (bool result,) = _runAddress.call{gas:gas}(abi.encodeWithSignature("enter(bytes8)", gateKey));
      if (result) {
        break;
      }      
      gas++;
    }
  } 
```
Embedded Methods for Feature Selection
Tags: filtermethod, featureselection, machinelearning, python
Published: 2022-05-26 18:01:11

## L1 Regularized Logistic Regression 

Let's have a brief overview of **Regularization**.

Regularization help us with the problem of overfitting model on the training dataset. Instead of just decreasing the LOSS function we also penalize the model complexity. 

There are different form of Regularizatoin.
1. L1 Regularization.
2. L2 Regularization.

We will be discussing them in detail in the future blogs.

## Using L1 (LASSO) Regularization

This L1 regularization can also be use as one of the method of feature selection.

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

We will discuss the loss function minimising part in some other blog. For this discussion, the interesting part is the **N1 Norm** it plays the main role in feature selection. This **N1 Norm** is the measure of how big the weights are. Here, **m** is the number of features in the dataset whereas |W| is the absolute sum of all the weights. You can think of **Lambda** as the scaling factor it's a hyper parameter which we have to tune when we use it in practice. This **N1 Norm** is the penalty against the LOSS function greater the complexity greater will be the penalty and vice versa.
  
Our final LOSS function is

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tfct8lki2aktfp9sy2a.png)
 
Our goal is to minimize the overall LOSS function but the **N1 NORM** added a large positive number. So, if we want to minimize the loss we also need to minimize this term which can only be possible if we use least weights (less complex model). So, our goal is to find **weights** which are not only good for predictions but also the smallest possible weights to make overall loss function less.

If we have large Lambda term, the trade of b/w minimizing the solution term and the global loss function lies where one of the weights is zero or usually more than one with is zero.

### How can we use it for feature selection?

As we know the greater the weight the more important/value-able is the feature. So, we can remove the features with zero weight or least weights or select the features with the most weights.

Most of this info is derived from this [video](https://www.youtube.com/watch?v=_aGWjt7GKBE&list=PLTKMiZHVd_2KyGirGEvKlniaWeLOHhUF3&index=89).

## Using Decision Trees & Random Forest 

In Logistic Regression, we are using all of the feature unless we are using L1 regularization which zero out some of the features. However, in Decision Tree the features selection is done implicitly. It is done such that a feature is selected which reduces the entropy the most. The goal is get the Entropy to 0. There can other criteria for selection of feature such as Gini or any other impurity in General. Also known as Information Gain.

Decision tree perform feature selection implicitly.
Web3.0 Kickstarter Program
Tags: web3
Published: 2022-05-26 17:55:14

I am happy to share that I just enrolled for 6-Week Web3.0 Kickstarter Program from @growthschoolio 🚀 

Join me & many others to learn about web3 for FREE within 6 weeks.

Here you go! : https://vy.tc/nuH1D85

Top 1000 people will get a 100% scholarship!
Conducted a free webinar on Angular Essentials for Corporate Folks
Tags: javascript, webdev, tutorial, angular
Published: 2022-05-26 17:45:54

## I give a free webinar on Angular Essentials, that covered all basic topics from angular, and by this they learned angular and cleared about these below questions

1. what is Angular?
2. How we can start work on Angular?
3. How is career path in Angular?
4. Jobs in Angular.


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

**In this webinar, folks learned about the following things:**

> What is Angular
> Angular/NodeJS/ VS Code Installation
> What is an API
> What is a package.json
> What is npm
> What is git
> Installing Angular CLI
> Creating the first Angular application
> Modules & Component in Angular 
> Data Binding in Angular
> Directives (like *ngFor, *ngIf) in Angular
> Pipes in Angular
> Basic Routing
> Creating basic service
> API Integration for GET/POST Operations

## All folks learned and enjoyed with totally coding part.


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

If you want to learn with me, please follow me on social accounts and also go through my website

[https://www.ankitkumarsharma.com/](https://www.ankitkumarsharma.com/)

Also please follow me on [GitHub](https://github.com/ankitkumarsharma) , [Twitter](https://twitter.com/ankit_k_sharma) , [Medium](https://medium.com/@ankit_k_sharma), and [Dev](https://dev.to/ankit_k_sharma) for more updates on articles with hands on code queries.

**Thank you**
[How-To] A guide on how to test (new versions of) your .nuget packages locally
Tags: guide, npm, visualstudio, tutorial
Published: 2022-05-26 17:42:48

Last week I had to test a new version of a package. The problem was that the package was released on a nuget feed, but to test it properly I had to first test it in another solution. 

By creating a local Nuget feed on your development machine, and publishing your nuget package to this feed we can very easily test and work with your package.

## Create a local feed##
Create a local folder where you want to store your local nuget packages. For example on your `C:\` drive.
- Create a new folder called `local.nuget`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1uab1jh3ns9ve9qzfwao.png)
 
- Open visual studio and navigate to `Tools > NuGet Package Manager > Settings` 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4oxin4qpe98oxlu2peo7.png)
- Navigate to `Package Sources` and click on the green + button.
- Give it a name and point the directory to your local nuget folder we just created.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v98pqxe86dxd7at6iwfr.png)
- Click `Ok`

##Publish the package to the feed##
Now to create the package and publish it to our custom feed.
- Open the project you want to publish and open the `.csproj` file of the project.
- Change the `<version>` tag to a version which is easily recognizable. (To avoid caching problems you can use something not easily used in production, such as 99.0.0.)

- Right click the project and click `Pack` to publish the nuget package to your `/bin` folder.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/okwj4wvix8wyxm2nv5lc.png)
- Copy the `.nupkg` to your local nuget folder in `C:\local.nuget`.

## Using the package ##
- Open the solution that uses the package
- Open the Package manager for this solution
- Navigate to the Browse tab and change the 'Package source' to `nuget.local`

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

- Use the new version of the package!


### That's all there is to it! ###