teleren/devto huggingface dataset:
How easy to deploy your app on vercel
Tags: nextjs, vercel, deployment, easy
Published: 2022-04-17 07:56:37

> Deploying app to vercel

1. Login to vercel by git account signup
2. Go to https://vercel.com/dashboard
3. Click on Create new project button on top right
4. Import git repository, (where you have to push your code excluding the node_modules folder)
5. After importing the git repo of your application, click on Import
6. Next click on Deploy. (Note – It will take few minutes)
7. Once deployed, click on the app image on left side to view
8. To edit the domain, click on domains & edit your domain
9. Thankyou & enjoy
Ways to handle disagreement at workplace
Tags: career, leadership, management
Published: 2022-04-17 07:21:54

As human beings, we cannot avoid disagreement no matter how good or how careful we are, there will be a time we will not agree with someone else's ideas, opinions, or actions

When disagreement happens, most of us will tend to just accept it and let it be just because we want to avoid confrontation or because our feelings are hurt.

The problem will not be solved and this will result in a bigger problem where it could affect our mental and work performance especially at work or with our colleagues. Here's the way to handle disagreement

## Acknowledge the disagreement
Recognize and acknowledge that 
there is a disagreement between both parties and work on ways to solve it. Everyone is entitled to their opinion. 

## Don't compare
Disagreement always comes from something that other people have said or done in the present but we have already experienced it in the past. This will trigger the emotional reaction that could start the disagreement. We need to learn how to control this feeling. Think as what happens now is not the same as what happened in the past and it is not related. This will help us deal with the conflict more effectively because of less emotional attachment involved

## Find a way to listen and understand
The biggest challenge in resolving conflict is a lack of willingness to listen and understand from the other parties. Try to not speak first. Hold it. Listen, and understand. Be calm and don't rush

## Do not look for differences
Find a common ground. Focusing on the differences will only widen the gap between us and the other party. If we want to end the disagreement, try to find a point that both of the parties can agree on even if it means that we have to make some compromises

## Be responsible for your own feelings
When we are at the peak of our anger or disagreement, it is so easy for us to make excuses, point blame, and make accusations. Oftentimes, conflict only lasts long because of the emotions involved in it. If we want to end the disagreement and move on, take full responsibility for our own feelings. Acknowledge how we have caused other people disappointment or hurt because of what we said or did during the argument

## Commit yourself to a resolution
Before we think that we want to make the relationship with the other parties become toxic after the disagreement. Think back, is it worth that conflict is worth destroying the relationship that has been built with that person. If it is not, commit ourselves to make sure that the other party understands that we want to resolve the conflict and continue to nurture the relationship.

We will encounter disagreement at some point in our life, but it should never hinder us from living a good life just because we don’t agree with someone else’s actions, ideas, or opinions. It’s all about knowing which battles to fight and which to just let be.

Hope this will help!
Most Commonly Used Annotations in Spring Boot
Tags: springboot
Published: 2023-03-07 14:39:53

---
title: Most Commonly Used Annotations in Spring Boot
published: true
date: 2022-04-17 06:54:10 UTC
tags: SpringBoot
canonical_url: 
---

Spring Boot Annotations are a form of metadata that provides data about a program that is not a part of the program itself. They do not have any direct effect on the operation of the code they annotate. Spring Boot Annotations do not use XML and instead use the convention over configuration principle. 

Following are some of the most used Spring annotations in no particular order.

**@SpringBootApplication** is Spring’s way of identifying that this application is from Spring Boot. It is also used for spring auto-configuration and component scan for your application. The component scan is used to identify which classes are to be instantiated in the application.

**@Component-** It is a generic stereotype for any Spring-managed component or bean. It tells Spring to look for “Components” when it starts up the application. Pretty much @Controllers, @Service, etc that may be found throughout your application.

**@Repository** – is a stereotype for the persistence layer.@Service – This stereotype is used to indicate that they’re holding the business logic. @Controller – is a stereotype for the presentation layer for Spring MVC application.

And here is a nice diagram to explain the hierarchy of all these annotations in Spring Framework:

![](https://stacktips.com/wp-content/uploads/2022/04/Blank-diagram.png)

**@Autowire** – This annotation is used to inject the dependencies without creating an object using a new keyword. Please note that it is recommended to use constructor-based injection instead of @Autowire annotation.

**@Bean** – The @Bean annotations are used at the method level and indicate that a method produces a bean that is to be managed by Spring container. For example:

```
@Bean
Public BeanExample beanExample () {
    return new BeanExample();
}

```

**@Configuration** – tells Spring to look for .properties files on your source path. Here, for example, you can define an “application.properties” file to define your data source (database information for Spring to use).

**@ControllerAdvice** – This annotation is used to handle exceptions at the global level. We will create a spring boot project step-by-step and handle the exceptions at the global level.

**@PostConstruct** – This annotation is executed after injections are committed to the given bean. We will create a spring boot project step-by-step and we will discuss this annotation.

**@Value** – This annotation is used to read the property value from the property file. We will create a spring boot project step-by-step and read the property from the property file with this annotation.

This is not an exhaustive list, there are many more annotations you can find in Spring Framework but that is for some other day. We will learn those as we cover each topic.

The post [Most Commonly Used Annotations in Spring Boot](https://stacktips.com/tutorials/spring-boot/spring-boot-annotations) first appeared on [Stacktips](https://stacktips.com).
How to mock node-fetch with Vitest
Tags: javascript, vitest, node, testing
Published: 2022-04-17 05:19:20

# What I Want to Do
  I want to mock [node-fetch](https://www.npmjs.com/package/node-fetch) with [Vitest](https://vitest.dev/), which is a unit-test framework. [Jest](https://jestjs.io/) introduces how to make a node-fetch mock. 

{% embed https://jestjs.io/docs/next/bypassing-module-mocks %}

Vitest is compatible with Jest in large part, but Vitest does not provide `jest.requireActual` helper is used in the above-linked article.
This article introduces how to mock `node-fetch` without using `jest.requireActual` by using Vitest.

# Required Environment
- Node.js

# Adding Necessary Dependencies
Vitest has not been common yet (at least in Japan), so I indicate how to install necessary dependencies.

```sh
npm i -D vitest vi-fetch node-fetch
```

# The Function I test
I made a simple function for testing. This function returns the `count` value of JSON on the response to access https://hogehoge.hogehoge.hogehoge with the GET method.

```js
import fetch from "node-fetch";

export const getCountNode = async () => {
  const response = await fetch("https://hogehoge.hogehoge.hogehoge"); // GET
  const countJson = await response.json(); // Get response body as json
  return countJson.count; // Return the value of count key in the response
};
```

# Writing Testing Code
As I mentioned before, Vitest does not provide `jest.requireActual` helper, so I implemented the following source code in reference to [the answer](https://stackoverflow.com/questions/58599735/jest-typeerror-response-json-is-not-a-function) written by E. Coleman et al. on stack overflow.

```js
import { describe, it, expect, vi } from "vitest";
import fetch from "node-fetch";
import { getCountNode } from "./getCountNode";

describe("sample", () => {
  it("hello", async () => {
    vi.mock("node-fetch");
    fetch.mockReturnValue(
      Promise.resolve({ json: () => Promise.resolve({ count: 33 }) })
    );
    const result = await getCountNode();
    expect(result).toBe(33);
  });
});
```

# Testing
The result of this testing is shown in the following. This result indicates "2 passed" because I ran another test simultaneously.

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

# Failed Testing Result
I modified the expected value in the testing. This testing failed.

```js
import { describe, it, expect, vi } from "vitest";
import fetch from "node-fetch";
import { getCountNode } from "./getCountNode";

describe("sample", () => {
  it("hello", async () => {
    vi.mock("node-fetch");
    fetch.mockReturnValue(
      Promise.resolve({ json: () => Promise.resolve({ count: 33 }) })
    );
    const result = await getCountNode();
    expect(result).toBe(31);
  });
});
```

This result is the following.

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

# Annotation
This article is originally written in Japanese.

{% embed https://zenn.dev/akira_kashihara/articles/2c3a985010f24b#fn-c036-1 %}
How to create CRUD routes in Nodejs in two lines only.
Tags: javascript, node, mongodb, programming
Published: 2022-04-17 04:24:18

hello dev,
How are you?
This post is about a tip that leaves your code clean and with fewer lines of code. So the idea is to group similar routes in your project's routes file using express's route method.
When we create a CRUD in Nodejs we have a route for each operation and it happens that we often have similar routes that differ only in the request methods (get, post, put and delete).
Imagine that, you have your routes as follows:
```js
router.get('/products', getProducts);
router.post('/products', createProducts);
router.put('/products/:id', updateProducts);
router.delete('/products/:id', deleteProducts);
```



Can you see that <strong>getProducts</strong> and <strong>createProducts</strong> are similar and only differ in the request method? Well, the same thing happens with <strong>updateProducts</strong> and <strong>deleteProducts</strong>.
So you can group similar routes as follows:




```js 

import { Router } from "express";
import { deleteProducts, getProducts, setProducts, updateProducts } from "../controllers/productsController";


const router = Router();

router.route('/').get(getProducts).post(setProducts);
router.route('/:id').put(updateProducts).delete(deleteProducts)

export { router }
```

## Feel free to fork this [repository on github](https://github.com/frantchessico/how-to-create-crud-routes-in-nodejs-in-two-lines-only) and ask for a star.

[Please follow me on instagram](https://www.instagram.com/frantchessico/)
Why you cannot pass location.reload as an argument
Tags: javascript, todayilearned, programming, webdev
Published: 2022-04-17 04:20:23

Let's say we have a function named `blockUser` which looks something like this

```js
const blockUser = (afterBlock = window.location.reload) => {
  // Some code to block the user
  afterBlock()
}
```
The interesting thing about this function is the `afterBlock` argument which defaults to `window.location.reload`. We basically want to reload the page after a user is blocked. But not always. Hence, the argument.


Lets use our pretty function:
```js
blockUser()
```
## Oops
![Illegal Invocation Error from Chrome](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5lirapf0xrotnzgyjzes.png)
Firefox gives us a more descriptive error. 
![Illegal Invocation Error from Firefox](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvruio7q9o88pnczzued.png)
 
 
## Why does this happen?
`location.reload` requires that `this` should point to `location`. When we are using javascript functions, `this` is bound to the scope from which the function was called.
if we call `window.location.reload()` directly, then the reload function is getting called through the location object. But lets say we do:
```js
const test = window.location.reload
test()
```
![Illegal Invocation Error from Chrome](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xirwwlcdgcg1omcgmazf.png)
 
We will still get the same error.
Let's try to create our own reload function to see what's going on.
```js
const fakeWindow = { location: { reload: function() { console.log(this) } } }
fakeWindow.location.reload()

// Re-assigning
let test = fakeWindow.location.reload
test()
```
![Custom reload function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfl4u3z58dtqscvnfpmp.png)

Whoa, looks like `this` is not the same anymore when we assign the reload function to a variable. If you remember the Firefox error, the reload function requires that it should be called from the context of `Location`. When we assign it to a variable, it gets called from the context of `Window`.

## How can we fix it?
The fix is pretty simple, you can just wrap a function around your re-assignment.

```js
const blockUser = (afterBlock = () => window.location.reload()) => {
  // Some code to block the user
  afterBlock()
}
const test = () => window.location.reload()
```
It works now! 😄

## Bonus
Can you guess what will happen if we defined our `fakeWindow` object a little differently? 
```js
const fakeWindow = { location: { reload: () => { console.log(this) } } }
fakeWindow.location.reload()
```
  
Have you ever come across this problem in a real project? Drop your thoughts and experiences in the comments. Don't forget to answer the question in Bonus section :)
Intro to Website Accessibility with CSS
Tags: css, html, a11y, webdev
Published: 2022-04-17 04:14:55

**What is website accessibility?**
Some users on your sites will use screen readers, only use a keyboard to navigate, use screen magnification, use speech input software, or use an older version of their browser. In CSS there are a number of ways you can make your sites accessible to these users.

- Focus styles
- Use `rem` for font sizing
- Browser prefixes

**Focus Styles**
Users who use only a keyboard to navigate will often use the Tab key to traverse websites. When Tab targeting different elements, the `focus` pseudo class is used to show which element is currently selected.

When I first started web development I would disable the focus outline because I thought it looked ugly, not knowing what it was really for. This is definitely a bad practice. A good alternative to disabling it, is the set your own focus behavior. This way elements that are focused will still be accessible to Tab users, and the focus outline or border will fit the color pallet of your site.

```css
*:focus {
  outline: none;
  border: 2px dotted blue;
}
```

**Use rem for Font Sizing**
The `rem` value will always be equal to the root elements `font-size`. If the default font size is 16px, then `1rem = 16px`. If the default font size is not explicitly set, then 1rem will be equal to the browser default font size.

If a user adjusts the font-size of their browser, then font-size set with rem will scale appropriately. Font sizes set with px will not be adjusted, which is bad for accessibility.

```css
.my-class {
  font-size: 1.5rem; 
  /*default font-size = 16px, so 1.5rem = 24px*/
}
```

**Browser Prefixes**
Not all CSS properties are available for all browsers. For example, the property `text-align-last` is not supported in any version of Safari. A good site for checking the availability of CSS properties on browsers is [https://caniuse.com/](https://caniuse.com/). 

You can use browser prefixes in your CSS to make these newer CSS features compatible with older browsers. Here are the four most common ones:

- `-moz-` for Firefox
- `-webkit-` for Android, Safari and Chrome
- `-o-` for Opera
- `-ms-` for Internet Explorer

```css
.my-class {
  -moz-text-align-last: right;
  -webkit-text-align-last: right;
  -o-text-align-last: right;
  -ms-text-align-last: right;
  text-align-last: right;
}
```
You can also use an [autoprefixer](https://www.npmjs.com/package/autoprefixer) package to make this process easier.

This article covered a few of the main ways to make your site more accessible with CSS, but this article only scratches the surface. A resource I recommend is the Web Content Accessibility Guidelines (WCAG) [https://www.w3.org/TR/WCAG22/](https://www.w3.org/TR/WCAG22/)

Leave a comment if you have any feedback or questions.
Why Data Structures and Algorithms are Important ?
Tags: coding, computerscience, ds, dsa
Published: 2022-04-17 04:10:39

• A lot of beginners and experienced programmers
avoid learning data structures and algorithms
because it's complicated and they think that
there is no use of all the above stuff in real life.

• These concepts help to improve the problem-
solving ability of a candidate to a great extent.

• To Solve Some Real-World Complex Problems

• You learn to use the right tool to solve the
problem

• To Crack the Interviews of the Top Product
Based Companies

**Important Topics** :

Data Structures :

- Arrays
- Heaps
- Stacks
- Queues
- Linked lists
- Collections
- Trees
- Hashtables
- Algorithms
- Complexity analysis
- Search
- Recursion
- Sort

Algorithms :

- Greedy algorithms
- Divide and conquer
- Dynamic programming
- Hashing
- Complexity analysis
- NP-completeness
- Approximation
- Linear programming
- Graph-algorithms
- Maximum flow

**Resources** :

Courses :

• MIT free open course on algorithms
• Stony brook university
• Open course
• NPTEL
• Princeton university

Books :

• Introduction to algorithms (Thomas h)
• Cracking the coding interviews
• DS and algorithms (Alfred v)

Websites :

• Geeksforgeeks
• Leetcode
• Topcoder
• Visualgo
Full stack monorepo boilerplate
Tags: graphql, react, mongodb, javascript
Published: 2022-04-17 03:42:27

We often struggle to built a repo with frontend and backend codes in the same repository. Many questions comes to our mind like is it a good practice to have both in the same repository? Is it maintainable? etc.

There is already a solution for maintaining multiple `features/modules/repositories` which is called **monorepo**. Many companies like Microsoft, Meta and Twitter follows it.

There are many ways to achieve mono repo structure like [Lerna](https://lerna.js.org/), [Rush](https://rushjs.io/), [Nx](https://nx.dev/)

<hr />
I have created a boiler plate for maintaining full stack applications. Here is the Github link - https://github.com/knowankit/fullstack-monorepo-boilerplate

I am using [Nx](https://nx.dev/) for mono repo. For front end I am using React with typescript and for backend I am using [NestJS](https://nestjs.com/), [GraphQL](https://graphql.org/) server with [mongoDB](https://www.mongodb.com/)

There is a working todo-app added in the repo which makes it easy to understand the flow.

Clone the repo and run `npm install` and after the `npm run dev`.

This single command will start both the front end and the back end application.

Do give a ⭐️ to the [monorepo-fullstack-boilerplate](https://github.com/knowankit/fullstack-monorepo-boilerplate) if you liked it.
Blazing fast comment system with Sveltejs and Supabase
Tags: javascript, jamstack, opensource
Published: 2022-04-17 03:22:11

Hey There,

MC.Naveen here. Developer of SupaComments. A simple open-source comment system for JamStack websites.

Built with Sveltejs and Supabase

For a long time, I wanted to build my own comment system. Finally had an opportunity when I found Supabase.

This doesn't have a lot of features at the moment. But I'm happy to improve based on your suggestions.

Feel free to check the [demo](https://supacomments.vercel.app/?ref=dev-to)
You can find the [source code here](https://github.com/mcnaveen/SupaComments)

> Supacomments is the #3rd Product of the day in ProductHunt
> <a href="https://www.producthunt.com/posts/supacomments?utm_source=badge-top-post-badge&utm_medium=badge&utm_souce=badge-supacomments" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/top-post-badge.svg?post_id=341628&theme=dark&period=daily" alt="SupaComments - A&#0032;blazing&#0032;fast&#0032;comment&#0032;system&#0032;for&#0032;your&#0032;JamStack&#0032;sites | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>

If you're a developer, Feel free to contribute.
Thank you.
Json Web Token, ¿Qué es?
Tags: backend, jwt, token, authentication
Published: 2022-04-17 02:39:54

*¿Qué es JWT o Json Web Token?*

JSON Web Token es un estándar abierto basado en JSON propuesto por IETF para la creación de tokens de acceso que permiten la propagación de identidad y privilegios o claims en inglés.

Contiene **toda la información importante** sobre una entidad, lo que significa que no hace falta consultar una base de datos ni que la sesión tenga que guardarse en el servidor (sesión sin estado)

*¿Cómo se compone un JWT?*

Un token JWT se compone de 3 partes codificadas en base64 que están separadas por un punto. Estas tres partes son las siguientes:

**Header**:

Contiene generalmente 2 valores y nos proporciona información sobre tipo de token y el tipo de cifrado que se utilizó para generarlo:

```python
{ "alg": "HS256", "typ": "JWT" }
```

**Payload:**

Contiene los datos del usuario y sus privilegios, aunque también podemos enviar otros tipos de datos(algo que no es recomendable)

**Signature:**

Sería la firma que nos permite verificar que quien está tratando de hacer algo con nuestra aplicación sea la persona con los permisos suficientes. Esta firma se crea a través de la unión de las anteriores partes (Header + Paylod) codificados en base64 y una clave secreta que generalmente es proporcionada por el servidor, esto hace que el hash generado sea único y si alguien intenta modificarlo, su valor va a cambiar, por lo que no ya no va a servir para hacer peticiones en nuestro server.

Generando un JWT en pseudocódigo(Platzi):

```python
key =  'clavesecreta'
unsignedToken = base64Encode(header) + '.' + base64Encode(payload)
signature = SHA256(key, unsignedToken)
token = unsignedToken + '.' + signature
```

Token final:

```bash
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjUwMTYyNzQxLCJpYXQiOjE2NTAxNjI0NDEsImp0aSI6Ijg0ZjhjMDlkZDE2MzRiMGNhZDlhMzUzZTNmODNlMDA4IiwidXNlcl9pZCI6MX0.qflyviX71uzLknz5YAjviVr1Bya-Z1e9AGXuHKuwEFc
```

Algo bueno es que podemos jugar con la página oficial de JWT y ver la composición de un token de una manera mucho más entendible:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glhyskrwe7cy4gz741bk.png)
How to change your website's font with google fonts
Tags: webdev, css, html, tutorial
Published: 2022-04-17 02:27:06

While HTML does contain some usable fonts, some of you might want to change your font into something unique. Today, I'll be showing you how to change your website's font with google fonts.

First, visit [https://fonts.google.com/](https://fonts.google.com/) and click on a font, after that, choose a style then click select this style. When you have selected the style, something should pop up from the side, if not, click this button on the top right corner.

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

Copy the HTML code and put it within your HTML files head. Now, you can add the CSS font family as shown in the popup!

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

Thanks for reading, I really hope this guide helped you through your web dev journey.