teleren/devto huggingface dataset:
Find the Distance Value Between Two Arrays
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 13:30:38

Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.

The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.

**Example 1:**

**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:** 
For arr1\[0\]=4 we have: 
|4-10|=6 > d=2 
|4-9|=5 > d=2 
|4-1|=3 > d=2 
|4-8|=4 > d=2 
For arr1\[1\]=5 we have: 
|5-10|=5 > d=2 
|5-9|=4 > d=2 
|5-1|=4 > d=2 
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**

**Example 2:**

**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2

**Example 3:**

**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1

**Constraints:**

*   `1 <= arr1.length, arr2.length <= 500`
*   `-1000 <= arr1[i], arr2[j] <= 1000`
*   `0 <= d <= 100`

**SOLUTION:**

    class Solution:
        def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
            ctr = 0
            for i in arr1:
                found = False
                for j in arr2:
                    if abs(i - j) <= d:
                        found = True
                        break
                if not found:
                    ctr += 1
            return ctr
Palindrome Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 13:00:48

Given an integer `x`, return `true` if `x` is palindrome integer.

An integer is a **palindrome** when it reads the same backward as forward.

*   For example, `121` is a palindrome while `123` is not.

**Example 1:**

**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.

**Example 2:**

**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

**Example 3:**

**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.

**Constraints:**

*   `-231 <= x <= 231 - 1`

**Follow up:** Could you solve it without converting the integer to a string?**SOLUTION:**

    class Solution:
        def isPalindrome(self, x: int) -> bool:
            xx = x
            nx = 0
            while x > 0:
                nx = 10 * nx + x % 10
                x = x // 10
            return xx == nx
Remove duplicate items in list, Python.
Tags: python, functional, programming, tutorial
Published: 2022-06-05 12:43:27

## How to remove duplicate list items in python ?
### Introduction
There are some options and features to remove duplicate items in a list. We are going to investigate some of them without any module (pandas, numpy etc.) in this essay. 
Let's code !

### Step by Step: Remove duplicate items from list

To be able to do that firstly we are going to use one of most common way, that is iteration by for loop. Assume we have a list including duplicate items like this *list = [1, 2, 2, 3, 4, 5, 5, ...]*. So we can use an iterator in a loop to remove duplicate items from list. 

```python
   def remove_duplicate(dup_list) -> None:
       result_list = list()
       [result_list.append(i) for i in dup_list if i not in result_list]
       print(f"Result -> {result_list}")
```
When the code above is run in the main method the output will be like following:
```python
   if __name__ == "__main__":
      remove_duplicate(dup_list = [1, 2, 2, 3, 3, 4, 5])
```

```
   Result List -> [1, 2, 3, 4, 5]
```

As you see above code we have used the optimized way to create list. Anyways let's try the other options that we can. One of the others is removing item from the original list by *count()* method. Think about that like the reverse of before instance. We will not create a new list, just delete duplicate items. 

```python
   def remove_duplicate(dup_list) -> None:
       for i in dup_list[:]:
           if dup_list.count(i) > 1:
               dup_list.remove(i)
       print(f"Result List => {dup_list}")

  if __name__ == "__main__":
     remove_duplicate(dup_list = [1, 2, 2, 3, 3, 4, 5])
```
```
   Output:
   Result List -> [1, 2, 3, 4, 5]
```

Note that we use the list like *dup_list[:]* in for loop because we want to remove items without any skipping. Unless you use the whole copy of the list as we do the iterator will skip the item after remove.

So far so good ! Now we will use dictionary to remove items. To do that we need *fromkeys()* method however, If you don't know what that module is you can search on the net. There are two parameters for this module and those are *sequence* and *value*. *Value* parameter is optional so it depends on what you need. 

Syntax:
> dict.fromkeys(sequence, value(optional))

```python
   result = list(dict.fromkeys(dup_list))
   print(f"Result List => {result}")
```
Check the output out.
```
   Output:
   Result List -> [1, 2, 3, 4, 5]
```

There is one more way to do that similar to the method above but this is slower than the *fromkeys* method. 

```python
   convert_to_set = list(set(dup_list))
   convert_to_set.sort(key=dup_list.index)
   print(f"Result List => {convert_to_set}")
```  
```
   Output:
   Result List -> [1, 2, 3, 4, 5]
```

That's all in this tutorial. I think the fastest way is *fromkeys()* method. Compare them each other and share your comments. 

Thank you for reading. :)
Reverse Integer
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 12:30:38

Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.

**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**

**Example 1:**

**Input:** x = 123
**Output:** 321

**Example 2:**

**Input:** x = -123
**Output:** -321

**Example 3:**

**Input:** x = 120
**Output:** 21

**Constraints:**

*   `-231 <= x <= 231 - 1`

**SOLUTION:**

    import math
    
    class Solution:
        def reverse(self, x: int) -> int:
            LIMIT = (1 << 31) - 1
            if x == 0:
                return x
            sign = x//abs(x)
            x = abs(x)
            op = 0
            while x > 0:
                d = x % 10
                x = x // 10
                op = 10 * op + d
                if (sign == 1 and op > LIMIT) or (sign == -1 and op > LIMIT + 1):
                    return 0
            return op * sign
How to ask for payment when finding security issues in a big website
Tags: security, help, freelance, discuss
Published: 2022-06-05 12:29:38

Recently I discovered two medium size security hacks in an international platform that ironically enough specializes in security by means of phishing prevention.

These issues allowed me to have insight in their internal db and graphql structure and insert data that should not be there. With these hacks I could theoretically make the platform useless for some of their paying clients, but obviously I am not going to do that.

I'd like to point these out to them, but am not intending to go unpaid. How would you contact the people behind this platform with my intentions? It's important not to come off as threatening (I really mean no harm), and not to reveal the source of the issues right away.

As you might guess I have no knowledge about anything like this. If you think this is a bad idea to begin with feel free to share your thoughts as well!
What CSS framework do you use and why? (Discussion)
Tags: discuss, css, webdev, beginners
Published: 2022-06-05 12:29:24

I use Tailwind CSS. I started using it recently so I'm still trying to get use to the class names.
(Also, writing codes is never a sprint... it's a journey, a marathon like they say."

I like TailwindCSS because it looks easier. And I heard it's lighter and easy to render than others.

I'll also want to try Material UI and Chakra UI soon.

So what framework do you use and why?

I'll love to hear from you.😊😊
Things I noticed when I left Mac Os for Pure OS
Tags: linux, productivity, opensource
Published: 2022-06-05 12:13:26

**TLDR;**
* My Mac uses a lot less space for apps 
* 32 GB RAM is being used really well....


Pure Os does a good job at keeping things minimal. My install used to use only about 2GB ROM & less than 1.5GB of RAM on average. In today's computing standard, that's pretty impressive; considering I am not missing much from Mac Os aside from the official apps available on the Mac. 

But now, considering I am editing this, and my RAM use is about 8GB and 23GB cached out of 32GB total. 
You could say, "Where's all that going?"

> It is being put to good use...

### Here's what I did:
1. I am running `preload` to load my app draw into RAM
2. `to_ram` option is being used to load entire OS into RAM at the cost of losing data in the event of immediate power failure.  


Before Getting this Mac Pro, I'd left Linux for quite a while. I felt like I spent more time up keeping the system instead of getting sh*t done; let's hope that's not the case this time.

Again, as a distro: Pure Os does a good job of coming packaged with daily apps that the average consumer can use. 

I am excited to see where this goes... 

Stay tuned!
Minimum Operations to Make Array Equal
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 12:00:42

You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`).

In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e., perform `arr[x] -=1` and `arr[y] += 1`). The goal is to make all the elements of the array **equal**. It is **guaranteed** that all the elements of the array can be made equal using some operations.

Given an integer `n`, the length of the array, return _the minimum number of operations_ needed to make all the elements of arr equal.

**Example 1:**

**Input:** n = 3
**Output:** 2
**Explanation:** arr = \[1, 3, 5\]
First operation choose x = 2 and y = 0, this leads arr to be \[2, 3, 4\]
In the second operation choose x = 2 and y = 0 again, thus arr = \[3, 3, 3\].

**Example 2:**

**Input:** n = 6
**Output:** 9

**Constraints:**

*   `1 <= n <= 104`

**SOLUTION:**

    class Solution:
        def minOperations(self, n: int) -> int:
            return (n * n) >> 2
Just created a fantastic looking temporary chat-room.
Tags: webdev, programming, opensource, javascript
Published: 2022-06-05 11:58:16


The story started last year when I was learning Javascript for web development. 
I wasn't sure how its going but i was obviously trying things out. So, i worked with a lot of technologies and found the best out of them, to finally work on my dream project which is currently under development. But during the journey, i also tried and built different kinds of things for utility purposes. One of such application was _Fortlax.io_.


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

This web app, being a very basic implementation of web sockets, is one of the most errorless application i had ever built(the development is still active).

Checkout the app here: [Fortlax.io](https://fortlax.vercel.app)

Link to the Github repository:[Fortlax.io](https://github.com/sambhavsaxena/fortlax.io)


Cheers♡
Roman to Integer
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 11:30:37

Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.

**Symbol**       **Value**
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used:

*   `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. 
*   `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. 
*   `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

**Example 1:**

**Input:** s = "III"
**Output:** 3
**Explanation:** III = 3.

**Example 2:**

**Input:** s = "LVIII"
**Output:** 58
**Explanation:** L = 50, V= 5, III = 3.

**Example 3:**

**Input:** s = "MCMXCIV"
**Output:** 1994
**Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4.

**Constraints:**

*   `1 <= s.length <= 15`
*   `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`.
*   It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`.

**SOLUTION:**

    class Solution:
        def romanToInt(self, s: str) -> int:
            sym = {
                "I": 1,
                "V": 5,
                "X": 10,
                "L": 50,
                "C": 100,
                "D": 500,
                "M": 1000
            }
            n = len(s)
            val = 0
            for i in range(n):
                if i < n - 1 and sym[s[i]] < sym[s[i + 1]]:
                    val -= sym[s[i]]
                else:
                    val += sym[s[i]]
            return val
Microsoft Engineer shares his Programming Interview Prep
Tags: career, programming, eventsinyourcity, webdev
Published: 2022-06-05 11:24:19

This video goes shares how one engineer (Leo) got a job at Microsoft. He answers questions like-

"What resources were critical for learning the fundamentals for you and why were those helpful?"

"How many mock interviews did you complete in your entirety of studying?"

"What other pieces of advice do you have for people who are preparing right now?"

"How were you able to evaluate your progress? Was leetcode good for this?"

Check out the full video **[HERE](https://www.youtube.com/watch?v=9hnFtu8y9O0)**.

### **Join the Community**

Leo joined Hackpack back in October 2021 to help him along his journey to Big Tech. Hackpack held him accountable as he studied and gave him a community of supporters.

Check out Hackpack - **[hackpack.io](https://www.hackpack.io/)** **[Big Tech Interview Newsletter](https://fangprep.substack.com/)**

**[Get notified next time we have a live event](https://discord.com/invite/VQkMr234zk?event=970275330294153257)** (Fireside with Meta Engineer 6/10)
Just got my 1st Salesforce Swag
Tags: salesforce, discuss, programming, beginners
Published: 2022-06-05 11:13:41

Thanks Salesforce For this amazing bottle
Thought It would be great sharing this achievement here.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fjbnl1nnli8ghrsukmj.jpeg)
Recoil State Management in Nextjs
Tags: recoil, nextjs, recoiljs
Published: 2022-06-05 11:13:18



Welcome 👋 guys, to this new tutorial blog post. In this blog post, I will teach you how to do state management in the nextjs with the help of **recoil**.

## Atoms

In this tutorial, I will teach you how to use atoms from recoil in nextjs.

Think of atom-like a news report, whose work is to take news from one area to the whole nation.

### 🫠Situation

Let’s suppose, today you have to build a modal for your website. An example of a modal is shown 👇

![](https://cdn-images-1.medium.com/max/3840/1*lUzba3eG_4N1z60aAt2keA.jpeg)

But how will you make it?

We can use useState hooks for that, but useState will not be efficient for this purpose. So, you need to use Recoil in this situation.

Step1: Download Recoil

yarn add recoil 

Step2: Go to the _app.js file and wrap components with RecoilRoot:
{% gist https://gist.github.com/studywithdesign/175ae48286f8170500b8baf634d168fe.js %}
Step3: Make a atoms folder in the root directory. Then make a atoms.ts file in that folder.

![](https://cdn-images-1.medium.com/max/3840/1*UYGUn6-pAVXmGTd2Bs-LFA.jpeg)

Step4: Make atom for modalSwitch:
{% gist https://gist.github.com/studywithdesign/6d7ff933d5438a8c53dc197564ec67e8.js %}
Step5: Use this atom in modal.tsx for making modal functional.

![](https://cdn-images-1.medium.com/max/3840/1*UYGUn6-pAVXmGTd2Bs-LFA.jpeg)
{% gist https://gist.github.com/studywithdesign/7bdacf475e20d3a6e1500a7476a6024e.js %}
Step6: Use this atom in index.tsx for making modal functional.
{% gist https://gist.github.com/studywithdesign/a03fd150e8ebf702d47716135439a5ec.js %}
Now you can try it 


If any error comes, feel free to join the discord server:
[https://discord.gg/hN4Wc5VR4M]( https://discord.gg/hN4Wc5VR4M)

Thanks for reading this blog post.
Minimum Lines to Represent a Line Chart
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 11:00:46

You are given a 2D integer array `stockPrices` where `stockPrices[i] = [dayi, pricei]` indicates the price of the stock on day `dayi` is `pricei`. A **line chart** is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:

![](https://assets.leetcode.com/uploads/2022/03/30/1920px-pushkin_population_historysvg.png)

Return _the **minimum number of lines** needed to represent the line chart_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2022/03/30/ex0.png)

**Input:** stockPrices = \[\[1,7\],\[2,6\],\[3,5\],\[4,4\],\[5,4\],\[6,3\],\[7,2\],\[8,1\]\]
**Output:** 3
**Explanation:**
The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.
The following 3 lines can be drawn to represent the line chart:
- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).
- Line 2 (in blue) from (4,4) to (5,4).
- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).
It can be shown that it is not possible to represent the line chart using less than 3 lines.

**Example 2:**

![](https://assets.leetcode.com/uploads/2022/03/30/ex1.png)

**Input:** stockPrices = \[\[3,4\],\[1,2\],\[7,8\],\[2,3\]\]
**Output:** 1
**Explanation:**
As shown in the diagram above, the line chart can be represented with a single line.

**Constraints:**

*   `1 <= stockPrices.length <= 105`
*   `stockPrices[i].length == 2`
*   `1 <= dayi, pricei <= 109`
*   All `dayi` are **distinct**.

**SOLUTION:**

    class Solution:
        def minimumLines(self, stockPrices: List[List[int]]) -> int:
            stockPrices.sort()
            stack = []
            for x, y in stockPrices:
                if len(stack) < 2:
                    stack.append((x, y))
                else:
                    ppx, ppy = stack[-2]
                    px, py = stack[-1]
                    if (py - ppy) * (x - px) == (px - ppx) * (y - py):
                        stack.pop()
                    stack.append((x, y))
            return len(stack) - 1
Pandas Tips
Tags: pandas, programming, analytics, webdev
Published: 2022-06-05 10:38:13

Below are some tips for pandas developers

**Dropping a column**

`df.drop(df.columns[idx], axis=1, inplace=True)`


**Setting the index column to the dataframe**

`df = pd.DataFrame.from_dict({
    'Name': ['Jane', 'Nik', 'Kate', 'Melissa', 'Evan', 'Doug', 'Joe'],
    'Age': [10, 35, 34, 23, 70, 55, 89],
    'Height': [130, 178, 155, 133, 195, 150, 205],
    'Weight': [80, 200, 220, 150, 140, 95, 180]
}).set_index('Name')`


**Group By in data frame**
`grouped = df.groupby("Age", axis="columns")`


**Selecting multiple columns**

`df2 = df[["Courses","Fee","Duration"]] `

**Using loc[] to take column slices**
`df2 = df.loc[:, ["Courses","Fee","Duration"]] 
df2 = df.loc[:, ["Courses","Fee","Discount"]] 
df2 = df.loc[:,'Fee':'Discount'] 
df2 = df.loc[:,'Duration':]  
df2 = df.loc[:,:'Duration']  
df2 = df.loc[:,::2]`          

`Using iloc[] to select column by Index`
`df2 = df.iloc[:,[1,3,4]] # Select columns by Index
df2 = df.iloc[:,1:4] # Select between indexes 1 and 4 (2,3,4)
df2 = df.iloc[:,2:] # Select From 3rd to end
df2 = df.iloc[:,:2] # Select First Two Colum
`

**DataFrame to a list**
`df = pd.DataFrame(data_dict)
print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")
col_one_list = df['one'].tolist()`

**DataFrame to an array**

`col_one_arr = df['one'].to_numpy()`


**Replacing all values in a dataframe based on condition**

`df.loc[df['First Season'] > 1990, 'First Season'] = 1`

**Changing the series data type to numeric**

`s = pd.Series(['1.0', '2', -3])
pd.to_numeric(s)`
Path Sum
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 10:30:35

Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.

A **leaf** is a node with no children.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg)

**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg)

**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

**Example 3:**

**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 5000]`.
*   `-1000 <= Node.val <= 1000`
*   `-1000 <= targetSum <= 1000`

**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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
            paths = [(root, root.val if root else 0)]
            i = 0
            while i < len(paths):
                curr, val = paths[i]
                if curr:
                    if not curr.left and not curr.right:
                        if val == targetSum:
                            return True
                    if curr.left:
                        paths.append((curr.left, val + curr.left.val))
                    if curr.right:
                        paths.append((curr.right, val + curr.right.val))
                i += 1
            return False