XD blog

blog page


2014-01-26 Inégalités

Le dernier forum de Davos a souligné l'accroissement des inégalités (Les dangers de la montée des inégalités au menu du Forum de Davos). La tranche des plus 1% les plus riches auraient capté l'essentiel des richesses créées depuis 20 ans et la statibilité et la durabilité de la croissance mondiale pourraient en être affectée. Ce n'est sans doute pas la dernière crise financière qui aura inspiré cette réflexion - à moins que sept années n'eussent été nécessaire pour formuler cette assertion - ou peut-être est-ce le mouvement We are the 99% qui a manifesté plusieurs mois en 2011. Plus récemment, les habitants de San Francisco se rebellent contre la Silicon Valley. La hausse des prix des logements altère la mixité sociale dans la plupart des grandes villes. Le fait de posséder un iPhone est aussi révélateur du niveau de revenu de son propriétaire. Qui sait si les ingénieurs d'Apple ne seront pas bientôt les seuls à pouvoir s'offrir un iPhone (Une tirelire à 150 milliards de dollars pour Apple).


more...

2014-01-24 On y va ! Oui mais comment ?

Le mot réforme est dans l'air du temps depuis la dernière allocation du président. Il faut réformer, simplifier l'enchêtrement que le temps a laissé faire. Mais comment fait-on ? Il est souvent plus simple d'apprendre à manoeuvrer un gouvernail tordu que de le réparer tout entier. Et comment le changer en pleine mer ? Définir l'objectif puis chercher à l'atteindre. On procède souvent comme ça. J'écoutais l'émission Peut-on changer l'école ?. L'interlocateur souligne que nous faisons la plupart du temps une assez bonne analyse des problèmes mais nous passons peu de temps à réflechir sur le cheminement à suivre pour mettre en place une réforme. Bref, la transition, le petit paragraphe qu'on écrit vite entre la thèse et l'anti-thèse, entre la synthèse et la conclusion, entre... Et si on n'arrivait jamais à l'écrire, arriverait-on jamais à la conclusion ? Dans la vrai vie, on zappe tout sauf la conclusion. Ca nous laisse des pages de transitions à remplir.

Pour finir, une citation autour de réforme, elle est extraite de La crise de l'intelligence de Michel Crozier qui commente le refus de Jacques Delors de se présenter à l'élection présidentielle : Il a renoncé parce qu'il pensait ne pas avoir tous les éléments nécessaires à la mise en oeuvre des réformes qu'il estimait indispensables. Il s'est donc posé en planificateur qui n'avait pas les moyens de ses objectifs plutôt qu'en stratège qui accepte d'analyser les probabilités de transformations réelles à l'intérieur du système. De ce point vue "adémocratique", effectivement, aucune réforme n'est jamais possible.

2014-01-22 Automatically saving emails on a local folder

When my student have their exams, I receive many emails with their solution attached to them. I avoid downloading them all because it is manual. However, a couple of days ago, I thought it might be useful if I write the tool which does it for me (I'm still refusing to do it manually). I ended up writing a Python module called pymmails. To get the email from my students, I just had to execute the following script:

from pyquickhelper import fLOG
from pymmails import MailBoxImap
fLOG(OutputPrint=True)
user = "your.email"
pwd = "password"
server = "imap.your_provider.ext"
box = MailBoxImap(user, pwd, server)
box.login()
box.dump_html(folder="students_exam", pattern='FROM "ensae" SINCE 1-Dec-2013')
box.logout()

All the attachments were in a single folder. I hope I'll remember my own trick next year or maybe I'll use jinja2 or even pelican to make it better.


more...

2014-01-21 What editor with Python

I usually use SciTE when programming Python. It is simple and fast. Plus, I usually do not use a debugger. I sometimes use Notepad++ but the shortcuts are different and I never really tried to change them. I once tried PyScripter but the project seems to be intermittently maintained.

I recently tried the free version of PyCharm and it is very to use. Create a project is not difficult, adding existing files too. And it was possible to change the shorcuts as I wanted. One feature I liked was the easy installation of setuptools and pip. The professional version offers support for django.

I tried The Eric Python IDE a long time ago but it seemed too complex for my needs. Python Tools for Visual Studio is a also nice integration, interesting for big projects. I'm surprised to see features such as creating a file setup.py, creating a sphinx project, using cx_Freeze. I'm wondering if I'm not going to switch from an editor to another one depending on what features I will need for the current project. To conclude, if you want to use a tablet, you can use Python Anywhere. You can check other alternative on Wikipedia. Don't forget to check the date of the latest release first. Older than a year is not a good sign.

If you do machine learning a lot, it might be interested to use an environment designed for that purpose such as WinPython. It includes Spyder which has been updated to Python 3.3 last year. It also includes IPython with the notebook which makes it easier to test some of the steps I went through in this previous blog More about interactive graphs using Python, IPython, ...

2014-01-18 Framework for Mobile Application

What framework to choose if you want to build a mobile application which will save you some time while deploying on multiple phones? (Android, Black Berry, iPhone, Windows Phone). I'm not sure there is a perfect answer and it will probably change in a couple of months. However, this what I found. I was looking for answers. Which phones does it support today? Where can you develop your application? Which language? How to build? How to deploy? Cost? I limited my study to the following frameworks (according to a friend, the others are not as mature):


more...

2014-01-16 La nuit des temps n'est pas si loin

Je l'ai lu il y a quelque temps mais j'ai dévoré La nuit des temps de Barjavel. Au dela de l'histoire, c'est aussi cet ordinateur capable de traduire toute langue en une autre qui m'a fasciné. Je ne sais pas ce que Barjavel aurait dit si on lui avait demandé quand ce serait effectivement possible. On n'en est probablement pas très loin... mais parlons d'abord de ce qui est accessible facilement aujourd'hui.

J'écoutais France Inter il y a deux jours Xavier Bertrand. A vrai dire, j'ai oublié ce qu'il a dit, j'ai juste retenu qu'il raisonnait non pas par rapport au contenu d'un propos mais par rapport à celui qui le prononçait. Peu importe, je voulais voir s'il était possible de décrypter des vieux podcasts du même bonhomme pour voir ce qu'il disait du président... Je n'en ai pas trouvé, probablement trop vieux et effacés. Je n'ai trouvé que Jean-François Coppé. Sur la page de France Inter, on peut lire deux extraits dont on ne sait pas quand dans l'émission ils ont été extraits. Qu'à cela ne tienne, Barjavel n'est pas si loin...


more...

2014-01-15 Copie d'écran automatique avec Selenium ou Splinter

On a parfois besoin de faire des copies d'écran, régulièrement, et cela devient toujours la même routine : aller sur un site internet, faire une copie d'écran et la copier dans un fichier. Et si on a le courage, limiter la zone à celle désirée. Lorsqu'il s'agit de faire une copie d'écran d'un site web, il est possible d'automatiser.

Le module selenium a été développé dans le but de tester un site internet. Il permet de reproduire une séquence d'événements (clic, clavier, ...) et d'observer le résultat. Entre autre chose, il permet de faire une copie d'écran de ce site. Le module selenium a une déclinaison en Python. Et à l'aide d'un petit script, il est possible de faire une copie d'écran de n'importe quel site web :


more...

2014-01-12 R or Python

Should you use R or Python? I won't give a precise answer except a reference to this blog post: Python Displacing R As The Programming Language For Data Science. To summarize, if you are a statistician, you are already using R. However, if you are not a statistician but you need statistics, you are probably wondering if you should use R and another language or just another language. R is not very well designed as a programming language and is not very suitable to manipulate files, create a web server or games... Using Python for everything avoids switching to another language. It avoids converting the data into various formats between the two languages.

With pandas, numpy, scipy, scikit-learn, matplotlib, IPython, many common statistics routines are available in Python. In the last two years, it became a really strong alternative to R. In the next years, SAS should less and less used (see Forecast Update: Will 2014 be the Beginning of the End for SAS and SPSS?). Computers speed and memory are not an issue anymore with others alternatives. Plus, it is expensive. I would also look at Julia (+ Julia Studio) which seems to be a promising language. I discovered at MCMSki IV. But maybe the future will be dedicated languages such as BUGS for bayesian models.

Finally, some articles about R and Python:

2014/06/30: I recommend reading Numeric matrix manipulation, The cheat sheet for MATLAB, Python NumPy, R, and Julia

2014-01-01 Frameworks for games in Python

Implementing a simple game in Python is not too difficult if you consider using a module such as pygame. With the multiplicity of devices (computers, laptop, tablets, phones), we may wonder whether or not the same code will work on many of them. So far, I was able to find a couple of modules to implement a game. I mean display graphics, play music or videos, intercept events coming from the mouse or the keyboard:

If the game requires 3D graphics, those extensions will have to associated with pyOpenGL. If my preference goes to pygame mostly because I know it, I would consider pysdl2 because SDL2 now supports Android and iOS (iPad, iPhone). GitHub and Bitbucket are now very popular. You can find examples just by searching the module you want to use: pygame on github, pygame on bitbucket.

However, there exist others solutions. They might need more effort to be used but they seem promising as they could really make deployment on many platform easy. kivy seems very promising. A game implemented with that framework can be deployed on Linux, Windows, Android, iOS. It is also available on Raspberry Pi. kivy allows the programmer to interact the same way with any device. The last one I found is pythonista. It was designed to easily implement Python programs on iOS (iPad), not necessarily games. It only works with Python 2.7 but I hope Python 3.x will be soon supported.

A last solution would be to use a HTML/Javascript solution packaged in a service but maybe, it goes beyond python and the scope of this post.

2013-12-30 Bitcoin

Le Bitcoin est la première monnaie électronique à susciter autant d'intérêt. Si vous voulez découvrir comment elle fonctionne, quel rôle elle a pu jouer durant la crise financière à Chypre, alors vous devriez sans doute écouter l'émission Place de la Toile du 12 décembre (France Culture) puis lire le blog Petit cours de Bitcoin pour les nuls. Il y a aussi l'épisode 13 de la saison 3 de la série The Good Wife qui s'intitule Bitcoin for dummies. Le sujet aurait problablement été plus intéressant s'il avait été traité par la série Ally McBeal qui n'aurait probablement pas utilisé la même astuce pour défendre son client.

L'arrivée de l'informatique et d'internet bouleverse quelques modèles économiques. La presse, la musique peinent à trouver un nouvel équilibre. On explore d'autres horizons, parfois depuis plus de 40 ans comme ce concept de supermarchés où les clients sont aussi les employés : FoodCoop (FoodCoop dans rue89) qui pourrait se décliner à Paris avec CoopLaLouve. Ce projet a cherché son financement sur KissKissBankBank qui sort des circuits traditionnels. Zach Braff, le réalisateur de Garden State a utilisé ce système pour financer son prochain film pour, dit-il, garder son indépendence.

2016/05/17, un lien vers une infographie que m'a envoyée Bastien Hudelot : Bitcoin, la crypto-monnaie qui monte

2013-12-29 Big or small modules in Python, pyrsslocal

It is not always easy to determine a good size for a module or a set of modules. Should it be kept as a single bloc which comes alone or a set of smaller modules? It is easier to understand a smaller modules. It usually limits itself to a small set of similar functionalities. However, extending a small module is faster than starting a new one, it avoids spending too much time setting up the installation steps, documentation automation, dependencies with others modules. Small modules grow, especially if you work late on them on your free time.

pypi makes it simple to install a module and its dependencies, GitHub helps to fork some existing module which needs to be fixed for a specific usage. That's why I started to split my own toolbox. Does it worth the effort knowing I'm the only one to use it? Probably not but, for my teachings, I think I will not be reluctant anymore to create a new small project for a specific purpose.

I created or updated three modules:

2013-12-15 Quelques exercices de préparation à l'examen (5)

Lorsqu'on cherche un élément dans un tableau, c'est généralement pour retrouver sa position. Supposons maintenant que cet élément soit présent en plusieurs exemplaires et qu'on veuille toutes les positions où il est présent.

def positions(liste, element) :
    ...
    return une liste
    
l = [ 4,3,3,6,4,3 ]
print ( positions(l, 3) ) # affiche [1,2,5]

Dans un second temps, on veut transformer la liste l en un dictionnaire de sorte que la fonction positions ne contienne plus de boucle. Quelle est la solution la plus rapide ?


more...

2013-12-14 Quelques exercices de préparation à l'examen (4)

On reprend le même texte que celui de l'exercice précédent. On veut connaître le nombre maximum de mots qu'on peut trouver entre deux mots commençant par une voyelle.

# source du texte : http://www.gutenberg.org/files/1567/1567-h/1567-h.htm#link2H_4_0017
texte = """They are rattling breakfast plates in basement kitchens,
And along the trampled edges of the street
I am aware of the damp souls of housemaids
Sprouting despondently at area gates.
The brown waves of fog toss up to me
Twisted faces from the bottom of the street,
And tear from a passer-by with muddy skirts
An aimless smile that hovers in the air
And vanishes along the level of the roofs.""".replace("\n"," ").lower().split()

def nombre_de_mot_maximum(mots) :
    ...
    return un_nombre 

more...

2013-12-13 Quelques exercices de préparation à l'examen (3)

On veut calculer la longueur moyenne des mots ayant le même nombre de voyelles. Le résultat est un dictionnaire où chaque élément vérifie :

La fonction qui compte le nombre de voyelles d'un mot est décrite sur cette page : exercice 2.

# source du texte : http://www.gutenberg.org/files/1567/1567-h/1567-h.htm#link2H_4_0017
texte = """They are rattling breakfast plates in basement kitchens,
And along the trampled edges of the street
I am aware of the damp souls of housemaids
Sprouting despondently at area gates.
The brown waves of fog toss up to me
Twisted faces from the bottom of the street,
And tear from a passer-by with muddy skirts
An aimless smile that hovers in the air
And vanishes along the level of the roofs.""".replace("\n"," ").lower().split()

def moyenne_longueur_pour_chaque_nombre_de_voyelles(mots) :
    ...
    return un dictionnaire 

more...

2013-12-12 Quelques exercices de préparation à l'examen (2)

On veut écrire une fonction qui compte le nombre de voyelles dans un mot.

def compte_voyelles(mot):
    ...
    return le nombre de voyelles
    
print (compte_voyelles("oui"))  # doit afficher 3
print (compte_voyelles("non"))  # doit afficher 1

more...
<-- -->

Xavier Dupré