teleren/devto huggingface dataset:
1970. Leetcode Solution in Java
Tags: java
Published: 2022-07-21 05:48:08

```
class Solution {
    static final int WATER = -1;
    static final int WHITE = 0;
    static final int BLACK = 1;
    int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };

    public int latestDayToCross(int row, int col, int[][] cells) {
        int low = col - 1, high = row * col - 1;
        while (low < high) {
            int mid = (high - low + 1) / 2 + low;
            boolean canCross = check(row, col, cells, mid);
            if (canCross)
                low = mid;
            else
                high = mid - 1;
        }
        return low;
    }

    public boolean check(int row, int col, int[][] cells, int mid) {
        int[][] grid = new int[row][col];
        for (int i = 0; i < mid; i++) {
            int[] cell = cells[i];
            grid[cell[0] - 1][cell[1] - 1] = WATER;
        }
        Queue<int[]> queue = new LinkedList<int[]>();
        for (int j = 0; j < col; j++) {
            if (grid[0][j] == WHITE) {
                grid[0][j] = BLACK;
                queue.offer(new int[]{0, j});
            }
        }
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int r = cell[0], c = cell[1];
            for (int[] direction : directions) {
                int newR = r + direction[0], newC = c + direction[1];
                if (newR >= 0 && newR < row && newC >= 0 && newC < col && grid[newR][newC] == WHITE) {
                    if (newR == row - 1)
                        return true;
                    grid[newR][newC] = BLACK;
                    queue.offer(new int[]{newR, newC});
                }
            }
        }
        return false;
    }
}
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/last-day-where-you-can-still-cross/
1998. Leetcode Solution in Java
Tags: java
Published: 2022-07-21 05:46:46

```
class Solution {
    public boolean gcdSort(int[] nums) {
        int maxNum = 100000;
        int[] parent = new int[maxNum + 1];
        boolean[] exists = new boolean[maxNum + 1];
        int length = nums.length;
        for (int i = 0; i < length; i++)
            exists[nums[i]] = true;
        for (int i = 1; i <= maxNum; i++)
            parent[i] = i;
        for (int i = 1; i <= maxNum; i++) {
            if (exists[i])
                divide(parent, i);
        }
        int[] sorted = new int[length];
        System.arraycopy(nums, 0, sorted, 0, length);
        Arrays.sort(sorted);
        for (int i = 0; i < length; i++) {
            if (find(parent, sorted[i]) != find(parent, nums[i]))
                return false;
        }
        return true;
    }

    public void union(int[] parent, int index1, int index2) {
        parent[find(parent, index1)] = find(parent, index2);
    }

    public int find(int[] parent, int index) {
        if (parent[index] != index)
            parent[index] = find(parent, parent[index]);
        return parent[index];
    }

    public int gcd(int num1, int num2) {
        while (num2 != 0) {
            int temp = num1;
            num1 = num2;
            num2 = temp % num2;
        }
        return num1;
    }

    public void divide(int[] parent, int x) {
        int y = x;
        for (int i = 2; i * i <= x; i++) {
            if (x % i == 0) {
                while (x % i == 0) {
                    x /= i;
                    union(parent, y, i);
                }
            }
        }
        if (x != 1)
            union(parent, y, x);
    }
}
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/gcd-sort-of-an-array
76. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 05:43:35

```
class Solution {
 public:
  string minWindow(string s, string t) {
    vector<int> count(128);
    int required = t.length();
    int bestLeft = -1;
    int minLength = s.length() + 1;

    for (const char c : t)
      ++count[c];

    for (int l = 0, r = 0; r < s.length(); ++r) {
      if (--count[s[r]] >= 0)
        --required;
      while (required == 0) {
        if (r - l + 1 < minLength) {
          bestLeft = l;
          minLength = r - l + 1;
        }
        if (++count[s[l++]] > 0)
          ++required;
      }
    }

    return bestLeft == -1 ? "" : s.substr(bestLeft, minLength);
  }
};

```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/minimum-window-substring/
16. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-21 05:42:06

```
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int ans = 0;
        int diff = INT_MAX;
        sort(nums.begin(), nums.end());
        
        for (int i = 0; i < nums.size(); i++) {
            if (i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            
            int j = i + 1;
            int k = nums.size() - 1;
            
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (abs(sum - target) < diff) {
                    ans = sum;
                    diff = abs(sum - target);
                }
                if (sum < target) {
                    j++;
                } else if (sum > target) {
                    k--;
                } else {
                    return target;
                }
            }
        }
        
        return ans;
    }
};
```


#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/3sum-closest/
3. Leetcode Solution in Java
Tags: java
Published: 2022-07-21 05:40:41

```
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        Map<Character, Integer> map = new HashMap<>();
        int ans = 0;
        int counter = 0;
        for (int left = 0, right = 0; right < s.length(); right++) {
            // count > 0 means repeating character
            char cRight = s.charAt(right);
            map.put(cRight, map.getOrDefault(cRight, 0) + 1);
            if (map.get(cRight) > 1) {
                counter++;
            }

            while (counter > 0) {
                char cLeft = s.charAt(left);
                map.put(cLeft, map.get(cLeft) - 1);
                // map.get(cLeft) == 1 means the cLeft is the duplicated character, 
                // and we have remove it, so after left++, it will be distinct.
                if (map.get(cLeft) == 1) {
                    counter--;
                }
                left++;
            }
            ans = Math.max(ans, right - left + 1);
        }

        return ans;
    }
}
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/longest-substring-without-repeating-characters
92. Leetcode Solution in Java
Tags: java
Published: 2022-07-21 05:33:40

```
class Solution {
  public ListNode reverseBetween(ListNode head, int left, int right) {
    if (left == 1)
      return reverseN(head, right);

    head.next = reverseBetween(head.next, left - 1, right - 1);

    return head;
  }

  private ListNode reverseN(ListNode head, int n) {
    if (n == 1)
      return head;

    ListNode newHead = reverseN(head.next, n - 1);
    ListNode headNext = head.next;
    head.next = headNext.next;
    headNext.next = head;

    return newHead;
  }
}

```


#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/reverse-linked-list-ii/
NextSeo not updated when inspect source code using dynamic Meta data and using external API
Published: 2022-07-21 05:30:26

Hello, I will share my problem and how I found solution with my Next JS project when i using dynamic Meta Data from external API using GraphQL(Apollo Client).

When i use "useQuery" from apollo client it does not working when using SEO or when i share URL in to Social media like Facebook, Linkedin.

Solution is using "getInitialProps" with async method and Hit API from getInitialProps.


```Typescript
const DetailBlogPage: NextPage = ({ data }: any) => {

    return (
        <SiteLayout>
            <NextSeo
                title={data.articles.title}
                description={data.article..summary}
                canonical={`https://www.nuliscv.com/blog/${data.article.slug}`}
                openGraph={{
                    type: 'website',
                    locale: 'id_ID',
                    url: `https://www.example.com/blog/${data.articles[0].slug}`,
                    site_name: 'Example.com',
                    images: [
                        { url: `https://abcdefg.directus.app/assets/${data.articles[0].image.id}` },
                    ]
                }}
            />
            <div>
                <DetailBlog data={data} />
            </div>
        </SiteLayout>
    )
}

DetailBlogPage.getInitialProps = async ({ query }) => {
    // do the data fetching here
    const { slug } = query;

    const errorLink = onError(({ graphqlErrors, networkError }: any) => {
        if (graphqlErrors) {
            graphqlErrors.map(({ message, location, path }: any) => {

            });
        }
    });

    const portfolioLink = from([
        errorLink,
        new HttpLink({ uri: "https://abcdefg.directus.app"}),
    ]);

    const client = new ApolloClient({
        cache: new InMemoryCache({
            addTypename: false
        }),
        link: portfolioLink,
    });


    const { data } = await client.query({
        query: GET_DETAIL_BLOG,
        variables: {
            slug
        }
    })

    return { data: data };
}
```
Use Eclipse to instantly create, rename, and delete getters and setters
Tags: java, javascript, tutorial, programming
Published: 2022-07-21 05:23:17

Despite the arguments and discussions surrounding Java's getters and setters, the reality is that you must deal with them.

## read also : **[getter and setter in java](https://professional-writer0.blogspot.com/2022/07/java-language-support-what-you-need-to.html)**

However, managing **getters and setters** takes time. It can take minutes to create a getter/setter for a class's five fields, renaming them can be problematic, and deleting them is just inconvenient.


You can avoid **getters and setters** entirely by redesigning your classes, or you can use options like Project Lombok (which creates getters and setters implicitly without requiring you to code them).

## read also : **[C# Getter Setter](https://professional-writer0.blogspot.com/2022/07/c-getter-setter-simple-tutorial-to-help.html)**

The good news is that Eclipse has some useful features for managing getters and setters because these options aren't always available. You can eliminate the boilerplate code by combining it with the capability to generate constructors based on fields in

## the creation of getters and setters

Follow these steps to create getters and setters:

After creating the desired fields for the class, press Alt+Shift+S, R. You can select the fields for which you want to generate getters and setters using a dialogue box that will appear.

To create getters and setters for every field, click Select All. Of course, you can select particular fields as needed.

Change the Last Member as the insertion point. This instructs Eclipse that the methods should be added last in the class. Since I want them out of the way, this is usually my best option.

Click Ok. The getters and setters will be made for you by Eclipse.

Here is an illustration of how the dialogue ought to appear.

It should be noted that by default, Eclipse prevents you from creating a setter for a final field—the setter simply isn't visible in the dialogue. This can be annoying, especially if you have autoformatting enabled to make fields final when possible. Enable the checkbox Allow setters for final fields on the dialogue to get around this restriction. The dialogue will now display the field's setter. Eclipse will generate the setter and remove the last keyword from the field after you click "Ok." Eclipse is also aware of this environment.

Place your cursor anywhere in the class (outside of any method), start typing "get" or "set," and then press Ctrl+Space to add a single getter or setter. Any will be among the choices on the autocomplete menu.


## Take away getters and setters

It's not as simple to remove getters and setters as it is to remove a field from the editor. However, the Outline view allows you to remove a field along with its getters and setters.

When you want to delete a field, select it in the Outline view (Alt+Shift+Q, O), then press Delete (or right-click, Delete). If you choose to delete the getters and setters as well, Eclipse will prompt you. Simply select Yes To All to get rid of them.
5 things to keep in mind as a programmer
Tags: programming, productivity, javascript, beginners
Published: 2022-07-21 05:20:00

Here is a list of 5 things to keep in mind when starting programming.

### 1. Languages are just tools

The most common mistake for a beginner - even for some experienced developers - is focusing too much on languages/frameworks rather than solving problems. It's a good thing to be a "Jack of all trades" but keep in mind that it will get you nowhere if you know all languages/frameworks in the world.

Pick a random one, learn to solve problems with it. Believe me, at the beginning it doesn't matter which programming language you are using. They all make sense.

I am not saying it's bad to learn a new language but make sure to focus on how you can use the language to solve some real-life problems.

Remember, programming is not about what language you use. It's about how you think.

### 2. Understand the underlying concepts
Don't just focus on solving a problem and then jumping directly to the next one. Programming is not just a typing statement. you have to understand the programming core skills - the fundamentals. Programming can be a highly competitive industry, so it's advisable to highlight your skills.

### 3. Complex Is Better Than Complicated
Don't be afraid of having a complex solution to a problem. It's true that Simple Is Better Than Complex but usually, complex problems require complex solutions. Just don't make it complicated - make it understandable.

### 4. Never Panic
Some people panic when they cannot solve a problem the first time. Don't be like that, even if the deadline is close. Most of the time the solution is around. Otherwise, you can find an alternative that might work. Make sure you understand what you are doing. Most importantly, never ever copy/paste code from StackOverflow without a complete understanding of it.

### 5- Build a routine of continuous learning
Things evolve rapidly in programming. So you better focus on continuous learning.
Reading can be a great way to improve yourself and get up to date. It's regular investment in your knowledge portfolio. But you should critically analyze what you read. Do not believe everything.


[For More Relevant topic](https://cmsinstallation.blogspot.com?query=dev5things)
What distinguishes JavaScript's getters from setters?
Tags: java, tutorial, programming, devops
Published: 2022-07-21 05:14:31

We can define object accessors by using getters and setters. In contrast to the latter, which is used to set a property in an object, the former is used to retrieve a property from an object. Let's talk about them using examples.

## Getters\sExample

## read also : [getter and setter in java](https://professional-writer0.blogspot.com/2022/07/java-language-support-what-you-need-to.html)

In the example that follows, an object called "business" is created, and "Getter" is used to display a property called "company" in the output.

```
<html>
<body>
<script>
   var business= {
      Name: "pro",
      Country : "nour",
      Company : "google",
      get comp() {
         return this.company;
      }
   };
   document.write(business.company);
</script>
</body>
</html>
```
## output

```
google
```
## Setters

## Example

In the example that follows, a new object called "business" is created, and the value of the property "company" is changed from PayPal to SolarCity as displayed in the output.

```
<html>
<body>
<script>
   var business = {
      Name: "pro",
      Country : "nour",
      company : "google",
      set comp(val) {
         this.company = val;
      }
   };
   business.comp = "SolarCity";
   document.write(business.company);
</script>
</body>
</html>
```
## output

```
SolarCity
```
How to run any project with one command?
Tags: shell, developers, zsh, tip
Published: 2022-07-21 05:06:32

Often times I like to try out new things in web development and nodejs world. But there is one problem with it.

I have tried out to create a new projects using [create-react-app](https://create-react-app.dev/), [create-next-app](https://nextjs.org/docs/api-reference/create-next-app) or any backend app using [express](https://expressjs.com/) or [hapi](https://hapi.dev/), or any monorepo using [lerna](https://lerna.js.org/), [turbo](https://turborepo.org/) or [nx](https://nx.dev/). 

But the command to start development environment or build the project changes from one to another. 

viz.
`create-react-app` starts development environment with `npm start`
`create-next-app` starts development environment with `npm run dev`
and so on.

and  there is no one command to rule them all.
But don't worry there is one solution to it.

You need to have [zsh](https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH), [oh-my-zsh](https://github.com/ohmyzsh/ohmyzsh#basic-installation) installed on your system to take advantage of the solution

Here is how you can do it

**Step 1:** Enable `dotenv` plugin in `zsh`. Edit your `~/.zshrc` 

```bash
plugins=(dotenv)
```

*Now this plugin will always automatically source your `.env` file everytime you cd into your project directory that contains a `.env` file*

**Step 2:** Create and add following content a `.env` to `create-react-app` project

```bash
alias ns="npm start"
alias nb="npm run build"
```

**Step 3:** Create and add following content a `.env` to `create-next-app` project

```bash
alias ns="npm run dev"
alias nb="npm run build"
```

**Step 4**: For java spring boot project you can add following
```bash
alias ns="mvn org.springframework.boot:spring-boot-maven-plugin:run"
```

Now when you `cd` into `create-react-app` project then all you need to run `ns` to start project
also when you `cd` into `create-next-app` project then as well you need to run `ns` to start the project

Thats it its just one time configuration you have to do in your project and you are done. No more remembering project specific commands. Cheers. Enjoy.
Connecting to Windows Virtual Machine created on Azure using RDP
Published: 2022-07-21 04:40:42

Let's see how we can start/connect to our Virtual Machine.

On the Virtual Machine page on [Azure Portal](https://portal.azure.com/), you can see this bar.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0cx4uprv63ht9oo6qse.png)

Here you have the option of **Connect**. So, you need to tap on the arrow with **Connect** and choose the **RDP** option from the dropdown menu.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jwtdevn9j5yj4pvcb9em.png)

**_Connect with RDP_** interface will open up, and now we need to download the RDP file using the **Download RDP File** button.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zotogxgw5wgafu0q3p3k.png)

Now in your downloads folder, you can see a .rdp file with the name of your VM.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sgu7gh09cghf0tii3cq3.png)
Just open that file.

**Remote Desktop Connection** interface will open up, and you need to tap on the **Connect** button to connect to your VM.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snatkouau2hda742rw72.png)

**Windows Security** interface will open up. But you need to tap on **_More choices_** option given below. And there you need to choose **_Use a different account option_**.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zeejz805nl16iynb7de.png)

Now on the new interface, you need to add the username and password which you set while creating the VM. And then tap on **OK** button below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igerlouh5cwk9oed6nmu.png)

If this kind of interface comes up, just tap **Yes** below.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdeoh1utq310aee1cnoy.png)

Now you can see the Virtual Machine is opening up.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/214fo8lwcxjraunz8anf.png)
You can enlarge the VM and make it full screen and use it like your own system.

Yayy!
You have successfully connected to your Virtual Machine.

Enjoy your new system 🎉
Generating Component in Angular (Using CLI/Manually)
Tags: angular, component, typescript
Published: 2022-07-21 04:30:27

## **Creating a component using the Angular CLI**

```jsx
ng generate component <component-name>
```

By default, this command creates the following:

- A folder named after the component
- A component file, `<component-name>.component.ts`
- A template file, `<component-name>.component.html`
- A CSS file, `<component-name>.component.css`
- A testing specification file, `<component-name>.component.spec.ts`

Where `<component-name>` is the name of your component.

## **Creating a component manually**

To create a new component manually:

1. Navigate to your Angular project directory.
2. Create a new file, `<component-name>.component.ts`.
3. At the top of the file, add the following import statement.
    
    ```
    content_copyimport {Component } from '@angular/core';
    ```
    
4. After the `import` statement, add a `@[Component](https://angular.io/api/core/Component)` decorator.
    
    ```
    content_copy@Component({
    })
    ```
    
5. Choose a CSS selector for the component.
    
    ```
    content_copy@Component({
      selector: 'app-component-overview',
    })
    ```
    
    For more information on choosing a selector, see [Specifying a component's selector](https://angular.io/guide/component-overview#specifying-a-components-css-selector).
    
6. Define the HTML template that the component uses to display information. In most cases, this template is a separate HTML file.
    
    ```
    content_copy@Component({
      selector: 'app-component-overview',
      templateUrl: './component-overview.component.html',
    })
    ```
    
    For more information on defining a component's template, see [Defining a component's template](https://angular.io/guide/component-overview#defining-a-components-template).
    
7. Select the styles for the component's template. In most cases, you define the styles for your component's template in a separate file.
    
    ```
    content_copy@Component({
      selector: 'app-component-overview',
      templateUrl: './component-overview.component.html',
      styleUrls: ['./component-overview.component.css']
    })
    ```
    
8. Add a `class` statement that includes the code for the component.
    
    ```
    content_copyexport class ComponentOverviewComponent {
    
    }
    ```
    
Reference : [ Angular Component Overview ](https://angular.io/guide/component-overview)