teleren/devto huggingface dataset:
Decode Ways
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 01:30:40

A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106"` can be mapped into:

*   `"AAJF"` with the grouping `(1 1 10 6)`
*   `"KJF"` with the grouping `(11 10 6)`

Note that the grouping `(1 11 06)` is invalid because `"06"` cannot be mapped into `'F'` since `"6"` is different from `"06"`.

Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.

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

**Example 1:**

**Input:** s = "12"
**Output:** 2
**Explanation:** "12" could be decoded as "AB" (1 2) or "L" (12).

**Example 2:**

**Input:** s = "226"
**Output:** 3
**Explanation:** "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

**Example 3:**

**Input:** s = "06"
**Output:** 0
**Explanation:** "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").

**Constraints:**

*   `1 <= s.length <= 100`
*   `s` contains only digits and may contain leading zero(s).

**SOLUTION:**

    class Solution:
        memo = {}
        
        def isCorrect(self, n):
            if n[0] == "0":
                return False
            return int(n) >= 1 and int(n) <= 26
        
        def numDecodingsRec(self, s):
            if len(s) == 0:
                return 1
            if len(s) == 1:
                if self.isCorrect(s):
                    return 1
                else:
                    return 0
            if s in self.memo:
                return self.memo[s]
            numWays = 0
            if self.isCorrect(s[:1]):
                numWays += self.numDecodingsRec(s[1:])
            if self.isCorrect(s[:2]):
                numWays += self.numDecodingsRec(s[2:])
            self.memo[s] = numWays
            return numWays
        
        def numDecodings(self, s: str) -> int:
            self.memo = {}
            return self.numDecodingsRec(s)
3Sum With Multiplicity
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 01:00:42

Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`.

As the answer can be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8
**Output:** 20
**Explanation:** 
Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

**Example 2:**

**Input:** arr = \[1,1,2,2,2,2\], target = 5
**Output:** 12
**Explanation:** 
arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times:
We choose one 1 from \[1,1\] in 2 ways,
and two 2s from \[2,2,2,2\] in 6 ways.

**Example 3:**

**Input:** arr = \[2,1,3\], target = 6
**Output:** 1
**Explanation:** (1, 2, 3) occured one time in the array so we return 1.

**Constraints:**

*   `3 <= arr.length <= 3000`
*   `0 <= arr[i] <= 100`
*   `0 <= target <= 300`

**SOLUTION:**

    class Solution:
        def threeSumMulti(self, arr: List[int], target: int) -> int:
            d = [0] * 300
            res = 0
            for i, el in enumerate(arr):
                res += d[target - el] if target - el >= 0 else 0
                for j in range(i):
                    d[el + arr[j]] += 1
            return res % (10 ** 9 + 7)
Parameter Passing
Tags: programming, cpp, beginners
Published: 2022-06-18 00:59:25

In C++ there are 3 ways to pass parameter to function -

1. Pass by Value  
2. Pass by Reference
3. Pass by Pointers

I will discuss one of them here.

###Pass by Value
In pass by value , each function have their own local variables and the variables have their own local scope.
```cpp
#include <iostream>
using namespace std;

void swap( int a , int b){
int temp = a;
a = b; 
b = temp;
cout<< "Values inside swap function , a is "<<a<<" and b is "<<b<<endl;
}

int main(){
int a = 10 ;
int b = 20;
cout<<"Before swapping a is "<<a<<" and b is "<<b<<endl;
swap(a,b);
cout<<"After swapping a is "<<a<<" and b is "<<b<<endl;

return 0;
}


```

Here if we run this code , we'll find that the values are only swapped in the swap function but when the activation record of swap function is delete when code control comeback to main function , the values of "a" and "b" are unchanged . That's because both "main" and "swap" function have their own "a" and "b" variables. 

Pass by value is a good choice when we want to return the result without changing the value of original variables . For example :- 

```cpp
int add(int a, int b){
return a+b;
}
```

We will learn _Pass by Reference_ next time.
Palindrome Partitioning
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 00:30:40

Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return all possible palindrome partitioning of `s`.

A **palindrome** string is a string that reads the same backward as forward.

**Example 1:**

**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]

**Example 2:**

**Input:** s = "a"
**Output:** \[\["a"\]\]

**Constraints:**

*   `1 <= s.length <= 16`
*   `s` contains only lowercase English letters.

**SOLUTION:**

    class Solution:
        def isPalindrome(self, s, i, j):
            if i >= j - 1:
                return s[i] == s[j - 1]
            if s[i] == s[j - 1]:
                return self.isPalindrome(s, i + 1, j - 1)
            return False
        
        def getPos(self, s, i, n):
            if i == n:
                return [[]]
            op = []
            for j in range(i + 1, n + 1):
                if self.isPalindrome(s, i, j):
                    curr = s[i:j]
                    val = self.getPos(s, j, n)
                    op += [[curr] + v for v in val]
            return op
        
        def partition(self, s: str) -> List[List[str]]:
            return self.getPos(s, 0, len(s))
Basic Linux Commands 101 pt1
Tags: tutorial, linux, ubuntu
Published: 2022-06-18 00:21:03

A very important tool any computer nerd should know is the Linux command line. Today we'll be going over simple but affective Linux commands that every computer nerd should be aware of. 😁

Starting with 
1. `pwd` will print the name of the current/working directory. 
![pwd](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shkl4df61razmffzfbf2.png)
2. `ls` & `ls -la` will provide details and list the contents of the current working directory. 
![ls](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/is3we4pyh685z6jnk6za.png)
![ls-la](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/omml3n5ezy9z37fqzfyu.png)
3. `cd` command is used for moving up down directories.
![cd](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ok4k0xmc2x9k910ykoo3.png) 
4. `touch` can be used for creating new empty files.
![touch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25lho1h4wsan8tcmyhcj.png)
5. `cat` will display the contents of a file. This file contains nothing, so let's add some data by using a text editor.
![cat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vl562n90e5ix6y3gx5qt.png)
6. `nano` is a small text editor, that can be used for editing texts of file.
![nano](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ilpbiddc1sy8gygv6kxd.png)
Press `Ctrl+O` to save, then `Ctrl+X` to exit
![nano1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zjibxmr258a9u8m0l9q.png)
We can then use `cat` once again to check if the edits were saved.
![cat2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cy7wunaewrpiilnm40t3.png)
7. You can also extract specific information from a file using the `grep` command.
![grep](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xlsnwpe6bdq4v3afkigq.png)
8. You can use `mkdir` to create a new directory for transferring files.
![mkdir](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iu21s0dskamr3i3r6yr9.png)
9. `mv` can be used for moving files from a directory into another. `mv *.txt ~/Desktop` will move all files that end with the .txt extension into the desktop directory.
![mv](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypkp5sxv4evrvrtkhi22.png)
10. `cp` can be used for copying files into another directory.
![cp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k39aniaw4odimoi96obx.png)
11. Last but not least, the `rm`, which can be used for removing files from the disk. 
![rm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sp4sfn3wjoo4yignz0x7.png)

Thanks for reading
Kenji
Find Median from Data Stream
Tags: leetcode, dsa, theabbie
Published: 2022-06-18 00:00:42

The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

*   For example, for `arr = [2,3,4]`, the median is `3`.
*   For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.

Implement the MedianFinder class:

*   `MedianFinder()` initializes the `MedianFinder` object.
*   `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
*   `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.

**Example 1:**

**Input**
\["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"\]
\[\[\], \[1\], \[2\], \[\], \[3\], \[\]\]
**Output**
\[null, null, null, 1.5, null, 2.0\]

**Explanation**
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = \[1\]
medianFinder.addNum(2);    // arr = \[1, 2\]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr\[1, 2, 3\]
medianFinder.findMedian(); // return 2.0

**Constraints:**

*   `-105 <= num <= 105`
*   There will be at least one element in the data structure before calling `findMedian`.
*   At most `5 * 104` calls will be made to `addNum` and `findMedian`.

**Follow up:**

*   If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
*   If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?

**SOLUTION:**

    import heapq
    
    class MedianFinder:
    
        def __init__(self):
            self.left = []
            self.right = []
    
        def addNum(self, num: int) -> None:
            left = self.left
            right = self.right
            if len(right) == 0:
                heapq.heappush(right, num)
            elif num < right[0]:
                heapq.heappush(left, -num)
            elif num >= right[0]:
                heapq.heappush(right, num)
            if len(left) > len(right) + 1:
                heapq.heappush(right, -heapq.heappop(left))
            if len(right) > len(left) + 1:
                heapq.heappush(left, -heapq.heappop(right))
    
        def findMedian(self) -> float:
            left = self.left
            right = self.right
            if len(left) == len(right):
                return (right[0] - left[0]) / 2
            if len(left) > len(right):
                return -left[0]
            if len(left) < len(right):
                return right[0]
    
    
    # Your MedianFinder object will be instantiated and called as such:
    # obj = MedianFinder()
    # obj.addNum(num)
    # param_2 = obj.findMedian()
Web Scraping Tutorial - Elixir API Server with a Chrome Extension
Published: 2022-06-17 23:40:06


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

{% embed https://www.youtube.com/watch?v=7x-R6eTbigA&feature=youtu.be %}

Imagine a site cars classification and You should follow a change the prices the determinate Vehicle Models. I called the fake site ‘FakeCars’, the site with a lot system anti-bots systems. Difficult to use Web Scraping default, but it doesn't impossible!

We choose models for price tracking with the idea of creating a Chrome Extension to reading the total number of ads for the page and sending for our API Server. We analyze their prices week-by-week.

Using stack for Price Tracking:

- API server in Elixir with Phoenix framework — Coding in next post, in then moment our using the URL for API server: "http://localhost:4000/api/v1/chrome_ads/"

- Chrome Extension in JavaScript

## Coding Chrome Extension

_Structure for a chrome extension_
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6qwxdo24gvip55k2p6g.png)


Our code
_manifest.json v.3_

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

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

_js/popup.js_

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

_js/fakecars_contentscript.js_

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


The JSON structure sent to API Server a for each page read.

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

## Coding API server

1 - Creating the Phoenix app
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39aw2uizroa6tza8qgvj.png)

2 - Configure in config/dev.exs your PostgreSQL login.

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

- Creating ad model
```
$ mix phx.gen.schema Vehicle.Ad vehicle_ads ad_date:utc_datetime ad_id:string ad_source:string city:string km:integer price:integer state:string vehicle_brand:string vehicle_model:string vehicle_version:string year_manufacture:integer year_model:integer active:boolean
```

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

- Create the database and run migrate
```
$ mix ecto.create
$ mix ecto.migrate
```

- Configure in 'lib/ads_api_web/route.ex' : 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2z9n5mlhwrkm4qlek9g.png)

- Finally, we create api_controller.ex in 'lib/ads_api_web/controllers/' for consuming the JSON received and saving it in the database.
Kth Smallest Element in a BST
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 23:30:41

Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg)

**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg)

**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3

**Constraints:**

*   The number of nodes in the tree is `n`.
*   `1 <= k <= n <= 104`
*   `0 <= Node.val <= 104`

**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def inorder(self, root, k):
            if root:
                self.inorder(root.left, k)
                self.i += 1
                if self.i == k:
                    self.kth = root.val
                self.inorder(root.right, k)
        
        def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
            self.i = 0
            self.kth = None
            self.inorder(root, k)
            return self.kth
Sorting the Sentence
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 23:00:41

A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.

A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence.

*   For example, the sentence `"This is a sentence"` can be shuffled as `"sentence4 a3 is2 This1"` or `"is2 sentence4 This1 a3"`.

Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_.

**Example 1:**

**Input:** s = "is2 sentence4 This1 a3"
**Output:** "This is a sentence"
**Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.

**Example 2:**

**Input:** s = "Myself2 Me1 I4 and3"
**Output:** "Me Myself and I"
**Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.

**Constraints:**

*   `2 <= s.length <= 200`
*   `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`.
*   The number of words in `s` is between `1` and `9`.
*   The words in `s` are separated by a single space.
*   `s` contains no leading or trailing spaces.

**SOLUTION:**

    class Solution:
        def sortSentence(self, s: str) -> str:
            ogwords = s.split()
            words = ogwords[:]
            for w in ogwords:
                words[int(w[-1]) - 1] = w[:-1]
            return " ".join(words)
Kafka Messages Lost
Tags: kafka
Published: 2022-06-17 22:51:04

I am a newbie to Kafka and trying to setup Kafka on EC2 Windows 2019 Instances  

**_Issue _**
On a "Single Zookeeper & Broker on same EC2 Instance"
I was able to produce and consume messages.   

But if I move the Broker to another EC2 Instance the Producer  messages are not showing up in the Consumer. Kafka server.properties has the Zookeeper IP Address:2181 Port Configured. The Ports in the Zookeeper Security Group have been configured in the inbound rules. Ports 2888-3888, 2181, 9092

**_Commands Used_**
--Start Zookeeper
Run zkserver on C:\Data\softwares\zookeeper\bin
kafka-server-start.bat 
--Start Kafka
C:\data\softwares\kafka\config\server.properties

--create topic 
kafka-topics.bat --create --bootstrap-server <IP Address>:9092 --replication-factor 1 --partitions 1 --topic multinodetopic
--create producer
kafka-console-producer.bat --broker-list <IP Address>:9092 --topic multinodetopic
--create consumer
kafka-console-consumer.bat --bootstrap-server <IP Address>:9092 --topic multinodetopic ––from-beginning****
Longest Palindromic Subsequence
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 22:30:47

Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.

A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

**Example 1:**

**Input:** s = "bbbab"
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb".

**Example 2:**

**Input:** s = "cbbd"
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb".

**Constraints:**

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

**SOLUTION:**

    class Solution:
        cache = {}
        
        def maxPalindrome(self, s, i, j):
            key = 1100 * i + j
            if (key) in self.cache:
                return self.cache[key]
            if i == j:
                self.cache[key] = 1
            elif s[i] == s[j] and i + 1 == j:
                self.cache[key] = 2
            elif s[i] == s[j]:
                self.cache[key] = self.maxPalindrome(s, i + 1, j - 1) + 2
            else:
                self.cache[key] = max(self.maxPalindrome(s, i, j - 1), self.maxPalindrome(s, i + 1, j))
            return self.cache[key]
            
        def longestPalindromeSubseq(self, s: str) -> int:
            self.cache.clear()
            return self.maxPalindrome(s, 0, len(s) - 1)
What was your win this week?
Tags: discuss, weeklyretro
Published: 2022-06-17 22:30:09

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey there! 


Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Attending CodeLand... or whatever else might spark joy ❤️ 

---

Have a wonderful weekend!

![Elmo dancing around in a party hat over a blue background](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/knom1otmggk9ehl57bot.gif)
Day 70: Research: Docker, Rust, GoLang
Published: 2022-06-17 22:12:20

Hi!
Today was okay, not much task to do on my end so I was just helping friends with their tasks. I got a chance to do some research Docker and the new programming language maybe I may try to get started looking into.
About Docker I had been postponing learning but I think in the upcoming months I may be forced to used to so I  have to be familiar with it ASAP so I may start creating articles about it soon. About the programming language I think it's by time I start looking into a new programming Language just to have another angle of looking at programming in general so some of the pick include Rust, Go, and maybe Ruby I'm still looking into what each has to offer and trying to spare some time for learning it in my daily agenda. for this learning I plan to do a separate Journaling plan specifically for the language itself so that's something that may come also in the few days.
Tomorrow I plan to look into Docker, Next.js or Sass I think Sunday will be for rest as it should be anyway :)
that's all for now
Signing off....
Software Engineering is a Total Trip
Tags: dotnet, testing, discuss, career
Published: 2022-06-17 22:10:56

Software engineering can be really annoying at times but it is also hilarious and super intellectually challenging. I just switched Dev groups in my company. I worked on an internal Data Deletion GDPR service for almost 2.5 years. The project went nowhere and nobody actually wanted it. Requirements were vague. Devs and PMs left the project left and right. Yet the project lives on because some VP wants it to. IMHO, it is a huge waste of valuable developer time.

But despite all of that I loved the daily hilarity of working on a doomed project with so many outstanding Devs on it. From a technical standpoint I wrote the most complex C# API automation code ever. For example, automating APIs that accept two totally different types of JWTs and having to update a database during tests to accelerate background processes. Great challenging stuff. Bittersweet describes my feelings leaving a team of great people and even this project. Even though being a Dev is frustrating at times it's also awesome. We are blessed to have a career that is challenging, constantly amusing, and financially rewarding.