teleren/devto huggingface dataset:
Dicas de Spring #1 – simulando autenticação no Spring Security em testes automatizados
Tags: braziliandevs, tutorial, ptbr, spring
Published: 2021-06-16 12:56:49

---
title: Dicas de Spring #1 – simulando autenticação no Spring Security em testes automatizados
published: true
description: Dicas de Spring #1 – simulando autenticação no Spring Security em testes automatizados
tags: braziliandevs, tutorial, ptbr, spring
cover_image: https://fiverr-res.cloudinary.com/images/t_main1,q_auto,f_auto,q_auto,f_auto/gigs/109433199/original/3f84cb797311c050a6961452736962dd64cb9f69/build-your-website-with-security-using-spring-java-framework.png
---
Estamos iniciando nossa série "Dicas de Spring". Neste primeiro post vamos ver como&nbsp;proceder para simular uma autenticação na escrita dos seus testes unitários ou de integração.

O primeiro passo é incluir a dependência&nbsp;<em>spring-security-test</em> em seu projeto. Se estiver usando Maven, basta incluir este código em seu arquivo&nbsp;<em>pom.xml</em>:
<pre>&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
  &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;
  &lt;version&gt;substitua pelo mesmo número da versão do seu Spring Security!&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
 &lt;/dependency&gt;</pre>
&nbsp;

Gradle? Igualmente fácil, inclua a dependência no seu arquivo <em>build.gradle</em> tal como exposto a seguir:
<pre>testCompile "org.springframework.security:spring-security-test:[versão]"</pre>
&nbsp;

Muita atenção para o escopo da dependência (apenas teste) e o número da versão, que sempre deve ser o mesmo que o da sua instalação do Spring Security.

Feito isto, simular um usuário autenticado é algo incrivelmente fácil: basta que você use a classe&nbsp;<em><a href="http://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/test/context/TestSecurityContextHolder.html">TestSecurityContextHolder</a></em> que vêm na dependência <em>spring-security-test</em> (pacote <em>org.springframework.security.test.context</em>), tal como no exemplo abaixo:

&nbsp;
<pre>TestSecurityContextHolder
     .getContext()
     .setAuthentication(new JwtUser(account, new ArrayList&lt;GrantedAuthority&gt;()));</pre>
&nbsp;

A classe JwtUser é uma classe que inventamos e&nbsp;que implementa a interface <a href="http://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/core/Authentication.html">Authentication</a> do Spring Security que recebe como parâmetro uma lista de permissões e o objeto que representa o usuário autenticado.

E é simples assim. Não é muito difícil imaginar como podemos proceder para simular o mesmo efeito com Grails no plugin Spring Security Core, hein? Quem sabe não será nossa próxima&nbsp;<em>Dica de Grails</em>?
Dicas de Java #1 - muito cuidado com SimpleDateFormat e seu aspecto "lenient"!
Tags: braziliandevs, ptbr, tutorial, java
Published: 2021-06-16 12:54:04

---
title: Dicas de Java #1 - muito cuidado com SimpleDateFormat e seu aspecto "lenient"!
published: true
description: 
tags: braziliandevs, ptbr, tutorial, java
cover_image: https://i2.wp.com/dfilitto.com.br/wp-content/uploads/2020/02/java.png?fit=640%2C444&ssl=1
---
Em Java (e Groovy) é muito comum validarmos&nbsp;uma data digitada usando a classe <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>&nbsp;escrevendo código&nbsp;muito parecido com o exposto a seguir:

```java
String dataInvalida = "45/42/2017"; // mês 42???</code>
SimpleDateFormat formatoData = new 
SimpleDateFormat("dd/MM/yyyy");
try {
  Date dataParseada = formatoData.parse(dataInvalida);
// se parseou, data válida!
  } catch (ParseException ex) {
// data inválida! Não parseou
 }
```
Por mais estranho que possa parecer, a data acima será considerada válida por SimpleDateFormat. Isto se deve ao aspecto "lenient" de sua implementação: um atributo do tipo boolean cujo valor default é true.

Se está definido como verdadeiro, SimpleDateFormat irá executar eurísticas internas para descobrir qual a data a partir da loucura que você forneceu. No exemplo acima a data encontrada será&nbsp;15/7/2020 (experimente com o código acima).

Como resolver então? Simples: chamando o método setLenient e passando para este o valor false, tal como no exemplo abaixo:

<code>String dataInvalida = "45/42/2017"; // mês 42???</code>
<code>SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");</code>
<code>formatoData.setLenient(false); // simples!</code>
<code>try {</code>
<code>&nbsp; &nbsp;Date dataParseada = formatoData.parse(dataInvalida);</code>
<code>&nbsp; &nbsp;// se parseou, data válida (de verdade)!</code>
<code>} catch (ParseException ex) {</code>
<code>&nbsp; &nbsp;// data inválida! Não parseou. Bobagem enviada.</code>
<code>}</code>

Problema resolvido, e não, infelizmente você não descobriu um bug na classe SimpleDateFormat. :)
Dicas de WordPress #1 – Melhorando a segurança
Tags: wordpress, braziliandevs, ptbr, tutorial
Published: 2021-06-16 12:46:53

---
title: Dicas de WordPress #1 – Melhorando a segurança
published: true
description: Dicas de WordPress #1 – Melhorando a segurança
tags: wordpress, braziliandevs, ptbr, tutorial
cover_image: https://geekflare.com/wp-content/uploads/2019/10/wp-security-best-practices-1200x385.jpg
---
Não uma, mas duas&nbsp;dicas rápidas que irão tornar mais segura a sua instalação do Wordpress.
<h2>Localização do arquivo wp-config.php</h2>
No arquivo wp-config.php ficam armazenadas as configurações essenciais do Wordpress, dentre as quais&nbsp;o modo como é realizada a conexão com o banco de dados. Por padrão este arquivo fica no diretório raiz da sua instalação do Wordpress, mas sabia que esta não é a única localização possível para este arquivo?

Ele também pode ficar no diretório pai que contém a sua instalação do Wordpress. Sendo assim, se sua instalação fica em <em>/var/www/meu_site</em>, você pode (e deve)&nbsp;armazena-lo em <em>/var/www</em>, tornado com isto muito mais difícil a obtenção deste arquivo através de algum ataque realizado ao seu servidor.

Por padrão o Wordpress sempre busca o arquivo primeiro no diretório de sua instalação e, não o encontrando, um diretório acima.
<h2>Prefixo no nome das tabelas</h2>
No momento em que o Wordpress é instalado, um dos campos a ser preenchido diz respeito ao prefixo a ser adotado no nome das tabelas.


Muitos acham que a principal razão para este prefixo é diferenciar as tabelas em um banco de dados compartilhado. É: também é pra isto, mas&nbsp;a razão principal é <strong>segurança</strong>.&nbsp;Se por algum acaso seu site vier a sofrer um ataque de <a href="https://pt.wikipedia.org/wiki/Inje%C3%A7%C3%A3o_de_SQL">sql injection</a>, o atacante irá ter uma maior dificuldade em descobrir o nome das suas tabelas (lembre que o esquema de tabelas do Wordpress é público e&nbsp;<strong>muito</strong> difundido). Sendo assim, evite o prefixo padrão "wp_" sempre.
Understanding Network things: part 2 – IP address & CIDR
Tags: network, http, beginners, cloud
Published: 2021-06-16 12:40:24

---
title: Understanding Network things: part 2 – IP address & CIDR
published: true
description: Serie of sketchnotes about Network concepts. Explaining in a visual way network principles.
tags: Network, HTTP, beginners, Cloud
series: Understanding network things in sketchnotes
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iu85bec5ce2y9fge6s1k.jpg
---

Hi,
I've got a secret for you, since several years. I'm a developer and I'm a mess in undestanding network things! :'(

It's hard to not understanding things that anyone seems to understand and understanding network concepts can be difficult or time-consuming, specially for developers. That the reason I started to create sketchnotes about Network concepts. I think it could be a good way, more visual, to explain it.

In this second article, we will see IP and CIDR concepts.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iu85bec5ce2y9fge6s1k.jpg)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tvsyeid1ss43xe8dz22.jpg)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tpzssefgs025bzgwm77d.jpg)

As usual, if you like theses sketchnotes, you can follow me, and tell me what do you think. I will publish others sketchs shortly :-).

If you are interested, I already published sketchnotes about [Kubernetes, Docker and Istio](https://gumroad.com/aurelievache).
Code Smell 80 - Nested Try/Catch
Tags: oop, exceptions, tutorial, webdev
Published: 2021-06-16 12:04:17

*Exceptions are a great way of separating happy path versus trouble path. But we tend to over-complicate our solutions.*

> TL;DR: Don't nest Exceptions. Nobody cares of what you do in the inner blocks.

# Problems

- Readability

# Solutions

1. Refactor

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/f180d0e09abe6dc0f637a142c4a5a58b)
```javascript
try {
    transaction.commit();
} catch (e) {
    logerror(e);
    if (e instanceOf DBError){
      try {
          transaction.rollback();
      } catch (e) {
          doMoreLoggingRollbackFailed(e);
      }
    }
}

//Nested Try catchs
//Exception cases are more important than happy path
//We use exceptions as control flow
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/a4fc40e63f2506bf02144c9f71f164a3)
```javascript
try {
    transaction.commit();
} catch (transactionError) {
    this.withTransactionErrorDo(transationError, transaction);
}

//transaction error policy is not defined in this function
//so we don't have repeated code
//code is more readable
//It is up to the transaction and the error to decide what to do
```

# Detection

We can detect this smell using parsing trees.

# Tags

- Exceptions

# Conclusion

Don't abuse exceptions, don't create Exception classes no one will ever catch, and don't be prepared for every case (unless you have a good real scenario with a covering test).

Happy path should always be more important than exception cases.

# Relations

{% post https://dev.to/mcsee/code-smell-73-exceptions-for-expected-cases-504c %}

{% post https://dev.to/mcsee/code-smell-26-exceptions-polluting-pbn %}

# More Info

- [Nested Try/Catchs](https://beginnersbook.com/2013/04/nested-try-catch/)

# Credits

Photo by <a href="https://unsplash.com/@davidclode">David Clode</a> on <a href="https://unsplash.com/s/photos/fishing-net">Unsplash</a>
  
Thanks to @[Rodrigo](@rodrigomd) for his inspiration

{% twitter 1403359513965731843 %}

* * *

> Writing software as if we are the only person that ever has to comprehend it is one of the biggest mistakes and false assumptions that can be made.

_Karolina Szczur_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Classification Applications: Spam Detection
Tags: article
Published: 2021-06-16 15:17:40

---
title: Classification Applications: Spam Detection
published: true
date: 2021-06-16 12:02:23 UTC
tags: Article
canonical_url: https://reinforcement-learning4.fun/2021/06/16/classification-applications-spam-detection/
---

Spam detection is one of the classical applications of classification algorithms.

It simply consists of assigning a received email one of two labels: spam or not spam.

By automatically classifying received emails as spam or not spam, email services provide a cleaner and safer mail Inbox.

The training data is obtained by collecting samples of …

[Continue reading Classification Applications: Spam Detection →](https://reinforcement-learning4.fun/2021/06/16/classification-applications-spam-detection/)
Day 28/30 :  CSS Button Hover Effect | Animated Border using HTML and CSS
Tags: html, css, webdev, tutorial
Published: 2021-06-16 12:01:34

Welcome to Day 28 of this [Challenge](https://dev.to/somanathgoudar/30dayschallenge-30-days-extreme-html-css-challenge-50k1). This is what I created today. 

**➜ Here is the Demo :**
![CSS Button Hover Effect](https://1.bp.blogspot.com/-V8l7rO0501s/YKolUQbJt9I/AAAAAAAAAIw/gXPZ4oBTqV4oGp9DtXaHCYWKLYmn_PQ7QCLcBGAsYHQ/s600/p28.gif)

**➜ Video Tutorial :**

{% youtube AQ30VHSdBEI %}
**➜ Source Code :**
https://www.futurecodersweb.com/2021/06/button-hover-effect-using-html-and-css_0323330805.html


**➜ Instagram Post and Reel for Day 28 :**
[See Post and Reel](https://www.instagram.com/future_coderss/)

------------------------------------------------------------------

Hey, If You don't know what is happening here. Don't Worry, I am doing a crazy challenge 😅. Read More about it from the post below.

{% link https://dev.to/somanathgoudar/30dayschallenge-30-days-extreme-html-css-challenge-50k1 %}

**Support Me :**
👉 Buy me a Coffee: https://www.buymeacoffee.com/somanathgoudar
👉 [Follow Me on Instagram](https://www.instagram.com/somanath_goudar/)
👉 [Follow Future Coders on Instagram](https://www.instagram.com/future_coderss/)
👉 [Subscribe to My Main Channel](https://www.youtube.com/channel/UC_nTrhTr5fnBGjOxnkPUmmA)
👉 [Subscribe to Channel Created for this Challenge](https://www.youtube.com/channel/UCzGSyMOf2jPt1MkNBB3SJ3g)

------------------------------------------------------------------
EF Core Identity field increment 1000 by insert
Tags: ef, upmfaq
Published: 2021-06-16 11:47:14

I had a problem with EF Core with identity field in SQL Server. When saved a register, the id value jumped to 1002, 2003.. and counting..

The solution was disable the IDENTITY_CACHE... 

`ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF`
`GO`
[More information here..](https://social.technet.microsoft.com/wiki/contents/articles/40666.sql-server-2017-identity-cache-feature.aspx)
IP / Phone Number Dox Method
Tags: ip, dox
Published: 2021-06-16 11:46:46

IP / Phone Number Dox Method

HOW TO DOX ANYONE (METHOD 1 - ISP / Phone Number DOX) BY DATALINKLAYER

1. Obtain the victims IP address, this can be through a method as simple as IP grabbing, or you can search databases if you can't manage to IP grab them. Be careful with databases, some are outdated.

2. Go to whatismyipaddress.*com or similar, and enter the victim's IP address.

3. Look for the victim's ISP or Organization.

4. Find the support number to their ISP, and call in. You can either spoof as an inside number to their company, or just use any throwaway phone number. Both methods will be explained below.

--------------------------------------------------------------------------------------------------------------------------------------

INSIDE NUMBER METHOD

1. Spoof your phone number to an internal one in the ISP. These can be found by finding all of their support numbers and choosing one to spoof yourself as. Any spoofer can be used, it won't be easy for them to track you with the amount of calls they receive.

2. Call a DIFFERENT support number than the one you are spoofing.

3. When you speak with a representative say the following (adjust wording to your liking), "Hello, this is Mr. Datalinklayer calling from the chat support department. I was recently helping a customer when I was disconnected with the chat, and I wanted to contact them to make sure they got the needed support. Unfortunately, I only have their IP to go off of, is there any way you could help me locate this customer?"

4. After this if you said it in nice tone, without stuttering or being a squeaker, they will gladly help you. If they don't thank them for their time, hang up and call again in 5 minutes.

5. If they do stay, give them the IP and ask for the associated names, phone numbers, and addresses. If you are convincing enough, you can even find the last 4 digits of their SSN.

6. Thank the employee, don't be rude as this could very well get them fired, then hang up. You now have the info you need.

-----------------------------------------------------------------------------------------------------------------------------------------

THROWAWAY NUMBER METHOD

1. Call the ISP support line, don't use your personal number, just use a random throwaway.

2. Tell them support that you are a private investigator on a cyber crime case (you MUST sound very convincing) and that you need the info to the IP address that you have in order to create a subpoena (pronounced soup-eena)

3. If it doesn't work, hang up, wait 5 minutes, then try again. Eventually you will find a na�ve employee willing to help.

-----------------------------------------------------------------------------------------------------------------------------------------

END NOTES

* YOU CAN ALSO DO THIS WITH A PHONE NUMBER, JUST CALL THE PHONE PROVIDER AND FOLLOW THE SAME STEPS, REPLACING THE IP WITH THE PHONE NUMBER.
* ALTHOUGH THIS IS HARD TO TRACK, DO NOT USE ON ANYONE FAMOUS OR INVOLVED IN GOVERNMENT WORK, IT WON'T END WELL.
HOW TO SLOW "(ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)"
Tags: mysql, database, ubuntu
Published: 2021-06-16 11:45:32


{% link https://dev.to/navidmansuri5155/react-code-development-navid-mansuri-j3m %}

If none of the other answers work for you, and you received this error:

```
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
```

1 Stop Your Server First
```
$ sudo service mysql stop
```

2 Make MySQL service directory.
```
$ sudo mkdir /var/run/mysqld
```

3 Give MySQL permission to work with the created directory.
```
$ sudo chown mysql: /var/run/mysqld
```

4 Start MySQL, without permission and network checking.
```
$ sudo mysqld_safe --skip-grant-tables --skip-networking &
```

5 Log in to your server without any password.
```
$ mysql -u root mysql
or
$ sudo mysql -u root mysql
```
THANKS 😃
Keycloak: REST API for Realm Role
Tags: keycloak, realm, authentication, authorization
Published: 2021-06-16 11:34:52

### Get access token

- Code
  ```bash
  curl \
  -d "client_id=admin-cli" \
  -d "username=admin" \
  -d "password=admin" \
  -d "grant_type=password" \
  "http://localhost:8080/auth/realms/master/protocol/openid-connect/token"
  ```

### Create a Realm Role

- Code
  ```bash
  curl -X POST http://localhost:8080/auth/admin/realms/<realm-id>/roles \
  -H "Authorization: Bearer ${TOKEN}" \
  -H 'Content-Type: application/json' \
  -d '{"name": "<role-name>"}'
  ```

### Get all Realm Roles

- Code
  ```bash
  curl -X GET http://localhost:8080/auth/admin/realms/<realm-id>/roles \
  -H "Authorization: Bearer ${TOKEN}" \
  ```
I made a complex Design System For Figma with 2000+ Components! Also, a Free Version is available.
Tags: showdev, design, html, systems
Published: 2021-06-16 11:34:38

I’m Fredy Andrei, the Founder of Simmmple. Today I’m excited to introduce our new product, Venus Design System, a complex & premium design system tool which comes with more than 2000+ Components states and more than 250+ Global Styles for Figma! ❤️

https://venusdesignsystem.com

The main idea of doing this tool was to help designers & developers reduce hours of time wasted wireframing and building UI projects. Venus Design System will increase cohesion, collaboration, and focus your creativity where it matters!

We realized these ready-to-use components can help you to make a premium project very quickly.

While designing Venus, there were a few things we knew we had to get right:

• Making sure it was easy for anyone, not just designers, but for developers to learn and use
• Connecting Venus with Figma features like Variants, Auto Layout V3.0 & many other cool features (we’re just getting started here!)
• Make Venus as a library of UI components and styles to help you use them & deliver your work faster
• Keep Venus design consistent, accessible and well-documented

For the moment, Venus comes just in Figma Version at $99 for Freelancer license, but we are working and we plan to launch Venus as a React Library to be more useful and to be easier to bring the design to life.

**Try Free Version of Venus:** https://bit.ly/venusdesign-free
**Venus Design System PRO**: https://bit.ly/venusdesign-pro
Keycloak: REST API for new Realm
Tags: keycloak, realm, authorization, authentication
Published: 2021-06-16 11:09:48

### Get access token

- Code
  ```bash
  curl \
  -d "client_id=admin-cli" \
  -d "username=admin" \
  -d "password=admin" \
  -d "grant_type=password" \
  "http://localhost:8080/auth/realms/master/protocol/openid-connect/token"
  ```

### Create realm json file

- Sample
  ```json
  {
    "id": "newrealm",
    "realm": "newrealm",
    "displayName": "New Realm",
    "enabled": true,
    "sslRequired": "external",
    "registrationAllowed": false,
    "loginWithEmailAllowed": true,
    "duplicateEmailsAllowed": false,
    "resetPasswordAllowed": false,
    "editUsernameAllowed": false,
    "bruteForceProtected": true
  }
  ```

### Create realm

- Code
  ```bash
  curl -v POST \
    -H "Authorization: Bearer <access-token>" \
    -H "Content-Type: application/json" \
    -d "@<realm-file>" \ http://localhost:8080/auth/admin/realms
  ```
EASY IOS APPLICATION DEVELOPMENT USING TOP 5 SWIFT 5.4 FEATURES
Tags: swiftforappdevelopment, iosdevelopment, iosappdevelopment
Published: 2021-06-16 11:09:32

This article will take you on the run through the new Swift 5.4 Features to help you during the <a href="https://www.logicrays.com/blog/top-5-swift-5-4-features-to-consider-for-ios-app-development/">iOS App development</a> process and make it easier. These features have been proved very powerful and valuable at the same time. Swift parts feel just like an Apple Pie.

There is a reason why people choose the Apple Gadgets rather than trying other technology because Apple provides durability, exquisite features, user-friendly, extreme security, good resale values, and faster usage. It is like an all in one package that will benefit you in many ways. Well, there is another competitor technology that is here to compete with Apple, i.e. Android. 

Apple is famous because it comes with the latest and the finest usability available in the market. So, a new version of Swift 5.0 came in in March 2019. This new version brought many changes in the process of iOS App development up until now. The process became much easier, and the work just got better and more efficient. People switch their iPhones like they switch Instagram Reels these days. Whenever the new iPhone launches, the sales of the product reach a peak. According to The Verge, there are now over 1.65 billion active iPhone users. 

Today, we will look at some of the most significant changes that came with Swift 5.0 and how it became the best choice for every single iOS app developer in the world. In 2019, when Swift 5.0 came out in the market, its features are all that mattered. This new version led to the development in Swift’s server-side to use it as a back-end language for web services. 

But what is the point of understanding all this? 

If you don’t know why we’re doing this, you need to realise that Swift is way too strong than creating any iOS app. Let’s take a look at the attribute of both.