teleren/devto huggingface dataset:
How to use User Impersonate in Laravel 9
Published: 2022-06-15 08:07:18

Hello Reader,

In today's blog I am going to show you how we can implement user impersonate in our project.

**What is user impersonate and why we use it in projects?**

- User Impersonate is useful when we want to login on behalf of admin user.

- When we are a super-admin and we want to know about our users what they do in their account then this package is useful to check their activity.

- If you implemented impersonate in your project then you need to maintain it because it may cause a security issue as well as user's privacy issue.

**Steps to follow**

1. Install user impersonate package
2. Setup User Model
3. Define routes
4. Create controller and Implement Impersonate logic

**Step 1:**
So let's start with installing  impersonate on your project copy the below code where we will install this package using composer.

```php
composer require lab404/laravel-impersonate
```

**Step 2:**
After installation we need to setup user model. Open `User.php` model and add use Impersonate and use Lab404\Impersonate\Models\Impersonate; to it as shown below.


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

**Step 3:**
Defining route: You can define a built in route as below

```php
Route::impersonate();
```
or, Alternately define route as,

```php
route('impersonate', $id)
```
where $id is the user ID whom we want to impersonate. For example,
 
```php
Route::get({user}/impersonate, [ControllerName::class, 'method_name')->name('user.impersonate);
```
and to leave impersonate the route will be define as

```php
route('impersonate.leave');

Route::get('/leave-impersonate', [ControllerName::class,'method_name'])->name('user.leave-impersonate');
```
**Step 4:**
Now create a controller where you want to implement impersonate logic and add below code in it.

```php
// to create controller
php artisan make:controller ControllerName

// method used to make user impersonate
public function method_name(User $user) 
{
    auth()->user()->impersonate($user);

    return redirect()->back();
}

// method used to leave impersonate user
public function method_name() 
{
    auth()->user()->leaveImpersonation();

    return redirect()->back();
}
```

In this way we can implement user impersonate in our project.
If you want to know more about it you can visit on below github
(https://github.com/404labfr/laravel-impersonate)

Thanks for Reading!
:heart: :unicorn:
Rank Transform of an Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 08:00:43

Given an array of integers `arr`, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

*   Rank is an integer starting from 1.
*   The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
*   Rank should be as small as possible.

**Example 1:**

**Input:** arr = \[40,10,20,30\]
**Output:** \[4,1,2,3\]
**Explanation**: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

**Example 2:**

**Input:** arr = \[100,100,100\]
**Output:** \[1,1,1\]
**Explanation**: Same elements share the same rank.

**Example 3:**

**Input:** arr = \[37,12,28,9,100,56,80,5,12\]
**Output:** \[5,3,4,2,8,6,7,1,3\]

**Constraints:**

*   `0 <= arr.length <= 105`
*   `-109 <= arr[i] <= 109`

**SOLUTION:**

    import heapq
    
    class Solution:
        def arrayRankTransform(self, arr: List[int]) -> List[int]:
            ranks = {}
            dist = sorted(set(arr))
            for i, d in enumerate(dist):
                ranks[d] = i + 1
            return [ranks[item] for item in arr]
Today's Daily Dose of Programming Humor
Tags: jokes, dailydeveloperjokes
Published: 2022-06-15 08:00:14

---
title: "Today's Daily Dose of Programming Humor"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125952bbb70.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Where did the API go to eat?

___A:___ To the RESTaurant
 -->
Laravel Firebase Push Notification
Tags: laravel, php, firebase, notification
Published: 2022-06-15 03:45:43

In this article, we will see laravel firebase push notification, firebase notification through you can notify users that new email or other messages are available to sync. firebase push notification is a free open source and you can easily implement using your google account. 

Firebase messaging or Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. FCM push notification is used for android, IOS as well as a web application.

So, let's see firebase notification in laravel 8, firebase messaging, firebase web push notification in laravel 8, how to set firebase push notification in laravel 8.

Here I will give an example, of firebase web push notification or firebase web push notification in laravel, Firebase provides a real-time database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients and stored on Firebase’s cloud.

Here we will see how to set firebase push notification in laravel step by step.

```
Step 1 : Create Firebase Project and App for Firebase Push Notification

Step 2 : Install Laravel 8 

Step 3 : Create Laravel 8 Auth Using Command

Step 4 : Create Migration and Model

Step 5 : Create Route

Step 6 : Create Controller

Step 7 : Update Blade File

Step 8 : Create firebase-messaging-sw.js File
```

---

**_[Read More: Laravel Firebase Push Notification](https://techsolutionstuff.com/post/laravel-firebase-push-notification)_**
Contribute to Open-Source: A step-by-step guide for Express NodeJs
Tags: opensource, node, tutorial, javascript
Published: 2022-06-15 07:54:51


[Express](https://github.com/expressjs/express) is a minimal and flexible Node.js web application framework for Node. It’s top features include DSL for routing, HTTP helpers like redirection, caching, cookie management etc with focus on high performance

We will explore the internals of express through a series of tasks of increasing complexity and scope. Each task will have a scope and runtime with it so you can get started without the setup load. 

---

## Repository Overview

Express is a lightweight framework which relies on developers adding custom middleware for their specific use case. It relies on Node’s http server to run and adds some core objects like

- **Request** - Object which handles request parsing for headers, fresh / stale, checking for proxy etc
- **Response** - Object for sending response (setting headers, attaching files, response codes etc)
- **Router** - Core routing logic ( setting up API path’s and corresponding functions) + framework for adding Middleware

Middlewares provide custom functionality and can be added by using app.use interface

- **Middleware** - Adding functionality to express like cookie-parsing, cors etc can be done by adding middleware functions which can alter request and response object. [In-depth](https://expressjs.com/en/guide/using-middleware.html).
- **Application** - Finally everything is wrapped around in the Application Object

---

## Tasks


**Task #1**: Add default port 1994 to the express server

**Description:** Express has a default port of 3000, try changing this to 1994. Get yourself familiar with lib/express.js and lib/application.js. Ignore other files for now. 

**Scope**:

1. lib/application.js
2. lib/express.js

**Hint:** Searching for app.listen will be a good starting point

**[Run Task](https://gitpod.io/#snapshot/46a6d1d0-e090-4677-8dc4-95da839512e5/)**



Checkout complete tutorial at [Full Tutorial](https://valuable-money-de6.notion.site/Express-e78fbc63bd75437aab61313f671ba83e)
Node For Dummies
Tags: javascript, node, beginners, programming
Published: 2022-06-15 07:46:08

There are a million ways you can learn Node JS but the one I Prefer is hand made notes that can assist me in all my future projects.

If your something like me you would also like sicknotes and cheat sheets for your future references.

So without further ado let's get started.

## WTF Is Node.js

Once upon a time JavaScript was a language that could not do anything more than manipulate DOM elements, In other words JS was confined only to your browser.

But today we can do just about anything with JS from building websites to training AI models and that's all thanks to Node.

So how exactly did node revolutionize JS ??? 

Basically when you write a line of code you need what's called a compiler that translates human readable code into lower level format that your computer can understand.

![js engine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e62xd8lvchx61x8a00es.png)

So browsers are shipped with something called a JS engine that acts as a compiler, 

Like shown in the image above the code from your app will go through the engine to perform the required operations but there are a lot of limitations to the JS engine shipped with browsers like we can not interact with the OS or create files with JS.

To over come these limitation Ryan Dahl in 2009 introduce the world to Node.JS

![chrome V8 engine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2j0bfhtxv2mw1fg38mnx.png)
 
which is basically uses chromes JS engine called V8 and wraps it  with Libuv a library built with C which gives JS the ability to perform a lot of native operations we will be visiting over the course of this series so stay tuned for the next blog post.
SVG Spinners!
Tags: webdev, showdev, opensource, beginners
Published: 2022-06-15 07:42:19

I have created a collection of 24 x 24 dp SVG spinners! Use them for free!

_I'll be adding new spinners every few days!_

**[https://github.com/n3r4zzurr0/svg-spinners](https://github.com/n3r4zzurr0/svg-spinners)**
Construct Binary Tree from Preorder and Postorder Traversal
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 07:30:46

Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_.

If there exist multiple answers, you can **return any** of them.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/07/24/lc-prepost.jpg)

**Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\]
**Output:** \[1,2,3,4,5,6,7\]

**Example 2:**

**Input:** preorder = \[1\], postorder = \[1\]
**Output:** \[1\]

**Constraints:**

*   `1 <= preorder.length <= 30`
*   `1 <= preorder[i] <= preorder.length`
*   All the values of `preorder` are **unique**.
*   `postorder.length == preorder.length`
*   `1 <= postorder[i] <= postorder.length`
*   All the values of `postorder` are **unique**.
*   It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def makeTree(self, preorder, pri, prj, prepos, postorder, poi, poj, postpos):
            if pri >= prj:
                return None
            root = TreeNode(val = preorder[pri])
            if pri + 1 == prj:
                return root
            leftval = preorder[pri + 1]
            rightval = postorder[poj - 2]
            root.left = self.makeTree(preorder, pri + 1, prepos[rightval], prepos, postorder, poi, postpos[leftval] + 1, postpos)
            root.right = self.makeTree(preorder, prepos[rightval], prj, prepos, postorder, postpos[leftval] + 1, poj - 1, postpos)
            return root
        
        def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
            n = len(preorder)
            prepos = {}
            postpos = {}
            for i, preval in enumerate(preorder):
                prepos[preval] = i
            for i, postval in enumerate(postorder):
                postpos[postval] = i
            return self.makeTree(preorder, 0, n, prepos, postorder, 0, n, postpos)
Checking for internet speed using Javascript
Tags: javascript, frontend, webdev, react
Published: 2022-06-15 07:29:52

Check Internet speed using JavaScript to render elements conditionally 

The downlink read-only property of the Network 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mvo34pgdwamh1u093z7.jpg)Information interface returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. This value is based on recently observed application layer throughput across recently active connections, excluding connections made to a private address space.

```
if (navigator.connection.downlink < 5){
   //logic for bad internet speeds
} else {
      //logic for good internet speeds

}

```
5 steps to add drag and drop in your website
Tags: tutorial, beginners, programming, react
Published: 2022-06-15 07:17:55

Hello people, this section is another video section. In video section, we mostly share videos instead of writing long texted stories. 
In today's story, we will discuss the 5 steps in just 5 steps to add drag and drop feature in your website. 


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

[5 steps to add drag and drop in your website](https://www.youtube.com/watch?v=YgrxSuL0aCs)

Our website [iHateReading](www.ihatereading.in)
[Twitter](https://twitter.com/treyvijay)
How to bind a function from an ObservableObject in swiftui
Tags: swift, ios, mobile
Published: 2022-06-15 07:08:17

my class contains a function,
```
class UserModel: ObservableObject {

  func fetchUser(){
    // code
  }
}
```
i call this class in a struct
```
struct UserView: View {
  @StateObject var userModel = UserModel()
  @State var loading: Bool = false
  
  var body: some View {
    ButtonComponent(loading: $loading)
  }
}
```
I would like to access the class in `ButtonComponent` just like i did with the `loading` variable by binding it.
The `ButtonComponent` is like this..
```
struct ButtonComponent: View {
  @Binding var loading: Bool
  
  var body: some View {
    Button(action: {loading.toggle()}){
      Text("Submit Button")
    }
  }
}
```
Help on how to achieve this is appreciated
Count Number of Teams
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 07:00:45

There are `n` soldiers standing in a line. Each soldier is assigned a **unique** `rating` value.

You have to form a team of 3 soldiers amongst them under the following rules:

*   Choose 3 soldiers with index (`i`, `j`, `k`) with rating (`rating[i]`, `rating[j]`, `rating[k]`).
*   A team is valid if: (`rating[i] < rating[j] < rating[k]`) or (`rating[i] > rating[j] > rating[k]`) where (`0 <= i < j < k < n`).

Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).

**Example 1:**

**Input:** rating = \[2,5,3,4,1\]
**Output:** 3
**Explanation:** We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). 

**Example 2:**

**Input:** rating = \[2,1,3\]
**Output:** 0
**Explanation:** We can't form any team given the conditions.

**Example 3:**

**Input:** rating = \[1,2,3,4\]
**Output:** 4

**Constraints:**

*   `n == rating.length`
*   `3 <= n <= 1000`
*   `1 <= rating[i] <= 105`
*   All the integers in `rating` are **unique**.

**SOLUTION:**

    class Solution:
        def numTeams(self, rating: List[int]) -> int:
            n = len(rating)
            bigger = {}
            smaller = {}
            for i in range(n):
                for j in range(i + 1, n):
                    if rating[i] > rating[j]:
                        smaller[i] = smaller.get(i, []) + [j]
                    if rating[i] < rating[j]:
                        bigger[i] = bigger.get(i, []) + [j]
            total = 0
            for a in bigger:
                for b in bigger.get(a, []):
                    total += len(bigger.get(b, []))
            for a in smaller:
                for b in smaller.get(a, []):
                    total += len(smaller.get(b, []))
            return total
8051 Microcontroller Projects
Tags: microcontroller, projects, 8051microcontrollerprojec, beginners
Published: 2022-06-15 06:46:03

As a Computer Science pupil in Computer Engineering/ Computer Science 285, I ’ve grown to appreciate using a prototype board to get through the class. As a person more inclined to software than to hardware, the sixteen- week travel has been a process. Part of my appreciation comes from my curiosity in the equipment of this class, in learning about other factors and the capability the board had. Learning not only about the 8051 microcontroller and board but also how to deal with it.

Engineering student projects for B.Tech and M.Tech final year students. Takeoff Edu Group offers a wide range of projects best for [8051 microcontroller projects](https://takeoffprojects.com/8051-microcontroller-projects) looking for magnificent final projects at low cost. 

We have successfully delivered wind energy projects to our engineering students. Our programs are specially designed by experts for best results of 8051 microcontroller projects  for engineering students. max of the B.Tech, M.Tech, PhD and Diploma scholars.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7ab76i2xn6thfbbsd6q.png)
 
Takeoff Edu Group provides the most creative conceptions and ideas that can make very effective final year projects for scholars, experimenters, and engineers. So browse through our list of [8051 microcontroller projects](https://www.youtube.com/watch?v=Edqwukqymuw)  and choose the smart final year projects for your requirements.
 
 
The first thing that needs to be done is to know the basics of what the 8051. The 8051 refers to a microcontroller. Microcontrollers are pieces of hardware that have set quantities on its corridor, like RAM, ROM, and its input and product ports. Microcontrollers are more cost effective than microprocessors, which need separate RAM, ROM, according to the requirements of the stoner. Microcontrollers come in handy when making embedded systems in operations so that it can control specific conduct of a computer in an effective way, in both processing and cost.
 
Like utmost technology, there's always the struggle to make the hardware more effective, major like the story of the 8051 microcontroller. In 1980, Intel introduced the 8051 microcontroller as a successor to the 8048. It was effective. It wasn't the stylish piece of equipment, but it worked at the time and was successful. 8- bits, multiple I/ O ports, 128kb of RAM, it was a standard piece to use.
Let's build a Sorting Visualizer using React - Part I
Tags: webdev, react, javascript, product
Published: 2022-06-15 06:37:37

Hello friends, I am back with a new project where we will build a sorting visualizer using React JS and I will use Chakra UI to speed up the UI development. Sorting Visualizer is an amazing project to strengthen your React skills. We can also learn about the algorithm. So let’s get started.

Find the demo for this project in below link
[Sorting Visualizer | CodeWithMarish](https://codewithmarish-sorting-visualizer.vercel.app/)

Want to know how I created this, please visit the post in our website.
[Let's build a Sorting Visualizer using React - Part I](https://codewithmarish.com/post/sorting-visualizer-using-react-part1)

Also please don’t forget to subscribe to our youtube channel codewithmarish for all web development-related challenges.

[Code With Marish | Youtube](https://www.youtube.com/channel/UCkPYmdVz8aGRH6qCdKMRYpA)

Posted with ❤️ from somewhere on the Earth
How to create a memory game in NEXT JS ?
Tags: webdev, nextjs, react, java
Published: 2022-06-15 06:31:54

Hello friends, Today in this post we are going to see how we can create a memory game using NEXT JS. Memory Game is an excellent project for beginners to get started with learning NEXT/REACT JS, doing this project will help you learn basic concepts such as lifecycle methods, useEffect & useState hooks, functional component, etc. A basic understanding of HTML, CSS & Javascript is enough to follow up with this tutorial. So get ready with your vscode and let’s get started.

You can find the demo for this in the below link
[Memory Game | CodeWithMarish](https://codewithmarish.com/products/memory-game)

Liked this! Do you want to know how I created this Please visit below post in our website
[How to create a memory game in NEXT JS ?
](https://codewithmarish.com/post/how-to-create-a-memory-game-in-nextjs)

Also please don’t forget to subscribe to our youtube channel codewithmarish for all web development-related challenges.

[Code With Marish | Youtube](https://www.youtube.com/channel/UCkPYmdVz8aGRH6qCdKMRYpA)

Posted with ❤️ from somewhere on the Earth
Teemo Attacking
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 06:30:39

Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack.

You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`.

Return _the **total** number of seconds that Ashe is poisoned_.

**Example 1:**

**Input:** timeSeries = \[1,4\], duration = 2
**Output:** 4
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.

**Example 2:**

**Input:** timeSeries = \[1,2\], duration = 2
**Output:** 3
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.

**Constraints:**

*   `1 <= timeSeries.length <= 104`
*   `0 <= timeSeries[i], duration <= 107`
*   `timeSeries` is sorted in **non-decreasing** order.

**SOLUTION:**

    class Solution:
        def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
            n = len(timeSeries)
            total = duration
            for i in range(1, n):
                total += min(timeSeries[i] - timeSeries[i - 1], duration)
            return total