teleren/devto huggingface dataset:
Day 576 : Another Sketch
Tags: code, hiphop, coding, lifelongdev
Published: 2022-06-17 22:01:06

_liner notes_:
- Professional : Pretty chill day. Had a brown bag session with some coworkers and learned more about a certain topic. After that, I basically worked on some stuff and completed some things to finish up the week.

- Personal : Worked more on the side project. It's coming together. I spent some time figuring out how I want the keyboard navigation to work. I want to do another sketch of how I want the layout to be now that I know I can get it to work. I also went through a bunch of tracks for the radio show.

![View of rooftops in Li Jiang, China at sunset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2v8ho9zxwqkuxvi2hoji.jpg)

Going to finish up the radio show pre-work tonight so that I can focus on other stuff tomorrow and during the weekend. Also, it's a long weekend because of Juneteenth. Going to use that time to get ahead at work because I want to take a couple of weeks in the near future. Also, I'll be doing https://untilit.works . I'm definitely going to watch "The Boys" and "Ms Marvel" tonight. At least I hope so. haha

Have a great night and long weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube QU_kTLRzIeU %}
Convert Sorted List to Binary Search Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 22:00:58

Given the `head` of a singly linked list where elements are **sorted in ascending order**, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of _every_ node never differ by more than 1.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/08/17/linked.jpg)

**Input:** head = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST.

**Example 2:**

**Input:** head = \[\]
**Output:** \[\]

**Constraints:**

*   The number of nodes in `head` is in the range `[0, 2 * 104]`.
*   `-105 <= Node.val <= 105`

**SOLUTION:**

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    # 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 sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
            if not head:
                return head
            if not head.next:
                return TreeNode(val = head.val)
            prev = None
            slow = head
            fast = head
            while slow and fast and fast.next:
                prev = slow
                slow = slow.next
                fast = fast.next.next
            prev.next = None
            root = TreeNode(val = slow.val)
            root.left = self.sortedListToBST(head)
            root.right = self.sortedListToBST(slow.next)
            return root
Textual has devtools
Tags: python
Published: 2022-06-17 21:51:08

---
canonical_url: https://waylonwalker.com/til/textual-has-devtools/
cover_image: https://images.waylonwalker.com/til/textual-has-devtools.png
published: true
tags:
- python
- python
- python
title: Textual has devtools
---

Textual has devtools in the upcoming css branch, and its pretty awesome!

## It's still early

Textual is still very early and not really ready for prime time, but it's quite amazing how easy some things such as creating keybindings is.  The docs are coming, but missing right now so if you want to use textual be ready for reading source code and examples.

## On to the devtools

As [@willmcgugan](https://twitter.com/willmcgugan) shows in this tweet it's pretty easy to setup, it requires having two terminals open, or using tmux, and currently you have to use the css branch.

{% tweet https://twitter.com/willmcgugan/status/1531294412696956930?ref_src=twsrc%5Etfw %}

## Why does textual need its own devtools

Textual is a tui application framework. Unlike when you are building cli applications, when the tui takes over the terminal in full screen there is no where to print statement debug, and breakpoints don't work.


## getting the css branch

In the future it will likely be in main and not need this, but for now you need to get the css branch to get devtools.

``` bash
git clone https://github.com/Textualize/textual git fetch --alll git checkout css
```

## install in a virtual environment

Now you can create a virtual environment, feel free to use whatever virtual environment tool you want, venv is built in to most python distributions though, and should just be there.

``` bash
python3 -m venv .venv --prompt textual source .venv/bin/activate pip install .
```

## Now that we have textual installed

Once textual is installed you can open up the devtools by running textual console.

```bash
textual console
```

![textual-console](https://screenshots.waylonwalker.com/textual-console.webp)
Blindly Following Other People's Solution
Tags: leetcode
Published: 2022-06-17 21:36:02

There are some things I do not understand in the coding world: Making assumptions like it's true. Let's see this solution to binary search. 

The question is to find a target number in an array of numbers. If the target is not in the array, return -1. If it is, return the index of the target in the array. 

This user's coding solution is brilliant
```javascript
var search = function(nums, target) {
    let lo = 0, hi = nums.length-1;
    while (lo < hi) {
        let mid = lo + Math.floor((hi-lo+1)/2);
        if (target < nums[mid]) {
            hi = mid - 1
        } else {
            lo = mid; 
        }
    }
    return nums[lo]==target?lo:-1;
};
```

The solver goes on further to explain (which I really appreciate by the way rather than simply writing down solution) the logic behind his choice of indexes of midpoint, low, and high. 

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


But! That seemingly sound very mathematical or programmatic is actually not that rigorous because if you change lo+hi/2 to lo+hi+1/2 there won't be an overflow. So, there is nothing wrong with that certain operations. 

This, I think is the problem in trying to understand every leetcode problem on the high level. You will not get things correct. 

Beware folks! You never know what's true until you see and understand how it works.
Arithmetic Subarrays
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 21:30:39

A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.

For example, these are **arithmetic** sequences:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not **arithmetic**:

1, 1, 2, 5, 7

You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.

Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._

**Example 1:**

**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.

**Example 2:**

**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]

**Constraints:**

*   `n == nums.length`
*   `m == l.length`
*   `m == r.length`
*   `2 <= n <= 500`
*   `1 <= m <= 500`
*   `0 <= l[i] < r[i] < n`
*   `-105 <= nums[i] <= 105`

**SOLUTION:**

    from collections import Counter
    
    class Solution:
        def isAP(self, arr):
            n = len(arr)
            if n == 1:
                return True
            arr = Counter(arr)
            a = min(arr)
            b = max(arr)
            d = (b - a) // (n - 1)
            if d == 0 and len(arr) == 1:
                return True
            for i in range(n):
                if arr[a + i * d] != 1:
                    return False
            return True
        
        def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:
            n = len(l)
            return [self.isAP(nums[l[i]:r[i]+1]) for i in range(n)]
Solid + GSAP: The superhero we need
Tags: gsap, solidjs
Published: 2022-06-17 21:24:44

Have you ever created a page and felt like it lacks the **SAUCE**? In my opinion, that drip usually comes from micro-interactions (small interactions with the sole purpose of delighting users). There are many libraries around for creating them, but my favorite one is GSAP, which allows creating performant and complex animations easily.

When using GSAP with React, however, the integration doesn't feel right: creating a Tween/Timeline and storing it in a `React.useRef()`, adding `.to()`'s and `.from()`'s inside a `React.useEffect()` looks strange to me. This is needed in order to prevent re-declaring on every render, which would re-trigger animations every time something changes in the DOM tree.

This is where SolidJS is brought into play. It looks like React, but has a main difference. according to its [documentation](https://www.solidjs.com/docs/latest#component-apis): 

> Every Component executes once and it is the Hooks and bindings that execute many times as their dependencies update.

This means no `useRef` needed for storing a timeline. In Solid you may simply declare it like this:
```jsx
const tl = gsap.timeline({paused: true});
```
And it won't be re-declared on every render. Very cool, eh? This approach is useful for most libraries thatinteract with the DOM to add transitions and animations ([ScrollReveal.js](), for example).

### Animating with GSAP in Solid.js
When adding an animation to a timeline, GSAP needs to know which element should be animated. This can be done using an element reference. There are two ways of getting a ref in Solid:

1. Pass a ref variable to a JSX element and add the animation inside `onMount`:
```jsx
  let containerRef;
  onMount(() => {
    gsap.to(containerRef, {
      // TODO: animation
    });
  });
  return <div ref={containerRef} />;
```

2. Or, my favorite one, using custom **directives**:
```jsx
const animation = (element) => {
  // code goes here
};

return <div use:animation />;
```

Custom directives are syntax sugar over ref, which allows us to easily attach multiple directives to a single element. A directive is a function that receives an Element and an Accessor as arguments, that looks like this:

```jsx
const hoverAnimation = (el, _accessor) => {
  const animation = gsap.to(el, {
    // properties
  });

  el.addEventListener("mouseenter", () => {
    animation.play();
  });

  el.addEventListener("mouseleave", () => {
    animation.pause();
  });
};
```
And may then be added to any element like this:
```jsx
const App () => (
  <div use:hoverAnimation />
  <div use:hoverAnimation />
);
```
An element can have multiple directives, and a directive can be used in multiple elements, making it possible to create GSAP animations that can be re-used throughout your app. 

Check out this live demo of an object that changes it background color on hover:

{% codesandbox solidjs-rainbow-box-wlysf4 %}
Bölüm 2) Next.js, TailwindCss ve echarts.js kurulumu
Published: 2022-06-17 21:20:05

`yarn create next-app --typescript`

## Typescript nereden çıktı?
Şimdiye kadar küçük projelerde ihtiyaç duymamıştım ve mülakatlar için dökümanları gözden geçirmiştim. Fakat büyük projelerde çalışmak için TypeScript bilgimi artırmam gerektiğini farkettim, bu sebeple bu projeye TypeScript'i de ekledim.

TailwindCSS ile kolay ve orantılı UI çıkarma yeteneği için projeye ekleme şansım varsa ekliyorum. Madem kendi portfolyomu yaratıyoruz TailwindCSS eklemezsem olmazdı. 
`cd proje_adi` ile proje klasörüme girdikten sonra 
`yarn add -D tailwindcss postcss autoprefixer`
`yarn tailwindcss init -p` ile tailwindCSS dependency'lerini ekliyorum.

Ve styles içindeki globals.css adlı klasöre 

```
@tailwind base;
@tailwind components;
@tailwind utilities;
```
ekledim.
Ardından tailwind.config.js dosyasına

```
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
```
Next.js için özelleştirilmiş config ayarlarını [burada](https://tailwindcss.com/docs/guides/nextjs) belirttiği gibi ekledim. Kodu yazacağımız dosyalardaki kullanılan class isimlerine bakacak ve kullanmadıklarımızı temizleyecek (purge). 

`yarn dev` komutu ile projeyi localde ayağa kaldırdım. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ar9hmbj7m7r41tgnq3dd.png)

## Sıra echarts'da:
`yarn add echarts` ve `yarn add echarts-for-react
` dependency'leri ekledikten sonra ilk grafiğimizi oluşturabiliriz. 
 

[Bölüm 3) echarts.js ile ilk grafiğimiz](https://dev.to/ozlemts/bolum-3-echartsjs-ile-ilk-grafigimiz-26fb)
Spiral Matrix
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 21:00:40

Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg)

**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg)

**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]

**Constraints:**

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

**SOLUTION:**

    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            m = len(matrix)
            n = len(matrix[0])
            op = []
            mark = "X"
            ctr = 0
            direction = 0
            x, y = 0, 0
            while ctr < m * n:
                if matrix[x][y] != mark:
                    ctr += 1
                    op.append(matrix[x][y])
                matrix[x][y] = mark
                switch = False
                if direction == 0:
                    if (y + 1) < n and matrix[x][y + 1] != mark:
                        y += 1
                    else:
                        switch = True
                elif direction == 1:
                    if (x + 1) < m and matrix[x + 1][y] != mark:
                        x += 1
                    else:
                        switch = True
                elif direction == 2:
                    if (y - 1) >= 0 and matrix[x][y - 1] != mark:
                        y -= 1
                    else:
                        switch = True
                else:
                    if (x + 1) >= 0 and matrix[x - 1][y] != mark:
                        x -= 1
                    else:
                        switch = True
                if switch:
                    direction = (direction + 1) % 4
            return op
[SOLVED] glue view is stale; it must be re-created
Tags: aws, glue
Published: 2022-06-17 20:32:00

when you facing this annoying error: 

`'<your-view-name' is stale; it must be re-created
This query ran against the "glue_<yours>_crawler"`

![power rangers begging for something to stop](https://media1.giphy.com/media/ERMGXqtKTDKHC/giphy.gif?cid=ecf05e471mnkczc0t47fvmkfv2l13oos58v7yphea5q4fe95&rid=giphy.gif&ct=g)

In the most cases the solution is simple, despite you barely find solutions on the internet (stackoverflow and some fancy blogs) try just review your columns order on presto metadata, in my case I'm creating the view with aws cdk, so I created a json with my configuration like the following example and then parse this to base64:

```json
{
  "catalog": "awsdatacatalog",
  "schema": "glue_my_crawler",
  "columns": [
    {
      "name": "name",
      "type": "varchar"
    },
    {
      "id": "id",
      "type": "varchar"
    },
  ],
  "originalSql": "SELECT id, name from \"schema-job-result\""
}
```

The example above results on the:

`'<your-view-name' is stale; it must be re-created
This query ran against the "glue_<yours>_crawler"`

## The correct way is like the example bellow

```json
{
  "catalog": "awsdatacatalog",
  "schema": "glue_my_crawler",
  "columns": [
    {
      "name": "id",
      "type": "varchar"
    },
    {
      "id": "name",
      "type": "varchar"
    },
  ],
  "originalSql": "SELECT id, name from \"schema-job-result\""
}
```

![Barney thumbs up](https://media3.giphy.com/media/dXZ6mCfV8GuA0/giphy.gif?cid=ecf05e47k1kyepf4q2tp0mzjh9qkhj8u8pbtxsdigi5n10va&rid=giphy.gif&ct=g)
Populating Next Right Pointers in Each Node II
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 20:30:39

Given a binary tree

struct Node {
  int val;
  Node \*left;
  Node \*right;
  Node \*next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.

Initially, all next pointers are set to `NULL`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/02/15/117_sample.png)

**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.

**Example 2:**

**Input:** root = \[\]
**Output:** \[\]

**Constraints:**

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

**Follow-up:**

*   You may only use constant extra space.
*   The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

**SOLUTION:**

    """
    # Definition for a Node.
    class Node:
        def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
            self.val = val
            self.left = left
            self.right = right
            self.next = next
    """
            
    class Solution:
        def connect(self, root: 'Node') -> 'Node':
            paths = [(root, 0)]
            i = 0
            latest = (0, -1)
            while i < len(paths):
                curr, level = paths[i]
                if curr:
                    if level == latest[1]:
                        curr.next = latest[0]
                    latest = paths[i]
                    paths.append((curr.right, level + 1))
                    paths.append((curr.left, level + 1))
                i += 1
            return root
JavaScript async and await in loops
Tags: javascript, webdev
Published: 2022-06-17 20:02:45

Basic **async** and **await** is simple. 

Things get a bit more complicated when you try to use **await** in loops.

Let's discuss further about in this article. 

## Prerequisite:
I’m going to assume you know how to use async and await. If you don’t, you can check it out [here](https://javascript.info/async-await)

## Await in a for loop

```
for (let index = 0; index < iterable.length; index++) {
  const value = await remoteApiCall();
}
```

```
for await (const variable of iterable) {
  const value = await remoteApiCall();
}
```

When you use await, you expect JavaScript to pause execution until the awaited promise gets resolved. This means awaits in a for-loop gets executed in series.

Same behaviour with `while` & `for-of` loops, i.e. all awaits gets executed in series one after another. 

## Loops that require a callback

await won’t work with loops that require a callback. Examples of such loops that require a callback i.e.
- forEach 
- map
- filter
- reduce

## Using await in loops with a callback
```
...
console.log('start')
const promises = iterable.map(remoteApiCall)
const values = await Promise.all(promises) // using promise.all is key
console.log(values)
console.log('end')
```

The console logs are printed in order. 

## Summary

- `await` doesn't work with loop in callback in serial fashion. 
- The solution is to use `await Promise.all(...)` where you pass all the promises
Super Pow
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 20:00:46

Your task is to calculate `ab` mod `1337` where `a` is a positive integer and `b` is an extremely large positive integer given in the form of an array.

**Example 1:**

**Input:** a = 2, b = \[3\]
**Output:** 8

**Example 2:**

**Input:** a = 2, b = \[1,0\]
**Output:** 1024

**Example 3:**

**Input:** a = 1, b = \[4,3,3,8,5,2\]
**Output:** 1

**Constraints:**

*   `1 <= a <= 231 - 1`
*   `1 <= b.length <= 2000`
*   `0 <= b[i] <= 9`
*   `b` does not contain leading zeros.

**SOLUTION:**

    class Solution:
        def pow(self, a, b, n):
            curr = 1
            for i in range(b):
                curr = ((curr % n) * (a % n)) % n
            return curr
        
        def superPow(self, a: int, b: List[int]) -> int:
            n = 1337
            if len(b) > 0:
                return (self.pow(a, b[-1], n) * self.pow(self.superPow(a, b[:-1]), 10, n)) % n
            return 1
Smallest Range II
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 19:30:43

You are given an integer array `nums` and an integer `k`.

For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.

The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.

Return _the minimum **score** of_ `nums` _after changing the values at each index_.

**Example 1:**

**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.

**Example 2:**

**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.

**Example 3:**

**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.

**Constraints:**

*   `1 <= nums.length <= 104`
*   `0 <= nums[i] <= 104`
*   `0 <= k <= 104`

**SOLUTION:**

    class Solution:
        def smallestRangeII(self, nums: List[int], k: int) -> int:
            n = len(nums)
            nums.sort()
            res = nums[-1] - nums[0]
            left = nums[0] + k
            right = nums[-1] - k
            for i in range(n - 1):
                currmax = max(right, nums[i] + k)
                currmin = min(left, nums[i + 1] - k)
                res = min(res, currmax - currmin)
            return res
Whatsapp-Status-React-Native
Tags: reactnative, javascript
Published: 2022-06-17 19:25:24

Features like zoom, pan, status progress, tap/swipe to switch image. Perfectly running on android/ios.

**Video**:
https://user-images.githubusercontent.com/13982255/174350613-c8c6a47d-48c7-4e31-9851-11a6919a945f.mp4


**Github Repo**:
https://github.com/Ajmal0197/Whatsapp-Status-React-Native

**Libraries used:**
``yarn add react-native-gesture-handler react-native-pager-view react-native-reanimated
``