Become a Guitar Hero with The Coder's Breakfast !

I'm in the process of learning scales, modes and chords for the guitar, but these aren't easy to remember. Being a developer, I thought I could write a small program to help me understand how they are built, and where I can find the related notes on the guitar neck.
So I spent a couple of hours on it tonight (mainly to find documentation on music theory) and here it is : a small companion program that can calculate and display any chord in any mode and key.

The API is very compact and ultra-easy to understand :
(A "Scale" is basically a collection of Notes. It is used to contain notes for whole Scales, Chords, etc.)

  1. Scale scale = Scale.of(Note.C);
  2. System.out.println("Scale of C : " + scale);
  3.  
  4. Scale mode = Mode.IONIAN.of(scale);
  5. System.out.println("Scale of C in "+Mode.IONIAN+" mode : " + mode);
  6.  
  7. Scale chord = Chord.major(mode);
  8. System.out.println("Major chord : " + chord);
  9.  
  10. Guitar.display(chord, Guitar.STANDART_TUNING, 12); // 12 frets

And here is the result :

Scale of C : [C, C#, D, D#, E, F, F#, G, G#, A, A#, B]
Scale of C in IONIAN mode : [C, D, E, F, G, A, B]
Major chord : [C, E, G]
                        3             5             7             9                    12  
--E --||------|------|--G --|------|------|------|------|--C --|------|------|------|--E --|
------||--C --|------|------|------|--E --|------|------|--G --|------|------|------|------|
--G --||------|------|------|------|--C --|------|------|------|--E --|------|------|--G --|
------||------|--E --|------|------|--G --|------|------|------|------|--C --|------|------|
------||------|------|--C --|------|------|------|--E --|------|------|--G --|------|------|
--E --||------|------|--G --|------|------|------|------|--C --|------|------|------|--E --|

The source code is available for download just below.
This ain't rocket science but hey, I thought It might be cool to share it with you :)
Comments and suggestions welcome !

Java Quiz #41 : time attack !

(FR)
La cellule d'expertise de votre entreprise a développé un Timer pour que vous puissiez mesurer les performances de votre application, mais... ils ont juste oublié de fournir une méthode pour récupérer la valeur du compteur ! Comment faire pour l'afficher une fois la mesure prise ?
Vous ne pouvez intervenir que sur la classe Quiz41, et il est interdit de modifier le code existant ou d'utiliser la Réflexion.
Bonne chance !

(EN)
The Architects Team developed a Timer class to help you measure the performance of your code, but... they forgot to provide a method to get the timer's value ! How can you get it back and print it in the console ?
You can only alter the Quiz41 class ; modifying the already existing code or using Reflection is forbidden.
Good luck !

  1. public class Quiz41 {
  2.  
  3. public static void main(String[] args) throws InterruptedException {
  4.  
  5. Timer timer = new Timer();
  6. timer.start();
  7. Thread.sleep(new Random().nextInt(2000));
  8. timer.stop();
  9.  
  10. }
  11. }
  1. public class Timer {
  2.  
  3. private TimerThread thread = new TimerThread();
  4.  
  5. public void start() {
  6. thread.start();
  7. }
  8.  
  9. public void stop() {
  10. thread.stop();
  11. }
  12.  
  13. public static class TimerThread extends Thread {
  14. private AtomicInteger counter = new AtomicInteger(0);
  15.  
  16. @Override
  17. public void run() {
  18. try {
  19. while (!isInterrupted()) {
  20. counter.incrementAndGet();
  21. Thread.sleep(100);
  22. }
  23. } catch (InterruptedException e) {
  24. interrupt();
  25. }
  26. }
  27.  
  28. public int getCounter() {
  29. return counter.get();
  30. }
  31. }
  32. }
Lire la suite...

Java Quiz #40

To please your Project Manager, a former developer (yeaaars ago), you sometimes let him help you develop some "very important" parts of your application.

Today, he's in charge of displaying "Hello World" by iterating on a list containing those words. Alas, distracted by his going on vacation this very afternoon, he forgets to add "World" to the list before starting the iteration. Trying to correct his mistake, he adds it a few lines later, but now his code unexpectedly breaks down at runtime ("this must be a JVM bug !").

A few minutes before leaving, he asks you to find a solution in his absence, with the following instructions :

  • Do not modify his existing code, it's Perfect (of course).
  • The FIXME tag shows where you're allowed to insert your corrective code
  • He must be able to understand your solution when he comes back (so

using Reflection is not an option).

Are you worth the trust of your beloved Manager ?

  1. final List<String> list = new ArrayList<String>() {{ add("Hello"); }};
  2. final Iterator<String> iterator = list.iterator();
  3. System.out.println(iterator.next());
  4. list.add("World");
  5. // FIXME : work here while I'm sunbathing
  6. System.out.println(iterator.next());

Hints - Keep in mind that :

  • the iterator is declared final
  • this is only a code fragment, so you cannot use System.exit(0) or return; you wouldn't like your application to terminate prematurely, would you ?
  • since you cannot modify the existing code, you cannot delete or ignore the last line, which must print "World"

Note : I must thank Romain Revol for helping me to write this quiz. Romain successfully attended the "Heinz Kabutz's Java Specialist Master Course" training session I presented in France in June at Zenika's office.

Lire la suite...

Paris JUG "Java EE 6" par Adam Bien

La séance de juillet du Paris JUG a eu pour thème "Lightweight Killer Apps with Nothing But Vanilla Java EE 6". Elle était présentée par Adam Bien et a occupé les deux créneaux horaires (19h30 à 22h00).
Le buffet était offert par François Ostyn.

Une soirée bien intéressante, qui l'a redonné envie de jouer avec Java EE 6, malgré son passif technologique assez lourd. Je vous laisse lire le compte-rendu intégral :

Lire la suite...

Conférence : Les annotations enfin expliquées simplement

Mardi dernier, j'ai animé chez Zenika une conférence sur les Annotations.

Et le sujet est plus complexe qu'il n'y paraît. Outre les subtilités de leur syntaxe, les annotations disposent d'un outillage puissant à la compilation et au runtime, dont la maîtrise ouvre de nouvelles perspectives en termes de méta-programmation.
En particulier, j'ai démontré l'utilisation des Annotation Processors, qui permettent d'interagir avec le compilateur Javac, et de la Réflexion pour lire et injecter des annotations dynamiquement au runtime.

Apparemment, la conférence a remporté un franc succès :

  • "Très intéressant. Niveau technique avancé" A. F.
  • "Vivement le prochain projet pour qu'on mette cela en place" JP. L.
  • "Excellente présentation avec démo hardcore à la fin ;)" C. M.
  • "Très bon intervenant" S. F.

Je remercie de leur présence tous les participants qui ont pu venir.
Pour les parisiens qui n'ont pas pu avoir de place, rassurez-vous, il est possible qu'une nouvelle session soit programmée. Et pour mes lecteurs de province, mon passage est prévu dans certains JUGs d'ici la fin de l'année. Renseignez-vous et faites pression ! :)

Pour finir, j'ai le plaisir de vous offrir, en annexe de ce billet, les slides et les sources de la conférence.
Tous les commentaires sont les bienvenus !

Java Quiz #39

If you're not getting your athletic body's tanned on a beach this week, here is a small quiz to keep your brain fit.
What does this code snippet do ?

  1. public class Quiz39 {
  2.  
  3. public static void main(String[] args) {
  4. int[] array = null;
  5. try {
  6. array[0] = array[(array = createArray())[array.length - 1]];
  7. } finally {
  8. System.out.println("Array = " + Arrays.toString(array));
  9. }
  10. }
  11.  
  12. public static int[] createArray() {
  13. return new int[]{1, 2, 3, 4};
  14. }
  15.  
  16. }
Lire la suite...

Paris JUG "Holly Cummins"

Le Paris JUG accueille pour sa séance du mois de juin un invité de marque, en la personne de Holly Cummins.

Holly présentera deux séances ce soir :

  • Java Performance Tuning - not so scary after all
  • OSGi and the Enterprise: A match made in a… box?

Vous trouverez ci-dessous une retranscription en temps réel de la conférence, sous la forme d'une Wave. N'hésitez pas à participer !
(PS : Google Wave est désormais en accès libre, si vous n'avez pas de compte il vous suffit de vous inscrire !)

Lire la suite...

Java Quiz #38

Can you help the poor Exception to escape the Matrix ?
Beware, the Agents are nearby and will spot you if you attempt in any way to modify or remove the existing lines of code ! (but you may add new ones).

  1. public class Matrix {
  2. public static void getTheSpoon() {
  3. throw new java.lang.NoSuchMethodException("There is no spoon !");
  4. }
  5. }
  1. public class Test {
  2. public static void main(String[] args) {
  3. try {
  4. Matrix.getTheSpoon();
  5. } catch (Exception ex) {
  6. System.out.println(ex instanceof java.lang.NoSuchMethodException ? "You passed the Quiz !" : "You failed !");
  7. }
  8. }
  9. }
Lire la suite...

Java Quiz #37

Voici un nouveau quiz, pour bien finir le mois de mai avant d'entamer ce beau mois de juin.

La classe ColoredPoint ci-dessous pose un problème assez subtil. Lequel ?

  1. public class Point {
  2. private int x;
  3. private int y;
  4.  
  5. public Point(int x, int y) {
  6. this.x = x;
  7. this.y = y;
  8. }
  9.  
  10. public boolean equals(Object o) {
  11. if (this == o) { return true; }
  12. if (!(o instanceof Point)) { return false; }
  13.  
  14. final Point point = (Point) o;
  15. return (x == point.x && y == point.y);
  16. }
  17.  
  18. public int hashCode() {
  19. int result = x;
  20. result = 31 * result + y;
  21. return result;
  22. }
  23. }
  24.  
  25. public class ColoredPoint extends Point {
  26. private Color color;
  27.  
  28. public ColoredPoint(int x, int y, Color color) {
  29. super(x, y);
  30. this.color = color;
  31. }
  32.  
  33. public boolean equals(Object o) {
  34. if (this == o) { return true; }
  35. if (!(o instanceof ColoredPoint && super.equals(o))) {
  36. return false;
  37. }
  38.  
  39. final ColoredPoint point = (ColoredPoint) o;
  40. return (color == null ? (point.color == null) : color.equals(point.color));
  41. }
  42.  
  43. public int hashCode() {
  44. int result = super.hashCode();
  45. result = 31 * result + (color != null ? color.hashCode() : 0);
  46. return result;
  47. }
  48. }
Lire la suite...

Why I Don't Read Your Comments - Votre avis ?

Il y a deux semaines, j'étais en Crète en compagnie des meilleurs experts Java (Michael Hunger d'Allemagne, Larry Presswood des USA, Herman Lintvelt pour l'Afrique du Sud, David Gomez pour l'Espagne, et David Hallett pour la Nouvelle-Zélande), pour suivre le séminaire de certification des formateurs du Java Specialist Master Course, sous la houlette du Champion Java Heinz Kabutz.

Nous en avons profité pour enregistrer un webinar intitulé "Why I Don't Read Your Code Comments", dans lequel nous confrontons nos avis quant aux bonnes et mauvaises pratiques relatives aux commentaires de code (et pas de blagues sur mon accent anglais :). Heinz avait déjà défriché le terrain dans sa newsletter n°39, mais il était intéressant d'avoir des avis supplémentaires.

Je me tourne donc vers vous à mon tour, pour recueillir vos témoignages :

  • Quelles sont vos bonnes pratiques personnelles ?
  • Quelles sont les meilleurs et pires commentaires que vous ayez vus / écrits ?
  • Que faut-il commenter ? Est-ce une perte de temps ?
  • Quels conseils donneriez-vous à un développeur débutant ?

Cadeau bonus : gagnez au choix Pragmatic Programmer ou Clean Code.
Pour participer au tirage au sort qui aura lieu ce week-end, il suffit de laisser un commentaire intelligent sur ce billet et d'habiter la France métropolitaine. Le gagnant sera contacté par l'email associé à son commentaire.

- page 1 de 16

Archives

Contacts

Olivier Croisier : mail, site
HollyDays : mail
Wikio - Top des blogs - Logiciels libres