teleren/devto huggingface dataset:
object oriented programming in Javascript (part 1)
Tags: javascript, programming, tutorial, beginners
Published: 2022-03-26 22:12:22

Object oriented programming, oop for short is a programming paradigm that can be used in Javascript

## What is a programming paradigm
a programming paradigm is a style or way of solving a certain problem in a programming language, it defines how you think about the solution and oop is a very popular paradigm that can be used in almost any programming language including Javascript

## How to design a solution using oop
in object oriented programming, just like the name implies we heavily use objects to implement the solution, we think about the different entities or logical real-world parts involved in it and store the data and logic for each entity in it's own object
#### Example: A restaurant app
to design a restaurant application for food ordering the oop way we break it down to it's logical entites or parts
- Customers
- Food
- Food categories
- Order
- Restaurants

(at least that's how i would define it's entities you might do it in another way but you get the point)

then we implement each object with the business logic and properties it requires

## oop in Javascript
to create an object for each entity of the app we first need to create a blueprint or plan for it that contains all the props and methods that must be in the object then we create the actual object following exactly that blueprint
objects that are created from an entity blueprint are called instances of that entity

## Creating the blueprint for an entity
in javascript there are 3 ways of creating a blueprint

- constructor functions
- ES6 classes
- Object.create()

### Constructor functions
they are just simple Javascript functions that we call to create the actual object
### Example
we will create a constructor function (blueprint) for the Customer entity mentioned in the previous example

``` javascript
function Customer(name, email, password, settings, cart) {
  this.name = name;
  this.email = email;
  this.password = password;
  this.settings = settings;
  this.cart = cart;
}
```
as you can see the function takes the necessary props to create a customer then attaches them to the customer object which is the this variable inside the function

now to create a customer from that prototype we simply do:

``` javascript
const customer = new Customer("Alex", "alex@gmail.com", "12", {});
```
now customer should be an object representing a customer in our food application having the given data

``` javascript
console.log(customer.name); // Alex

console.log(customer.email); // alex@gmail.com

console.log(customer.password); // 12

console.log(customer.settings); // {}
```

in the next post i will explain that weird new keyword used with the function call and why we use this inside the function body then we will add some methods to the Customer blueprint
Day 14 of 100 Days of Code
Tags: javascript, webdev, beginners
Published: 2022-03-26 21:28:33

This is the final part of the chrome extension build along. The concepts I learnt were

- Const

- addEventListener()

- innerHtml

- inputvalue

- function parameters

- Template Strings

- Local Storage

- JSON objects (JSON.Stringify & JSON.Parse)

- Objects in arrays

In the [part 2](https://nkem.hashnode.dev/day-13-of-100-days-of-code), the extension did not have local storage so it was not persistent after the browser was closed. That means when the browser is closed, whatever data is put in the chrome extension would be gone. Hence the essence of the local storage. 
The HTML page two more buttons added to it. The Save tab and the Delete Button. The **Save** button saves the value in the text box into the local storage. The **SaveTab** button retrieves URL into the textbox while the **Delete** button is for clearing the values in the box and the local storage. Below is the HTML snippet.

```
<html>
    <head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <input type="text" id="input-el">
        <button id="input-btn">SAVE INPUT</button>
        <button id="tab-btn">SAVE TAB</button>
        <button id="delete-btn">DELETE ALL</button>
        <ul id="ul-el">
        </ul>
        <script src="index.js"></script>
    </body>
</html>
``` 
Javascript code

```
let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")
const deleteBtn = document.getElementById("delete-btn")
const leadsFromLocalStorage = JSON.parse( localStorage.getItem("myLeads") )
const tabBtn = document.getElementById("tab-btn")

if (leadsFromLocalStorage) {
    myLeads = leadsFromLocalStorage
    render(myLeads)
}

tabBtn.addEventListener("click", function(){    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        myLeads.push(tabs[0].url)
        localStorage.setItem("myLeads", JSON.stringify(myLeads) )
        render(myLeads)
    })
})

function render(leads) {
    let listItems = ""
    for (let i = 0; i < leads.length; i++) {
        listItems += `
            <li>
                <a target='_blank' href='${leads[i]}'>
                    ${leads[i]}
                </a>
            </li>
        `
    }
    ulEl.innerHTML = listItems
}
```
i3wm Screenshot Shortcuts
Tags: i3wm, linux
Published: 2022-03-26 20:53:35

Have excellent screenshot shortcuts in your [i3wm](https://i3wm.org/).

| Feature | Shortcut |
| :----- | :------ |
| Full Screen | `PrtScrn` |
| Selection | `Shift` + `PrtScrn` |
| Active Window | `Super` + `PrtScrn` |
| Clipboard Full Screen | `Ctrl` + `PrtScrn` |
| Clipboard Selection | `Ctrl` + `Shift` + `PrtScrn` |
| Clipboard Active Window | `Ctrl` + `Super` + `PrtScrn` |

> All the screenshots are saved on `~/Pictures/CURRENT_DATE`.
> The key `super` refers to the modifier key (window/command or alt by default depending on config).

## Requirements

- `maim`
- `xclip`
- `xdotool`

## Set-up

Set this on your i3 config file `~/.i3/config`.

```
## Screenshots
bindsym Print exec --no-startup-id maim "/home/$USER/Pictures/$(date)"
bindsym $mod+Print exec --no-startup-id maim --window $(xdotool getactivewindow) "/home/$USER/Pictures/$(date)"
bindsym Shift+Print exec --no-startup-id maim --select "/home/$USER/Pictures/$(date)"

## Clipboard Screenshots
bindsym Ctrl+Print exec --no-startup-id maim | xclip -selection clipboard -t image/png
bindsym Ctrl+$mod+Print exec --no-startup-id maim --window $(xdotool getactivewindow) | xclip -selection clipboard -t image/png
bindsym Ctrl+Shift+Print exec --no-startup-id maim --select | xclip -selection clipboard -t image/png
```

> You may want to remove the default or any other screenshot shortcuts to prevent errors.
> Don't forget to reload your window manager `super`+ `shift`+ `c`.

---

> The source of this information is from my gist [_My i3 shortcuts to take screenshots_](https://gist.github.com/dianjuar/ee774561a8bc02b077989bc17424a19f).
A chart walks into a bar: Altair vs. leather
Tags: python, datavisualization, altair, leather
Published: 2022-03-26 20:47:40

In this blog post series, we're going to compare two Data Visualization packages in the Python landscape. We will create a bar chart from dummy data, based on [this example available in the Altair documentation](https://altair-viz.github.io/gallery/simple_bar_chart.html), with each package. Furthermore, we will try to follow the most straightforward implementation to compare the two APIs/charts from their defaults.

For this first installment, let's create a bar chart using [Altair](https://github.com/altair-viz/altair) and then [leather](https://github.com/wireservice/leather). The dataset looks like this:

```python
import pandas as pd

source = pd.DataFrame(
    {
        "a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
        "b": [28, 55, 43, 91, 81, 53, 19, 87, 52],
    }
)
```

From the `source` above, we can define a bar chart in Altair via the following snippet:

```python
import altair as alt

alt.Chart(source).mark_bar().encode(x="a", y="b")
```

When we run the snippet above, we get the result below:

![Bar chart created with Altair](https://res.cloudinary.com/dnhtjs74d/image/upload/v1648324433/blog/altair_oroodi.png)

Now, using leather, we get a similar bar chart as follows:

```python
import leather

chart = leather.Chart()

# We cannot use a pandas DataFrame directly.
chart.add_columns(data=source.to_records(index=False).tolist())

chart.to_svg()
```

![Bar chart created with leather](https://res.cloudinary.com/dnhtjs74d/image/upload/v1648324433/blog/leather_ciwdtm.png)

Comparing the two (default) outputs, we can highlight a number of differences:

- The default width is larger with leather. As a result, the bars are also wider.
- In leather, the bars are red (`#e41a1c`), compared to blue in Altair.
- The bar chart created with leather does not show titles for the axes, unlike Altair.
- There is no axis line on the Y-axis in leather. On the X-axis, the labels are not rotated (0°).
- In Altair, there are only horizontal gridlines. In the case of leather, there are horizontal and vertical ones.
- The default fonts are different. In leather, [Monaco](<https://en.wikipedia.org/wiki/Monaco_(typeface)>) is used.
- The background colors are also different. In Altair, the background color is white, while in leather, it is a (very) light gray (`#f9f9f9`).

On the other hand, for the Y-axis, both charts present a scale with the same domain, ending in a [nice round value](https://github.com/d3/d3-scale) (100). However, the number of ticks is different.

Finally, if you have any questions or suggestions, feel free to leave a comment below!
How to make an animated like button | HTML, CSS, JavaScript
Tags: webdev, beginners, css, tutorial
Published: 2022-03-26 20:04:22

There are many like animations available on the internet, but this is one of my favorites. It's simple, easy to apply and different from what we see out there.

In this article, we will create an animated like button that you can use in your projects.

Let's first look at what are we building, feel free to press the button and see the animation happening :):
{% codepen https://codepen.io/romaopedro199/pen/zYpZawP %}

## Explaining the code

The "item--bg" class is the active state color that will be appear when the user press the "Click me" button. At the beginning, it will be invisible to the user and will appear only when the "active" class is with the "item" element:
![Like state](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wisl0t1wnzptyh5xcagn.png)


The shake animation will happen only when the "shake" class is with the "item" element:
![Shake animation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5ciocv8dsk4h1hrmi1m.png)

When the user press the "Click me" button, the JavaScript code will be called adding the "active" and "shake" class to the "item" element and removing the "shake" class after 2 seconds:
![Pressing the button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a87tuf1x9xr41ir84hmk.png)

## Thank you for reading, and let's connect!
Thank you for reading, and feel free to connect with me on [Linkedin](https://www.linkedin.com/in/pedro-romão/) and check my [Youtube channel](https://www.youtube.com/channel/UCRD32HK_9epZ1oSRJ9eIkxg).

And if you like my work and want to support me, you can buy me a coffee by [clicking here](https://www.paypal.com/donate/?hosted_button_id=R6FE32NPAN6MY).
#Day 7 of solving 450 questions[25/450]
Tags: programming, python, computerscience
Published: 2022-03-26 19:49:26

📅Day 7 : March 26,2022
Problems solved today :

## - [Rearrange positive and negative numbers in O(n) time and O(1) extra space](https://www.geeksforgeeks.org/rearrange-positive-and-negative-numbers-publish/)

*Tried many approaches but this made a lot of sense to me.


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

## [subarray-sum-equals-k](https://leetcode.com/problems/subarray-sum-equals-k/)

-Logic :
1) sum all the elements from start: prefix sum
2)store prefix sum inside dictionary
           * if prefixsum not in dictionary: dict[prefixsum]=1
           * else : increase the dictionary[key] +=1
3)Now check for K-prefixsum in dict , if exist increase your count.



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

## [Factorial of Very large number](https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers2508/1)
* Couldn't find any linear solution.
**5 OPTIONS**: 
a)iterative  approach : fact = fact*i
b)Recursive : n or n*fact(n-1)
c)Math factorial function
d)lgamma library function
e)Ramanujan's factorial **approximation**

## [array-subset-of-another-array](https://practice.geeksforgeeks.org/problems/array-subset-of-another-array2317/1)
-    a)HashMap should be the best approach(lookup in linear time) OR 
     b)for arr1 in arr2: count +=1 , if(count = len(arr2): Pass.

## [229.Majority Element II](https://leetcode.com/problems/majority-element-ii)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lntrvrfa30kov7j81tbl.png)
 

## [maximum-product-subarray](https://leetcode.com/problems/maximum-product-subarray/)


Thoughts: 

> Finally starting to get in flow and actually thinking about the problem not the code.
Play voice SpaceWords 🚀
Tags: hackwithdg
Published: 2022-03-26 19:32:55

SpaceWords game with voice control, made with p5.js and Deepgram

- To play the game enable access to microphone and to shoot the asteroids say the word from where the asteroid comes

- as the score increases larger asteroids appear which give more points

- If the game is over or you want to restart the game, say restart to play again


<img width="100%" style="width:100%" src="https://media.giphy.com/media/etWjAjmwYzL0hk8Vd2/giphy.gif">

### Submission Category: 
- Gram Gamers
- Wacky Wildcards


### Link to Code on GitHub
{% github verica02/spacewords-deepgram %}

### Demo
https://space-words.netlify.app/
I'm Looking to Connect with Engineers | Can I connect with you?🚀
Published: 2022-03-26 19:31:20

Hello DEV Community!

Can I connect with you? My name is Michael C. Bertoni, and I’m the Founder-CEO of PhillyTech. PhillyTech is exclusively focused on working with SaaS and Hi-Tech companies, we have 100+ clients and have been in business for 7+ years. 

We have multiple clients that are looking for awesome Engineers (We currently have 42 positions open in the US and Latin America For Full-time and Contract work) and I’m simply looking to connect and network with engineers and be a resource for the community.

More specifically at this point we have open jobs for:

- Senior Ruby on Rails Engineers
- Mid level and Senior Node.js Engineers
- Mid Level and Senior React.js Engineers
- .NET / C# Engineers
- Data Engineers

My LinkedIn is below and if you would like to connect with me! Have a great weekend!

Michael C. Bertoni | Founder-CEO | PhillyTech
[](https://www.linkedin.com/in/michaelbertoni33/)
[solved] Class 'App\Http\Controllers\Storage' not found - Laravel 9
Tags: laravel, php, storage, developer
Published: 2022-03-26 19:18:27

This article give on: Class ‘App\Http\Controllers\Storage’ Not Found. here laravel simple solution is here now get storage not found on this error and laravel 8 use get a**pp/http/controllers/storage solved**.

are you follow me and get this error solve laravel 6, laravel 7, laravel 8, laravel 9 get solved.

having an error:
**Class ‘App\Http\Controllers\Storage’ not found**
Class 'App\Http\Controllers\Storage' not found in laravel, Class 'App\Http\Controllers\Storage' not found 
Solution 1: Out of Class ‘App\Http\Controllers\Storage’ not found
You need to import Storage class because it’s a facade.

## Add.

`use Storage;`

## At your Project Controller:

For example: Class ‘App\Http\Controllers\Storage’ not found

```
<?php

namespace App\Http\Controllers;

use Storage;

class UserController {
   ...
}
```
Solution 2:
You must add this line of import use storage is use Illuminate\Support\Facades\Storage;

use Illuminate\Support\Facades\Storage;

## Final Code is:
now paste this code and get this your storage is found were well.

```
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
  
class UserController extends Controller

{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        Storage::put('ads.txt', 'Contents');
  
        return view('_MY_BLOGS');
    }
}
```
I hope it can help you…
GitHub Copilot made GF in PyGame
Tags: github, githubcopilot, fun, meme
Published: 2022-03-26 19:15:52

I just bored today so I decided to do fun with GitHub copilot.

I asked GitHub copilot to do this 👇

```python
# draw my dream girlfriend
```

and copilot started coding lol

see the output 👇

{% embed https://youtu.be/XkiPyVzBvng %}

I learn some new today like video editing lmao for this

actually I never did pygame before and yes I'm still single 

happy weekend <3
Comparing String to Avoid Time Based Attacks
Tags: beginners, go, string
Published: 2022-03-26 19:59:19

---
title: Comparing String to Avoid Time Based Attacks
published: true
date: 2022-03-26 19:10:21 UTC
tags: Beginner,Golang,String
series: "Sunday Snippet"
canonical_url: https://clavinjune.dev/en/blogs/comparing-string-to-avoid-time-based-attacks/
---

 ![Sunday Snippet #10 comparing string to avoid time based attacks](https://clavinjune.dev/img/sunday-snippet/image.png "Sunday Snippet #10 comparing string to avoid time based attacks")

## Code

```go
package foo_test

import (
	"crypto/rand"
	"crypto/subtle"
	"fmt"
	"strings"
	"testing"
	"time"
)

var (
	a      []byte
	length int = 100000
	batch  int = length / 10
)

func init() {
	a = make([]byte, length, length)
	rand.Read(a)
}

func getCopied(changedIndex int) []byte {
	b := make([]byte, length, length)
	copy(b, a)
	b[changedIndex] = byte(1)

	return b
}

func wrapper(fn func(a, b []byte) bool) {
	for i := length - 1; i > 0; i -= batch {
		b := getCopied(i)

		n := time.Now()
		fn(a, b)

		m := time.Since(n)
		fmt.Printf("Differences at Index: %d, time takes: %s\n", i, m.String())
	}
}

func Cmp(a, b []byte) bool {
	return string(a) == string(b)
}

func CmpSub(a, b []byte) bool {
	return subtle.ConstantTimeCompare(a, b) == 1
}

func TestCmp(t *testing.T) {
	fmt.Printf("length of chars: %d\n", length)
	fmt.Println("comparison using: string(a) == string(b)")
	wrapper(Cmp)
	fmt.Println(strings.Repeat("=", 60))
	fmt.Println("comparison using: subtle.ConstantTimeCompare(a, b) == 1")
	wrapper(CmpSub)
}
```

## Test

```shell
$ go version
go version go1.18 darwin/arm64
$ go test . -v -count=1
=== RUN   TestCmp
length of chars: 100000
comparison using: string(a) == string(b)
Differences at Index: 99999, time takes: 2.875µs
Differences at Index: 89999, time takes: 2.583µs
Differences at Index: 79999, time takes: 2.375µs
Differences at Index: 69999, time takes: 2.209µs
Differences at Index: 59999, time takes: 1.75µs
Differences at Index: 49999, time takes: 1.5µs
Differences at Index: 39999, time takes: 1.209µs
Differences at Index: 29999, time takes: 958ns
Differences at Index: 19999, time takes: 666ns
Differences at Index: 9999, time takes: 375ns
============================================================
comparison using: subtle.ConstantTimeCompare(a, b) == 1
Differences at Index: 99999, time takes: 50.792µs
Differences at Index: 89999, time takes: 50.583µs
Differences at Index: 79999, time takes: 50.958µs
Differences at Index: 69999, time takes: 50.709µs
Differences at Index: 59999, time takes: 51µs
Differences at Index: 49999, time takes: 51.333µs
Differences at Index: 39999, time takes: 55.875µs
Differences at Index: 29999, time takes: 50.75µs
Differences at Index: 19999, time takes: 51.709µs
Differences at Index: 9999, time takes: 51.167µs
--- PASS: TestCmp (0.00s)
PASS
ok  	example	0.092s
```

## Conclusion
Thus, `subtle.ConstantTimeCompare(a, b) == 1` is more likely to be safe to use to avoid time-based attacks. Also, to avoid the length of the string to be guessed, you can hash the string first.
What I learn from my Discord clone project
Tags: programming, beginners, webdev, react
Published: 2022-03-26 19:02:14

So after about 2 weeks and countless hours of scratching my head, I had finish major functionality of my  discord clone. 

###Tool I use for this project:

ReactJs
react-firebase-hook
firebase auth
firestore
Redux
Tailwind Css

first style homepage to look as close to discord homepage:

![discord clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rvfgpi94m73k4aw8dp0r.png)

###Add channel section:

![discord clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7s2daufcc1wf7to5sf6.png)


###Finally a message section:

![discord clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y3w21y8e79qlle7f7e6j.png)

additional features:

- Login has a condition and change from "Login" to "open discord" if there is user.

- Protected route so only if user who login are able to access else they are navigate to home page.

### First style a homepage:
![discord clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u99gcmy6tkn3kn8ueqfn.png)

   This project teaches me the important of reading code and documentation. I've been trying not to only following tutorial but also read source code which in this case was through GitHub repository. Follow tutorial and go step by step but I feel like reading other people code help me understand more of what I am doing and why I'm doing it, really dig deep and even implemented my own methods. In this project I've undated my fire store to the latest version(v9) but in the tutorials the version was version 8, which challenge me to read through firebase documentation to be able to implement the authentication, CRUD operations, react firebase hooks, and using redux to store the state of my channels using the updated code base. 

   It has been an overwhelming two weeks but at the end of the day it's has been quite rewarding. Every project you do you'll learning something new, not only in web development but about yourself as well. I though I would give up after a few days of just staring at the my code editor for hours on end going nowhere 
trying to center a div :), adding channels, or just get distracted by funny dog video's. 

###Lesson learn for next project:

- Take a step back when stuck, and com back with clear head.

- Get better and reading code.

- Read documentation for tools you're using

- Take not when implementing features for future use