teleren/devto huggingface dataset:
React Custom Hook: useHover
Tags: webdev, javascript, programming, react
Published: 2023-08-19 21:00:00

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useHover" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks
```javascript
import { useState } from "react"
import useEventListener from "../useEventListener/useEventListener"

export default function useHover(ref) {
    const [hovered, setHovered] = useState(false)
    useEventListener("mouseover", () => setHovered(true), ref.current)
    useEventListener("mouseout", () => setHovered(false), ref.current)
    return hovered
}
```
This lightweight hook leverages the useState and useEventListener hooks from React to keep track of the hover state. By simply passing a ref to the useHover hook, you can start receiving accurate hover events. The hook listens for "mouseover" and "mouseout" events, updating the hovered state accordingly.

One of the key advantages of **useHover** is its simplicity and reusability. By encapsulating the hover logic within the hook, you can easily use it across multiple components without duplicating code. This promotes clean and maintainable code, saving you time and effort in the long run.

UseHover can be used in a variety of scenarios. Whether you need to highlight an element on hover, trigger additional actions, or dynamically change styles, this custom hook has got you covered. It provides a seamless way to enhance the interactivity and user experience of your React components.
```javascript
import { useRef } from "react"
import useHover from "./useHover"

export default function HoverComponent() {
    const elementRef = useRef()
    const hovered = useHover(elementRef)
    return (
        <div
            ref={elementRef}
            style={{
                backgroundColor: hovered ? "blue" : "red",
                width: "100px",
                height: "100px",
                position: "absolute",
                top: "calc(50% - 50px)",
                left: "calc(50% - 50px)",
            }}
        />
    )
}
```
To demonstrate its power, consider the HoverComponent example above. By applying the _useHover_ hook to the elementRef, the background color of the div dynamically changes between blue and red depending on the hover state. This simple yet effective implementation showcases the potential of useHover in creating interactive and engaging UI components.

Full Version | React Custom Hooks: 
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4
裝 WP-CLI
Tags: wordpress
Published: 2023-08-19 21:53:46

在裝 WordPress 之前，先裝 [WP-CLI](https://wp-cli.org/)。

參照 WP-CLI 〈[Installing](https://make.wordpress.org/cli/handbook/guides/installing/#recommended-installation)〉文件。

抓下來：

```sh
$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
```

確認一下運作正常：

```sh
$ php wp-cli.phar --info
```

加上可執行屬性：

```sh
$ chmod +x wp-cli.phar
```

移放到 /usr/local/bin/wp：

```sh
$ sudo mv wp-cli.phar /usr/local/bin/wp
```

再次確認運作正常：

```sh
$ wp --info
```

很簡單。

我是用 CentOS，不過以上步驟應該都是通用的。
Releasing Myanmar Calendar App
Tags: webdev, nextjs, react, opensource
Published: 2023-08-19 21:12:17

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

## 🌌 New Features
- Dual Support: Gregorian & Myanmar Calendars 
- Multi-Languages: Karen, Mon, Tai, Burmese, English and Shan 
- Complete Myanmar Date Details 
- User-Friendly Interface
- Cross-Platform Convenience: macOS, Windows, Linux 
**Upgrade your calendar experience now!** 

## 🚀 Download
Support for all Operating Systems 
https://github.com/.../15266628572/artifacts/872083865

## 🔗 Do we have a website?
Here you go.
https://myanmar-calendar.vercel.app/

## 👀 Contribution
**Calling All Developers!** Join us in shaping the Myanmar Calendar App!
https://github.com/myanmarcyberyouths/myanmar-calendar
When (and more importantly why) are merge commits created?
Tags: go
Published: 2023-08-19 20:25:43

_This post is part of my ["Shorts"](https://poddarayush.com/shorts) series, where each post is concise and hyper-focused on a single concept._

If you have worked with Git, you must have come across merge commits. These commits are not created every time you merge, but only on some special scenarios. In this post, we will learn about merge commits and when are they created. At the end of the post, I will also provide a way to avoid them.

## First, the simple fast-forward merge
Consider that you have a branch named `featureX` which diverges from the `main` branch like shown below.


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



If you try to merge `featureX` into `main` using `git merge featureX`, you will see the text `Fast-forward` in the merge output. Git uses this merge strategy when the commit pointed to by the branch that is being merged into - `main` in this case - is a direct ancestor of the branch that is being merged - `featureX` in this case.

In other words, if you start following the parent starting from the commit pointed to by `featureX` and you reach the commit pointed to by `main` after some jumps, Git will simply move _(fast-forward)_ the `main` branch pointer to the commit pointed to by `featureX`.


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

> I have used the `main` branch as an example. I don't mean to convey that merges can only happen into the `main` branch. Any Git branch can be merged into any Git branch.

## When the main branch is NOT an ancestor of your feature branch
Consider the scenario below where the `main` branch has moved ahead from the point where `featureX` diverged.



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



In this case, the commit pointed to by `main` is not an ancestor of the `featureX` branch. So, Git tries to find the common ancestor of the `main` and `featureX`. Then, Git performs a three-way merge between the common ancestor commit, the commit pointed to by `main`, and the commit pointed to by `featureX`. It creates a new snapshot that results from this merge and creates a "merge commit" on the `main` branch _(or the branch being merged into)_.


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




> A merge commit has more than one parent.

## Avoiding merge commits
To avoid "merge commits", you can rebase the `featureX` branch on the `main` branch. After the rebase, the commit pointed to by `main` will become an ancestor of `featureX`. To learn more about rebasing, I suggest you read my [post introducing git-rebase](https://dev.to/ello/stop-merging-the-main-branch-into-your-feature-branch-try-rebasing-5h87).

## References
- [https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging](https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging)
- [https://blog.git-init.com/the-magic-of-3-way-merge/](https://blog.git-init.com/the-magic-of-3-way-merge/)
Getting error on grade sync moodle
Published: 2023-08-19 20:19:19

while using cURL in moodle I am getting response as 

```
HTTP/2 401 
date: Sat, 19 Aug 2023 20:14:38 GMT
content-type: application/json; charset=utf-8
server: Apache
strict-transport-security: max-age=63072000; includeSubdomains
x-content-type-options: nosniff

{
    "status": 401,
    "reason": "Unauthorized",
    "request": {
        "method": "POST",
        "url": "/mod/lti/services.php/91/lineitems/234/lineitem/scores?type_id=4",
        "accept": "application/json",
        "contentType": "application/vnd.ims.lis.v1.score+json"
    }
}
```

can any one pls help me out
command not found: gsutil
Tags: firebase, cloudfunctions, tutorial, googlecloud
Published: 2023-08-19 19:50:50

Hola hola,

I ran into this error when trying to retrieve the most recent backup we have for one of our apps that use Firebase Cloud Functions. 

Here's the command I was trying to run from our Cloud Function Node project:

```
gsutil ls -l gs://{APP_FIRESTORE}-backup/backups/ | sort -k2 | tail -n1
```

## Looking to Google
I typed `command not found: gsutil cloud functions nodejs` into Google and found [this Google Cloud documentation](https://cloud.google.com/storage/docs/gsutil_install#sdk-install).

After downloading and extracting the `.tar.gz` file from step 2, I ran the following two commands from the folder that contains the extracted `.tar.gz`:
- `./google-cloud-sdk/install.sh` in the folder where the extracted `.tar.gz` existed (which was Downloads for me).
- `./google-cloud-sdk/bin/gcloud init`
  - This part can happen fast and you may chose the wrong project like I did. _[Here's a quick post](https://dev.to/matthewzruiz/changing-your-gcloud-cli-project-6cb-temp-slug-5170063) about switching projects._
  - Note: You may need to restart your terminal after installing `gcloud`.

That worked for my situation and I hope it helps others getting the `command not found: gsutil`.

- Matt
Changing your gcloud CLI project
Tags: firebase, node, cloudfunctions, tutorial
Published: 2023-08-19 19:50:12

Hola hola,

I was running into issues because I did not have `gcloud` or `gsutil` installed on our macs. Therefore, I could not run any related commands in our Firebase Cloud Functions project.

[After installing them](https://dev.to/matthewzruiz/command-not-found-gsutil-5fj2-temp-slug-8968256) I needed to switch the project.

First, I needed to retrieve the `PROJECT_ID` for the project that I wanted to switch to. I did that by running this command:
- `gcloud projects list`

Once I got the `PROJECT_ID` value, I then ran this command:
- `gcloud config set project {PROJECT_ID}`

If successful, you should see a message like:
- `Updated property [core/project].`

-Matt
Changing your Firebase CLI project
Tags: firebase, cli, cloudfunctions, tutorial
Published: 2023-08-19 19:47:23

Hola hola,

## TLDR
Retrieve `PROJECT ID` by running:
- `firebase projects:list`.

Once you have that id, run the following command:
- `firebase use {PROJECT ID}`

## Problem
As you work with projects, you'll notice that you will often have a `dev` and a `prod` database instance.

You don't want to test new features on live user data so you create a _duplicate_ of your `prod` database.

Now that you have two projects, you're gonna' need to switch between them as you test and deploy your Cloud Cunctions (CF).

Imagine the following scenario:

1. New CF feature A is being developed, tested, and deployed to the `dev` database/CF instances.
2. Feature A is now ready to release to our Users.
3. We need to now deploy the feature A updates to our `prod` instances. 

## Solution
_At this point, I will assume that you have installed [Firebase CLI](https://firebaseopensource.com/projects/firebase/firebase-tools/)._

These projects have a unique `PROJECT ID` that we use in our commands to switch projects.

First, we want to make get that `PROJECT ID`. Do that by running:
- `firebase projects:list`.

Once you have that id, run the following command:
- `firebase use {PROJECT ID}`

If successful, you should see a message like:
- `Now using project {PROJECT_ID}`

I hope that's helpful to some.

-Matt
API 101 USING POSTMAN(basics of API)
Tags: postmanstudent, postmanapi
Published: 2023-08-19 19:44:55

I have always wanted to learn about APIs and was opportuned to attend an event on the basics of APIs which was taken by @abdulkabirsultan

Although I had no background knowledge about APIs but the tutor was able to take us through the basics. Will be sharing some of the things I learned during the session below:

APIs(Application Programming Interfaces)is an intermediate software agent that allows dependent applications to communicate with each other. It allows developers to access data from a service without any knowledge of how the codebase has been implemented this makes it easy for developers to create services without building from scratch. APIs also acts as an intermediary between a client and the server. 
Postman is a standalone API development platform that offers a variety of features. It allows developers to easily create and share API requests and collections, automate testing, mock APIs and monitor performance. It also provides a simpler graphic user interface for sending and viewing HTTP requests and responses.

Moving on to how we interact with API (making requests) there are three(3) things needed to make a request:

1. Method(get method - to retrieve information, post method - to send information, put/patch method- to update information, delete method - to delete information)

2. Address(url)
3. Path
Illustrating these 3 using an example:

https://www.facebook.com/search
In the address above the (https:) stands as the method, (www.facebook.com) is the address or URL and (search) is the path i.e the destination where the request can be heard and executed.

Receiving responses
- status codes (e.g 201 created, 404 not found)
- headers
- accessing body data.

Talking about the request - response pattern:
A client can interact with an API by making requests over the network to the API. The API will then evaluate and interact with a database or other APIs then send back a response to the client.
The keywords are:
1. Client - an entity that makes a request to a server.
2. Network
3. Server - it controls resources and services. 

In order to further my knowledge I signed up for the API certification course.
Sending Jwt's using cookies in NodeJs Explained
Tags: node, javascript, webdev, beginners
Published: 2023-08-19 19:31:17

Sending JWTs (Json web tokens) using cookies in Node.js is like giving a special pass to someone after they've logged into a website. This pass, the JWT, is like a digital ticket that proves they're allowed to access certain parts of the website.

Imagine this pass is put inside a cookie, just like a tasty treat. So, when you visit the website, your browser automatically carries this cookie (with the pass inside) back and forth to the website with each request you make.

The website checks this pass to see if it's valid and not expired. If everything looks good, it lets you in. If not, it says, "Sorry, you can't come in."

This way, you don't have to enter your username and password every time you click on something on the website. It's a convenient and secure way to prove who you are without constantly typing in your credentials.
What is Application software
Tags: cse, softwaredevelopment, webdev, needdev
Published: 2023-08-19 19:10:42

Application software refers to computer programs and software designed to perform specific tasks or functions for users. Unlike system software, which includes the operating system and utilities that manage computer hardware and provide basic functionality, application software is tailored to the needs and preferences of users.

Examples of application software include word processors, spreadsheet programs, web browsers, photo editing software, video players, games, and various productivity tools. These programs are created to help users complete tasks, create content, or interact with digital media, making them an essential part of daily computing.
Understanding NestJS Modules
Tags: nestjs, javascript, node, beginners
Published: 2023-08-19 18:58:54

### What is a module?

In **NestJS**, a module is a class which helps to organize other building blocks of the application like components, services etc. maintaining modularity with separate concerns. 

Modules serve several key purposes in NestJS development.

Each module provides encapsulation and isolation to a closely related set of capabilities. This isolation helps to avoid naming conflicts and provides an effective way to organize the components.

A module class define providers and inject them into other components leveraging `Dependency Injection`.

Modules create way of reusability and scalability across the components and across projects and can also be nested within other modules creating a hierarchical structure.

### An example module

Let's create a basic Module.

```javascript
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}
```
In this example `UserModule` encapsulates the `UserService` and `UserController`.

Seems confusing? Let's break down the parts of the module.

### Breakdown of a module

`decorators`
We use the `@Module` decorator to create a module which takes a single object defining the module's properties.

`providers`
The provider that can be shared across other parts of the application and handles specific business logic and consists of service and other reusable components.

`controllers`
The set of Controllers which define end points and route handlers.

`imports`
The list of imported modules that export the providers required in this module.

`exports`
Modules export components available to be used outside the module.

### Conclusion

Modules are the backbone of a reusable and well structured NestJS application enabling us to create well-organized, scalable and modular codebases. This was a brief introduction to modules.

[Read more from the official documentation](https://docs.nestjs.com/modules)
Zsh, What is it and why should you use it?
Published: 2023-08-19 18:47:09

## What is Zsh?
Zsh, also called Z shell, is a UNIX shell that is built on top of the Bourne shell(macOS default shell), more commonly know as bash. It is essentially the same thing as bash but just has many additional features.

It was initially created by Paul Falstad while he was a student and Princetown University and originally it was created incorporating many useful features from other already present Shells like Bourne-Again Shell (Bash), the Korn Shell (ksh), C-shell (csh), and tcsh. So with that in mind, it does offer some level of compatibility with these mentioned shells, allowing it to have a high user adoption rate.

## How does it hold up to bash?
Zsh has plenty of features, some minor tweaks to bash, while there are other major like automatic directory changing by typing the name of said directory, spelling correction and approximate completion, and plugin and theme supports so you can customize you Zsh how you want! However, in our current years, bash isn't being left in the dust either. Both are always in active development because they're open source and in so, keep they fairly close to one another. You can even install oh-my-zsh to manage your zsh configurations, themes, and plugins to customize the appearance and functionality of your shell!

## So should I use it?

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

Zsh has proved itself time and time again that it is an incredibly powerful and fast shell, has tons of add-ons/features/themes/etc to customize it with, and having a user friendly CLI set up. If you as a SWE find yourself doing any sort of activity that requires you to use CLI often enough on your own personal computer, the Zsh would prove to be an incredible quality of life improvement. And who knows, even if you may not like Zsh it may open your eyes to another shell that will scratch that itch you have.

## In Conclusion...
Granted, I am still fairly new to Zsh and everything it can do, but I believe that everything it has to offer makes i more than worth the time to install and look around as it has so much to offer and is literally bash but better. I can only implore other people who use CLI frequently to give it a shot or even explore outside of just bash. I hope this blog gave some insight on a different terminal that may or may not change your CLI QoL.

Sources;
https://ohmyz.sh/
https://en.wikipedia.org/wiki/Z_shell
https://github.com/ohmyzsh/ohmyzsh
https://linuxhandbook.com/why-zsh/
https://www.howtogeek.com/362409/what-is-zsh-and-why-should-you-use-it-instead-of-bash/
Hello!
Tags: beginners, devops, career
Published: 2023-08-19 18:13:28

Hey! I'm Marshallshaddy, a full-stack developer and programmer. I love building things with code although it can be frustrating at times. 9-7 on my desk, C++ is infuriating, debugging is a nightmare. I'm always looking for new challenges and I'm excited to share my journey with you on this DEV community. Follow me to see what I'm up to!
DAY 77 - Find the Smallest Divisor Given a Threshold
Tags: leetcode, beginners, coding, codenewbie
Published: 2023-08-19 18:05:05

Hey Guys! It's day 77 and we are going to do another binary search question.


## Question: [Finding Smallest Divisor to Meet Threshold](https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/)

The problem involves finding the smallest divisor that, when applied to each element in an array, ensures that the sum of the divided values does not exceed a given threshold. Given an array `nums` of integers and an integer `threshold`, the task is to determine the smallest divisor that satisfies the threshold constraint.

## Approach Overview

The problem can be addressed through a binary search approach. The main idea is to search for the optimal divisor within a certain range. The algorithm should determine whether dividing each element by a particular divisor results in a sum that is within the threshold limit.

The approach involves the following steps:

1. Initialize the search range for the divisor. The lower bound can be set as 1 (minimum possible divisor), and the upper bound can be set as the maximum element in the array.

2. Perform a binary search within the defined divisor range. Calculate the sum of divided values using the `calcThreshold` function at the current divisor.

3. If the calculated sum is less than or equal to the given `threshold`, the current divisor is feasible. Move the upper bound of the search range to explore smaller divisors.

4. If the calculated sum is greater than the threshold, the current divisor is not feasible. Move the lower bound of the search range to explore larger divisors.

5. Repeat steps 2-4 until the lower bound is less than or equal to the upper bound.

6. The final value of the lower bound will represent the smallest divisor that meets the threshold constraint.

---

**Code:**

```cpp

class Solution {
public:
    long long calcThreshold(vector<int>& nums, int div){
    long long ans = 0;
    for(auto& it: nums){
        ans += (it + div - 1) / div;  // Corrected division
    }
    return ans;
}
    int smallestDivisor(vector<int>& nums, int threshold) {
        int n = nums.size();
        if (n > threshold) return -1;
        int low = 1;
        int high = *max_element(nums.begin(),nums.end());

        while(low <= high){
            int mid = low + (high-low)/2;
            if(calcThreshold(nums,mid) <= threshold){
                high =  mid-1;
            }
            else{
                low = mid+1;
            }
        }
        return low;
    }
};

```



**_Complexity Analysis:_**


| Algorithm | Time Complexity | Space Complexity |
|---|---|---|
| Binary Search Approach | O(nlog(m) | O(1) |