teleren/devto huggingface dataset:
Subarray Sum Equals K
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 01:30:42

Given an array of integers `nums` and an integer `k`, return _the total number of subarrays whose sum equals to_ `k`.

A subarray is a contiguous **non-empty** sequence of elements within an array.

**Example 1:**

**Input:** nums = \[1,1,1\], k = 2
**Output:** 2

**Example 2:**

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

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `-1000 <= nums[i] <= 1000`
*   `-107 <= k <= 107`

**SOLUTION:**

    class Solution:
        def subarraySum(self, nums: List[int], k: int) -> int:
            n = len(nums)
            curr = 0
            prevsum = {}
            ctr = 0
            for num in nums:
                curr += num
                if curr == k:
                    ctr += 1
                if (curr - k) in prevsum:
                    ctr += prevsum[curr - k]
                prevsum[curr] = prevsum.get(curr, 0) + 1
            return ctr
Creating Server with Express & Node.js
Published: 2022-06-06 01:24:36

In your project folder,npm init -y, then run npm i express. Create an index.js file

In the index.js file, that will start up your project at run time, write this code;

`
const express = require('express');
const ejs = require('ejs');
const app = new express();

// this will set the file to be 
// viewed in views folder, your
// index.ejs, html, pug, etc.
app.set('view engine', 'ejs');

app.listen(8000, () => (
 console.log('App running')
))
app.get('/', (req, res) => {
  res.render("index")
});
`
I will be publishing an Express course for allow8ng logins, resgister, delete profile, post blogs, and routing to the blog by the unique id created by Mongoose automatically. If anyone interested in this low cost course, please message me in this thread.
Reverse Bits
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 01:00:43

Reverse bits of a given 32 bits unsigned integer.

**Note:**

*   Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
*   In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.

**Example 1:**

**Input:** n = 00000010100101000001111010011100
**Output:**    964176192 (00111001011110000010100101000000)
**Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**.

**Example 2:**

**Input:** n = 11111111111111111111111111111101
**Output:**   3221225471 (10111111111111111111111111111111)
**Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**.

**Constraints:**

*   The input must be a **binary string** of length `32`

**Follow up:** If this function is called many times, how would you optimize it?

**SOLUTION:**

    class Solution:
        def reverseBits(self, n: int) -> int:
            return int("{:032b}".format(n)[::-1], 2)
How to deploy react projects to heroku
Tags: react, design, webdev, tutorial
Published: 2022-06-06 00:31:33


```
$ npm install -g heroku

//confirm heroku has been installed , it would show the version
$ heroku --version

$ heroku login -i

//make sure you are in your react project directory

$ git init

$ git add .

$ git commit -m "initial commit"

$ heroku create

$ git push heroku master

```
Maximum Product Subarray
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 00:30:38

Given an integer array `nums`, find a contiguous non-empty subarray within the array that has the largest product, and return _the product_.

The test cases are generated so that the answer will fit in a **32-bit** integer.

A **subarray** is a contiguous subsequence of the array.

**Example 1:**

**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.

**Example 2:**

**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `-10 <= nums[i] <= 10`
*   The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.

**SOLUTION:**

    class Solution:
        def maxProduct(self, nums: List[int]) -> int:
            n = len(nums)
            maxSoFar = nums[0]
            maxEndingHere = nums[0]
            minEndingHere = nums[0]
            for i in range(1, n):
                temp = max(nums[i], maxEndingHere * nums[i], minEndingHere * nums[i])
                minEndingHere = min(nums[i], maxEndingHere * nums[i], minEndingHere * nums[i])
                maxEndingHere = temp
                maxSoFar = max(maxSoFar, maxEndingHere)
            return maxSoFar
Relative Ranks
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 00:00:46

You are given an integer array `score` of size `n`, where `score[i]` is the score of the `ith` athlete in a competition. All the scores are guaranteed to be **unique**.

The athletes are **placed** based on their scores, where the `1st` place athlete has the highest score, the `2nd` place athlete has the `2nd` highest score, and so on. The placement of each athlete determines their rank:

*   The `1st` place athlete's rank is `"Gold Medal"`.
*   The `2nd` place athlete's rank is `"Silver Medal"`.
*   The `3rd` place athlete's rank is `"Bronze Medal"`.
*   For the `4th` place to the `nth` place athlete, their rank is their placement number (i.e., the `xth` place athlete's rank is `"x"`).

Return an array `answer` of size `n` where `answer[i]` is the **rank** of the `ith` athlete.

**Example 1:**

**Input:** score = \[5,4,3,2,1\]
**Output:** \["Gold Medal","Silver Medal","Bronze Medal","4","5"\]
**Explanation:** The placements are \[1st, 2nd, 3rd, 4th, 5th\].

**Example 2:**

**Input:** score = \[10,3,8,9,4\]
**Output:** \["Gold Medal","5","Bronze Medal","Silver Medal","4"\]
**Explanation:** The placements are \[1st, 5th, 3rd, 2nd, 4th\].

**Constraints:**

*   `n == score.length`
*   `1 <= n <= 104`
*   `0 <= score[i] <= 106`
*   All the values in `score` are **unique**.

**SOLUTION:**

    class Solution:
        def findRelativeRanks(self, score: List[int]) -> List[str]:
            n = len(score)
            ranks = sorted(range(n), key = lambda i: -score[i])
            labels = {
                0: "Gold Medal",
                1: "Silver Medal",
                2: "Bronze Medal"
            }
            op = [0] * n
            for i, r in enumerate(ranks):
                op[r] = labels.get(i, str(i + 1))
            return op
Solve nvim lsp denols vs tsserver clash
Tags: neovim, lsp, deno, typescript
Published: 2022-06-05 23:39:28

---
title: Solve nvim lsp denols vs tsserver clash
published: true
description: 
tags: neovim, lsp, deno, typescript
---

Recently I started using Deno for some personal projects, and when I installed the Deno lsp client on neovim, it clashed with tsserver as it has no idea what Deno types are and some other annoying diagnostics.

The [official](https://deno.land/manual/getting_started/setup_your_environment#neovim-06-using-the-built-in-language-server) documentation instructs you to specify the `root_dir` param in the `server:setup(options)`, but I thought that was a lot of hassle as it would not work for when you don't have a Deno project, but have no `package.json` either.

My solution was to use a programmatic way to have fine grained control over when to start which. Basically when `tsserver` wants to start, it checks if `denols` is in the active clients (which you can get using `vim.lsp.get_active_clients()`) and not continue setup, and `denols` does the same check to see if `tsserver` is attached to a file that belongs to it and kills it.

here's the full snippet:

```lua
      local active_clients = vim.lsp.get_active_clients()
      if client.name == 'denols' then
        for _, client_ in pairs(active_clients) do
          -- stop tsserver if denols is already active
          if client_.name == 'tsserver' then
            client_.stop()
          end
        end
      elseif client.name == 'tsserver' then
        for _, client_ in pairs(active_clients) do
          -- prevent tsserver from starting if denols is already active
          if client_.name == 'denols' then
            client.stop()
          end
        end
      end
```

I hope it saves you some time.
House Robber
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 23:30:40

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.

Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.

**Example 1:**

**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

**Example 2:**

**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

**Constraints:**

*   `1 <= nums.length <= 100`
*   `0 <= nums[i] <= 400`

**SOLUTION:**

    class Solution:
        def robRec(self, nums, i, n):
            if i >= n:
                return 0
            if i == n - 1:
                return nums[i]
            if i in self.cache:
                return self.cache[i]
            maxRob = nums[i]
            for j in range(i + 2, n):
                maxRob = max(maxRob, nums[i] + self.robRec(nums, j, n))
            self.cache[i] = maxRob
            return maxRob
        
        def rob(self, nums: List[int]) -> int:
            self.cache = {}
            return max(self.robRec(nums, 0, len(nums)), self.robRec(nums, 1, len(nums)))
Building Kadi. The Kenyan version of Poker. Part 1, The rules.
Tags: rails, ruby, opensource, showdev
Published: 2022-06-05 23:24:54

This I hope will be a multipart series of progress I make building Kadi. I didn't know how to play Kadi till my last year of college. And even then, I still kinda suck at it. So why automate it? Honestly I don't know, it seems like fun and it will have me implementing some pretty cool concepts if I build it to the standards I have in mind. 

Kadi rules in Kenya varies from region to region, so I wanted to first define the ruleset I will be using. 

=====================================================
## Ruleset
### Cards
There are 3 types of cards. 
#### 1. Feeding Cards
**2** , **3** and **J** are considered feeding card. When played, the next player has to pick 2, 3 or 5 cards respectively, or add a compatible feeding card. A compatible feeding card would have the same face/number, i.e if a 2 of Hearts is played a compatible feeding card would be a 2 of Clubs/Spades/Diamonds, a 3 of hearts or a J of Hearts.

#### 2. Winning Cards
**4 to 10**

These are cards that can be played to win the game. Of note is that **8** and **Q** are question cards that have to be played with an answer. An answer is a compatible face from 4-10. This means you can drop an 8 of hearts with a 4 of hearts. You can also stack question cards together as long as the last card stacked has a compatible answer played after it. 

#### 3. Special Cards
**A, K, J, Q and the Joker**

**A** can be used to demand a change in the face being played. For instance, if the game was Hearts, you can play **A** to request the face be changed to a Diamond.

**J** skips the next player's turn

**K** is a kickback meaning the game continues in the opposite direction. 

You can not win the game if you have any of the Special Cards. 

## How to Play & Win
There is a starter_card placed on the table. The first player must match the face/number or pick a card.

The game ends if a player legally plays all the cards they have left in one move. 

====================================================

I have no idea how long this will take but I aim to finish it, however long it takes. [This is the Repo](https://github.com/W3NDO/Kadi/)

I have some issues open already just to help me keep track of my own work, but if anyone is willing to help, they can make a pr. I will outline how the PRs are to be made.

This is just the beginning.
Shortest Path Visiting All Nodes
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 23:00:46

You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge.

Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/05/12/shortest1-graph.jpg)

**Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\]
**Output:** 4
**Explanation:** One possible path is \[1,0,2,0,3\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/05/12/shortest2-graph.jpg)

**Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\]
**Output:** 4
**Explanation:** One possible path is \[0,1,4,2,3\]

**Constraints:**

*   `n == graph.length`
*   `1 <= n <= 12`
*   `0 <= graph[i].length < n`
*   `graph[i]` does not contain `i`.
*   If `graph[a]` contains `b`, then `graph[b]` contains `a`.
*   The input graph is always connected.

**SOLUTION:**

    class Solution:
        def shortestPathLength(self, graph: List[List[int]]) -> int:
            n = len(graph)
            if n == 1:
                return 0
            req = (1 << n) - 1
            visited = {}
            queue = []
            for i in range(n):
                queue.append((0 | (1 << i), i))
            lvl = 1
            qi = 0
            while qi < len(queue):
                k = len(queue) - qi
                while k > 0:
                    curr, currnode = queue[qi]
                    qi += 1
                    for u in graph[currnode]:
                        newMask = curr | (1 << u)
                        if newMask == req:
                            return lvl
                        if newMask in visited.get(u, {}):
                            continue
                        visited[u] = visited.get(u, set()).union({newMask})
                        queue.append((newMask, u))
                    k -= 1
                lvl += 1
            return -1
Rearrange Words in a Sentence
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 22:30:47

Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format:

*   First letter is in upper case.
*   Each word in `text` are separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

**Example 1:**

**Input:** text = "Leetcode is cool"
**Output:** "Is cool leetcode"
**Explanation:** There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.

**Example 2:**

**Input:** text = "Keep calm and code on"
**Output:** "On and keep calm code"
**Explanation:** Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.

**Example 3:**

**Input:** text = "To be or not to be"
**Output:** "To be or to be not"

**Constraints:**

*   `text` begins with a capital letter and then contains lowercase letters and single space between words.
*   `1 <= text.length <= 10^5`

**SOLUTION:**

    class Solution:
        def arrangeWords(self, text: str) -> str:
            op =  " ".join(sorted(text.lower().split(), key = lambda s: len(s)))
            return op[0].upper() + op[1:]
Typescript Turn Tuple Type to Array
Tags: webdev, typescript, tutorial, programming
Published: 2022-06-05 22:28:08

here is how you do it

```ts
type TupleToArray<
  T extends unknown[],
  Acc = never
> = T extends [infer H, ...infer Rest]
  ? Rest extends []
    ? (H | Acc)[]
    : TupleToArray<Rest, Acc | H>
  : "impossible route"

type A = TupleToArray<[number, string, boolean]> // (string | number | boolean)[]
```

[playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAKgrmANhGB7AggJ0wQxAHhiggA9gIA7AEwGco4KBrC1AdwoG0BdAGinQDGAqAF4oFCADcImAHwiipctTocAlhQBmMqAAkeAOiMbtmKACUINYFwD8AWABQUF5evEylWlG5RbUAApdKAAffiEASl8ALlgEZDQsXAI3YD5BYTDg2WiAIjUAWzBUGho1ACNkKExUOHJcpydQSH5ROKQUDGw8fA4KOALymT5rTA0Acz5y1FRkHAouWSgAemXA0YnQ8QGhszDp2Yh5qK5GxycgA)

joke, I was messing, here is the easy way

```ts
type B = [number, string, boolean][number][] // (string | number | boolean)[]
```
Add Binary
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 22:00:42

Given two binary strings `a` and `b`, return _their sum as a binary string_.

**Example 1:**

**Input:** a = "11", b = "1"
**Output:** "100"

**Example 2:**

**Input:** a = "1010", b = "1011"
**Output:** "10101"

**Constraints:**

*   `1 <= a.length, b.length <= 104`
*   `a` and `b` consist only of `'0'` or `'1'` characters.
*   Each string does not contain leading zeros except for the zero itself.

**SOLUTION:**

    class Solution:
        def addBinary(self, a: str, b: str) -> str:
            m = len(a)
            n = len(b)
            if m > n:
                b = "0" * (m - n) + b
            else:
                a = "0" * (n - m) + a
            op = []
            k = max(m, n)
            i = k - 1
            carry = 0
            while i >= 0:
                currval = int(a[i]) + int(b[i]) + carry
                op.append(str(currval % 2))
                carry = currval // 2
                i -= 1
            return "1" * carry + "".join(op[::-1])
Creative CSS Profile Card Hover Effects Using Pure HTML and CSS Only | CSS Profile Cards UI Design
Tags: css, html, beginners, programming
Published: 2022-06-05 21:42:51

Hello Everyone, 
Before publishing my new tutorial about CSS Profile Card Hover Effects Using Pure HTML and CSS Only I want all of your opinions. Please check out my new CSS profile card hover animation demo and let me know should I publish it on YouTube or not? I will appreciate all of your opinions. Your feedback is really important to me.
{% youtube FpaILDDcnKM %} 
Thanks.
A New Start in Life
Published: 2022-06-05 21:32:06

A new start in life, that will hopefully take a hobby into a career.  I have always enjoyed building frontend websites for family and friends.  I would like to take that further start a small business of success.  Already enrolled in a bootcamp looking forward to learning to become a Fullstack Developer.  Please stick around to keep up with updates on the progress of this learning curve.
Maximum Product After K Increments
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 21:30:39

You are given an array of non-negative integers `nums` and an integer `k`. In one operation, you may choose **any** element from `nums` and **increment** it by `1`.

Return _the **maximum** **product** of_ `nums` _after **at most**_ `k` _operations._ Since the answer may be very large, return it **modulo** `109 + 7`. Note that you should maximize the product before taking the modulo. 

**Example 1:**

**Input:** nums = \[0,4\], k = 5
**Output:** 20
**Explanation:** Increment the first number 5 times.
Now nums = \[5, 4\], with a product of 5 \* 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.

**Example 2:**

**Input:** nums = \[6,3,3,2\], k = 2
**Output:** 216
**Explanation:** Increment the second number 1 time and increment the fourth number 1 time.
Now nums = \[6, 4, 3, 3\], with a product of 6 \* 4 \* 3 \* 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.

**Constraints:**

*   `1 <= nums.length, k <= 105`
*   `0 <= nums[i] <= 106`

**SOLUTION:**

    import heapq
    
    class Solution:
        def maximumProduct(self, nums: List[int], k: int) -> int:
            MAX = 10 ** 9 + 7
            n = len(nums)
            heap = []
            deleted = {}
            for i, num in enumerate(nums):
                heapq.heappush(heap, (num, i))
            for _ in range(k):
                curr, j = heapq.heappop(heap)
                while (curr, j) in deleted:
                    deleted[(curr, j)] -= 1
                    if deleted[(curr, j)] == 0:
                        del deleted[(curr, j)]
                    curr, j = heapq.heappop(heap)
                nums[j] += 1
                deleted[(curr, j)] = deleted.get((curr, j), 0) + 1
                heapq.heappush(heap, (curr + 1, j))
            p = 1
            for num in nums:
                p = (p * num) % MAX
            return p
Minimum Operations to Make the Array Increasing
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 21:00:47

You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`.

*   For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`.

Return _the **minimum** number of operations needed to make_ `nums` _**strictly** **increasing**._

An array `nums` is **strictly increasing** if `nums[i] < nums[i+1]` for all `0 <= i < nums.length - 1`. An array of length `1` is trivially strictly increasing.

**Example 1:**

**Input:** nums = \[1,1,1\]
**Output:** 3
**Explanation:** You can do the following operations:
1) Increment nums\[2\], so nums becomes \[1,1,**2**\].
2) Increment nums\[1\], so nums becomes \[1,**2**,2\].
3) Increment nums\[2\], so nums becomes \[1,2,**3**\].

**Example 2:**

**Input:** nums = \[1,5,2,4,1\]
**Output:** 14

**Example 3:**

**Input:** nums = \[8\]
**Output:** 0

**Constraints:**

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

**SOLUTION:**

    class Solution:
        def minOperations(self, nums: List[int]) -> int:
            n = len(nums)
            ctr = 0
            for i in range(n - 1):
                if nums[i + 1] <= nums[i]:
                    ctr += nums[i] + 1 - nums[i + 1]
                    nums[i + 1] = nums[i] + 1
            return ctr