teleren/devto huggingface dataset:
Protecting routes in Angular 👮‍♂️
Tags: angular, routes
Published: 2020-10-24 05:36:40

Protecting specific routes in Angular is a common use-case. Most applications will have some logged in section.

Yesterday we [created a login service](https://daily-dev-tips.com/posts/angular-authenticating-users-from-an-api/), so that someone can log in to our application.

But having this, we are also able to go to the home route not being logged in.

That's weird because we don't have a user and see nothing.

![Home page available](https://cdn.hashnode.com/res/hashnode/image/upload/v1603003313238/FXp0yfcgm.png)

Let's fix that and make `home` a protected route.

## Creating our auth guard

Firs let's open the terminal and generate a new service.

```bash
ng generate service guards/AuthGuard
```

This will generate the `auth.guard` service inside the guards folder.

```js
import { Injectable } from "@angular/core";
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
} from "@angular/router";
import { AuthService } from "../services/auth.service";

@Injectable({providedIn: 'root'});
export class AuthGuardService implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      const currentUser = this.authService.userValue;
      if (currentUser) {
          return true;
      }
      this.router.navigate(['/login']);
      return false;
  }
}
```

We make use of the `CanActivate` method to intercept if this route can become active. We will place this in the routing in a second.

Then we overwrite this actual function and check if we have a current user value in our `authService`.

If we do, it's fine, and the route can return true (valid route).
Else we redirect the user to the login page.

## Implementing the auth guard

To implement the auth guard we just created, we need to modify our `app-routing.module.ts`.

```js
import { AuthGuardService } from './guards/auth-guard.service';

const routes: Routes = [
  // Other routes
  { path: 'home', component: HomeComponent, canActivate: [AuthGuardService] },
];
```

You see it's as simple as passing the `canActive` option with out custom `AuthGuardService`.

Now, if we visit the home page without being logged in, we will be redirected to login.

Once we log in, we will be able to see the page.

![Auth Guard in Angular](https://cdn.hashnode.com/res/hashnode/image/upload/v1603004398467/gyUqRPsIh.gif)

You can also find this code on [GitHub](https://github.com/rebelchris/angular-starter-demo/tree/feature/auth).

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

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
How often have you re-designed your portfolio?
Tags: watercooler, portfolio, ui, ux
Published: 2020-10-24 05:35:33

---
title: How often have you re-designed your portfolio?
published: true
description: 
tags: watercooler, portfolio, ui, ux
cover_image: https://www.iamhrsinclair.com/wp-content/uploads/2019/09/redesign.jpg
---
As for someone who is in the process of making a portfolio, I thought it would be interesting to hear how many visual or structural re-designs you have made to your personal portfolio over the years.

I'm not talking about minor updates and content addition, but major updates that have significantly changed UI and UX.
Why I Chose Software Engineering
Tags: software, engineering, first, blog
Published: 2020-10-24 04:57:22

Programming has been something I've had interest in ever since attending computer science courses in community college. Although I didn't stick with it at the time, after exploring a few different career paths, I can confidently say that software engineering is what I want to do.

The primary reason I want to become a software developer is because I enjoy the process. Figuring out a solution to a problem I was stumped on or working my way through a long project and finally seeing the pieces starting to line up are both examples of things that I get a kick out of. Unlike other areas of study, I find myself looking forward to being able to work through assignments and learn more about programming.

Second, working with technology has always been something I've been good at. Whether it was troubleshooting my internet connection so I could play online video games or taking apart my Xbox to fix the infamous red ring of death myself I have always enjoyed being able to solve problems with electronics. I get the same enjoyment from solving an error in my code that I did when I fixed my broken internet so I could play World of Warcraft as a teen. Working with computers feels natural to me. 

Coding is a skill that I have an aptitude for and an eagerness to learn more about. More than anything, I believe pursuing a career in software engineering is what is best for me.
If it ain't broke
Tags: personal, blog, advice
Published: 2020-10-24 04:47:01

*Originally posted on https://mitchinson.dev/If-It-Aint-Broke/*

I haven't updated my website site in too long, and this post is somewhat of a resolution.

</br>
###If it ain't broke don't fix it
___

- Is the javascript bundle of my portfolio / blog website https://mitchinson.dev larger than it needs to be? Probably.
- Am I using google analytics instead of the more ethical [Plausible](https://plausible.io/open-source-website-analytics), yeah.
- Should future static sites of mine be written in something cool lightweight and new like e11nty, maybe.
- Is my lighthouse score 110%, no. ([It's not toooo gross tho](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fmitchinson.dev)).

</br>
For the last view months during covid, I've had a ton of ideas. Fun things I could make / try. But at the front of my mind I say

> "But first I should redo my website"

</br>
The purpose of my website is for me to be able to post projects I'm proud of and track tech related goals.

Whether the site is fully optimized to Rich Harris standards or not, it gets the job done, and it gets it done well.

<br>

While twitter is great for learning about new tools, it can be easy to be bogged
down into an endless cycle of "you should checkout and use this neat new thing".

--- 

**If you attempt to use every tool designed to make launching a product "easier" and "efficiently", you'll never launch a product.**

---

Now that the barrier of "redoing my website" has been solved with instead 50 lines of markdown, I'm looking forward to smaller more frequent posts. Hopefully hints that others can find valuable about KnexJS, GraphQL, NestJS, React and more.

I'm currently learning rust basics outside of work, to [work on this VR project](https://www.notion.so/bmitchinson/JPGVR-Viewer-5136ef4d51744e73936bb9b1b549b246), and i'd love to know what you think of it.

Stay safe, wear a mask, and please vote.
Creating a blog with Cookiecutter-Django & deploying it to Heroku: Introduction
Tags: django, python, beginners, tutorial
Published: 2020-10-24 04:42:10

# Table of Contents

I. An introduction on the tech stack we're using and how we'd style our blog

II. Creating the blog project

III. Starting a Django App

IV. Model Architecture Planning

V. Creating the models.py, views.py, urls.py, admin.py & the superuser

VI. Testing our app using Unittests

VII. Creating the data and fine-tuning the templates

VIII. Showing Data on the frontend

IX. Deployment to Heroku

## I. Introduction

In this tutorial, I'll walk you through developing a blog using the Cookiecutter-Django framework, storing the projects' static assets in an AWS S3 bucket, and deploying the blog to Heroku. Our blog would have a blog model that we'll call Post, a categories model, a contact form, and a model to showcase our past works or a portfolio page.

We'll then be using [Bootswatch](https://bootswatch.com/darkly/)'s Darkly theme, built on top of the Bootstrap CSS framework for our blog's styles. Feel free to choose a different theme if you prefer to.

#### Homepage

![Homepage](https://dev-to-uploads.s3.amazonaws.com/i/8mqod9ba7vlko6syanva.png)

#### About page

![About page](https://dev-to-uploads.s3.amazonaws.com/i/8nmvt3qc3bjkk8fty4sm.png)

#### Blog detail page

![Blog detail page](https://dev-to-uploads.s3.amazonaws.com/i/br5lgg5te13g49nzhxsz.png)

#### Portfolio page

![Portfolio page](https://dev-to-uploads.s3.amazonaws.com/i/hbbswrh5m6buuz0q4upo.png)

#### Contact page

![Contact page](https://dev-to-uploads.s3.amazonaws.com/i/kiakev54j8asvlrfbqlk.png)


Since we now know how the site would look, let's start creating our models and understand how Django's Model-View-Template architecture works.
JavaScript Rendered Hello World
Tags: react, javascript, beginners, tutorial
Published: 2020-10-24 04:40:15

In this article, we are not going to use React at all. Instead, we are going to use JavaScript to create a `div` [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) element with the text content "Hello World".

**Why we are doing this?**
It's very important to have a basic understanding of how the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) elements are created using JavaScript because it will help you to understand how  React really works under the hood.

**Exercise 1**
```html
<!DOCTYPE html>
<html>
  <head>
    <title>Excercise</title>
  </head>
  <body>
    <!-- create a 'div' element with an id 'root' -->

    <script>
      // create a 'div' element
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

      // set the textContent of div element to 'Hello World'
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

      // append the div element to root div using append method
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append
    </script>
  </body>
</html>
```
**Solution Code (Exercise 1)**
{% codepen https://codepen.io/bipinrajbhar/pen/WNxRpjG %}

**Exercise 2**
```html
<!DOCTYPE html>
<html>
  <head>
    <title>Excercise</title>
  </head>
  <body>
    <script>
      // create a root 'div' element
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

      // set id attribute to 'root' for root div element
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

      // append the root div element to body using append
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append

      // create a 'div' element
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

      // set the textContent of div element to 'Hello World'
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

      // append the div element to root div using append method
      // 📜 https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append
    </script>
  </body>
</html>
```

**Solution Code (Exercise 2)**
{% codepen https://codepen.io/bipinrajbhar/pen/dyXNveE %}

I hope you learned something from this article and if you like this article then do not forget to give heart, unicorn, etc.

My name is **Bipin Rajbhar** and I am a software engineer at [QuikieApps](https://www.quikieapps.com/) and you can follow or connect to me on [Twitter](https://twitter.com/Bipin_1598) and [Linked In](https://www.linkedin.com/in/bipinrajbhar1598/)

**Resources**
[The Beginner's Guide to React](https://egghead.io/courses/the-beginner-s-guide-to-react)
[Epic React](https://epicreact.dev/)
Data Science from Scratch: Intro & Setup
Tags: datascience, machinelearning, python
Published: 2020-10-24 04:07:59

After diving head first into machine learning [roughly 47 days ago](https://twitter.com/paulapivat/status/1319316323663425537), I'm taking a step away from libraries like scikit-learn, tensor flow, even matplotlib and numpy to go back to the basics (note: I provide a rationale [here](http://getwyze.com/44-days-of-data-recap/)). 

Starting with this post, i'll be documenting my progress through [Joel Grus'](https://twitter.com/joelgrus) **Data Science from Scratch** (DSFS). 

As a newcomer to Python (coming from R), it took a minute to understand the Python 2 vs 3, and explore the various tooling options. I tried out Spyder, Pycharm, then finally settled on the Anaconda Distribution platform to access Jupyter notebooks. 

Coming into this book, I knew Joel Grus [didn't like notebooks](https://www.youtube.com/watch?v=7jiPeIFXb6U). 

**edit 10.29.2020**: Jeremy Howard of fast.ai offers a contrasting perspective. He *does* [like notebooks](https://www.youtube.com/watch?v=9Q6sLbz37gk&feature=emb_title).

I'm going to wait till I get to the end of the book to make a personal verdict. As a relative newcomer to Python, i'm not attached to notebooks, but have found some features to be nice (i.e., in-line plotting). I'm open to having my mind changed and I'll take the author at his word. 

He states explicitly that its good discipline to "work in a virtual environment, and never use the 'base' Python installation" (p. 17). Fortunately, I had already gone through the process of setting up Python 3.8.5. My next task was to setup a virtual environment and install IPython. My IDE of choice is VSCode. 

I'm happy to report that the setup process was relatively painless. I learned to setup a virtual environment for any work related to Data Science from Scratch and have started playing around with IPython.

The following are good to know: entering and exiting the virtual environment (I use conda). Entering and exiting an IPython session. Saving the IPython session, specific lines, to a `.py` file. Opening said `.py` file directly from terminal *within* VSCode and making edits. Creating and opening `.py` file within VSCode.

The commands I use to do the following with commented explanation are as follows:

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

In the next post, we'll get into [functions](https://dev.to/paulapivat/higher-order-functions-4k7b).
Dịch vụ viết thuê luận văn - Luận Văn 99
Tags: vietthueluanvan
Published: 2020-10-24 03:58:00

Luận Văn 99 là đơn vị hàng đầu trong cung cấp dịch vụ viết thuê báo cáo, tiểu luận, luận văn giá rẻ - uy tín số 1 trên thị trường. Chúng tôi có kinh nghiệm viết hơn 10000 bài luận lớn nhỏ thuộc đầy đủ chuyên ngành, học vị. Cam kết chất lượng, uy tín.
Hotline: 0989 546 803
Địa chỉ: Tòa Nhà Nam Đô - 609 Trương Định, Thịnh Liệt, Hoàng Mai, Hà Nội 100000
Website: https://luanvan99.com
Does Django need a database?
Tags: django, database
Published: 2020-10-24 03:42:01

Depends on what you are trying to build though in most cases it will require to set up a database if you want to store the data permanently

Django supports a lighter version of database like SQLlite (out of the box) so it's easy to enable the database functionality

To be honest, one of Django strength is handling database, they have an efficient way of handling it using their own ORM, so if your project does not require any database activity there is no point in using Django it may be overkill for your project
Is Django still good?
Tags: django
Published: 2020-10-24 03:39:01

Yes Django still exciting to use especially now they are moving towards full async (though their own ORM and others are not yet in async)

Django template system may not be that exciting after React, Angular, & Vue front end framework came but still, Django is a loosely coupled architecture that you can easily support any type of front end framework.

Django has a huge community and the ecosystem keeps on growing that keep it at least with the current technology
CSS Halloween Faces: Skull
Tags: css, frontend
Published: 2020-10-24 03:38:40

Last time I showed a Ghoul I made with CSS. It was originally planned as a skull but the more it evolved, it turned toward a Ghoul. I still wanted a skull. I started to search for LEGO skull image only to realize I was wearing a skull and cross bones tee. 

I decided I had to change the mouth to get a better skull. The Ghoul mouth was too open and the fangs looked like needles. So The mouth was collapsed to just a line and the teeth were made wider and shorter. `overflow` was changed to visible. So the teeth poked above and below the mouth line.  

```css
.mouth {
	width: 140px;
	height: 10px;
	background: rgb(26 23 23);
	margin-top: 90px;
	border: 4px solid black;
	display: flex;
	justify-content: space-around;
	align-items: center;
	position: relative;
	overflow: visible;
}

.fangs {
	width: 10px;
	height: 30px;
	background:rgb(26 23 23);
	display: flex;
	justify-content: center;
	position: relative;
	z-index: 10;
}

.fangs_bottom {
	width: 10px;
	height: 40px;
	background: rgb(26 23 23);;
	display: flex;
	justify-content: center;
	position: relative;	
} 

```

Next I changed the `background-color` of the nose and mouth to match the eyes. Also changed the page `background-color` to a darker color makes the bone pops off the screen more but without the too sharp contrast of #000 and #fff.

I removed the bridge between the nostrils and shortened the nose over all. I could combine the nostrils into one triangle but like the ability to have separate nostrils. 

```css
.nose_pair {
	position: relative;
	display: flex;
	justify-content: center;
	align-items: center;
}

.leftNostril {
	border-left: 30px solid transparent;
	border-bottom: calc(4 * 14px * 0.8) solid rgb(26 23 23);
	display: inline-block;
	margin-bottom: -70px;
}


.rightNostril {
	border-right: 30px solid transparent; 
	border-bottom: calc(4 * 14px * 0.8) solid rgb(26 23 23);
	display: inline-block;
	margin-bottom: -70px;
}

```

The Skull and the Ghoul.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ggkw0zrpciwnd27mpc72.png)
I continued to work on building a CSS Skull. 
the next step was to remove the bridge from the nose and shorten the nostrils.

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

Have you ever made something cool with CSS? Share it.

-$JarvisScript git push
git rebase
Tags: opensource
Published: 2020-10-24 03:32:13

# how to refactoring code using `git rebase`

I used my repo to practice `git rebase`. First, I created a new branch to do the changes. 
```bash
git checkout -b refactoring master
```
Then I tried to find some improvement in my code. I found four improvements. After I finished each improvement:
```bash
git add .
git commit -m "message"
```

When I finish all my changes. I checked my commits with `git log`, add all the changes are in the log.

All the magic happens next step:

```
git rebase master -i
```
And I squash all other commits which I don't need to show on the log.

```
// change commit message.
git commit --ament
``` 

## merge and push

```bash
git checkout master
git merge refactoring
git push origin master
```
POO: Herencia
Tags: javascript, poo, beginners
Published: 2020-10-24 03:13:50

### **Requerimientos:**
* NodeJS.
* JavaScript básico.
* POO básico.

## ¿Qué es la Herencia?
La herencia es la capacidad que tiene una clase «hija» de "recibir" los métodos y propiedades de una clase «padre».

## Ejemplo

Realizaremos una clase **Humano** la cual sera nuestra clase padre, y como hijo tendremos a la clase **SuperHumano** que heredara todas las propiedades y metodos de **Humano**.

> 👋 Para que una clase herede los atributos de otra tendremos que usar la palabra reservada *extends*.

{% collapsible Humano.js %}
 ```js
class Humano {
    nombre
    edad

    constructor(nombre, edad){
        this.nombre = nombre
        this.edad = edad
    }

    dormir(){
        console.log(this.nombre, 'esta durmiendo...')
    }

    comer(){
        console.log(this.nombre, 'esta comiendo...')
    }

    programar(){
        console.log(this.nombre, 'esta programando...')
    }

    toString(){
        console.log('Class:', this.constructor.name)
        console.log('Nombre:', this.nombre)
        console.log('Edad:', this.edad)
    }
}

module.exports = Humano
```
{% endcollapsible %}

> 👋 Para tener acceso a los métodos de la clase padre tendremos que usar el método reservado *super*, por eso encontraras que a veces se refieren a la clase padre como «SuperClass».

{% collapsible SuperHumano.js %}
 ```js
const Humano = require('./Humano')

class SuperHumano extends Humano{
    poder

    constructor(nombre, edad, poder){
        super(nombre, edad)
        this.poder = poder
    }

    usarPoder(){
        console.log(this.nombre, 'usa su poder de', this.poder)
    }

    toString(){
        super.toString()
        console.log('Poder:', this.poder);
    }
}

module.exports = SuperHumano
```
{% endcollapsible %}

## Lo hicimos! 🚀
Como puedes ver en la clase **SuperHumano** No se declaran los metodos *comer*, *programar* o *dormir* pero podremos hacer uso de ellos gracias a que hereda de nuestra clase **Humano**. ¿Qué tal si lo probamos?


{% collapsible index.js %}
 ```js
const Humano = require('./Humano')
const SuperHumano = require('./SuperHumano')

const humano = new Humano('Ushieru', 20)
humano.toString()
humano.comer()
humano.programar()
humano.dormir()

console.log('\n---------------------------\n')

const superHumano = new SuperHumano('Super Ushieru', 22, 'Volar')
superHumano.toString()
superHumano.comer()
superHumano.programar()
superHumano.dormir()
superHumano.usarPoder()
```
{% endcollapsible %}

## En hora buena! 🎉
Acabamos de crear nuestra primer herencia! Ahora te invito a poner aprueba tus habilidades y usar la herencia en tus proyectos. Cuéntame tu experiencia o deja tus preguntas en comentarios. Suerte Devs! 👩‍💻👨‍💻
Match Valid RGB/RGBA Color String using Range Pattern
Tags: javascript, regex
Published: 2020-10-24 03:06:00

First, we need to match range from `0` to `9`. This range is safe enough so you can just:

``` js
let range = /^[0-9]$/;
```

Then match range from `10` to `99`:

``` js
let range = /^([0-9]|[1-9][0-9])$/;
```

Then match range from `100` to `199`:

``` js
let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9])$/;
```

Then match range from `200` to `249`:

``` js
let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9])$/;
```

Last, match range from `250` to `255`:

``` js
let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5])$/;
```

---

You can narrow down the range pattern using alternative syntax. For example, use `\d` in place of `[0-9]`:

``` js
let range = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|2[0-5]{2})$/;
```

Test it!

``` js
for (let i = -100; i < 300; ++i) {
    if (range.test(i + "")) {
        console.log('[' + i + ']');
    } else {
        console.log(i);
    }
}
```

Matching RGB color string using the range pattern (with permissive white-spaces):

``` js
let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';

let rgb = new RegExp('^rgb\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*\\)$');
```

To match RGBA color string, you need to create alpha range. First, match range from `0` to `1`:

``` js
let alpha = /^(0|1)$/;
```

Then match the decimal point prefixed by `0`:

``` js
let alpha = /^(0|0\.[0-9]+|1)$/;
```

Sometimes, leading zero is not required, so:

``` js
let alpha = /^(0|0?\.[0-9]+|1)$/;
```

Narrow down the pattern:

``` js
let alpha = /^([01]|0?\.\d+)$/;
```

To match RGBA color string:

``` js
let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let alpha = '([01]|0?\\.\\d+)';

let rgb = new RegExp('^rgba\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + alpha + '\\s*\\)$');
```

To match both RGB and RGBA color string:

``` js
let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let alpha = '([01]|0?\\.\\d+)';

let rgb = new RegExp('^(?:rgb\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*\\)|rgba\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + alpha + '\\s*\\))$');
```