teleren/devto huggingface dataset:
Understand The DOM and DOM manipulation with javascript. (part 3 final)
Published: 2022-11-05 14:31:50

Now , You have an understing of what DOM is ,how to select element from the page, and how to add and remove elements to and from the page, those knowledges will be helpful in this part. If you've missed the last two part of this serie, you can still find them :

- [Understand The DOM and DOM manipulation with javascript. (part 1)](https://dev.to/jonathz/understand-the-dom-and-dom-manipulation-with-javascript-part-1-54kk)
- [Understand The DOM and DOM manipulation with javascript (part 2)](https://dev.to/jonathz/understand-the-dom-and-dom-manipulation-with-javascript-part-2-153i)

Like any program, Javascript programs can get slow fast if we are not careful about how we're writing our code. In this part we will lock at how to minimize DOM changes to make our page faster.

## I. Reflow and Repaint

- **Reflow** happens when a browser process and draws parts of a web page. It happens when you first display the DOM (generally after the DOM and CSS have been loaded), and happens again every time something could change the layout. This is a slow process.


- **Repain**  happens after reflow as the browser draws the new layout to the screen.

## I.1 Add elements efficiently

### Problematic

```javascript

for (let i = 1; i <= 200; i++) {
    const newPara = document.createElement('p');
    newPara.textContent = 'This is paragraph number ' + i;

    document.body.appendChild(newPara);
}

```
The code above adds two hundred paragraphs to the page, doing the following steps two hundred times

- Create the paragraph
- Add some text to the paragraph
- Add the paragraph to the page

This means, **Reflow** and **Repaint** will happen two hundred times each one. That's no good according the **Reflow's** processing time. The good way will be to reduce **reflows** to once and **repaints** to once.

### Possible solution

The above approach can be improved by creating an extra container that will hold our two hundred paragraphs, then we add that container once to the page. 

```javascript
const container = document.createElement('div');

for (let i = 1; i <= 200; i++) {
    const newPara = document.createElement('p');
    newPara.textContent = 'This is paragraph number ' + i;

   container.appendChild(newElement);
}

document.body.appendChild(container);

```
This approach is more efficient because, instead of updating the DOM two hundred times, we created a container once, that will hold two hundred paragraphs, and finally added this container to the page. For one modification to the page, **Reflow** and **Repaint** will happen once. 

## Conclusion
We should care about web performance because Good or bad website performance correlates powerfully to user experience, as well as the overall effectiveness of most sites
Thank your for reading this article. You can reach out to me on [twitter](https://twitter.com/JonathanZihind4), or [linkedIn](https://www.linkedin.com/in/jonathan-z-0a40ab209/).
Non-overlapping Intervals
Tags: javascript, leetcode
Published: 2022-11-05 11:07:39

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

 

Example 1:

Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.

Example 2:
Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.

Example 3:
Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

```
const eraseOverlapIntervals = (arr) => {
  let selected = [];

  // Sort jobs according to finish time
  arr = arr.sort(function (a, b) {
    return a[1] - b[1];
  });

  // The first activity always gets selected
  let i = 0;
  selected.push(arr[i]);

  for (let j = 1; j < arr.length; j++) {
    /*If this activity has start time greater than or
         equal to the finish time of previously selected
         activity, then select it*/
    if (arr[j][0] >= arr[i][1]) {
      selected.push(arr[j]);
      i = j;
    }
  }
  return arr.length - selected.length;
};

console.log(
  eraseOverlapIntervals([
    [1, 2],
    [2, 3],
    [3, 4],
    [1, 3],
  ])
);

console.log(
  eraseOverlapIntervals([
    [1, 2],
    [1, 2],
    [1, 2],
  ])
);

console.log(
  eraseOverlapIntervals([
    [1, 2],
    [2, 3],
  ])
);

```
Fix my code! Chain of if-else statements.
Tags: cleancode, refactoring, refactorit, codequality
Published: 2022-11-05 14:02:46

How to get rid of a chain of if-else statements in your code? There're several ways.

👉Ignore it

Not all the code that you write can and has to be pretty and clean. Sometimes it just doesn't worth investing into making a particular code cleaner. And don't forget that any refactoring creates risk of breaking a working code.


👉Design patterns

GoF patterns offer several different ways to deal with if-else chains. Check them out!


👉Use loop

Sometimes it is possible to replace if-else statements with a loop. On the video below I show how to do that

{% embed 
https://youtu.be/TMyt6JTbuNc %}
Calculating Sine, Cosine and Tangent in Python
Tags: python, beginners, tutorial
Published: 2022-11-05 13:57:33

Let's calculate sine, cosine and tangent in Python. It is not a difficult task, but it requires attention to some details.

First of all, we need to import the `math` library:

```py
import math
```

Next, we need to read the angle value the user will enter. But an important note, the calculation requires the angle value in radians.

So, just perform this conversion from angle to radians. How? Using the `radians()` method from the `math` library:

```py
ang = int(input('Angle: '))
rad = math.radians(ang)
```

With the angle value in radians, we can now calculate the sine, cosine and tangent values. We'll use the `sin()`, `cos()` and `tan()` methods from the `math()` library:

```py
sine = math.sin(rad)
cosine = math.cos(rad)
tangent = math.tan(rad)
```
Functions in JavaScript.
Tags: javascript, programming, beginners, tutorial
Published: 2022-11-05 13:37:46

**1. Introduction**
Function is a block of code which perform specific task in a better and efficient way.  

**Syntax**
It is defined using _function_ keyword, then followed by the name of the function say var1, followed with parentheses ().
Function name follows same rules as of variable name. 
```
function var1(par1, par2) {
code to be executed
}
```
**2. Uses of Functions**
Functions basically resist the repetition of same code again and again. Once the code is designed, we can use it multiple times just by giving the 
arguments.

Example:

```
function add(num1, num2) {
  const addition = num1 + num2;
  console.log(addition);
}
add(2, 1);
add(63,232):
```
Output:
3
295
**3. Function Return**
When _return_ keyword is used in Function and it reaches to return statement, the code will stop executing. Return keyword helps in future use of the output of Function.

For example:

```
function multi(par1, par2) {
  return par1 * par2;
}
console.log(multi(10, 2));
```
Using Python list as a Stack
Tags: python, algorithms, datastructures
Published: 2022-11-05 13:34:08

## What is a stack?
Stack is a data structure which follows the **LIFO ** property, which means Last-In-First-Out. The element inserted last will be the first to be removed.

## Stack operations

1. **Push**- To insert new element in the stack.

2. **Pop**- To remove an element from the stack.


## Using python list as stack

We can use the python's in-built list as stack data structure.

### Push
You can use the in-built append method to insert element at the end of the array/list.

```python
stack = []
stack.append(3)
stack.append(4)
stack.append(5)
stack.append(6)

print(stack) # [3, 4, 5, 6]
```

### Pop
To pop an element we can use the in-built `pop` method on list.

```python
print(stack.pop()) # 6
```

This method will remove the last element in the list, if we do not specify any element to be removed.

### Getting top of stack
To get the top element in the stack we can use a python's in-built feature to index list from the end.

```python
print(stack[-1]) # 5
```
Displaying the Integer Part of a Value in Python
Tags: python, beginners, tutorial
Published: 2022-11-05 13:30:08

We can check the integer part of a real number, and one of the ways to do that is using the `trunc()` method of the `math` library.

Let's import the method:

```py
from math import trunc
```

Then we read a real number and display its truncated value on the screen:

```py
n = float(input('Real number: '))

print(f'Integer part: {trunc(n)}')
```

Another way is simply using the `int()` function to display the value in its entirety.

```py
print(f'Integer part: {int(n)}')
```
Validating Types and Data in Python
Tags: python, beginners, tutorial
Published: 2022-11-05 13:19:04

We can find out the type of a variable using the `type()` function, that allows us to check what type of variable the algorithm will accept or not.

Let's read a variable that's not being converted to an integer, so it's a string:

```py
x = input('Type something: ')
```

Then we run the `type()` function inside the `print()` function, to display the type of the variable `x` on the screen:

```py
print(type(x))
```

The result will be:

```
<class 'str'>
```

## Basic validation

Here is a brief validation of the variable, if it's not `int`, the code will execute the programmed condition:

```py
if type(x) != int:
    print('The variable is not integer')
```

## Advanced validation

We can get so much more informations from a variable in the program, just run some of the methods:

```py
#Contains only letters?
isalpha()

#Contains only spaces?
isspace()

#Contains only numbers?
isnumeric()

#Contains only uppercase?
isupper()

#Contains only lowercase?
lower()

#Contains only letters and numbers?
isalnum()

#First capital and others lowercase?
istitle()
```

The result returned will be `True` or `False`.

Let's run the methods with a `y` variable:

```py
print('Only letters?', y.isalpha())

print('Only spaces?', y.isspace())

print('Only numbers?', y.isnumeric())

print('Upper case only?', y.isupper())

print('Lower case only?', y.islower())

print('Is it capitalized?', y.istitle())

print('Letters and numbers only', y.isalnum())
```

Try entering different inputs until you fully understand the concepts of each method.

## In practice

We can, for example, use the `isnumeric()` method to validate a Zip Code. In which the program will proceed when the user enters only numbers.

Or use the `istitle()` method to check the Name field of a form. If the name entered is not capitalized, we can validate and even make the necessary changes to the variable.
creating a self signed ssl certificate and making your browser trust it
Published: 2022-11-05 13:18:13

So i needed to make localhost with ssl certificate but couldn't find a way to create a certificate. After a few hours i found the solution. So first of all:
1) `openssl genrsa -out rootCA.key 2048`
2) `openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem`
After those 2 commands you should get 2 files (rootCA.key & rootCA.pem
3) Now let's create a bash script. I'll name it create_certificate_for_domain.sh
to begin type this lines:

```
if [ -z "$1" ]
then
  echo "Please supply a subdomain to create a certificate for";
  echo "e.g. mysite.localhost"
  exit;
fi
if [ -f device.key ]; then
  KEY_OPT="-key"
else
  KEY_OPT="-keyout"
fi
DOMAIN=$1
COMMON_NAME=${2:-$1}
SUBJECT="/C=CA/ST=None/L=NB/O=None/CN=$COMMON_NAME"
NUM_OF_DAYS=999


cat v3.ext | sed s/%%DOMAIN%%/$COMMON_NAME/g > /tmp/__v3.ext
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days $NUM_OF_DAYS -sha256 -extfile /tmp/__v3.ext

mv device.csr $DOMAIN.csr
cp device.crt $DOMAIN.crt

rm -f device.crt;

```
4) create csr file 
openssl req -new -newkey rsa:2048 -sha256 -nodes $KEY_OPT device.key -subj "$SUBJECT" -out device.csr
5) now we have to create a support file with settings. I'll call it v3.ext

```
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%
DNS.2 = *.%%DOMAIN%%
```
5) Now run the script
`./create_certificate_for_domain.sh mysite.localhost`
6) We get 2 files: **mysite.localhost.crt** && **device.key**
7) We have to link them to our localhost (nginx example)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spwgj4nmjjj3p42r7p9e.png)
8)open our link in browser. you should get security error
9) go into keychain and trust our mysite.localhost.crt

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

10) open the browser again and open localhost. That's it, you should be good to go!
Telemetry on software defined networking
Tags: sdn, networking, openflow, opensdn
Published: 2022-11-05 13:05:20

## **WiFi 7**

WiFi 7 is coming up with detection and human sensing. This creates an enormous amount of opportunities that works with opentelemetry. I had an opportunity to listen to opentelemetry, which involves solving observability by logging, metrics and synthetic checks. 

## **Human in the loop**

I have observed human-in-the-loop scenarios where certain images are classified into desired classes. This involves a high dimensional data drift which may be matured into high dimensional concept drift, using automation. DevOps will also remain prominent in such a scenario. 

## **OpenTelemetry**

If WiFi 7 improves it functionality, then security becomes stronger because it is illegal to tamper with the networking equipments. OpenTelemetry will be widely used by businesses to achieve 99.99% uptime in observability.
Let's Make the Computer Think of a Number with Python
Tags: python, beginners, tutorial
Published: 2022-11-05 12:59:11

A practical way of doing that's using the `random` library. Let's import it:

```py
import random
```

Among the `random` methods, there is the `randint` method, that returns an integer value within a specified range.

```py
random.randint(0,10)
```

Just use a variable to store the value the function will return and that's it, we can display the value the computer thought.

```py
x = random.randint(0,10)
print(x)
```
How to recursively remove .DS_Store
Tags: devops, bash
Published: 2022-11-05 12:58:56

Lately, I've been doing a lot of development on Mac. With that comes a lot of use of the Finder app.

In order keep your repo clean, you need to remove .DS_Store files from the folders created using the Mac GUI. Doing that by hand is really boring, painful, and repetitive. Enter that awesome thing we call the command line.

## Recursively Remove .DS_Store
Open up Terminal

In the command line, type: 

`cd to/your/directory` - then press enter.

Finally, in the command line, type: 

`find . -name '.DS_Store' -type f -delete` - then press enter.

> Warning: Never use a wildcard (*) with this command, unless you know what you're doing. Bad things can happen if you don't.

This snippet will remove .DS_Store files from the selected folder, as well as all of the folders that it contains. All of them. At once.

This command can be used for other types of files, as well. Just replace '**.DS_Store**' with whatever file name, or type, that you want to delete.

## Other uses
You can do this for other file types, as well.

For example, you could use the below to delete all JavaScript files within a containing folder.

`find . -name '*.js' -type f -delete` 

> Note that the asterisk is a wildcard, meaning the Terminal is looking for any file with an extension of .js... it can be dangerous to use wildcards...

_be careful._
O-1 Visa USA vs UK Global Talent Visa: What’s better
Published: 2022-11-05 12:44:04

O-1 Visa USA vs UK Global Talent Visa - let’s talk to someone who has had BOTH!

Artur Paikin is the only person I know who has been granted “extraordinary ability” visas in both the UK and the USA: O-1 visa in 2016 and UK Global Talent Visa in 2019.

Join me for a live chat with Artur where we will take this unique experience apart and talk about:

- What are the differences between the two visa processes?
- What are the pros and cons of each visa?
- How to choose whether to apply for O-1 or Global Talent?
- USA vs UK as a relocation spot for software engineers

You'll also get to ask Artur questions during the Q&A.

{% embed https://youtu.be/Uksw7zrFr4A %}
Anaconda as a Data Science Solution
Tags: datascience, python, beginners
Published: 2022-11-05 12:43:54

As soon as I started a course of Data Analysis with Python, I had the opportunity to use the Anaconda distribution.

A platform that encompasses the main tools and packages for Data Science and Machine Learning, including everything that's essential: Jupyter Notebook, Pandas, NumPy, Scikit-learn and more.

Because instead of installing these packages and libraries separately, installing Anaconda allows the users to immediately start using all the tools they might need.

I highly recommend it, and for more information:

https://www.anaconda.com
From "add" to "push" to GitHub in a Single Line
Tags: github, beginners, tutorial
Published: 2022-11-05 12:36:10

I adopted the multiple commands on a single line to push to GitHub. Instead of running:

```powershell
git add .
git commit -m 'Update file'
git push
```

I simply run:

```powershell
git add .; git commit -m 'Update file'; git push
```

Believe me, the use of semicolons to execute multiple commands can make a difference when we want agility in the moments of development.

But of course, each case is different. There will be times when a specific commit, with a specific message, will be needed.
How to run Google Chrome Apps via Command Line (CLI)
Tags: archlinux, cli, chrome
Published: 2022-11-05 12:21:52

So I use ArchLinux on my Home PC and my Work PC. I use Google Chrome for work as a default browser and at home I use QuteBrowser. Sometimes, Google Chrome has the ability to just install Chrome Apps instead of downloading Electron and Nativefier to create your own.

So for instance, I like to use this Spike email as my email client but they do not have it for Linux. A great alternative it is install it as an App in Google Chrome.

Once I install it. I would go to my terminal and create an alias

First if you have multiple Profiles in Chrome, you would need to find out which profile it is and it is by the Number. Ex. Profile 1, Profile 2, Profile 3 and so on.

I will show you how my alias looks first. You can add this to your fish config, your zsh or bash. I did it for my fish config

[I] ┌──[archlinux] as haxnet in ~/.config/fish on (master ↓7 ✚10)
└──▶ cat config.fish | grep spike

```
alias spike='/usr/bin/google-chrome-stable --profile-director="Profile 3" --app-id=emldofgbopmlaimkbbfnionhnagimknj & disown'
```

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


You need to figure out where is your google chrome executable file is. In my case, it is /usr/bin/google-chrome-stable (btw, you can do this with chromium)

Now you would select your Profile. How to find this you can go to google chrome and find your installed app settings


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

Click on the menu and go to app info>setting


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

The url where I highlighted is your AppID this is where you put in the command line in the terminal as --app-id=AppID

Copy that appID and then go to your terminal and locate the appID

[I] ┌──[archlinux] as haxnet in ~ on (master ↓7 ✚10)
└──▶ locate emldofgbo | grep Profile

/home/haxnet/.local/share/icons/hicolor/128x128/apps/chrome-emldofgbopmlaimkbbfnionhnagimknj Profile_3.png
/home/haxnet/.local/share/icons/hicolor/256x256/apps/chrome-emldofgbopmlaimkbbfnionhnagimknj Profile_3.png
/home/haxnet/.local/share/icons/hicolor/32x32/apps/chrome-emldofgbopmlaimkbbfnionhnagimknj-Profile_3.png
/home/haxnet/.local/share/icons/hicolor/48x48/apps/chrome-emldofgbopmlaimkbbfnionhnagimknj-Profile_3.png
/home/haxnet/.local/share/icons/hicolor/512x512/apps/chrome-emldofgbopmlaimkbbfnionhnagimknj Profile_3.png
/home/haxnet/Desktop/chrome-emldofgbopmlaimkbbfnionhnagimknj-Profile_3.desktop


You will quickly see the results and for me, it is Profile 3

that's where you put --profile-director="Profile 3"

I just add the & disown to basically run it as a standalone so I can continue using the same terminal.

for the locate function - you will need to download **mlocate**

You can read my other post about this function

[dev.to/haxnet/locate](https://dev.to/haxnet/locating-a-specific-file-in-terminal-pk9)
Prometheus - New Azure managed service
Tags: azure, prometheus, monitoring
Published: 2022-11-05 12:16:25

**Prometheus**, the go to monitoring tool for open source applications, but when it comes to monitoring containerized workloads, Prometheus play very well, because it's backed up by open source community.

**Challenge**, when it comes to enterprises, especially using it inside Azure Kubernetes service,  🙋‍♂️🤔 question often asked is how to manage each Prometheus without getting escalation email from security team ⚠️☠️.

**Solution**, Implement Prometheus as a feature inside Azure monitor, and add extensions like Azure Monitor container insights and Azure Managed Grafana into it, hope other teams in Azure will create extensions for their services too.

> Prometheus is not free service, [detail pricing](https://azure.microsoft.com/en-us/pricing/details/monitor/)

![Prometheus pricing snip](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oxx4mkhvc7qdz8yk47nx.png)


## How to start

-  Search for **Managed Prometheus** in the Azure Portal

![getting started](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/taptlrrvx5dfj6mx04x1.gif)

Now Prometheus is up and running, let's onboard some AKS clusters into it.

with few clicks inside Azure blade, AKS is setup with Azure Managed Grafana to collect all data and comes with its default dashboards to visualize your Prometheus data. 

![enable collection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5esff00dnl5u5lf5cre8.gif)

## Integrate with AKS

Existing AKS Clusters, under monitor setting you can enable Prometheus metrics and Grafana workspace 

During the setup process you will have the option to add Managed Prometheus as a new data source to your Azure Managed Grafana workspace. 

Once setup, few default dashboards to get you started with visualizing, and navigate into Azure Managed Grafana from both Managed Prometheus and Container Insights,

![enable from AKS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zyw34xhsgjrrjn0iwdmj.gif)


![azure to Grafana](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/97bldq0u0v4lmhmtbpo7.gif)

## Available in few regions

## Refer documentation to learn more [🎯here](https://learn.microsoft.com/en-us/azure/azure-monitor/essentials/prometheus-metrics-overview)