teleren/devto huggingface dataset:
965. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:56:58

```

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if (!root) return true;
        if (root->left && root->left->val != root->val) return false;
        if (root->right && root->right->val != root->val) return false;
        return isUnivalTree(root->left) && isUnivalTree(root->right);
    }
};
```
966. lrrtcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:55:52

```
class Solution {
 public:
  vector<string> spellchecker(vector<string>& wordlist,
                              vector<string>& queries) {
    vector<string> ans;
    unordered_map<string, string> dict;

    for (const string& word : wordlist) {
      dict.insert({word, word});
      dict.insert({lowerKey(word), word});
      dict.insert({vowelKey(word), word});
    }

    for (const string& q : queries)
      if (dict.count(q))
        ans.push_back(dict[q]);
      else if (dict.count(lowerKey(q)))
        ans.push_back(dict[lowerKey(q)]);
      else if (dict.count(vowelKey(q)))
        ans.push_back(dict[vowelKey(q)]);
      else
        ans.push_back("");

    return ans;
  }

 private:
  string lowerKey(const string& word) {
    string s{"$"};
    for (char c : word)
      s += tolower(c);
    return s;
  }

  string vowelKey(const string& word) {
    string s;
    for (char c : word)
      s += string("aeiou").find(tolower(c)) != string::npos ? '*' : tolower(c);
    return s;
  }
};

```
967. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:54:48

```

class Solution {
 public:
  vector<int> numsSameConsecDiff(int n, int k) {
    if (n == 1)
      return {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    vector<int> ans;

    if (k == 0) {
      for (char c = '1'; c <= '9'; ++c)
        ans.push_back(stoi(string(n, c)));
      return ans;
    }

    for (int num = 1; num <= 9; ++num)
      dfs(n - 1, k, num, ans);

    return ans;
  }

 private:
  void dfs(int n, int k, int num, vector<int>& ans) {
    if (n == 0) {
      ans.push_back(num);
      return;
    }

    const int lastDigit = num % 10;

    for (const int nextDigit : {lastDigit - k, lastDigit + k})
      if (0 <= nextDigit && nextDigit <= 9)
        dfs(n - 1, k, num * 10 + nextDigit, ans);
  }
};
```
922. leetcode solution in CPP
Tags: cpp
Published: 2022-06-15 17:53:58




```
class Solution {
 public:
  vector<int> sortArrayByParityII(vector<int>& A) {
    const int n = A.size();

    for (int i = 0, j = 1; i < n; i += 2, j += 2) {
      while (i < n && A[i] % 2 == 0)
        i += 2;
      while (j < n && A[j] % 2 == 1)
        j += 2;
      if (i < n)
        swap(A[i], A[j]);
    }

    return A;
  }
};

```
954. leetcode solution in java
Tags: java
Published: 2022-06-15 17:52:45

```
class Solution {
  public boolean canReorderDoubled(int[] A) {
    Map<Integer, Integer> count = new HashMap<>();

    for (final int a : A)
      count.merge(a, 1, Integer::sum);

    A = Arrays.stream(A)
            .boxed()
            .sorted((a, b) -> Math.abs(a) - Math.abs(b))
            .mapToInt(i -> i)
            .toArray();

    for (final int a : A) {
      if (count.get(a) == 0)
        continue;
      if (count.getOrDefault(2 * a, 0) == 0)
        return false;
      count.merge(a, -1, Integer::sum);
      count.merge(2 * a, -1, Integer::sum);
    }

    return true;
  }
}
```
385. leetcode solution in CPP
Tags: cpp
Published: 2022-06-15 17:50:58

```
class Solution {
 public:
  NestedInteger deserialize(string s) {
    if (s[0] != '[')
      return NestedInteger(stoi(s));

    stack<NestedInteger> stack;
    int start;  // the start index of num

    for (int i = 0; i < s.length(); ++i) {
      switch (s[i]) {
        case '[':
          stack.push(NestedInteger());
          start = i + 1;
          break;
        case ',':
          if (i > start) {
            const int num = stoi(s.substr(start, i));
            stack.top().add(NestedInteger(num));
          }
          start = i + 1;
          break;
        case ']':
          NestedInteger popped = stack.top();
          stack.pop();
          if (i > start) {
            const int num = stoi(s.substr(start, i));
            popped.add(NestedInteger(num));
          }
          if (stack.empty())
            return popped;
          else
            stack.top().add(popped);
          start = i + 1;
          break;
      }
    }

    throw;
  }
};

```
Colors in PHP command line output
Tags: php, productivity, terminal, cmd
Published: 2022-06-15 17:50:32

It's always good to colorize the output of the command line. Give a custom style. In this case, you can use color codes on strings to color the output. One very important thing to note is that these colors will only work on the command line and not in your browser.

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

Let's see the syntax:

`echo "\e[1;37;42mHello World\e[0m\n";`

The above command returns "Hello World" in white font and green background. You can see that the first part of the string, **\e**, is the escape character to open and close the string.

**[0;31;42m**, this is what sets the color (0;31) and background (42). This should be followed by the text that we are coloring.

In Skater I use it to style when the `-help` command is required.

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

There are few colors, but enough to give style to outings. I share the list of colors. See you soon!

```
# Text Colors			Code
# ---------------------------
# Black					0;30
# White					1;37
# Dark Grey				1;30
# Red 					0;31
# Green					0;32
# Brown					0;33
# Yellow				1;33
# Blue					0;34
# Magenta				0;35
# Cyan					0;36
# Light Cyan			1;36
# Light Grey			0;37
# Light Red				1;31
# Light Green			1;32
# Light Blue			1;34
# Light Magenta			1;35

# Background Colors 	Code
# ---------------------------
# Black					40
# Red					41
# Green					42
# Yellow				43
# Blue					44
# Magenta				45
# Cyan					46
# Light Grey			47
```
851. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:47:41

```

class Solution {
 public:
  vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
    vector<int> ans(quiet.size(), -1);
    vector<vector<int>> graph(quiet.size());

    for (const auto& e : richer)
      graph[e[1]].push_back(e[0]);

    for (int i = 0; i < graph.size(); ++i)
      dfs(graph, i, quiet, ans);

    return ans;
  }

 private:
  int dfs(const vector<vector<int>>& graph, int u, const vector<int>& quiet,
          vector<int>& ans) {
    if (ans[u] != -1)
      return ans[u];

    ans[u] = u;

    for (const int v : graph[u]) {
      const int res = dfs(graph, v, quiet, ans);
      if (quiet[res] < quiet[ans[u]])
        ans[u] = res;
    }

    return ans[u];
  }
};
```
838. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:46:46



```
class Solution {
 public:
  string pushDominoes(string dominoes) {
    int L = -1;
    int R = -1;

    for (int i = 0; i <= dominoes.length(); ++i)
      if (i == dominoes.length() || dominoes[i] == 'R') {
        if (L < R)
          while (R < i)
            dominoes[R++] = 'R';
        R = i;
      } else if (dominoes[i] == 'L') {
        if (R < L || L == -1 && R == -1) {
          if (L == -1 && R == -1)
            ++L;
          while (L < i)
            dominoes[L++] = 'L';
        } else {
          int l = R + 1;
          int r = i - 1;
          while (l < r) {
            dominoes[l++] = 'R';
            dominoes[r--] = 'L';
          }
        }
        L = i;
      }

    return dominoes;
  }
};

```
835. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:46:11


```
class Solution {
 public:
  int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
    const int n = A.size();
    const int magic = 100;
    int ans = 0;
    vector<pair<int, int>> onesA;
    vector<pair<int, int>> onesB;
    unordered_map<int, int> map;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        if (A[i][j] == 1)
          onesA.emplace_back(i, j);
        if (B[i][j] == 1)
          onesB.emplace_back(i, j);
      }

    for (const pair<int, int>& a : onesA)
      for (const pair<int, int>& b : onesB)
        ++map[(a.first - b.first) * magic + (a.second - b.second)];

    for (const auto& [_, value] : map)
      ans = max(ans, value);

    return ans;
  }
};
```
881. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:44:35

```

class Solution {
 public:
  int numRescueBoats(vector<int>& people, int limit) {
    int ans = 0;

    sort(begin(people), end(people));

    for (int i = 0, j = people.size() - 1; i <= j; ++ans) {
      int remain = limit - people[j--];
      if (people[i] <= remain)
        ++i;
    }

    return ans;
  }
};
```
898. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:43:51

```
class Solution {
 public:
  int subarrayBitwiseORs(vector<int>& arr) {
    vector<int> s;
    int l = 0;

    for (const int a : arr) {
      const int r = s.size();
      s.push_back(a);
      // s[l..r) are values generated in previous iteration
      for (int i = l; i < r; ++i)
        if (s.back() != (s[i] | a))
          s.push_back(s[i] | a);
      l = r;
    }

    return unordered_set<int>(begin(s), end(s)).size();
  }
};
```
900. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:41:49

```

class RLEIterator {
 public:
  RLEIterator(vector<int>& A) : A(A) {}

  int next(int n) {
    while (index < A.size() && A[index] < n) {
      n -= A[index];
      index += 2;
    }

    if (index == A.size())
      return -1;

    A[index] -= n;
    return A[index + 1];
  }

 private:
  int index = 0;
  vector<int> A;
};
```
649. leetcode solution in CPP
Tags: cpp
Published: 2022-06-15 17:39:00




```
class Solution {
 public:
  string predictPartyVictory(string senate) {
    const int n = senate.length();
    queue<int> qR;
    queue<int> qD;

    for (int i = 0; i < n; ++i)
      if (senate[i] == 'R')
        qR.push(i);
      else
        qD.push(i);

    while (!qR.empty() && !qD.empty()) {
      const int indexR = qR.front();
      qR.pop();
      const int indexD = qD.front();
      qD.pop();
      if (indexR < indexD)
        qR.push(indexR + n);
      else
        qD.push(indexD + n);
    }

    return qR.empty() ? "Dire" : "Radiant";
  }
};
```
From a list to one number
Tags: javascript, tutorial, beginners
Published: 2022-06-15 17:38:34

The JavaScript Reduce Method

## Introduction

The JavaScript reduce method is one of the higher order functions introduced in es6 which allows us to "reduce" the values inside of an array into a single value. Today, we will be taking a look at how to implement this in our code.

## Getting Started

The `.reduce()` method is a higher order function that can be called on any array -- see below:

```js
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce();
```

Like all the other array methods `.reduce()` loops through your entire array. The difference here is that `.reduce()` is a function has two parameters, one being a function while the other is the initial value of what we call and accumulator -- this is the thing that will increment at every iteration of the loop.

```js
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce(() => {}, 0);
```

The function inside reduce, takes in two parameters itself, one being an accumulator while the other being the value of the current position in the array. See Below:

```js
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce((acc, curr) => {}, 0);
```

To update the accumulator at each iteration we must add a return it inside the function. We can assign this function to a variable which can then be used for anything.

## Using Reduce: Example

Lets say we have an array from 1 - 10 and we need to add all the elements in the array to determine the total, we can use the reduce method to accomplish this -- We can call the reduce method on our array, setup the accumulator and current parameters and also pass in an initial value of 0.

```js
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.reduce((acc, curr) => {
  return acc + cur;
}, 0);
```

## Using reduce: Another Example

Going over out class object that we created (link to other post), lets say we wamted to calculate the average for the class. We can either write a while loop or for loop to accomplish this or we can use the reduce method.

Here is an array of objects where each object represents a student in the class.

```js
const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];
```

Using the reduce method:

```js
const students = [
  {
    Name: "John",
    Grade: 90,
  },
  {
    Name: "Sarah",
    Grade: 95,
  },
  {
    Name: "Jane",
    Grade: 80,
  },
  {
    Name: "Julie",
    Grade: 79,
  },
];

const TotalMarks = students.reduce((acc, curr) => acc + cur, 0);
const averageMark = TotalMakrs / students.length;
console.log(averageMark);
```

Now that this is complete, we have a way to reduce an array into a single value without writing our own loop!

## Question for you

Now knowing this, here's a question for you -- how else can we implement the reduce method?

---

Check out the youtube channel to see how we are implementing the feature in the app we are building! [theYoutubeChannel](https://www.youtube.com/channel/UCX5U1Acli00LRTV3FijGL1g)
646. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:37:45

```
class Solution {
public:
    int findLongestChain(vector<vector<int>>& A) {
        sort(begin(A), end(A));
        int N = A.size();
        vector<int> dp(N, 1);
        for (int i = 1; i < N; ++i) {
            for (int j = 0; j < i; ++j) {
                if (A[j][1] >= A[i][0]) continue;
                dp[i] = max(dp[i], 1 + dp[j]);
            }
        }
        return *max_element(begin(dp), end(dp));
    }
};
```
645. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:36:54

```
class Solution {
 public:
  vector<int> findErrorNums(vector<int>& nums) {
    int duplicate;

    for (const int num : nums)
      if (nums[abs(num) - 1] < 0)
        duplicate = abs(num);
      else
        nums[abs(num) - 1] *= -1;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] > 0)
        return {duplicate, i + 1};

    throw;
  }
};
```
643. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:35:43

```
 class Solution {
 public:
  double findMaxAverage(vector<int>& nums, int k) {
    double sum = accumulate(begin(nums), begin(nums) + k, 0);
    double ans = sum;

    for (int i = k; i < nums.size(); ++i) {
      sum += nums[i] - nums[i - k];
      ans = max(ans, sum);
    }

    return ans / k;
  }
};

```
Architecture of an Amazon Redshift cluster
Tags: aws, database, dataengineering
Published: 2022-06-15 17:33:37

**The image above shows the basic architecture of an Amazon Redshift cluster, it is summarized below:**

1. The total number of nodes in the redshift cluster is equal to the number of  "EC2 instances" used in the cluster.

2. Each slice in a redshift cluster is at least 1 CPU with dedicated memory and storage.

3. The image above shows a cluster with 4 nodes, each one contains 4 slices, the maximum number of partitions per table is 16 partitions.

4. The leader node (Leader Node), is responsible for coordinating lower level nodes, manages external communications and optimizes queries.

5. The lower level nodes, slave nodes (Compute nodes), as mentioned above, each slave node has its own CPU, memory, and disk, depending on the type of EC2 instance selected, this architecture has the ability to "**scale out** (add more nodes to the cluster)" or "**scale up** (add more resources to a specific node)".
Sum of Nodes with Even-Valued Grandparent
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 17:30:40

Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`.

A **grandparent** of a node is the parent of its parent if it exists.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/08/10/even1-tree.jpg)

**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 18
**Explanation:** The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/08/10/even2-tree.jpg)

**Input:** root = \[1\]
**Output:** 0

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 104]`.
*   `1 <= Node.val <= 100`

**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 sumEvenGrandparent(self, root: TreeNode) -> int:
            paths = [(root, [root.val] if root else [])]
            i = 0
            total = 0
            while i < len(paths):
                curr, currpath = paths[i]
                if curr:
                    if len(currpath) > 2 and currpath[-3] % 2 == 0:
                        total += curr.val
                    if curr.left:
                        paths.append((curr.left, currpath + [curr.left.val]))
                    if curr.right:
                        paths.append((curr.right, currpath + [curr.right.val]))
                i += 1
            return total
606. leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:30:40

```


class Solution {
 public:
  string tree2str(TreeNode* t) {
    return dfs(t);
  }

 private:
  string dfs(TreeNode* root) {
    if (!root)
      return "";

    const string& rootStr = to_string(root->val);
    if (root->right)
      return rootStr + "(" + dfs(root->left) + ")(" + dfs(root->right) + ")";
    if (root->left)
      return rootStr + "(" + dfs(root->left) + ")";
    return rootStr + "";
  }
};

```
leetcode solution in cpp
Tags: cpp
Published: 2022-06-15 17:29:53

```
class Solution {
 public:
  bool canPlaceFlowers(vector<int>& flowerbed, int n) {
    if (n == 0)
      return true;

    for (int i = 0; i < flowerbed.size(); ++i)
      if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) &&
          (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {
        flowerbed[i] = 1;
        if (--n == 0)
          return true;
      }

    return false;
  }
};

```
SQL Has Evolved a Lot In Order To Meet New Challenges — But The Fundamentals Have Remained 🎙
Tags: podcast, sql, database, cloud
Published: 2022-06-15 17:14:41

This episode of DevDiscuss has us joined by Jim Walker of Cockroach Labs to talk about what modern SQL is in a new world of distributed cloud computing — while also getting into the fundamental value of SQL throughout the decades.

It's a great listen!

## Listen on Apple Podcasts

{% embed https://podcasts.apple.com/us/podcast/s9-e6-the-evolution-of-sql-and-how-it-managed/id1513053883?i=1000566488123 %}

## Listen on Spotify

{% embed https://open.spotify.com/episode/700PLnEa6KHhLAnsIMLspa?si=VZcqY7qdREug_HsYVqIpjA %}

## [Or listen right here on DEV](https://dev.to/devdiscuss/s9e6-the-evolution-of-sql-and-how-it-managed-to-last-through-time)

***

Happy querying!
Does a Data Access Layer make it easier to change your Database?
Tags: architecture, database, distributedsystems, backend
Published: 2022-06-15 17:09:09

One primary reason for a data access layer or abstraction is your ability to move underlying databases easier. Have you ever replaced the underlying database of a large system or service? For example, moved from one relational database like PostgreSQL to MySQL. Or perhaps went from a relational database to a document or event store?

There seem to be two groups of people. Those that have will say that abstracting the underlying database is crucial.  While the other group never has moved database and question abstracting or creating a data access layer because you likely won't replace the database.

For me, like many things in software architecture, it's about coupling. If you limit coupling this isn't much of a hot topic.

{% embed https://www.youtube.com/watch?v=_IXEfi1B-lA %}
Sample File CDN Links or Download
Tags: webdev, beginners, tutorial, opensource
Published: 2022-06-15 17:05:51

## Video / mp4

```
https://bit.ly/bbsamplevideo
```

---

## Poster / Image (Landscape)

```
https://bit.ly/bbsampleposter
```

---

## Audio / mp3

```
https://bit.ly/bbsampleaudio
```

---

## Subtitles / vtt

```
https://yoriiis.github.io/cdn/static/vlitejs/demo-video-html5-subtitle-en.vtt
```

---
Percentage of Letter in String
Tags: leetcode, dsa, theabbie
Published: 2022-06-15 17:00:47

Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._

**Example 1:**

**Input:** s = "foobar", letter = "o"
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2 / 6 \* 100% = 33% when rounded down, so we return 33.

**Example 2:**

**Input:** s = "jjjj", letter = "k"
**Output:** 0
**Explanation:**
The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.

**Constraints:**

*   `1 <= s.length <= 100`
*   `s` consists of lowercase English letters.
*   `letter` is a lowercase English letter.

**SOLUTION:**

    class Solution:
        def percentageLetter(self, s: str, letter: str) -> int:
            n = len(s)
            ctr = 0
            for c in s:
                if c == letter:
                    ctr += 1
            return floor(100 * ctr / n)
The Turin Horse - Hadi
Tags: codepen, webdev, svg, html
Published: 2022-06-15 16:57:54

<p>SVG implementation of Hadi's super cool Dribbble shot: <a href="https://dribbble.com/shots/18288950-The-Turin-Horse" target="_blank">https://dribbble.com/shots/18288950-The-Turin-Horse</a></p>

{% codepen https://codepen.io/leimapapa/pen/GRQGzOZ %}
Microsoft Virtual Desktop Infrastructure Development Environment Question
Tags: microsoft
Published: 2022-06-15 16:47:24

---
title: Microsoft Virtual Desktop Infrastructure Development Environment Question
published: true
description: Dev experience in VDI env
tags: microsoft
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

Does anyone have experience actually developing in Microsoft's Virtual Desktop Environment? If so, what was your experience like?

With difficulties procuring hardware, we have considered utilizing this infrastructure. Marketing, obviously, says it will work beautifully, but I would like to gain insight into real world experience.

Thanks!