teleren/devto huggingface dataset:
Add Google Analytics to a React-based Website
Tags: react, analytics
Published: 2020-08-01 15:30:08

Google provides a *free* web analytics service that can be used to analyze details about the visitors on our website.

**Tracking ID**

- Firstly, we need to have a Google Analytics Account, Go to [Google Analytics](http://www.google.com/analytics/). Once you have signed in to your Google account, click Access Google Analytics, and click Sign up.
-  Fill in your account name, website name, website URL, and select an *Industry Category* and also the *Reporting Time Zone*. 
- Under *Data Sharing Options*, check the boxes next to the options that you want. 
- Click *Get Tracking ID*.

**Configuring the React Project**

In the project where you want to add google analytics follow these steps:

Install *react-ga* package
```
npm install react-ga --save
```
Initializing GA and Tracking Pageviews:
Add the following snippet of code in your Index.js file
```
import ReactGA from 'react-ga';
ReactGA.initialize('UA-tracking-id'); // add your tracking id here.
ReactGA.pageview(window.location.pathname + window.location.search);
```

Deploy the changes.
Now you can view the analytics in [Google Analytics](http://www.google.com/analytics/) account.
Choosing a CSS framework
Tags: css, wecoded, beginners, webdev
Published: 2020-08-01 15:26:44

Once I was done playing with pure CSS and hitting my head every time I had to center div element or resize that <code>img</code>, I heard the words of (not then) magic. CSS FRAMEWORK.

![I died!](https://dev-to-uploads.s3.amazonaws.com/i/1ztv53wnrz49xsksqm2q.png)

You must be wondering, everyone uses Bootstrap, why would I be trying without it?

Okay to be very very honest, I was scared of the most known framework, Bootstrap. That is one of the sole reasons I kept on brewing my tea of web on pure CSS fire. But ever so much of a fun game it was, one can not simply dwell on it forever. 

So I began my hunt for a framework for ME. Bootstrap though was the king of the domain, I had already sidelined it. One of major reasons. The monotony. Most sites were built in Bootstrap, and hence looked basically same.

Few Google searches and after trying different snippets from like of [w3.css](https://www.w3schools.com/w3css/defaulT.asp) and bit of bootstrap(okay, yeah) and a little of Foundation, Pure- I came across the FINAL DESTINATION to my mess- Bulma. 
Bulma was a love at first sight. I scanned their entire official [site](https://bulma.io/) and religiously went through the documentation, made my cheatsheet and few great pages.

I followed a tutorial on Skrimba that is by the way mentioned on Bulma's official page and okay [Skrimba](https://scrimba.com/) is so cool! Literally. The site is so pretty and well innovative methods too! Plus Plus! I just had to stay.

If you are someone looking for a framework for better CSS game, well, Bulma--a pure CSS, no javascript-- framework can be the one for you. 

*I'd be posting few front end development posts with project videos and source codes, covering everything Bulma has and I will share the cheatsheet at the end if you need, so you don't have to struggle through the entire documentation, like I did.*

**If nothing you can follow the videos and fork the code and get few great projects on your profile!**
Don't forget to do your own thing.
Keep designing!

Boba!
I got an ESP32, now what?
Tags: esp32, arduino, hardware
Published: 2020-08-01 15:23:25

Now you're going to install Arduino IDE.

If you already have it installed, you need to go to:

* `File > Preferences`
* Copy `https://dl.espressif.com/dl/package_esp32_index.json` into `Additional Board Manager URLS`
* Click `OK`
* Go to `Tools > Board > Boards Manager...`
* Type esp32 and install `esp32 by Espressif Systems`

Now plug your ESP32 to your computer via the USB port.

Upload whatever example you want to try to make sure your ESP32 works properly, I recommend `Wifi > WiFiScan`.

If you get a permission error while uploading your example, such as : `could not open port /dev/ttyUSB0: [Errno 13] Permission denied: '/dev/ttyUSB0'`

Do `sudo chmod a+rw /dev/ttyUSB0`

Another example you could also try is the `WebServer > HelloServer`

Make sure to change the value of `const char* ssid` to your own SSID (your wifi network's name) and add your wifi's password in `const char* password`.

Upload the code, open the Serial Monitor at a baud rate of **115200**. Then take your ESP32 and press the **EN** button on it to do a reset. You'll now be able to see something like this on the serial monitor if everything goes well:

`-> Connected to Wifi
-> IP address: 192.168.0.00
-> MDNS responder started
-> HTTP server started`

Your web server is online!

Enter the IP address it gave you in your browser and be greeted by your sweet ESP32.
Choosing React Design System /Component Library
Published: 2020-08-01 15:14:57


> 
What's your experience and what do you use? 

Today I've decided to set up my UI design system, do a short research on what would be 
right fit for my use case and once install do a small example.

Checkboxes I wanted to fill:
1.  it's easily compatible with `styled-components`

2. have a wide react UI  ready to use components library

3. it's easy to tweak CSS styles of  #2 (preferably with `styled-components`)

I've stumbled upon a lot of react component libraries but only these ones 
made happy and they left in the last decision steps.

# [Just use styled-components](https://styled-components.com/)

This was my first choice I prefer this one over the others, but I don't want to spend time designing my own it will be just a waste of time. 
I would love to have one but I want to build it over time while I'm working on a project.

Also, I plan to use `styled-component` to overwrite styles of the below whatever UI libraries I choose from. Meaning that I won't import components from below libraries, instead, I will wrap them around styled component and export that. 

# [Ant.Design ](https://ant.design/) 

I liked the design of this one clean, simple, beautiful. A lot of components to choose from and the documentation were just amazing with a wide range of examples.

I was ready to go with this one, but then I heard that voice in my mind 🙃 "Search up for style overwrites with styled comp." its a good practice to do that and it can save you some time. Just search for issues for whatever package you might use 😄.

And there was some tricky integration with styled-components that I found and it did not work all of the time for some components from [ant.design](http://ant.design) - so I decided to continue with my search.

# [Material-UI](https://styled-components.com/)

Oh, this one ☝️ - it's ok. if I was looking for something like this 3 years back I would choose this one but now I just don't like the look of it. One thing that makes me have look at it once again is that I see a lot of people praise it. Will see - still don't like it 😁.

# [Reach-UI](https://reach.tech/)

I'm using this one in a big project and it works great with `styled-components` we have e UI/UX 
senior dev that it's working on our UI library in combination with other react components and it works great. But once again it takes time so setup different components and I don't want to waste time on something that I can have easily (example ant.design) 

This one is light and that's one thing that I can't say about the [ant.design](http://ant.design)  

There is one interesting library that I found Bit, it will extract component library from some of your projects and you can use it later one. I plan to try this one later on when I have built some of my components libraries.

# Conclusion

Not decided yet - I've spent so much time researching and trying examples and can't decide yet.


> 
What's your experience and what do you use?
How does the Internet work?
Tags: webdev, internet, network, codenewbie
Published: 2020-08-01 15:13:27

We all have been using the **Internet in our daily life for communicating, streaming, trading, shopping, sharing, travelling, etc purposes to name a few**. Our lives have been revolving around the usage of the internet where on **average a person uses 31.4 GB per month** (as per The NPD Group Market Analysis) which is at almost 25% increase from the data collected the last year.  Another report suggests **users spend around 2 hours on average per day on social media** and is **nearly 4 hours on average active on the internet**. 

Since we are so much depended on the internet, let's dive deeper into the world of the internet and explore how the internet actually works! 


**Let's start with our favourite Browser first.**

![Browser](https://dev-to-uploads.s3.amazonaws.com/i/ov429lvn1msq4zsv1dzo.png)

A browser is a software application used to **makes a request to the server using URL's and then render the response data**. The modern browsers can also interpret and run code written by other applications too.

**The next big word is URL**

**Uniform Resource Locator or URL** as we commonly know it, helps us to find the server and render the resource of the server. **A URL is a heterogeneous combination of protocols, hostname, path and query string(if any).** Each URL is mapped with a unique IP address of its own. This **IP address is then passed onto the DNS** which takes the IP address and **looks up in different servers**.

![URL](https://dev-to-uploads.s3.amazonaws.com/i/x30hlih6caw7xp3j4ps4.png)

**This brings us to the next set of fancy terms, which is DNS and IP Address.** 


**DNS or Domain Name Server is responsible for converting the human-readable URL (eg: https://codingdeck.com/) into machine-readable IP Address(eg: 104.24.123.112).** This is possible because the DNS system works like a phonebook which maps the name with the number. This entire process is popularly known as **DNS Lookup.**

![DNS Lookup](https://dev-to-uploads.s3.amazonaws.com/i/rgntbxapjzwbcz3eu4vg.png)

Now let's take up these fancy numbers which we called IP Address earlier. **Each computer in order to communicate with other machines over the internet has been allotted with a unique identity which we call as IP address**. We can think of IP address as the physical address where each computer or website resides and in order to visit them, we have to go to their address.


This brings us to the last stage were **using the IP address we hit the Web Server and get back the response data rendered in our browser**, which is nothing but the website we were trying to access. 

This, in short, is how the internet works in the background when we try to access a website or web application from our devices.
What's the best way to deeply clone an object in JavaScript?
Tags: javascript, webdev, discuss, explainlikeimfive
Published: 2020-08-01 14:49:27

I recently attempted a code challenge where I needed to deeply clone an object. Prior to this I learned to do this by converting it to JSON. But according to [this blog post](https://flaviocopes.com/how-to-clone-javascript-object/#deep-copy-vs-shallow-copy), he specifically has JSON Serialization as the wrong way to do this.

The reason for this is:
  > "By doing this you will lose any Javascript property that has no equivalent type in JSON, like Function or Infinity. Any property that’s assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object.

  > Also, some objects are converted to strings, like Date objects for example (also, not taking into account the timezone and defaulting to UTC), Set, Map and many others"

Is there a native way to deeply clone an object in JavaScript? The only approach he listed is by using the Lodash library. All of the other methods are shallow copies.
[medium]Utilizando o reduce da API Streams do Java 8 em um exemplo real
Tags: java, functional
Published: 2020-08-01 14:48:03

Medium link:

https://medium.com/@marceloazvedo/utilizando-o-reduce-da-api-streams-do-java-8-em-um-exemplo-real-61e62b1b5a93?source=friends_link&sk=20d738955e7c49e4ca60a78454b53210
Readable codebase: extract conditions / predicates
Tags: cleancode, kotlin
Published: 2020-08-01 14:47:22

---
title: Readable codebase: extract conditions / predicates
published: true
date: 2020-08-01 14:46:33 UTC
tags: cleancode,kotlin
canonical_url: https://le0nidas.gr/2020/08/01/readable-codebase-extract-conditions-predicates/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/l6gabb22k6vqm0pwau4z.png
---

A quick way to make a codebase more readable is to extract long or complex conditions / predicates to their own functions. The function’s name will explain to the reader what is being checked allowing her to move forward instead of trying to figure out the context or the calculations that are taking place.

#### The task

{% gist https://gist.github.com/le0nidas/fc6bde28aaf0b0ba2c72401c5b90499b %}

#### Completed tasks of the last two days

Lets assume that we have a piece of code that prints all tasks that were created in the last two days and are, as the business experts calls them, completed. Which means that are either `Resolved` or `Cancelled`.

{% gist https://gist.github.com/le0nidas/ec236999793a185a9001182a568625c6 %}

We have two distinct concepts that can be extracted. One that will explain the date calculations and one that will force the business knowledge behind those two statuses.

#### createdInTheLastTwoDays()

The calculations can be extracted to a private function but since we are using [Kotlin](https://kotlinlang.org/) we will extract them to an [extension function](https://kotlinlang.org/docs/reference/extensions.html#extension-functions) to make the code even more readable:

{% gist https://gist.github.com/le0nidas/d908132b509093c5047ca1713ef9e454 %}

#### isCompleted()

Another benefit of having “the mentality of extraction” (yep, I just made it up) is that eventually we will come across a case like the `completed` which is a _business term_ that has not been transferred to the codebase!

So we don’t just make the code more readable but we improve our domain representation and force a rule that until now was known through documentations or, even worse, through conversations only.

{% gist https://gist.github.com/le0nidas/a4ee394eb7b0a112161d96771066aa5b %}

The reader will not have to make any calculations while reading this code or trying to understand why only those statuses are being checked.

The code speaks for itself!
Don't Try This at Work: Exception Driven Fizz Buzz V2
Tags: python
Published: 2020-08-01 14:32:50

So I have decided I will embrace some of my, sometimes, let's call them "less practical ideas". Therefore, I will do this as a series, _Don't try this at work_ or _DTTAW_ for short. My previous and first post of the series was:
{% post fronkan/don-t-try-a-this-at-work-exception-driven-fizz-buzz-4j8d %}

However, I figured I would take on the challenge of removing all if-statements from the code. This was surprisingly easy. The solution:
```python
import sys
import inspect
import traceback

def fizzbuzz(val):
    assert val % 15 != 0
    fizz(val)

def fizz(val):
    assert val % 3 != 0
    buzz(val)

def buzz(val):
    assert val % 5 != 0

def exception_driven_fizzbuzz(val):
    try:
        fizzbuzz(val)
        print(val)
    except AssertionError as e:
        tb = e.__traceback__
        while tb.tb_next:
            tb = tb.tb_next
        print(tb.tb_frame.f_code.co_name)


for val in range(1, 16):
    exception_driven_fizzbuzz(val)
```
The only difference from last time is that we have swapped the if-statements for assert-statements. In doing so we had to flip the logic checks. Instead of detecting that value is divisible by 3 for the fizz function we assert that it is not divisible by 3. Then if it is divisible by 3 an `AssertionError` is raised. As we are using `AssertionError` instead of `ValueErrors` we also had to modify the error type in the except-statement, but that is it!

Small caveat here, the change from if-statement to asserts actually introduces a bug. This bug is triggered only if you run the script using the `-O` flag: `python -O fizzbuzz_v2.py`. If you do, it will just print the numbers instead. The reason is that the `-O` flag runs the script with optimizations, which includes removing all assert-statements. No assert-statements gives no errors and results in no fizzbuzzing.

I hope this post was entertaining and can inspire you to try some unorthodox coding practices (at home of course). It is a fun way to explore the language where you might find some interesting and actually useful insights.
Cheap sudo tricks
Tags: linux, security
Published: 2020-08-01 14:15:40

> It's easier to ask forgiveness than it is to get permission.
> -- Grace Hopper

I've done ops work under various titles for various employers for the last 15 years. If memory serves *every* one of them has given the ops-geeks `sudo` rules that allowed `sudo chmod` and `sudo chown` to run as root, but would choke on a request for `sudo -i`. Here's why that's a stupid policy:


1. Create an SSH key on your local box if you don’t have one already.

2. Connect to a target box, and cd to ~roleaccount.
   If ~roleaccount/.ssh exists, change permissions on it to allow you to read and write. Otherwise, create ~roleaccount/.ssh

3. cd to ~roleaccount/.ssh and `sudo chmod o+wx` authorized_keys.

4. Edit the authorized_keys file to append your public key.

5. Restore permissions on authorized_keys

6. Go up to ~roleaccount and restore permissions on .ssh

7. From your local box: ssh roleaccount@target_host

If you reset permissions correctly, you have just connected directly as roleaccount.

*This isn't a stealthy method of switching to another user, so please be ready to explain yourself if there's an audit.*
Nibbles: nullish coalescing
Tags: javascript
Published: 2020-08-01 14:13:27

The nullish coalescing operator is a logical operator similar to the logical OR operator. The operator will return what is on it's right hand side when the left hand side is nullish, (null or undefined).

## Syntax

```js
const output = leftExpr ?? rightExpr;
```

## Example
{% jsfiddle https://jsfiddle.net/link2twenty/0bnvLj2a/ result js %}

## Support
Current support is all major browsers except IE.

##### Further reading:
[nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)
[caniuse](https://caniuse.com/#feat=mdn-javascript_operators_nullish_coalescing)
[logical OR operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)
I made a Mac/Windows app that lets you Control your Music, Movies and Slides with Hand Gestures (Touch-Free).
Tags: python, machinelearning
Published: 2020-08-01 14:05:08

👋 Hey everyone!

Touchless technology is the future (especially after the Covid-19 pandemic).

So, I made 👋 Zesture, a Mac/Windows app that lets you control your favourite media, entertainment and presentation applications using hand gestures. 


💻  **Supported Apps**
- **Music -** Spotify, Apple Music, Amazon Music.
- **Video -** VLC Media Player.
- **Presentation - Microsoft Powerpoint** and Keynote.


🌐 **Supported Websites (needs Zesture Helper chrome extension as well)**
- **Music -** Spotify (Web Player), YouTube Music, Amazon Music (Web Player) and Deezer.
- **Video -** YouTube and Netflix.


✌️ **Supported Actions:**
- Play/Pause.
- Next/Previous Track.
- Enter/Exit Fullscreen.
- Forward/Rewind.
- Mute/Unmute.
- Volume Up/Down.


🤩 **Highlights**:
- Control media in the background while you are checking your emails or doing some other work
- Control your screen from a distance
- Groove to your favourite music while cooking without the fear of your screen getting dirty
- Enjoy exercising while listening to music or watching videos
- Control your Presentation staying away from your laptop
- No extra hardware needed


⬇️ Download it now to get a 7-day free trial (**no credit card required**). 


**Privacy:** *Using your webcam is totally secure. Gesture recognition is done locally on your computer and hence we don't record, save or send any images or videos at all. Your camera is turned off automatically after a certain period of inactivity (configurable via the app).*


🙏 We’d love to get your feedback and look forward to answering any questions!
Comparing Crystal’s concurrency with that of Go (Part II)
Tags: go, crystal, ruby
Published: 2021-07-24 17:04:59

---
title: Comparing Crystal’s concurrency with that of Go (Part II)
published: true
date: 2020-08-01 14:03:50 UTC
tags: golang,crystal,ruby
canonical_url: 
---

[![](https://cdn-images-1.medium.com/max/1000/0*HzrvQ9UCByp4-LcE.jpg)](https://itnext.io/comparing-crystals-concurrency-with-that-of-go-part-ii-89049701b1a5?source=rss-9a53804556------2)

In the first part of this article series, I focused on comparing Crystal and Go’s concurrency from Communicating Sequential Processes…

[Continue reading on ITNEXT »](https://itnext.io/comparing-crystals-concurrency-with-that-of-go-part-ii-89049701b1a5?source=rss-9a53804556------2)
Handling large DOM with Angular
Tags: angular, performance, discuss
Published: 2020-07-31 09:29:28

Have you noticed that creating (i.e. instanciating) 1000 components is not instant in Anguar? 

It kind of suprised me that this takes ~300ms on Chrome on my rather decent laptop. Depending on worse hardware and/or more complex components, this number might be larger and is well above the "instant" threshold of 200ms (see e.g. [here](https://www.smashingmagazine.com/2015/09/why-performance-matters-the-perception-of-time/)).

It is known that a bloated DOM makes any web app sluggish - no difference for Angular. But you reach 1000 components rather fast, e.g. with a table with 30 rows and 30 components in each row. I know 30 components per row is not really small, but when nesting some stuff for reusability, this is reached easily.

To reproduce this without a complex app, I created https://daniel-sc.github.io/smartlook-performance-showcase/ (just ignore the stuff about smartlook).

*This still leaves me kind of puzzled, any ideas what might be the cause or meaningful optimization? Please comment!!*

## Defer initialization

One possible workaround, is to defer the initialization of each row. This does not block the UI and the parent component could be rendered immediately, but comes at the cost of a higher total CPU usage, as all rows are added sepaerately to the DOM, hence the browser must run the layouting for each row instead of only once.

```typescript
@Directive({
  selector: '[appDeferInit]'
})
export class DeferInitDirective implements OnInit {

  constructor(private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef) {
  }

  ngOnInit(): void {
    setTimeout(() => {
      this.viewContainer.createEmbeddedView(this.templateRef).markForCheck();
    });
  }
}
```

Usage:
```html
<div class="row" *ngFor="let r of rows">
   <app-my-row-component *appDeferInit></app-my-row-component>
</div>
```