teleren/devto huggingface dataset:
Unique Paths II
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 22:00:47

You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m-1][n-1]`). The robot can only move either down or right at any point in time.

An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.

Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.

The testcases are generated so that the answer will be less than or equal to `2 * 109`.

**Example 1:**

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

**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

**Example 2:**

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

**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1

**Constraints:**

*   `m == obstacleGrid.length`
*   `n == obstacleGrid[i].length`
*   `1 <= m, n <= 100`
*   `obstacleGrid[i][j]` is `0` or `1`.

**SOLUTION:**

    class Solution:
        memo = {}
        
        def uniquePathsRec(self, m, n, i, j, obstacleGrid):
            if i == m - 1 and j == n - 1:
                if obstacleGrid[i][j] != 1:
                    return 1
                return 0
            if obstacleGrid[i][j] == 1:
                return 0
            if (i, j) not in self.memo:
                self.memo[(i, j)] = 0
                if i + 1 < m:
                    self.memo[(i, j)] += self.uniquePathsRec(m, n, i + 1, j, obstacleGrid)
                if j + 1 < n:
                    self.memo[(i, j)] += self.uniquePathsRec(m, n, i, j + 1, obstacleGrid)
            return self.memo[(i , j)]  
                
        def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
            self.memo = {}
            return self.uniquePathsRec(len(obstacleGrid), len(obstacleGrid[0]), 0, 0, obstacleGrid)
Nft Explained in 60 words.
Tags: nft, web3, crypto, blockchain
Published: 2022-06-06 21:50:09

Suppose to want to buy the Starry Night, you go to the Van Gogh Museum and give them an absurd amount of money. They take you to the backroom and give you a copy of Starry night and the place where it is hung they write "Donated by Your Name". **It is not about owning the painting but having ownership.**
I stan Chakra-UI in 2022
Tags: react, uiweekly, frontend
Published: 2022-06-06 21:47:58

I like to sometimes let the web page tell me where it wants to go in terms of responsiveness... 

Haha well, in 2022, that approach might lead you to some hectic places on the front end. I truly didn't find any joy in making a component responsive ad nauseam and was struggling to find a design library that didn't feel bulky or claustrophobic.

Lucky for me, that helper turned out to be [Chakra-UI](https://chakra-ui.com/). 

Chakra-UI is just enough to bring the baseline UI up to a higher standard, but the extensive customizability leaves you feeling still very much in control. After redesigning two UIs from this library, I am sold and will preferentially use it for my front end projects going forward. Some features that really stood out:

1. The [built-in breakpoints](https://chakra-ui.com/docs/styled-system/theming/theme#breakpoints) saved me on total-app responsiveness and are adaptable enough to meet today's diverse screen requirements. 

2. You can combine features like the breakpoints with their custom hooks such as the [useMediaQuery](https://chakra-ui.com/docs/styled-system/utility-hooks/use-media-query) hook, which I used to easily switch views I had designed for mobile or desktop. 

3. The dark/light mode works really nicely and it was super easy to implement, as you can see on my personal website [here](www.simoneballard.com). 

4. The [text styles](https://chakra-ui.com/docs/styled-system/features/text-and-layer-styles) are intuitive, fun, and attractive. I created my "newspaper headlines" design [here](www.lwballard.com) just from variations on their Heading feature. I also replaced the Wix pro gallery with their Grid component and found it more responsive overall. 

All-in-all I would highly recommend integrating Chakra-UI into your next project for a satisfying User Experience and modern look!
Best Time to Buy and Sell Stock
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 21:30:40

You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.

You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.

Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.

**Example 1:**

**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 5
**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

**Example 2:**

**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transactions are done and the max profit = 0.

**Constraints:**

*   `1 <= prices.length <= 105`
*   `0 <= prices[i] <= 104`

**SOLUTION:**

    # class Solution:
    #     def maxProfit(self, prices: List[int]) -> int:
    #         valIndex = {}
    #         maxProfit = 0
    #         for i, price in enumerate(prices):
    #             if price not in valIndex:
    #                 valIndex[price] = [i, i]
    #             else:
    #                 valIndex[price][1] = i
    #         newprices = sorted(valIndex.keys())
    #         n = len(newprices)
    #         for j in range(n - 1, -1, -1):
    #             end = newprices[j]
    #             if end - newprices[0] <= maxProfit:
    #                 break
    #             for i in range(j):
    #                 curr = end - newprices[i]
    #                 if curr <= maxProfit:
    #                     break
    #                 if valIndex[end][1] > valIndex[newprices[i]][0]:
    #                     maxProfit = max(maxProfit, curr) 
    #         return maxProfit
    
    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            n = len(prices)
            minSoFar = prices[0]
            maxDiffSoFar = 0
            for i in range(1, n):
                minSoFar = min(minSoFar, prices[i])
                maxDiffSoFar = max(maxDiffSoFar, prices[i] - minSoFar)
            return maxDiffSoFar
Jump Game III
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 21:00:43

Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.

Notice that you can not jump outside of the array at any time.

**Example 1:**

**Input:** arr = \[4,2,3,0,3,1,2\], start = 5
**Output:** true
**Explanation:** 
All possible ways to reach at index 3 with value 0 are: 
index 5 -> index 4 -> index 1 -> index 3 
index 5 -> index 6 -> index 4 -> index 1 -> index 3 

**Example 2:**

**Input:** arr = \[4,2,3,0,3,1,2\], start = 0
**Output:** true 
**Explanation:** 
One possible way to reach at index 3 with value 0 is: 
index 0 -> index 4 -> index 1 -> index 3

**Example 3:**

**Input:** arr = \[3,0,2,1,2\], start = 2
**Output:** false
**Explanation:** There is no way to reach at index 1 with value 0.

**Constraints:**

*   `1 <= arr.length <= 5 * 104`
*   `0 <= arr[i] < arr.length`
*   `0 <= start < arr.length`

**SOLUTION:**

    class Solution:
        def canReach(self, arr: List[int], start: int) -> bool:
            n = len(arr)
            paths = [[start]]
            visited = set()
            while len(paths) > 0:
                curr = paths.pop(0)
                currIndex = curr[-1]
                jump = arr[currIndex]
                if jump == 0:
                    return True
                visited.add(currIndex)
                if currIndex - jump >= 0 and (currIndex - jump) not in visited:
                    paths.append(path + [currIndex - jump])
                if currIndex + jump <= n - 1 and (currIndex + jump) not in visited:
                    paths.append(path + [currIndex + jump])
            return False
SDKMAN! for dummies
Tags: java, programming, beginners, tutorial
Published: 2022-06-06 20:54:25

## ❔ About

It's a very common task for **programmers or ops to maintain a runtime.** Everyday, the ecosystem around the [jvm](https://en.wikipedia.org/wiki/Java_virtual_machine) gets richer and richer.

The consequence is simple : 

- You have to **install and upgrade** software on a regular basis
- You have to be able to easily **switch between versions & runtimes**
- You need to **be noticed on new major/minor** software releases

> **_This is all what SDKMAN! is about and helps managing all theses challenges with comfort and ease._**

👉 Let's take first look at what SDKMAN! is and all the amazing benefits you can get... and much more 🙋

 > ️ ⚠️ **Caution : testing `SDKMAN!` is adopting `SDKMAN!`** 😂 ⚠️

## 🍿 Démo

{% youtube https://youtu.be/oP8zJR1epBk %}

## 🔖 Resources

- [SDKMAN! homepage](https://sdkman.io/)
- [Available SDKs](https://sdkman.io/sdks)
My journey into software engineering and a sleek peek into my first month of learning to code.
Published: 2022-06-06 20:34:27

Although in early 2020, just at the tail end of my Master program in Physics, i began to develop interest in software engineering but, i wanted to be sure if i am really ready for the responsibility that comes with learning an entirely different and broad field. i don't want to be deluded by my technical skills, i wanted to be sure of my curiosity and interest about software development. by mid 2020, i took a job as electronics instrumentation and control engineer. i enjoyed the experience but something inside me wanted to use software to do some instrument automation. 

My interest for software development grew everyday.  by the end of 2021, i could't help but to start researching the area of software development to specialise. i found out that front-end development is fascinating to me. i began to search for resources and materials to kick start. tried freeCodeCamp, watched dozens of youtube roadmaps and tutorials. but all were not giving me an organised learning path. but i continue leaning anyways. randomly setting out time every week to learn.

By the 26th of April 2022, i became upset with my snail progress in learning programming. i decided to meet with a friend who is a senior software engineer to seek advice. he gave me a few resources and websites to stat with. By the end of April, i quit my job to focus on learning software development. i began my active learning of HTML and CSS, and after three weeks i made a peek into JavaScript and learn Git CLI and Github. today made it the second week of learning JavaScrip and i already built two  projects. A Todo List and Student registration app. today i started a work on a passenger counting app. the experience has been awesomely challenging and i could wait to see what the experience would be in my second month. Coding is sweet but only when you find solution to your problem. lol. 

watch me as i develop this skill and make a significant change in software development.

Note. i will appreciate resources recommendation and i am open for internship or project collaboration that can enhance my learning.

thanks for reading.
Insert Delete GetRandom O(1)
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 20:30:38

Implement the `RandomizedSet` class:

*   `RandomizedSet()` Initializes the `RandomizedSet` object.
*   `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
*   `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
*   `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.

You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.

**Example 1:**

**Input**
\["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]

**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

**Constraints:**

*   `-231 <= val <= 231 - 1`
*   At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
*   There will be **at least one** element in the data structure when `getRandom` is called.

**SOLUTION:**

    import random
    
    class RandomizedSet:
    
        def __init__(self):
            self.set = set()
    
        def insert(self, val: int) -> bool:
            if val not in self.set:
                self.set.add(val)
                return True
            return False
    
        def remove(self, val: int) -> bool:
            if val in self.set:
                self.set.remove(val)
                return True
            return False
    
        def getRandom(self) -> int:
            return random.choice(list(self.set))
    
    
    # Your RandomizedSet object will be instantiated and called as such:
    # obj = RandomizedSet()
    # param_1 = obj.insert(val)
    # param_2 = obj.remove(val)
    # param_3 = obj.getRandom()
Power of Three
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 20:00:47

Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_.

An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.

**Example 1:**

**Input:** n = 27
**Output:** true

**Example 2:**

**Input:** n = 0
**Output:** false

**Example 3:**

**Input:** n = 9
**Output:** true

**Constraints:**

*   `-231 <= n <= 231 - 1`

**Follow up:** Could you solve it without loops/recursion?**SOLUTION:**

    class Solution:
        def isPowerOfThree(self, n: int) -> bool:
            if n <= 0:
                return False
            while n % 3 == 0:
                n = n // 3
            return n == 1
JS Promises are monadic... just not the way you'd expect
Tags: javascript, promise, monad
Published: 2022-06-06 19:50:37

Note that these apply mostly to `Promise<NonPromiseType>`. Some properties do not hold due to the "unwrapping" of nested promises.

## FP definition <span id="fp-def"></span>

Based on Functional Programming definitions all we need are:
* a type constructor: `Promise<T>` for any `T`
* a `unit` / type converter: `Promise.resolve(value)`
* a `bind` / combinator: `Promise#then`
* have unit be left identity of bind (i.e. `unit(x) >>= f <=> f x`): `Promise.resolve(x).then(f)` is functionally the same as `f(x)`
* have `unit` be right identity of bind (i.e. `p >>= unit <=> p`): `myPromise.then(Promise.resolve)` is functionally the same as `myPromise`
* `bind` is associative (i.e. `ma >>= λx → (f(x) >>= g  <=>  (ma >>= f) >>= g`): `promise.then(x => f(x).then(g))` is functionally the same as `promise.then(f).then(g)`

Thus, we have proven `<Promise, Promise.resolve, Promise#then>` is a monad.

## Where it blocks

JS promises have one cool trick that makes them viable instead of all the alternatives we ever had (e.g. jQuery's deferred): they unwrap themselves.

For instance: `Promise.resolve(2).then(x => Promise.resolve(x * x)` is a `Promise<int>` and not a `Promise<Promise<int>>`. There are two ways to look at this:

* Nested promises cannot exist as a type
* Nested promises are aliases to their non-nested equivalents

The problems with the proof above is as follows:
```javascript
const x = Promise.resolve(2);
const f = px => px.then(x => x * 2);

f(x) !== Promise.resolve(x).then(f);
```

Because `Promise#then` is a continuation that gets a value as input (and not a promise), we cannot hold the left identity of `unit` of Promises for promises: we can only hold the left identity of Promises for values. That's because `Promise#then` plays the role of both `map` and `flatMap`.

Obviously this is the only situation this will bite you in the ass if you consider Promises monadic, otherwise you're absolutely free to treat them as that and start rewriting non async/await code to proper clean promise-based code:

```javascript
promise.then(x => {
 return fetch(x).then(f);
});

// <=>

promise
  .then(fetch)
  .then(f);
```
Tools of the Trade: Topgrade
Tags: beginners, opensource, tooling
Published: 2022-06-06 19:44:41

In the third post of this series, let's talk about `topgrade`.

# What is topgrade?
You've probably run into this scenario before: you have a package manager for your system; `brew` on Mac, `pacman` on Arch Linux etc, and you have a bunch of packages installed using these package managers.

Now comes the twist, you end up having several other package managers (eg: `pip`, `npm`); because nobody can agree on a standard and it's probably too far gone at this point to care anyway.

To keep the entirety of your system up to date, you end up having to run several commands, which eats up precious time that you could be spending watching cat videos.

`topgrade` remedies this situation by detecting the tools and package managers installed on your system and runs the appropriate commands to update them.

# How do I get it?
Pretty straightforward. `topgrade` provides packages for Arch Linux, NixOS, and Mac (via `homebrew` or `macports`).

If you're on a different platform or OS, install `topgrade` via the `cargo` package manager by running `cargo install topgrade`. 

If you're a normie who doesn't use Rust, go ahead and download one of the binaries available in the [releases](https://github.com/r-darwish/topgrade/releases) and place it on your `$PATH`.

# Usage
Dead simple. Just run `topgrade`.
[![asciicast](https://asciinema.org/a/499879.svg)](https://asciinema.org/a/499879)

And that's it from me. Enjoy those cat videos!
Models, Views, Controllers Ruby on Rails Basics
Published: 2022-06-06 19:36:40

I am currently working on my first Rails Application with a React frontend for my online software engineering program.  My application is a Yelp/Untapped clone where a client/user can login/signup.  Once that user is authenticated they can add a brewery to the database for any valid user to view and leave a review on.  I was required to have a many_to_many relationship, so `reviews` is my join table in this instance.  I wanted to share some of the basics of the MVC architecture.


#`Models`
Models are in charge of all of the methods we receive through ActiveRecord association ([ActiveRecord Associations and Methods](https://dev.to/walktheworld/active-record-associations-15go)). It handles all the business logic, dealing with state of the application.  Here is an example of how your `User` model may look:

```
class User < ApplicationRecord

  has_many :breweries,  dependent: :destroy

  has_many :reviews 

  has_many :reviewed_breweries, through: :reviews, source: :brewery
  
  has_secure_password

  validates :username, presence: true, uniqueness: true

end
```


#`Views`
The Views are responsible for generating the GUI (graphic user interface) and presenting the data to the user.

#`Controllers`
 The controllers are responsible for the communication between the user/views and the backend. Talking through the models to sort the database and send back the appropriate view to the user.  Here is an example of how your `User` controller may look:

```
class Api::UsersController < ApplicationController
  skip_before_action :authorized!, only: :create
  
  def index
    render json: User.all
  end

  def create
    user = User.create!(user_params)
    session[:user_id] = user.id
    render json: user, status: :created
  end

  def show
    render json: @current_user
  end

  def profile
    reviewed = @current_user.reviewed_breweries
    render json: reviewed
  end

  private
  def serialized_user
    @user.to_json(include: :breweries)
  end

  def user_params
    params.permit(:username, :password, :password_confirmation, :image_url, :bio)
  end
end
```

I know how hard it can be to sift through the endless documents of info out there.  I hope this helps you, as it did for me, retain some of the basics during your learning process. 

```Happy Coding!```

*Resources:
(https://guides.rubyonrails.org/active_record_basics.html)*
Repeated Substring Pattern
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 19:30:40

Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

**Example 1:**

**Input:** s = "abab"
**Output:** true
**Explanation:** It is the substring "ab" twice.

**Example 2:**

**Input:** s = "aba"
**Output:** false

**Example 3:**

**Input:** s = "abcabcabcabc"
**Output:** true
**Explanation:** It is the substring "abc" four times or the substring "abcabc" twice.

**Constraints:**

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

**SOLUTION:**

    class Solution:
        def repeatedSubstringPattern(self, s: str) -> bool:
            n = len(s)
            for l in range(1, 1 + (n // 2)):
                valid = True
                prev = None
                for i in range(0, n, l):
                    if prev and prev != s[i:i+l]:
                        valid = False
                        break
                    prev = s[i:i+l]
                if valid:
                    return True
            return False
How to Encourage and Develop Female Software Engineers
Tags: webdev, devops, career, news
Published: 2022-06-06 19:29:25

Learn what it was like for Valli to be a software engineer on teams comprised mostly of men. Hear her thoughts on [how leaders can encourage and develop female software engineers](https://community.lohika.com/home/videos/how-to-encourage-and-develop-female-software-engineers-2022-02-01) from this on-demand recording [here](https://community.lohika.com/home/videos/how-to-encourage-and-develop-female-software-engineers-2022-02-01)
How to install latest version of packages on Amazon Linux 1
Published: 2022-06-06 19:20:52

As we all know that Amazon linux 1 support is no linger available ,hence some of the latest packages are not available for the same,I faced this issue while installing nrpe v 4.0.0 for nagios, The supported version for amazon linux was only 2.3
But I was able to install nrpe 4.0.0 package on my instance my changing the "OS" value in /etc/release file from "Amazon Linux 1" to "Cent OS" .

Since both are Red Hat based, most of the packages might work using this trick
Easy CLI budget calculator
Tags: cli, bash, sqlite, finance
Published: 2022-06-06 19:18:18

Tired of collecting bank account data in order to get a grip on your spending? 

Get started easily with this simple daily budget calculator. Not a calculator for your next big expense. 
Only a straightforward answer to the question: _How much can I spend today?_

[repo YNAB](https://codeberg.org/miccaman/YNAB) 

Feedback welcome.