Kerflyn's Blog

Well… It's a blog!

My First Coding Dojo

I took part in a coding dojo. We aimed to find the firsts prime numbers with the help of Clojure. The primary goal was not to solve the prime number problem. In fact, we tried to learn how to program in Clojure, also trying to be as close to the Clojure’s programming style as we could.

Trying to solve the prime number problem with Clojure

Photo by Ulrich Vachon

We started from a configuration using Cake to manage the project, a text editor, and some unit tests. We’ve worked by pair, changing one member and switching roles time to time.

I must confess that it isn’t something easy to think FP and write a program in Clojure. But the cohesion of the group and the overall will to reach the goal made it easier to finally write a program that succeeded all the tests.

So, after 1 hour and 20 minutes, here’s the result of our dojo :

https://github.com/elefevre/dojo-at-lunch/blob/master/2011-09-21-nombres-premiers/test/prime_numbers/test/core.clj

Written by fsarradin

2011/09/22 at 22:51

Posted in Agility, Programming

Tagged with ,

Comparing Java APIs for Functional Programming [FR]

While the Java Community Process (JCP) has announced the appearance of the functional programming in the Java language,  with the introduction of the lambda expressions (JSR 335: Lambda Expressions for the JavaTM Programming Language), is it possible with the current version of Java to practice this paradigm? While writing those lines, the JCP is in a deep brainstorming on this topic. There are different propositions about the syntax to adopt for the JSR 335 : a straw-man proposal, a prototype for OpenJDK is in progress, the BGGA proposal (Bracha, Gafter, Gosling, and von der Ahé), etc. But none of these syntaxes have formalized. Nevertheless, a first draft should be available during September 2011 and should appear in 2012 with Java 8.

Till then, there are different APIs that allow the developers to use functional programming with Java and they don’t have to learn a new the language.

My first article on the Xebia’s blog is available in French: http://blog.xebia.fr/2011/06/29/comparaison-dapi-java-de-programmation-fonctionnelle/

Written by fsarradin

2011/06/30 at 21:34

Posted in Programming

How TreeMap can save your day?

In Java collections, the TreeMap is a sorted and navigable map that organizes elements in a self-balancing binary tree. It can help you solve problems like “Which element in this collection is the closest to this one?”

Introduction

You want to plan reservations for a room. Here are some reservations:

  • From 4-Jan to 7-Jan, occupant: Mr. A
  • From 10-Jan to 21-Jan, occupant: Mrs. B
  • From 5-Feb to 18-Feb, occupant: Mr. A
  • From 20-Feb to 3-Mar, occupant: Mr. C

Suppose that there is no possibility for a reservation to override another one. How do you determine in a programmatic way who is the occupant the 10-Feb? And the 19-Feb?

Algorithm

There are many possibilities to answer to those questions. Basically, one of them is to store the reservations in a set. When searching for an occupant at a given date, you walk through the set, testing each element. You stop when you have a reservation that contains the given date or when there is no more reservation to test. This is a linear search algorithm. In  the worst case, the time complexity is O(n), ie. when you have to test all elements and there is no matching element or the matching element is the last one.

To improve this algorithm, you can also use a binary search algorithm. It consists at each step in dividing the set of elements in two parts and continuing searching in one of those parts. This algorithm needs a set of sorted elements. Its time complexity is O(log(n)) in the worst case. This is better because if you have 7 elements, you will only need 3 tests against 7 for linear search, in the worst case. And if you have 1000 elements, you will only need 10 tests against 1000 for the linear version, in the worst case. However, with the binary search algorithm, you may lost time while sorting elements. Java proposes in classes java.util.Arrays and java.util.Collections the method sort() the uses the merge sort algorithm that guaranties a time complexity of O(n.log(n)). Thus, sorting + binary search is worst than a linear search, that doesn’t need a sorted set of elements. Note that Java SE proposes implementations of the binary search algorithm in the methods java.util.Arrays.binarySearch() and java.util.Collections.binarySearch().

Another approach to the binary search is to generate the corresponding binary tree. Indeed, the binary search algorithm is like a walk through a height-balanced binary tree. At each step of the algorithm, we select the left part (left branch) or right part (right branch) of the subset of elements (the subtree) according to a central element (a node). But the big difference is that if you apply an algorithm like the red-black tree for your binary tree, two aspects are guaranteed:

  1. Each time you add an element, it is sorted with the rest of the tree.
  2. The tree is height-balanced. It means that its maximal height is O(log(n)).

For such a tree, the operations insert and search cost of time is O(log(n)) each.

The class java.util.TreeMap represents such a height-balancing binary tree and uses the red-black tree algorithm. But what is even more interesting with this class, is that it provides the methods ceilingEntry() and floorEntry(). They return the map entry which key is the closest respectively after and before the given key.

Representation of a reservation

Below is the source code of a simplified class to represent such reservations. This implementation uses guava.

public class Reservation {
    public Date from;
    public Date to;
    public String occupant;

    public Reservation(Date from, Date to, String occupant) {
        this.from = from;
        this.to = to;
        this.occupant = occupant;
    }

    public boolean contains(Date date) {
        return !(from.after(date) || to.before(date));
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
            .add("from", from)
            .add("to", to)
            .add("occupant", occupant)
            .toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(from, to, occupant);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || !(obj instanceof Reservation)) {
            return false;
        }
        Reservation reservation = (Reservation) obj;
        return Objects.equals(from, reservation.from)
            && Objects.equals(to, reservation.to)
            && Objects.equals(occupant, reservation.occupant);
    }

}

We declare below all four reservations that you can find in the introduction at the top of the post.

Date from, to;
Calendar calendar = Calendar.getInstance();

calendar.set(2011, 0, 4);
from = calendar.getTime();
calendar.set(2011, 0, 7);
to = calendar.getTime();
Reservation reserv1MrA = new Reservation(from, to, "Mr. A");

calendar.set(2011, 0, 10);
from = calendar.getTime();
calendar.set(2011, 0, 21);
to = calendar.getTime();
Reservation reserv1MrsB = new Reservation(from, to, "Mrs. B");

calendar.set(2011, 1, 5);
from = calendar.getTime();
calendar.set(2011, 1, 18);
to = calendar.getTime();
Reservation reserv2MrA = new Reservation(from, to, "Mr. A");

calendar.set(2011, 1, 20);
from = calendar.getTime();
calendar.set(2011, 2, 3);
to = calendar.getTime();
Reservation reserv1MrC = new Reservation(from, to, "Mr. C");

How to find a reservation from a given date

I group a set of reservations in a class that I’ve called Planning. Once instantiated, you can add reservations (method add()) and you can get a reservation at a given date (method getReservationAt()).

There are two steps to get a reservation close to a date.

  1. I first use the method floorEntry(). It gets you the map entry which key is the greatest one less than the given date.
  2. Second, I check if the reservation (that is the value of the entry) contains the given date.
public class Planning {
    public final TreeMap<Date, Reservation> reservations;

    public Planning() {
        reservations = new TreeMap<Date, Reservation>();
    }

    public void add(Reservation reservation) {
        reservations.put(reservation.from, reservation);
    }

    public Reservation getReservationAt(Date date) {
        Entry<Date, Reservation> entry = reservations.floorEntry(date);
        if (entry == null) {
            return null;
        }
        Reservation reservation = entry.getValue();
        if (!reservation.contains(date)) {
            return null;
        }
        return reservation;
    }
}

Test

We first store the reservations declared above in a planning.

Planning planning = new Planning();
planning.add(reserv1MrA);
planning.add(reserv1MrsB);
planning.add(reserv2MrA);
planning.add(reserv1MrC);

Now, who has made a reservation the 10-Feb and the 19-Feb? (Here, I use FEST-assert as assertion API.)

Calendar calendar = Calendar.getInstance();

calendar.set(2011, 1, 10);
Date dateOfMrA = calendar.getTime();
assertThat(planning.getReservationAt(dateOfMrA).occupant).isEqualTo("Mr. A");

calendar.set(2011, 1, 19);
Date dateNoReservation = calendar.getTime();
assertThat(planning.getReservationAt(dateNoReservation)).isNull();

Written by fsarradin

2011/05/20 at 02:59

Posted in Programming

Tagged with ,

“Is this point inside this rectangle?” without IF

The class Point is given below. The hasCode() method uses an helper that you can find in guava. The method equals() contains the only if in this post (promised ;)).

public class Point {
    public final int x;
    public final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(x, y);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Point)) {
            return false;
        }
        Point point = (Point) obj;
        return x == point.x && y == point.y;
    }
}

Here is the class Rectangle:

public class Rectangle {
    public final Point start;
    public final Point end;

    public Rectangle(Point start, Point end) {
        this.start = start;
        this.end = end;
    }
}

I suppose that start.x < end.x and that start.y < end.y

I define the minimum and the maximum of two points as the point which coordinates are respectively the minimum and the maximum of the coordinates of the given points. For example, the minimum of the points (1, 4) and (3, 2) is (1, 2), and the maximum is (3, 4).

public class Points {
    // it's an utility class
    private Points() { throw new UnsupportedOperationException(); }

    public static Point min(Point p1, Point p2) {
        return new Point(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y));
    }

    public static Point max(Point p1, Point p2) {
        return new Point(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y));
    }
}

Now, I give the method Rectangle.contains() that checks if a point is inside a rectangle. The idea is to use the methods min() and max() between the given point and the rectangle edges as filters: if the computed point is different from the given point, then the given point is not in the rectangle.

import static Points.*;

public class Rectangle {
    // see code above...

    public boolean contains(Point point) {
        return point.equals(max(start, min(end, point)));
    }
}

Written by fsarradin

2011/05/04 at 07:01

Posted in Programming

Tagged with ,

Playing with Scala’s pattern matching

How many times have you been stuck in your frustration because you were unable to use strings as entries in switch-case statements. Such an ability would be really useful for example to analyze the arguments of your application or to parse a file, or any content of a string. Meanwhile, you have to write a series of if-else-if statements (and this is annoying). Another solution is to use a hash map, where the keys are those strings and values are the associated reified processes, for example a Runnable or a Callable in Java (but this is not really natural, long to develop, and boring too).

If a switch-case statement that accepts strings as entries would be a revolution for you, the Scala’s pattern matching says that this is not enough! Indeed, there are other cases where a series of if-else-if statements would be generously transformed into a look-alike switch-case statement. For example, it would be really nice to simplify a series of instanceof and cast included in if-else-if to execute the good process according to the type of a parameter.

In this post, we see the power of the Scala’s pattern matching in different use cases.

Notice that the pattern matching is not something new. It is something that appears already in some other languages like OCaml, Haskell. A kind of pattern matching also exits in Prolog, but it uses a far different mechanism (unification in this case).

Traditional approach

There is an approach to the Scala’s pattern matching that looks similar to the switch-case structure in C and Java: each case entry use an integer or any scalar type. Here is an example:

def toYesOrNo(choice: Int): String = choice match {
    case 1 => "yes"
    case 0 => "no"
    case _ => "error"
  }

So if  you enter toYesOrNo(1), Scala says “yes”. And if you enter toYesOrNo(2), Scala says “error”. Notice that the symbol _ is used to formulate the default case.You also have to remark that there is no need to use the break statement.

But if you want that Scala says “yes” when you enter toYesOrNo(1), toYesOrNo(2), or toYesOrNo(3), you will write the function like this:

def toYesOrNo(choice: Int): String = choice match {
    case 1 | 2 | 3 => "yes"
    case 0 => "no"
    case _ => "error"
  }

Now, you can use a string for each case entry. Using strings is interesting when you want to parse options of your applications:

def parseArgument(arg: String) = arg match {
    case "-h" | "--help" => displayHelp
    case "-v" | "--version" => displayVerion
    case whatever => unknownArgument(whatever)
  }

So if you enter parseArgument(“-h”) or parseArgument(“–help”), Scala calls the displayHelp function. And if you enter parseArgument(“huh?”), Scala calls unknownArgument(“huh?”).

Notice that I have not used _ for the default case. Instead, I have put an identifier as its value is used in the associated instruction.

Typed pattern

Sometimes in Java, you have to deal with an instance of something that appears like an Object or any high level classes or interfaces. After checking for nullity, you have to use series of if-else statements and instanceof-cast to check the class or the interface that the instance extends or implements, before using it and processing the instance correctly. This the case when you have to override the equals() method in Java. Here is the way Scala sees the thing:

def f(x: Any): String = x match {
    case i:Int => "integer: " + i
    case _:Double => "a double"
    case s:String => "I want to say " + s
  }
  • f(1) → “integer: 1”
  • f(1.0) → “a double”
  • f(“hello”) → “I want to say hello”

Is not it better than a succession of if+instanceof+cast?

This kind of pattern matching is useful to walk through a structure using the composite design pattern. For example, you can use it to explore the DOM of an XML document or the object model of a JSON message.

Functional approach to pattern matching

A side effect of such a matching is that it provides an alternative way to design functions. For example, consider the factorial function. If you choose the recursive version, usually, you would define it like this:

def fact(n: Int): Int =
    if (n == 0) 1
    else n * fact(n - 1)

But you can use Scala’s pattern matching in this case:

def fact(n: Int): Int = n match {
    case 0 => 1
    case n => n * fact(n - 1)
  }

Notice the use of the variable n in this case. It is matched with any value that does not appears in the preceding cases. You have to understand that the n in the last case is not the same as the one used in the function signature. If you wanted to use the parameter n and not a new variable with the same name, you have to delimit the variable name with back-quote in the case definition, like this: `n`

Here is a simple way to build you factorial function in Scala:

def fact(n) = (1 to n).foldLeft(1) { _ * _ }

Pattern matching and collection: the look-alike approach

Pattern matching may be applied to the collections. Below is a function that computes the length of a list without pattern matching:

def length[A](list : List[A]) : Int = {
    if (list.isEmpty) 0
    else 1 + length(list.tail)
  }

Here is the same function with pattern matching:

def length[A](list : List[A]) : Int = list match {
    case _ :: tail => 1 + length(tail)
    case Nil => 0
  }

In this function, there are two cases. The last one checks if the list is empty with the Nil value. The first one checks if there is at least one element is the list. The notation _ :: tail should be understood “a list with whatever head followed by a tail”. Here the tail can be Nil (ie. empty list) or a non-empty list.

To go further, we will use this approach with tuples in order to improve our method parserArgument() above:

  def parseArgument(arg : String, value: Any) = (arg, value) match {
    case ("-l", lang) => setLanguageTo(lang)
    case ("-o" | "--optim", n : Int) if ((0 < n) && (n <= 5)) => setOptimizationLevelTo(n)
    case ("-o" | "--optim", badLevel) => badOptimizationLevel(badLevel)
    case ("-h" | "--help", null) => displayHelp()
    case bad => badArgument(bad)
  }

Notice first the use of the operator | that allows to match alternative forms of arg inside the tuple. Notice also the use of two patterns for options -o and --optim. These patterns are distinguished by the use of a guard condition. The guard conditions help you to get fine tuned pattern matching when pattern matching alone is not enough.

Advanced pattern matching: case class

Case classes are classes with part of their behavior predefined in order to make easier their construction and their use in a pattern. Case classes enables you to manipulate parameterized symbols for example, parsed by a compiler or used by your internal Domain Specific Language (DSL).

The example below shows how to use case classes and pattern matching in order to build simple mathematical expressions, evaluate them, and compute their derivative. First, lets define the symbol to represent expressions: the variable X, constants, addition, multiplication, and the negative operator (for the fun!). Here sealed means that there is no other children of the class Expression outside of the namespace.

  sealed abstract class Expression
  case class X() extends Expression
  case class Const(value : Int) extends Expression
  case class Add(left : Expression, right : Expression) extends Expression
  case class Mult(left : Expression, right : Expression) extends Expression
  case class Neg(expr : Expression) extends Expression

Now, lets define a function to evaluate expressions with a given value for the variable by using pattern matching.

  def eval(expression : Expression, xValue : Int) : Int = expression match {
    case X() => xValue
    case Const(cst) => cst
    case Add(left, right) => eval(left, xValue) + eval(right, xValue)
    case Mult(left, right) => eval(left, xValue) * eval(right, xValue)
    case Neg(expr) => - eval(expr, xValue)
  }

Lets try the eval() function:

val expr = Add(Const(1), Mult(Const(2), Mult(X(), X())))  // 1 + 2 * X*X
assert(eval(expr, 3) == 19)

Now, we define a function that compute the (unreduced) derivative of an expression:

  def deriv(expression : Expression) : Expression = expression match {
    case X() => Const(1)
    case Const(_) => Const(0)
    case Add(left, right) => Add(deriv(left), deriv(right))
    case Mult(left, right) => Add(Mult(deriv(left), right), Mult(left, deriv(right)))
    case Neg(expr) => Neg(deriv(expr))
  }

Lets try the deriv() function:

val df = deriv(expr)

Here is what you get in df:

Add(Const(0),Add(Mult(Const(0),Mult(X(),X())),Mult(Const(2),Add(Mult(Const(1),X()),Mult(X(),Const(1))))))
// = 0 + (0 * X*X + 2 * (1*X + X*1)) = 4 * X
assert(eval(df, 3), 12)

Other advanced pattern matching features

There are some special notations used in the Scala’s pattern matching. Scala allows to put aliases on patterns or on parts of a pattern. The alias is put before the part of the pattern, separated by @. For example, in the expression address @ Address(_, _, "Paris", "France"), we want any addresses in Paris/France, but we do not care about its content after the match is done. So after, we just use the alias address.

There is also a specific notation to match sequences with _*. It matches zero, one or more elements in a sequence to its end.

In Scala, pattern matching does not appears only after a the function match. You can put pattern matching in any closure and also in a catch block.

You can provide your own behavior for pattern matching. This is called extractor. To do so, you have to provide your own implementation of the unapply() method (and/or unapplySeq() for a sequence).

Conclusion

In this post, we have seen different ways to use the pattern matching with Scala. The main advantage of such a feature is to provide an easy way to build alternative structures based the matching of scalar values, strings, collections, but also types and parameterized symbols. For me, pattern matching is one of the sexiest alternatives to if statements! A good use of pattern matching can make your program really readable and helps you to build an internal DSL.

Written by fsarradin

2011/02/14 at 18:52

Posted in Programming

Tagged with , ,

[Report] A Trip In China 2010

Here is a report of my trip in China in October 2010. I speak about China, Shanghai, Guilin, Wuxi, Zhujiajiao, … and well, it also cover Expo 2010 in Shanghai. I haven’t used the services of travel agency, except for the trip in Guilin. For Guilin, I have used CITS, a Chinese travel agency.

In this report, I use a twitter style composed of “tweets” (small messages) with fake #hashtag 😉 to highlight the topic. This style is more easy to use when you only have a smartphone to take notes. The tweets follow almost the chronological order.

Notice that some blocks of tweets are shifted to the right when it covers a more specific topic. Notice also that some of those tweets are in French, indicated by the tag [FR].

The report

Here I go for 2+1/2 weeks in #China. It’s the 3rd time.

Survival kit : #python and #scheme on my smartphone #imageek

Have seen just a part of the Taihu lake from the plane #china

I’ve just seen a giant thermometer on a blast furnace: #Shanghai#Expo 2010 ?

The last time, I’ve taken the maglev from Pudong airport to #Shanghai

Maglev: Magnetic Levitation train, speed=400km/h, so cooool ! (thx Siemens) #shanghai

Tested: there is no access to twitter from china

As tweeter isn’t accessible from china, I’ve noticed my tweets in my phone #imanolife

For my tweets I have my smartphone and a small notepad

Tested: there is no google.cn. google.com is forward to google.com.hk (hong-kong) by default

#China: world leader of “I fixed it” contest

#China is a quarter of a day in advance compared to France. I’m fully awake at 2am :/

Octobre in #Shanghai is like the end of August in Paris

It’s all foggy in #Shanghai and around: pollution or natural?

Shanghai Sculpture Space

At an art gallery at #Shanghai Sculpture Space in Red Town (http://www.sss570.com/)

Suddenly, mini cooper, thousand of them
Suddenly, mini cooper, thousand of them
Une voiture à 100 briques ?
[FR] Une voiture à 100 briques ?
Chinese laptop: past meets present? future? or inside truth?
Chinese laptop: past meets present? future? or inside truth?

“1 people 1 dream” said CN olympic games #china

“Be a better you” says Jiaotong University #shanghai

#Shanghai#Expo 2010: “Better City, Better Life”, and sometimes: “Deeper Freindship”

So cool! IT books worth only about 10 EUR… Even those in English from O’Really. And it seems to be legal #imageek #china

Bah! A computer in #Shanghai has the same price than in Europe 😦

Wúxī (无锡) and Tài Hú Lake (太湖)

10-08: today, I visit #Wuxi and #Taihu lake

#Taihu lake: huge lake close to Shanghai: 2h by bus. It’s like a sea without waves

#Taihu lake: an average deep of 2m for more than 2000km² (see http://en.wikipedia.org/wiki/Taihu_Lake)

A tree at the top of a building #wuxi
A tree at the top of a building #wuxi
Some junks on the #Taihu lake. They are rented by the government for the Chinese National Day
Some junks on the #Taihu lake. They are rented by the government for the Chinese National Day

Poor #Taihu lake: a green alga on its surface gives the impression that someone has poured some paint

Auchan Carrefour Citroën Peugeot Ikea Mercedes Lamborghini etc.: am I in #China?

#China is one of the only country where you can see cars from all around the world

Chinese people are musicians: they like to play with the horn of their car #IWantToSleep#china

#Shanghai at night is outstanding: the buildings are covered with thousand of dancing lights

There’s even a building that displays a giant TV screen on its front #imahick #shanghai

The top of some buildings have a specific decoration: a crown, a palace entrance, an observatory, etc. #shanghai

There's a building top that looks like a golden mansion #shanghai

There's a building top that looks like a golden mansion #shanghai

[FR] En #Chine, pas d’hypocrisie : on peut vraiment voir les fonctionnaires dormir à leur guichet lol

Bah! 17h and the night is falling already #shanghai

Liked: there’s a countdown for each traffic light, for cars, for pedestrians, for the red light and the green light #china

Good idea: on most of the street name signs, names are written in Chinese and in Pinyin/English #china

Good idea: on the street name sign, you know if you are on the east/west/north/south/middle side of the street and you know where are the other sides #china

Commerce is everywhere you can put an eye on. But concurrency is very hard #china

Today is 10-10-10… Binary for 42. OMG! what does means? #imageek

Today is 10-10-10… Doesn’t mean anything for #China :/

Zhūjiājiǎo (朱家角)

10-10: today, I visit #ZhuJiaJiao #china

There are very nice small villages (eg. #ZhuJiaJiao) with water channels like in Venice #shanghai

Doesn't it look like Venice? #ZhuJiaJiao
Doesn’t it look like Venice? #ZhuJiaJiao

#ZhuJiaJiao is a city close to Shanghai: 1h by bus

If you don’t like touristic cities full of commerces like Mont-Saint-Michel, don’t come at #ZhuJiaJiao

There is a smell in the air of a mix of a sweet and/or fatty steamed foods #ZhuJiaJiao

Shanghai places and history

Some places in #Shanghai: The Bund, NanJing lu and People Square, HuaiHai lu, XuJiaHui, PuDong

#Shanghai is word with two syllables, so 2 Chinese characters: shang (上) = on, hai (海)= the sea

#Shanghai is mainly divided in 2 parts by the HuangPu river

#Shanghai was originally a village of fishers

During the 19th century, the main foreign countries has settled their concession around the Bund (west side of the HuangPu) #shanghai

Located in the south part of the city, the French concession has grown to the west #shanghai

We can find HuaiHai lu that was originally called Avenue Joffre #shanghai

#Shanghai is one of the most European cities in China. Here, I feel somewhat at home, compared to Beijing

Or is it the most New-Yorker of the European cities? #shanghai

Guìlín (桂林)

10-11: today I go to #Guilin for 3 days. It is full of beautiful landscape. 2h from Shanghai by plane

#Guilin is located in the Guangxi Zhuang region in the south of China (http://en.wikipedia.org/wiki/Guilin)

Going to test a domestic flight with Juneyao Airlines to go to #Guilin

OH! Changing the boarding gate two times, plane is late due to air flow (1h). WTF! #china

Inside the plane at last! Seems to be a small airbus (A320). The inside is nice #china

[FR] La nourriture à bord est acceptable pour une bouche française. #chine

[FR] “Mini french bread” est une hérésie: ici, c’est un pain au lait assez sucré #chine

Tested: green clementine – it’s good and it leaves virtually no smell on your fingers 🙂 #china

Has landed. The atmosphere is full of humidity #guilin

even bikes can drive on motorway! #guilin

#Guilin landscape
#Guilin landscape

people are poor. “There is nothing except tourism and past. #Guilin is like a beautiful woman with dirty clothes” said the guide

#Guilin landscape appears on 20 yuan bills, it also appears in Star Wars and Doom video game

Visiting by boat on the Li river (Li jiang in Chinese). Destination: Yangshou (http://wikitravel.org/en/Yangshuo). #Guilin landscape is really beautiful!

Li river: the water is almost clear and absolutly not deep #guilin

there’s a mountain with 9 horses naturally inscribed on. You can also see faces. Chinese people have a very strong imagination #guilin

A bamboo raft on the Li river#guilin
A bamboo raft on the Li river #guilin

now on board of a sort of raft made of 10 bamboo sticks. Never been so closed from water on a boat. #guilin

the water of the river is good, I would like to swin #guilin

The river is 6m deep max #guilin

Result: have crossed some small waterfalls and my bottom is a little wet – nice 🙂 for the rest, it’s almost quiet #guilin

#Guilin altitude: about 200m

Yangshou: has seen an entertainment named “Impression Liu Sanjie”. Made by the famous Chinese movie director Zhang Yimou. Actors come from local villages. It was really beautiful #guilin

Impression Liu Sanjie: a woman dancing on the moon #guilin
Impression Liu Sanjie: a woman dancing on the moon #guilin

Yangshou: an American asked where I come from. I needed time not to answer “faguo” (法国)

Yangshou: There’s a street with a heavy crowd at night. It’s full of night bars with some individuals that dances in front #guilin

[FR] En France, 13 = malheur. En #Chine, 13 ne veut rien dire. Par contre, 8 = bonheur, 4 = mort/serpent/malheur

The small safe in the hotel is not sealed. It is lightweight and can be put in a large suitcase. Seriously WTF? #china

Chinese ancient imperial examination system has 7 levels #china

Have to pass an exam. 2′ to write the answers in Chinese with an old Chinese pencil. It’s really hard to write “I don’t know”! #guilin#china

Chinese exam: every student is behind a desk in a small cell. Students can’t cheat on each other #guilin#china

Have to go in a Japanese restaurant to drink a safe beer (Asahi). The food in the restaurant is really good and different compared the Japanese restaurant in France 🙂 #guilin

#China really miss something important: cheese :p

taken in photos with 3 women from Shanghai wearing traditional clothes of #Guilin 🙂

have drunken some beer from #Guilin. It’s water with a taste of beer :/ QsingTao is better

/me made some adv. about France: good wines, perfums and cheeses 😉 #FTW #guilin

end of trip in #Guilin. Good journey. Forgot everything about my French life except my language

plane from Guilin to Shanghai is one hour late too, due to air traffic congestion 😦 #china

#Shanghai at 3am is unrecognizable: the buildings have disappeared in the dark. The taxis have invaded the streets.  They lookout for the lost costumer

The taxis wait the customers even at the bus stop or at the restaurant exit #shanghai

My little Chinese guidebook confuses men’s/ladies’ restroom (to know the difference can save your life!)

It’s possible to hear some repeated explosions of firecrackers to wish happiness. This leaves some traces of red paper in the street #china

Shanghai Expo 2010 (中国2010年上海世界博览会)

Inside #Shanghai#Expo 2010 for one day

Space Home Pavilion: nothing to do here #shanghai#expo

Some interesting sculptures a the Shanghai shipyard pavilion #shanghai#expo

Pavilion of Future: a giant thermometer on a blast furnace displays 24°C #shanghai#expo
Pavilion of Future: a giant thermometer on a blast furnace displays 24°C #shanghai#expo

Pavilion of Future: giant books, light games, playing with senses… imagine the cities of tomorrow: exiting #shanghai#expo

Future Pavilion: enregy city #shanghai#expo
Future Pavilion: enregy city #shanghai#expo

have to cross the river. Too many people waiting for the ferry or the bus #shanghai#expo

Know what? The pavilions of North Korea and of Iran are neighbours #shanghai#expo

France Pavilion: Chinese faces, metalic roses on water, nice looking Citroën berlin car, vertical green elements #shanghai#expo

France Pavilion: nice looking Citroën berlin car #shanghai#expo
France Pavilion: nice looking Citroën berlin car #shanghai#expo

France Pavilion: has seen Léon, our French mascot #shanghai#expo

France Pavilion: “la ville sensuelle”, romantism with lounge music, time to time: Eiffel tower #shanghai#expo

France Pavilion: I’ve the feeling that this was an expo about Paris #shanghai#expo

Belgian fries (at Léon de Bruxelles) and waffles sold next to the Belgian/EU pavillon (no beer?) #shanghai#expo

Spain Pavilion: this one is really sensual with those women dancing flamengo! #shanghai#expo

Spain Pavilion: Picasso, horses that cross a room: yes! #shanghai#expo

Spain Pavilion: babies on curtains: nice! Giant baby at the end: o_O #shanghai#expo

UK Pavilion: only the transparent structure is interesting #shanghai#expo

Italy Pavilion: really like this one. Full of good surprises #shanghai#expo

Italy Pavilion: Ferrari, pasta, wine, many kind of art #shanghai#expo

Italy Pavilion: an upside down room #shanghai#expo
Italy Pavilion: an upside down room #shanghai#expo

Italy Pavilion: Italy, you have to remember that the ground floor is numbered 1 in China, not 0 #shanghai#expo

Luxembourg Pavilion: not so good #shanghai#expo

Would like to visit those pavilion: Algeria, Peru, China, China’s Petroleum #shanghai#expo

[FR] Il est vendu en #Chine des modèles de Peugeot 307 et 408 et de Citroën qu’on ne verra jamais en France

[FR] La Peugeot 206 n’a pas changé en dehors d’une inscription en chinois #chine

In #China, superstitions have also a long life

24°C in #Shanghai. The air is muggy

Jewelry made of jade is very popular #china

Wrong good idea: switch on the light in the hallway by hitting the floor with your foot #IWantToSleep #china

In #China, you don’t eat a yoghurt, you drink it… through a straw!

[FR] Viens de voir la photo de la famille présidentielle sur fond du pavillon français dans petit journal shanghaien #shanghai#expo

[FR] Carla y montre la mascotte française : Léon, un petit chat aux couleurs française #shanghai#expo

The Dream in the Red Chamber (Hóng Lóu Mèng – 红楼梦)

Grand View Garden (Dàguānyuán – 大观园) is a touristic place with a garden, a mansion, and a pagoda on a island. It’s a little frequent: it’s nice 🙂

#Daguanyuan represents the place where the story of “The Dream in the Red Chamber” (Le Rêve dans le Pavillon Rouge in French) would have held

The throne room #daguanyuan
The throne room #daguanyuan

“The Dream in the Red Chamber” is one the four important novels in the Chinese literature

#Daguanyuan is a place that is often used as a movie set. Each movie is an opportunity to restore the mansion

Many portals for building entrances in #China are folding, mounted on wheels and automated

Many portals for building entrances in #China are folding, mounted on wheels and automated

Seen: Asian people in Tibetan dresses, dancing on a Tibetan music in front of a Tibetan restaurant #shanghai

Restaurant in China

The chic restaurant is located in a tower. You can ask for a private lounge (there a many) #china

In a Chinese restaurant, you usually find a large round table with a lazy Susan made of glass #china

Dishes arrive with the same rhythm. They are put on the lazy Susan. Everyone around the table helps oneself as he wants #china

A pair of chopsticks, a spoon made of porcelain, a bowl for the rice and the soup, a bowl for the tea, a small plate: here are your weapons to eat in #China

Just notice that china with a small ‘c’ means porcelain in English!

Seen: someone has dropped (not done on purpose) a bottle in a gutter. 5min later, an old man on a bike collected it in a view to sell it #shanghai

There’s no need for a street cleaning company, because poor people work on them already #shanghai

Bah! Spitting is a common practice #china

Have to back soon: it’s forecast 22°C in #Shanghai. In Paris, 7°C with a strike maybe 😦 Why should I come back?

I spent 2 weeks and a half in October wearing t-shirts and sunglasses #notashamed

I really forgot lots of thing about my French life. That’s what I call a good trip 🙂

Written by fsarradin

2010/10/24 at 08:20

Posted in MyLife

Tagged with , , ,

[FAQ] Learn To Program In Python

Here is a small FAQ about how to become a programmer in Python and making progress. Do not expect this FAQ to be completely logical. Python’s name comes from Monty Python’s Flying Circus. So you have to experience the language to appreciate it… before to think ;p

Python is simple, so becoming a Python programmer is simple too!

How to learn to program in Python?

The answer is simple! Go to the address http://www.python.org/doc/ and click on the Tutorial link.

Once you have done with the tutorial, you will not be a strong Python programmer. In fact, at the end, you will be able to put most of your ideas into a Python script. It helps if you have experienced programming with another language and if you have some knowledge in object-oriented programming (OOP) — the last is optional. But, above all, it is necessary to have a sufficient open mind.

How to be a better Python programmer?

The answer is simple! Practice Python and read the source code of the files in the Python standard library ($PYTHONPATH/Lib).

Do not fear that kind of code, it will not bite you! By doing this, you will learn some patterns and some idioms used in Python. The bulk of the source code in the standard library is sufficiently clear.

How to become a strong Python programmer?

The answer is simple! Read the PEPs (Python Enhancement Proposals) starting from this one http://www.python.org/dev/peps/ and use google.

Here the goal is to explore what is unknown by most of the programmer or by other language. Do you know what is a generator or a decorator? Can the list comprehension make my life as a developer better? And what about the database API? The answers are in the PEPs and google.

For example, to learn more about Python’s decorators, take a look at http://www.python.org/dev/peps/pep-0318/.

Is this enough?

The answer is simple! Absolutely not!

All the answers here should be considered as starting points. After that, there are many things to explore. But, you have to do the same thing you would do with another language to improve your skill: explore forums, listen to conferences, answer to questions, and contribute.

To Infinity And Beyond

$ python -c "import this"
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Written by fsarradin

2010/09/26 at 16:06

Posted in Programming

Tagged with ,

Homemade context management

A stateless application component is a component that looks like a mathematical function. By definition, a mathematical function always returns the same result providing that you enter the same parameters. If a component follows such a definition, it is easier to test, because the component is decoupled from the rest of the application. Moreover, it is safer in case of concurrency.

If you want application components as stateless as possible, you have to manage a context, in order to export and manipulate the component state outside of the component. A context can be a complex structure that contains all the configuration elements needed by a component or more to run.

There are two kinds of context:

  • The application context is a context that is built during the load time and that do not change during the application life. Spring and Java CDI have such an approach.
  • The session context is a context that is built dynamically at a specific phase during the runtime.

In this post, we see this last case of context: the session context.

Interface

A context can be seen as a set of objects. Each object is identified by a name.

Here is an interface to represent contexts:

public interface Context {
    void register(String name, Object o);
    Object get(String name);
    <T> T get(String name, Class<T> contract);
    <T> T get(Class<T> contract);
    Context getParent();
}

Contexts can be organized in a hierarchical structure. A context has a parent context. All registered objects in the parent context is accessible to the child context. This help not to redefine abusively previously registered objects.

There are three methods to get a registered object in a context or its parent:

  • get(name) is the easiest one, but its drawback is to return an Object and not something more specific like a String, a Date, a BigDecimal, or anything else. So, if you know what it is, you have to cast the result. Otherwise, the result might not be directly useful.
  • get(name, contract) applies a check on the returned type according to the contract. The contract may be a class, a super-class, or an interface. What is return is of the type of the contract. Notice that get(name, Object.class) is the same as get(name).
  • get(contract) searches the first registered object which type matches or inherits of the given contract.

Implementation

Here is the class to generate contexts.

public class Contexts {
    public static final NULL = new NullContextImpl();

    private Contexts() {
        throw new UnsupportedOperationException();
    }

    public static Context create() {
        return new ContextImpl(NULL);
    }

    public static Context create(Context parent) {
        return new ContextImpl(parent);
    }

    /* Implementation of context classes (see later...) */
}

You can get or create three types of contexts:

  • A null context that is the parent of all contexts.
  • A top-level context with create(), which is a context without parent (more exactly, a context which parent is the null context).
  • An ordinary context with create(parent), which has a parent context.

A null context is defined. In fact, it is the top parent of all contexts. The null context is built according to the Null Object pattern. Every get() method throws a NoSuchElementException.

private static class NullContextImpl implements Context {
    public Context getParent() { return this; }

    public void register(String name, Object o) {
        throw new UnsupportedOperationException();
    }

    public Object get(String name) {
        throw new NoSuchElementException();
    }

    public <T> T get(String name, Class<T> contract) {
        throw new NoSuchElementException();
    }

    public <T> T get(Class<T> contract) {
        throw new NoSuchElementException();
    }
}

Here is a simple implementation of a context. It is not intended to be thread-safe nor to be scalable. In order to be improved, cache can be used in the method get(contract).

private static class ContextImpl implements Context {

    private final Context parent;

    private final Map<String, Object> objects;

    public ContextImpl(Context parent) {
        this.parent = parent;
        this.objects = new HashMap<String, Object>();
    }

    public void register(String name, Object o) {
        objects.put(name, o);
    }

    public Object get(String name) {
        if (objects.containsKey(name)) {
            return objects.get(name);
        }
        return parent.get(name);
    }

    public <T> T get(String name, Class<T> contract) {
        if (objects.containsKey(name)) {
            return contract.cast(objects.get(name));
        }
        return parent.get(name, contract);
    }

    public <T> T get(Class<T> contract) {
        for(Object o : objects.values()) {
            if (contract.isInstance(o)) {
                return (T) o;
            }
        }
        return parent.get(contract);
    }

    public Context getParent() { return parent; }
}

We can notice that for each get() method, either the method internally succeeds or it calls the get() method of the parent. And as the null context is the parent of every context, if each get() fails, a NoSuchElementException is thrown.

Example

Here is some examples that use our context implementation:

Context context = Context.create();

context.register("message-en", "hello");
context.register("message-fr", "salut");

System.out.println(context.get("message-en"));               // display: hello
System.out.println(context.get("message-fr", String.class)); // display: salut
System.out.println(context.get(String.class));               // display "hello" or "salut"

Now, let’s get a more concrete example. Suppose that you manage message persistency through a DAO. We have a DAO based on the interface MessageDao and using the XML medium. Here is the preparation of the DAO in a main context.

public void init() {
    Context mainContext = Context.create();

    MessageDao messageDao = new XmlMessageDao(file);
    mainContext.register("messageDao", messageDao);
}

In the main context, the element lifespan is the same as the main component one.

Now, to call the sub-component, we have to prepare a specific context. But we do not want to copy/paste the main context. So, we set the parent of the newly created context as the main context and build the new context.

public void callComponent() {
    Context context = Context.create(mainContext);

    // specific context composition for the sub-component call...

    component.call(context);
}

Now, we wanted to use the DAO in a sub-component.

public void call(Context context) {
    // create an entity
    Message myMessage = new Message():

    // save it
    context.get(MessageDao.class).save(myMessage);
}

For the last line above, we can notice that if an object is a singleton inside a context, there are different ways to access it, especially if it is part of an inheritance tree. Indeed, we might use the class XmlMessageDao, instead of MessageDao. But in this case, the use of MessageDao is better because it helps to decoupled the application from the implementation of its components.

Annexe

Written by fsarradin

2010/09/15 at 01:24

About Sustainable Software Development

I try to explore some aspect around sustainable development applied to IT. At present, I see two ways of understanding this term.

Green IT: respect to the environment

This is the first thing I think of when I hear “sustainable development”: adopt a behavior that take care of the environment. We are not at the level of the infrastructure, that is the usual field when we speak about green IT. Here, I think about the way we program: the choice should be made across the algorithms and the patterns that do not increase so much the computer temperature and that consume less resources.

  • Choose a low-consumption algorithm
  • Have a behavior that conducts to respect the environment
  • Choose a greener language implementation

The language and more specifically the way it is implemented (i.e. the way your source code is compiled and interpreted) has its importance in relation to green IT. One day, I have heard of a company that has abandoned PHP. Indeed, at this time, the way the PHP engine was implemented implied a high-rate in energy consumption.

But green IT drives us to difficult equations. Certain modifications in the code, in order to turn it to green code, can turn the other part of the code to high-rate in energy consumption. What are the good behavior that a developer should adopt in order to become a green developer? May we, one day, see a label for eco-software craftsman?

IT craftsmanship

There is another aspect behind the “sustainable development” that can be represented by a question: How long will your code last? It is of the interest of a project to create a code that last in time. Not only for the developer himself but also for others. So, there is the question to become a perfect “software craftsman“.

  • The code source is a document that describes how the software works. Thus, write your code so that any other sources of document (specifications, code comments, tests) become useless. By acting like this, any developer will not spent too many time to understand your code and it will not require heavy maintenance in order to evolve.
  • Use of: best practices, design pattern, struggle against anti-pattern, some idioms. Do not use them without a preliminary reflexion, because a pattern can easily turned to a anti-pattern or an idiom can make your code unreadable.

Again, the software craftsmanship is a difficult exercise. On the one side, it requires a strong experience in software development. On the other side, more and more techniques or practices emerge in order to help you create a clean code. I think specifically about TDD, TDR, refactoring, and other practices. Furthermore, IT tools to analyze your code (Checkstyle, PMD, or Sonar in the Java world) help you to make progress in order to provide a better code.

Conclusion

Regardless on how “sustainable IT development” is understood, it requires experience and practice, because we have to think about a wide range of parameters that acts on how the resources are consumed or how the other developers will perceive our code. Nevertheless, there are tools to help us producing clean code and if you are confident in the future, tools will be created to help us producing green code.

Written by fsarradin

2010/08/02 at 18:06

Being Agile in a Non Agile Environment (Part 1)

Introduction

I was recently asked to manage a project in autonomy, in a view to develop a software component. The deadline was extremely short in relation to the expected features. In order to manage the project correctly, I needed a method that would help me to stay focus on the project objectives, and that would be adaptable to the situation. In a view to meet such requirements, I could have used methods like XP or Scrum. But, they are rather intended for project management with a team, not for a lonely developer.

I had already used a method of my own that met such requirements. It was a method that incorporated some best practices from XP, Scrum, and Kanban. So, I decided to use this method and to enhance it not only to make it as agile as possible but also to improve my own performance.

In these series of posts, I describe the method I have used to manage a project in autonomy. In this post, I will stay focus on the principles and previous work, while I will ask myself about the agileness of this method. In the next posts, I will spent time to present how I organize the project and how it evolves through the use of tools like spreadsheets. Then, I will detail the development phase.

Motivation and Principles

I have developed such a method, because I have noticed some difficulties when I have to achieve a significant project. The major difficulty was to have a better focus on the objectives. Sometimes, I’m starting a project with a high productivity. But, all along the development, I should test different implementations in order to provide the best solution. By doing this, I lost little by little the main thread of the project. And at the end, I’m working on a different project without realizing.

Another difficulty I have experienced was the lack of communication especially with the managers. If you do not communicate or if you do not provide the good information, and even if you do not point out the difficulties, you are going to develop an application that is not what is expected. You are like a fly without a head! Some questions about decision to take in term of implementation are best answered by other developers. Other questions need an advice of a business analyst. And some management difficulties need decision of the managers in order to point out the priorities.

By working on a long and urgent project, it is difficult, even impossible, to get an accurate planning from the start. In such a case, the planning should enumerate the main tasks, but it has to be relatively vague. The planning may change all along the project: tasks may appear or disappear, others may be shorten or last a longer time. Thus, to provide an accurate planning, it is the same thing as to invest in risky assets. In the same time, you have to respect the imposed deadline. So, if your project is defined in term of tasks, in order to control your tasks and thus to control your time, you need flexibility in your planning.

For a better method, it is interesting to have feedbacks of the work you have done. One idea is to use the communication. Another idea is to collect data of your abilities and limits during the project. This will help you to make assumptions about your abilities for the rest of the project and improve your performance. Furthermore, these collected data enhance the communication with the rest of the team.

From these preceding points, we can infer that it is interesting to increase the perception of your project. In the one hand, you know what you have done, on the hand, you know where you are going to. By doing this, you will not lose the focus on the objectives and you will be kept aware to every opportunities and/or difficulties that appears all along the project.

There is a last point. Things getting better if you’re motivated. As Confucius said:

Choose a job you love, and you will never have to work a day in your life.

— Confucius

A good way to get motivated is to see your project rather like a game than like a pain. And the best to see this, it is to turn your project management so it looks like a game. Thus, if the programming seems boring for you, you can make things funnier with such a project management.

Is a method based on these principles an agile method?

So, you are alone and you are the team. You have to self-organize yourself. But, with the principles I have enumerated above, can you claim that you are Agile? These principles favour the interaction with the people in your environment (your local customer),  because you are supposed to communicate. You are helped to be motivated by your work, because you perceive it like a game, and the feedbacks help to enhance your performance. Moreover, the flexibility principle and the fact that you have an enlarge perception provide you a fast response to change. Moreover, the fact that you are focused on the objectives helps you to deliver a working software.

In fact, there is a missing Agile principle for me: deliver a working software and  deliver it frequently. According this principle, your planning should be created so you deliver frequently a usable software, component, or framework. This is especially important in order to test the integration of your project in the rest of your development or those of your customer as often as possible (that is why we speak about continuous integration). This is also important if another team is waiting your implementation. If things are well done, you can already deliver a bundle version, before you deliver a fully functional version.

Can you soon be agile in a non agile environment?

The method I want to present is not the only one. There are already others.

There is the Personal Software Process (PSP) of the Software Engineering Institute (SEI). This institute is best known for CMMI. PSP provides to the developer methods to drive his project to success. But PSP is not considered as an Agile method. Furthermore, it is complicated, full of documentations. In response to this, Y. Dzhurov et al. have written a paper called Personal Extreme Programming – An Agile Process for Autonomous Developers. This method, also called PXP, is a kind of refinement of the XP method adapted to one-person team. It is combined with the Personal Software Process (PSP). It has been proven that this method is more efficient than an ad hoc method. A test has been made on the basis of Visual Studio.

You can find over Internet a site describing the method Personal Kanban. It is a good method based on the Kanban method that helps to visualize your project. It is not dedicated to IT processes but more generally for personal productivity. This is a good base to start. But for me, it lacks some statistics about your own performances during the project and other feedbacks, because Kanban provides only a snapshot of your work in progress (WIP). Other methods in this case exist like Pomodoro or Getting Things Done (GTD). They are not considered as agile methods, but they help you to improve your productivity.

Conclusion of the Part 1

In this post, we have seen principles that can be helpful for a developer in order to manage a project in autonomy:

  • stay focus on the objectives,
  • communicate with the team,
  • have flexibility during the project,
  • collect feedbacks on your abilities,
  • increase the perception of your project,
  • be motivated by your work, perceive the project as a game,
  • deliver frequently.

We have seen that this principles helps to make you an Agile developer. In the next posts, we will see a way to organize your project according to these principles.

Written by fsarradin

2010/07/06 at 15:38