teleren/devto huggingface dataset:
1745. Leetcode Solution in Java
Tags: java
Published: 2022-07-17 05:50:13

```
class Solution {
    public boolean checkPartitioning(String s) {
        int length = s.length();
        boolean[][] isPalindrome = new boolean[length][length];
        for (int i = 0; i < length; i++)
            isPalindrome[i][i] = true;
        for (int i = 1; i < length; i++)
            isPalindrome[i - 1][i] = s.charAt(i - 1) == s.charAt(i);
        for (int i = length - 3; i >= 0; i--) {
            for (int j = i + 2; j < length; j++)
                isPalindrome[i][j] = isPalindrome[i + 1][j - 1] && s.charAt(i) == s.charAt(j);
        }
        int maxFirst = length - 3, maxSecond = length - 2;
        for (int i = 0; i <= maxFirst; i++) {
            if (isPalindrome[0][i]) {
                for (int j = i + 1; j <= maxSecond; j++) {
                    if (isPalindrome[i + 1][j] && isPalindrome[j + 1][length - 1])
                        return true;
                }
            }
        }
        return false;

        /* also working, but a little lower efficiency

        for (int i = 0; i <= maxFirst; i++) {
                for (int j = i + 1; j <= maxSecond; j++) {
                    if (isPalindrome[0][i] && isPalindrome[i + 1][j] && isPalindrome[j + 1][length - 1])
                        return true;
                }
        }
        */

    }
}
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/palindrome-partitioning-iv/
Error handling in fetching data via HTTP
Tags: errors, exception, handling
Published: 2022-07-17 01:47:38

---
title: Error handling in fetching data via HTTP
published: true
description: 
tags: error,exception,handling
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

Fetching data from REST APIs or a plain HTTP server is usually a part of my work. Many problems may arise during fetching data; for example,  a server goes offline, my storage is out of space, an API gives the wrong URL, a server sends data in an invalid format, etc. To illustrate the situation, I can oversimplify my task to the function below:

```Python
def fetch(uri):
    requests.get(uri)
```

A fetcher usually faces one of these problems. I don't want to rerun a fetcher after running it for an hour or a day. Maybe I can write my fetcher to resume working after it stops at any state, but it will take time, and my fetcher will be more complex. If I code in Python, the fetch function can raise many exceptions, and my fetcher will stop because my code didn't handle any exceptions.

I see two types of environments that will help me fix the problem. 

1. Type checker may help me handle as many types of exceptions as possible upfront. Java definitely can do this because, in Java, I have to declare the list of exceptions as a part of the fetch function, and Javac checks if the caller handles these exceptions. Rust doesn't use a Java-like exception, but the result type encodes the types of errors, so the Rust compiler can check if a caller handles these errors.

2. Common Lisp runtime will run a debugger if unhandled errors occur. So I can choose what to do next. For example, I can empty my trash folder if my storage is out of space. I still don't know if I can handle the storage space problem later with Erlang runtime. 

Python doesn't seem to belong to (1) nor (2). I tried mypy, a static type checker for Python, but it didn't warn me anything. And I don't know how to retry or do something else with Python's exception system rather than let it stop.
132. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 05:48:24

```
class Solution:
  def minCut(self, s: str) -> int:
    n = len(s)
    cut = [0] * n
    dp = [[False] * n for _ in range(n)]

    for i in range(n):
      mini = i
      for j in range(i + 1):
        if s[j] == s[i] and (j + 1 > i - 1 or dp[j + 1][i - 1]):
          dp[j][i] = True
          mini = 0 if j == 0 else min(mini, cut[j - 1] + 1)
      cut[i] = mini

    return cut[n - 1]

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/palindrome-partitioning-ii/
18. Leetcode Solution in JavaScript
Tags: javascript
Published: 2022-07-17 05:45:40

```
var fourSum = function(nums, target) {
    nums.sort((a,b) => a-b)
    console.log(nums)
    let ans = [], len = nums.length;
    for(let i = 0; i < len; i ++ ){
         for(let j = i+1; j < len-1; j ++ ){
             let left = j+1, right = len-1
             while(left < right){
                 let sum = nums[left] + nums[right] + nums[i] + nums[j]
                 if(sum == target){
                     ans.push([nums[i],nums[j], nums[left], nums[right]]);
                     while(nums[left] == nums[left+1]){
                         left++
                     }
                     while(nums[right] == nums[right-1]){
                         right--
                     }
                     left++
                     right--
                 } else if (sum < target){
                     left++
                 } else {
                     right--
                 }
             }
             while(nums[j] == nums[j+1]){
                 j++
             }
    }
        while(nums[i] == nums[i+1]){
                 i++
             }
    }
    return ans
};
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/4sum/
Reading: C++11 perfect forwarding
Published: 2022-07-17 05:43:46

---
title: Reading: C++11 perfect forwarding
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

[This article](https://www.yuanguohuo.com/2018/05/25/cpp11-perfect-forward/) explains C++11 perfect forwarding and reference collapsing.

It is partly of a translation of [this article](http://thbecker.net/articles/rvalue_references/section_07.html). So I'll read on.
1452. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 05:43:01

```
class Solution:
  def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
    ans = []
    n = len(favoriteCompanies)
    companies = [set(comp) for comp in favoriteCompanies]

    for i in range(n):
      find = False
      for j in range(n):
        if i == j:
          continue
        if companies[i].issubset(companies[j]):
          find = True
          break
      if not find:
        ans.append(i)

    return ans

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/
Brain App - Give Quizes and explore news
Tags: android, requestly, kotlin, opensource
Published: 2022-06-12 07:16:13

Hello there , I am Ashish Ranjan from Birla Institute of Technology , Mesra. I made a Quiz App which is the assignment for Requestly. First of all , I thank Mr.Sachin Jain , Founder & CEO Requestly for giving me this opportunity.

In this app which is made of android where there are 10 questions which has 4 options - one correct. This app includes ---
- First at starting screen user has to type his/her name (otherwise it shows message "Please Enter Your Name") then only they can enter to the home screen where there are two option quiz and news.
- In quiz section , Users should see questions one by one like some general knowledge questions, images and give them 4 options.
- When user selects an Incorrect option, that options becomes red and correct option shows up in green and there is message "Sorry, This is Wrong Answer :(" and change the question.
- When user selects a correct option ,that option becomes green and show a message "Bravo Right Answer :)" and move on the next question.
- When user has made the 10 attempts, show them their score.
- In news section , user can see latest news which I called using news API.
- When clicked to certain news , that news will open where it is published in that screen only.

In this app I have integrate Requestly Android Debugger , which make easy for me to debug API traffic. 
We can integrate this debugger in very easy steps -

- We have to first copy 
dependencies {
  debugImplementation "io.requestly.rqinterceptor:library:1.+"
  releaseImplementation "io.requestly.rqinterceptor:library-no-op:1.+"
} in our build.gradle

- Then we have to add requestly interceptor in our okhttp/Retrofit Client which includes following code - 
val collector = RQCollector(context=appContext, sdkKey=" ")
val rqInterceptor = RQInterceptor.Builder(appContext).collector(collector).build()
val client = OkHttpClient.Builder().addInterceptor(rqInterceptor).build()

- Then we can test integration and see how our app runs and its processes.




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bx24lzrdb2ignwnntlf.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lvj81oqchgt4ep7g5y4z.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gj223ior2ks2z9ae5nxp.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7ixd8foo5emraar559b.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igr2j4byuu8jffcl4cdc.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/art0sykxuz9by10tcmua.png)
1452. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 05:42:18

```
class Solution {
public:
    template <typename T>
    bool IsSubset(std::vector<T> A, std::vector<T> B)
    {
        std::sort(A.begin(), A.end());
        std::sort(B.begin(), B.end());
        return std::includes(A.begin(), A.end(), B.begin(), B.end());
    }
    
    vector<int> peopleIndexes(vector<vector<string>>& favoriteCompanies) {
        int n = favoriteCompanies.size();
        
        vector<int> ans(n);
        
        iota(ans.begin(), ans.end(), 0);
        
        for(int i = 0; i < n; i++){
            sort(favoriteCompanies[i].begin(), favoriteCompanies[i].end());
        }
        
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(j == i) continue;
                // cout << "compare " << i << " and " << j << endl;
                if(std::includes(favoriteCompanies[j].begin(), favoriteCompanies[j].end(),
                  favoriteCompanies[i].begin(), favoriteCompanies[i].end())){
                // if(IsSubset(favoriteCompanies[j], favoriteCompanies[i])){
                    // cout << i << " in " << j << endl;
                    auto it = find(ans.begin(), ans.end(), i);
                    if(it != ans.end()){
                        ans.erase(it);
                    }
                    break;
                }
            }
        }
        
        return ans;
    }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/
107. Leetcode Solution in Java
Tags: java
Published: 2022-07-17 05:40:43

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for(int i=0; i< size; i++){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
            res.add(list);
        }

        Collections.reverse(res);

        return res;
    }
}
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
1679. Leetcode Solution in Java
Tags: java
Published: 2022-07-17 05:39:13

```
class Solution {
    public int maxOperations(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int n : nums) {
            if (n < k) {
                map.put(n, map.getOrDefault(n, 0) + 1);
            }
        }
        
        int res = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int n1 = entry.getKey();
            
            if (n1 > (k / 2)) {
                continue;
            }
            
            int v1 = entry.getValue();
            int n2 = k - n1;
            
            if (n1 == n2) {
                res += (v1 / 2);
            } else {
                Integer v2 = map.get(n2);
                if (v2 != null) {
                    res += Math.min(v1, v2);
                }
            }
        }
        
        return res;
    }
}
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/max-number-of-k-sum-pairs/
2281. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 05:36:49

```
class Solution:
    def totalStrength(self, strength: List[int]) -> int:
        n = len(strength)
       
        left, right, st = [-1] * n, [n] * n, []
        for i, v in enumerate(strength):
            while st and strength[st[-1]] >= v: right[st.pop()] = i
            if st: left[i] = st[-1]
            st.append(i)

        ss = list(accumulate(accumulate(strength, initial=0), initial=0))  

        ans = 0
        for i, v in enumerate(strength):
            l, r = left[i] + 1, right[i] - 1 
            tot = (i - l + 1) * (ss[r + 2] - ss[i + 1]) - (r - i + 1) * (ss[i + 1] - ss[l])
            ans += v * tot  
        return ans % (10 ** 9 + 7) 


```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/sum-of-total-strength-of-wizards/
1799. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 05:34:00

```
class Solution {
    int dfs(const vector<int>& nums, int round, int state, unordered_map<int, int>& cache) {
        if (round > nums.size() / 2) {
            return 0;
        }
        if (cache.count(state) > 0) {
            return cache[state];
        }
        
        int ans = 0;
        for (int i = 0; i < nums.size(); i++) {
            for (int j = i + 1; j < nums.size(); j++) {
                int picked = (1 << i) | (1 << j);
                if ((state & picked) == 0) {
                    ans = max(ans, round * __gcd(nums[i], nums[j]) + dfs(nums, round + 1, state | picked, cache));
                }
            }
        }

        return cache[state] = ans;
    }
public:
    int maxScore(vector<int>& nums) {
        unordered_map<int, int> cache;
        return dfs(nums, /*round=*/1, /*state=*/0, cache);
    }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/maximize-score-after-n-operations/
Amazon S3:
Tags: s3, amazon3s, objectstorage, cloudstorage
Published: 2022-07-17 05:31:06

Amazon S3 stands for **S**imple **S**torage **S**ervice and is a scalable, high -speed   cloud storage served via a web interface. It is first amazon’s service and played a major role in the growth of Amazon Web Service.

Since its launch date in 2006, many more features have been added to the Simple Storage Service but the core functionality has remained the same which is: making Object Storage available on the cloud top the mass. 

 S3 was Initially designed to cater to companies looking to store their ever-growing data in the cloud by offering online backup, Disaster recovery and Archiving.  Since them, S3 has evolved and now can be used for many other purposes such as hosting static Websites.
 
 Amazon also offer a free tier for S3. With that free tier comes 5GB of standard storage class, 20, 000 Get Requests and 2,00 Put, Copy, Post or List Requests.  To learn more about Amazon S3 pricing, click [here](https://aws.amazon.com/s3/pricing/?p=pm&c=s3&z=4)

With S3, it is  possible to upload of file or object up to 5 gigabytes. However, it is possible to upload up to 5 Terabyte of data to via multi-part upload.

## Durability 

AWS S3 offer the possibility to store unlimited and unstructured data on the cloud with almost unmatched durability of 99.999999999%. of objects over a given year. This means that over the course of a year, you are only expected to lose 0.000000001% of objects. This is pretty good 

## Availability 

  AWS S3 also offers some amazing numbers when it comes to availability, which means the ability of data to be continuously access.  When it comes to availability, numbers vary according to the storage tiers used (I will be publishing another article focused on Storage tier later on).    S3 still offer 99% with some slight variations.  It is worth mentioning that items that are not available at a giving time are not lost and will be accessible at a later time. 

Below are the numbers.

99.99% for Standard storage class.
99.9% for Intelligent-Tiering class.
99.9% for Standard Infrequent Access storage class.
99.5% for One-Zone Infrequent Access storage class.
99.99% for Glacier and Glacier Deep-Archive classes.

  As an object Storage area of application where S3 is preferred are the following ones:
•	Databases 
•	Email servers
•	Virtual Machines file system (Boot Volume)
•	RAID Arrays (High Redundancy)
•	High performance compute 
 In addition to that, applications that require server-side processing suck as Java, PHP AND .NET are the best candidate for Block Storage since they need to be as close as possible to the storage to reduce latency.
1655. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 05:26:32

```
class Solution {
public:
  bool canDistribute(vector<int>& nums, vector<int>& quantity) {
    unordered_map<int, int> m;
    for (int x : nums) ++m[x];
    vector<int> cnt;
    for (const auto& [x, c] : m) cnt.push_back(c);
    
    const int q = quantity.size();
    const int n = cnt.size();
    function<bool(int)> dfs = [&](int d) {
      if (d == q) return true;
      for (int i = 0; i < n; ++i) 
        if (cnt[i] >= quantity[d]) {
          cnt[i] -= quantity[d];
          if (dfs(d + 1)) return true;
          cnt[i] += quantity[d];
        }
      return false;
    };
    
    sort(rbegin(cnt), rend(cnt));
    sort(rbegin(quantity), rend(quantity));
    
    return dfs(0);
  }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/distribute-repeating-integers/
Choosing Technologies as a Senior Dev
Tags: senior, webdev
Published: 2022-07-17 05:22:45

I found an interesting change in my perspective upon becoming an actual Senior Developer.  Of course my responsibilities increased: I'm expected to mentor lesser experienced devs and new employees, and talk with PMs, BAs, and upper management more. But of interest is deciding on some of the tools and technologies we use going forward. And sometimes, selling that to a team that may not be all that thrilled with my choices.  

Formerly my choice of technology came down to one of two things.  First, what was new, what was hot, what was growing in popularity with the speed of a rocket.  I wanted in on those bandwagons and a lot of my peers did too.  Second was technical specs.  What was more performant, what elided boilerplate, what had good tooling. 

But now I have not only newer concerns but larger ones and they are this:  what does the team already know?  What could the team learn quickly based on analogous things to technologies we already use?  What is the expected lifespan of any new tech we bring into our business?  What are the security and licensing ramifications? What other tools exist in its ecosystem, and are they mature?

These new concerns pretty much obliterate my previous measures of desirability. I'm more concerned with the long-term stability of software and the short-term training of people than I have ever been in my life. I'm concerned with budget, with time and money, despite that I'm NOT the one who wields the schedule. 

I used to be the outspoken one that wasn't afraid to express his dissatisfaction with management for their clueless tech takes.

Now I am the boss monster.  Now I feel I owe an apology to twenty or thirty years' worth of my former managers.
1766. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 05:22:23

```
class Solution {
    
    void dfs(int node, const vector<int>& nums, const vector<vector<int>>& graph,
             vector<int>& result,
             map<int, pair<int, int>>& ancestors /*value, {node, depth}*/,
             int depth, int parent) {
        int closest_ancestor = -1;
        int distance = INT_MAX;
        for (const auto& pair : ancestors) {
            if (__gcd(nums[node], pair.first) == 1 && (depth - pair.second.second) < distance) {
                distance = depth - pair.second.second;
                closest_ancestor = pair.second.first;
            }
        }
        result[node] = closest_ancestor;
        
        bool has_original_node = (ancestors.count(nums[node])) > 0;
        pair<int, int> original_node = ancestors[nums[node]];
        ancestors[nums[node]] = {node, depth};
        for (int neighbor : graph[node]) {
            if (neighbor == parent) {
                continue;
            }
            dfs(neighbor, nums, graph, result, ancestors, depth + 1, node);
        }
        ancestors.erase(nums[node]);
        if (has_original_node) {
            ancestors[nums[node]] = original_node;
        }
    }
    
public:
    vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {
        int n = nums.size();
        vector<vector<int>> graph(n);
        for (const vector<int>& edge : edges) {
            graph[edge[0]].push_back(edge[1]);
            graph[edge[1]].push_back(edge[0]);
        }
        
        map<int, pair<int, int>> ancestors;
        vector<int> result(n, -1);
        dfs(/*node=*/0, nums, graph, result, ancestors, /*depth=*/0, /*parent=*/-1);
        return result;
    }
};
```


#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/tree-of-coprimes/
CSS Layers - Tackling specificity in CSS
Tags: css, programming, tutorial, react
Published: 2022-07-17 05:19:00

## Do you know that:

There are 3 different layers in CSS that govern how all styles work?

- Browser (also known as user agent) styles
- User styles
- Author styles


Browser styles are the default styles applied to your browser. This is why buttons in Chrome and Safari look different. The styles found in the browser layer are different between browsers and give each browser a unique look.


The next layer is user styles which is not really something that you have to worry about. These are generally custom styles that users can write and inject into their browser, but that is not really supported anymore by browsers. There may be some browser settings that users can change which will add styles to this layer, but for the most part this layer can be completely ignored.


Finally, we come to the author layer. This is the layer you are most familiar with since every piece of CSS code you write falls within this layer.


The reason these layers are separate is because it makes overwriting the code defined in browser styles and user styles very easy since layers define their own hierarchy that completely ignores specificity.

## Read more here: 👇

Originally posted: https://blog.webdevsimplified.com/2022-04/css-cascade-layers/ 

### Paul Ishaili C.
`Traditional Creative Director, Software Engineer, and Tech Writer.`