teleren/devto huggingface dataset:
Binary Tree Tilt
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 03:30:37

Given the `root` of a binary tree, return _the sum of every tree node's **tilt**._

The **tilt** of a tree node is the **absolute difference** between the sum of all left subtree node **values** and all right subtree node **values**. If a node does not have a left child, then the sum of the left subtree node **values** is treated as `0`. The rule is similar if the node does not have a right child.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg)

**Input:** root = \[1,2,3\]
**Output:** 1
**Explanation:** 
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg)

**Input:** root = \[4,2,9,3,5,null,7\]
**Output:** 15
**Explanation:** 
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15

**Example 3:**

![](https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg)

**Input:** root = \[21,7,14,1,1,2,2,3,3\]
**Output:** 9

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `-1000 <= Node.val <= 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 sumOfTree(self, root):
            if root:
                return root.val + self.sumOfTree(root.left) + self.sumOfTree(root.right)
            return 0
        
        def findTilt(self, root: Optional[TreeNode]) -> int:
            if root:
                l = self.sumOfTree(root.left)
                r = self.sumOfTree(root.right)
                return abs(l - r) + self.findTilt(root.left) + self.findTilt(root.right)
            else:
                return 0
I am stuck want to learn about alot of things at same time.
Published: 2022-06-11 03:16:54

I am stuck because I am learning to many things at the same time I am learning java and python and data structures and algorithms.
And I am learning web development also, and recently I started studying database like- MySQL.
And now someone said cloud computing has enormous opportunities ,there are so many jobs but very few people.
I am stuck I want to focus on less but I get fomo that if I didn't learnt it someone else will and I will be left behind.
Please help me out.
Remove Outermost Parentheses
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 03:00:45

A valid parentheses string is either empty `""`, `"(" + A + ")"`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.

*   For example, `""`, `"()"`, `"(())()"`, and `"(()(()))"` are all valid parentheses strings.

A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.

Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.

Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.

**Example 1:**

**Input:** s = "(()())(())"
**Output:** "()()()"
**Explanation:** 
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

**Example 2:**

**Input:** s = "(()())(())(()(()))"
**Output:** "()()()()(())"
**Explanation:** 
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".

**Example 3:**

**Input:** s = "()()"
**Output:** ""
**Explanation:** 
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

**Constraints:**

*   `1 <= s.length <= 105`
*   `s[i]` is either `'('` or `')'`.
*   `s` is a valid parentheses string.

**SOLUTION:**

    class Solution:
        def removeOuterParentheses(self, s: str) -> str:
            n = len(s)
            stack = []
            allowed = set(range(n))
            for i in range(n):
                if s[i] == '(':
                    stack.append(i)
                else:
                    curr = stack.pop()
                    if len(stack) == 0:
                        allowed.remove(curr)
                        allowed.remove(i)
            return "".join([s[i] for i in allowed])
Use Custom Hook to Separate Logic & UI in React
Published: 2022-06-11 02:52:59

In this article, I will show you how to separate the concern between logic and UI when building react app. Let’s get started.

Have a look at below code example.


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

It’s a simple react counter app that works just perfectly fine. At this stage, your component will not have any problem by having two method inside it. But imagine as your component grow, the method inside it will increase, and your component will harder to debug, and so many lines in one file. This is where custom hook come in handy to separate between your logic and your actual UI.

Now let’s create another file called useCounter, since our main component called counter, or whatever you like, but the name of the function is highly recommend to have use word in front of it as it state in react docs.

In this file, we move all our method and state inside our main component to here. It would be look like code below.


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

We have move all our method to here, and notice that in the end, we return all the value and method that our main component will need. Now move back to our main component and import these from our custom hook like below.


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

Now our code will look much cleaner and readable because it’s only concern about the UI, and only import all the method and value from the custom hook. This also make the method inside the hook is reuseable for other component that need it. Thank you for reading, see ya!
Avoid These 1 Mistakes to Optimize Your Website Speed (Easy Guide)
Tags: webdev, wordpress, tutorial, showdev
Published: 2022-06-11 02:42:48


In this video, you'll learn how to optimize your website speed within a few minutes. Avoid These 1 Mistakes to Optimize Your Website Speed (Easy Guide) and It's a super simple way to do this.

## Is website speed affect search engine rank?

The simple answer is that page speed does affect SEO. Page speed is a direct ranking factor, a fact known even better since Google's Algorithm Speed Update.

## How much does page speed affect SEO?

A good page speed for SEO is three seconds or less. A fast-loading page speed will help your SEO efforts, as Google rewards fast sites over slow ones. Keep in mind mobile page speed as well in your optimization efforts.

## Why does site speed Matter in SEO?

Poorly performing sites that render slowly in a browser can drive users away.

{% youtube kkBUe-Kv9pQ %}
Baseball Game
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 02:30:40

You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.

At the beginning of the game, you start with an empty record. You are given a list of strings `ops`, where `ops[i]` is the `ith` operation you must apply to the record and is one of the following:

1.  An integer `x` - Record a new score of `x`.
2.  `"+"` - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
3.  `"D"` - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
4.  `"C"` - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.

Return _the sum of all the scores on the record_. The test cases are generated so that the answer fits in a 32-bit integer.

**Example 1:**

**Input:** ops = \["5","2","C","D","+"\]
**Output:** 30
**Explanation:**
"5" - Add 5 to the record, record is now \[5\].
"2" - Add 2 to the record, record is now \[5, 2\].
"C" - Invalidate and remove the previous score, record is now \[5\].
"D" - Add 2 \* 5 = 10 to the record, record is now \[5, 10\].
"+" - Add 5 + 10 = 15 to the record, record is now \[5, 10, 15\].
The total sum is 5 + 10 + 15 = 30.

**Example 2:**

**Input:** ops = \["5","-2","4","C","D","9","+","+"\]
**Output:** 27
**Explanation:**
"5" - Add 5 to the record, record is now \[5\].
"-2" - Add -2 to the record, record is now \[5, -2\].
"4" - Add 4 to the record, record is now \[5, -2, 4\].
"C" - Invalidate and remove the previous score, record is now \[5, -2\].
"D" - Add 2 \* -2 = -4 to the record, record is now \[5, -2, -4\].
"9" - Add 9 to the record, record is now \[5, -2, -4, 9\].
"+" - Add -4 + 9 = 5 to the record, record is now \[5, -2, -4, 9, 5\].
"+" - Add 9 + 5 = 14 to the record, record is now \[5, -2, -4, 9, 5, 14\].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.

**Example 3:**

**Input:** ops = \["1","C"\]
**Output:** 0
**Explanation:**
"1" - Add 1 to the record, record is now \[1\].
"C" - Invalidate and remove the previous score, record is now \[\].
Since the record is empty, the total sum is 0.

**Constraints:**

*   `1 <= ops.length <= 1000`
*   `ops[i]` is `"C"`, `"D"`, `"+"`, or a string representing an integer in the range `[-3 * 104, 3 * 104]`.
*   For operation `"+"`, there will always be at least two previous scores on the record.
*   For operations `"C"` and `"D"`, there will always be at least one previous score on the record.

**SOLUTION:**

    class Solution:
        def calPoints(self, ops: List[str]) -> int:
            score = [0]
            for op in ops:
                if op == "+":
                    score.append(score[-1] + score[-2])
                elif op == "C":
                    score.pop()
                elif op == "D":
                    score.append(score[-1] << 1)
                else:
                    score.append(int(op))
            return sum(score)
How to convert file to string in native java ?
Tags: java, tutorial, programming, webdev
Published: 2022-06-11 02:18:24

Writing real world java code and some of the java interviews involves file and string processing. One of the common use cases is to convert a file to string. For eg: Read a json file and parse content from it. 

There are numerous ways to convert file to string in java. Let's talk about the most frequently used ones.  

##### 1. If you are using Java 1.11+ , you can use inbuilt Files package: 
```java
import java.nio.file.Files;
import java.nio.file.Path;

String result = Files.readString(Path.of("filePath"));

//To Write string to a file you can use 
String content = "Demo Content";
Files.writeString(filePath, content);
```

##### 2. If you are using Java 1.8+ inbuilt Streams package: 
```java
String result = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
```
This method works with Java 1.8+ 

There are few more ways to convert using scanner class, Google Guava library, Apache commons library. You can see them in here. 
[How to read and write to file as a string in java in simple way](https://tipseason.com/how-to-read-file-as-string-in-java/
)

Bonus: [How to read or convert an inputstream into a string in java](https://tipseason.com/how-to-read-convert-an-inputstream-into-a-string-in-java/)
Letter Tile Possibilities
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 02:00:45

You have `n`  `tiles`, where each tile has one letter `tiles[i]` printed on it.

Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`.

**Example 1:**

**Input:** tiles = "AAB"
**Output:** 8
**Explanation:** The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

**Example 2:**

**Input:** tiles = "AAABBC"
**Output:** 188

**Example 3:**

**Input:** tiles = "V"
**Output:** 1

**Constraints:**

*   `1 <= tiles.length <= 7`
*   `tiles` consists of uppercase English letters.

**SOLUTION:**

    class Solution:
        def numTiles(self, tiles, ctr):
            num = 0
            for c in ctr:
                if ctr[c] > 0:
                    num += 1
                    num += self.numTiles(tiles + c, {**ctr, c: ctr[c] - 1})
            return num
        
        def numTilePossibilities(self, tiles: str) -> int:
            n = len(tiles)
            ctr = {}
            for c in tiles:
                ctr[c] = ctr.get(c, 0) + 1
            return self.numTiles("", ctr)
Pure CSS Johnny Depp
Tags: codepen, html, css, webdev
Published: 2022-06-11 01:45:06

---
title: Pure CSS Johnny Depp
published: true
tags: codepen,html,css,webdev
---
{% codepen https://codepen.io/AsyrafHussin/pen/MWQPOJG %}
<p>Speed Code Video
<a href="https://twitter.com/asyrafhussin4/status/1534777630989295616" target="_blank">https://twitter.com/asyrafhussin4/status/1534777630989295616</a></p>
Maximum Twin Sum of a Linked List
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 01:30:38

In a linked list of size `n`, where `n` is **even**, the `ith` node (**0-indexed**) of the linked list is known as the **twin** of the `(n-1-i)th` node, if `0 <= i <= (n / 2) - 1`.

*   For example, if `n = 4`, then node `0` is the twin of node `3`, and node `1` is the twin of node `2`. These are the only nodes with twins for `n = 4`.

The **twin sum** is defined as the sum of a node and its twin.

Given the `head` of a linked list with even length, return _the **maximum twin sum** of the linked list_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png)

**Input:** head = \[5,4,2,1\]
**Output:** 6
**Explanation:**
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6. 

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png)

**Input:** head = \[4,2,2,3\]
**Output:** 7
**Explanation:**
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7. 

**Example 3:**

![](https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png)

**Input:** head = \[1,100000\]
**Output:** 100001
**Explanation:**
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.

**Constraints:**

*   The number of nodes in the list is an **even** integer in the range `[2, 105]`.
*   `1 <= Node.val <= 105`

**SOLUTION:**

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def lenList(self, head):
            if head:
                return 1 + self.lenList(head.next)
            return 0
        
        def pairSum(self, head: Optional[ListNode]) -> int:
            sums = {}
            n = self.lenList(head)
            curr = head
            i = 0
            while curr:
                key = min(i, n - i - 1)
                sums[key] = sums.get(key, 0) + curr.val
                curr = curr.next
                i += 1
            return max(sums.values())
masonite关于debugger
Tags: masonite, python
Published: 2022-06-11 01:28:06

## 安装

```bash
pip install masonite-debugbar
```


## 使用

`config/providers.py` 文件修改

```python
from debugbar.providers import DebugProvider
PROVIDERS = [
    ....
    DebugProvider
]

```

不过上线的时候也这样就不好了，会暴露敏感信息，所以改造一下


```python
from debugbar.providers import DebugProvider

# 如果不是生产环境，不要开启debug，即便安装了插件，也不会暴露敏感信息
if (env("APP_ENV") != 'prod'):
    PROVIDERS.append(DebugProvider)
```

这样即便打开了这个工具，也看不到信息

![效果1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/433w8fusvplj42sftxuo.png)
How to Create Singleton Class in Kotlin?
Tags: kotlin, beginners, android, programming
Published: 2022-06-11 01:15:07

**Singleton is a global object that can be accessed from everywhere in your application. This article shows different ways of creating it in Kotlin.**

In Kotlin, you can use the [object declaration](https://vtsen.hashnode.dev/complete-c-to-kotlin-syntax-comparisons#heading-static-vs-object-keyword) to implement singleton. However, if you don't aware of this object keyword, you probably will do something like this.

## Conventional Singleton

```kotlin
class Singleton private constructor() {

    companion object {
        @Volatile
        private lateinit var instance: Singleton

        fun getInstance(): Singleton {
            synchronized(this) {
                if (!::instance.isInitialized) {
                    instance = Singleton()
                }
                return instance
            }
        }
    }

    fun show() {
        println("This is Singleton class!")
    }
}

fun run() {
    Singleton.getInstance().show()
}
```

> - `private constructor()` is used so that this can't be created as usual class
> - `@Volatile` and ` synchronized()` are used to make sure this Singleton creation is thread-safe.

## Object Declaration Singleton

This can be simplified to
```kotlin
object Singleton {
    fun show() {
        println("This is Singleton class!")
    }
}

fun run() {
    Singleton.show()
}

```
> `Singleton` is a class and also a singleton instance where you can access the singleton object directly from your code.

## Constructor Argument Singleton

The limitation of this object declaration is you can't pass a constructor parameter to it to create the singleton object.  If you want to do that, you still need to use back the first conventional method above.

```kotlin
class Singleton private constructor(private val name: String) {

    companion object {
        @Volatile
        private lateinit var instance: Singleton

        fun getInstance(name: String): Singleton {
            synchronized(this) {
                if (!::instance.isInitialized) {
                    instance = Singleton(name)
                }
                return instance
            }
        }
    }

    fun show() {
        println("This is Singleton $name class!")
    }
}

fun run() {
    Singleton.getInstance("liang moi").show()
}
```

## Conclusion

I personally use singleton for simple utility class (use object declaration) and database (use convention singleton method - because it is required to pass in argument). 

---

*Originally published at [https://vtsen.hashnode.dev](https://vtsen.hashnode.dev/how-to-create-singleton-class-in-kotlin)*.
Consecutive Characters
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 01:00:44

The **power** of the string is the maximum length of a non-empty substring that contains only one unique character.

Given a string `s`, return _the **power** of_ `s`.

**Example 1:**

**Input:** s = "leetcode"
**Output:** 2
**Explanation:** The substring "ee" is of length 2 with the character 'e' only.

**Example 2:**

**Input:** s = "abbcccddddeeeeedcba"
**Output:** 5
**Explanation:** The substring "eeeee" is of length 5 with the character 'e' only.

**Constraints:**

*   `1 <= s.length <= 500`
*   `s` consists of only lowercase English letters.

**SOLUTION:**

    class Solution:
        def maxPower(self, s: str) -> int:
            s += "0"
            maxCtr = [0] * 26
            curr = [0] * 26
            for c in s:
                for i in range(26):
                    maxCtr[i] = max(maxCtr[i], curr[i])
                if c != "0":
                    tmp = curr[ord(c) - ord('a')]
                    curr = [0] * 26
                    curr[ord(c) - ord('a')] = tmp
                    curr[ord(c) - ord('a')] += 1
            return max(maxCtr)
Minimum Falling Path Sum
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 00:30:41

Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.

A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg)

**Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\]
**Output:** 13
**Explanation:** There are two falling paths with a minimum sum as shown.

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg)

**Input:** matrix = \[\[-19,57\],\[-40,-5\]\]
**Output:** -59
**Explanation:** The falling path with a minimum sum is shown.

**Constraints:**

*   `n == matrix.length == matrix[i].length`
*   `1 <= n <= 100`
*   `-100 <= matrix[i][j] <= 100`

**SOLUTION:**

    class Solution:
        def minSum(self, matrix, i, j, m, n):
            if i == m - 1:
                return matrix[i][j]
            if (i, j) in self.cache:
                return self.cache[(i, j)]
            minPath = float('inf')
            for col in [j - 1, j, j + 1]:
                if 0 <= col < n:
                    minPath = min(minPath, matrix[i][j] + self.minSum(matrix, i + 1, col, m, n))
            self.cache[(i, j)] = minPath
            return minPath
        
        def minFallingPathSum(self, matrix: List[List[int]]) -> int:
            m = len(matrix)
            n = len(matrix[0])
            self.cache = {}
            minPath = float('inf')
            for i in range(n):
                minPath = min(minPath, self.minSum(matrix, 0, i, m, n))
            return minPath