teleren/devto huggingface dataset:
1031. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-14 15:01:40

```
class Solution {
 public:
  int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {
    return max(helper(nums, firstLen, secondLen),
               helper(nums, secondLen, firstLen));
  }

 private:
  int helper(vector<int>& A, int l, int r) {
    const int n = A.size();
    vector<int> left(n);
    int sum = 0;

    for (int i = 0; i < n; ++i) {
      sum += A[i];
      if (i >= l)
        sum -= A[i - l];
      if (i >= l - 1)
        left[i] = i > 0 ? max(left[i - 1], sum) : sum;
    }

    vector<int> right(n);
    sum = 0;

    for (int i = n - 1; i >= 0; --i) {
      sum += A[i];
      if (i <= n - r - 1)
        sum -= A[i + r];
      if (i <= n - r)
        right[i] = i < n - 1 ? max(right[i + 1], sum) : sum;
    }

    int ans = 0;

    for (int i = 0; i < n - 1; ++i)
      ans = max(ans, left[i] + right[i + 1]);

    return ans;
  }
};
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/
Codewars Challenge Day 3: Moving Zeros To The End
Tags: javascript, python, php, challenge
Published: 2022-07-14 15:00:38

# Details
**Name Kata:** [Moving Zeros To The End](https://www.codewars.com/kata/52597aa56021e91c93000cb0/)
**5kuy**
**Description:**
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
**Example**
```
moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]
```

# My Solutions

## JavaScript

```javascript
const moveZeros = (arr) => {
  if (arr[0]===0){arr.push(arr.splice(i, 1).pop())}
  for(var i=arr.length;i>0;i--){if(arr[i]===0){arr.push(arr.splice(i,1).pop())}}
  return arr
}
```
## Python

```py
from typing import List

def move_zeros(lst: List) -> List:
    return [x for x in lst if x != 0] + [x for x in lst if x == 0]
```

## PHP

```php
function moveZeros(array $items): array
{
    return array_pad(
      array_filter(
        $items, function($x) {return $x !== 0 and $x !== 0.0;}
      ), count($items), 
     0);
}
```
1051. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-14 15:00:22

```
class Solution {
 public:
  int heightChecker(vector<int>& heights) {
    int ans = 0;
    int currentHeight = 1;
    vector<int> count(101);

    for (int height : heights)
      ++count[height];

    for (int height : heights) {
      while (count[currentHeight] == 0)
        ++currentHeight;
      if (height != currentHeight)
        ++ans;
      --count[currentHeight];
    }

    return ans;
  }
};
```


#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/height-checker/
1305. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-14 14:55:32

```
class BSTIterator {
 public:
  BSTIterator(TreeNode* root) {
    pushLeftsUntilNull(root);
  }

  int peek() {
    return stack.top()->val;
  }

  void next() {
    TreeNode* node = stack.top(); stack.pop();
    pushLeftsUntilNull(node->right);
  }

  bool hasNext() {
    return !stack.empty();
  }

 private:
  stack<TreeNode*> stack;

  void pushLeftsUntilNull(TreeNode* node) {
    while (node) {
      stack.push(node);
      node = node->left;
    }
  }
};

class Solution {
 public:
  vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
    vector<int> ans;
    BSTIterator bstIterator1(root1);
    BSTIterator bstIterator2(root2);

    while (bstIterator1.hasNext() && bstIterator2.hasNext())
      if (bstIterator1.peek() < bstIterator2.peek()) {
        ans.push_back(bstIterator1.peek());
        bstIterator1.next();
      } else {
        ans.push_back(bstIterator2.peek());
        bstIterator2.next();
      }

    while (bstIterator1.hasNext()) {
      ans.push_back(bstIterator1.peek());
      bstIterator1.next();
    }

    while (bstIterator2.hasNext()) {
      ans.push_back(bstIterator2.peek());
      bstIterator2.next();
    }

    return ans;
  }
};

```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
1472. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-14 14:53:24

```
class BrowserHistory {
 public:
  BrowserHistory(string homepage) {
    visit(homepage);
  }

  void visit(string url) {
    if (++index < urls.size())
      urls[index] = url;
    else
      urls.push_back(url);
    lastIndex = index;
  }

  string back(int steps) {
    index = max(0, index - steps);
    return urls[index];
  }

  string forward(int steps) {
    index = min(lastIndex, index + steps);
    return urls[index];
  }

 private:
  vector<string> urls;
  int index = -1;
  int lastIndex = -1;
};

```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/design-browser-history/
1023. Leetcode Solution in Java
Tags: java
Published: 2022-07-14 14:51:15

```
class Solution {
    public List<Boolean> camelMatch(String[] queries, String pattern) {
      List<Boolean> res = new ArrayList<>();
      for (String query : queries) {
        res.add(match(query, pattern));
      }
      return res;
    }
  
    boolean match(String query, String pattern) {
      int queryPoint = 0;
      int patternPoint = 0;
      while (queryPoint < query.length() 
             && patternPoint < pattern.length()) {
        while (queryPoint < query.length() 
               && query.charAt(queryPoint) !=
               pattern.charAt(patternPoint)) {
          if (isCapital(query.charAt(queryPoint)))
            return false;
          queryPoint++;
        }
        if (queryPoint == query.length()) {
          return false;
        }
        queryPoint++;
        patternPoint++;
      }
      if (patternPoint == pattern.length()) {
        while (queryPoint < query.length()) {
          if (isCapital(query.charAt(queryPoint)))
            return false;
          queryPoint++;
        }
        return true;
      }
      return false;
    }
  
    boolean isCapital(char c) {
      return c >='A' && c <= 'Z';
    }
}
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/camelcase-matching/submissions/
Promises in javascript(🔖)
Tags: beginners, javascript, webdev, tutorial
Published: 2022-07-14 07:24:43

**Promise is an object that bundles a provider and consumer.** To understand this, remember how this keyword was encountered in async javascript blog?

Promises are used to keep track of whether a **successful output was received** from a piece of code or not. 

Promises has two callbacks, either one of which is executed **depending on the output received**-  resolve(value) & reject(error). 

Resolve is for *successful run* while reject is for errors received. 

```javascript
const MyPromise=new Promise((resolve, reject)=>{
    const rand=Math.floor(Math.random()*2);
    console.log(rand)
    if(rand===0)
        resolve();
    else
        reject()
        
})

MyPromise
.then(()=>{console.log("success")})
.catch(()=>{console.log("Error")})

```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tx5037pcqxondo038t17.png)
  
Here we are working with a [random number](https://www.w3schools.com/jsref/jsref_random.asp) case, where it either returns 1 or 2. `.then` handles succesful responses and `.catch` works with errors. These are used to access internal Promise properties called **`state` and `result`**.

- **state** indicates status of the job that needs to be done. Pending, fulfilled or rejected are the three indicators.

- **result** is initially empty but gets a value when either resolved or an error when rejected.

> Only the first call to resolve/reject is taken and once the value for state and result is set it's final. [More on promises by javascript.info](https://javascript.info/promise-basics)


⭐New to Javascript? Try out great courses from https://boot.dev/tracks/computer-science
Small Features Matter
Tags: webdev, productivity, beginners
Published: 2022-07-14 14:49:48

## Small features that are useful are worth adding
My day job uses a custom web application in-house that is used by all staff for their daily jobs, we use it more than Outlook. 

I recently added a feature to our in-house application that was overwhelmingly accepted by staff, yet I thought it was such a small feature addition that no one would bother, and initially was only for myself. 

## Back Story
With the global pandemic and some people working in the office, others at home, some are on vacation, it was hard to know who was actually working before reaching out or sending them something to work on. Sure, our HR people knew, but from the IT/Dev side, I had no clue who was in or out and could wait hours only to realize they are off that day. Occasionally I delegate tasks to staff members and more often than not, I was sending requests to staff members that needed a quick response even when they were out of the office. 

## Idea
I had an idea to solve this for myself. Our custom web application features authentication where users login and logout. I wrote a small feature that only I could see, with a list of users who were currently logged into the system. This helped me know who was actually working that day. 

![Shows 'Logged In Users' with a green square and the name Chris](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5aji4nn3pcyoy2shgle.png) 

## Sharing
After using this personally for a few weeks, I offered the feature to the rest of the management staff that were complaining of similar issues. When we all work at home, it's really hard to know if someone is off that day or not aside from our HR department. The other managers were quickly excited and made use of the feature right away. Within 24-hours they requested that I make this feature available to all. 

Initially this feature only showed users who had logged in each day but didn't check whether they had logged out. After sharing, some of the feedback requests were to indicate if a user logged out, such as for an appointment, then their name was removed from the list. This feature may never have been added if I didn't share this feature with others.  

I immediately began hearing praise from staff members who were excited about a relatively simple feature that allows them to know someone is working that day before calling or emailing to avoid wasted time for our clients. 

## Conclusion
Small features are worth developing, but more importantly, they are worth sharing. If you create a feature that benefits you, think about whether or not someone else can benefit from the same feature. The feedback you receive from others can actually improve your design in ways you didn't initially realize.
1052. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-14 14:49:36

```
class Solution {
 public:
  int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
    int satisfied = 0;
    int madeSatisfied = 0;
    int windowSatisfied = 0;

    for (int i = 0; i < customers.size(); ++i) {
      if (grumpy[i] == 0)
        satisfied += customers[i];
      else
        windowSatisfied += customers[i];
      if (i >= X && grumpy[i - X] == 1)
        windowSatisfied -= customers[i - X];
      madeSatisfied = max(madeSatisfied, windowSatisfied);
    }

    return satisfied + madeSatisfied;
  }
};

```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/grumpy-bookstore-owner/
11 Free Unlimited SSD cPanel Hosting
Tags: testing
Published: 2022-07-14 14:37:01

Free hosting package is perfectly suitable for lightweight websites like WordPress blog, Internet forum, or website built with our Site Builder. You can also try [11 Free cPanel Hosting](https://soogam.com/100-free-web-hosting-2020/).

## Why choose Free Hosting?

**There are a few reasons why someone might choose free hosting**:

1.**Cost**: Free hosting is, as the name suggests, free of charge. This can be appealing for individuals or small businesses with limited budgets who don't want to invest in a paid hosting service.

2.**Ease of use**: Free hosting services often have user-friendly interfaces that are easy to navigate, making it simple for beginners to get started with creating a website.

3.**Minimal website needs**: If you only need a basic website with a few pages, free hosting may be sufficient for your needs. However, if you have more complex requirements, such as ecommerce functionality or high traffic volumes, you may need to upgrade to a paid hosting service.

4.**Experimentation**: Free hosting can be a good option if you're just experimenting with creating a website and want to test the waters before committing to a paid hosting service.

It's important to note, however, that free hosting services often come with limitations, such as limited storage and bandwidth, as well as potential security risks. Additionally, they may include ads on your website, which can detract from the user experience. It's important to carefully evaluate your needs and the limitations of free hosting before making a decision.

## Best Free Hosting Providers:
It's important to note that while these providers offer free hosting, they may also have limitations and restrictions, such as limited customer support or lack of certain features. **There are several free hosting providers available, including**:

1. **PrepareHost.com**: PrepareHost has earned the top spot on our list of free web hosting providers due to its exceptional premium services offered completely free of cost. With 25GB of SSD storage, 250GB bandwidth, and a variety of other valuable free resources, PrepareHost stands out as an excellent choice for web hosting.

2. **FreeHosting.com**: This provider offers 10 GB of storage and unlimited bandwidth, as well as a website builder and one-click installer for popular apps like Joomla and WordPress.

3. **InfinityFree**: This provider offers unlimited storage and bandwidth, as well as a website builder and softaculous app installer.

4. **000webhost**: This provider offers 300 MB of storage and 3 GB of bandwidth, as well as a website builder and one-click installer for popular apps like WordPress.

5. **Awardspace**: This provider offers 1 GB of storage and 5 GB of bandwidth, as well as a website builder and free domain name.

6. **Byet Host**: This provider offers unlimited storage and bandwidth, as well as a website builder and one-click installer for popular apps like WordPress.
How to Host your React App for Free. (Part 1)
Tags: javascript, react, webdev, programming
Published: 2022-07-14 14:26:29

In this Blog, we will see how to host a react JS app for free. There are so many ways to host your app online for free but in this blog we will see how to host on github pages.

Hosting a normal html, css and js files to github is very easy, but when it comes to react js it is a bit tricky.

Let's get started.

## Step 1:
First step we need to do is to add `Homepage` to `package.json`
```json
"homepage": "https://myusername.github.io/my-app",
```
it you want to host to github user page
```json
"homepage": "https://myusername.github.io/",
```

## Step 2:
The next step you need to do is to install `gh-pages`. to install run the following command in the terminal

```javascript
npm install --save gh-pages
```
then add the following lines of code in your `package.json` scripts
```javascript
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
```
## Step 3:
The very next step is to run the following command
```javascript
npm run deploy
```

Now you are done 💥💥

you have successfully hosted your react app on github 🚀

Thank You for reading 🌹🌹

Also Read :
[MongoDB beginner tutorial](https://dev.to/vamsitupakula_/mongodb-beginner-tutorial-12bg)
[Express JS getting started](https://dev.to/vamsitupakula_/getting-started-with-express-js-2705)
useState ()
Published: 2022-07-14 14:14:00

Hi👋, if you landed up on this page there is good chance that you already know the JavaScript .I believe if you reading this blog that mean you have basic understanding of variables . if your answer is yes then congratulations ! you will understand useState very easily .  
   lets think about it , what is the purpose of variable?? yep yep yep you are absolutely right ! , the puspose of  variable is store some value and we can change the value of variable .finally react talks ...
**important note** useState hook is only for functional component

useState accepts an initial state and returns two values

1. The current state.
2. A function that updates the state.

To use the useState Hook, we first need to import it into our component.
> import {useState} from "react"

sample counter using useSate hook:
`import {useState} from "react"
import "./styles.css";
export default function App() {
// count is state name and setCount is a setter function 
const [count,setCount]=useState(0)
 const addHandler =()=>{
  setCount(count+1)
}
const substractHandler=()=>{
  setCount(count-1)
} 
  return (
   <div>
      <div className="heading-name">
      Counter App
      </div>
      <div className="count">
        {count}
       </div>
      <div className="button-container">
       <button class="counter-button" onClick={addHandler}> + 
      </button>
       <button class="counter-button" onClick={substractHandler}> 
     - </button>
      </div>
    </div>)}
`
we can able to change the state value by using setter function easily . The count is the current value and setCount is setter function for manipulating count value . 
summery : 
1. react hooks are special functions 
 2. useState is also a special kind of function which accepts 
 state as an argument it can be anything string, array , object , 
 number 
 3. it will return current value and setter  function.
 Hope you love the blog! you can check the sandbox link and play around it.. take carea!!!
https://codesandbox.io/s/react-uesstate-hook-counter-mvki7w?file=/src/App.js:0-595
Current Issue with AWS,EKS Cluster –Fargate-VPC
Tags: aws, ekscluster, faragatevpc, beginners
Published: 2022-07-14 14:12:14

Following the AWS documentation on Amazon EKS was very helpful and very detailed, covering topics such as AWS networks and security and prerequisites. 
PROBLEM 
However, I had a problem with the implementation of coredns, which failed when searching for nodes. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s03p6t0jafzoondqrmb9.png)
SOLUTION 
I used an existing VPC with public and private subnets, internet gateway, and national gateway. The solution was in your VPC, make sure you set enableDNSHostnames and enableDNSSupport to True.
How to Mock the Date in Redux Toolkit
Tags: jest, javascript, testing
Published: 2022-07-14 14:11:09

---
title: How to Mock the Date in Redux Toolkit
published: true
date: 2022-07-013 18:16:35 UTC
tags: Jest,JS,Testing
canonical_url: https://robertmarshall.dev/blog/how-to-mock-the-date-in-redux-toolkit/
---

--------

This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/how-to-mock-the-date-in-redux-toolkit/

--------

Redux Toolkit (RTK) was an absolute blessing when I finally got around to using it, rather than the old way of a million action creators and constant files. So much boilerplate work! However, it did come with some small issues that took some working out.

One of this issues was unit testing. For the most part Redux Toolkit makes testing very simple, but there is always that little edge case that creeps up when on a deadline. My particular issue was being unable to correctly test and mock dates within Redux Toolkit.

I had previously written an article on [how to mock dates in Jest](https://robertmarshall.dev/blog/mock-the-date-in-jest-consistently/), and was pretty confident that Redux could be handled in the same way. This was not the case.

## The Problem

My jest unit test was trying to make sure that a date ISO string was correctly set in the reducer. The slice creation looked like this:

```javascript
const makeNewSlice = createSlice({
  name: "myNewSlice",
  initialState: {
    currentDate: new Date(Date.now()).toISOString()
  }
});
```

However, as discussed in this [github issue](https://github.com/reduxjs/redux-toolkit/issues/456), the use of ‘new’ is a class instance and isn’t able to be serialized. Even mocking the date out seems to be ignored by RTK and throws the current computer date string. The test would always fail with the mocked date being incorrect.

## The Solution

Create a helper function which returns the date string, and then mock that function file. Like so:

```javascript
// util/dateHelper.js
export const getCurrentDateString = () => new Date(Date.now()).toISOString();

// state/features/mySlice.js
import { getCurrentDateString } from './util/dateHelpers';

const makeNewSlice = createSlice({
  name: "myNewSlice",
  initialState: {
    currentDate: getCurrentDateString()
  }
});
```

 

The `getCurrentDateString` file can then be mocked out, and we can avoid having to handle any date/class mocking awkwardness.
What is Amazon EKS Connector ?.
Tags: aws, eks, eksconnector, beginners
Published: 2022-07-14 14:08:30

You can use Amazon EKS Connector to register and be a part of any conformant Kubernetes cluster to AWS and visualize it in the Amazon EKS console. You can see the status, configuration, and workload in the Amazon EKS console after a cluster is connected. You can use this feature to view connected clusters, but you can't control them
The Amazon EKS Connector can connect the following kinds of Kubernetes clusters to Amazon EKS. The Amazon EKS Connector is also an open supply project on Github.
•	The clusters are on-premises.
•	There are clusters on Amazon Elastic Compute Cloud.
•	Other cloud providers have managed clusters.
Amazon EKS Connector considerations
Understand the following before using Amazon EKS Connector:
•	You should have administrative privileges to the Kubernetes cluster to join the cluster to Amazon EKS.
•	Before connecting, the cluster must have Linux worker nodes present. ARM worker nodes aren't supported.
•	Outbound access to the ssm. and ssmmessages is required for you to have worker nodes in your cluster.
•	Up to 10 clusters can be connected by default. The service quota console can be used to request an increase.
•	Only the Amazon EKS RegisterCluster, ListClusters, DescribeCluster, and DeregisterCluster are supported by external Kubernetes clusters.
•	Permissions are needed to register a cluster.
1.	eks:RegisterCluster
2.	ssm:CreateActivation
3.	ssm:DeleteActivation
4.	iam:PassRole
•	Permissions are needed to deregister a cluster.
1.	eks:DeregisterCluster
2.	ssm:DeleteActivation
3.	ssm:DeregisterManagedInstance
Required IAM roles for Amazon EKS Connector
The following two roles are required for using the Amazon EKS Connector.
•	The service-linked role of amazon EKS connector is created when you register the cluster.
•	The agent IAM role of Amazon EKS Connector have to be created manually.
To enable cluster and workload view permission for another user, you must apply the eks-connector and Amazon EKS Connector cluster roles to your cluster.
USING CSS AND HTML IN DESIGNING WEBSITE
Published: 2022-07-14 13:25:25

WHAT IS HTML:HTML DEFINES THE CONTENT OF A WEBSITE
HTML STANDS FOR HYPER TEXT MARKUP LANGUAGE
WITH HTML YOU CAN CREATE YOUR OWN WEBSITE
HTML IS EASY TO LEARN
HTML EXAMPLES
   IN THIS HTML TUTORIAL,YOU WILL FIND MORE THAN 200 EXAMPLES.
WITH OUR ONLINE"TRY IT YOURSELF"EDITOR'YOU CAN EDIT AND TEST
EACH EXAMPLE YOURSELF!
HTML REFERENCES
AT W3SCHOOLS YOU WILL FIND COMPLETE REFERENCES ABOUT HTML
ELEMENTS,ATTRIBUTES,EVENTS,COLOUR NAMES,ENTITIES,CHARACTER-SETS,
URL ENCODING,LANGUAGE CODES,HTTP MESSAGES,BROWSER SUPPORT AND MORE

                         CSS

WHAT IS CSS:CSS IS THE LANGUAGE WE USE TO STYLE HTML.
CSS DESCRIBES HOW HTML ELEMENTSSHOULD BE DISPLAYED.
CSS STANDS FOR CASCADING STYLE SHEETS.
CSS SAVES ALOT OF WORK.IT CAN CONTROL THE LAYOUT OF
MUTIPLE WEBPAGES ALL AT ONCE.
EXTERNAL STYLE SHEETS ARE STORED IN CSS FILES.