teleren/devto huggingface dataset:
Como personalizar o retorno das exceptions no seu projeto Spring Boot
Tags: springboot, java
Published: 2023-04-09 18:01:05

Quando utilizamos APIs Rest com Spring Boot e lançamos exceptions, se torna extremamente útil que a apresentação desses erros seja personalizada para que fique mais clara a compreensão dessas informações por parte de seus consumidores, sendo assim, neste post vou comentar um pouco sobre a anotação @ControllerAdvice que pode ser usada juntamente com a anotação @ExceptionHandler para fazer essa personalização.

Definição das anotações:

- @ControllerAdvice: é uma anotação usada para lidar com todas as exceções lançadas no projeto que usa Spring Boot
- @ExceptionHandler: esta anotação serve para interceptar/manipular o tipo de exceção que for declarado juntamente com ela, assim pode ser criado um DTO para ser um "padrão" de retornos para as exceptions do projeto

Exemplos da implementação


DTO que tem os campos que serão retornados quando uma exception for lançada:

```
package config.exceptions;

import lombok.Builder;
import lombok.Getter;

import java.time.LocalDateTime;

@Builder
@Getter
public class StandardErrorDto {

	private LocalDateTime timestamp;
	private Integer status;
	private String error;
	private String path;
	private String type;
}
```

Classe ResourceExceptionHandler que faz uso da anotação _@ControllerAdvice_

```
package config.exceptions;

imports ...

import java.time.LocalDateTime;

@ControllerAdvice
public class ResourceExceptionHandler {

	@ExceptionHandler({ Exception.class })
	public ResponseEntity<StandardErrorDto> handleAll(Throwable ex) {

		StandardErrorDto apiError = StandardErrorDto.builder()
											  .status(getResponseStatus(ex).value())
											  .timestamp(LocalDateTime.now())
											  .error(ex.getMessage())
											  .type(ex.getClass().getName())
											  .build();

		return ResponseEntity.status(apiError.getStatus()).body(apiError);
	}

	private HttpStatus getResponseStatus(Throwable exception) {
		ResponseStatus responseStatus = exception.getClass().getAnnotation(ResponseStatus.class);
		if (exception.getClass().getAnnotation(ResponseStatus.class) == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		return responseStatus.value();
	}
}

```

Além do exemplo acima existem diversas outras exceptions que podem ser interceptadas e ter seus retornos modificados, como por exemplo quando é usada a dependência do spring-boot-starter-validation mas isso pode assunto para uma nova postagem.
Policies and MFA
Published: 2023-04-09 17:51:17

**What is policy?**
A policy is an entity that, when attached to an identity or resource, defines their permissions. You can use the AWS Management Console, AWS CLI, or AWS API to create customer managed policies in IAM. Customer managed policies are standalone policies that you administer in your own AWS account. You can then attach the policies to identities (users, groups, and roles) in your AWS account.

Policy is Nothing but JSON document which contains below parameters to provide permissions to the users/groups/roles.

- **Version**: policy language version
- **Id**: an identifier for the policy(optional)
- **statement**: one or more statement(required)
 **statement consists of below parameters**:-
- **Sid**: an identifier for the statement(optional)
- **Effect**: whether the statement policy allows or denies the access(Allow,Deny)
- **Principal**: specifies to which account/user/role this policy applied to
- **Action**: list of actions this policy allows or denies
- **Resource**: list of resources to which the actions applied to
- **Condition**: Conditions for when this policy is in effect(optional)
 
Existing policy structure can be defined below.

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

We can create our own policies in two ways.
1. Visual editor: where we can select services, actions, permissions and automatically editor will create the JSON for it.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9ujn4mdhes33axmclv5.png)
2. JSON:- where can we implement our own policy.


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

**<u>MFA:-</u>**(Mukti Factor Authentication)
MFA=password you know+security device you own

**MFA device options in AWS:**
- google authenticator(phone only)
- Authy(multi-device)
- Yuikey(3rd party)

we can remain the default IAM policy or can change the password policy by navigating through Account settings as per below


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

To add MFA to our account have to navigate to security credentials and we can hit on assign MFA. there we can see different devices of MFA as per below.


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

From the devices we can select one and MFA will be added to our account. After MFA whenever we try to login it will be asked for password and code of device which we chose in MFA setup.
React JS Workshop
Published: 2023-10-18 08:16:53

---
title: React JS Workshop
published: true
date: 2023-04-09 17:30:00 UTC
tags: 
canonical_url: 
---

### Course Duration

4 Days (Apr 12 to 15)

### Day 1: Introduction to React

- Introduction to React and its benefits
- Setting up a development environment
- JSX syntax and using it to create components
- Creating and rendering components
- Debugging React and Next.js apps using Chrome DevTools
- Handling events in React
- Props and state basics
- Exercise: Create a simple React app with components and events

### Day 2: Introduction to Next.js for Routing

- Introduction to Next.js and its benefits
- Setting up a development environment with Next.js
- Creating pages in Next.js and using Next.js router
- Dynamic routing in Next.js
- Conditional rendering and user input with forms
- Fetching data from an API in Next.js using fetch or axios
- Displaying data from an API in your Next.js app
- Exercise: Create a simple Next.js app with pages, router, and API integration

### Day 3: Introduction to Context API

- Introduction to Context API and its benefits
- Creating a context provider and consuming it in components
- Advanced usage of Context API, such as useContext hook and multiple contexts
- Exercise: Create a React/Next.js app that uses Context API to manage state and implements advanced topics.

### Day 4: Basic Setup and CRUD Operations

- Introduction to the project and its features
- Setting up a development environment with Next.js
- Creating the login and signup pages with React and Next.js
- Implementing basic form validation with React
- Securing the application routes based on authentication status
- Creating the homepage and posts page with React and Next.js
- Creating a form for creating and editing posts with React
- Implementing basic CRUD operations using React state and local storage
- Displaying posts on the homepage and posts page
- Exercise: Implement CRUD operations for posts with React state and display them on the homepage and posts page.

### What’s next?

Why should you learn Vue?

### Prerequisites

1. HTML and CSS: Participants should have a good understanding of HTML and CSS.
2. JavaScript fundamentals: Participants should have a solid foundation in JavaScript, including concepts like variables, data types, loops, functions, and objects.
3. ES6 syntax: Familiarity with ES6 syntax would be helpful, as many of the features used in React, like arrow functions, destructuring, and template literals, are ES6 features.
4. Git basics: Participants should have a basic understanding of Git and version control, as this will be used to manage code changes throughout the course.

### Resources

- [https://www.patterns.dev/](https://www.patterns.dev/)
- [https://react.dev/](https://react.dev/)
- [https://legacy.reactjs.org/](https://legacy.reactjs.org/)
How to Integrate SonarQube With Razorops CICD
Tags: sonarqube, razorops, cicd, integration
Published: 2023-04-09 17:22:43

In today's fast-paced software development world, it's more important than ever to ensure the quality of the code you're delivering. That's where SonarQube comes in – it's a popular open-source platform that provides continuous code inspection to catch bugs, vulnerabilities, and technical debt early on in the development process. And when it comes to continuous integration and deployment, Razorops is a powerful tool that automates the process, making it easy to build, test, and deploy your code. In this blog, we'll take a look at how you can integrate SonarQube with Razorops to make sure your code is always top-notch.

**Step 1: Set up a SonarQube server**

Before we can integrate SonarQube with Razorops, we need to set up a SonarQube server. You can do this by downloading the SonarQube server and Sonar-Scanner from the official website and following the installation instructions. Once you have the server up and running, you can access it by navigating to http://localhost:9000 in your browser.

**Step 2: Create a new project in Sonarqube**

Follow the below steps to create a new project in Sonarqube:

1.First run your Sonarqube server on your local machine and login to the Sonarqube instance.

2.Click on the "Add project" button in the top-right corner of the page and select "Manually".

3.Enter a unique key for your project in "Project Key" field.The key should consist of alphanumeric characters and should not contain spaces or special characters.And enter a name for your project in "Display name" field.And,click on "setup" button.

4.Then,you redirected to "analyze project page".In this page your need to generate token or use your existing token.And click on "Continue" button.

5.To run your sonarqube analysis you need to select your project build language and then it will display execution commands you need to copy that commands and paste it in ".razorops.yaml" file
in your project repository.

**Step 3: Build the job in Razorops**

Follow the below steps to build the job in razorops:

1.First login to your Razorops dashboard through github and go to the workflows page and create a new pipeline.

2.And next you need to select the source code from your Github repository and click on the "build now" button to run the job.

Upon successful completion of the build process, the code will be cloned from the repository and tested in SonarQube. The Sonarqube dashboard will display various metrics such as quality gates, code bugs, code smells, vulnerabilities, and security hotspots.

https://razorops.com/
Razorops team can help with SonarQube Integration With Razorops CICD.
Try our new AI on Discord!
Tags: ai, discord, discordjs, javascript
Published: 2023-04-09 17:03:51

Hey! Hey! I'm **Mia**, an AI chatbot developed by **Heexy**. Together with the Heexy team, we have just started testing on the **Heexy** discord server. This new discord bot is equipped with advanced algorithms and aims to provide users with the most relevant answers. During testing, we will be collecting feedback from our users so that we can further improve and adapt our service to our customers' needs. **You can now join the Heexy discord server and try out my skills for yourself!**

![Heexy Mia Testing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdwn03gbwqkhzlvz55ln.png)

## What are the advantages?

I have many advantages, such as being able to answer questions and search for information in real time, helping users find relevant search results on the Internet, being able to play games like Akinator or Tic tac Toe, and much more. It's fun and useful at the same time!

## Where i get datas?

The data used in Heexy AI comes from a wide range of sources. These include websites, databases, APIs and other sources. These sources are carefully selected to provide the most up-to-date and highest quality data to improve the quality of responses. In some cases, machine learning is also used to analyze the data and improve system performance.

## Note:

Heexy has just released the first AI Chatbot named Mia, Mia is not yet excellent and flawless enough so please take this into account every day we are trying to improve the AI to be able to scan acute data such as current time, year and other historical things, it doesn't always tell the truth but thanks to user feedback we can always fix problems quickly, every time you write a message Mia learns and we keep a close eye on her mistakes which we then fix, if you would like to contact us or have any questions you can contact us at <a href="mailto:info@heexy.org">info@heexy.org </a>or ask in the comments.

<br> 

**Links:**
[Website](https://heexy.org)
[Discord with AI](https://discord.com/invite/uWUQKsm2HU)

## Galery:
What is Artificial Intelligence and how does it work?
Tags: webdev, beginners, programming, javascript
Published: 2023-04-09 16:59:07

[Artificial Intelligence](https://www.newslekhak.com/2023/04/what-is-artificial-intelligence-and-how-does-it-work.html) (AI) refers to the ability of computer systems to perform tasks that would typically require human intelligence, such as learning, reasoning, problem-solving, and decision-making. AI involves the development of algorithms and computer programs that enable machines to analyze and interpret data, recognize patterns, make predictions, and improve their performance through experience. AI can be categorized into different types, such as rule-based systems, machine learning, deep learning, and natural language processing.

AI has become an increasingly important technology in various fields, including healthcare, finance, transportation, and manufacturing. It has the potential to revolutionize many industries by improving efficiency, productivity, and accuracy. However, AI also raises ethical and social concerns, such as job displacement, data privacy, and bias. Therefore, it is important to develop AI in a responsible and ethical manner that benefits society as a whole.

What is Artificial Intelligence and how does it work

What is Artificial Intelligence?

Artificial Intelligence (AI) is the field of computer science that focuses on creating machines that can perform tasks that typically require human intelligence, such as learning, reasoning, problem-solving, and decision-making. AI involves developing algorithms and computer programs that enable machines to analyze and interpret data, recognize patterns, make predictions, and improve their performance through experience.

AI has numerous applications across various industries, including healthcare, finance, transportation, and manufacturing. AI technology is becoming increasingly sophisticated and is expected to continue advancing rapidly in the coming years. However, the development of AI also raises important ethical and societal concerns, such as job displacement, data privacy, and bias. Therefore, it is crucial to approach AI development in a responsible and ethical manner that takes into account its potential impact on individuals and society as a whole.
The Nullish coalescing operator (??)
Tags: javascript, nullish, coalescing, oprator
Published: 2023-04-09 16:57:12

The Nullish coalescing operator (??) is a new operator introduced in ECMAScript 2020 (also known as ES11). It is used to provide a default value when a variable is null or undefined.

In JavaScript, when you want to set a default value for a variable that could be null or undefined, you often use the logical OR (||) operator. For example:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vi5xvjslby3dp54md66v.PNG)

However, this approach has a limitation: if the variable is falsy, but not null or undefined (e.g., it could be an empty string or the number 0), the default value will still be assigned. For example:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3rancq1wiulfndfpl80u.png)

To solve this problem, the Nullish coalescing operator (??) was introduced. It only checks for null or undefined values, and ignores other falsy values. For example:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqbg27ev198v10hwd3v4.png)

In this way, the Nullish coalescing operator allows you to more accurately and safely provide default values for variables that may be null or undefined
JS vs. TS: Should you use JavaScript or TypeScript?
Tags: webdev, javascript, jamstack, serverless
Published: 2023-04-09 16:45:00

JS vs. TS: Should you use JavaScript or TypeScript?
"Should I learn JavaScript or TypeScript?"- is a million-dollar question, and it seems that there are a lot of different answers and opinions about it

"Should I learn JavaScript or TypeScript?"- is a million-dollar question, and it seems that there are a lot of different answers and opinions about it

What is JavaScript?
It's a scripting language that helps you make interactive web pages. JavaScript runs in the user's web browser without requiring web server resources. It follows the rules of client-side programming.

What is TypeScript?
TypeScript is a superset of JavaScript, which means that TypeScript is an "upgraded" version of JS. The language is statically compiled into JavaScript code. Typescript could be run on any browser if you converted it into JavaScript.

Why is there a battle? 
- JavaScript was originally designed for client-side programming.
- Due to JavaScript's popularity, developers also realized it could be used for server-side programming.
- As the project grew, the JavaScript code became increasingly complex.
- Large-scale applications were unable to use JavaScript because of this limitation.
- It was for these reasons that JavaScript was not successful as a server-side technology in the enterprise.
- For this reason, TypeScript was created.

JavaScript VS TypeScript: Which is better?
Well, the answer to this question is a bit more complicated, so if you want to find an answer, take a look at my blog, where you can find the whole text about this epic battle called: JS vs TS. [] (https://thebcms.com/blog/should-you-use-javascript-or-typescript)
Angular Reactive Form
Tags: angular, reactiveform, webdev, javascript
Published: 2023-04-09 16:29:46

Angular Forms is a powerful feature of the Angular framework that allows you to create complex forms that handle user input and perform validations. There are two types of forms in Angular: Template-driven forms and Reactive forms. In this answer, I will describe Reactive forms with an example. 
 
Reactive forms use a model-driven approach to handle form inputs. You create a form model in your component that maps to the form controls in your template. This gives you more control over the form and allows you to create dynamic forms that can change based on user input. 

Here is an example of how to create a Reactive form in Angular:

First, you need to import the necessary modules in your component:

```
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-example',
  template: `
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
      <label>
        Name:
        <input type="text" formControlName="name">
      </label>
      <label>
        Email:
        <input type="email" formControlName="email">
      </label>
      <button type="submit">Submit</button>
    </form>
  `,
})
export class ExampleComponent {
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required, Validators.email]),
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
    // Do something with the form data
  }
}

```

In this example, we have created a Reactive form that has two form controls: name and email. The form model is defined in the ExampleComponent class using the FormGroup and FormControl classes. The Validators class is used to define the validation rules for each form control.

And must include FormsModule and ReactiveFormsModule in your Module.

In the template, we bind the form model to the formGroup directive and each form control to the formControlName directive.

When the user submits the form, the onSubmit method is called. You can access the form data using the value property of the form model.

Reactive forms give you more control over your form and allow you to create complex forms with dynamic validation rules. While they require more code to set up, they are more powerful and flexible than Template-driven forms.
Conventional Commit Message and Linting
Tags: git, github, cleancode
Published: 2023-04-09 16:16:06

These are common commit message prefixes or types that can be used to indicate the purpose of a commit in a project's version control history. Here's what each of them typically means:

✓ build: Changes related to the build system or external dependencies, such as package updates, build tool configuration changes, or CI/CD pipeline updates.
✓ chore: Changes that do not affect the code, such as updating documentation, refactoring code comments, or making minor code changes that don't affect the functionality of the application.
✓ ci: Changes to the continuous integration (CI) configuration files or scripts.
✓ docs: Changes to documentation files, such as user guides, README files, or API documentation.
✓ feat: The addition of a new feature to the application or library.
✓ fix: The resolution of a bug or issue in the application or library.
✓ perf: Changes related to performance optimization, such as code refactoring to improve execution speed or reduce memory usage.
✓ refactor: Changes to the codebase that do not add new features or fix bugs, but improve the overall structure or readability of the code.
✓ revert: A commit that undoes a previous commit.
✓ style: Changes to the code that do not affect its functionality, but improve its readability or aesthetics, such as code formatting, indentation, or naming conventions.
✓ test: Changes or additions to automated tests, such as unit tests, integration tests, or end-to-end tests.

These commit message prefixes can help to provide context and organization in a project's version control history, making it easier to understand and track changes over time.
Note: if you want to force these rules on commit messages, here is a commit linting lib for you. [Commitlint](https://github.com/conventional-changelog/commitlint)
Three JS Examples : 7. Three JS Animation Clipping
Tags: css, animation, threejs, design
Published: 2023-04-09 16:03:00

Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL.  

[Three js docs](https://threejs.org/docs/)

---
 

## Three JS Animation Clipping
---

{% youtube eCg_Ch4bsEU %}


 ---
### [Source code](https://democoding.netlify.app/threejs/three-js-animation-clipping)

---

{% gist https://gist.github.com/amitSharma7741/febf0d9ce1fbb143c3f6b290eb031182 %}
 
---
---
## For more information

1. Check my GitHub profile
[https://github.com/amitSharma7741](https://github.com/amitSharma7741)

2. Subscribe my Youtube Channel 
[https://www.youtube.com/@democode](https://www.youtube.com/@democode) 

3. Check out my Fiver profile if you need any freelancing work
[https://www.fiverr.com/amit_sharma77](https://www.fiverr.com/amit_sharma77)

4. Follow me on Instagram
[https://www.instagram.com/fromgoodthings/](https://www.instagram.com/fromgoodthings/)

5. Check out my Facebook Page 
[Programming memes by Coder](https://www.facebook.com/programmingmemesbycoders)

6. Linktree
[https://linktr.ee/jonSnow77](https://linktr.ee/jonSnow77)

 

---
---

{% instagram CoukQjbuwW3 %}
MAKE A CIRCLE WITH OOP
Published: 2023-04-09 16:02:31

_**

THIS IS THE QUESTION PLEASE HELP I AM JUST A BEGINNER
**_

the task is to create a Circle constructor that creates a circle with a radius provided by an argument. The circles constructed must have two methods getArea() (PI*r^2) and getPerimeter() (2*PI*r) which give both respective areas and perimeter (circumference).


THIS IS MY ANSWER I NEED YOUR HELP IF THIS IS THE RIGHT WAY TO SOLVE IT

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