Testing a Spring Profile Bean

We have seen in a previous post how to use the Spring Profile annotation to let the framework select which Bean to load at runtime. Let's see now how to test this behavior with JUnit.

Say that for some peculiar reason, my Web Application needs to have different beans in different environments. To address this delicate matter, we can create a Spring Configuration class that autowires objects implementing classes in the same hierarchy using a specific factory method.

For instance, here is how I could let Spring know that I want to create CharSequence Beans in an application:
@Configuration
public class CharSeqConfig {
    @Bean
    @Profile("dev")
    public CharSequence myString() {
        return new String("String");
    }

    @Bean
    @Profile("prod")
    public CharSequence myStringBuilder() {
        StringBuilder sb = new StringBuilder();
        sb.append("StringBuilder");
        return sb;
    }
}
When the "dev" profile is specified, Spring will use the myString() method when asked to wire a CharSequence bean. When in "prod", myStringBuilder() will be selected instead.

Testing this code with JUnit it is not much more complicated than the usual job we have already seen, basically, we have to specify which profile we want check using the ActiveProfiles annotation. However, usually we want to keep together the same tests for different profiles, and the nice thing is that we can easily do it, using static classes:
public class CharSeqConfigTest {
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=CharSeqConfig.class)
    @ActiveProfiles("dev")
    public static class DevCharSeqTest {
        @Autowired
        private CharSequence charSeq;
        
        @Test
        public void testCharSeq() {
          assertThat(charSeq.toString(), is("String"));
        }
    }

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=CharSeqConfig.class)
    @ActiveProfiles("prod")
    public static class ProdCharSeqTest {
        @Autowired
        private CharSequence charSeq;
        
        @Test
        public void testCharSeq() {
          assertThat(charSeq.toString(), is("StringBuilder"));
        }
    }
}
A minor nuisance is that we have to tell to STS which family of tests we want to run with JUnit:
However it pays off well.
Having seen the green light for both the profiles, I have pushed the code on GitHub, both for the configuration class and the JUnit test case.

I have written this post while reading the third chapter, Advanced wiring, of Spring in Action, Fourth Edition by Craig Walls. I ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration. I have also done a few minor changes to keep the post as slim and readable as possible. Here I have used CharSequence as root for my bean hierarchy instead of DataSource. In this way my example code makes less sense, but it give some immediate satisfaction.

Go to the full post

CodeEval Panacea - truth or lie

Given the string representation of two lists of numbers, the first ones in hexadecimal format, the latter in binary, return True if and only if the sum of the first ones is strictly less then the sum of the second ones.
This is the CodeEval problem #237, and here I give my Python 3 solution.

The sample provided could be easily converted in these python test cases:
def test_provided_1(self):
    self.assertTrue(solution('64 6e 78 | 100101100 11110'))

def test_provided_2(self):
    self.assertTrue(solution('5e 7d 59 | 1101100 10010101 1100111'))

def test_provided_3(self):
    self.assertFalse(solution('93 75 | 1000111 1011010 1100010'))
After splitting the input line, we just have to use the built-in function int(), passing as second parameter the expected base:
hexes = [int(x, 16) for x in data[0].split()]
bins = [int(x, 2 ) for x in data[1].split()]
And then it is just a matter of comparing the sum() of the two lists:
return sum(hexes) <= sum(bins)
I have pushed the test case and the python script to GitHub.

Go to the full post

CodeEval Simple or trump

Given in input a representation of two cards and the current trump, return the highest one, or both if they have the same value.
This is the CodeEval problem #235 and here I am giving a Python 3 solution.

Cards are represented by their value, a number or the first letter in case of Jack, Queen, King, Ace, and the suit (Clubs, Diamonds, Hearts, Spades) initial. I have converted the sample provided in python test cases:
def test_provided_1(self):
    self.assertEqual('2H', solution('AD 2H | H'))

def test_provided_2(self):
    self.assertEqual('KD KH', solution('KD KH | C'))

def test_provided_3(self):
    self.assertEqual('JH', solution('JH 10S | C'))
The problem is so easy that I went for the fastest solution jumped to my mind, without caring much of anything possibly more refined.
Splitting the input line I get the facial description of the card, for instance KD for the King of Diamonds, and the current trump, as C for Club.

Then I wrote a puny, unsophisticated function that takes in input as a two-element list the cards, and the trump. I trivially converted the values in integers and then used the trump as a x10 multiplier. The idea is that even the lowest value card, a deuce (2), when is a trump has a value higher than the highest non-trump card.
def values(cards, trump):
    result = [0, 0]
    for i in [0, 1]:
        suit = cards[i][-1] # 1
        value = cards[i][:-1] # 2
        if value == 'J':
            result[i] = 11
        elif value == 'Q':
            result[i] = 12
        elif value == 'K':
            result[i] = 13
        elif value == 'A':
            result[i] = 14
        else:
            result[i] = int(value)

        if suit == trump:
            result[i] *= 10
    return result
1. Suit is the last character in the card description.
2. Value is the card description stripped of its last character.

Finally, it is just a matter of returning the face description of the highest card, or both, if they have the same value.

CodeEval accepted this solution, and I pushed test cases and python script.

Go to the full post

Filtering apples with Predicate and lambdas

We have to write a apple filtering Java method that, given in input a string describing a list of apples, preceded by a flag that tell us how to filter them, gives as output the filtered apples.

Even if just two ways of filtering have to be implemented, we should design a solution that could be easily extended to support many unforeseen other filters.

Here is a few test cases that I have written to better explain the problem.
@Test
public void testSolutionByColor() {
    assertThat(AppleFilter.solution("color:80 green|155 green|120 red"), is("80 green|155 green"));
}

@Test
public void testSolutionByMissingColor() {
    assertThat(AppleFilter.solution("color:80 blue|155 yellow|120 red").length(), is(0));
}

@Test
public void testSolutionByWeight() {
    assertThat(AppleFilter.solution("weight:80 green|155 green|120 red"), is("155 green"));
}
Each apple is represented by its color and weight, blank separated. A pipe is used as separator between apples. There are just two filtering way currently, color, that let's us select just the green apples, and weight, that select only the apples heavier than 150.

The point of this exercise is in using a few Java 8 features, namely the Predicate functional interface and lambda functions.

The core of the algorithm is this filter method:
private static List<Apple> filter(List<Apple> apples, Predicate<Apple> p) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : apples) {
        if (p.test(apple)) {
            result.add(apple);
        }
    }
    return result;
}
Given a list of apples and a predicate on apples, each apple in the list is tested against the predicate. If the test is passed, the apple is added to a new list that is returned by the method.

Here is how I decide which predicate to use, given that data[0] is a String containing the selector as extracted from the input parameter.
Predicate<Apple> p = data[0].equals("color") ?
    (Apple a) -> a.color.equals("green") :
    (Apple a) -> a.weight > 150;
I store in the predicate p a lambda function that has as input an apple and return a boolean, accordingly to the kind of filtering I want to perform. Here I assume only two kind filtering could be performed, however is easy to extend, and make more robust, this piece of code.

The rest of the code I have written is all about converting raw data to objects and back from objects to a string formatted as required by the user. There is some interesting stuff there, too.

I used the String split() method to split the input string. Nothing much to say on it when the separator is a colon or a blank, however we should remember that it is a regular expression, so we have to pay attention to correctly escape it when a special character, like a pipe, is passed it. So, to split the list of apples I write:
data[1].split("\\|")
For the other way round, I used the static String join() method, that joins an iterable on a give character sequence. There is a caveat here, too. The iterable has to be a generic based on CharSequence, quite a nuisance. Libraries as Guava and Apache Commons provide smarter functions, however, if we want to keep our code free from third-party code, we need to use some workaround, like:
List<Apple> selected = filter(apples, p);
List<String> result = new ArrayList<>(selected.size());
for (Apple a : selected) {
    result.add(a.toString());
}
return String.join("|", result);

I have conceived this problem as a way to work with the information provided by the authors when reading Java 8 in action, chapter one. If you have this book at hand, you are going to find in section 1.2 Functions in Java code very similar to the one I used above.

I have create a repository on GitHub where I plan to push all the code I write related to this book. You can see the code above in the Java source AppleFilter class and in the JUnit AppleFilterTest.

Go to the full post

CodeEval Suggest Groups

Given in input a number of strings where each of them represent an user, her/his friends and groups, generate a sorted list of suggestions (both by user and group name) for other groups a user could be interested to join, assuming that if a group is followed by half of his friends or more, it could be a good choice.
More details on this problem on its page on CodeEval #165.

Here is the provided sample, as I converted it to a Python test case:
def test_provided_1(self):
    data = 'Amira:Isaura,Lizzie,Madalyn,Margarito,Shakira,Un:Driving,Mineral collecting\n' \
            'Elliot:Isaura,Madalyn,Margarito,Shakira:Juggling,Mineral collecting\n' \
            'Isaura:Amira,Elliot,Lizzie,Margarito,Verla,Wilford:Juggling\n' \
            'Lizzie:Amira,Isaura,Verla:Driving,Mineral collecting,Rugby\n' \
            'Madalyn:Amira,Elliot,Margarito,Verla:Driving,Mineral collecting,Rugby\n' \
            'Margarito:Amira,Elliot,Isaura,Madalyn,Un,Verla:Mineral collecting\n' \
            'Shakira:Amira,Elliot,Verla,Wilford:Mineral collecting\n' \
            'Un:Amira,Margarito,Wilford:\n' \
            'Verla:Isaura,Lizzie,Madalyn,Margarito,Shakira:Driving,Juggling,Mineral collecting\n' \
            'Wilford:Isaura,Shakira,Un:Driving\n'
    output = 'Isaura:Driving,Mineral collecting\n' \
            'Lizzie:Juggling\n' \
            'Madalyn:Juggling\n' \
            'Margarito:Driving,Juggling\n' \
            'Shakira:Driving,Juggling\n' \
            'Un:Driving,Mineral collecting\n'
    self.assertEqual(output, solution(data))

I have split my solution in three parts. Firstly I parse the data in input to a couple of collection to easily manage them. The I actually look for the solution, and finally I prepare the output.

Get the input

I can keep the first two fields in each input string in a list, it is enough to manage the relation between each user and his associated friends. However, I'd better move the third field, in a different collection. For ease of access, and performance, I decided to put them in a dictionary, keeping the relation with the relative user.
def solution(data):
    users = [row.split(':') for row in data.rstrip().split('\n')] # 1
    u_groups = {} # 2
    for user in users:
        for i in [1, 2]: # 3
            user[i] = user[i].split(',') if user[i] else []
        u_groups[user[0]] = user.pop() # 4
1. The input parameter data contains all the lines in the file. I remove the last newline with a call to rstrip() to avoid a final empty record, then I split on newline. Again another split, on colon this time, so the result will be a list of list of strings.
2. In the dictionary u_groups I am going to put each user -> groups.
3: The first element in each line is the user name, no need to more processing on it. The other two elements need another split, on comma this time, to convert them from plain string to list of friends and groups respectively. Notice that it is possible for a user to have no friends or no groups, this should lead to an empty list.
4. I have formatted as expected the groups in the users list, now I pop it to the dictionary defined in (2)

The real job

In users we have, for each user, his name and his friends. In u_groups his groups. Let's put in the dictionary suggestions for each user which groups we think could be interesting for him.
suggestions = {}
for user in users:
    candidates = {} # 1
    for friend in user[1]:
        for group in u_groups[friend]:
            candidates[group] = candidates.setdefault(group, 0) + 1
    for group in candidates: # 2
        if group not in u_groups[user[0]] and candidates[group] >= len(user[1]) / 2:
            suggestions.setdefault(user[0], []).append(group)
1. I'm simply looping on all the friend for the current user, pushing the associated groups to this dictionary.
2. For each group that I found, I check if it is worthy as suggestion. It should not be already a group for the current user, and it should be quite popular in his circle.

To avoid the nuisance of checking if an item is in the dictionary, and then inserting it as new or modify its value, I used the more compact setdefault() method that return the value, if exists, or creatd the key inserting a specified value.

Formatting for output

Basically, I already have the output. I only have to convert it from the suggestions dictionary to a string in the expected format.
result = ['%s:%s' % (u, ','.join(sorted(suggestions[u]))) for u in sorted(suggestions.keys())]
return '\n'.join(result) + '\n'
In the list comprehension I loop on the sorted dictionary keys() then, for each user I put in the list a string that comes out from formatting as strings separated by colon the user name and all the sorted suggestions.
Finally, it is just a matter of putting a bunch of newlines where needed.

After getting the OK from CodeEval, I pushed test case and python script to GitHub.

Go to the full post

CodeEval Not So Clever

Implement a silly sorting algorithm that scans an array of integers for the first element out of order, swaps it with its neighbor, and start again from beginning. Given in input a starting sequence and the number of steps we should apply, give back the resulting output.
This is CodeEval problem #232, and here I giving a Python 3 solution to it.

The given samples, here converted in python test cases, give a better idea of what we should implement:
def test_provided_1(self):
    self.assertEqual('3 4 2 1', solution('4 3 2 1 | 1'))

def test_provided_2(self):
    self.assertEqual('4 3 5 2 1', solution('5 4 3 2 1 | 2'))

Once split the input line to get a list of int, data, and the number of iterations to be applyed to them, steps, the code to write is pretty strighforward:
for i in range(steps):
    for j in range(1, len(data)):
        if data[j] < data[j-1]:
            data[j-1], data[j] = data[j], data[j-1]
            break
return ' '.join(str(c) for c in data)
The internal for loop represents the sorting implementation. Notice how the full scan of the list is performed each time. When is detected an element out of order, a swap is performed, in a very pythonic way, and the next iteration starts.

The full sort takes Big-Oh n squared time, however CodeEval can't complain about this solution, and gives full marks to it. I pushed test cases and python script to GitHub.

Go to the full post

CodeEval Football

We have in input a string that represents a map between countries and the most liked football team in there. Both countries and teams are represented by numbers, the first ones implicitly, by their position, that we should assume 1-based. Our job is to reverse the presentation, giving in output a string in which teams are the keys and countries the values. Both should be sorted in natural order (as numbers, not strings).
Having chosen to use Python 3 as implementation language, this CodeEval problem #230 asks for working with a dictionary.

Let's have a look at the test cases. I found that the ordering requirement was not clarified enough in the provided samples, so I added one test case more:
def test_provided_1(self):
    self.assertEqual('1:1,2,3; 2:1; 3:1,2; 4:1,3;', solution('1 2 3 4 | 3 1 | 4 1'))

def test_provided_2(self):
    self.assertEqual('11:1; 19:1,2; 21:2; 23:2; 29:3; 31:3; 39:3;', solution('19 11 | 19 21 23 | 31 39 29'))

def test_key_numbers(self):
    self.assertEqual('1:1,2,3; 2:2; 4:3; 10:1;', solution('1 10 | 2 1 | 4 1'))
We see how the input line is formatted, and how we have to format the output. The third test case shows that the team "10" has to be placed in the output after the team "4", being number 4 less than 10, and not between "1" and "2" as the sorting in lexicographical order would do.

I divided my solution in two steps.

Dictionary transposition

I have in input a dictionary that maps each country in a list of team, I want to get a dictionary team to countries. Let's build it:
def solution(line):
    teams = {}
    for country, clubs in enumerate(line.split(' | '), start=1): # 1
        for team in map(int, clubs.split()): # 2
            teams.setdefault(team, []).append(str(country)) # 3

# ...
1) The input gives me the country number only implicitly, I make it explicit by using the built-in python function enumerate() that returns a tuple containing a count (that I force to be 1-based by the parameter start) and a value from the passed iterable. As iterable I have passed to enumerate() the input string, as resulting from splitting it on ' | ', that's it, a list of strings containing a space separated string representing the most cheered teams (I called them "clubs" to avoid name clashes) in that country.
2) I split the clubs string, I convert on the fly, by map(), each resulting value to an integer, and I loop on them.
3) Finally, push a value, stored in country, to the teams dictionary for the key stored in club. However, I should be careful not to append the value on nothing. Meaning I need to explicitly consider the case the current team is not already in the dictionary. This is done by a call to setdefault(), that returns the value associated to the passed key if it exists, otherwise create a new entry for it, with the other parameter as its value (by default None, I have astutely passed an empty list instead).

Formatting the dictionary

I have the data in the teams dictionary, I just need to create a string out of it, respecting the required format. I did it in this way:
result = ["{}:{};".format(key, ",".join(teams[key])) for key in sorted(teams.keys())]
return ' '.join(result)
To keep the code compact, I did large part of the job in a list comprehension, and then I simply joined each element on a blank string. But let's how I built up the list.

Firstly, look to the right. I have got the keys() from the teams dict, I sorted them, as required - notice that in (2) above I converted them to integers, so the order is the expected one - and I loop on them.
Now on the left. Each element in the list is a string in the format "{}:{};" where the curly brackets are parameters received from the for loop on the right. The first parameter is easy, just the key as retrieved from the dictionary, namely a team number. The second one in a string generated by joining on a comma the value associated to the key on the dictionary. That is the list of countries for the given team.

As a minor point, there is no need to sort the countries, since we have pushed them in the map respecting the order given implicitly in input.

Solution accepted by CodeEval, code pushed to GitHub, both test cases and python script.

Go to the full post

CodeEval Filename Pattern

As input we get a string containing blank separated tokens. The first one is a pattern, the other ones have to be checked against it. Return the matching tokens, or a minus if no matching is found.
This is CodeEval problem #169 and I am going to show how I have written a Python 3 solution for it.

Firstly, I have converted the given samples to test cases:
def test_provided_1(self):
    self.assertEqual('bh1770.h', solution('*7* johab.py gen_probe.ko palmtx.h macpath.py tzp dm-dirty-log.h bh1770.h pktloc faillog.8.gz zconf.gperf'))

def test_provided_2(self):
    self.assertEqual('IBM1008_420.so', solution('*[0123456789]*[auoei]* IBM1008_420.so zfgrep limits.conf.5.gz tc.h ilogb.3.gz limits.conf CyrAsia-TerminusBold28x14.psf.gz nf_conntrack_sip.ko DistUpgradeViewNonInteractive.pyc NFKDQC'))

def test_provided_3(self):
    self.assertEqual('menu_no_no.utf-8.vim', solution('*.??? max_user_watches arptables.h net_namespace Kannada.pl menu_no_no.utf-8.vim shtags.1 unistd_32_ia32.h gettext-tools.mo ntpdate.md5sums linkat.2.gz'))

def test_provided_4(self):
    self.assertEqual('-', solution('*.pdf OldItali.pl term.log plymouth-upstart-bridge rand.so libipw.ko jisfreq.pyc impedance-analyzer xmon.h 1.5.0.3.txt bank'))

def test_provided_5(self):
    self.assertEqual('groff-base.conffiles', solution('g*.* 56b8a0b6.0 sl.vim digctl.h groff-base.conffiles python-software-properties.md5sums CountryInformation.py use_zero_page session-noninteractive d2i_RSAPublicKey.3ssl.gz container-detect.log.4.gz'))

def test_provided_6(self):
    self.assertEqual('46b2fd3b.0 libip6t_frag.so', solution('*[0123456789]* keyboard.h machinecheck 46b2fd3b.0 libip6t_frag.so timer_defs.h nano-menu.xpm NI vim-keys.conf setjmp.h memcg'))
Then I noticed the regular expression grammar is close with the one used in many programming languages, Python included. With a few slight differences.

A dot ('.') in the pattern means just a dot.
A question mark ('?') means a single character whichever, what we use to represent with a dot.
A star ('*') means any number of any characters, without the need of a dot before it.

And, there is one more change that is not given in the problem description but it is caught by the third test case.

The pattern should cover the entire string. So, for instance "*.???" means that a matching string starts with whatever and ends with three unspecified characters after a dot. So basically, it is like the behavior of the python re match() function when is passed a dollar sign ('$') at the end of the string.

Given the changes are so tiny, it doesn't make sense to create a custom regex engine, a much more effective solution is adapting the input pattern so that it obeys to the rules of the standard python regular expressions. So, I have written this function:
def adjust(pattern):
    return re.sub('\*', '.*', re.sub('\?', '.', re.sub('\.', '\.', pattern))) + '$'
Three calls to substitute the characters as expected by python, and then add a dollar at the end of the string.
The more internal call to sub() replace each non-escaped dots to escaped ones. Then each plain question marks become plain dots. And finally each plain stars become the couple dot-star.

Applying this adjustment, the solution is just a matter of regular expression matching:
def solution(line):
    data = line.split()
    pattern = adjust(data.pop(0)) # 1
    result = [name for name in data if re.match(pattern, name)]
    return ' '.join(result) if result else '-'
I used a list comprehension to filter the names in data to keep just the ones that matches the pattern.

This solution has been accepted by CodeEval, and I have pushed test cases and python script to GitHub.

Go to the full post

Testing Spring autowiring in a more complex scenario

Let's improve the code seen in the previous Spring post. I add a CD player components that implements a media player interface and it is autowired to the CD component.

The media player interface has just a couple of methods
public interface MediaPlayer {
    String play();
    boolean hasMedia();
}
The second one checks if a media is inserted in the player and, you have probably guessed, it's there just to let me check if the autowiring of a CD is done as expected.

Then I have written a CD player, implementing this interface
@Component
public class CDPlayer implements MediaPlayer {
    private CompactDisc cd;

    @Autowired
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
    }

    // ...
}
Notice that this class is annotated as Spring component, and its constructor is autowired. So we expect the framework will look for a suitable component in the CompactDisc hierarchy and wire it to the ctor parameter.

To have the wiring working we need to configure properly the component scan class, so I modify it in this way:
@Configuration
@ComponentScan(basePackageClasses = { CompactDisc.class, MediaPlayer.class })
public class CDPlayerConfig {
}
To test it, I have change the CDPlayerTest to use just a MediaPlayer.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private MediaPlayer player;

    @Test
    public void testPlayerNotNull() {
        assertNotNull(player);
    }

    @Test
    public void testCDInserted() {
        assertTrue(player.hasMedia());
    }

    @Test
    public void testPlay() {
        assertEquals("Sgt. Pepper's Lonely Hearts Club Band by The Beatles", player.play());
    }
}
JUnit, using the Spring class runner, let the framework to do all the required wiring, in the app source code, and also here in the test. I ran it, and I was happy to get full green light.

I have written this post while reading the second chapter, Wiring beans, of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration.
I have also done a few minor changes to keep the post as slim and readable as possible. For instance I removed the references to the brilliant System Rule library by Stefan Birkner & Marc Philipp.

Full code on github.
Have a look at the soundsystem package and the test file.

Go to the full post

CodeEval Testing

We have a string in input representing two versions of a text, separated by " | ", that we have to check for changes. If there is no difference, we return 'Done', otherwise a growing alert message. More detail on the CodeEval page for problem #225. Here I present my Python 3 solution.

This is the tests I have extracted from the given samples.
def test_provided_1(self):
    self.assertEqual('Low', solution('Heelo Codevval | Hello Codeeval'))

def test_provided_2(self):
    self.assertEqual('Critical', solution('hELLO cODEEVAL | Hello Codeeval'))

def test_provided_3(self):
    self.assertEqual('Done', solution('Hello Codeeval | Hello Codeeval'))
Notice that the two versions have the same length, and that the error checking is case sensitive.

After splitting the input line on ' | ' I simply count the bugs comparing the elements in the same position for the two components in the list:
bugs = 0
for i in range(len(data[0])):
    if data[0][i] != data[1][i]:
        bugs += 1
Then it is just a matter of swithing on the bugs and returning an appropriated message. However, for some obscure reason, Python does not have a switch statement. So the better I could think of, was a if/elif/else structure:
if bugs == 0:
    return 'Done'
elif bugs < 3:
    return 'Low'
elif bugs < 5:
    return 'Medium'
elif bugs < 7:
    return 'High'
else:
    return 'Critical'
That's it. Submitted to CodeEval, than pushed to GitHub, both test case and python script.

Go to the full post

CodeEval Real fake

Given in input a string representing a credit card number, four groups of four digits, separated by a blank, return "Real" or "Fake" accordingly to the checksum. Adding all ciphers together, multiplying by two the ones in even position, should give a multiple of ten.
This is the CodeEval problem #227 and I have solved it using Python 3 as implementation language.

Here is how I converted the samples in test cases:
def test_provided_1(self):
    self.assertEqual('Fake', solution('9999 9999 9999 9999'))

def test_provided_2(self):
    self.assertEqual('Real', solution('9999 9999 9999 9993'))

The solution, even though it is pretty short, could be logically divided in three parts.

Extracting data from the provided string
numbers = [int(i) for i in line if i.isdigit()]
I used a list comprehension to convert the input string in a list of integer. For each character in the line I check if it is a digit. If so, I convert it to integer and then I append it to the list.

Calculate the checksum
result = 0
for i in range(len(numbers)):
    result += numbers[i] if i%2 else numbers[i] * 2
I applied the rule. Looping on all numbers, add to the result the current value if it is in odd position, or its square value otherwise.

Return the result
return 'Fake' if result % 10 else 'Real'
It is natural for me using here a conditional expression, given my background as C programmer where a ternary operator (?:) would have done the job.
If the division by ten gives a remainder, aka result modulo ten is not zero, we have a fake credit card, otherwise the checksum is passed.

Solution accepted by CodeEval, so I pushed test case and python script to GitHub.

Go to the full post

CodeEval Black card

Given in input a string containing a list of blank separated names, a pipe, and "black spot" number, eliminate one after the other all the names but one, as in a couting rhyme. Return the name of the surviver. This is the CodeEval problem #222.

Before starting developing my Python 3 code, I converted the given samples in test cases.
def test_provided_1(self):
    self.assertEqual('Sara', solution('John Sara Tom Susan | 3'))

def test_provided_2(self):
    self.assertEqual('Mary', solution('John Tom Mary | 5'))
It's easy to get what the code should do, executing by hand a sample. For the first one, Tom is the third element, so he's out. Susan becomes third, she's out. John is the first, aka third modulo two, he's out too. Sara is the only surviver, she is the winner.

This is my solution:
def solution(line):
    data = line.split(' | ')
    players = data[0].split() # 1
    black = int(data[1]) - 1 # 2

    while len(players) > 1: # 3
        del players[black if black < len(players) else black % len(players)]
    return players[0]
1. Convert the first part of the input string to a list, splitting on blanks, resulting in a list of names.
2. We should start counting from the first name, considering it as 'one' in the counting rhyme. To adjust this to the fact that in Python we start counting from zero, I decrease here the black spot number.
3. While there is more than one player, remove an element from the list. I did it by the del operator, using the plain black number when possible, otherwise its modulo on the current list length.

I have pushed to GitHub the full Python script and its associated test case.

Go to the full post

Testing Spring autowiring with JUnit

Given a Spring component, we can let Spring wiring it automatically to a reference to an interface that it implements, assuming that we tell Spring which components to scan. And using the SpringJUnit4ClassRunner we can test if it works.

In my Maven Boot Spring web application, I created a package, dd.sia.soundsystem, and I put in it an interface:
public interface CompactDisc {
    String play();
}
Then I have written a class that implements it, annotated as Spring component:
@Component
public class SgtPeppers implements CompactDisc {
    // ...
    @Override
    public String play() {
        // ...
    }
}
Now I create a class having the only purpose of letting know to Spring how to configure for autowiring:
@Configuration
@ComponentScan(basePackageClasses=CompactDisc.class)
public class CDPlayerConfig { 
}
Here I said that Spring has to scan all the classes based on CompactDisc. There are other ways to feed the annotation ComponentScan, and we could even rely on a empty default, meaning check all the components in the current package. I feel more confident passing the base class/interface.

Let's test if the wiring works correctly.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
    @Autowired
    private CompactDisc cd;

    @Test
    public void testNotBeNull() {
        assertNotNull(cd);
    }

    @Test
    public void testPlay() {
        assertEquals("Sgt. Pepper's Lonely Hearts Club Band by The Beatles", cd.play());
    }
}
I annotated the class to let JUnit know that it should use the specific Spring runner, then I said to Spring that it should configure the context using CDPlayerConfig. Now I just have to autowire a CompactDisc reference, and let Spring inject in it an instance of the only available component rooted in it, namely, the SgtPeppers class.


I have written this post while reading the second chapter, Wiring beans, of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration.

Full code on github. Most relevant files are the ones in the source soundsystem package and the test file.

Go to the full post

CodeEval Game of Life

In input we get a string representing the board of the game of life at a given step, we have to give back a string representing the same board after ten iterations. For more detail on the game rules, and to submit your solution, check the CodeEval problem #161.

Before thinking on how to implement my Python 3 solution, I have converted the given sample in a test case:
def test_provided_1(self):
    data = '.........*\n' \
           '.*.*...*..\n' \
           '..........\n' \
           '..*.*....*\n' \
           '.*..*...*.\n' \
           '.........*\n' \
           '..........\n' \
           '.....*..*.\n' \
           '.*....*...\n' \
           '.....**...\n'
    output = '..........\n' \
             '...*......\n' \
             '..*.*.....\n' \
             '..*.*.....\n' \
             '...*......\n' \
             '..........\n' \
             '..........\n' \
             '..........\n' \
             '..........\n' \
             '..........\n'
    self.assertEqual(output, solution(data))
I am going to need a few constants:
STEPS = 10
ALIVE = '*'
DEAD = '.'
STEPS represents the number of iterations I want to run on the input sequence. DEAD and ALIVE should have a clear meaning.

Then I wrote a simple python function, that converts the input string in a squared matrix (remember, in the fantastic world of CodeEval we can forget about error handling), use it to start a ten times loop on a function that implements a round in the game, convert back the 2D list to a string, and return it.
def solution(data):
    step = [list(row) for row in data.rstrip().split('\n')] # 1

    for i in range(STEPS):
        step = next_iteration(step) # 2

    result = [] # 3
    for row in step:
        result.append(''.join([c for c in row]))
    return '\n'.join(result) + '\n'
1. Firstly, I have right-stripped the input data, because I want to get rid of the final newline, then I split it on new lines, getting a list of strings, each of them representing a row in the board. Finally, I convert each row in a list of single characters.
2. Call STEPS times the function implementing a round in the game. Notice it passes in input the board representation, and gets back its new status.
3. Convert back the bidimensional list to a plain string. Firstly each row is joined to a string, then all the rows are joined on a newline. Finally a last newline is added at the end.

Let's play the game!
def next_iteration(matrix):
    next_step = [] # 1
    for i in range(len(matrix)):
        row = []
        for j in range(len(matrix[0])):
            count = local_population(matrix, i, j) # 2
            if matrix[i][j] == ALIVE: # 3
                row.append(ALIVE if 1 < count < 4 else DEAD)
            else:
                row.append(ALIVE if count == 3 else DEAD)
        next_step.append(row)
    return next_step
1. I am going to push the new value for each cell to a new board.
2. For each cell, I count how many neighbors are alive. It's a bit tricky piece of code, so I put it in a function on its own.
3. Accordingly to the rules of the game, a cell gets dead or alive based on its current status and its neighbors' one. So, if it is alive, and it has 2 or 3 neighbors, it stay alive, otherwise it dies. If it is dead, and there are three neighbors, it springs to life.

And here I check the neighborhood:
def local_population(matrix, i, j):
    result = 0
    for row in [i-1, i, i+1]:
        for col in [j-1, j, j+1]:
            if 0 <= row < len(matrix) and 0 <= col < len(matrix) \
                    and not (row == i and col == j) \
                    and matrix[row][col] == ALIVE:
                result += 1
    return result
I check the cells in the square around position [i,j]. However I don't have to check [i,j] itself, and I should avoid to go out of the board. For each cell nearby that is alive, I increase the neighbor counter.

It took some time to get the OK from CodeEval, given the O(n**2) nature of the solution, I suspect. Anyway, it worked fine and I have got full marks. So I pushed test case and python script to GitHub.

Go to the full post

AOP with Spring

I am still working with the Boot Spring Web Application that in the previous post has got concrete Knight and Quest. By injection, the app knows which Knight has to be used the the RESTful service is consumed, and similarly the Knight knows which is his quest.

In this post I add a Minstrel, whose task is singing a song when a knight starts and ends a quest. Following the idea that we don't know to create tight connections between components, we are going to use an Aspect Oriented Programming (AOP) design, treating Minstrel as an aspect of our application.

AOP suggests to let Knight unaware of the Minstrel existence. I could have left the Knight code as was before Minstrel entered the game, I just added logging to let see better how the execution stream passes from Knight to Minstrel.

However there is some job to be done to let a Spring application using AOP. Fistly, I have to add a dependency to the spring-boot-starter-aop artifact, group id org.springframework.boot, in the application POM file.

Moreover, Spring should know about the aspects I want to use in the app. This could be done by an XML or a Java class, in the AspectJ configuration style. I followed the second way, creating this SpringInActionConfig class:
@Configuration
@EnableAspectJAutoProxy
public class SpringInActionConfig {
    @Bean
    public Minstrel minstrel() {
        return new Minstrel();
    }
}

I have implemented Minstrel using the Spring AspectJ support:
@Aspect
public class Minstrel {
    private final Log log = LogFactory.getLog(Minstrel.class);

    @Before("execution(public String Knight.doQuest())")
    public void singBeforeQuest() {
        log.info("Fa la la, the knight is so brave!");
    }

    @After("execution(public String Knight.doQuest())")
    public void singAfterQuest() {
        log.info("Tee hee hee, the brave knight did embark on a quest!");
    }
}
The aspect Minstrel has a method annotated as Before, with the specification that is related to the execution of the Knight doQuest() method, and another one annotated as After, again referring to the same Knight method.

Running the application we should see a change in its log:

Before and after the knight doQuest() execution, the minstrel methods are executed, just as we should have expected.

I have written this post while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of the classic xml configuration.

Full code on github.

Go to the full post

CodeEval Trick or Treat

You get as input a string containing in a strictly defined format the number of vampires, zombies, witches, and number of houses they visited.
Each vampire gets 3 candies from each visited house, zombies 4, and witches 5. Return the average number of candy each kid gets, as a truncated integer.
This Halloween-style problem is #220 from CodeEval. I have solved it using Python 3 as implementation language.

The couple of samples provided, that I have converted in python test cases, explain which is the expected input format. As usual, we are not required to perform any error handling whatsoever.
def test_provided_1(self):
    self.assertEqual(4, solution('Vampires: 1, Zombies: 1, Witches: 1, Houses: 1'))

def test_provided_2(self):
    self.assertEqual(36, solution('Vampires: 3, Zombies: 2, Witches: 1, Houses: 10'))
Curiosly, the most interesting part of this problem is in extracting the values from the input string. I decided to work on it firstly splitting it on commas, then splitting each resulting element on ': ' - colon and a blank - so that on the right part of the split is going to be the string representation of the number. The is just a matter of convert it to integer. I wrote all this stuff as a list comprehension, and then I extracted its values on variables with more readable names:
vampires, zombies, witches, houses = [int(item.split(': ')[1]) for item in line.split(',')]
After calculating the numbers of candies, we have return the average of them for kid, as an integer number,
return candies // (vampires + zombies + witches)
Notice that I used the Python 3 integer division operator that returns the floor result of a division, as for requirements.

As by routine, I have pushed test case and Python script to GitHub.

Go to the full post

CodeEval One zero, two zeros...

Getting passed in input a string containing two integers, x and y, return how many binary numbers in the range [1, y] that have x zeros in it.
This is the CodeEval problem #217, and here is my Python 3 solution.

A couple of samples explains how our program should work, I have converted them in test cases.
def test_provided_1(self):
    self.assertEqual('3', solution('1 8'))

def test_provided_2(self):
    self.assertEqual('1', solution('2 4'))
The first one asks us to check the numbers in [1, 8] and report how many of them has 1 zero.
From [1, 10, 11, 100, 101, 110, 111, 1000] we get [10, 101, 110]. The expected result is 3.

This is what I came out as a high level description of my solution:

Firstly, I create a list of strings, where each element represents a binary number.
I ensure that I have all the required elements in the list.
I loop on all of them, checking if each of them has the right number of zero.
I return the counter of them.

Here it is, converted in Python code:
binaries = ['0', '1', '10', '11', '100', '101', '110', '111', '1000'] # 1


def solution(line):
    count, top = map(int, line.split()) # 2
    top += 1 # 3
    for i in range(len(binaries), top): # 4
        binaries.append(format(i, 'b'))

    result = 0
    for i in range(1, top):
        if binaries[i].count('0') == count: # 5
            result += 1
    return result
1. To avoid recreating on and on the same list of numbers, I store it in a global variable. I initialize it with a few values, and then I will add more elements to it when needed. Notice that I start with 0, even if it is not used by the problem, just to make the code more readable.
2. I split the input line and map its two values to integers. It is in the nature of the CodeEval problems assuming no error handling is needed.
3. The problem requirements assume right-close intervals, in Python we think in term of right-open intervals.
4. When needed, the list of binary numbers is extended. I use the function format() to convert an integer to its string representation - 'b' stands for binary.
5. Only the element that has the required number of zeros is considered for the result.

CodeEval accepted the solution, and I pushed test case and python script to GitHub.

Go to the full post

CodeEval Longest Lines

You get as input the number of lines you want in output and a bunch of lines having different lengths. You should return the longest ones. This is the CodeEval problem #2.

I am about to write a Python 3 solution, but first thing I write a test case for my function, based on the provided sample:
def test_provided_1(self):
    self.assertEqual('San Francisco\nHello World', solution(2, ['Hello World', 'CodeEval', 'Quick Fox', 'A', 'San Francisco']))

This problem uses a different structure from the CodeEval standard, I change accordingly the main script to extract the output size from the first line and to put all the other lines, stripped of their terminating newline character, in a list of strings.
data = open(sys.argv[1], 'r')
top = int(data.readline())
lines = [line.rstrip('\n') for line in data]
Having prepared the input data in this way, my solution is pretty compact:
def solution(size, lines):
    lines.sort(key=len, reverse=True) # 1
    del lines[size:] # 2
    return '\n'.join(lines) # 3
1. I use the specific list sort() method instead of the built-in sorted() function because I'm happy to modify the existing list. Using sorted() would have created a new list. In a real world application, usually sorted() is the preferred approach, because we don't want to mess with the data owned by the caller. I sort the strings by their length, this is done by passing in the key parameter the function len, that has to be used to compare the strings. And I want to get the longest on top, so I want to get the reversed natural (shorter first) order.
2. I want to output just the top 'size' lines. The easiest way to do that is removing all the other elements from the collection. Here I do it using the handy del operator.
3. Finally, I join the surviving elements in the list on the newline, since I have been asked to present each element on a different line.

After the solution was accepted with full marks, I pushed test case and actual python script to GitHub.

Go to the full post

CodeEval Time to eat

Given a string contains a blank separated list of timestamps in format HH:MM:SS, return it sorted in descending order. This is the CodeEval problem #214.

I'm using Python 3 as implementation language, that leads naturally to a trivial solution. If line is the string containing the input string, the output could be generated by a one-liner:
' '.join(sorted(line.split(), reverse=True))
The split() function converts the input line to a list of timestamps, the sorted() function rearrange the list in a ordered fashion, passing True as its reverse parameter, instead of the natural, increasing, order I ask it to use the decreasing one. Joining on a blank I get back the required result.

Even though it is a kind of an overkilling, I put the test case and the actual python solution on GitHub.

Go to the full post

CodeEval Chardonnay or Cabernet

We are given in input a list of blank separated words, supposedly wine names, and, after a pipe, another word. We should consider the last word as a loose collection of characters. We should return each wine name that contains these characters, or the string 'False'. You could fine a fancier description on CodeEval, problem #221.

I have converted the provided samples in test cases for Python 3. I have added a fourth test because I found an ambiguity in the problem description that I wanted to clarify.
def test_provided_1(self):
    self.assertEqual('Merlot', solution('Cabernet Merlot Noir | ot'))

def test_provided_2(self):
    self.assertEqual('Chardonnay Sauvignon', solution('Chardonnay Sauvignon | ann'))

def test_provided_3(self):
    self.assertEqual('False', solution('Shiraz Grenache | o'))

def test_reversed(self):
    self.assertEqual('pinot', solution('pinot | to'))
As you can see in the latest test, the characters in the last word do not say anything about the required search order in the wine name. So 'pinot' is a match for 'to', because it contains both characters, even if in reversed order.

Given this specification, I thought the best way to solve the problem was putting in a dictionary the letters we want to search and their number, and then comparing them in the wine name.

Setting the dictionary
hints = {}
for c in data[1]:
    hints[c] = hints.get(c, 0) + 1
Being data[1] the result of splitting the input line on ' | ', I loop on each character. I try to get it from the dictionary. If it is not there, I force get() to return 0, instead of the default None. Then I increase the value returned by get(), increase it, and store it back in the dictionary.

Selecting the wines
result = []
for wine in wines: # 1
    for key in hints.keys(): # 2
        if wine.count(key) < hints.get(key): # 3
            break
    else: # 4
        result.append(wine)
1. Loop on wines, the list that contains all the words on the left to ' | ', split by the default single blank as separator.
2. Loop on all the characters in the dictionary initialized above.
3. Count the current character in the current wine. If there are less instances of it than expected, exit from the for loop through a break.
4. A nice Python feature. When the for loop is completed correctly, meaning no break has interrupted its execution, proceed to its else block, if any. Here it means that all the checks have succeeded, so I push the current wine in the result list.

Conditional join

If there is something in the result list, I should return it as a string, joining each wine name to the next on a blank. However, if the list is empty I should return a not-found message. As a C programmer, I am used to do it with the infamous ternary operator (?:). It does not exist in Python, but there is a mimic if-else construct:
return ' '.join(result) if result else 'False'
It could be read in this way: if result is not empty return the join on result, otherwise return the 'False' string.

Being this solution accepted by CodeEval, I have pushed test cases and the python 3 function source code to GitHub.

Go to the full post

Injecting and Wiring in Spring with annotations

In the previous I have sketched a component structure for a Spring Web application and I mock-tested with Mockito. Now I am going to create a concrete components and to wire them together.

I create a concrete Quest, annotated so that Spring sees it as a Component qualified as quest.
@Component
@Qualifier("quest")
public class SlayDragonQuest implements Quest {
    @Override
    public String embark() {
        return "Embarking on quest to slay the dragon!";
    }
}
I annotate the BraveKnight component, that Springs can now manage directly the wiring on its own, using in the Constructor Injection a component qualified as quest.
@Component("knight")
public class BraveKnight implements Knight {
    // ...
    @Autowired
    public BraveKnight(@Qualifier("quest") Quest quest) {
        this.quest = quest;
    }
 // ...
}
Spring tries to inject in the resource owned by the controller, seen in the previous post, a component with the same name as its Java type (lowercase fist letter, though), and then maps the call the the /quest URI using the controller method annotated as request mapping.

Once the Spring Web app is started in the Boot Dashboard, we can consume the service from a browser.


I have written this post while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of using the classic xml configuration.

Full code on github.

Go to the full post

CodeEval Find the highest score

Given the representation of a flattened table of scores where the rows represents artists and columns painting styles, give back a string containing the highest score for each style. This is a minimal description of the CodeEval problem #208, and here I am showing my Python 3 solution.

I converted the provides samples in test cases:
def test_provided_1(self):
    self.assertEqual('100 250 150', solution('72 64 150 | 100 18 33 | 13 250 -6'))

def test_provided_2(self):
    self.assertEqual('13 25 70 44', solution('10 25 -30 44 | 5 16 70 8 | 13 1 31 12'))

def test_provided_3(self):
    self.assertEqual('100 200 300 400 500', solution('100 6 300 20 10 | 5 200 6 9 500 | 1 10 3 400 143'))
Then I divided the problem in for steps.

1) Convert the input line in an integer table of scores, where each row represents an artist and each column a style.
2) Rearrange the table so that it can easily be scanned by style.
3) For each style, get its maximum value.
4) Convert the maximum collection in a string and return it.

Authors table

Let's use a list comprehension:
authors = [[int(score) for score in author.split()] for author in line.split('|')]
If your reaction is "what?!", here is the same thing unwinded:
authors = [] # 1
for author in line.split('|'): # 2
    row = [] # 3
    for score in author.split(): # 4
        row.append(int(score)) # 5
    authors.append(row) # 6
1) Create an empty list. This will be our resulting table.
2) Split the input line, using the pipe as separator, and loop on each resulting element.
3) Create an empty list, the current raw we'll fill with scores and push to the table.
4) Split the current section of the input line using the default blank character as separator, and loop on each element, a string that represents the current score.
5) Convert the current score to an integer and push it in the row.
6) Push the row in the authors table.

In a way or the other now we have our table of scores. Given the first test case, author is this list of lists:
[[72, 64, 150], [100, 18, 33], [13, 250, -6]]

Style table

The point of this step is simplify the next one. We could happly skip it, but it improves so much the resulting code readability that we don't really want to miss it.
Besides, here we have a way to put the handy * (star, asterisk, unpack) list operator and the zip built-in function at work.

We want to traspose our table, so that we have styles in the rows. Done in a jiffy
styles = zip(*authors)
The star operator unpacks the authors list, passing its rows, each of them by requirement is an equally sized list, to the zip function.
Zip packs back (for a formal description of its job, see the online Python documentation) the lists, putting in its first element all the first elements of the input lists, down to the last elements.

The result is that in styles we have something that could be seen in this way
[(72, 100, 13), (64, 18, 250), (150, 33, -6)]
(I avoid the details because here I just want to get the problem solved. Please, check about Python iterators and iterables to have more information on what is really going on here.)
Notice that rows are now represented by tuples and not as lists as in the original table. Not a problem, since we don't want to change them in any way.

Max for style

To perform this step I am going to use the built-in functions max(), that returns the largest value among the passed ones, and map(), works like zip, but applying a function to the input data. Putting them together I get:
result = map(max, styles)
If I print result for the first test case, I should get something like
[100, 250, 150]
That is almost the expected output, I only have to format it in the right way.

Let's say we don't want to transpose the table, as done in the previous step. Maybe we want to solve a more complex problem, where tables could be huge, and we don't want to pay the cost of that job. In that case we can fall back to less readable but more efficient code like this:
size = len(table[0]) # 1
result = [-1000 for score in range(size)] # 2
for row in table: # 3
    for i in range(size): # 4
        if row[i] > result[i]:
            result[i] = row[i]
1. By requirement, all rows have the same size.
2. Another requirement is that the lowest score is -1000, I shouldn't use it as a magic number, I know. However, I initialize result to have each element set to the lowest possible value.
3. Scan all the rows.
4. For each element in the row, compare it against the current result for that style, if bigger store it as candidate result.

It should be clear why we prefer the write the map-max version instead of this one, if we don't really have to.

Formatting the result

Usual stuff, convert the solution to a string of blank separated values. Here there is just a minor tweak:
return ' '.join(map(str, result))
I can't join directly on result, because it contains integers, not strings! So, I map result using the str() function that converts its input to string. Done.

Being CodeEval happy with my solution, I pushed test cases and python function source code to GitHub.

Go to the full post

Spring and Mockito

A modern web application written using Spring would use Dependency Injection to loose coupling among the components in the project. This is good, and help us to write more flexible code, as we have seen in a previous post. However this also mean that we need a way to test code that uses a component that is not actually there. Mock testing its here to help us. We'll see here how to use Mockito to achieve this result.

Say that my Spring Boot Application has a RestController named KnightController. It maps a request for the /quest resource to a call to the method doQuest() on the Knight resource owned by the controller.
@RestController
public class KnightController {
    @Resource
    private Knight knight;

    @RequestMapping("/quest")
    public String quest() {
        return knight.doQuest();
    }
}
Knight is just an interface that declares a single method, doQuest(). The beauty of this approach is that we can send any kind of knight in a quest, the only requirement being he implements this interface. For instance, here is a BraveKnight:
public class BraveKnight implements Knight {
    private Quest quest;

    public BraveKnight(Quest quest) {
        this.quest = quest;
    }

    @Override
    public String doQuest() {
        return quest.embark();
    }
}
This Knight owns a Quest, that is defined at runtime, by Constructor Injection, i.e., the actual quest this knight is going to embark is injected in the knight by use of the ctor. As for the Knight, also Quest is an interface with a single method, embark(). Again, in this way a knight is very flexible, having a way to change by injection which is the quest he would embark.

Even if there is more to say on this architecture, here we are interested in see how we can test if what we have now works as expected. Meaning, I would like to write a test case where I create a Quest, I inject it in a BraveKnight, and when I call his doQuest() method I see if the quest embark() method is called. We can't do that in the real world, since Quest is just an interface. But we can mock it, for instance using Mockito.

I need to add the mokito-core dependency in my pom file for the test scope
And then I can create a JUnit-Mockito test case in the test folder. I named it BraveKnightTest.
Its structure is straighforward, let's spend in any case a few words on the first and last line:
Quest quest = Mockito.mock(Quest.class); // 1
// ...
Mockito.verify(quest, Mockito.times(1)).embark(); // 2
1. Create an instance from a mock class that implements the Quest interface.
2. Verify that the method embark() defined on our mock Quest object has actually been called once, as expected.

I have written this post while reading the first chapter of Spring in Action, Fourth Edition by Craig Walls. While doing it, I have ported the original code to a Maven Spring Boot Web project on the STS IDE, using AspectJ annotations instead of the classic xml configuration.

Full source code is on github in the springInAction folder.

Go to the full post

CodeEval Clean up the words

Given a string containing 'dirty' characters, return its 'clean' version. See the CodeEval problem #205 for a full description. Basically, we want to return only lowercase alphabetic characters and a single blank to replace any number of non-alpha characters in between. I am working on this problem using Python 3 as implementation language.

I have converted the given examples in Python test cases, just adding a garbage-only line:
def test_provided_1(self):
    self.assertEqual('hello world', solution('(--9Hello----World...--)'))

def test_provided_2(self):
    self.assertEqual('can you', solution('Can 0$9 ---you~'))

def test_provided_3(self):
    self.assertEqual('what are you doing', solution('13What213are;11you-123+138doing7'))

def test_garbage(self):
    self.assertEqual('', solution('7/8§§?'))
Given my background, I came up firstly with a solution that looks like a code porting from an existing C-language function:
def solution(line):
    result = []
    alpha = False

    for c in line: # 1
        if c.isalpha():
            alpha = True
            result.append(c.lower())
        elif alpha: # 2
            result.append(' ')
            alpha = False

    if result:
        result.pop() # 3

    return ''.join(result) # 4
1. Loop on all the characters in the string. If the current one is an alpha, push its lowered representation to the result list, and raise the flag to signal that we have detected an alpha.
2. If the current character is not an alpha, and we have just pushed an alpha to the result, it is time to push a blank and reset the flag.
3. Actually, CodeEval is not that strict to require this. However, we can avoid to leave a blank at the end of the string popping it. But only if the list is not empty!
4. Finally, convert the list to a string by joining it elements on an empty string.

Still does not come to me naturally, eventually I came up with a more pythonic solution.
import re


def solution(line):
    return re.sub('[^a-zA-Z]+', ' ', line).lower().strip()
Remove the 'dirty' characters by regular expression substitutions, asking to select all sequences composed by one or more non-alpha characters, and pushing a single blank for each of them. Then make it lowercase, and strip all leading and trailing blanks.

Very elegant indeed. Notice that here I'm saying to Python what I want it to do for me, and not how to do it. This way of thinking leads to code that is much more readable and compact.

CodeEval looks happy about both solutions, so I pushed test cases and my python functions to GitHub.

Go to the full post

CodeEval Strings and Arrows

Find how many arrows, '>>-->' or '<--<<', are in a passed string. Beware of overlapping arrows!
This is CodeEval problem #202, and here I show you my Python 3 solution to it.

A few test cases to clarify the problem:
def test_provided_1(self):
    self.assertEqual(2, solution('<--<<--<<'))

def test_provided_2(self):
    self.assertEqual(4, solution('<<>>--><--<<--<<>>>--><'))

def test_provided_3(self):
    self.assertEqual(0, solution('<-->>'))

def test_empty(self):
    self.assertEqual(0, solution(''))

def test_overlapping_right(self):
    self.assertEqual(3, solution('>>-->>-->>-->'))
The idea to solve the problem is neat and simple, just scan the input string looking for the patterns. Here is my solution:
ARROWS = ['>>-->', '<--<<']
ARROW_SIZE = 5


def solution(line):
    result = 0
    for i in range(len(line)): # 1
        candidate = line[i:i + ARROW_SIZE] # 2
        if candidate in ARROWS: # 3
            result += 1
    return result
1. Worst case scenario, I am going to loop on all the characters in the passed string looking for the patterns. Notice that I am working on indeces, in the next note I explain why.
2. I put in candidate the slice of the input line based on the current index. This is the usual way we create a substring in Python.
3. If the candidate matches an arrow, I increase the result.

For our purposes, that is, passing the CodeEval tests, this code is good enough. However, while I was writing it, I felt a bit sad I couldn't skip the loop counter when I identify a matching. Besides, I didn't get any use of the hint about the possible overlapping of arrows. The fact is we simply can't mess with it in a Python for loop, whatever we do to it, it is going to be reset by the for loop control statement.

In this case it is not a big concern, the performance loss is minimal. Still, if the arrows where much longer strings, it could be worthy using a while loop instead, like this:
def solution(line):
    result = 0
    i = 0
    while i < len(line):
        candidate = line[i:i + ARROW_SIZE]
        if candidate in ARROWS:
            result += 1
            i += ARROW_SIZE - 1 # 1
        else:
            i += 1 # 2
    return result
1. In a while loop I have full control on the looping variable. Here I use this feature to jump over the substring, starting the next check on its last character, for what we said about overlapping above.
2. Otherwise, we just pass to the next position in the string.

Both versions works fine for CodeEval, with about the same performance. First one is more readable, so I'd say it should be the preferred one.
As usual, I have pushed test cases and both solutions to GitHub.

Go to the full post

CodeEval Stepwise Word

Write a function that, given in input a list of words, gives back the longest one, in a stepwise fashion. This is the 202 CodeEval problem. Here I am going to show my Python 3 solution.

Firstly, I have converted their example in unit tests. Having a look at them should be clear what they mean for "stepwise".
def test_provided_1(self):
    result = solution('cat dog hello')
    self.assertEqual('h *e **l ***l ****o', result)

def test_provided_2(self):
    result = solution('stop football play')
    self.assertEqual('f *o **o ***t ****b *****a ******l *******l', result)

def test_provided_3(self):
    result = solution('music is my life')
    self.assertEqual('m *u **s ***i ****c', result)
Then, I have divided the problem in two parts. Finding the longest word, and then converting a word in the weird format required.

The longest word could be found in linear time. It is just a matter of keeping track of the currently found solution, comparing its size against the other candidates until a better solution is found or we reach the end of the list:
def get_longest_word(line):
    words = line.split()
    selected = ''
    for word in words:
        if len(word) > len(selected):
            selected = word
    return selected
I get the "stepwise" format by concatenating a growing number of stars followed by the actual character for each step, and then pushing the result in a temporary list. Finally, I join the list on a blank to get the expected string:
result = []
for i in range(len(word)):
    result.append('*' * i + word[i])
return ' '.join(result)
I submitted successfully my solution to CodeEval, and then I have pushed to GitHub both the unit test and the python3 source file.

Go to the full post

A Python function

In the official Python tutorial as an example of function is showed a piece of code that calculate the Fibonacci series. Among the language features on display there, we can also see the handy way of assigning values to more variables in a single operation. Reading it, I though "Cool. But we don't really need two of them there".

So, just for the fun of it, I refactored the function to get rid of the extra variable.

Here is the original code, as you can find it on the python.org tutorial page:
def fib2(n):
    result = []
    a, b = 0, 1
    while a < n:
      result.append(a)
      a, b = b, a+b
    return result
You see the point. It is nice to initialize and modify a and b in the same line, since they are so strictly connected. However, just a single buffer integer is required, since we can refer to the list we are going to return. Well, at least if we can assume that the user won't pass as parameter a value less than one.
def fibonacci(n):
    result = [0]
    candidate = 1
    while candidate < n:
        result.append(candidate)
        candidate += result[-2]
    return result
In comparison with the original function, my version loose the example of comma-assignment functionality. However I use the increase-assign (+=) operator and the negative index support on list. I would say it is a tie.

Go to the full post

CodeEval Fizz Buzz

Do you know the Fizz Buzz game? We take a couple of number, say 2 and 3, call the first one Fizz and the second Buzz. Then we say the numbers as they are in the natural series, uttering "Fizz!" instead of the first number (2 in my case) and all its mutiples, and Buzz for the second and multiples. If a number is a multiples of both of them I should say "FizzBuzz!".

The reason to talk about it here is that Fizz Buzz is the first Codeeval problem, and here I am going to present my Python 3 solution to it.

As usual, I started writing a few test cases. In this case I merely converted the two examples provided by CodeEval in Python Unit Tests:
class TestFizzBuzz(unittest.TestCase):

    def test_provided_1(self):
        result = solution('3 5 10 ')
        self.assertEqual('1 2 F 4 B F 7 8 F B ', result)

    def test_provided_2(self):
        result = solution('2 7 15 ')
        self.assertEqual('1 F 3 F 5 F B F 9 F 11 F 13 FB 15 ', result)
When Fizz is 3, Buzz is 5, and we want to go through the first 10 numbers, I should get what showed in the first test case.
A bit more interesting the second one, where 14, should generate a FizzBuzz result.

Being myself a C/C++ programmer at heart, I came out with a first solution in line with my background:
def solution(line): #1
    result = [] #2
    x, y, n = map(int, line.split()) #3
    for i in range(1, n + 1): # 4
        fb = False # 5
        if i % x == 0: # 6
            fb = True
            result.append('F')
        if i % y == 0:
            fb = True
            result.append('B')
        if not fb: # 7
            result.append(str(i))
        result.append(' ') # 8

    return ''.join(result) # 9
1. The parameter line is supposed to be a character string.
2. I would push each result in a list of strings, and in the end I will convert the list to a single string. This is done for efficiency reasons, being a Python string immutable.
3. Extract the values passed by the user. Notice that no error handling is done here, we boldly assumes we have three blank-separated meaningful numbers in it. For the rules of CodeEval this is our expected way of programming. Don't do that at work. Besides, notica also that I have used the Python built-in map function to convert the strings generated by split() to integers.
4. Loop on the natural series, starting from one up to n, as required by the caller. Since Python use the right-open interval concept, I had to increase n by one to get the expected behavior.
5. The problem has a tiny complication. We need to keep track if a number is either multiple of Fizz or Buzz. To achieve this result I use a boolean variable that I named fb.
6. If the current number is a Fizz (or a Buzz) push its letter to the result list.
7. If it is not a Fizz/Buzz push its actual value to the list. But be careful, we want it as a string, so we have to explicitely convert it to that type.
8. A single blank is added as separator.
9. Finally, we convert the list to a string, by joining it.

This code works fine. However anyone could see that it has been written by a C/C++ programmer. By the way, after writing it, I checked in the blog and I found out I had already written a post on this CodeEval problem, proposing a C++ solution. As you can see, the code looks like a transcription of the same concepts with minimal variations.

I decided to think to a more pythonesque solution, and I came out with this:
def solution(line):
    x, y, n = map(int, line.split())
    result = [
        (((i % x == 0) * 'F' + (i % y == 0) * 'B') or '%d' % i) + ' '
        for i in range(1, n + 1)
    ]
    return ' '.join(result)
Basically, is the same thing. However, I moved the for loop inside the list initialization, and I used the clever trick of multiplying a letter for a boolean, knowing that False means zero and True one. Then using the or operator to check if any Fizz/Buzz has been detected and, if not, pushing in the list the number, converted to string.

On GitHub you can find the full Python 3 source code for the unit test and the actual solutions.

Go to the full post

A more springy Hello World

I am going to modify my Spring Boot Hello World application to let it be a bit more springish. The first version was the bare minimum to check that the STS installation was working fine. The second one was a proper, even if minimal, Web Service. The third one added logging capabilities.

Ensured that all this basic stuff works properly, I can confidently move to something more interesting. Let's say hello using IoC (Inversion of Control) and DI (Dependency Injection).

I create a dedicate package for the logic related stuff for my hello project. Not surprisingly, I name it logic, and I put it under the hello package.
Actually, there's not much logic in this app, I just want to greet users. This suggests me to create an interface, Greeter, that exposes the a single greeting method.
The GreetingController changes accordingly. I remove the logic in it, delegating the work to the actual class that is going to implement the Greeter interface.
Notice how much more cleaner is this way of working. The controller doesn't know anymore about how a greeting is generated. It just knows that exists a Greeter interface, it holds a reference to it that is annotated as a Resource, a javax annotation, and through it, a greeting() method would be called to answer to the user request.

I create a couple of concrete classes implementing Greeter to give a sense to this architecture. There are about identical, in the real world things are usually more complicated. Here is the PlainGreeter, its brother MockGreeter is about the same.
Notice how the relation between the controller and the concrete Greeter is set. Before IoC it was commonly considered a controller task to define a dependency with the Greeter. In a way or another, an instance of the actual Greeter was created and used. Now IoC rules, so we perform an Inversion of Control. Is the Greeter that signal to be available for the controller, and the framework, Spring here, that take care of making it work.

I use annotation to implement the IoC relation, and you can see how in the code.
In the controller I have annotated its Greeter data member as Resource. This javax annotation tells Spring that Dependency Injection should be used here.
Each concrete class implementing the Greeter interface that could be a target for DI should be marked as Component, a springframework stereotype annotation.

Finally, we have to tell Spring which among the available Components should be injected in the controller Resource.

An handy way to do it is combining configuration and annotation. In the Spring configuration file I specify which profile is the active one
spring.profiles.active=prod
Then, I add a springframework context Profile annotation to each component, marking with the active profile only the one I want to be used. Be careful on it. Here is the exception that I get at startup if I mark both my components as "prod":
org.springframework.beans.factory.BeanCreationException:
 Error creating bean with name 'greetingController':
 Injection of resource dependencies failed; nested exception is 
org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
 No qualifying bean of type 'dd.manny.hello.logic.Greeter' available:
 expected single matching bean but found 2:
 mockGreeter,plainGreeter

This Spring Boot project is on github. You could be mainly interested in these files:

Go to the full post

Logging in Spring

Spring has been designed to use the Apache Commons Logging, often called JCL from its previous name, Jakarta Commons Logging. It acts as a wrapper (more technically, bridge) hiding the actual log library used by the application. By default, Logback is assumed.

JCL provides six level of logging, from trace to fatal. To show how it works, I have modified the greeting method from my simple Web Service I am playing with:
private static final Log log = LogFactory.getLog(GreetingController.class);

public String greeting() {
 log.trace("trace hello");
 log.debug("debug hello");
 log.info("info hello");
 log.warn("warn hello");
 log.error("error hello");
 log.fatal("fatal hello");
 return "Hello";
}
LogFactory is the apache.commons.logging class that acts as a factory to create a log object.

If I consume the service, I get something like this:
I see some logging in the console window generated by my app, with a couple of surprises. I miss trace and debug messages, and the fatal one is showed as a plain error.

The latter is a feature, not a bug. Since Logback has no fatal level, JCL maps a fatal request to the error level.
The first one is the default behaviour common to many loggers. If I don't specify which level of logging I want to display, only messages from info level onward are shown.
Here I want to see the full logging, so I add this line to the Spring application.properties file:
logging.level.dd.manny=trace
I restart my Spring application, consume the service, and I get the expected changes in the log.

Log to file

By default, when I ask Spring to log to file, it sends the messages to a file named spring.log, it is usually a good idea to keep this name, however it make sense to place this file in a specific folder. To do that, I add this line to the Spring properties file:
logging.path=/tmp
Last thing. I want to log _only_ to file. To do that I have to mess a bit with the actual logger (once again, in this case Logbackis assumed) configuration file. I am simply using the default one provided by Spring, specifying FILE as appender in the root element:
<root level="INFO">
 <appender-ref ref="FILE" />
</root>
Only the Spring banner is printed to standard output, the log goes straight to file.

The full Spring Boot project is on github. The relevant files are GreetingController.java, application.properties, and logback.xml.

Go to the full post