teleren/devto huggingface dataset:
Count Hills and Valleys in an Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 02:00:53

You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closest non-equal neighbors of `i` are larger than `nums[i]`. Adjacent indices `i` and `j` are part of the **same** hill or valley if `nums[i] == nums[j]`.

Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on **both** the left and right of the index.

Return _the number of hills and valleys in_ `nums`.

**Example 1:**

**Input:** nums = \[2,4,1,1,6,5\]
**Output:** 3
**Explanation:**
At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.
At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. 
At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.
At index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.
At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.
At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. 
There are 3 hills and valleys so we return 3.

**Example 2:**

**Input:** nums = \[6,6,5,5,4,1\]
**Output:** 0
**Explanation:**
At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.
At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.
At index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.
At index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.
At index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.
At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.
There are 0 hills and valleys so we return 0.

**Constraints:**

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

**SOLUTION:**

    class Solution:
        def countHillValley(self, nums: List[int]) -> int:
            n = len(nums)
            groups = []
            i = 0
            while i < n:
                ctr = 1
                while i < n - 1 and nums[i] == nums[i + 1]:
                    i += 1
                    ctr += 1
                i += 1
                groups.append((nums[i - 1], ctr))
            ctr = 0
            m = len(groups)
            for i in range(1, m - 1):
                left = groups[i][0] > groups[i - 1][0]
                right = groups[i][0] > groups[i + 1][0]
                if not left ^ right:
                    ctr += 1
            return ctr
Minimum Operations to Reduce X to Zero
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 01:30:36

You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations.

Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`.

**Example 1:**

**Input:** nums = \[1,1,4,2,3\], x = 5
**Output:** 2
**Explanation:** The optimal solution is to remove the last two elements to reduce x to zero.

**Example 2:**

**Input:** nums = \[5,6,7,8,9\], x = 4
**Output:** -1

**Example 3:**

**Input:** nums = \[3,2,20,1,1,3\], x = 10
**Output:** 5
**Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `1 <= nums[i] <= 104`
*   `1 <= x <= 109`

**SOLUTION:**

    class Solution:
        def lenOfLongestSubarrayWithSum(self, arr, n, k):
            prevsums = {}
            total = 0
            maxLen = 0
            for i in range(n):
                total += arr[i]
                if (total == k):
                    maxLen = i + 1
                elif (total - k) in prevsums:
                    maxLen = max(maxLen, i - prevsums[total - k])
                if total not in prevsums:
                    prevsums[total] = i
            return maxLen
        
        def minOperations(self, nums: List[int], x: int) -> int:
            n = len(nums)
            total = sum(nums)
            if total == x:
                return n
            k = self.lenOfLongestSubarrayWithSum(nums, n, total - x)
            if k == 0:
                return -1
            return n - k
Richest Customer Wealth
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 01:00:47

You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `i​​​​​​​​​​​th​​​​` customer has in the `j​​​​​​​​​​​th`​​​​ bank. Return _the **wealth** that the richest customer has._

A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**.

**Example 1:**

**Input:** accounts = \[\[1,2,3\],\[3,2,1\]\]
**Output:** 6
**Explanation****:**
`1st customer has wealth = 1 + 2 + 3 = 6`
`2nd customer has wealth = 3 + 2 + 1 = 6`
Both customers are considered the richest with a wealth of 6 each, so return 6.

**Example 2:**

**Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\]
**Output:** 10
**Explanation**: 
1st customer has wealth = 6
2nd customer has wealth = 10 
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.

**Example 3:**

**Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\]
**Output:** 17

**Constraints:**

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

**SOLUTION:**

    class Solution:
        def maximumWealth(self, accounts: List[List[int]]) -> int:
            return max([sum(person) for person in accounts])
How To Install And Configure The AWS CLI On Linux OS
Tags: aws, linux, webdev, programming
Published: 2022-06-13 00:40:24

The Amazon Web Service Command Line Interface(CLI) is the fastest and easiest way to connect to AWS services and products.

Some instances have the CLI pre-installed such as the Amazon Linux instances while instances like the Red Hat Linux don’t. In this article, I will show you how to install and configure the CLI in an instance.

You’ll need a secure shell connection (SSH), to your AWS instance account and then configure and install.

Pre-requisite: AWS account, SSH Access key, Linux OS installed computer, internet access and a stable mind.

> STEP 1: Create an instance in your EC2

```
- Login to your AWS management console and navigate to EC2
- Create an EC2 with the Red Hat Linux AMI
- Select Network and security in the navigation pane, and enter key pairs
- Select Create Key Pair.
- Then, select the format of the file (. pem)
- Then, download
```

> STEP 2: Connect to your instance using SSH

```
- Open your terminal with Shift + Ctrl + T
- Navigate to your downloads or anywhere you must have downloaded the .PEM file with “cd downloads”
- Change the permission on it with chmod 400 <filename.pem>
- Go to your AWS management console, go instance.
- Select the the instance type
- By the description tab copy the IPv4 Public IP value.
- Go back to your terminal and run this command ssh -i labsuser.pem ec2-user@<public-ip> (replace <public-ip> with your IPv4 Public IP)
- Type “yes” at the prompt.
- Voila, connected sucessfully
```

> STEP 3: Install the AWS CLI on Red Hat Linux

Now that you have an active SSH connection to the Red Hat Linux instance running on Amazon EC2, next is to install AWS CLI.

```
- Run sudo yum install -y unzip
- Then, run curl “https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o “awscliv2.zip”
- Then, unzip awscliv2.zip
- Then, sudo ./aws/install
- Verify that AWS CLI is now working by running the following command: aws help
- At the : prompt, type q to exit.
- You are set.
```

> STEP 4: Configure the AWS CLI to connect to your AWS Account

Time to connect your AWS account to your AWS CLI. Go to the active SSH session terminal window and run `aws configure`. At the prompt enter your AWS Access Key ID and AWS Secret Access Key

We are all set, now you can work on your EC2 instance and every other AWS service from your personal machine using your local terminal.
Delete Operation for Two Strings
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 00:30:33

Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_.

In one **step**, you can delete exactly one character in either string.

**Example 1:**

**Input:** word1 = "sea", word2 = "eat"
**Output:** 2
**Explanation:** You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

**Example 2:**

**Input:** word1 = "leetcode", word2 = "etco"
**Output:** 4

**Constraints:**

*   `1 <= word1.length, word2.length <= 500`
*   `word1` and `word2` consist of only lowercase English letters.

**SOLUTION:**

    class Solution:
        def md(self, word1, word2, i1, i2):
            if (i1, i2) in self.cache:
                return self.cache[(i1, i2)]
            if i1 == len(word1):
                return len(word2) - i2
            if i2 == len(word2):
                return len(word1) - i1
            if word1[i1] == word2[i2]:
                self.cache[(i1, i2)] = min(self.md(word1, word2, i1 + 1, i2 + 1), 1 + self.md(word1, word2, i1, i2 + 1), 1 + self.md(word1, word2, i1 + 1, i2))
                return self.cache[(i1, i2)]
            else:
                self.cache[(i1, i2)] = 1 + min(self.md(word1, word2, i1, i2 + 1), self.md(word1, word2, i1 + 1, i2))
                return self.cache[(i1, i2)]
        
        def minDistance(self, word1: str, word2: str) -> int:
            self.cache = {}
            return self.md(word1, word2, 0, 0)
All Elements in Two Binary Search Trees
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 23:00:43

Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png)

**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png)

**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8,8\]

**Constraints:**

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

**SOLUTION:**

    import heapq
    
    # 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
            heap = []
            paths = [root1, root2]
            i = 0
            while i < len(paths):
                curr = paths[i]
                if curr:
                    heapq.heappush(heap, curr.val)
                    if curr.left:
                        paths.append(curr.left)
                    if curr.right:
                        paths.append(curr.right)
                i += 1
            return heapq.nsmallest(len(heap), heap)
Kth Missing Positive Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 00:00:47

Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`.

Return _the_ `kth` _**positive** integer that is **missing** from this array._

**Example 1:**

**Input:** arr = \[2,3,4,7,11\], k = 5
**Output:** 9
**Explanation:** The missing positive integers are \[1,5,6,8,9,10,12,13,...\]. The 5th missing positive integer is 9.

**Example 2:**

**Input:** arr = \[1,2,3,4\], k = 2
**Output:** 6
**Explanation:** The missing positive integers are \[5,6,7,...\]. The 2nd missing positive integer is 6.

**Constraints:**

*   `1 <= arr.length <= 1000`
*   `1 <= arr[i] <= 1000`
*   `1 <= k <= 1000`
*   `arr[i] < arr[j]` for `1 <= i < j <= arr.length`

**Follow up:**

Could you solve this problem in less than O(n) complexity?

**SOLUTION:**

    class Solution:
        def findKthPositive(self, arr: List[int], k: int) -> int:
            arr = set(arr)
            mx = max(arr) + k + 1
            ctr = 0
            for i in range(1, mx):
                if i not in arr:
                    ctr += 1
                if ctr == k:
                    return i
Limitations of Go generics
Tags: go, generics
Published: 2022-06-13 00:00:00

---
title: Limitations of Go generics
date: 20220613T00:00Z
tags: go,generics
---

Go does not allow type parameters (generics) in method declarations, and that limits the APIs you can make.

Here's an example when you might encounter that problem and how to work around it:

Say you're building a library to process streams of values, and you start with this type:

```go
// Stream receives In values from upstream and
// sends Out values downstream.
type Stream[In, Out] ...
```

Ideally, we could write the following generic `.connect()` method:

```go
//                           vvvvvvv ❌ not allowed by Go!
func (s Stream[A, B]) connect[C any](o Stream[B, C]) ...
```

But [Go does not allow type parameters in method declarations](https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#no-parameterized-methods). That means the `.connect()` method can't introduce any new types:

```go
//                                                  vvvvvv ✅ OK
func (s Stream[A, B]) connect(o Stream[B, B]) Stream[A, B]
```

That restricts the kinds of processing we can do by chaining `.connect()` methods together:

```go
lines
	.connect(omitEmpty) // ✅ (string -> string) same type
	.connect(getLength) // ❌ (string -> int   ) new type
	.connect(print)
```

We can get around this limitation by converting `.connect()` into a top-level `connect()` function that can change the stream type 🎉:

```go
func connect[A, B, C any](
    s1 Stream[A, B],
    s2 Stream[B, C],
) Stream[A, C]
```

Unfortunately, readability suffers a little:

```go
connect(connect(connect(lines, omitEmpty), getLength), print)
```

Or written with right-associativity:

```go
connect(lines, connect(omitEmpty, connect(getLength, print)))
```

Or on separate lines:

```go
s1 := lines
s2 := connect(s1, omitEmpty)
s3 := connect(s2, getLength)
s4 := connect(s3, print)
```

We need separate variables for each step in the stream, but other than that it's not much different from method chaining above!
My plan going forward...
Tags: career, discuss, beginners, programming
Published: 2022-06-12 23:28:16

## I have finally figured out what I'll do...

Moving forward, I will begin The Odin Project. I've read some good reviews about it. And since it has a strong focus on JavaScript, I think it's worth a try. It also helps prepare you when looking for a job which is a huge plus. 

In addition to TOP, I'll also continue building projects on frontendmentor.io. Frontendmentor is a great way to build realistic projects if you can't come up with any ideas of your own.

And lastly, NETWORK, NETWORK, NETWORK, and oh yeah, NETWORK. When an opportunity arises for me to meet people whether it's through online events or meetups, I'm definitely signing up. It's time to roll up my sleeves and get to work.

For me not to feel the pressure, I think I'll relax on the timeline. I'll get a job eventually. Just have to keep putting myself out there and just keep practicing and building projects.
3 actions to improve my English and the tools I must have - Dev Advocate Journal #DAJ 2
Tags: tools, english, setup, daj
Published: 2022-06-12 23:24:46

Hello, I hope you feel well. 🌞

Today I will tell you what I am doing to improve my English and what tools I identify are a must in my work computer.



## What I am doing to improve my English
In languages, we have to think in 4 areas: two inputs and two outputs:

- Read
- Listen
- Write
- Speak

In my work, I **read** the documentation in English and try to do my google search in English.

I try to watch series and funny videos in English in my free time for **listening**.

For my **writing**, I am doing this journal.
![Is she still speak?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3au9kodnfsqe8ckjapc.gif)

And for **speak**, I am not doing anything for this area right now. I tough about Tandem, but I don't want to depend on another person. So I think I need to make time to study with Elsa Speak.


If you want to learn faster, you need to spend more time in touch with the language.



**About the cleaning of my computer**
I install Ubuntu 22, and for my work I install:

- Chrome - as a browser
- VScode - as a code editor
- Terminator - as terminal
- Meld - as file comparator
- SMerge - as git facilitator



Then I downloaded some plugins for VScode -> [Top 10 Python Plugins for VS code](https://www.tabnine.com/blog/top-python-plugins-for-vscode/).



And that's it.



I hope you have a great start to the week 🌅

We read each other later ♥
Laravel and the MetaVerse
Published: 2022-06-12 22:42:23

Second Life, and Opensim are old-school Virtual Worlds that have an in-world scripting language called LSL (short for Linden Scripting Language).  LSL Scripts live inside of primitive objects (cubes, spheres, pyramids etc) which can be "rezzed" by your avatar when logged into the game.  The cool thing about these scripts, is that functions exist which can receive and send HTTP requests in and of the game.  

I've started an opensource project called [Laravel-Meta-Connect](https://github.com/firecentaur/laravel-meta-connect/blob/master/README.md).

The objective of this project is to examine how Laravel can be used to provide a backend interface for gaming inside of the virtual world. 


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

To acheive this, Laravel-Meta-Connect will consist of serveral in-world LSL Scripts which, once configured, will communicate with Laravel to provide the following:

* A Laravel View that displays Current Games Being Played In Second Life with Active players.
** A player will be registered as playing if they are sitting in a game chair (to be developed), or has clicked join on a Join Game Button (to be developed)

* A Laravel view that displays a scoreboard that lists top scores of an in-world Meta-Connect game

* A Laravel View that displays the latest Zombie Attacks that have happened in-world from the Zombie Attacks Quiz Game. Users will have to answer questions to defend against a zombie attacks.  Note: I have already created this game in Second Life, Code is just needed to pull in quiz questions from Laravel, and to report all Zombie Attacks. A Laravel backend web interface will be used for creating a quiz and questions for each in-world zombie attacks game

* Transporter Quiz: Sit in a Second Life vehicle, and have it move to next location by answering a question. Locations are saved in the database physically in world by moving to the location, and clicking a save-location button on a HUD in Second Life. User will also add a description to the location. A Laravel backend web interface will be used for attaching a question to each location saved.


* Scavenger Hunt Game: Place Scavenger hunt objects around the Virtual World (each registering with Meta Connect), have users collect points by clicking each object placed.  A Laravel view will display a SLURL (SL URL) to each item inside Second Life, that users will need to teleport to.  The View will display a checkmark beside each item collected.  Another Laravel View will list a Grid of each item, and of each user who has joined the game, and who has collected each item.  Points will be awarded to each user when an item is collected.  A Laravel backend web interface will be used for attaching a question to each location saved.

Please let me know if you are interested in joining this project.  Once developed, I would like to use it for language learning websites.
How to create 2 MySQL DBs in a single container?
Tags: docker, mysql, windows, beginners
Published: 2022-06-12 22:32:33

_Disclaimer: my Docker knowledge is non-existent. I only hack things together whenever I need something from a test project. In this particular case, I hit a wall since I'm not sure what I'm doing._

I am playing with some NodeJS apps, and in order to set up a quick database for my **Windows** machine, I use the following command:

```
docker run \
    --detach \
    --env MYSQL_ROOT_PASSWORD=something \
    --env MYSQL_USER=something_else \
    --env MYSQL_PASSWORD=something_new\
    --env MYSQL_DATABASE=something_name \
    --name some_other_name \
    --publish 127.0.0.1:1234:1234 \
    --volume "C:\Database":/var/lib/mysql \
    mysql:8.0
```

This all works great. I get a fast container that I can just `docker compose start` from _Docker for Windows_ and all is great.

However, I hit a wall now because I am trying to get a second database. Basically, a clone of the first one, with a different name.

The purpose of the secondary database is to have a dedicated DB for tests. But I'd like it to be in the same docker container, and ideally part of the same script. 

Is this even possible? Any suggestions on how I could achieve this?
Interleaving String
Tags: leetcode, dsa, theabbie
Published: 2022-06-12 22:30:40

Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`.

An **interleaving** of two strings `s` and `t` is a configuration where they are divided into **non-empty** substrings such that:

*   `s = s1 + s2 + ... + sn`
*   `t = t1 + t2 + ... + tm`
*   `|n - m| <= 1`
*   The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...`

**Note:** `a + b` is the concatenation of strings `a` and `b`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg)

**Input:** s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
**Output:** true

**Example 2:**

**Input:** s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
**Output:** false

**Example 3:**

**Input:** s1 = "", s2 = "", s3 = ""
**Output:** true

**Constraints:**

*   `0 <= s1.length, s2.length <= 100`
*   `0 <= s3.length <= 200`
*   `s1`, `s2`, and `s3` consist of lowercase English letters.

**Follow up:** Could you solve it using only `O(s2.length)` additional memory space?

**SOLUTION:**

    class Solution:
        def isLeave(self, s1, s2, s3, i, j, k, m, n, p):
            if (i, j, k) in self.cache:
                return self.cache[(i,j,k)]
            if i >= m or j >= n or k >= p:
                if i >= m:
                    res = s2[j:] == s3[k:]
                    self.cache[(i,j,k)] = res
                    return res
                if j >= n:
                    res = s1[i:] == s3[k:]
                    self.cache[(i,j,k)] = res
                    return res
                self.cache[(i,j,k)] = False
                return False
            if s1[i] == s3[k] and self.isLeave(s1, s2, s3, i + 1, j, k + 1, m, n, p):
                self.cache[(i,j,k)] = True
                return True
            if s2[j] == s3[k] and self.isLeave(s1, s2, s3, i, j + 1, k + 1, m, n, p):
                self.cache[(i,j,k)] = True
                return True
            self.cache[(i,j,k)] = False
            return False
        
        def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
            m = len(s1)
            n = len(s2)
            p = len(s3)
            self.cache = {}
            return self.isLeave(s1, s2, s3, 0, 0, 0, m, n, p)