teleren/devto huggingface dataset:
JavaScript basics if...else statement
Tags: javascript
Published: 2021-08-24 07:20:05

I sometimes forget that I write about content in a medium to advanced kind of matter.

In these JavaScript basics series, I'll be looking at some more fundamental topics of JavaScript, so you get a good idea of how to use these methods.

In this article, we'll be looking at using if...else statements in JavaScript.

## A JavaScript if statement

An if statement can be used to execute code only when a specific condition is met.

Let's say we have a variable and want to evaluate whether it's true or false.

```js
let our_var = true;
if(our_var === true) {
	// Execute this code if true
	console.log('Value is true);
}
```

In this case when we are checking boolean values, we don't need to specify the specific value so we can do this:

```js
if(our_var) {
	// Execute this code if true
	console.log('Value is true);
}
```

You can also check if the value is false, like this:

```js
if(!our_var) {
	// Execute this code if false
	console.log('Value is false);
}
```

We can even write this as a one-liner, but most linters will want to see the brackets for neatness.

```js
if (our_var) console.log('Value is true');
```

## JavaScript if...else statement

Often you also want to execute some code if the first condition is not met.
We can achieve this by using the else statement as well.

```js
if (our_var) {
  console.log('Condition is met');
} else {
  console.log('Condition is not met, fallback?');
}
```

And you can even bind another if statement to this else, making it super powerful.

Let's say you want to check multiple conditions after each other.

```js
if (our_var) {
  console.log('first condition met');
} else if (our_second_var) {
  console.log('Second condition was met!');
} else {
  console.log('No condition was met');
}
```

You can make these as big as you want, but often you might want to consider using other solutions for bigger statements.

## JavaScript Ternary Operator

The JavaScript ternary operator is a quick way to express conditions and is often used for shorthand if...else.

The Syntax looks like this:

```js
condition ? truthy : falsy;
```

If we take our example, we could write code like this:

```js
our_var ? console.log('Condition is met') : console.log('Condition not met');
```

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
JavaScript : Create Map to Store Key Value Pair
Tags: javascript
Published: 2021-08-24 06:32:47

JavaScript map
When you want to store data which can be accessed by a key rather than looping over the data like Arrays
Or you wanted to create an alias. For example, you are storing an Array of some object which contains emails but you also wanted to store the name of that user.

Either you add the name attribute to the object or Instead create a map to get the name corresponding to the email. (Map will be helpful when the array of objects have common attribute values)

***Syntax with Examples***

``` javascript
    let myMap = new Map();
```
or
``` javascript
    let myFilledMap = new Map([
    ["key1", "value1"],
    ["key2", "value2"],
    ["key3", "value3"]
    ]);
```

The map is key-value pair like an Object. So to add a value we could do
``` javascript
    myMap.set("redthemers@gmail.com","Red");
```
Here the first parameter is the key & the second is the value to be stored. and to retrieve the data I could use
``` javascript
    myMap.get("redthemers@gmail.com");
```
To check if a value Exists
``` javascript
    myMap.has("redthemers@gmil.com");
```
To Delete a particular value
``` javascript
    myMap.delete("redthemers@gmail.com");
```
To clear everything from a Map we could do
``` javascript
    myMap.clear();
```
Common Map Operations

***map.get(key)
map.set(key,value)
map.has(key)
map.delete(key)
map.clear()***
So InShort Its Similar to an Object & very useful.

***For Practice***

Open your browser console (f12 for chrome) and create a map add some properties. Now try to add a key that had already been added. See What Happens. Also, can we add an Object as a Key in Map?
Taints and Tolerations in Kubernetes
Tags: kubernetes, devops, sre, programming
Published: 2021-08-24 06:42:24

In this blogpost, we'll learn about Taints and Tolerations in Kubernetes.

**Taints**
Taints are the property of nodes , that is used to repel the pods if they don't tolerate this taint.
Taints can be applied on the nodes just like labels.
This means that only those pods that are tolerant to the taints , will be scheduled on that node.

To apply a taint on a node:
```cmd
kubectl taint nodes <node_name> key1=value1:taint_effect
```
places the taint on node.The taint has key=key1,value=value1 and a taint_effect

taint_effect can take 3 different values:
1. **NoSchedule**: If this effect is applied to the node , then the pods that are tolerant to all the taints applied on the node, are only scheduled on this node.
2. **PreferNoSchedule**: In this case, the system will try to avoid placing a pod that does not tolerate the taint on the node, but it is not required.
3. **NoExecute**: In this case, the new pods that do not match the taint are not scheduled on the node and existing pods on the node will also be evicted if they do not tolerate all the taints.

**Tolerations**
Tolerations are applied on the pods,that allow the pods to schedule on the nodes with matching taints.

We apply the toleration for a Pod in PodSpec.
```yaml
tolerations:
    - key: "key1"
      operator: "Equal"
      value: "value1"
      effect: "NoSchedule"
```
By Default the value of operator is *Equal*
A toleration "matches" a taint if the keys are the same and the effects are the same, and:

 - the operator is Exists (in which case no value should be specified), or
 - the operator is Equal and the values are equal.


Let us take an example
Suppose we have two worker nodes node01 and node02
We apply the taints to nodes as follows:
```cmd
kubectl taint nodes node01 key1=value1:NoSchedule
kubectl taint nodes node02 key2=value2:NoExecute
```
And then we apply toleration to a pod as:
```yaml
apiVersion: v1
kind: Pod
metadata:
    name: nginx-pod
spec:
    containers:
       - image: nginx
         name: nginx-container
    tolerations:
        - key: "key1"
          operator: "Equals"
          value: "value1"
          effect: "NoSchedule"
```

In this case the pod will be scheduled on node01 since it has the toleration to its taint. 

Ever wondered why the pods are not scheduled on master(controlplane) nodes?
Because it has a taint `node-role.kubernetes.io/master=true:NoSchedule`
which prevents pods from being scheduled unless otherwise untainted the master node. 
Using Taints and Tolerations , we can create nodes that are reserved(dedicated) for specific pods.


Ref: https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/
Don't overoptimize your React App
Tags: react, javascript, webdev
Published: 2021-08-24 06:04:09

𝗢𝗽𝘁𝗶𝗺𝗶𝘀𝗶𝗻𝗴 𝘆𝗼𝘂𝗿 𝗥𝗲𝗮𝗰𝘁 𝗔𝗽𝗽

Do checkout the video for more details:

https://youtu.be/2woSmgfUjC8

If you have a parent-child component structure then Whenever the parent state changes it will re-render.
Do you know it will even re-render your child? No matter if your child uses any prop or not it will still re-render.

Ideally, Child should re-render only if: parent prop or method used inside the child is changed.

𝗛𝗼𝘄 𝘁𝗼 𝗽𝗿𝗲𝘃𝗲𝗻𝘁 𝘂𝗻𝗻𝗲𝗰𝗲𝘀𝘀𝗮𝗿𝘆 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿𝘀 ?
The solution is "𝗥𝗲𝗮𝗰𝘁.𝗺𝗲𝗺𝗼"

React.memo (is a higher-order component) takes the component and memoizes the rendered output of the wrapped component.

So whenever there is a re-render in the parent, For a child it will compare the props and if all the props are the same it reuses the memoized result skipping the next rendering.

𝗢𝗯𝘀𝗲𝗿𝘃𝗮𝘁𝗶𝗼𝗻:
- Pressing the "click" button, updates the state due to which <App> re-renders
- <Child> is re-rendered every time "Parent" is re-rendered (even it is not using any parent state)
- <MyMemoed> is not re-rendered when "Parent" is re-rendered (As it is using memoised result)

𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗽𝗼𝗶𝗻𝘁𝘀:

1. If you are using function as a prop in your child, it will still re-render even if props are the same in comparison (let's discuss it in the next post)

2. If you are thinking to have every component to use React.memo then it may overkill the performance in some scenarios where it will first compare the props if they are not the same it will still do the re-rendering (extra comparison check)

3. Do check the profiler to actually figure out if it will be worth using it

4. If a child is re-rendering it doesn't mean it is costly unless it is doing the "commit" phase which actually does the real DOM changes.

5. Before preventing re-renders, Do fix your SLOW renders.

Do share your thoughts in the comments
How to extract text from HTML String using javascript
Tags: html, javascript
Published: 2021-08-24 05:59:08

There are various ways to extract text from an html string but we will be doing it using Regex.
First we will store the html string in a variable then apply the replace method and pass and the appropriate regular expression and another parameter for the value to be changed with.

***Example*** :
``` javascript
        let  name = “my name is anzar”
        let  newName = name.replace(“anzar”,”red”);
        console.log(“the new name is ”, newName);   // my name is red
``` 

Here if we see the first parameter is used to find the matching word from the variable . And the second param replaces it with the matched word.

Simple right, but wait what if there are many matching words for anzar

***Example*** :

``` javascript
        let name = “hey anzar how are you anzar”;
        let  newName = name.replace(“anzar”,”red”);
        console.log(“the new name is ”, newName);  
```
    
If we try again on this string the result would be - hey red how are you anzar.
So it will work for the first matching word only. As html have many tags so this won’t work for us.
In Order to get this working we need to add /g at the end of the first parameter. This means global, so now every matching word will be replaced, Instead of only the first word.

Great, now let's do our main task, There are close to 100 html tags like p tag, a tag etc.
So it needed to remove every tag the way above. Just kidding 😜

Regular Expression comes for the rescue. This is one one of the most powerful things you can use in programming but is highly frustrating.
We can’t understand it now but don’t worry i will provide you the expression for removing html.

The regular expression is -

  ``` javascript
      replace(/<[^>]*(>|$)| |‌|»|«|>/g, ' ');
  ```

The second parameter is empty because we just wanted to remove the html This will work great. Just one more stuff remaining.

In html & is represented as ***&amp;*** so if the text in the html contains & there would be chances that it may have ***&amp;*** So to remove this lets again use replace method but this time instead of passing the second parameter as empty string we will pass & because we wanted to preserve the text.

***Example*** :

  
``` javascript         
replace(/&/g,"&");
```
    
Finally we removed everything and just got a plain text. Hope you had understood it completely. Do remember to add ***/g*** at the end of the first parameter to remove every matching instance.
Decode HTTP Query Params into a Struct in Go
Tags: go, http, api
Published: 2021-08-24 05:54:34

Many people use `net/http` package directly in Go to deal with HTTP requests, including reading URL parameters, HTTP headers, and the request body. It's straightforward and efficient, though. We can still get bored writing so much tedious code for just reading and parsing the URL params. Especially when we were maintaining a service with hundres of APIs.

Let's see a piece of code for dealing with HTTP requests by using `net/http` package:

```go
// GET /v1/users?page=1&per_page=20&is_member=true
func ListUsers(rw http.ResponseWriter, r *http.Request) {
	page, err := strconv.ParseInt(r.FormValue("page"), 10, 64)
	if err != nil {
		// Invalid parameter: page.
		return
	}
	perPage, err := strconv.ParseInt(r.FormValue("per_page"), 10, 64)
	if err != nil {
		// Invalid parameter: per_page.
		return
	}
	isMember, err := strconv.ParseBool(r.FormValue("is_member"))
	if err != nil {
		// Invalid parameter: is_member.
		return
	}

	// Read database and return the user list.
}
```

It's okay if there are only a few (usually less than 3) parameters to be parsed. But what if more? Both the number of lots of local variables and the writing of statements of parsing string URL params to target types can kill us. Some "evil" guys even spread these statements all over in an API handler. 🤒

For such cases, what can we do to save a clean and tidy code base?

## Use `ggicci/httpin`

> [**httpin**](https://github.com/ggicci/httpin) - 🍡 HTTP Input for Go - Decode an HTTP request into a custom struct

**ggicci/httpin** is an awesome package which helps you easily decoding HTTP reqeusts from:

- Query string (URL parameters), e.g. `?name=john&is_member=true`
- Headers, e.g. `Authorization: xxx`
- Form data, e.g. `login=john&password=*****`
- JSON/XML body, e.g. `POST {"name": "john", "is_member": true}`
- Path variables, e.g. `/users/{username}`
- File uploads

You don't need to write parsing code for each parameter by yourself. You only care about the input struct and in which handler it will be used.

Let's see an example:

```go
// 1. Define you input struct
type ListUsersInput struct {
	Page     int  `in:"form=page"`
	PerPage  int  `in:"form=per_page"`
	IsMember bool `in:"form=is_member"`
}

// 2. Bind this input struct with an HTTP handler
func init() {
	http.Handle("/users", alice.New(
		httpin.NewInput(ListUsersInput{}),
	).ThenFunc(ListUsers))
}

// 3. Use the input in the handler, all the parsing stuff are handled by httpin
func ListUsers(rw http.ResponseWriter, r *http.Request) {
	input := r.Context().Value(httpin.Input).(*ListUsersInput)
}
```

You will find that with the help of **httpin**, you can get the following benefits:

- ⌛️ Saving developer time
- ♻️ Lower code repetition rate
- 📖 Higher readability
- 🔨 Higher maintainability

**httpin** is well documentated at https://ggicci.github.io/httpin/.

❤️ Have a try with it :)
🔵 CSS Responsive Sidebar Navigation.
Tags: html, css, webdev, tutorial
Published: 2021-08-24 05:52:14

💜 Today, I’m going to share a responsive sidebar navigation with a step-by-step implementation guide. This sidebar navigation menu comes with an animated hamburger button to toggle the menu drawer.

Generally, a hamburger menu requires a small function of JavaScript to toggle the menu drawer. But, it can also functionalize using HTML and pure CSS.

### HTML for Responsive Sidebar Navigation

+ The HTML consists of three parts, navigation menu, a toggle button and a dummy content that contains navigation links. 
+ The All div and section are wrapped into main div with class name `.container`.
![Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yant738tgflv4ml4ngvm.png)

### The CSS Styles
+ As the above HTML, first of all, we’ll define some styles for the body and main container. 
+ After that styles nav using CSS position absolute property, if you want to make it static just remove position attribute. If you want to change its thickness, update the height value. 
+ Similarly, you are also able to change its background color according to your own theme.
![css1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51rpccs9hh0ee3kbddad.png)
![css2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47dh7yb88m3w2uoqv8li.png)
![css3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5r1aoonj0x8akznj08i8.png)
+ Add the following CSS code for the dummy content and it's menu.
![css4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yfnme8b3crowtjr5novk.png)
![css6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nfb9ejzfu5suzx8p15iy.png)

## Final Result:-
![Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmq4qvbgtlv7ed38zoqu.gif)
###If you need source code please follow me on instagram @codev_land

That’s all! Let me know by comment below if you have successfully implemented this sidebar navigation menu into your project.

###Keep Claim And Just Code It 😎
Getting Started with ionic in Angular
Tags: javascript, ionic
Published: 2021-08-24 05:45:46

**Intro**
Ionic is one of the leading frameworks for hybrid app development. That means to have one code base for all mobile, Desktop app & web. One can create an app using javascript frameworks like angular,react & vue. Though in this article we will be creating an ionic app using angular. Let's get started.

**Prerequisites**
Basic understanding of node & npm
Had built at least hello world app in angular
At least know what Android studio is

**Installations**
First let's install all the required tools/software

VS code editor you can install it from - [vs code download](https://code.visualstudio.com/download)

Command line - 

Linux - the default terminal is more than enough
Windows - recommended windows powershell or the default terminal

[See how to add env to use in terminal](https://www.redthemers.tech/2021/05/how-to-set-environment-variable.html)

Install node & npm 

For linux perform the following operation - 

``` python
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
```
``` python
sudo apt install nodejs
```
Use 
***node --version*** & 
***npm --version*** 
to check if it's installed correctly.
For windows please refer -  [nodejs for Windows](https://www.guru99.com/download-install-node-js.html)

After you had installed the above stuff now run the following command in terminal to install ionic tooling
``` python
npm install -g @ionic/cli native-run cordova-res
```
Run ***ionic --version*** to check if its installed correctly
Running the app 
Now we create a simple ionic app with these simple commands 

``` python
ionic start myIonicapp tabs --type=angular --capacitor
cd myIonicapp
Npm i
ionic serve
```
That's it, now your test application should be running on localhost 8100 or as mentioned in the terminal.
So, you are the one who learn by doing mistakes in Interview? How to avoid it...
Tags: datascience, database
Published: 2021-08-24 05:00:49

Let's not stretch the problem much and make it more scary. Rather let's talk about the potential solutions to avoid such mistakes.

1. Furnish your resume and projects according to job requirements. This is not a secret, but we always avoid it or use the same resume for all the job applications.

2. Understand the profile and it's roles and responsibilities. Whether it align with your purpose. It should allow you to learn and grow. If it is not clear ask for an exploratory call with your hiring manager to clarify these very important points.

3. Know the process and nitty-gritty before you get into it. Specially understand the interviewer background. Research on LinkedIN etc. This will give you a better understanding of person you going to face.


4. The above step would also give you a better understanding of your manager in your upcoming company.

5. Prepare for each interview round in advance. This is very tricky and crucial. It can make or break a deal. All the above steps and hard work is waste if you are not prepared for interview.

We think we know all the answers of questions. But have we validated it with someone. Are we understanding the question rightly and sticking to point while answering. In case our resume is getting rejected multiple times then what is wrong with resume. What projects we should talk in interview and how to manage that interview stress.

For instance, you are preparing for Data Science interview for first time. You never want to miss that opportunity to nail the interview in your dream company. How about taking help from an experienced Data Scientist to prepare for your interview, to manage your portfolio projects and validate your answers. He/She can simulate the environment where one try to trap you with the tricky questions. It can be a deal breaker. Expert data scientist have experience of taking 100 of interviews and can share hidden agenda and tips with you.

How you can find that expert and ask for help? MentorIF creating a community of experts who are helping learns with all their career, skills and job related requirements.

https://www.mentorif.com/event/58396148744?utm_source=Dev&utm_medium=blog&utm_campaign=dev-ds-pradip&utm_id=dev-ds-pradip
The 6 VSCode Extensions I couldn't live without
Tags: beginners
Published: 2021-08-24 04:49:37

The geniuses behind VSCode can't think of *everything*, so it's absolutely wonderful that any programmer with a great idea can create an extension that we can all benefit from. We all have our favorites, and these are mine. 

* __[Fold Plus](https://marketplace.visualstudio.com/items?itemName=dakara.dakara-foldplus)__
 * __What:__ Allows you to collapse every nested block of code 
 * __Why:__ Collapsing all your code blocks makes your code so much easier to understand
 * __How much:__ Free

* __[Git Graph](https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph)__
 * __What:__ A visualization of your git history 
 * __Why:__ Your git history is confusing as fuck, admit it
 * __How much:__ Free

* __[Monokai Pro](https://marketplace.visualstudio.com/items?itemName=monokai.theme-monokai-pro-vscode&ssr=false#overview)__
 * __What:__ Color scheme for code 
 * __Why:__ It's just how code should be colored. Prove me wrong.
 * __How much:__ Free evaluation copy, then €9.95 to buy it (I did. It's worth it)

* __[Rainbow Brackets](https://marketplace.visualstudio.com/items?itemName=2gua.rainbow-brackets)__
 * __What:__ Colors opening and closing bracket pairs the same color 
 * __Why:__ Makes it 1000 times easier to understand which opening and closing brackets are paired because they are the same color
 * __How much:__ Free

* __[Prettier Code Formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)__
 * __What:__ It formats and indents your code so it's much easier to parse 
 * __Why:__ It's much easier than trying to understand a giant block of spaghetti code.
 * __How much:__ Free

* __[Spell Right](https://marketplace.visualstudio.com/items?itemName=ban.spellright)__
 * __What:__ A spellchecker for VSCode 
 * __Why:__ You're still lousy at spelling and need a spellchecker
 * __How much:__ Free

Those are my favey-faves, what are yours? Please add them in the comments below, I am always hungry for a new clever extension to make writing code easier!
My first web page
Tags: html, css, webdev
Published: 2021-08-24 04:18:00

**¡Hello World!** This is my first web page. It is my first 
step toward becoming a developer.

This web page is about showing my favorite programming languages(Java, Python and C++) and its histories.
This page was created using **HTML** and **CSS**.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtc6bj3zlo1i0h8wdf7h.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a31buql0pn6j5epma56d.png)