teleren/devto huggingface dataset:
Find Elements in a Contaminated Binary Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 19:00:43

Given a binary tree with the following rules:

1.  `root.val == 0`
2.  If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3.  If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`

Now the binary tree is contaminated, which means all `treeNode.val` have been changed to `-1`.

Implement the `FindElements` class:

*   `FindElements(TreeNode* root)` Initializes the object with a contaminated binary tree and recovers it.
*   `bool find(int target)` Returns `true` if the `target` value exists in the recovered binary tree.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4-1.jpg)

**Input**
\["FindElements","find","find"\]
\[\[\[-1,null,-1\]\],\[1\],\[2\]\]
**Output**
\[null,false,true\]
**Explanation**
FindElements findElements = new FindElements(\[-1,null,-1\]); 
findElements.find(1); // return False 
findElements.find(2); // return True 

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/11/06/untitled-diagram-4.jpg)

**Input**
\["FindElements","find","find","find"\]
\[\[\[-1,-1,-1,-1,-1\]\],\[1\],\[3\],\[5\]\]
**Output**
\[null,true,true,false\]
**Explanation**
FindElements findElements = new FindElements(\[-1,-1,-1,-1,-1\]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False

**Example 3:**

![](https://assets.leetcode.com/uploads/2019/11/07/untitled-diagram-4-1-1.jpg)

**Input**
\["FindElements","find","find","find","find"\]
\[\[\[-1,null,-1,-1,null,-1\]\],\[2\],\[3\],\[4\],\[5\]\]
**Output**
\[null,true,false,false,true\]
**Explanation**
FindElements findElements = new FindElements(\[-1,null,-1,-1,null,-1\]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True

**Constraints:**

*   `TreeNode.val == -1`
*   The height of the binary tree is less than or equal to `20`
*   The total number of nodes is between `[1, 104]`
*   Total calls of `find()` is between `[1, 104]`
*   `0 <= target <= 106`

**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 FindElements:
    
        def __init__(self, root: Optional[TreeNode]):
            self.root = root
            self.exists = set()
            nodes = [(self.root, 0)]
            while len(nodes) > 0:
                curr, l = nodes.pop()
                if curr:
                    self.exists.add(l)
                    nodes.append((curr.left, 2 * l + 1))
                    nodes.append((curr.right, 2 * l + 2))
    
        def find(self, target: int) -> bool:
            return target in self.exists
    
    # Your FindElements object will be instantiated and called as such:
    # obj = FindElements(root)
    # param_1 = obj.find(target)
Complete game development blog #1.5: Pathfinding
Tags: beginners, csharp, unity3d, gamedev
Published: 2022-06-10 18:49:35

I was about to start implementing the movement system I talked about in my last post, but once I remembered I needed some kind of pathfinding for tiles that are around corners, I realized I could get two birds with one stone.

First things first I want to shout out someone who is a lifesaver to all 2D unity developers. Aaron Granberg made an amazing opensource project called the "A* Pathfinding Project". It's such an amazing, simple, easy to understand pathfinding solution for unity games, especially for 2D since navmesh isn't an option. I toyed around with the idea of doing A* pathfinding on my own, but making a game on you're own is enough of an undertaking in and of itself so any outside help is always nice.

So back to the shortcut idea. Since i had to implement pathfinding for obstructive objects and walls, i might as well use it for all movement. Since i was going to use the circle method, I could use the pathfinding to find out whether a tile is inside a certain sized circle or not. The simplest way to find that out, is to know if the tile is closer to the player than the circle's radius. So i simply compare the path length to the players movement range. You could say this is a bit of a twisty way to arrive at a very simple solution, but I had to make sure it's balanced in the way I wanted it, and I'm happy to say, it is. And this is what it currently looks like.


![An image of a character with a line forming from it to the cursor signifying the calculated path. A number next to the cursor shows the length of the path.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4v0e77k0tveq1m2p0z2d.png)
Delete Columns to Make Sorted
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 18:30:40

You are given an array of `n` strings `strs`, all of the same length.

The strings can be arranged such that there is one on each line, making a grid. For example, `strs = ["abc", "bce", "cae"]` can be arranged as:

abc
bce
cae

You want to **delete** the columns that are **not sorted lexicographically**. In the above example (0-indexed), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1.

Return _the number of columns that you will delete_.

**Example 1:**

**Input:** strs = \["cba","daf","ghi"\]
**Output:** 1
**Explanation:** The grid looks as follows:
  cba
  daf
  ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.

**Example 2:**

**Input:** strs = \["a","b"\]
**Output:** 0
**Explanation:** The grid looks as follows:
  a
  b
Column 0 is the only column and is sorted, so you will not delete any columns.

**Example 3:**

**Input:** strs = \["zyx","wvu","tsr"\]
**Output:** 3
**Explanation:** The grid looks as follows:
  zyx
  wvu
  tsr
All 3 columns are not sorted, so you will delete all 3.

**Constraints:**

*   `n == strs.length`
*   `1 <= n <= 100`
*   `1 <= strs[i].length <= 1000`
*   `strs[i]` consists of lowercase English letters.

**SOLUTION:**

    class Solution:
        def isSorted(self, arr, i, n):
            if i == n - 1:
                return True
            if arr[i] <= arr[i + 1] and self.isSorted(arr, i + 1, n):
                return True
            return False
        
        def minDeletionSize(self, strs: List[str]) -> int:
            n = len(strs[0])
            k = len(strs)
            ctr = 0
            for i in range(n):
                col = [s[i] for s in strs]
                if not self.isSorted(col, 0, k):
                    ctr += 1
            return ctr
3 ways to write better CSS
Published: 2022-06-10 18:24:06

CSS can be annoying to write and difficult to optimize, but in this article, we will go over the different ways of writing better and cleaner CSS. 

#### 1. CSS Component Framework (Boostrap , MaterlizeCSS)
A CSS Component Framework is just a bunch of pre-written classes to handle things like buttons, cards, dropdowns, etc, Example include Boostrap, MaterlizeCSS, Foundation, etc. The main advantage of this is that you have access to a lot of components and might just need very little custom CSS. This is great for people who are building powerful apps whose purpose is functionality and who do not have time to write custom CSS. The main disadvantage is that it does not really offer flexibility to write custom CSS.

#### Making a Button with a Component Framework

```html
<button class='btn blue'>Click me</button>
``` 

#### 2. CSS Utility Framework (tailwindcss)
A CSS Utility Framework is a bunch of low-level classes(like ```.text-2xl ```) that allows you to build custom components like buttons, cards, dropdowns, etc, A popular Example of this is tailwindcss.  The main advantage of tailwindcss is that it allows combining low-level classes to build custom UIs and it has a design specification. You might be thinking, who has time to remember those classes, well you do not have to memorize them because there is a vs code extension that can help you out. The main disadvantage of tailwindcss is that building custom components takes time and the setup tailwind is a bit of a hassle.

#### Making a Button with a Utility Framework

```html
<button class="bg-blue-500 text-white font-bold py-2 px-4 rounded">
  Button
</button>
``` 

#### 3. A CSS Preprocessor (Sass)
A CSS Preprocessor Is a program that allows you to write styles in another language and convert them to CSS. A popular example of this is Sass/Scss, with sass you can nest styles do functions, loops and etc. The main advantage of sass is that it provides you with a more stable, powerful, and robust superset of CSS. The main disadvantage is that the code has to be complied and it is a bit difficult to debug.

#### Making a Button with a CSS Preprocessor (Sass)

```scss
   /*mixins are like  functions*/
@mixin button-bg($bg) {
   /* takes and argument $bg*/
 background: $bg;

 color:white;
 text-decoration:none;
 padding:5px 10px;
 border-radius:3px;
 font-family: 'Poiret One', cursive;
 font-size:2em;
   /*hover state */
  &:hover {
    background:darken($bg,8%);
    transition: all 0.3s ease;
  }
  /* active state */
  &:active {
    background:darken($bg,25%);
  } 
}

.btn-green {
   @include button-bg(#2ecc71);

}

``` 
#### in conclusion
I would recommend component frameworks for people who do not have time to write custom CSS.  I would recommend utility frameworks for anyone who wants to build custom UIs and with a design spec, and I would recommend Preprocessors for anyone who loves writing CSS but wants some extra features. Those are some ways to deal with CSS, if missed any other way please tell me in the comment section. Thanks for reading see you next time, peace.
WebSockets for noobs
Published: 2022-06-10 18:09:01

WebSockets is a bidirectional way of communication between a server and a client. 
WebSocket is different from then HTTP. Both protocols are located at layer 7 in the OSI model and depend on TCP at layer 4.WebSocket is designed to work over HTTP ports 443 and 80, thus making it compatible with HTTP. To achieve compatibility, the WebSocket handshake uses the `HTTP Upgrade header` to change from the HTTP protocol to the WebSocket protocol.

This is how you would create a dead simple web socket server. 
I will try to create a web socket server using nodejs.

Install `ws` using npm.
```bash
npm install ws
```

```js
import { WebSocketServer } from "ws";

const server = new WebSocketServer({ port: 4000 });

server.on("connection", ws => {
  console.log(`new connection`);
  ws.on("message", message => {
    console.log(`Received message ${message}`);
    ws.send(`got your message: ${message}`);
  });
  ws.on("close", () => console.log("closing connection"));

  setInterval(() => {
    ws.send(`Message ${Math.random()}`);
  }, 5000);
});
```

We can create a web socket client from any browser using the native WebSocket API.

This is how to create a client to connect to our WebSocket server that we opened on  port 4000.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0parhhf8lcxy0a6mvsvc.png)

We can send message to the server using `ws.send()`.
We also get a response from the server confirming our message.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cw7f7xympg9hjrlmwkkc.png)

Thanks for reading!
Ransom Note
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 18:00:43

Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.

Each letter in `magazine` can only be used once in `ransomNote`.

**Example 1:**

**Input:** ransomNote = "a", magazine = "b"
**Output:** false

**Example 2:**

**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false

**Example 3:**

**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true

**Constraints:**

*   `1 <= ransomNote.length, magazine.length <= 105`
*   `ransomNote` and `magazine` consist of lowercase English letters.

**SOLUTION:**

    from collections import Counter
    
    class Solution:
        def canConstruct(self, ransomNote: str, magazine: str) -> bool:
            ctrNote = Counter(ransomNote)
            ctrMag = Counter(magazine)
            for c in ctrNote:
                if ctrMag[c] < ctrNote[c]:
                    return False
            return True
I used to stay up to date years ago, now I feel like I am not relevant
Published: 2022-06-10 17:58:55

With my day-job it's become difficult to find amazing new things and learn about it, try it out and do fun stuffs. 

Years ago when I was in school and college I used to be involved in new things so much, now I feel like I am outdated. 

Do you know great places, like blogs, forums to keep updated with latest things in web dev. primarily ?
Ace's Ebook LIVE On Product Hunt [Get Your Copy]
Published: 2022-06-10 17:56:08

Ace's launched a big and awesome Ebook on career paths on Product Hunt! 🔥

With the help of Ace’s new Ebook, managers will explore the experience of the world’s best tech companies, as well as get useful tips on how to build a career ladder that will REALLY work and meet the goals of the company.

[DOWNLOAD your copy](https://www.producthunt.com/posts/ebook-ultimate-guide-to-career-paths) 

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

## The Ebook includes:

- Step-by-step guide on building and implementing a career ladder that works for your company
- Basic toolkit for a manager
- Experts’ advice and their experience
- Cases and examples for different team sizes (10 to 400 ppl)

And BONUS!

- 65+ skill matrix templates with skills and career paths to steal

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

## This guide will help:

- 🚀 Significantly increase the team’s motivation
- 🚀 Make promotion decisions transparent & fair
- 🚀 Improve the company’s brand image
- 🚀 Make the hiring process easier & more effective

[Get Ebook](https://www.producthunt.com/posts/ebook-ultimate-guide-to-career-paths) and enjoy implementing it at your tech team!
Students Benefit from Brain Training and Neurofeedback
Tags: healthydebate, mentalhealth, neurofeedback, wellbeing
Published: 2022-06-10 17:39:43

[Brain training and Neurofeedback](https://tnnfb.com/) have been shown to significantly increase a person's capacity to focus. Given that a large percentage of children are thought to suffer from hyperactivity problem or attention deficiency, it might be quite beneficial for pupils in this respect. When done correctly, brain training and neurofeedback may have a significant impact on a student's academic performance, mostly by reducing interruptions in the classroom.

According to a new study, many students are turning to drugs to manage their problems. However, the fact is that such medications do not work for everyone, not to mention their potentially dangerous side effects. Students who use such pharmaceuticals to boost their focus and attention have been reported to have an increased risk of heart disease, digestive or eating difficulties, and mood disorders including depression. When it comes to helping children with ADHD pay attention and increase their focus, brain training and neurofeedback have been shown to be the best alternative. This, in turn, leads to increased academic achievement, much to the delight of all parties involved.

The good news is that the benefits of brain training and neurofeedback in pupils have been proven to endure for months after the training sessions have concluded. This is fantastic news for children, and it's no surprise that most school systems have adopted it in their attempts to ensure that pupils make significant progress in their schoolwork. The instruction is appropriate for all ages, which means that all pupils, regardless of age, may profit substantially. The brain is trained on how to respond to information or cues from the surroundings throughout the training, and the outcomes are surely exhilarating.The time it takes for a student to see improvements following Brain training and Neurofeedback depends entirely on the learner. Students should, however, expect to see some beneficial benefits after roughly 10 sessions. The good news is that brain training and neurofeedback haven't been linked to any negative side effects, so they're safe for your precious child. It may be the greatest answer for youngsters who struggle with inattention, forgetfulness, inability to complete tasks, and even disorganization, all of which have a negative impact on their academic achievement.
How to troubleshoot AWS Lambda timeouts
Tags: aws, lambda, serverless
Published: 2022-06-10 17:36:36

We can all agree that troubleshooting AWS Lambda timeouts can be tricky, here are some things to try when troubleshooting.

The Lambda timeouts can be caused by not enough memory or processing power of the Lambda itself, or can be caused by other services.

The way to find out what is the reason for the timeout, is digging into the Lambda logs and checking the logs of the container that ended with timeout. If the logs show that the used memory is the same as allocated memory then it is a lack of memory issue. When this happens, usually the container freezes, just stops at whatever was doing and consequently ends with a timeout. The lack of memory issue could be caused simply because Lambda needs more memory, so increasing the memory size will fix it. But it is always worth exploring the reason behind. Like in this [case](https://dev.to/aws-builders/optimize-memory-usage-in-aws-lambda-net-with-a-simple-fix-412h), where the underlying framework caused a lack of memory issue.

But what if the memory usage is not the reason for the timeout? Again, digging into the Lambda logs should give us the answer. By adding proper logs, you can easily see at which stage the Lambda freezes. If you are calling a service that takes too long to respond or is not scalable enough, by looking at the logs you should be able to see that the Lambda execution stopped at that particular service call. Usually this kind of issue can happen when Lambda is under load, but the underlying service cannot scale at the speed that Lambda is scaling. If this is the case then fixing the issue with the service will fix the timeout as well.

If none of the above is the case and you are still experiencing a timeout, it could be that your Lambda function does not have enough processing power. Usually this is the case when Lambda does CPU intensive work. Lambda allocates CPU power proportional to the amount of memory provisioned. So the more memory is allocated, the more CPU power is allocated too. Even if the whole memory is not used, the function will gain more CPU power and thus will execute faster.

Hope this information will help with resolving your Lambda timeout issues.
Sort the Matrix Diagonally
Tags: leetcode, dsa, theabbie
Published: 2022-06-10 17:30:37

A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`.

Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return _the resulting matrix_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png)

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

**Example 2:**

**Input:** mat = \[\[11,25,66,1,69,7\],\[23,55,17,45,15,52\],\[75,31,36,44,58,8\],\[22,27,33,25,68,4\],\[84,28,14,11,5,50\]\]
**Output:** \[\[5,17,4,1,52,7\],\[11,11,25,45,8,69\],\[14,23,25,44,58,15\],\[22,27,31,36,50,66\],\[84,28,75,33,55,68\]\]

**Constraints:**

*   `m == mat.length`
*   `n == mat[i].length`
*   `1 <= m, n <= 100`
*   `1 <= mat[i][j] <= 100`

**SOLUTION:**

    import bisect
    
    class Solution:
        def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
            m = len(mat)
            n = len(mat[0])
            diags = {}
            for i in range(m):
                for j in range(n):
                    if i - j in diags:
                        bisect.insort(diags[i - j], mat[i][j])
                    else:
                        diags[i - j] = [mat[i][j]]
            for i in range(m):
                for j in range(n):
                    mat[i][j] = diags[i - j][min(i, j)]
            return mat
    
    # import bisect
    
    # class Solution:
    #     def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
    #         m = len(mat)
    #         n = len(mat[0])
    #         vals = [[] for i in range(m + n - 1)]
    #         curr = 0
    #         for i in range(m):
    #             x, y = i, 0
    #             while x < m and y < n:
    #                 bisect.insort(vals[curr], mat[x][y])
    #                 x += 1
    #                 y += 1
    #             curr += 1
    #         for i in range(1, n):
    #             x, y = 0, i
    #             while x < m and y < n:
    #                 bisect.insort(vals[curr], mat[x][y])
    #                 x += 1
    #                 y += 1
    #             curr += 1
    #         curr = 0
    #         for i in range(m):
    #             x, y = i, 0
    #             while x < m and y < n:
    #                 mat[x][y] = vals[curr][y]
    #                 x += 1
    #                 y += 1
    #             curr += 1
    #         for i in range(1, n):
    #             x, y = 0, i
    #             while x < m and y < n:
    #                 mat[x][y] = vals[curr][x]
    #                 x += 1
    #                 y += 1
    #             curr += 1
    #         return mat