teleren/devto huggingface dataset:
Some of my commonly used tool methods
Tags: css, javascript, ticks
Published: 2020-06-20 15:24:08

---
title: Some of my commonly used tool methods
published: true
description: 
tags: CSS, Javascript, Ticks
---

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

### ellipsis text

```scss
@mixin ellipsis($line) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: $line;
  -webkit-box-orient: vertical;
}

.desc{
 @include ellipsis(2) // over 2 line will be fold and show ...
}
```



### Safe decimal

```javascript
import Decimal from 'decimal.js-light'

export default function(value) {
  return new Decimal(value || 0)
}

new Decimal(null) // will be new Decimal(0)
```



### Vuex extend

```javascript
import isArray from 'lodash/isArray'
import Vue from 'vue'

export function setState({ commit }, attrs, value = null) {
  commit('mutationState', attrs, value)
}

/*
 * setState('key',value)
 * setState(['key','value'])
 * setState({key: 'key', value: 'value'})
 * setState([{key: 'key', value: 'value'}])
 */
export function mutationState(state, attrs, value = null) {
  if (value) {
    Vue.set(state, attrs, value)
  } else if (isArray(attrs)) {
    // [{key: 'xx', value: 'xx'}, ['key', 'value']]
    while (attrs.length) {
      const ele = attrs.pop()
      if (isArray(ele)) {
        const [key, value] = ele
        Vue.set(state, key, value)
      } else {
        const { key, value } = ele
        Vue.set(state, key, value)
      }
    }
  } else {
    // setState({key: 'key', value: 'value'})
    const { key, value } = attrs
    Vue.set(state, key, value)
  }
}

// store/user.js
import { mutationState, setState } from '@/utils/vuex'
export const actions = {
  setState
}
export const mutations = {
  mutationState
}

this.$store.dispatch("user/setState",data)
```

 You can use `setState` method to update vuex state values 



### Generate utils class in scss

```scss
@for $i from 1 through 8 {
  .mt-#{$i*4} {
    margin-top: #{$i * 4}px !important;
  }
  .mb-#{$i*4} {
    margin-bottom: #{$i * 4}px !important;
  }
  .pb-#{$i*4} {
    padding-bottom: #{$i * 4}px !important;
  }
  .pt-#{$i*4} {
    padding-top: #{$i * 4}px !important;
  }
  .ml-#{$i*4} {
    margin-left: #{$i * 4}px !important;
  }
  .mr-#{$i*4} {
    margin-right: #{$i * 4}px !important;
  }
}

// will out put css
.mt-4{margin-top:4px}
.mb-4{margin-bottom:4px}
.ml-4{margin-left:4px}
.mr-4{margin-right:4px}
...
.mt-32{margin-top:32px}
.mb-32{margin-bottom:32px}
.ml-32{margin-left:32px}
.mr-32{margin-right:32px}

.pt-4{padding-top:4px}
...
.pt-32{padding-top:32px}

.pb-4{padding-bottom:4px}
...
.pb-32{padding-bottom:32px}
```



More tips you can share in comments



Hope it can help you :)
The Aviator🎮  -  Test your coding and logic skills with a web game
Tags: webdev, javascript, challenge
Published: 2020-06-20 14:58:45

I've always liked challenges and problem-solving. This is the reason that made me embark on a journey into the world of programming.

It started when I was 15, in the high school computer science course, where I wrote my first _`"Hello World"`_. Looking back, I can see the most significant **stages** passed so far, in which I have improved, matured, and in which I can identify a _before_ and _after_.

Now I study computer engineering at university, and I feel I have reached another important stage of this journey. Stage that I want to represent with a project, to test myself and the skills I have gained.

And so was born _The Aviator_, a coding game for folks like me who like to test themselves.

<img src="https://github.com/Paol-imi/the-aviator/blob/master/images/screens/worlds.gif?raw=true" />

4 worlds compose the game. The _Aviator_, the protagonist of this journey, will have to be instructed through code, to overcome the levels of each world.

<img src="https://github.com/Paol-imi/the-aviator/blob/master/images/screens/game.gif?raw=true" />

As with any journey, the difficulty grows over time. Starting from the first simple challenges, the game ends with a last _"impossible"_ level, which represents that stage to reach to mark the beginning of a new part of the journey.

Do you think you can reach it? Well, if you like challenges, what are you waiting for? Test yourself and challenge friends and colleagues 😎

- [**Online Game**](https://paol-imi.github.io/the-aviator/)
- [**Tutorial**](https://paol-imi.github.io/the-aviator/tutorial/#/)

The game is also available on Github.

{% github Paol-imi/the-aviator no-readme %}

---

_As a computer engineering student and creator of this project, I would recommend tools like this as educational support👨‍🎓 in schools and universities. With targeted design choices and an advanced code debugging system (with time travel), The Game tries to provide the best developer experience and guide the student's reasoning in each challenge._

## Special thanks

The inspiration for the protagonist of the game came to me thanks to [this](https://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/) fantastic project, from which I took the name and the sprite of the Aviator.
I turned my website into a template, mostly by git tricks
Tags: nuxt, webdev, git, showdev
Published: 2020-06-20 14:54:12

This was created by

- Move personalized information from every folders to some very specific folders

```sh
/blog/**/*.md # Any deep nesting is possible
/media/
/theme.yml
```

- Separate to two repos, of theme, and of content

```sh
# Shared commands
brew install git-filter-repo # https://github.com/newren/git-filter-repo/blob/main/INSTALL.md
```

```sh
# Content repo
git remote add upstream <GIT_UPSTREAM_URL>
git fetch upstream
git pull upstream master
git remote remove upstream
git filter-repo --path 'blog/**/*.md' --path 'media/' --path theme.yml --force # and other related content folders in the past
git push origin master
```

```sh
# Theme repo
git remote add upstream <GIT_UPSTREAM_URL>
git fetch upstream
git pull upstream master
git remote remove upstream
git filter-repo --invert-paths --path 'blog/**/*.md' --path 'media/' --path theme.yml --force # and other related content folders in the past
echo '/content/' >> .gitignore
git push origin master
```

- Then, add `environmental variables` to Netlify as needed. After, if you working repo git is connected to Netlify

```sh
# Working repo
git remote add upstream <GIT_THEME_URL>
git fetch upstream
git switch -c dev upstream/master
git clone <GIT_CONTENT_URL> content
git push origin dev
git branch -D master
git checkout master
git push -f origin master
```

I also summarized this on GitHub's wiki.

{% github https://github.com/patarapolw/nuxt-blog-template %}

Of course, this is used in a real website -- https://www.polv.cc and the lighthouse score (https://web.dev/measure/) is quite commendable, I think; although there are indeed [rooms to improve](https://github.com/patarapolw/nuxt-blog-template/issues/5).

[![Lighthouse score](https://user-images.githubusercontent.com/21255931/85204182-d91a2380-b33c-11ea-8a82-74b857868d03.png)](https://github.com/patarapolw/nuxt-blog-template/issues/6)
Day-4: WebSocket! Wait, what???
Tags: cybersecurity, javascript, security, blogaday
Published: 2020-06-20 14:48:58

**Day-4:** Okay so I was scrolling on Twitter and read this,![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x48w6yoxefvpv9n5sja0.png) This made me think what the heck is WebSocket? I never heard about it before!👀

Also, he got $8000 as Bug bounty for his submission on another report! Basically, it was somewhat related to Npm token as well as WebSocket hijacking! At first, I watched his WriteUp Video and then read his WriteUp but was not clear so I thought let's understand the concept and then maybe I understand what he wanted to say!

**What is WebSocket?**
- Ohhhh lol, Websocket is just like Http, a communication protocol that enables interaction between a browser and a web server. I thought it was linked with a socket or something (Just Kidding)! 

- WebSocket is especially great for services that require continuous data exchange, e.g. online games, real-time trading systems and so on. For example, Slack’s web app uses WebSocket connections to sync messages in its chat functionality.

- During the lifetime of a WebSocket connection, the client and the server are free to exchange any amount of data without incurring the overhead and latency of using traditional HTTP requests.

- For more good Understanding I prefer you to watch this https://www.youtube.com/watch?v=ZbrEztkwcw8!

**How WebSocket it different from HTTP?**
- https://www.youtube.com/watch?v=i5OVcTdt_OU

**How WebSocket connections are created?**
- A WebSocket connection between a client and a server is established through a WebSocket handshake.
- To open a WebSocket connection, we need to create new WebSocket using the special protocol `ws://` in the URL.
- There's also an encrypted `wss://` protocol. It’s like HTTPS for WebSockets.

**Problems with WebSocket?**
- WebSocket allows an unlimited number of connections to the target server and thus resources on the server can be exhausted because of DOS attack. 
- WebSockets are vulnerable to malicious input data attacks, therefore leading to attacks like Cross-Site Scripting (XSS).
- The Websocket protocol doesn’t handle authorization and/or authentication. Application-level protocols should handle that separately in case sensitive data is being transferred.
- Also, some more problems, Do refer [WebSocket Issues](https://resources.infosecinstitute.com/websocket-security-issues/#gref) for the same!

PS: Now I got Idea what actually WebSocket is, So probably I'll do research about Hijacking WebSockets on Day-5! I hope my notes from different websites are/will helping/help you! Thanks!❤️

---
# **Resources**
**Aseem's WriteUp:** https://medium.com/@aseem.shrey/one-token-to-leak-them-all-the-story-of-a-8000-npm-token-79b13af182a3
**Aseem's WriteUp Video:** [YouTube](https://www.youtube.com/watch?v=9LBl-uFiYUE)
**Javascript Docs:** https://javascript.info/websocket
**Infosecinstitue:** [WebSocket Issues](https://resources.infosecinstitute.com/websocket-security-issues/#gref)


# **Contact:**

Got doubts? Contact me on [Twitter](https://twitter.com/FenilShah1616). 
Feedbacks are welcomed, do comment it down below! :)
Introduction to Progressive Web Applications (PWAs)
Tags: javascript, html, css, progressivewebapps
Published: 2020-06-20 14:35:35

I was honored to deliver a talk on Progressive Web Application courtesy of Microsoft Student Partners.

Fun fact: this was my first technical talk. Below are link to the recorded session, presentation slides, GitHub repo and the PWA we built during demo.

[Recorded Session] (https://bit.ly/3fBYMWS)
[Presentation Slides] (https://bit.ly/2CpKlad)
[PWA App Built During Demo] (https://bit.ly/2YWUNh7) 
[GitHub Repo] (https://bit.ly/2V2kOKO)
How to fix Xcode Playground getting stuck on 'Running'
Tags: xcode, ios, swift, xcodeplayground
Published: 2020-06-20 14:35:00

Sometimes when working on Xcode Playground you may experience some unexpected behavior where Playground gets stuck on 'Running...' without any obvious reason. 🤷:triumph: 

The root cause of this issue is Xcode trying to run the code on a simulator.
By default, when creating a Playground, Xcode will set the platform to iOS and it will open a simulator to run the code. 

So, if you are not working on iOS-specific code, you can solve this by switching the platform on the Playground Settings to `macOS`.

You can change that on the File Inspector tab, which you can either access from the Inspector area or by using the shortcut Command (`⌘`) + Option (`⌥`) + 1.

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

With that change in place, your Playground will compile and run successfully :rocket:

---
➡️ This post was originally published on my [blog](https://diamantidis.github.io).
🤦‍♂️ Blog post became viral then the server crashed
Tags: lesson, fail, viral, server
Published: 2020-06-20 14:26:18

Hey everyone 👋

A few days ago Bootstrap 5 Alpha was officially launched and since we build themes using Bootstrap and we also have a blog we thought it would be a good idea to quickly set up an article and distribute it on our social media, reddit and so on.

After about 1-2 hours of writing the article it was ready. I also created a custom preview image to make it more shareable on social media. Here's the article if you're curious:

[Article about Bootstrap 5 Alpha launch](https://themesberg.com/blog/bootstrap/bootstrap-version-5-alpha-whats-new).

I started to share it on our social media, relevant subreddits, designersnews, hackernews and so on. Little did I know what would happen. With my co-founder, Robert, we even started joking around that it might crash our server lol.

So after sharing it on these multiple platforms the Google Analyics live users was like this: 20, then 50, then 70, then 100, then 130 and so on. I went outside for a couple of minutes and when I got back my colleague told me that he can no longer access Themesberg.

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

I was like... what? This never happened before. So I took a look and indeed, it was not working. Like at all. Anywhere. Started panicking a little since this was a crucial time especially because of the many visitors.

I took a look on our server logs and hundreds of 500 server errors were popping up. The queries no longer worked. The culprit was a stupid query that counted all of our users for every page accessed. I quickly hardcoded the count and later on optimized the whole thing.

### The damage?

Around 700 lost visitors in the 10 minutes while the website was down.

### Lesson learned?

Optimize your queries. Update your hosting. We were on the cheapest plan on Heroku.

We also switched to Cloudflare for DDoS protection because this was a period of security paranoia LOL.

Keep building awesome stuff people,
Zoltan, CEO @ Themesberg
Road to Genius: smart #24
Tags: javascript, beginners, computerscience
Published: 2020-06-20 14:17:13

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

![coding challenge](https://dev-to-uploads.s3.amazonaws.com/i/b67enj10m311nbslg7qa.png)

In this challenge we have to fix four bugs, it's an easy challenge but does require some attention.

The first three lines initialize variables `A, B and C`, the value for `A` is unknown 😈. The 4th line declares `R` using the equation:
`(💚 + B + 💎) / 3;`
This line contains the bugs 💚 and 💎, these are most likely going to be `A` and `C` respectively (`B` in the middle spoils it). The formula appears to be computing the average value of three variables.

Finally we have the buggy line:
`R = 🚀.floor(R);`
The commonly used function `floor` reveals that 🚀 must be JavaScript's `Math` object.

To find our remaining bug 😈, we must reverse engineer `R`, which we know should equal to 4 (given). This can also be written as:
`4 = (A+1+5)/3` with `A` being the unknown 😈.
After rewriting this equation we find that `A = (4*3)-1-5 = 6`. But 6 is not an available answer to select, so we must use another value for 😈. Keep in mind that the value `R` is being floor-rounded on the last line, so basically 😈 can be any value as long `R = 4`. The acceptable answers are 7 and 8, because:
`(7+1+5)/3 = 4.333`  and  `(8+1+5)/3 = 4.666`

![coding challenge answer](https://dev-to-uploads.s3.amazonaws.com/i/zxo84sxaxh9grhv8znhb.png)

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/
Função em PHP para validar CPF
Tags: php
Published: 2020-06-20 14:07:59

Exemplo:

```php
<?php

function validaCPF($cpf) {
 
    // Extrai somente os números
    $cpf = preg_replace( '/[^0-9]/is', '', $cpf );
     
    // Verifica se foi informado todos os digitos corretamente
    if (strlen($cpf) != 11) {
        return false;
    }

    // Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11
    if (preg_match('/(\d)\1{10}/', $cpf)) {
        return false;
    }

    // Faz o calculo para validar o CPF
    for ($t = 9; $t < 11; $t++) {
        for ($d = 0, $c = 0; $c < $t; $c++) {
            $d += $cpf[$c] * (($t + 1) - $c);
        }
        $d = ((10 * $d) % 11) % 10;
        if ($cpf[$c] != $d) {
            return false;
        }
    }
    return true;

}
```
Fonte: https://gist.github.com/rafael-neri/ab3e58803a08cb4def059fce4e3c0e40
98/100 100daysofcode Flutter
Tags: 100daysofcode
Published: 2020-06-20 14:00:49

day 98/100 of #100daysofcode #Flutter
Learning Flutter , courses Udemy from
@maxedapps

Today learn about firebase auto trigger to topic firebase and finishing flutter chat
https://github.com/triyono777/100-days-of-code/blob/master/log.md
DL with PyTorch (Week 3)
Tags: activation, classification, pytorch, cifar10
Published: 2020-06-20 13:28:22

### Done with Assignment 3 🤩🎉😎🎊
Done with all the assignments, now, will be participating in my first Kaggle competition(although it's not open to everyone still there will be a lot of competition from the participants of this course) and will start working on the course project.

This assignment was a part of the 6 week-long free course named, **Deep Learning with PyTorch: Zero to GANs** provided by [Jovian.ml](https://www.jovian.ml/) in collaboration with [FreeCodeCamp](https://www.freecodecamp.org/).

Learned about different *hyperparameter tuning*, *activation functions* and we trained a model using image classification to do **classification of images of everyday objects using neural networks**.

Dataset used: **CIFAR-10**
Accuracy achieved: 55% to 56%

My key ***observations***🧐 during this assignment are mentioned in the compare tab [here](https://jovian.ml/hiteshkumar-1mv17cs042/03-cifar10-feedforward) Have a look at it, especially the [Version-9](https://jovian.ml/hiteshkumar-1mv17cs042/03-cifar10-feedforward/v/9) which contains a random selection of activation functions selected JUST FOR FUN🤪.

To find out what I have been doing in this Lock-down period, click [here](https://technolgee.blogspot.com)
Angular 10/9 ViewChild, ElementRef & AfterViewInit
Tags: angular
Published: 2020-06-20 13:11:01

---
title: Angular 10/9 ViewChild, ElementRef & AfterViewInit
published: true
description: "In this article, we'll see how to use ElementRef, ViewChild decorator, and AfterViewInit life-cycle event for accessing the DOM by example with Angular 10"
tags: angular
cover_image: https://i.imgur.com/7gQ2IPy.jpg
---

In this article, we'll see how to use ElementRef, ViewChild decorator, and AfterViewInit life-cycle event for accessing the DOM by example with Angular 10:

```ts
import { Component, AfterViewInit, OnInit, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit, OnInit {

  name = 'Angular';
  isDisplayed = false;

  @ViewChild("myimg") elementView: ElementRef;

  ngOnInit(){
    this.isDisplayed=true;
  }

  ngAfterViewInit(){
    console.log(this.elementView);
    console.log("client height: " + this.elementView.nativeElement.clientHeight);
    console.log("client width: "+ this.elementView.nativeElement.clientWidth);
  }
}
```

Run the example https://stackblitz.com/edit/angular-10-viewchild-elementref-ngafterviewinit-example

Learn Angular with techiediaries.com
<img  src="https://i.imgur.com/7gQ2IPy.jpg"  />
Randomising CSS with CSS Variables and JS
Tags: css, javascript, webdev, tutorial
Published: 2020-06-20 13:09:25

# Intro

I was watching The Salisbury Poisonings TV show and the credits caught my eye. Behind the actor’s/actress’s names was a box that looked like it was randomly translated/rotated and I wanted to try and recreate the effect on codepen.

## Desired Effect

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

## Final Result

{% codepen https://codepen.io/PeterW570/pen/KKVaozz %}

# How it was done

## HTML

First I made the markup which you can see in the codepen, it was a list, and in each list item was a key and value.

## CSS

For the layout, I made the main container display flex so that I could easily center the list, and then I made each list item a grid with two equal columns.

For the white background behind the ‘value’ divs, I used a pseudo element positioned absolutely to the same size as the div and then put behind the text with a negative `z-index`.

Now for the randomness, I made a `-—random` variable initialised to `0`. Then on the pseudo element background I added:

`transform: scale(1.15) translate(calc(var(--random) * 4px), calc(var(--random) * 2px)) rotateZ(calc(var(--random) * 2deg));`

This scaled it up so that I had a bit of a buffer to be able to translate/rotate it and keep it behind the text. Then I translate and rotate using `calc`s and my variable.

## Javascript 

Now at this point, because the variable is initialised to one, the background will only be scaled and look the same for all of them. This is where some javascript comes in.

```js
function randomise() {
  document
    .querySelectorAll('.value')
    .forEach(el => {
      el.style
        .setProperty(
          '--random',
          Math.random() * 2 - 1
        );
    });
}
```

This sets the CSS variable on each ‘value’ div to a random number between -1 and 1, which is then used in the transforms.

I call this function on initial load and also if you press the randomise button.

# Conclusion

I’m pretty happy with how it turned out. It’s a shame there’s no built in css random number generator (as far as I’m aware) but with a small amount of js we’re able to achieve the same effect!
Resources to get started with Python !
Tags: python, beginners
Published: 2020-06-20 13:03:38

Hi everyone !

Today I will be sharing some awesome resources to learn python for free! 

So, let’s begin 🎉

# Automate the Boring Stuff with Python
This ebook guides us through the various concepts of Python with hands-on, real-world applications.

![Image](https://automatetheboringstuff.com/images/automate_2e_cover.png)
[Link](https://automatetheboringstuff.com/)


# FreeCodeCamp
The tutorial covers most of the basic concepts in Python to get ready for intermediate Python programming.

{% youtube rfscVS0vtbw %}


# GeeksForGeeks
The website has topic-wise listing of the Python concepts. It starts with beginner-friendly topics and also has handled complex topics efficiently.

![Image](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png)
[Link](https://www.geeksforgeeks.org/python-tutorial/)


# Real Python
If you are a real Pythonista, then this is the right place. You can learn Python, take part in quizzes or join with other Pythonistas here.

![Image](https://files.realpython.com/media/real-python-logo-square.28474fda9228.png)
[Link](https://realpython.com/)


# Official Python Documentation
Last but not the least ! The official Python docs. If you are refering them, you are surely a league ahead.

I hope you found this helpful !

# Thanks for reading !