teleren/devto huggingface dataset:
Conditional examples
Published: 2022-07-19 12:46:19

#Conditional examples
##In this reading, you will learn when to use the if else statement and when to use the switch statement.

Both if else and switch are used to determine the program execution flow based on whether or not some conditions have been met.

This is why they are sometimes referred to as flow control statements. In other words, they control the flow of execution of your code, so that some code can be skipped, while other code can be executed.

At the heart of both flow control structures lies the evaluation of one or more conditions.

Generally, if else is better suited if there is a binary choice in the condition.

For example, in plain English: if it's sunny, wear sunglasses. Otherwise, don't.

In this case, using an if statement is an obvious choice.

When there are a smaller number of possible outcomes of truth checks, it is still possible to use an if else statement, such as:
  <pre>
```javascript
if(light == "green") {
    console.log("Drive")
} else if (light == "orange") {
    console.log("Get ready")
} else if (light == "red") {
    console.log("Dont' drive")
} else {
    console.log("The car is not green, orange, or red");
}
```
</pre>

## However, if there are a lot of possible outcomes, it is best practice to use a switch statement because it is easier less verbose. Being easier to read, it is easier to follow the logic, and thus reduce cognitive load of reading multiple conditions.

Nevertheless, this is not a rule set in stone. It is simply a stylistic choice.

To reinforce this point, here's an example of the earlier if else conditional statement, using the switch syntax: 

  <pre>
```javascript
switch(light) {
   case 'green':
       console.log("Drive");
       break;
   case 'orange':
       console.log("Get ready");
       break;
   case 'red':
       console.log("Don't drive");
       break;
   default:
       console.log('The light is not green, orange, or red');
       break;
}
```
</pre>
Redux don't need Redux. || Redux in a nutshell.
Tags: redux, react, javascript, programming
Published: 2022-07-19 12:45:29

Redux

A JavaScript state management library.

Which is **90% convention and 10% library**.

When different components of the app needs to share information back and forth, things become very messy very quickly.

![redux-visual](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9wd7crnjshjx5mtjwdw.png)

Philoshopy of Redux is to keep a single source of truth instead of each component managing their own internal state.

And this dramatically simplifies the state managment proccess.

Redux is based on 3 core principles:

Action, Reducer, and State

Remember, when I said **Redux is 90% convention**. Its these 3 concepts. These concepts are not Redux specific.

Their is a saying that **“Redux don’t need Redux”**.

To understand what it means, let’s take a look at Actions and Reducers.

**Action**: Is an object with type & payload as key. Which is dispatched.

**Reducer**: Is a **pure function** which returns a new state, based on action’s type and payload. `Pure function is the key here`.

See, in React there is a hook called useReducer, so with combination of useReducer and useContext, you can achieve the same behaviour as Redux without actually using Redux.

That’s where the saying comes in. (**Redux don’t need Redux**)

Infact you can implement your own Redux library in just 24 lines of code.

Here is the complete Redux flow.

![Redux flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kuvr2m29li2w3tbfdmt.jpg)

- Dispatch an action.
- Reducer returns a new state based on action type and payload.
- Redux store is updated and the app is synced via subscribe method.

The 10% which is the actuall library are the helper methods and performance optimization techniques provided by Redux.

So, that was Redux in a nutshell.

-----------------------

So, that is it for this post. If you anyhow liked this post, make sure to show your support.

Will see you in the next post.

I also run a weekly newsletter, so you can join me there also: https://swastikyadav.com

Thank You!
#4.Basic algorithms problems for frontend developers.
Tags: javascript, algorithms, frontend, react
Published: 2022-07-19 12:30:26

Find a letter that occurs the most in a given sentence.

In our case example: in the phrase 'hey there my friend' the letter** e** occurs the most

```
const str = 'hey there my friend';

const mostFrequent = s => {
  /* declare a helper obj */
  const obj = {};

  // get a words array out of the string
  const string = s.split(' ');

  // loop over the words
  for (let word of string) {
    //loop over each letter in every word
    for (let letter of word) {
      // assign 1 if that propriety does not exist in obj
      if (!obj[letter]) obj[letter] = 1;
      // increase by one if it exists
      else obj[letter]++;
    }
  }

  //declare 2 helper variables
  let max = 0;
  let prop = '';

  // loop over the obj
  for (let key in obj) {
    /* if the value is bigger than max (which first time is 0), 
    assign the new value to max and return that key. */
    if (obj[key] > max) {
      /* reassign max to the current value 
      in the loop if the value is bigger than max */
      max = obj[key];
      //return the key of the object for the biggest value of the max
      prop = key;
    }
  }

  return prop;
};

console.log(mostFrequent(str));```
Making typed forms a bit more consistent
Tags: angular
Published: 2022-07-19 12:24:00

Angular typed forms are pretty awesome. Strongly typing your forms bring a lot of benefits, but one issue is holding it back: allowing you to define a single interface from which you can create a typed form and infer the form value from it.

Consider the following code:

```ts
interface UserFormControls {
  firstName: FormControl<string>;
  lastName: FormControl<string>;
  email: FormControl<string | null>;
  age: FormControl<number | null>;
}

interface User {
  firstName: string;
  lastName: string;
  email: string | null;
  age: number | null;
}

function processUser(user: User): void {
	// ...
}

const userForm = new FormGroup<UserFormControls>({
	firstName: new FormControl('foo', { nonNullable: true }),
	lastName: new FormControl('bar', { nonNullable: true }),
	email: new FormControl('foo@bar.com', { nonNullable: true }),
	age: new FormControl(null)
});

processUser(userForm.value); // This won't actually compile, keep reading
```

Ideally, you don't want to be forced to maintain two separate interfaces defining the same thing. The User interface can be inferred from the UserFormControls, so let's do that. We use two new types for this.

```ts
type FormValue<T extends AbstractControl> = 
	T extends AbstractControl<infer TValue, any>
	? TValue
	: never;
type FormRawValue<T extends AbstractControl> = 
	T extends AbstractControl<any, infer TRawValue> 
	? TRawValue 
	: never;
```

Let's see what happens when we apply these to our `UserFormControls`.

```ts
interface UserFormControls {
	firstName: FormControl<string>;
	lastName: FormControl<string>;
	email: FormControl<string | null>;
	age: FormControl<number | null>;
}
type UserForm = FormGroup<UserFormControls>;
type User = FormValue<UserForm>;
// type User = {
// 	firstName?: string | undefined;
// 	lastName?: string | undefined;
// 	email?: string | null | undefined;
// 	age?: number | null | undefined;
// }

type UserRaw = FormRawValue<UserForm>;
// type UserRaw = {
// 	firstName: string;
// 	lastName: string;
// 	email: string | null;
// 	age: number | null;
// }
```

Note that the `User` type now has all it's properties as optional. This is because controls can be disabled and those won't show up in the final form value. The raw value is typed exactly how we specified our User interface earlier. It is also why the `processUser(userForm.value);` in the first code block won't compile.

## Make your choice

Here you must make a choice: 
- You can either use the `FormValue<..>` and deal with every property being potentially `undefined`, or;
- Use the `FormRawValue<..>` with care. As long as all the controls that can be disabled are marked as optional, your typing will be sound.

My recommendation would be the latter. In that case, we'll end up with the following solution:

```ts
type User = FormRawValue<UserForm>;
// type User = {
// 	firstName: string;
// 	lastName: string;
// 	email: string | null;
// 	age: number | null;
// }

// ...

function processUser(user: User): void {
	// ...
}

processUser(userForm.value as User);
// or:
processUser(userForm.getRawValue());
```

Good luck!
Can You Have 2 Cash App Accounts For Personal And Business Purposes?
Tags: it, mobile
Published: 2022-07-19 12:17:34

If you would like to confirm [Can You Have 2 Cash App Accounts](.  https://www.pcmonks.net/blog/2-cash-app-accounts/) to cater to your personal as well as your business needs, you should keep the fact in mind that you will be able to do the same without confronting any kind of hassle. To find out the right kind of guidance under the supervision of the cash App support engineers, you have to visit the contact us page where you can find out the right way to approach these specialists.
JSON Creator Douglas Crockford Interview
Tags: javascript, webdev, programming, news
Published: 2022-07-19 12:17:21

We had a nice chat with Douglas Crockford, a well-known American computer programmer who was involved in the development of the JavaScript language. Douglas is the author of How JavaScript Works. He also discovered the JSON Data Interchange Format, the world’s most loved data format.

[Enjoy full interview here!](https://evrone.com/douglas-crockford-interview)
Optimism (OP) L2 Market Share Eyes 20% as ETH Price Spikes Ahead of The Merge
Tags: programming, optimism, javascript, ethereum
Published: 2022-07-19 12:13:52

Optimism (OP), a top-tier second-layer scalability solution for Ethereum (ETH) is among leaders of 7-day change, L2Beat says.
Optimism (OP), a high-performance scalability solution for Ethereum (ETH) blockchain, increases its dominance in the L2s sphere.

## Optimism (OP) nodes on fire in mud-July

According to the statistics shared by L2Beat blockchain’s tracker, [Optimism](https://getblock.io/dedicated-nodes/op/) (OP) nodes are leading the market recovery of L2s ecosystem. Its aggregated total value locked (TVL) among all supported protocols spiked by 6.9 per cent in the last 7 days.

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

As such, Optimism (OP) is the second fastest growing solution in Top-10, surpassed by Arbitrum only. Optimism (OP) nodes ecosystem is responsible for $761 mln in total value locked or about 19.07 per cent of net TVL across all L2 protocols.

Largely, this upsurge should be attributed to the increase of Ethereum (ETH) price. In the last five days, Ethereum (ETH), the second cryptocurrency, spiked by more than 44 per cent.

As such, Optimism (OP) is the second fastest growing solution in Top-10, surpassed by Arbitrum only. Optimism (OP) nodes ecosystem is responsible for $761 mln in total value locked or about 19.07 per cent of net TVL across all L2 protocols.

Largely, this upsurge should be attributed to the increase of Ethereum (ETH) price. In the last five days, Ethereum (ETH), the second cryptocurrency, spiked by more than 44 per cent.

## Ethereum (ETH) merge date announced

In turn, [Ethereum](https://getblock.io/nodes/eth/) (ETH) price upsurge is catalyzed by the decision of its core developers to finally set the tentative date for much-anticipated upgrade The Merge. This upgrade is set to signal for the migration from Proof-of-Work to Proof-of-Stake consensus as the basic technical consensus for its nodes.

Ethereum’s core developer and ACD meetings coordinator Tim Beiko announced that Ethereum Merge is expected to be activated on September 19, 2022. This is the most crucial milestone on the road towards Proof-of-Stake Ethereum (ETH) since the launch of ETH2 deposit contract in Q4, 2020.

Also, some analysts claim that The Merge date might be an end for ‘Crypto Winter’ of 2021-2022.

## GetBlock’s Optimism (OP) dedicated nodes meet market recovery locked and loaded

Bullish or bearish, GetBlock is always ready to support developers with reliable and cost-efficient node APIs. Optimism (OP) dedicated nodes are the latest addition to GetBlock’s nodes stack; they are designed to highly scalable mainstream dApps.

Optimism (OP) shared nodes are reasonable solution for early-stage dApps that are getting ready for the migration from Ethereum (ETH) blockchain.
Die Suchintention bzw. Search Intent steht im Mittelpunkt der SEO
Tags: seothemen
Published: 2022-07-19 12:49:32

---
title: Die Suchintention bzw. Search Intent steht im Mittelpunkt der SEO
published: true
date: 2022-07-19 11:58:18 UTC
tags: SEOThemen
canonical_url: https://bloggerpilot.com/suchintention/
---

![Die Suchintention bestimmt die Art deines Inhalts.](https://bloggerpilot.com/wp-content/uploads/2021/09/suchintention.png)

Die Suchintention hilft dir dabei, relevante Inhalte zu erstellen. Lerne,...

Der Original-Artikel erschien auf [Die Suchintention bzw. Search Intent steht im Mittelpunkt der SEO](https://bloggerpilot.com/suchintention/).

Google führte Search Intent im Jahr 2014 ein, und es ist eines der neueren großen Algorithmus-Updates der letzten Jahre. Google kategorisiert die verschiedenen Arten, wie Nutzer nach Dingen suchen, und weist jeder einen Intent-Score zu, anhand dessen Google die Reihenfolge der Suchergebnisse bestimmt. Im Falle eines durchschnittlichen Nutzers ist der Intent Score für eine Suche hoch für eine Anfrage wie "Was ist SEO?" oder "Wie nehme ich ab?" oder "Was ist SEO?"

Da die Verbraucher immer besser informiert sind und Online-Suchmaschinen und Websites zur Erstellung von Inhalten immer mehr relevante Informationen bereitstellen, schließt sich die Lücke zwischen der Suchabsicht und der Nutzerabsicht. Die Suchabsicht ist das, wonach jemand im Internet sucht, während die Benutzerabsicht das ist, was diese Person tut, wenn sie tatsächlich sucht. Die Schnittmenge zwischen Suchabsicht und tatsächlicher Benutzerabsicht wird oft als Absichtsdaten bezeichnet.

Nach Angaben von Google gibt es fünf verschiedene Arten von Suchabsichten, von denen die folgenden die beliebtesten sind:

## Wie die Suchabsicht erkennen?

Die Suchabsicht basiert sowohl auf der Nutzerabsicht als auch auf den bewährten Praktiken der Suchmaschinen. Die Benutzerabsicht analysiert das Suchverhalten der Benutzer im Web und interpretiert es, um die Absicht des Benutzers zu ermitteln. Die Best Practices von Suchmaschinen sind eine Reihe von Richtlinien, die Suchmaschinen befolgen, um den Benutzern zu helfen, relevante Suchergebnisse zu finden.

## Fazit

Zusammenfassend lässt sich sagen, dass die Suchabsicht das ist, was passiert, wenn du Google, Bing, Yahoo oder Ask verwendest. Die Nutzerabsicht ist das, was passiert, wenn du die Suche tatsächlich durchführst.
Firebase 9 Firestore Get A Document By ID Using getDoc()
Tags: javascript, webdev, beginners, programming
Published: 2022-07-19 11:41:55

---
canonical_url: https://softauthor.com/firebase-firestore-get-document-by-id/
---

Learn how to **get document** by **ID** using the **getDoc()** method in **Firebase version 9 Cloud Firestore Database**.

- [Get All Documents From A Collection](https://softauthor.com/firebase-firestore-get-documents-data-in-collection/)
- Get Document By ID → you’re here

The sample **Firestore Database** has a **cities** collection that has four **documents** in it like in the screenshot below.

![alt text](https://softauthor.com/wp-content/uploads/2022/06/Firebase-9-Firestore-GET-ALL-DOCUMENTS-Data-From-A-Collection-1-1024x497.png)

Let’s get the **first document** of the **cities** collection by **id**.

In this case: **Edmonton** document using its ID (2l3bcSGs2vZBIc3RODwp)

**Import Firestore** Database and de-structure the **three methods** that we need:

- **getFirestore()** → **Firestore Database**
- **doc()** → It takes **references** of **database**, **collection name** and **ID of a document** as arguments
- **getDoc()** → getDoc() query gets **data** of a **specific document** from **collection** based references mentioned in the **doc()** method.

```JavaScript
import { getFirestore, doc, getDoc } from https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";
```

>*The import statement uses the CDN version of the Firebase SDK in this example.*

**Initialize** Firestore Database:

```JavaScript
const db = getFirestore();
```

The **getDoc()** method takes a single argument which is the **doc()** method.

The three arguments of the **doc()** method are:

- Database → **db**
- Collection name → **cities** in this case (see the screenshot above)
- ID of a document → **2l3bcSGs2vZBIc3RODwp** in this case (see the screenshot above)

Call the **doc()** method, pass **three arguments** and assign it to a constant called **docRef** (_short form for document reference_).

```JavaScript
const docRef = doc(db, "cities", "2l3bcSGs2vZBIc3RODwp");
```

Invoke the **getDoc()** method passing **docRef** as an argument to it.

The **getDoc()** method will return a **promise**, add **await** keyword in front of it.

Assign it to a constant called **docSnap** (_short form for document snapshot_).

```JavaScript
const docSnap = await getDoc(docRef);
```

To get actual document data, call the **data()** method on the **docSnap** object.

```JavaScript
docSnap.data();
```

Wrap **async** query with **try catch block** to handle **client-side error** if any.

```JavaScript
try {
    const docSnap = await getDoc(docRef);
    console.log(docSnap.data());
} catch(error) {
    console.log(error)
}
```

Check to see if the targeted **document** actually **exists** before **using** it.


```JavaScript
try {
    const docSnap = await getDoc(docRef);
    if(docSnap.exists()) {
        console.log(docSnap.data());
    } else {
        console.log("Document does not exist")
    }

} catch(error) {
    console.log(error)
}
```
Build and use embedded packages with Luos
Tags: luos, embedded, opensource, microservices
Published: 2022-07-19 11:38:08

Packages represent these blocks of code. They contain independent functionalities which will be run by Luos engine.

⏩  https://www.luos.io/docs/luos-technology/package

Let's see how it works in our documentation page.

#luos #opensource #microservices #embedded #edge
JAVASCRIPT CRYING
Tags: javascript, webdev, beginners, programming
Published: 2022-07-19 11:36:15

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

😭JavaScript😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭
**What he says null == empty**
What year are we living in?
did you know what happened today?
Tags: discuss, world
Published: 2022-07-19 11:12:02

&{%!s(*http.body=&{0xc00000e228 <nil> <nil> false false {0 0} false false false <nil>}) {%!s(int32=0) %!s(uint32=0)} %!s(bool=false) <nil> %!s(func(error) error=0x1212100) %!s(func() error=0x1212200)}
How to create a fidget spinner using python.
Tags: python, programming, codenewbie
Published: 2022-07-19 11:11:20

Hello, I got an idea for a practical example on how to create animations using python and I thought a fidget spinner showing three different colours will be brilliant.

Here is a step by step breakdown of the code to help you create the same thing or something similar.


```
#How to create a Fidget Spinner game using python.

from turtle import *
state ={'turn': 0}
def spinner ():
    clear()
    angle = state['turn']/10
    right(angle)
    forward(100)
    dot(120, 'red')
    back(100)
    right(100)
    forward(100)
    dot(120, 'green')
    back(100)
    right(120)
    forward(100)
    dot(120, 'blue')
    back(100)
    right(120)
    update()
def animate():
    if state['turn']>0:
        state['turn']-=1
    spinner() 
    ontimer(animate, 20)
def flick():
    state['turn']+=10
setup(420, 420, 360, 0)
hideturtle()
tracer(False)
width(20)
onkey(flick, 'space')
listen()
animate()
done()
```
Sending Client-side Emails using EmailJs in ReactJs App
Tags: react, emailjs, frontend, javascript
Published: 2022-07-19 11:06:41

- Go to [EmailJs](https://www.emailjs.com/)

- Create a free account (you can send only 200 emails per month in this account) want more emails head to [pricing](https://www.emailjs.com/pricing/)

- Create a email service

- Create a email template

- You can choose the template_id and service_id you want or can genrate one if needed.

- Setup a react project and install the module using.

```
npm install @emailjs/browser --save
```

- Import and use it in your project.

```
import emailjs from "@emailjs/browser"

export const sendEmail = (templateParams) => {
	emailjs
		.send(
			process.env.REACT_APP_EMAILJS_SERVICE_ID,
			process.env.REACT_APP_EMAILJS_TEMPLATE_ID,
			templateParams,
			process.env.REACT_APP_EMAILJS_PUBLIC_KEY
		)
		.then(
			(result) => {
				console.log(result.text)
			},
			(error) => {
				console.log(error.text)
			}
		)
}
```

- Add REACT_APP_EMAILJS_SERVICE_ID, REACT_APP_EMAILJS_TEMPLATE_ID, REACT_APP_EMAILJS_PUBLIC_KEY to your env file. (do not forgot to restart the server after adding the variables)

- That's it you are done with sending emails.

- You can see your logs at [events](https://dashboard.emailjs.com/admin/events) and email history at [history](https://dashboard.emailjs.com/admin/history).

- Also you can add reCAPTCHA v2 and google analytics while sending the email.


> If you have any query you can leave it in the comment.

> Don't forgot to visit my [webite](http://www.adarshgoyal.com/) and follow me. Thank you.
Leaders in an array
Published: 2022-07-19 11:06:01

To day let's see Leaders in array Problem 

> An element is leader if it is greater than all the elements to its right side. 

we can solve this problem using 

1. two for-loop method(easy)
2. for-loop method(efficient)


```
int[] findLeader(int[] arr) {
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < arr.length; i++) {
      boolean isLeader = true;
      for (int j = i + 1; j < arr.length; j++) {
        if (arr[i] < arr[j]) {
          isLeader = false;
          break;
        }
      }
      if (isLeader) {
        result.add(arr[i]);
      }
    }
    return result.stream().mapToInt(Integer::intValue).toArray();
  }
```
In This method we are going to traverse the array using i loop
,we are going to check is there any element greater than the element present in the i index by using another for loop j

if we find any element greater than that we don't add that to list if not we add that element to the result

>Time Complexity: O(n<sup>2</sup>)

```
int[] findLeaderEfficient(int[] arr) {
    List<Integer> result = new ArrayList<>();
    int currentHigh = arr[arr.length - 1];
    result.add(currentHigh);
    for (int i = arr.length - 1; i > 0; i--) {
      if (arr[i] > currentHigh) {
        result.add(arr[i]);
        currentHigh=arr[i];
      }
    }
    return result.stream().mapToInt(Integer::intValue).toArray();
  }
```
The element present at the last of the array will be in the result because we don't have any element at right side to that

we declare currentHigh with the last element value
we move from right to left
we check is the current number is greater than currentHigh
if yes we add that to result list and set that element as currentHigh, if not we move to the next element.

>Time Complexity: O(n)