Libellés

lundi 6 juin 2011

TopCoder Arena

Ce soir je vais sur le site de recrutement de Google, et dans la section Préparation de l'entretien, Google nous conseil de s’entraîner sur TopCoder Arena.

Aller je tente.

Après un processus d'enregistrement super chi..., où l'on me demande ma couleur de peau (merci les Etats-Unis) je peux enfin avoir des accès.

Top Coder Arena est une Applet Java qui affiche des problèmes informatiques à résoudre. On se croirait en cours pendant un TD d'info. L'appli permet de compiler et de tester son code avant de le soumettre.

J'ai commencé facile avec un problème à 150 points. Je vous le donne :


Problem Statement
    
***Note: Please keep programs under 7000 characters in length. Thank you


Class Name: HowEasy
Method Name: pointVal
Parameters: String
Returns: int

TopCoder has decided to automate the process of assigning problem difficulty
levels to problems. TopCoder developers have concluded that problem difficulty
is related only to the Average Word Length of Words in the problem statement:

If the Average Word Length is less than or equal to 3, the problem is a 250
point problem.
If the Average Word Length is equal to 4 or 5, the problem is a 500 point
problem.
If the Average Word Length is greater than or equal to 6, the problem is a 1000
point problem.

Definitions:
Token - a set of characters bound on either side by spaces, the beginning of
the input String parameter or the end of the input String parameter.
Word - a Token that contains only letters (a-z or A-Z) and may end with a
single period. A Word must have at least one letter.
Word Length - the number of letters in a Word. (NOTE: a period is NOT a letter)

The following are Words :
"ab", "ab."

The following are not Words :
"ab..", "a.b", ".ab", "a.b.", "a2b.", "."

Average Word Length - the sum of the Word Lengths of every Word in the problem
statement divided by the number of Words in the problem statement. The
division is integer division. If the number of Words is 0, the Average Word
Length is 0.

Implement a class HowEasy, which contains a method pointVal. The method takes
a String as a parameter that is the problem statement and returns an int that
is the point value of the problem (250, 500, or 1000). The problem statement
should be processed from left to right.

Here is the method signature (be sure your method is public):
int pointVal(String problemStatement);

problemStatement is a String containing between 1 and 50 letters, numbers,
spaces, or periods. TopCoder will ensure the input is valid.

Examples:

If problemStatement="This is a problem statement", the Average Word Length is
23/5=4, so the method should return 500.
If problemStatement="523hi.", there are no Words, so the Average Word Length is
0, and the method should return 250.
If problemStatement="Implement a class H5 which contains some method." the
Average Word Length is 38/7=5 and the method should return 500.
If problemStatement=" no9 . wor7ds he8re. hj.." the Average Word Length is 0,
and the method should return 250.
Definition
    
Class: HowEasy
Method: pointVal
Parameters: String
Returns: int
Method signature: int pointVal(String param0)
(be sure your method is public)
    


Et je vous donne ma solution.


import java.util.regex.*;

public class HowEasy{

Pattern regex = Pattern.compile("[a-zA-Z]+\\.?$");

public int pointVal(String problemStatement){
String[] words = problemStatement.split(" ");
int matchingWords = 0;
int wordLength=0;
for(String word: words){
Matcher m =regex.matcher(word);
if(m.matches()){
matchingWords++;
wordLength+=word.length();
}


}

if(matchingWords==0) return 250;

int avgWordLength = wordLength / matchingWords;
if(avgWordLength<=3){
return 250;
}else if(avgWordLength==4){
return 500;
}else if(avgWordLength==5){
return 500;
}else{
return 1000;
}


}

}


150 points / 250, c'est pas terrible, je peux mieux faire.
Je pense que j'ai oublié d'enlever les points pour calculer la longueur des mots.

A vous !!!

lundi 16 mai 2011

Expo Soufflez du vert à Paris

Une petite info qui n'a rien à voir avec l'informatique pour une fois.

Aux tuileries du 25 au 29 mai aura lieu une exposition sur les jardins et les designs extérieurs.

Voici une des expositions à découvrir absolument :


http://soufflez-du-vert.github.com/ (site prochainement accessible)

Et oui le site est hébergé par Github ;)

lundi 9 mai 2011

Dig en Java

DNSJava est une API JAVA permettant de faire des résolutions de domaines.

DNSJava offre également une implémentation équivalente à dig (voir les sources)

Si vous souhaitez parser le contenu d'un DIG en Java pour récupérer les IPs des serveurs, je vous conseil plutôt d'utiliser l'API de DNSJava.
Vous aurez une représentation objet du DIG qui vous permettra de ne récupérer que ce qui vous intéresse vraiment.

Voici un exemple écrit en groovy qui fait l'équivalent d'un 'dig google.com'


import org.xbill.DNS.*;

@Grab(group='dnsjava', module='dnsjava', version='2.1.1')

SimpleResolver res = new SimpleResolver();
Record rec = Record.newRecord(Name.fromString("google.com", Name.root), Type.A, DClass.IN);
Message query = Message.newQuery(rec);
Message response = res.send(query);
println("----------------------------------------------------------");
for (Record record : response.getSectionArray(1)) { // ANSWER SECTION
println(record.rdataToString());
}
println("----------------------------------------------------------");
println(response.toString()); //THE WHOLE DIG


Et voici le résultat affiché :

--------------------------------------------------------
209.85.227.106
209.85.227.103
209.85.227.105
209.85.227.104
209.85.227.99
209.85.227.147
--------------------------------------------------------
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 53158
;; flags: qr rd ra ; qd: 1 an: 6 au: 0 ad: 0
;; QUESTIONS:
;; google.com., type = A, class = IN

;; ANSWERS:
google.com. 300 IN A 209.85.227.106
google.com. 300 IN A 209.85.227.103
google.com. 300 IN A 209.85.227.105
google.com. 300 IN A 209.85.227.104
google.com. 300 IN A 209.85.227.99
google.com. 300 IN A 209.85.227.147

;; AUTHORITY RECORDS:

;; ADDITIONAL RECORDS:

;; Message size: 124 bytes

vendredi 15 avril 2011

Grails thumbnail : Reduire une image dans grails en gardant une bonne qualité

En java ce n'est pas forcement facile de trouver une librairie pour réduire des images en gardant une bonne qualité.

Heureusement il existe le projet Java Image Scaling qui a sa librairie sur maven.
http://code.google.com/p/java-image-scaling/


Maintenant voici comment intégrer Java Image Scaling dans grails : un jeu d'enfant :)

Ajouter la dépendance suivante dans grails-app/conf/BuildConfig.groovy


runtime 'com.mortennobel:java-image-scaling:0.8.5'


Dans votre controller ajoutez le bout de code suivant :


/**
* Return the content of screen shot
*/
def viewScreen = {
File img = new File("myImage.png")
response.contentType = 'image/png'
if(params.thumbnail){
BufferedImage inputImage = ImageIO.read(img);
BufferedImage rescaledImage = new MultiStepRescaleOp(DimensionConstrain.createMaxDimension(355,500)).filter(inputImage, null);
def outputStream = new ByteArrayOutputStream()
ImageIO.write(rescaledImage, "png", outputStream);
response.outputStream << outputStream.toByteArray()
}else{
response.outputStream << img.bytes
}
}

jeudi 14 avril 2011

Firefox4 (Iceweasel4) sur Debian Squeeze

La méthode est simple il suffit de saisir les commandes suivantes sous root :


echo "deb http://mozilla.debian.net/ squeeze-backports iceweasel-4.0" > /etc/apt/sources.list.d/firefox.list

apt-get update

apt-get install iceweasel

Selenium JUnit4 et Maven

Voici un exemple de test Junit qui démarre un Serveur Selenium puis execute un ensemble de tests.

Je prefère ce type de configuration, plutôt que d'écrire 50 lignes de XML dans maven afin de lancer un serveur selenium : http://blog.xebia.fr/2011/02/18/automatiser-les-tests-selenium-avec-maven/

import com.thoughtworks.selenium.DefaultSelenium;
import org.junit.*;
import org.openqa.selenium.server.SeleniumServer;

import static org.junit.Assert.*;


public class DemoTest {

private static SeleniumServer server;
private DefaultSelenium selenium;

@BeforeClass
public static void startSeleniumServer() throws Exception {
System.out.println("START Selenium Server");
server = new SeleniumServer();
server.start();
}

@Before
public void fixture() {
selenium = new DefaultSelenium("localhost", 4444, "*firefox" , "http://google.fr/");
selenium.start();
}

@Test
public void testWhatYouWant() throws Exception {
...
}

@Test
public void testWhatYouWant2() throws Exception {
...
}

@After
public void tearDown() throws Exception {
selenium.stop();
}

@AfterClass
public static void stopSeleniumServer() throws Exception {
server.stop();
}
}



Voici mes dépendances maven :


<dependencies>
<dependency>
<groupid>junit</groupid>
<artifactid>junit</artifactid>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.seleniumhq.selenium</groupid>
<artifactid>selenium-server</artifactid>
<version>2.0b3</version>
</dependency>
<dependency>
<groupid>org.seleniumhq.selenium</groupid>
<artifactid>selenium-remote-control</artifactid>
<version>2.0b3</version>
</dependency>
</dependencies>

jeudi 24 mars 2011

Script SQL en Groovy

Voici un exemple de script Groovy se connectant sur une base de donnée MySQL avec Groovy Grape :


import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;

@GrabConfig(systemClassLoader=true)
@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
@Grab(group='org.springframework', module='spring-jdbc', version='3.0.5.RELEASE')


DataSource dataSource = new SimpleDriverDataSource(
Class.forName("com.mysql.jdbc.Driver").newInstance(),
"jdbc:mysql://localhost:3306/myDatabase",
"login",
"password");

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
println jdbcTemplate.queryForList( """SELECT 1;""" )


C'est très pratique pour debugguer les erreurs du type :

Caught: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Last packet sent to the server was 0 ms ago.
at test.run(test.groovy:19)