teleren/devto huggingface dataset:
How to test @Configuration class in Spring Boot
Tags: java, spring, testing, springboot
Published: 2020-05-09 21:29:25

In Spring Boot, if you look at the official documentation, there is a lot of ways to test [things](https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html) and we end up in the [AnnotationMania ©](http://annotatiomania.com/) which is from my point of view, "too magic for me". 

In this article, we will explore an alternative solution which is more readable and simpler to implements.

Like [Josh Long](https://twitter.com/starbuxman?lang=fr) said, everything starts in [start.spring.io](https://start.spring.io/). I've just created a simple project without any dependency.

# @Configuration Class

Then, I have created this kind of configuration class, which is pretty usual in Spring Boot Projects: 

```java
@Configuration
public class ExampleConfiguration {

    @Bean 
    ExampleService exampleService() {
        return new ExampleService();
    }

}
```

# Test the @Configuration Class

I would like to test this class with a very simple configuration. To do that, I choose to use the tooling usually used by libraries in Spring Boot environment. 

So, the test will look like this: 

```java
class ExampleConfigurationTest {

    /*
     * I setup a context runner with the class ExampleConfiguration
     * in it. For that, I use ApplicationContextRunner#withUserConfiguration() 
     * methods to populate the context.
     */
    ApplicationContextRunner context = new ApplicationContextRunner()
            .withUserConfiguration(ExampleConfiguration.class);

    @Test
    public void should_check_presence_of_example_service() {
        /*
         * We start the context and we will be able to trigger
         * assertions in a lambda receiving a
         * AssertableApplicationContext
         */
        context.run(it -> {
            /*
             * I can use assertThat to assert on the context
             * and check if the @Bean configured is present
             * (and unique)
             */
            assertThat(it).hasSingleBean(ExampleService.class);
        });
    }
}
```

With that, you can unit test your `@Configuration` classes without any problem.

Thanks to the [ApplicationContextRunner](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.html) you will be able to do a lot thing to test your code, like: 

* Add Bean to your context
* Load AutoConfiguration classes
* Set properties
* Modify the ClassLoader to remove some class

And with the [AssertableApplicationContext](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/assertj/AssertableApplicationContext.html), you will be able to:

* Check the presence of bean
* Get Bean from the context
* Check if the context has failed

Thanks to that, you will be able to unit-test every `@Configuration` class simply, without complexity 🚀.

You can check out the whole code [here](https://gitlab.com/davinkevin/testing-configuration-class/-/tree/master)
Take the day off
Tags: bash, beginners, azure
Published: 2020-05-09 21:16:04

Sometimes you need to remind yourself that through all of the madness in the world, you can take the day off.  I travel a lot, I meet people, I spend time discussing Azure as a part of my role as a [Cloud Advocate](https://developer.microsoft.com/advocates/jay-gordon?WT.mc_id=blog-devto-jagord).  Since returning from [Microsoft Ignite | The Tour in Copenhagen,](https://www.microsoft.com/ignite-the-tour?WT.mc_id=blog-devto-jagord) I've been in New York City in about a quarter mile space.  Thanks to the work I am able to do, I am thriving by creating blog posts on dev.to, making YouTube videos and helping people learn about technology.  

Doing this all from home is pretty normal for me.  I have been working from my apartment in the Financial District of Manhattan for almost two years.  It's been a joy to be able to spend more time with my pug Rico and see my wife when she returns from work every day.  With that came regular travel.  So being able to break up my time, even thought I worked from home, was manageable.  If I wasn't traveling for work, I was taking short trips to find some time to decompress.  

![Rico and I by the South Street Seaport.](https://tva1.sinaimg.cn/large/007S8ZIlgy1gemw6oujn4j30b40b4t9o.jpg)

Now, the days are a tad harder to break up.  I notice myself working quite a bit.  Not out of demand, but out of the idea that I need to do something.  One of my faults is I do not recognize that I am throwing myself a bit too much into it and not taking a moment to recognize the other parts of life.

So I did myself a favor. [I made a repository](https://github.com/jaydestro/takethedayoff), with a script to remind myself... take the day off.

## Take the day off

There is nothing to do. You have today off.

## Install

[clone this repo](https://github.com/jaydestro/takethedayoff)

```
git clone git@github.com:jaydestro/takethedayoff.git
```

Open a terminal and run

```
cd takethedayoff
sh ./takethedayoff.sh
```

![run the script](https://media.giphy.com/media/Qv4SOcEhn0uIIjvyR4/source.gif)

### Why?

I needed a reminder that sometimes there are days off. Feel free fork, and make it with your own favorite language.  The shell I did this in was the [Azure Cloud Shell.](https://docs.microsoft.com/azure/cloud-shell/overview?WT.mc_id=blog-devto-jagord)  You can get [$200 in credit](https://azure.microsoft.com/free/?WT.mc_id=blog-devto-jagord) and run the script there or in your favorite terminal.

Please let me know about what you do.  How you fork this.  What makes this all easier in times of uncertainty.  Send me a [tweet](https://twitter.com/jaydestro) or leave a comment.  Also don't forget that you [can now register](https://register.build.microsoft.com/?WT.mc_id=blog-devto-jagord) for [Microsoft Build 2020](https://mybuild.microsoft.com/?WT.mc_id=blog-devto-jagord),  an all digital event, for **free**!  Can't wait to see all the amazing presentations!

**Take the day off.**
How to login securely to your AWS EC2 Instance?
Tags: aws, ec2, awscloud
Published: 2020-05-09 21:07:19

Securing the AWS EC2 instance is the first thing you have to think while creating it. This post specifically talks about how to secure SSH/RDP port on your AWS EC2 Instances and how not to open port 22/3389 to the Internet (0.0.0.0/0).

Follow it on https://medium.com/@vijaykodam/how-to-login-securely-to-your-aws-ec2-instance-cc94fff5ebd2
Help needed 🥺
Tags: news, html, help
Published: 2020-05-09 20:29:36

Hello, www.covidtenders.org is a non-profit organisation which aims to secure tenders from government for projects helping to tackle challenges posed by the world pandemic.

❤️ we need your help ❤️

If you can spare up to 3 hours a week to make a difference in the world click [here](https://join.slack.com/t/covidinnovations/shared_invite/zt-dscqlsd0-efAXxIWeXr0e40b2lkVqxQ).

There are various areas where help is needed. Feel free to leave comments post on other platforms 🦄 or just say hello.
Free Exchange rate API
Tags: discuss, webdev
Published: 2020-05-09 20:24:16

Hey guys, right now I'm looking for an API that allows you to convert from one currency to another, this is for a personal project so I'm looking for something free at the moment, I found several APIs that offer a free version but they all limit the number of requests per month, and is usually a very small amount.

Any help would be very appreciated.
Why to use async & await instead of the Promise class?
Tags: javascript, react, angular, codequality
Published: 2020-05-09 20:13:10

<p>In order to answer this question we should first say what are actually promises and what they do.</p>

<h2>What are promises</h2>
<p>Promises are a way to write asynchronous code, which means that a function will return some data in a certain time in the future and the code will continue to execute. For example let's say we want to make a burger because we are hungry. So what we do, we can put the meat on the stove, and in parallel with this we can cut the vegetables. When the meat is ready we remove it from the hot plate and put it in the burger, then we put the vegetables and we are ready. Cooking the meat is the Promise and when it is ready we do something with it, this is what we call asynchronous programming.</p>

<h2>Usage</h2>
<p>Here a simple function that get some data load some data. These are the two ways to do it with the Promise class which has 2 methods .then when the promise has ended and .catch when there is an error.</p>

```javascript
const makeRequest = () => {
    getUserData
        .then(user => {
            console.log(user);
        });
}
```

```javascript
const makeRequest = async () => {
   console.log(await getUserData());
}
```
<p>What we see is that using  <span class="font-italic">async & await</span> we write less code but in this way when there is 1 function it doesn't matter if you use await or promise class. But what will happen if there are 2 or more functions that depend on each other. For example, first we want to get a user and then we want to get all clubs that a user has joined. Here are the 2 implementations.</p>

```javascript
const makeRequest = () => {
    getUserData
        .then(user => {
            getClubsForUser(user.id)
                .then(clubs => {
                    console.log(clubs);
                }).catch(err => {
                console.log(err.message);
            })
        }).catch(err => {
        console.log(err.message);
    })
};
```

```javascript
const makeRequest = async () => {
    try {
        let user = await getUserData();
        let clubs = await getClubsForUser(user.id);
        console.log(clubs);
    }
    catch(err) {
        console.log(err.message);
    }
};
```
<p>When looking at the first example it gives you a headache. It’s easy to get lost in that nesting, braces.
You can see in the second example that the code with <span class="font-italic">async & await</span> is more clean and easy to read. And also what we deal with is the callback hell.  <span class="font-italic">Async & await</span> is a syntactical sugar for writing asynchronous code. It makes the code look and behave a little more like synchronous code but it remains to be asynchronous.</p>

<h2>Conclusion</h2>
<p>Some people may say that using  <span class="font-italic">async & await</span> can make the asynchronous code less obvious. But C# had this feature for years and people who are familiar with it know it’s worth this minor, temporary inconvenience.<p>
How to build Enterprise Architecture for your next project?
Tags: architecture, csharp, design, dotnet
Published: 2020-05-09 20:02:14

Last a few weeks, I was thinking how can I build an enterprise architecture for my project so I searched a lot about it. There are many ways you can structure your app in effective way. You might have heard about All-in-one architecture, N-Layer Architecture, Microservices and so on. All of them are good in a certain situation but the architecture that I liked most is Clean Architecture. This pattern is proposed by Uncle Bob in his book as a way of building flexible and maintainable software solutions. So I decided to use and extend this template. The solution template consists of 5 layers. I will show you a C# implementation for ASP Net Core applications. You can find a link to the source code at the bottom of the page.


Core Layer
The Application Core holds the business model, which includes entities, services, and interfaces. These interfaces include abstractions for operations that will be performed using Infrastructure, such as data access, file system access, network calls, etc. Sometimes services or interfaces defined at this layer will need to work with non-entity types that have no dependencies on UI or Infrastructure. These can be defined as simple Data Transfer Objects (DTOs).

Infrastructure Layer
It typically includes data access implementations. In a typical ASP.NET Core web application, these implementations include the Entity Framework (EF) DbContext, any EF Core Migration objects that have been defined, and data access implementation classes. The most common way to abstract data access implementation code is through the use of the Repository design pattern.

Web Layer
The web layer in an ASP.NET Core MVC application is the entry point for the application. This project should reference the Application Core project, and it's types should interact with Infrastructure strictly through interfaces defined in Application Core. No direct instantiation of or static calls to the Infrastructure layer types should be allowed in this layer.

Tests Layer
This layer is for testing. Here you can test all others layers by writing both Unit Tests and Integrational tests. In this way you guarantee that your project has lower chance of bugs.

Common Layer
This layer is for global constants or files that are used in others layers.

If you want to see the source code of the template you can find it here: {% github Svetloslav15/ASP.NetCore-Template %} If you like it, please consider giving me a star. Thank you!
Inline codes inside XAML with XAMARIN
Tags: xamarin, xaml
Published: 2020-05-09 19:58:21

![https://raw.githubusercontent.com/jaysonragasa/jaraimages/master/EvaluateCodeInXAML/2020-05-09_1825.png](https://raw.githubusercontent.com/jaysonragasa/jaraimages/master/EvaluateCodeInXAML/2020-05-09_1825.png)

## Basic Information
I couldn't think of any best example of this one so above is a little example how you can execute/evaluate a code inside the XAML file. 
  
There are three things happening here  
1. The placeholder hides when there's an image.
2. The placeholder shows when there is no image.
3. It shows a portion of the item name inside the placeholder.
  
I know, I know. Coverters can easily do this. You just have to create a Converter for hiding a part of an element and a Converter for taking part of the string... but this is a code inside the XAML and one great thing with this one is for example in Hot Reload, you will be able to see the changes. Imagine the flexibility of having an inline code inside the XAML.
  
So if you notice, I am only using one converter `eval` which executes my code.
  
**Here's GIF preview**
  
![https://raw.githubusercontent.com/jaysonragasa/jaraimages/master/EvaluateCodeInXAML/05-07-2020-15-01-59.gif](https://raw.githubusercontent.com/jaysonragasa/jaraimages/master/EvaluateCodeInXAML/05-07-2020-15-01-59.gif)
  
  
## History
This is made possible by [Interpreter](https://github.com/jaysonragasa/Interpreter) made by [HiSystems](https://github.com/hisystems) way back 2013. The development was stopped last 2015 and I think this is a good addition to Xamarin platform, WPF, or UWP.
  
I extended the Interpreter a bit to support some additional functions. Check [README](https://github.com/jaysonragasa/Interpreter/blob/master/readme.md)
  
## So why Converter?
I was trying to implement this with Attached Attribute to somehow make it a bit interesting but I want this to run in any attributes in element.
  
I also tried using Markup Extension but it's just not possible since the source path could be in any name and it is important to know the source and getting the source value is even harder.
  
So the Converter is much easier to implement. It can be implemented in any attributes and you can easily get the actual value from the source.
  
Here's our converter
```csharp
public class Convert_Interpret : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;

        if (!string.IsNullOrEmpty((string)value))
        {
            string p = (string)parameter;
            p = p.Trim();

            var e = ((App)Application.Current).Interpret;
            var xp = e.Parse(p);
            xp.Variables["x"].Value = new Text((string)value);
            return xp.Execute();
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}
```
  
Added this line in App.xaml.cs
```csharp
public Engine Interpret = new Engine();
```
Object.entries()
Tags: beginners, javascript, codenewbie
Published: 2020-05-09 19:47:00

Object.entries() is used for listing all key-value pairs in an object. It accepts an object as a argument, and returns an array enumerating the key-value pairs of an object.

```javascript
const obj = { 
  1: 'Israel', 
  2: 'Temi', 
  3: 'Miro' 
};
console.log(Object.entries(obj))

//Expected result: [ ["1", "Israel"], ["2", "Temi"], ["3", "Ayo"]]
```

Another example:
```javascript
const obj1 = {
  a: 'Hello',
  b: 28
};

for (let [key, value] of Object.entries(obj1)) {
  console.log(`${key}: ${value}`);
}

//Expected result: 
// "a: Hello"
// "b: 28"
```


If the argument passed is not an object, it causes TypeError,
If the key passed in the argument is not in the range of the property[key, value] pair, it causes RangeError.
Dual Boot Ubuntu 20.04 on a 2017 MacBook? My Attempt.
Tags: ubuntu, linux, macos, installation
Published: 2020-05-09 19:41:43

---
title: Dual Boot Ubuntu 20.04 on a 2017 MacBook? My Attempt.
published: true
description: My attempt at installing Ubuntu 20.04 on my MacBook. Result: Fail.
tags: Ubuntu, Linux, macOS, installation
---
I love my MacBook and I love trying new things. Among all the major desktop GUIs out there: Windows, macOS, and Linux, I like Linux the best. I tried to install Ubuntu before on my 2015 MacBook Pro a couple of years back. It had some issues and I ended up uninstalling it. With Ubuntu 20.04, I decided to give it another shot and tried to dual boot Ubuntu with macOS on my 2017 MacBook.

So last night, I backed up my MacBook using Time Machine. This morning, I was so excited to do the installation that I got up at 6:30 to install Ubuntu 20.04 along side macOS. I had to delete the local Time Machine snapshots before partitioning the drive using Disk Utility. After that, the installation went well mainly because I followed a [YouTube tutorial](https://www.youtube.com/watch?v=kRgKlcm1XPI).

After the install, I logged into Ubuntu. The first thing I noticed is my trackpad didn’t work. I searched online and found three command lines I needed to run then it got fixed. I struggled for a couple of hours trying to get the speakers to work. The headphone works but not the laptop speakers. In the end, I couldn’t find the solution. Around 1 pm, I called it quits and deleted the partitions I created this morning and deleted the ubuntu grub folder so everything is back to where I started.

My conclusion is that Linux and MacBooks don't play well. To me, Apple makes great looking laptops and I want a great customizable OS to go with it. In my opinion, that's Linux. I know Linux has less trouble working with Windows machines and I like the new Dell XPS 13 Developer Edition that has Ubuntu baked in. But that's another $1000+ I don't want to spend right now. I just wish Linux worked better on Macs.

Anyone with similar thoughts?
My Coding "Why"
Tags: codenewbie, beginners
Published: 2020-05-09 19:32:32

Ever since the tender age of five, my dream was to become a teacher, assign homework and bake cookies for my students.

I’m here to tell, you I did just that!

For a decade, this was the challenging and often syrupy sweet job I’d always wanted. Until it wasn’t.

Even though it felt like I was throwing away a perfectly good career, I wanted to keep learning: health coach, shoe salesperson, personal trainer, and mama.

Then in 2018, I was hired to work for an ed-tech company in New York City. This, my dear readers, ignited the spark. I got to see software engineers and developers in action, and the results were magical. I was officially intrigued.

Compared to guiding customers on how to fill out their tax form, I wanted to be the one to advise on that line of code that could transform a page.

I first dabbled in HTML and CSS on freeCodeCamp, which proved my interest was real. Knowing I’d need the accountability as well as curricular guidance, I applied to Flatiron and a week later was accepted.

Six months of coding, sweating, and building the most supportive community, I graduated as a Software Engineer with a new lease on life.

I learned that I could learn anything (you CAN teach an old dog new tricks!) and that has opened up my world.

With a solid foundation in Ruby and JavaScript and beautiful frameworks, I’m embarking upon the next segment of this journey. Coding, learning, growing. Looking forward to any and all opportunities to do so!

If you made it all the way to the bottom, thanks so much for reading. I’d love to hear what brought you here - get in touch any time.
TIL record keeping
Tags: opensource, todayilearned, github
Published: 2020-05-09 19:20:51

Getting inspired from TIL repo of [jbranchaud](https://github.com/jbranchaud), I have started my own [TIL](https://github.com/jayeshathila/til) repo. Hashtag `TIL` seems to have awesome content for me to cover and get started.

I feel most of us have one or the other way to keep record of our learnings, would love to know how do you maintain it.
A Python binding for the web monetization Javascript API
Tags: gftwhackathon
Published: 2020-05-09 19:06:52

For this hackathon, I'm thinking of building a python binding for the web monetization API. Here's what I have in mind:

According to the [docs](https://webmonetization.org/docs/api), if you want to check if a user is web monetized, you check the state using:

```js
document.monetization.state
```

You would then proceed to implement your logic based on the state.

As a backend python developer, it would be cool if I could do that in python. If I'm using Flask for example, and I have a monetized route, I would want to write something like:

```py
from monetize import check_state

@app.route('/monetized')
def monetized_page():
    state = check_state()
    if state == 'started':
        # implement logic to offer monetized content
    else:
        # do something else
```

This is a simple example but that's the general idea - to have all the methods exposed by the js API in python. Javascript would of course still be working behind the scenes once this gets to the browser.

I believe something like this would make it easier to implement the monetization API for python developers working with web frameworks like flask and django.