teleren/devto huggingface dataset:
How to use NPM (and import/export modules) in JavaScript
Tags: javascript, react, vue, crosspost
Published: 2020-06-14 04:42:46

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1g53dn9dayilsvcdzd3s.jpeg)
If you are familiar with JavaScript or Web Development then you must have heard about npm. NPM helps us to manage packages and dependencies in our projects. So, while learning a JavaScript framework the knowledge of npm would be really useful to learn it in an easier manner.

In this series of articles, we aimed to cover the following topics:

1. [Important ES6 Features](https://medium.com/javascript-in-plain-english/things-to-learn-before-learning-a-javascript-framework-b7baec310247)
2. [Objects and Array methods](https://medium.com/javascript-in-plain-english/object-and-array-methods-to-learn-before-javascript-frameworks-59728dcea306)
3. [Asynchronous JavaScript and Fetch API](https://medium.com/javascript-in-plain-english/asynchronous-javascript-to-learn-before-javascript-frameworks-9b63972290c2)
4. NPM and import/export modules in JavaScript (this article)

Let’s first start with NPM:

#NPM
What is NPM?

NPM is the default package manager for node. It is used to install, share, and manage javascript packages in a project.
NPM has three components:

1. [The website](https://npmjs.com/) (Using the website we can find, share, and view packages)
2. The Command Line Interface (CLI) (The CLI is the component that helps us in managing our packages)
3. The registry (The npm registry is the database where all the packages exist, we can download packages published by other developers and can also publish our own packages to the registry)

###Note:
- NPM can also be used to publish and manage private packages.
- A package is simply a program that performs one or more operations.

###How to Install npm?
NPM comes pre-installed with node.js. So, you don’t need to worry about installing it manually, you just have to install node.js on your system.

To install node.js, visit https://nodejs.org/en/download, and install its LTS (Long Term Support) version.
After installation, use the commands shown below to check if they are installed:

```
// to check nodejs's version
node -v or node --version  
// to check npm's version
npm -v or npm --version
```

This will result in something like this:
<img src="https://i.ibb.co/wsBwVTj/image.png" alt="image.png" />

###package.json
The package.json file is like the manifest of your project. It makes it easier to install and manage packages. It consists of all the metadata of the project that will be useful while sharing the project with other developers.
According to the official docs:

A package.json file:
1. lists the packages your project depends on
2. specifies versions of a package that your project can use using semantic versioning rules
3. makes your build reproducible, and therefore easier to share with other developers

[Read more>>>](https://medium.com/javascript-in-plain-english/how-to-use-npm-and-import-export-modules-in-javascript-31a7f66a2064)
Tests with Jest and TypeORM
Tags: node, typescript, tutorial, testing
Published: 2020-06-14 00:52:14

#### Hello Everyone!
So, today I'll show you how to configure your code to make tests with TypeORM and Jest.

## Modules
First thing first, let's install some modules in our node environment. I'm using yarn:

`yarn add jest ts-jest @types/jest -D`

`yarn add typeorm typescript pg`

Then, let's create our tsconfig file:
`yarn tsc --init`

## Jest configs
Ok, now we need to configure our jest.config.js and there are my conigs: 

```javascript
module.exports = {
  clearMocks: true,
  maxWorkers: 1,
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: [
    '**/__tests__/**/*.[jt]s?(x)',
    '!**/__tests__/coverage/**',
    '!**/__tests__/utils/**',
    '!**/__tests__/images/**',
  ],
};
```
I like to make a directory named __tests__ in the root of the project to make tests.

## TypeORM configs
And I like to create a ormconfig.js. Be comfortable to make a .json or .env.

```javascript
module.exports = {
  name: 'default',
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'postgres',
  database: 'tests',
  dropSchema: true,
  logging: false,
  synchroize: true,
  migrationsRun: true,

  entities: ['src/database/entities/*.ts'],
  migrations: ['src/database/migrations/*.ts'],
  cli: {
    entitiesDir: 'src/database/entities',
    migrationsDir: 'src/database/migrations',
  },
};
```

So, let the `dropSchema: true` because this will delete your data after the tests.

I like to let `migrationsRun: true` to automatically run migrations before the tests.

I'm using postgres, but be comfortable to use your favorite database.

## Creating connection file
Let's create a connection.ts to export some functions to run in our tests.

```javascript
import {createConnection, getConnection} from 'typeorm';

const connection = {
  async create(){
    await createConnection();
  },

  async close(){
    await getConnection().close(); 
  },

  async clear(){
    const connection = getConnection();
    const entities = connection.entityMetadatas;

    entities.forEach(async (entity) => {
      const repository = connection.getRepository(entity.name);
      await repository.query(`DELETE FROM ${entity.tableName}`);
    });
  },
};
export default connection;
```

The clear method will delete all data for every single entity registered in our connection.

## Creating a test
So, in your tests, just put this code: 

```javascript
import connection from '../src/connection';

beforeAll(async ()=>{
  await connection.create();
});

afterAll(async ()=>{
  await connection.close();
});

beforeEach(async () => {
  await connection.clear();
});

it('creates a user', () => {
  // TODO
})
```
And that's it :)

## Github project

If you want to see the full project just click [here](https://github.com/caiulucas/jest-typeorm)
Leetcode - Reverse Integer (with JavaScript)
Tags: javascript
Published: 2020-06-14 04:27:46

Today I am going to show how to solve the Leetcode Reverse Integer algorithm problem.

Here is the problem:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ut5l6pzn9cksae3tlq08.png)

1) I declare the two variables revNum and lastDigit, which represent the reverse and the last digit of giving integer x, respectively. Then, I loop through x and build up the reverse integer one digit at a time.
```javascript
const reverse = function(x){
    let revNum = 0, lastDigit = 0;
}
```
2) The remainder of a number divided by 10 will give us the last digit. 
For example: 123/10 = 12.3 -> the remainder is 3, which is the last digit.
```javascript
const reverse = function(x){
    let revNum = 0, lastDigit = 0;
    while (x!==0) {
        lastDigit = x % 10; 
    }
}
```
3) Then, I remove that digit from the end of x by using parseInt() method.
For example: parseInt(12.3) = 12

```javascript
const reverse = function(x){
    let revNum = 0, lastDigit = 0;
    while (x!==0) {
        lastDigit = x % 10; 
        x = parseInt(x/10);
        revNum = revNum * 10 + lastDigit; // building up the reverse number
   }
}
```
4) In the problem it was noted that we are dealing with an environment which could only store integers within the 32-bit signed integer range. I therefore check beforehand whether or not appending another digit would cause overflow. If it causes overflow, the loop will break and return 0.
```javascript
const reverse = function(x){
    let revNum = 0, lastDigit = 0;
    while (x!==0) {
        lastDigit = x % 10; 
        x = parseInt(x/10); 
        revNum = revNum * 10 + lastDigit;
        if (revNum < Math.pow(-2, 31) || revNum > Math.pow(2, 31) - 1) return 0
    }
    return revNum
}
```
Caching an Inverse of a Matrix Using R
Tags: r, datascience, inverse, matrix
Published: 2020-06-14 02:49:37


Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly.

This is an example code to cache an inverse of a matrix which then called if:

1. The new matrix computation similar to the previous matrix
2. Matrix is invertible — Read Invertible Matrix
3. The structure and content of the new matrix is equal to previous
The program consists of two functions

A function to cache the matrix and the inverse. It is similar to getter and setter in many programming languages like Java and C.
A function which will be call for the computational process of the matrix

###Here are parts of the code:

####Setting the matrix
    invMatrix <- NULL
    
    #define the set function for the matrix
    set <- function(y) {
        x <<- y
        invMatrix <<- NULL
    }

####Setting the inverse matrix
    setInvMatrix <- function(invM){
        invMatrix <<- invM ##assign the inverse matrix to the environment var
    } 
    
    ##define the function for returning the inverse matrix
    getInvMatrix <- function(){
        invMatrix ##the environment var inverse matrix is return
    }

####Verification on the matrix
    if (!is.null(invM)){
        ## check if the return invMatrix is identical
        if ( identical( x$get() %*% invM, invM %*% x$get() ) ){
            ## get it from the cache and skips the computation. 
            print("getting cached data")
            return(invM)
        }
    }

####Setting the new inverse
    data <- x$get()
    invM <- solve(data, ...)
    
    # sets the value of the inverse in the cache via the setinv function.
    x$setInvMatrix(invM)

Complete source code is reachable at [https://github.com/masteramuk/ProgrammingAssignment2](https://github.com/masteramuk/ProgrammingAssignment2)

If you like the post, [https://www.buymeacoffee.com/masteramuk](do buy me a coffee please) :)
What is JavaScript Function?
Tags: javascript, codenewbie, webdev
Published: 2020-06-14 02:34:52

After reading the title you must want to know what is Function and how it is used in javaScript. So let's talk about it.

#1.Functions.
So, Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it. If you want to learn deep about the function click (here).


#2. How to define Functions.
Here you can know that how you can define a function first of all define function is also called a Function declaration, or Function statement. consists of the function keyword, followed by:

1.The name of the function.
2.A list of parameters to the function, enclosed in parentheses and separated by commas.
3.The JavaScript statements that define the function, enclosed in curly brackets, {...}.

For example:-
`function square(number){
return number*number;
};`

This code defines the simple function (square).
The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The statement return specifies the value returned by the function:
I develop first Chrome Extension
Tags: chromeextension
Published: 2020-06-14 02:30:29

---
title: I develop first Chrome Extension
published: true
description: insert review badge for textarea Add a badge to your review comments.
tags: chromeextension
cover_image: https://lh3.googleusercontent.com/7ECAXyydPgJS1ufoNScvyuuQKzEF9vUJsiKPaBgKTzzNU60wOwPgE-5yXoONx1NMFrIslGBHemI=w128-h128-e365
---

I create Crhome Extension for GitHub's reviewing comment.
https://chrome.google.com/webstore/detail/review-badge/kiepclhakcefkflamflnjbfogmfamoal

Please use it.
and Please Check source code
https://github.com/sassy/review-badge-crx
React, NextJS, TypeScript, GraphQL, Type-GraphQL
Published: 2020-06-14 02:30:09

Hello,

I have an e-commerce website template built using React, NextJS, TypeScript, GraphQL, Type-GraphQL.

I wish to setup, configure and set it up on my domain so it's ready for use.
So you're not building, only configuring. how can i do that any help please?
จำลอง Binary Adder Logic จากหนังสือ Code ด้วย Go
Tags: go, code
Published: 2020-06-14 01:30:17

ตอนนี้กำลังอ่านหนังสือที่ชื่อว่า [Code](https://www.amazon.com/Code-Language-Computer-Hardware-Software/dp/0735611319/ref=sr_1_2?dchild=1&keywords=Code&qid=1592097556&sr=8-2) เล่มนี้อยู่

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n7134ntbq85l1fd490ik.jpg)

ถึงบทที่ชื่อว่า A Binary Adding Machine ซึ่งทำให้ดูว่าเราจะสร้าง วงจรบวกเลขผ่าน Logic Gate เช่น XOR, AND และ OR gate ได้ยังไงบ้าง

ซึ่งการบวก ก็จะต้องคำนึงถึงตัวทด (carry) ด้วย สุดท้ายของบทนี้เราก็ได้วงจร FullAdder ที่ input จะมีตัวทดด้วยสำหรับบวกตัวทดของหลักก่อนหน้า 

ส่วนการคำนวนผลบวกของเลข 1 BIT นั้นเราจะใช้ XOR gate และ การคำนวณตัวทดเราจะใช้ AND gate แต่ว่านี่จะทำให้ได้แค่ HalfAdder พอเป็น FullAdder จะใช้ OR gate คำนวณ carry สุดท้ายที่ด้วยด้วยโดยเอา carry ของ A บวก B ไป OR กับ carry ของผลบวกของ A กับ B และ carry input นั่นเอง

สุดท้ายเราก็จะเอา FullAdder มาสร้างวงจรของการบวก 8 BITS ได้

นี่คือโค้ด Go ที่ลองเขียนจำลองตามในหนังสือ

```go
package main

import "fmt"

type BIT byte

const (
	O BIT = iota
	I
)

func (b BIT) String() string {
	if b == O {
		return "🌑"
	} else {
		return "🌕"
	}
}

func FullAdder(cin, a, b BIT) (cout, out BIT) {
	o1 := a ^ b            // a XOR b
	c1 := a & b            // a AND b
	out = cin ^ o1         // cin XOR o1
	cout = c1 | (cin & o1) // c1 OR (cin AND o1)
	return
}

func Add8BIT(
	a7, a6, a5, a4, a3, a2, a1, a0,
	b7, b6, b5, b4, b3, b2, b1, b0 BIT) (c, o7, o6, o5, o4, o3, o2, o1, o0 BIT) {
	c, o0 = FullAdder(c, a0, b0)
	c, o1 = FullAdder(c, a1, b1)
	c, o2 = FullAdder(c, a2, b2)
	c, o3 = FullAdder(c, a3, b3)
	c, o4 = FullAdder(c, a4, b4)
	c, o5 = FullAdder(c, a5, b5)
	c, o6 = FullAdder(c, a6, b6)
	c, o7 = FullAdder(c, a7, b7)
	return
}

func PResult(c, o7, o6, o5, o4, o3, o2, o1, o0 BIT) {
	fmt.Println(c, o7, o6, o5, o4, o3, o2, o1, o0)
}
func main() {
	fmt.Println("A", O, I, I, I, I, I, I, I, O)
	fmt.Println("B", O, O, O, O, O, O, O, O, I)
	fmt.Print("= ")
	PResult(Add8BIT(
		I, I, I, I, I, I, I, O,
		O, O, O, O, O, O, O, I,
	))
}
```

เมื่อลองรันจะได้

```shell
go run main.go
A 🌑 🌕 🌕 🌕 🌕 🌕 🌕 🌕 🌑
B 🌑 🌑 🌑 🌑 🌑 🌑 🌑 🌑 🌕
= 🌑 🌕 🌕 🌕 🌕 🌕 🌕 🌕 🌕
```
How to rename your git branch
Tags: github
Published: 2020-06-14 01:26:37

---
title: How to rename your git branch
published: true
description: rename your master branch to something else!
tags: #github
//cover_image: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2vdbc2xohghtfk0h6ce7.png)
---
Thinking about renaming your default branch for your repo? You can do it 3 easy steps.
git branch -m stem
git push origin :master
git push --set-upstream origin stem

You might encounter an error that looks like this! Not to worry, this means that your default branch is set to master, and you need to change your repo settings.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/cx3n44cgdeigrt1lmak9.png)

Go to your repo, and switch to another branch as your default. Do your thang. Then update your default branch settings to the new branch you have made!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u4bgv43vlexvy2ja96g9.png)

That's it! What did you rename your branch to? Drop a comment below. Like a comment if you renamed your branch to the same thing!
Road to Genius: beginner #12
Tags: beginners, computerscience, javascript
Published: 2020-06-14 00:42:53

Each day I solve several challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, but you will learn a ton of new and interesting things as you go.

![programming challenge](https://dev-to-uploads.s3.amazonaws.com/i/iymyg21owrrf41unka54.png)

Until now there weren't many decent challenges regarding strings. This challenge consists of three lines of code, but does require some attention, especially if you're new to coding and/or javascript.

We need to fix two bugs 💧 and 🐼, both should be strings as required by the challenge. The third line of code goes like this: `R = (A + B)[2]`. It creates a variable `R` whose value is a "complex" string operation. The operation concatenates (combines) the string values of `A` and `B`, from this result it takes the character at index two. The challenge requires `R` to equal `k`, so this means we need to make sure that the 2nd character in the combined string is the character `k`. When we look at the possible options for 💧, we can find only one answer that contains the character `k` at the 2nd index (or 3rd position). This value will ensure that the final condition is met; the value of 🐼 is no longer important so we can choose pretty much anything.

Example:
```JS
let A = 'cuk'
let B = 'pap'
let R = (A+B)[2]    // similar to: R = 'cukpap'[2]
```

![programming challenge answer](https://dev-to-uploads.s3.amazonaws.com/i/k781bgrjq24m730iwm67.png)

---

If you feel inspired and motivated to upgrade your coding + debugging skills, join me on the Road to Genius at https://nevolin.be/codr/
World of WoqlCraft - Ep.11 TerminusDB new Python client updates and new woql.py syntax
Tags: python, database, tutorial, video
Published: 2020-06-14 00:24:34

---
title: World of WoqlCraft - Ep.11 TerminusDB new Python client updates and new woql.py syntax
published: true
description: Today is a short episode that I am giving you a preview of the new Python Client for TerminusDB. It is more pythonic than the last version and let you to have more options in constructing your WOQL objects. Best of all, it works with the most powerful TerminusDB 2.0.
tags: python, database, tutorial, video
---
Today is a short episode that I am giving you a preview of the new Python Client for TerminusDB. It is more pythonic than the last version and let you to have more options in constructing your WOQL objects. Best of all, it works with the most powerful TerminusDB 2.0.

Find the source code from our [tutorial repo](https://github.com/terminusdb/terminus-tutorials).

Join the TerminusDB community at [Discord](https://discord.gg/Gvdqw97)
How to become a Cloud Engineer in 2020
Tags: cloud, career, womenintech
Published: 2020-06-14 00:00:30

# What is a cloud engineer?

Someone who builds, monitor, maintains, and/or architects cloud solutions and infrastructure.

You see the and/or in here and that's because your responsibilities will depend on where you work. Larger companies will have more engineers and you'll be able to work on just building, or architecting, whereas at smaller companies, you might have to work on each piece. It can get overwhelming, but trust me, cloud engineering is a very exciting field to be working in currently.

Okay, let's dive in

**Area 1: Choose a cloud platform to learn**

As a cloud engineer, you will live and breath inside one or multiple cloud platforms. 

**Area 2: Learn DevOps methodology**

DevOps is a set of practices that if you implement, you will shorten your development lifecycle, improve your software quality, and provide continuous delivery of your software. All of this means you to better serve your customers and your time to market is shorter.

**Area 3: Learn a programming language** 

The power of the Cloud really comes into play when you learn how to automate your tasks.

Side note: This isn't really programming but learn some terminal skills, knowing how to use a terminal well will save you time. 

In this video I provide an overview of each area, resources and a few project ideas to get you started!

{% youtube 7i1WMGxyt4Q %}

I plan on creating more content around Cloud Engineering; it's great to share what I've been learning.

If you have any feedback at all, please let me know in the comments below or reach out to me on socials.

Thanks for reading and possibly watching!
Teaching hard concepts in an easy way
Tags: gftwhackathon
Published: 2020-06-13 23:37:51

## What I built

Hello people! Super happy to finally finish my web app project using the monetization API. It is a platform for people who want to learn hard subjects such as databases, biology, politics and several other categories. On the other side, if you know much about a topic, you can write articles and share a little knowledge.

All the articles have a free content, which everyone can see and learn from. But if the author feels like diving deep into the subject, he/she can write a premium content, only available for those who have a monetization provider. The author just have to go to the profile page and insert his/her wallet endpoint. From there, all the articles written will append the endpoint for receiving payments.

This idea came from a sub-reddit called "explain like I'm five", which I think is such a nice way of introducing hard topics for people with zero knowledge but willing to learn. 


### Submission Category: 

Creative Catalyst

## Demo

🤞🤞🤞

https://affectionate-cray-bf90a2.netlify.app/

## Link to Code

`{% client https://github.com/ricardohan93/likeiam5-client %}`

`{% server https://github.com/ricardohan93/likeiam5-api %}`


## How I built it 

The stack I used was:

- Preact
- CSS modules
- NodeJS (Fastify framework)
- Docker

I found the monetization API to be very straightforward and the documentation very clear. Huge thanks for the team working on this new API, is awesome and very simple to use.

I'm not super proud of the code I've written rsrs, but after submitting the project I plan to iterate and improve a lot of things, client and server side =)

On the client side, I used a lot of Preact hooks and even wrote an nice little custom hook for the monetization feature.

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

On the server side, I decided to try the fastify famework and honestly really liked. It's based in a plugin system, and it worked great.

The client was deployed using the netlify infrastructure and the server side code was deployed as a EC2 instance in AWS.


## Additional Resources/Info 

The past few weeks were full of anxiety, anger and desolation. Things in Brazil are not great, with the COVID, politics instability and racial discussions powered by the traumatic events happening in USA. My journey through this hackaton was very unstable either. Sometimes I felt joy and had a great time coding and reading about open standard web. Other times, it felt hard to concentrate and even discouraged to code. But now, I'm happy to deliver this project, even with a few things to improve. The idea of sharing knowledge and explaining hard concepts in a simple manner seems really nice and has a lot of potential for me. 

Hope you like it. Feel free to contact me and stay well 👋