teleren/devto huggingface dataset:
Getting Started with a 5 pin relay by controlling 2 LEDs
Tags: relays, iot, leds
Published: 2021-02-20 10:12:30

A relay is an electromagnetic switch which allows low powered devices to control highly powered circuits. There are various types of relays, but in this post, I will be focusing on a 5 pin relay. 

This post is meant to help you understand how the 5 pin relay works. I am going to show you step by step procedure of using a relay to blink two leds. 
One of the leds will be connected to the normally open terminal and the other to the normally closed terminal. We will give the relay a delay of 3000 microseconds to switch between the terminals. 

REQUIREMENTS:
→ 2 leds (preferably of different colors)
→ 1 5v 5 pin relay 
→ 1 pnp transistor (2N2222)
→ Arduino Uno (or any other of your choice)
→ 1 1N4007 diode
→ 1 1k resistor
→ 2 300ohm resistors
→ Breadboard and several jumper wires for connection

POINTS TO NOTE:
* The 1N4007 diode is connected across the electromagnetic coil of the relay and is used to prevent the fallback of high voltages when power supply is disconnected

* The transistor (2N2222) amplifies the current to drive the relay


CONNECTING THE CIRCUIT

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


CODE:


int relay = 8;
void setup() {
 Serial.begin(9600);
 pinMode(relay, OUTPUT);
}
void loop() {
  digitalWrite(relay, HIGH);
  Serial.println("relay pin closed; blue should be on");
  delay(3000);
  digitalWrite(relay, LOW);
  Serial.println("relay pin open; red should be on");
  delay(3000);
}
5 useful javascript tricks for begginers.
Tags: javascript, webdev, codenewbie, tutorial
Published: 2021-02-20 10:10:41

<p>In this post, I will show you 5 awesome javascript tricks which will make your life more easier. And will help you to become a better developer. So if you are interested, continue reading.</p>

<h1>Trick-1: Remove duplicates from an Array!</h1>
<p>This trick is pretty simple. Suppose I have an array which is containing number, strings and booleans. And in this array I want to make sure, that there's no duplicate item. So how do you do do that?</p>
```javascript
const array = [1, 2, 3, 2, 1, true, true, false, 'Ratul', 1, 5];
const filtered__array = [...new Set(array)];
console.log(filtered__array) // [ 1, 2, 3, true, false, 'Ratul', 5 ]
```
<p>Simple!</p>
<br />

<h1>Trick-2: Turn a Decimal Number to a integer.</h1>
<p>This one is a pretty straight forward trick. Let me show you.</p>
```javascript
const number = 23.6565
console.log(number | 0);
```
<p>Isn't it so simple!</p>
<br />

<h1>Trick-3: Getting the Last Value of an Array!</h1>
<p>Suppose you have an array of something. Now if you want to have the last item of the array, how will you do that?</p>
```javascript
const array = [1, 2, 3, 4, 5]
const last_Item = array.slice(-1)
console.log(last_Item)

```
<p>Here we go! Now if you put -2 instead of -1, you will get the last two values of the array and then if you give -3 instead of -2, you will get the value of last three index's and so on.</p>
<br />

<h1>Trick-4: Get a random index value from an array.</h1>
<p>Suppose we are doing a lottery programme. We have an array which is containing the names of the prticipants. Now we want only one user randomly from the array to decide a winner.</p>
```javascript
const participants = ['Ratul', 'George', 'july', 'Padrik', 'G']
const winner = participants[Math.floor(Math.random() * participants.length)]
console.log(winner) // july was the winner 😊
```
<br />

<h1>Trick-5: Detect the most lengthy word in an array</h1>
<p>Create an array and add some different strings. Now print the most lengthy string of this array.</p>
```javascript
const array = ['Apple', 'Pine-apple', 'Banana', 'Jack-fruit']

let most_lengthy_string = ''
array.forEach((item) => {
  if (item.length > most_lengthy_string.length) {
    most_lengthy_string = item
  }
})
console.log(most_lengthy_string)
```
<p>Simple! So let me explain you what's going on here. Firstly we have array which is containing some strings. And After that, I have created a variable which is containing an empty string. And now, to detect the most lengthy string in this array, I need to take a look at all of the array items So I have looped through the array. And if the array's item length is greater that the length of our "most_lengthy_string" The we are reassigning the value of the variable and after all I am just printing out the variable. That's all!</p>
<br />

<h3>Conclusion</h3>
<p>Thanks for reading this article. Hope you enjoyed that. If you have any doubt regarding that post, please let me know. And make sure you follow me to recieve all the informational posts just like that.</p>
<h1>:)</h1>
Using Svelte-Notion & Code Blocks
Tags: svelte, notion, codeblocks
Published: 2021-02-20 09:53:32

I use [svelte-notion](https://github.com/leveluptuts/svelte-notion) to dynamic add learning pieces to my [personal site](https://r-bt.com/learning) a Notion table. It's a really nice experience and uses [Splitbee's Notion-API-Worker](https://github.com/leveluptuts/svelte-notion). However I had some difficulty getting code-highlighting to work.

`svelte-notion` uses [PrismJS](https://prismjs.com/) to do the highlighting. This package takes a string of code and then formats it by wrapping the code in different elements with different classes. Of course, to get them styled you have to import a style-sheet from `PrismJS`, I like **Okaidia**.

Sapper has built-in support for importing css files so it's as simple as:
```javascript 
import "prismjs/themes/prism-okaidia.css";
```

Unfortunately this didn't work properly as `svelte-notion ` doesn't wrap the code in a `pre` and `code` tag as PrismJS requires: https://prismjs.com/#basic-usage . I've submitted a [pull-request](https://github.com/leveluptuts/svelte-notion/pull/4) but I'm not sure if the package is still maintained so have forked it [here](https://github.com/r-bt/notion-in-svelte)
Pi - An Upcoming Cryptocurrency
Tags: cryptocurrency, intro
Published: 2021-02-20 09:47:51

#Cryptocurrency :-
(Noun) 
A digital currency in which transactions are verified and records maintained by a decentralized system using cryptography, rather than by a centralized authority.

#Decentralized :-
(Adjective) 
(Of an activity or organization) controlled by several local offices or authorities rather than one single one.


##What is Pi ?
Pi is a project cryptocurrency which unlike Bitcoins and Ethereum , can be mined on your phone by downloading the Pi network app directly from the [Play Store](https://play.google.com/store/apps/details?id=com.blockchainvault&hl=en_IN&gl=US) and [App Store](https://apps.apple.com/us/app/pi-network/id1445472541) . It is still in it's developing stages but is increasing in popularity and users ( Current User Count : 13 million) .

#Who created Pi ?
The Pi Network is developed by Stanford Phd Graduates: anthropologist Chengdiao Fan, computer scientists Nicolas Kokkalis and Aurélien Schiltz, and business major Vince McPhilip as a project mobile cryptocurrency 

##How to mine Pi ?
Pi is currently invite only app ie , you can only be a part of the network if someone invites you to his/her network . Follow the steps to begin mining Pi :-
1) Download the app from either the App Store or play store .
2) After Installing the app , It will ask you to enter the invitation code .
3) Now , the app will ask you for basic information as Name and User name .
4) After completing the above steps , you will be lead to a main screen where you will be shown a tutorial on how to use the app .

##Is Pi worth anything ?
As the Pi network is still in its development stages but you can still earn more pi by inviting people to your network but may be worth a lot once it hits the market . So as of now , NO , you cannot earn money from Pi .


For more information of the Pi network , I have linked their [official website](https://minepi.com/jlee444333?gclid=CjwKCAiAg8OBBhA8EiwAlKw3kg00bEpVkxnzgkEk5Q54WHv55-m1lrgRJqrv_Z8gFJ1WH6YBUFiGExoC4eIQAvD_BwE) and a post by [Stanford Daily](https://www.stanforddaily.com/2019/09/16/stanford-grads-develop-cryptocurrency-for-smartphone-users-to-increase-its-accessibility/) as well as a post by their Ambassador  [Michael Gehlert] (https://www.linkedin.com/pulse/what-pi-network-faq-ξ-michael-gehlert-/?trk=public_post_promoted-post)

I hope I have sparked interest in some of you , the project appears to be promising with a bit of public uneasiness but we shall see the result hopefully in the near future  .
Firebase emulators:start – getaddrinfo ENOTFOUND localhost localhost:4400
Tags: firebase, emulators
Published: 2021-02-20 09:45:00

For some reason today `firebase start:emulators` broke on me. In the morning it worked fine but when I returned after lunch I just got

```bash
An unexpected error has occurred.
```

I tried restarting my laptop, rolling back `firestore.rules` changes and updating `firebase-tools` but nothing worked. The `firebase-debug.log` had some errors talking about not being able to find localhost

```bash
port check error: Error: getaddrinfo ENOTFOUND localhost localhost:4400
```

However, googling this query returned nothing for the first 30 mins. However, googling this query returned nothing. After an hour of experimenting I found the solution. Add the following to your `/etc/hosts` file:

```bash
127.0.0.1 localhost
```

Well that was an hour wasted. I still don't know how `localhost` got disassociated with `127.0.0.1`.
Stack Data Structure
Tags: stack, javascript
Published: 2021-02-20 09:19:43

Stack data structure resembles the real world stacking of things like papers. The item which is last inserted into the stack will come out first, the principle is called Last In First Out(LIFO).
##Implementation 
Firstly we create a class for implementation in javascript and then creating three data members top, capacity and an empty array of five undefined items.
```
class Stack{
      constructor(){
          this.top = 0;
          this.items = new Array(5);
          this.capacity = 5;
      }
}
```
##Functions
The Stack should contain functions for adding an item at the top(push), removing an element from top(pop), check if the stack is empty, check if the stack is full and get the top element of the stack(peek)
```
  isEmpty() {
    if (this.top === 0) return true;
    else return false;
  }
  isFull() {
    if (this.top === this.capacity) return true;
    else return false;
  }
  push(item) {
    if (this.isFull() === true) {
      console.log("Stack Overflow");
    } else {
      this.items[this.top] = item;
      this.top += 1;
    }
  }
  pop() {
    if (this.isEmpty() === true) {
      return "Stack Underflow";
    } else {
      let item = this.items[this.top - 1];
      delete this.items[this.top - 1];
      this.top -= 1;
      return item;
    }
  }
  peek() {
    return this.items[this.top - 1];
  }
```
##Why we need Stack?
Pushing the element and popping out the element in the stack takes place in a constant time O(1). One of the real time example of stack is browser history, when you click back the site you visited last appears.

Follow me for awesome content on coding.
<Fragment> vs <></>
Tags: javascript, react, programming
Published: 2021-02-20 09:16:17

#Introduction
Hey Guys 👋, hope you're having a great weekend. Today, I'm going to speak about the pros and cons of <React.Fragment> and <>. I'll also compare them and give you my opinion on what should be used.

#What is a Fragment
In jsx, we are not allowed to return more than 1 child element. For example - 

Allowed - 
```
function myDemo() {
   return <p>Demo</p>
}
```

Not allowed
```
function myDemo() {
   return (
      <p>Demo</p>
      <p>Bad code</p>
   )
}
```

So, what used to happen was that developers used to put in a div surrounding the adjacent elements - 

```
function myDemo() {
   return (
      <div>
          <p>Demo</p>
          <p>Bad code</p>
      </div>
   )
}
```

This approach of adding a div added an extra element into the DOM and sometime messed up the styling. So, there was a feature in react called `React.Fragment`. It was used like this -

```
function myDemo() {
   return (
      <React.Fragment>
          <p>Demo</p>
          <p>Bad code</p>
      </React.Fragment>
   )
}
```

`React.Fragment` acted as a parent element for the adjacent JSX elements however it was not added into the DOM. 

In react 16.2, `<></>` was introduced.`<></>` is basically an empty JSX element that does the same functionality


#The Comparison
According to me, `React.Fragment` is much clearer and it's obvious that it acts as a fragment. On the other hand, `<></>` may seem like a bug to beginners who are not aware of React.Fragment

That's all for now, hope you guys liked the post. Share your views in the comments.
Book: Understanding the Four Rules of Simple Design by Corey Haines
Tags: oop, review, books, architecture
Published: 2021-02-20 09:01:25

It describes handy techniques to create a testable and flexible software system. Honestly, it changed the way I write in an object-oriented style. `Ruby` is used for demonstration purpose. 

## For beginners: 
It is an excellent guide for people who just started to learn object-oriented programming, but some of the highlighted problems might be unfamiliar. 

## For experienced:
It is a fantastic resource to update your object-oriented programming. It worth to read the short book at least to make sure that you do everything right.

[Understanding the Four Rules of Simple Design](https://www.goodreads.com/book/show/21841698-understanding-the-four-rules-of-simple-design)
Vim .. best code editor ?
Tags: vim, javascript, python, programming
Published: 2021-02-20 08:58:35

Vim, a text editor for writing code where you navigate around the screen with your keyboard instead of a mouse.
It's based on the original Unix text editor VI which was created by Bill Joy in 1976, 

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


then VI improved or VIM followed it in 1991; but why would you ever want to use a keyboard-based text editor in 2021 if you have a lot of easy to use mouse-based IDEs ?

When you write code everyday, your fingers should be glued to the keyboard at all times, every time you touch your mouse, your  productivity declines; and learning to code with VIM is like learning to play an instrument, it will be painful at first but that pain will lead to more precise and productive code editing in the future.

VIM runs in the terminal and it's installed on almost every machine, and at some point you'll likely find yourself accidently dropped into VIM with no way to escape - which is a joke I always heard in my classes , if you want to mess with someone who doesn't know VIM, let them enter nonsense/crap in VIM editor on their machine, but they don't know how unpredictable it is to escape the main page - in other words, shut down VIM.

If you find yourself there you can quit VIM by typing :q that will close and modify the file, or if it has been modified and saved, you can use :q! to discard any other changes, or :wq to save and quit VIM peacefully.

 You can open a file in VIM like so :

terminal > vim bek.py

You can toggle between different modes 
Normal mode, where you can navigate with your H J K L keys

H -> Left
J -> Up
K -> Down
L -> Right

You have INSERT mode, you can access it by hitting i for insert, logical right?
You have COMMMAND mode, and for that to happen you can hit on :
And VISUAL mode by hitting v 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1za92be38tqkwf422hgc.PNG)

If there is a character you want to delete, you can hit (x) [ Delete Character ]
Or, double (d) to quickly delete an entire line.
To undo it, hit (u) to Undo it. 
To add line number, got to command mode by hitting semicolon : then type set number, and now you can navigate any line with :(number), so to got to line 5 -> :5 and so on.

While navigating the document, if you want to modify something, you can hit (i) for insert mode , modify what you want then hit (Esc) button to exit to normal mode.

If you want to copy and paste code, you can paste from system clipboard using (+p). 
To save the changes, you can hit (:w) to save it, then run the program directly using (:!) followed by the command we want to run, in this example it will be:
terminal > :! python bek.py 

Credit: Fireship - VIM in 100 seconds
I'm creating Lets Code videos! [feedback wanted]
Published: 2021-02-20 08:52:46

I came to this: I will create content for programmers (that's you!)

I want to do relevant content for those who either want to learn software development from scratch or improve their skills. I've been in the programming field for 10+ years and it's already time to share some knowledge.

Here is something I've been working on:

{% youtube 1B6iq3blBMI %}

Next video on that series goes online later today 💪

👉 Would **very much** like to hear your feedback!

My content focus on technologies I know very well and have been working with in the last few years: Ruby and Javascript for programming languages, a backend-ish full-stack career and devops.

Let me know what you think!
Welcome to Draftbox
Tags: gettingstarted
Published: 2021-02-20 08:46:53

We are excited to have you on-board. To give you a glimpse of what Draftbox is, we have populated it with sample posts.

## A short story

We are building Draftbox on the promise of bringing JAMstack to content creators. We are very bullish on results when content creators can fully utilize JAMstack, and we want to empower them. Draftbox is a **no-code JAMstack** blogging platform that provides performance, user experience, SEO, security, and scalability without breaking a sweat.

## Under the hood

Draftbox sites are created using [Gatsby](https://www.gatsbyjs.com/). Gatsby is a framework for building blazing-fast apps and websites. Gatsby has a flourishing ecosystem, strong community, and is being used by companies like Nike, Tinder, and AirBnB.

Draftbox sites are deployed to [Netlify ](https://www.netlify.com/)Edge. Netlify is a market leader in hosting services for static sites. Netlify has been at the forefront of the JAMstack revolution and loved by thousands of developers worldwide.

## Next up — Draftbox Editor

As a content creator, you would be excited to learn what kind of content blocks you can add using [editor](/powerful-editor-built-for-pro-content-creators/).

BTW, you can delete these sample posts from dashboard.
PANCAKE SORTING
Tags: computerscience, algorithms, datastructures
Published: 2021-02-20 08:40:19

Pancake sort is a sorting algorithm in which the only allowed operation is to "flip" one end of the list. It is **inplace** but not **stable**.

Just like the name, it means the same as sorting pancakes on a plate with a spatula, where you can only flip some of the top pancakes in the plate using spatula. 

Given an unsorted array, sort the given array. You are allowed to do only following operation on array:
``` python
flip(arr, n): Reverse array from 0 to n
```
*Our aim is to sort the sequence in as few reversals as possible i.e. shortest ways possible.*

<h2>Explanation</h2>
The idea is to do something similar to Selection Sort. We one by one place maximum element at the end and reduce the size of current array by one. 

Let given array be arr[] and size of array be i. 

Start from current size equal to n and reduce current size by one while it’s greater than 1. Let the current size be current_size. Do the following for every current_size 

▪︎ Find index of the maximum element in arr[0..current_size-1]. Let the index be ‘mid’
▪︎Call flip(arr, mid)
▪︎Call flip(arr, current_size-1)

```python
# program to sort array using pancake sort
# Reverses arr[0..n] */

def flip(arr, n):
    start = 0
    while start < n:
        temp = arr[start]
        arr[start] = arr[n]
        arr[n] = temp
        start += 1
        n -= 1

# to return index of the maximum

def findMax(arr, i):
    mid = 0
    for i in range(0,i):
        if arr[n] > arr[mid]:
            mid = i
    return mid
#Main function
def pancakeSort(arr, i):
# Starting from the main array

    current_size = i
    while current_size > 1:
# Find index of the maximum element

        mid = findMax(arr, current_size)

#then current size is reduced one by one
# maximum element is moved to the end

        if mid != current_size-1:
# To move at the end, we first move maximum number to the beginning

            flip(arr, mid)
#now we reverse the array and maximum element is moved to the end

            flip(arr, current_size-1)
        current_size -= 1
# Function to print an array of size i

def printArray(arr, i):
    for i in range(0,i):
        print ("%d"%( arr[n]),end=" ")

# Driver program 
arr = [8,6,3,2,5,9,1,4,7,10]
i = len(arr)
pancakeSort(arr, i);
print ("The Sorted Array is")
printArray(arr,i)

```

> Output: 
The Sorted Array is: 1 2 3 4 5 6 7 8 9 10

Time Complexity: **O(nlogn)**

<h2>Applications</h2>
1. Pancake sorting appears in applications in parallel processor networks, it provides an effective routing algorithm between processors.

2. It is used when the only allowed operation to sort a sequence is reversing.
PHP8 constructor type test experiment
Published: 2021-02-20 07:57:09

PHP8 simplify constructor method from 
```
//php7 version
class Point {
  public float $x;
  public float $y;
  public float $z;

  public function __construct(
    float $x = 0.0,
    float $y = 0.0,
    float $z = 0.0
  ) {
    $this->x = $x;
    $this->y = $y;
    $this->z = $z;
  }
}
```
to
```
class Point {
  public function __construct(
    public float $x = 0.0,
    public float $y = 0.0,
    public float $z = 0.0,
  ) {}
}
```

write a simple case
```
<?php    
    class Point {
        public function __construct(
          public string $name
        ) {}

        public function returnVal(){
            return $this->name;
        }
    }

    $testClass = new Point('the string case');
    print $testClass->returnVal();
?>
```
The output
```
the string case
```

>check array in string test

turn `'the string case'` to `['the string case']` 
The output
```
PHP Fatal error:  Uncaught TypeError: Point::__construct(): Argument #1 ($name) must be of type string, array given
```
works well

>check number in string test

turn `'the string case'` to `123` 

The output
```
123
```
There's no type error warning. 
add `declare(strict_types=1);` to the top of code
The output
```
PHP Fatal error:  Uncaught TypeError: Point::__construct(): Argument #1 ($name) must be of type string, int given
```
Rate my resume out of 10.
Tags: help, resume, showdev, webdev
Published: 2021-02-20 07:45:10

Hi, I am sick of googling "online resume builder". So I decided to make it from scratch. I ended up with some basic resume which looks same and exact to others. I wanted something unique.
I recently learned figma almost 2 months ago to speed up my web development projects. So i also decided to use it for making resume. 
It's my first try on making resume. I want the help of dev.to community to rate this design so i can know what can be improved in this.

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

Also if you want the same design for yourself for free, plz tell me in the comments.
For those who are wondering why would I do it for free, you just need to follow me here on dev.to :)
Thank you