teleren/devto huggingface dataset:
My existential problem as a beginner "nav" = "a"?
Published: 2020-11-17 00:40:38

When I heard that the "nav" element was used to navigate and previously I have learned that the "a" element was used to navigate between pages I was confused, I thought that they both served the same purpose or had the same function, then I investigated in FreeCampCode and MND and I could see that they are definitely not the same.
Nav is used to allocate a space or section on your web page to navigate and nested within nav is an "a" which is the link that makes the jump. You can find more information [`nav`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav)

e.g.
```html
<nav>       
   <ul>
       <li><a href="Https://mytoping">menu toping </a></li>           
       <li><a href="Https://mycupon">menu coupon </a></li>              
   </ul>
</nav>
```

The structure of the "a" element should at least have the "href" attribute, they always go in the opening tag followed by the "=" sign and the assigned value.
The value can be a URL for external links or an id of another html element to create internal links

e.g.
```html
<a href="http://AnyLink">any page</a>
```

Basically "nav" is the box that nests the element "a" which are the internal or external links that make the jump to somewhere
Tracking Time with React Hooks
Tags: javascript, react, time, datefns
Published: 2020-11-17 00:18:37

## Let's Talk About Time

Time is super tricky to account for in software, and one of the most common issues in frontend applications is developers forget that time keeps passing when the page is open.

> Take a look at [Falsehoods programmers believe about time](https://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time) for a starting point on the assumptions developers make.

It's really common to write a component that looks like this:

```js
const formatter = new Intl.DateTimeFormat("en-us", {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
});

const MyDateComponent = () => {
  const date = new Date();

  return formatter.format(date);
};
```

> See [MDN Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) for more on the date formatter used.

The issue with this component is that it doesn't update when the seconds change. This isn't as much an issue if we're not displaying seconds, but even hours and days can pass while browser tabs are open.

## `useDateTime`

To solve this problem, I wrote `useDateTime`, a React hook that tracks the time to a specified precision (second/minute/hour/day), triggering a state change on each `tick`.

Using `useDateTime` to fix `MyDateComponent`, we get the following:

```js
const MyDateComponent = () => {
  const date = useDateTime("second"); // second | minute | hour | day

  return formatter.format(date);
};
```

This component now updates every second, keeping it accurate. We probably only want updates for every second in a clock component, and should avoid this frequency of updates for expensive renders. Outside of clocks, updating by the hour/day is much more common and something we should plan for as frontend engineers.

You can take a look at the implementation of `useDateTime` in this codesandbox:

{% codesandbox usedatetime-example-icfmq module=/src/use-datetime.js view=editor %}

_The implementation uses [`date-fns`](https://github.com/date-fns/date-fns) but could be rewritten with any date library (e.g. Moment/Luxon/Day.js)_

> A similar hook could be used to track relative times by modifying `msUntilNext` to determine the next `tick` in increasing intervals.

### Disclaimer

This component _attempts_ to update immediately after the next `tick` at the specified precision. Javascript's `setTimeout` API does not guarantee that the timeout will trigger precisely on the target time, so the precision of this hook is also limited. Here's a good [Stack Overflow Q&A](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript) summarizing this problem and a workaround.
How to remove an element at a specific position or index from an array in JavaScript?
Tags: javascript
Published: 2020-11-17 00:00:00

---
  title: How to remove an element at a specific position or index from an array in JavaScript?
  published: true
  tags: JavaScript
  date: Tue Nov 17 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/remove-element-at-specific-position-from-array-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-1592bfce9c1198f6e41975956da8b93f.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/remove-element-at-specific-position-from-array-javascript)
  
To remove elements or items from any position in an array, you can use the `splice()` array method in JavaScript.

- [Jump to full code](#full-code)

Consider this array of numbers,

```js
// number array
const numArr = [23, 45, 67, 89];
```

What if we need to remove the element at index `1` in the array, in our case `45`.

We can do that with the `splice()` array method. The method can be used to delete a group of elements from an array, starting from a particular index.

We can define the starting point to start deleting elements from the array by passing an `index` number as the first argument to the method.

In our case let's remove `45` which is at index `1`.

```js
// number array
const numArr = [23, 45, 67, 89];

// remove element 45
// at index 1
// But this is wrong ❌ for our case
numArr.splice(1);

console.log(numArr); // [23] 😕
```

But the problem with the above code is since we defined only the starting point it starts deleting elements from the array and we lost the last 2 elements `67, and 89` along with `45`.

This can be solved by passing another number as the second argument to the method which is the number of elements to be deleted from the starting position. 😃

In our case, we don't need to delete any other elements other than the number `45` at index `1`. So let's pass `1` as the second argument to the method to delete only 1 element from the staring position like this,

<a name="full-code"></a>

```js
// number array
const numArr = [23, 45, 67, 89];

// remove element 45
// at index 1 and
// pass 1 as second argument
// to tell method to
// delete 1 element
// from the starting index
numArr.splice(1, 1);

console.log(numArr); // [23, 67, 89]
```

Yay! 🌟. We removed only one element from the array 😃.

See this example live in [JSBin](https://jsbin.com/dijucemafu/2/edit?js,console).

Also, if you need the deleted elements from the array the method returns an array of deleted elements from the array.

```js
// number array
const numArr = [23, 45, 67, 89];

// remove element 45
// at index 1 and
// pass 1 as second argument
// to tell method to
// delete 1 element
// from the starting index
const deletedElements = numArr.splice(1, 1);

console.log(numArr); // [23, 67, 89]
console.log(deletedElements); // [45]
```

### Feel free to share if you found this useful 😃.

---
Querying top requested URL's using Kusto and Log Analytics in Azure Application Insights
Tags: azure, apm, logging
Published: 2020-11-23 16:15:39

---
title: Querying top requested URL's using Kusto and Log Analytics in Azure Application Insights
published: true
date: 2020-11-17 00:00:00 UTC
tags: azure, apm, logging
canonical_url: https://swimburger.net/blog/azure/querying-top-requested-urls-using-kusto-and-log-analytics-in-azure-application-insights
---

When you integrate Azure Application Insights into your web applications, a lot of telemetry is captured and made available for querying and visualizing. HTTP requests are one of those datapoints stored in the underlying Log Analytics workspace. One query many webmasters and content editors are interested in is which URL's are most popular.

Many analytics products will also answer this question, but those analytics programs usually rely on JavaScript, iframes, and 1-pixel images. Meanwhile, Azure Application Insights can answer the same question, but its data comes from back-end telemetry and can include request telemetry of static files as well.

## Querying top requested URL's

Navigate to your Application Insights resource in the Azure Portal:

 ![Screenshot of an Azure Application Insights resource](https://swimburger.net/media/qn0ozjth/application-insights-resource.png)

Navigate to the 'Logs' section:

 ![Screenshot of Azure Application Insights Log Analytics workspace querying 404&#x27;s](https://swimburger.net/media/gdpbboih/application-insights-404-log-query.png)

Inside of the query editor, copy/paste the following Kusto query:

```
requests
| where resultCode == 200
| summarize Count=sum(itemCount) by url
| sort by Count 

```

This query does the following:

- fetch requests from the ' **requests**' table. This is the table where HTTP requests are stored.
- filter to requests that resulted in a 200 HTTP Status response.
- Group the requests by **'url'.** Sum-aggregate the request rows by the ' **itemCount**' property. 'itemCount' will be 1 or higher depending on how the requests were sampled. If similar requests were sampled, they are rolled into a single row and the 'itemCount' is increased.
- Sort descending by the aggregated ' **Count**'.

The result will be a table where every URL represents a row and you can see the number of requests made to that URL resulting in 200 HTTP response. You can use this data to find your most popular/request URL's.

Optionally, you can improve this query by filtering out HTTP requests made by bots. There's a property in the requests dataset called "operation\_SyntheticSource" which will be equal to "Bot" if it determines the request was made by a bot. This doesn't mean that if the property is not equal to "Bot", that you can be 100% sure the request wasn't made by a bot.  
The query including the bot filtering looks like this:

```
requests
| where resultCode == 200
| where operation\_SyntheticSource != "Bot"
| summarize Count=sum(itemCount) by url
| sort by Count 

```
S1E7 Learn JMeter Series - HTTP Header Manager
Tags: performance, tutorial, testing, webperf
Published: 2020-11-16 23:40:19

Welcome to Learn JMeter Series!

In this season one, episode seven, you will learn the following:

* HTTP Header Manager

{% youtube 2zvfnTaMeuM %}

✔ [Buy me a tea 🍵](https://www.buymeacoffee.com/qainsights)
✔ [My Blog](https://qainsights.com)
✔ [My Udemy Course](https://www.udemy.com/course/performance-testing-using-truweb)
RxJS Tip: Creation Function: from()
Tags: angular, rxjs
Published: 2020-11-16 23:37:39

The RxJS `from` function is a creation function that iterates an object and emits its values.

# How Does It Work?
The `from` creation function can convert many kinds of things to an Observable. It can take in an array, a promise, or other iterable object. It creates an Observable, iterates the provided object emitting its values, and completes.

The Observable created with `from` is generally synchronous, meaning the values are iterated and emitted, and the Observable completes immediately after it is subscribed.

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

The above example passes an array of three strings to the `from` function and subscribes.

The `from` iterates the array, emitting each of the three array elements which are logged.

# How About Some Examples?
This example iterates an array, emitting each of its elements.
```typescript
// Array: Iterates and emits the elements
from([42, 72, 21]).subscribe(x => console.log(x)); // 42,72,21
```

The following example iterates the characters of a string.
```typescript
/ String: Iterates and emits the characters
from('Apple1').subscribe(x => console.log(x)); // A,p,p,l,e,1 
```

This example emits the result of a promise.
```typescript
// Promise: Emits the fulfilled result of the promise
const p = new Promise( ( resolve, reject ) => {
  resolve( "Apple1" );
  reject( "Error" );
} );
from(p).subscribe(x => console.log(x)); // Apple1
```

# What Are Some Common Uses?
In addition to converting other structures to Observables, here are some common uses of the `from` creation function.

Sample code to try out a pipeline of operations when working with an array.
```typescript
from([1, 2, 3])
```

User selects items for processing (ids of products in a cart, ids of selected songs for a playlist, etc.), managed as an array.
```typescript
from([45, 72, 21])
```

# Where's the Code?
Here is a [link to sample code](https://stackblitz.com/edit/rxjs-from-deborahk) demonstrating the `from` creation function. Feel free to fork it and try it out.

# What About the Marble Diagram?
This is the `from` creation function shown on a marble diagram:

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

Thanks to @michael_hladky for this marble diagram.

Do you have another common use of `from`? If so, please leave a comment.

Enjoy!
Rust vs Go - Load testing  webserv (>400k req/s)
Tags: rust, webdev, go, tutorial
Published: 2020-11-16 23:12:33

**TLDR:** Go can reach 270k req/s where Rust can hit 400k req/s.

## Go server
Let's go straight to buisness with a minimal server sample using [httprouter](https://github.com/julienschmidt/httprouter).

```go
package main

import (
    "fmt"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!")
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)

    http.ListenAndServe(":8080", router)
}
```

## Rust
For the Rust server we'll use [Actix](https://github.com/actix/actix-web) as our framework of choice, down below is the minimal sample.

```rust
use actix_web::{web, Responder, middleware, App, HttpServer};

async fn health_check() -> impl Responder {
    "Welcome!"
}

fn routes(cfg: &mut web::ServiceConfig) {
    cfg.route("/health", web::get().to(health_check));
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let serv = HttpServer::new(move || {
        App::new()
            .wrap(middleware::Compress::default())
            .configure(routes)
    });
    serv.bind("127.0.0.1:8080")?
        .run()
        .await
}
```

## Benchmark
To put a big load on both our servers, we're going to use [wrk](https://github.com/wg/wrk).

_the benchmarks are performed on a i7-8750H (6c, 12threads)_

```bash
wrk -t12 -c1000 -d15s http://127.0.0.1:8080/
```

## Results
#### Rust:
```
Running 15s test @ http://127.0.0.1:8080/
  12 threads and 1000 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     3.73ms    4.70ms  57.76ms   85.86%
    Req/Sec    33.66k     5.80k   69.35k    71.65%
  6039978 requests in 15.10s, 714.26MB read
Requests/sec: 400095.92
Transfer/sec:     47.31MB
```

#### Go:
```
Running 15s test @ http://127.0.0.1:8080/
  12 threads and 1000 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     5.03ms    6.11ms 102.78ms   86.66%
    Req/Sec    22.81k     4.77k   53.73k    71.19%
  4087276 requests in 15.10s, 487.24MB read
Requests/sec: 270691.36
Transfer/sec:     32.27MB
```

The results speak for themselves... 400.000 vs 270.000 for Rust and Go respectively.

## Conclusion
While Go might be easier to write and faster to compile compared to Rust, it's still slower compared to its competitors.

If you're hesitating, let me give you this advice: _use rust if you want speed, else go with Go_.

###### Cover image from [dzone](https://dzone.com/articles/a-detailed-comparison-between-top-programming-lang).
PHP - Create your own PHP template engine
Tags: php, laravel, html, tutorial
Published: 2020-11-16 23:08:13

Ideal for small project :

```php
<?php

namespace DevCoder;

/**
 * Class Template
 * @package DevCoder
 */
class Template
{
    /**
     * @var string
     */
    private $path;

    /**
     * @var array
     */
    private $parameters = [];

    /**
     * Template constructor.
     * @param string $path
     * @param array $parameters
     */
    public function __construct(string $path, array $parameters = [])
    {
        $this->path = rtrim($path, '/').'/';
        $this->parameters = $parameters;
    }

    /**
     * @param string $view
     * @param array $context
     * @return string
     * @throws \Exception
     */
    public function render(string $view, array $context = []): string
    {
        if (!file_exists($file = $this->path.$view)) {
            throw new \Exception(sprintf('The file %s could not be found.', $view));
        }

        extract(array_merge($context, ['template' => $this]));

        ob_start();

        include ($file);

        return ob_get_clean();
    }

    /**
     * @param string $key
     * @return mixed
     */
    public function get(string $key)
    {
        return $this->parameters[$key] ?? null;
    }
}
```
Easy to use:

``` php
$template = new Template('var/www/html/project/template', []);
echo $template->render('home-page.php');
```
With parameters:
``` php
$template = new Template('var/www/html/project/template', ['lang' => 'fr']);
echo $template->render('home-page.php', ['title' => 'Home Page']);
```

``` php
<!doctype html>
<html lang="<?php echo $template->get('lang'); ?>">
<head>
  <meta charset="utf-8">
  <title><?php echo $title; ?></title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
  ...
  <!-- Le reste du contenu -->
  ...
</body>
</html>
```

[https://github.com/devcoder-xyz/php-template-engine](https://github.com/devcoder-xyz/php-template-engine)
RxJS Tip: Creation Function: of() 
Tags: angular, rxjs
Published: 2020-11-16 23:08:07

The RxJS `of` function is a creation function that emits specified values.

# How Does It Work?
The `of` creation function takes in a set of values, creates an Observable that emits those values, and completes.

The Observable created with `of` is synchronous, meaning the values are emitted and it completes immediately after it is subscribed.

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

The above example passes three strings to the `of` function and subscribes.

Each of the three strings are then emitted and logged.

# What Are Some Common Uses?
Sample code to try out a pipeline of operations.
```typescript
of(1, 2, 3)
```

User selects items for processing (ids of products in a cart, ids of selected songs for a playlist, etc.) and those items are emitted from an Observable.
```typescript
of(45, 72, 21)
```

For branching when one branch returns an Observable and another returns a static value as an Observable (such as null, an empty array, or an initialized value).
```typescript
of(null)
of({})
of(this.initializedProduct())
```

As a more concrete example of branching:
```typescript
  getProduct(id: number): Observable<Product> {
    if (id === 0) {
      return of(this.initializeProduct()); // <-- of() used here
    }
    const url = `${this.productsUrl}/${id}`;
    return this.http.get<Product>(url)
      .pipe(
        tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError)
      );
  }
```
This ensures that each branch returns an Observable.

NOTE: This example is meant to show usage of of() and is NOT meant to show the best technique to accomplish this objective.

# Where's the Code?
Here is a [link to sample code](https://stackblitz.com/edit/rxjs-of-deborahk) demonstrating the `of` creation function. Feel free to fork it and try it out.

# What About the Marble Diagram?
This is the `of` creation function shown on a marble diagram:
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x3p0veau0kmiex63vi2d.jpg)
Thanks to @michael_hladky for this marble diagram.

Do you have another common use of `of`? If so, please leave a comment.

Enjoy!
Making things look a bit better! Journal #2
Tags: 100daysofcode, codenewbie, webdev
Published: 2020-11-16 23:07:05

This week I worked a lot on my JavaScript skills, but still have a long way to go! I added some more styling to my Portfolio webpage with a bit of the CSS I learned and started adding some of the JavaScript, but hit a wall when trying to make multiple Modal windows. I was hoping to achieve the desired outcome with as little code as possible, but it's looking a bit more complicated than I thought it would be. I would sit and here and solve it, but today I studied a lot and I'm a bit tired (hahaha), so I'll leave that for tomorrow and post the result on next week's Journal.

I've learned a lot with the JS course on Udemy, by Jonas Schmedtmann, definitely an amazing teacher. I've been doing a lot of research as well, trying to get things solved without a teacher or browsing through Stack Overflow looking for other people's issues and trying to reproduce and solve them. CodeWars is an amazing website for developing problem solving skills too!

It is indeed a really challenging journey, but I'm excited! Sometimes it feels like there is too much to learn and I feel overwhelmed, but then I take a couple steps back and just try to focus on what I'm struggling right now to reinforce it, before moving forward with learning.

This is it for tonight! See you guys next week! Much love!

Link to my portfolio: https://filipeqm94.github.io/portifolio/

I should soon add the couple games I made with JS in there.
RxJS Tip: Use a Creation Function
Tags: angular, rxjs
Published: 2020-11-16 22:34:22

Some of the Angular features, such as Http, automatically create and return Observables. But in some cases, you may want to create your own Observables.

Create your own Observable using a **creation function**.

# What Is a Creation Function?
A **creation function** is an RxJS library function that takes in arguments and returns an Observable.

You can create an Observable from a set, an array, a timer, keyboard events, mouse events, and much more.

This series covers the more common creation functions.
I need help me!!! React Native
Published: 2020-11-16 22:33:04

I am developing a cryptocurrency wallet. The problem I have today is in SingUp, more precisely in redirecting when verifying the account. The app has a wizard for creating accounts, among these steps, I need to verify the email through a link that is sent to the user's email. From the wallet, I put the email, then we give it to verify email and here is the problem, I need from the wallet app to go to the email app installed on the phone, enter the link, click on the link so that the user is verified and automatically return the focus to the wallet app but I can't do it, can you help me?

Thanksssss