text
stringlengths
256
65.5k
You can use a cumulative density function to generate random numbers from an arbitrary distribution, as described here. Using a histogram to produce a smooth cumulative density function is not entirely trivial; you can use interpolation for example scipy.interpolate.interp1d() for values in between the centers of your bins and that will work fine for a histogram with a reasonably large number of bins and items. However you have to decide on the form of the tails of the probability function, ie for values less than the smallest bin or greater than the largest bin. You could give your distribution gaussian tails based on for example fitting a gaussian to your histogram), or any other form of tail appropriate to your problem, or simply truncate the distribution. Example: import numpy import scipy.interpolate import random import matplotlib.pyplot as pyplot # create some normally distributed values and make a histogram a = numpy.random.normal(size=10000) counts, bins = numpy.histogram(a, bins=100, density=True) cum_counts = numpy.cumsum(counts) bin_widths = (bins[1:] - bins[:-1]) # generate more values with same distribution x = cum_counts*bin_widths y = bins[1:] inverse_density_function = scipy.interpolate.interp1d(x, y) b = numpy.zeros(10000) for i in range(len( b )): u = random.uniform( x[0], x[-1] ) b[i] = inverse_density_function( u ) # plot both pyplot.hist(a, 100) pyplot.hist(b, 100) pyplot.show() This doesn't handle tails, and it could handle bin edges better, but it would get you started on using a histogram to generate more values with the same distribution. P.S. You could also try to fit a specific known distribution described by a few values (which I think is what you had mentioned in the question) but the above non-parametric approach is more general-purpose.
In the package for Python 2.7.4, when you go to Lib -> email -> errors.py, there is something funny in the module. # Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """email package exception classes.""" class MessageError(Exception): """Base class for errors in the email package.""" class MessageParseError(MessageError): """Base class for message parsing errors.""" class HeaderParseError(MessageParseError): """Error while parsing headers.""" class BoundaryError(MessageParseError): """Couldn't find terminating boundary.""" class MultipartConversionError(MessageError, TypeError): """Conversion to a multipart is prohibited.""" class CharsetError(MessageError): """An illegal charset was given.""" # These are parsing defects which the parser was able to work around. class MessageDefect: """Base class for a message defect.""" def __init__(self, line=None): self.line = line class NoBoundaryInMultipartDefect(MessageDefect): """A message claimed to be a multipart but had no boundary parameter.""" class StartBoundaryNotFoundDefect(MessageDefect): """The claimed start boundary was never found.""" class FirstHeaderLineIsContinuationDefect(MessageDefect): """A message had a continuation line as its first header line.""" class MisplacedEnvelopeHeaderDefect(MessageDefect): """A 'Unix-from' header was found in the middle of a header block.""" class MalformedHeaderDefect(MessageDefect): """Found a header that was missing a colon, or was otherwise malformed.""" class MultipartInvariantViolationDefect(MessageDefect): """A message claimed to be a multipart but no subparts were found.""" This is the entire content of the module. Apart from this, there are 2 very strange characters which don't show up in the preview, and can't be copy-pasted. They look like stick-characters of humans (in notepad), and I found it pretty amusing. One of them is in the line before class MessageError(Exception): """Base class for errors in the email package.""" The other is after class CharsetError(MessageError): """An illegal charset was given.""" Does anyone have an idea as to what these characters are doing there? Or is it just my package?
I'm using django-mptt to manage a simple CMS, with a model called Page, which looks like this (most presumably irrelevant fields removed): class Page(mptt.Model, BaseModel): title = models.CharField(max_length = 20) slug = AutoSlugField(populate_from = 'title') contents = models.TextField() parent = models.ForeignKey('self', null=True, blank=True, related_name='children', help_text = u'The page this page lives under.') removed fields are called attachments, headline_image, nav_override, and published All works fine using SQLite, but when I use MySQL and try and add a Page using the admin (or using ModelForms and the save() method), I get this: ProgrammingError at /admin/mycms/page/add/ (1110, "Column 'level' specified twice") where the SQL generated is: 'INSERT INTO `kaleo_page` (`title`, `slug`, `contents`, `nav_override`, `parent_id`, `published`, `headline_image_id`, `lft`, `rght`, `tree_id`, `level`, `lft`, `rght`, `tree_id`, `level`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' for some reason I'm getting the django-mptt fields (lft, rght, tree_id and level) twice. It works in SQLite presumably because SQLite is more forgiving about what it accepts than MySQL. get_all_field_names() also shows them twice: >>> Page._meta.get_all_field_names() ['attachments', 'children', 'contents', 'headline_image', 'id', 'level', 'lft', 'nav_override', 'parent', 'published', 'rght', 'slug', 'title', 'tree_id'] Which is presumably why the SQL is bad. What could I have done that would result in those fields appearing twice in get_all_field_names()?
I'm working on determining relationships (boundary/interior intersections) between two 3D objects (triangular faces) and stumbled on shapely, which I am interested in using instead of implementing my own point/segment/ray/triangle intersection functions. However, I'm running into the following problem: >>> from shapely.geometry import Polygon >>> poly = Polygon([(0,1,1),(1,-1,1),(-1,-1,1)]) >>> poly2 = Polygon([(0,1,0),(1,-1,0),(-1,-1,0)]) >>> poly.intersects(poly2) True >>> poly.equals(poly2) True The problem I seem to be running into is that the two polygons are equal in their 2D orthogonal projections (same triangle), but in different planes (one's at Z=1, other at Z=0), but shapely is saying they're equal and intersect. Is there some magic I'm missing to make shapely think in 3 dimensions? I've been googling, but every example I've seen so far is only in two dimensions.
Arguments are passed by assignment. The rationale behind this is twofold: the parameter passed in is actually a reference to an object (but the reference is passed by value) some data types are mutable, but others aren't So: If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object. If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object. To make it even more clear, let's have some examples. List - a mutable type Let's try to modify the list that was passed to a method: def try_to_change_list_contents(the_list): print 'got', the_list the_list.append('four') print 'changed to', the_list outer_list = ['one', 'two', 'three'] print 'before, outer_list =', outer_list try_to_change_list_contents(outer_list) print 'after, outer_list =', outer_list Output: before, outer_list = ['one', 'two', 'three'] got ['one', 'two', 'three'] changed to ['one', 'two', 'three', 'four'] after, outer_list = ['one', 'two', 'three', 'four'] Since the parameter passed in is a reference to outer_list, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope. Now let's see what happens when we try to change the reference that was passed in as a parameter: def try_to_change_list_reference(the_list): print 'got', the_list the_list = ['and', 'we', 'can', 'not', 'lie'] print 'set to', the_list outer_list = ['we', 'like', 'proper', 'English'] print 'before, outer_list =', outer_list try_to_change_list_reference(outer_list) print 'after, outer_list =', outer_list Output: before, outer_list = ['we', 'like', 'proper', 'English'] got ['we', 'like', 'proper', 'English'] set to ['and', 'we', 'can', 'not', 'lie'] after, outer_list = ['we', 'like', 'proper', 'English'] Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed. String - an immutable type It's immutable, so there's nothing we can do to change the contents of the string Now, let's try to change the reference def try_to_change_string_reference(the_string): print 'got', the_string the_string = 'In a kingdom by the sea' print 'set to', the_string outer_string = 'It was many and many a year ago' print 'before, outer_string =', outer_string try_to_change_string_reference(outer_string) print 'after, outer_string =', outer_string Output: before, outer_string = It was many and many a year ago got It was many and many a year ago set to In a kingdom by the sea after, outer_string = It was many and many a year ago Again, since the the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new string, but there was no way to change where outer_string pointed. I hope this clears things up a little. EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that. How do we get around this? As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out: def return_a_whole_new_string(the_string): new_string = something_to_do_with_the_old_string(the_string) return new_string # then you could call it like my_string = return_a_whole_new_string(my_string) If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list: def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change): new_string = something_to_do_with_the_old_string(stuff_to_change[0]) stuff_to_change[0] = new_string # then you could call it like wrapper = [my_string] use_a_wrapper_to_simulate_pass_by_reference(wrapper) do_something_with(wrapper[0]) Although this seems a little cumbersome.
ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] @sam7 : je suppose que tu parles de mon live "Madbox" .. comme je te l'ai dit sur l'autre post, il n'est pas prévu pour une installation "normale" et les paquet *-fr ne sont pas installés. Sinon , j'ai une mise à jour de mon live en cours ( plus conventionnel .. je vais en parler sur le post dédié ). Edit : .. pendant que je suis la , ma dernière configuration avec plusieurs "adeskbar" bureau avec les barres cachées et bureau avec toutes les barres toujours visible A+ Dernière modification par ADcomp (Le 07/07/2009, à 00:41) Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] hello .. ADeskBar 0.1.7 .. pour tester : http://www.ad-comp.be/public/projets/AD … .7-all.deb !!! Attention .. beaucoup de changement dans le code et la structure du fichier de conf. Il faut supprimer l'ancienne conf. avant .. rm -rf ~/.config/adeskbar Nouvelle video : http://www.youtube.com/watch?v=EmLpxCGI35Y Tout est ok pour l'ajout de plugins , mais j'ai encore quelques soucis ( focus , etc .. ) et le choix des librairies ( xlib , wnck , .. ) .. Donc je n'ai pas inclus le support dans cette version Les feedback sont bienvenus Bye .. Hors ligne frafa Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Salut je viens d'installer pour la premiere fois histoire de tester et je me retrouve avec des erreurs genre glib.GError: Impossible d'ouvrir le fichier « ADeskBar/images/default/user-home.png » : Permission non accordée apres un tour dans /usr/share/adeskbar/ADeskBar/images/default je me rend compte que pas les bons droits sur fichiers images je corrige sudo chmod 644 /usr/share/adeskbar/ADeskBar/images/default/folder-documents.png /usr/share/adeskbar/ADeskBar/images/default/folder-downloads.png /usr/share/adeskbar/ADeskBar/images/default/folder-image.png /usr/share/adeskbar/ADeskBar/images/default/folder-sound.png /usr/share/adeskbar/ADeskBar/images/default/folder-video.png /usr/share/adeskbar/ADeskBar/images/default/user-home.png apres c'est ok. sympas comme lanceur Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] salut frafra .. Pff .. j' te jure , parfois .. .. Merci pour ton feedback !! j'ai corrigé tout de suite .. A+ Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Tadaaa !! update !! Zoom sur l'image quand la souris est au-dessus C'est pas encore parfait mais ca fonctionne ( plus d'effet bientot .. surement comme wbar ) Et une nouvelle video pour voir à quoi ca ressemble : http://www.youtube.com/watch?v=jDu4LLNFV1k Dernière modification par ADcomp (Le 17/07/2009, à 17:39) Hors ligne frafa Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Salut, Cool si je puis me permettre à mon gout, il y a un gros manque qui ne doit pas etre dur a coder, en effet je pense que tu devrait ajouter la possibilité d'ajouter un lanceur via drag and drop d'un xxx.desktop car c'est lourd a saisir sans cela... Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] salut frafra .. ce que tu expliques est déjà présent ( mais pas encore le drag'n drop ) !! Il suffit de cliquer sur le boutton ( ... ) à coté du champ de saisie "Commande". Cela ouvre une fenetre de sélection de fichier directement dans /usr/share/applications. Si tu sélectionne un fichier *.desktop , ADeskBar recherche automatiquement le nom , la commande et l'icone. Exemple en video : http://www.youtube.com/watch?v=S72EtmknL10 Merci pour ton (2em) test A+ Dernière modification par ADcomp (Le 17/07/2009, à 18:53) Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Quelques infos sur la suite des opérations .. Un petit fade in / fade out lorsque adeskbar est utilisé , pas de remplissage ( juste la bordure ) , arrondis des coins ( % de la taille des icones ) , dégradé du remplissage de la barre .. Vous en pensez quoi ..? des idées ? Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Salut sam7, Merci pour ton commentaire , mais pour concurrencer cairo-dock , il faudrait que je démissionne de mon boulot, que je me clone au moins cinq ou six fois , que je retourne à l'école reprendre des cours de programmation , etc .. Plus sérieusement .. Dans le principe , oui c'est comme cairo-dock , mais en beaucoup plus simple. Pas du tout orienté "effets" ( il n'y aura pas d'effet avec opengl pas exemple ) .. Même si pour le moment je bosse pas mal sur la partie "aspect" et look'n feel .. C'est une simple barre de lancement (et je suppose , le restera). programmer en python Usage basique pour une utilisation sous Openbox ( dans mon cas ) et qui fonctionne bien sans grosse config même avec xcompmgr ( souvent utilisé avec openbox pour avoir le composite ) Voilà .. ce projet n'a pas d'autre prétention que de satisfaire : * mon besoin de bidouiller en python * avoir une barre de lancement simple et facile à configurer * mon ego .. Bon , maintenant j'avoue que de toute mes bidouilles / scripts en tout genre , c'est mon petit "bébé" et que je passe pas mal de mon temps libre à coder dessus ( lecture doc , recherche , test , on efface et on recommence .. ). La première version ( sans config ) devait faire dans les 200 lignes de code ... Je passe allègrement les 2000 lignes à présent ( sans compter les extentions / plugins en cours ) Voilà .. c'était mon petit roman du soir .. Merci et @pluche Dernière modification par ADcomp (Le 19/07/2009, à 01:52) Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Ready ? let's go paquet Deb : http://www.ad-comp.be/public/projets/AD … .2-all.deb nouvelle vidéo : http://www.youtube.com/watch?v=PNvbiaSzFf4 Feedback bienvenus .. Bye Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Hello .. Voilà une version alpha pour tester les dernières améliorations .. : http://www.ad-comp.be/public/projets/AD … .3-all.deb * taille de la barre , % du fading quand la barre est inactive, choix de la "forme" de la barre , .. * line et curve sont en test (codé à la hache) , l'utilsation d'une image comme fond n'est pas encore au point ( il faut que je "masque" avec la "forme") Et en prime , une petite vidéo : http://www.youtube.com/watch?v=TqrDPqauS14 Bye .. Dernière modification par ADcomp (Le 25/07/2009, à 15:01) Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Salut sam, Si jamais tu as problème au lancement d'ADeskBar , renomme ton fichier de conf .. mv ~/.config/adeskbar/config ~/.config/adeskbar/config.old sinon , j'ai repris le boulot pour les plugins ( j'avais besoin d'un menu ) .. Ce menu peut être utilisé en "standalone" .. sans avoir besoin que ADeskBar soit en cours d'exécution. A+ Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] hey pas mal ton menu, il ressemble un peu a celui que je voulais creer depuis longtemps et que je viens de faire en c++/Qt. mais moi j'ai galéré pour parser les .desktop pour remplir le menu et surtout pour les icones pour recuperer celle qui va bien avec le theme t'a fais comment toi ? ta utilisé bonobo ? corba ? ou a la mano ? c quoi le truc ? merci d'avance ;... ps : pour le moment je suis obligé de tout parser (dossier /usr/share/applications et /usr/share/icons) au demarrage du menu et de tout stcocker dans une bdd sqlite (ps le parsage des desktop prend une dizaine de secondes maiis celui des icon prend un dizaine de minutes lol) Dernière modification par TheBootroo (Le 30/07/2009, à 00:27) ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] edit : moi ca ressemble à ca : trois semaines de codage intensif lol (et des nuit blanches) ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] [..]menu clic droit ou clic gauche sur le bureau ... ou sur une icône du dock ? au choix .. en plugin pour ADeskBar (par défaut) mais comme on peut le lancer tout seul , on le lance comme on veut ( click sur bureau , raccourci , boutton , etc .. ) en fonction de ta config. [..] moi j'ai galéré pour parser les .desktop pour remplir le menu et surtout pour les icones pour recuperer celle qui va bien avec le theme. t'a fais comment toi ? ta utilisé bonobo ? corba ? ou a la mano ? 2 petites routines (donc mano) : une parse tout les fichiers .desktop , l'autre recherche l'icone associé. un truc tout bète, je ne prend pas (encore) en compte le thème utilisé. Tu peux jeter un coup d'oeil dans le fichier source ( ADeskBar/core.py ) ps : pour le moment je suis obligé de tout parser (dossier /usr/share/applications et /usr/share/icons) au demarrage du menu et de tout stcocker dans une bdd sqlite (ps le parsage des desktop prend une dizaine de secondes maiis celui des icon prend un dizaine de minutes lol) tu analyses tout le répertoire icons ? voici +/- la structure de ma recherche ..: iconbase=('gnome','hicolor','locolor') iconpath='/usr/share/icons/' sizelist =('256x256', '128x128', '64x64', '48x48', '32x32', '24x24') categorylist=('apps',"devices", 'categories','filesystems','') extensionlist = ('png', 'svg', 'xpm') et je regarde aussi dans /usr/share/pixmaps .. il manque juste l'analyse de la config gtk pour ajouter le répertoire du thème ( prévu .. ). Et c'est presque instantané .. maintenant peux aussi enregistrer dans un fichier de config et seulement le mettre à jour en arrière plan de temps en temps .. Si tu veux en discuter, envois moi un pm .. Sinon plutot sympa ton menu. De bonnes idées , dommage que c'est du Qt/C++ Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] salut ! en fait non j'analyse pas tout le dossier icons, juste (dans l'ordre car l'ordre de préférence compte danns ma fonction) : mon theme officiel hicolor tango gnome pixmaps et je compte avoir un jour un theme assez complet pour me passer de tous ces dossiers (le mien fait deja 180 mo soit un peu plus de 8000 icones). tu dis que le scan est rapide pour toi ? pour moi le temps d'analyser les sous dossiers de chaque theme suscité, cela prend bien 10 min sur mon SSD qui lit à 280 mo / sec donc j'ose même pas imaginer sur un 5400 trpm..... la config gtk pour ma part je m'en tape car je compte faire un projet indépendent de gnome et kde (bien que basé entierement sur qt4), car c'est pour les besoins de mon nouvel environement de bureau en création qui est lui même entièrment en Qt. encore merci d'avance pour tes infos je vais lire ton code meme si j'ai toujours du mal a relire le code des autres (surtout en python vu que c'est pas vraiment mon langage .. .. mais bon je l'ai deja fait donc je peux le refaire...) a+ PS : pourquoi dommage que se soit du qt / c++ ????? qt ou au moins la version acuelle, est bien plus souple que gtk concernant le positionnement des widgets et le skinnage en CSS (je le sais car je galerais avant ca a essayer de realiser mon projet en Winforms avec vb, puis en C avec gtk+) quand à c++ c'est un des meilleurs langages ; orienté objet, simple, rapide (surtout avec les excellent compilateurs du genre g++ 4.4) car je dois t'avouer que je suis un peu allergique au python, sa syntaxe et les pb de compatibilité entre les différentes versions de l'interpreteur (2.4,2.5,2.6,2.8,3.0,3.1 ...) ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] euh au fait il est ou le code du menu ? t'a pas un tgz à me passer pasque depuis ton post sur le menu t'a pas remis de paquet en ligne je crois ... ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] bon j'ai trouvé ton code et surtout la fonction find_icon, je l'ai traduite en c++ et intégrée dans mon code. maintenant j'ai parsing + icones qui prend en tout une dizaine de secondes .... c'est bien mieux !!!! merci reste pour moi a mettre tout cela dans un QThread pour le faire de facon asynchrone et donc pouvoir afficher le menu avant que le parsing soit fini. merci encore (merci merci merci merci merci merci merci merci merci merci merci merci merci merci merci merci merci merci merci mercimerci merci merci merci merci merci merci merci merci merci merci merci merci merci) PS : ceci ci dessus n'est PAS du flood, juste un petit (tout petit) débordement de reconnaissance.... ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne ADcomp Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] Hello, PS : pourquoi dommage que se soit du qt / c++ ????? parce que je code en python/gtk .. j'aurais simplement mixé avec le tien ( ca sert à rien de réinventer la roue ) Sinon , pas d'apriori sur C++ ou encore QT. Tu as aussi parler un desktop complet en QT, j'ai testé il n'y a pas longtemps un WM basé sur QT .. : Antico bon j'ai trouvé ton code et surtout la fonction find_icon, [..] maintenant j'ai parsing + icones qui prend en tout une dizaine de secondes ... c'est bien mieux !!!! j'ai rien inventé. je me suis simplement basé sur un exemple de recherche ( freedesktop ? ) trouvé sur le net. Content que cela fonctionne pour toi .. Si tu veux discuter 'devel' , l'invitation du 'mp' tient toujours .. A+ Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] antico je connais bien : le mien en reprend quelques lignes de code (une centaine). sinon cool l'invitation a discuter. mais perso je prefere le chat en direct (google talk ?). sinon je te previendrais quand le site de mon projet (en signature) sera retabli, peut etre que cela t'interresserait ? sinon si tu arrive à lire le code c++ je peux t'envoyer les source de mon menu (format de projet : QtCreator, .pro). dis le moi si ca t'interresse ... ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne TheBootroo Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo] sinon mon desktop ressemblera à ça une fois terminé : (mockup en svg fait avec inkscape) ALLEZ VISITER MON SITE INTERNET : http://modern-os.projects.servhome.org/ (différents sous-projets visant a créer une distro linux plus orienté débutant et complètement anti-geek) developpeurs C++/Qt et graphistes (SVG surtout) motivés : rejoignez-nous !!! VOUS POUVEZ DESORMAIS VOUS INSCRIRE. Hors ligne
The following is the model for a Django app. Let the app be called MyApp. The idea is for every app to have it's folder under the MEDIA_ROOT. class MyModel(models.Model): .... #Other fields datoteka = models.FileField(upload_to = 'MyApp',null = True) Is there a way to get the name of the app from somewhere and remove the hardcoded MyApp. This is a similar question, however I have no access to the request object in the model.
Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go from gblocks.models import Image f = 'image__endswith="jpg"' # Would be scripted in another area, but passed as text <user input> d = Image.objects.filter(f) #for the non-django pythonistas: d = Image.objects.filter(image__endswith="jpg") # would be the non-dynamic equivalent.
As stated earlier, you will need to update your config/initializers/active_admin.rb to reflect the correct auth method. Additionally, however, you will want to update the following settings as well: # This setting changes the method which Active Admin calls # to return the currently logged in user. config.current_user_method = :current_admin_user to config.current_user_method = :current_user and # This setting changes the path where the link points to. If it's # a string, the strings is used as the path. If it's a Symbol, we # will call the method to return the path. # # Default: config.logout_link_path = :destroy_admin_user_session_path to config.logout_link_path = :destroy_user_session_path Of course, you don't HAVE to update these (or the method mentioned in the post), and just over-ride the methods elsewhere, but this seems to be the easiest / cleanest approach. You will obviously need to substitute "user" in each setting (current_USER) with the name of the model using devise authentication. I would also recommend updating the following setting as well while you are in there: # This setting changes the http method used when rendering the # link. For example :get, :delete, :put, etc.. # # Default: config.logout_link_method = :get to config.logout_link_method = :delete This last change is required if the default HTTP method used by your devise config is set to :delete, which it is unless you changed it. It matters that they are now synced because if you follow these instructions, you will be using destroy_user_session_path which is a path already defined by devise. Otherwise you will get a message stating that [GET] /users/sign_out route does not exist.
Recently I've been doing a lot of music based programming, and as such find myself doing this kind of thing a lot to deal with missing metadata in some songs: default = {'title': 'Unknown title', 'artist': 'unknown Artist'} default.update(song) print '{title} - {artist}'.format(**default) Is there a cleaner way to do this? I tried overriding __missing__ like so but missing keys still throw a KeyError: class Song(dict): # dictionary with some nice stuff to make it nicer def __missing__(self, key): return 'Unknown {key}'.format(key = key) Edit: Sorry I should have been clearer, basically the following must work. s = Song() print '{notAKey}'.format(s) A couple of people have pointed out that the **s are not necessary. Edit 2: I've "solved" my problem, at least to my satisfaction. It's debatable whether or not this is cleaner, but it works for me. from string import Formatter class DefaultFormatter(Formatter): def get_value(self, key, args, kwargs): # Try standard formatting, then return 'unknown key' try: return Formatter.get_value(self, key, args, kwargs) except KeyError: return kwargs.get(key, 'Unknown {0}'.format(key)) class Song(dict): def format(self, formatString): # Convenience method, create a DefaultFormatter and use it f = DefaultFormatter() return f.format(formatString, **self) So the following will return 'Unknown notAKey' k = Song() print k.format('{notAKey}')
new to python and I'm having trouble converting a script to a more effective algorithm I was given. Here's the python code: #!/usr/bin/env python import itertools target_sum = 10 a = 1 b = 2 c = 4 a_range = range(0, target_sum + 1, a) b_range = range(0, target_sum + 1, b) c_range = range(0, target_sum + 1, c) for i, j, k in itertools.product(a_range, b_range, c_range): if i + j + k == 10: print a, ':', i/a, ',', b, ':', j/b, ',', c, ':', k/c (it only does 3 variables just for example, but I want to use it on thousands of variables in the end). Here's the result I am looking for(all the combo's that make it result to 10): 1 : 0 , 2 : 1 , 4 : 21 : 0 , 2 : 3 , 4 : 11 : 0 , 2 : 5 , 4 : 01 : 2 , 2 : 0 , 4 : 21 : 2 , 2 : 2 , 4 : 11 : 2 , 2 : 4 , 4 : 01 : 4 , 2 : 1 , 4 : 11 : 4 , 2 : 3 , 4 : 01 : 6 , 2 : 0 , 4 : 11 : 6 , 2 : 2 , 4 : 01 : 8 , 2 : 1 , 4 : 01 : 10 , 2 : 0 , 4 : 0 In question can brute force algorithms scale? a better algorithm was suggested but I'm having a hard time implementing the logic within python. The new test code: # logic to convert #for i = 1 to k #for z = 0 to sum: # for c = 1 to z / x_i: # if T[z - c * x_i][i - 1] is true: #having trouble creating the table...not sure if thats a matrix # set T[z][i] to true #set the variables sum = 10 data = [1, 2, 4] # trying to find all the different ways to combine the data to equal the sum for i in range(len(data)): print(i) if i == 0: continue for z in range(sum): for c in range(z/i): print("*" * 15) print('z is equal to: ', z) print('c is equal to: ', c) print('i is equal to: ', i) print(z - c * i) print('i - 1: ', (i - 1)) if (z - c * i) == (i - 1): print("(z - c * i) * (i - 1)) match!") print(z,i) Sorry its obviously pretty messy, I have no idea how to generate a table in the section that has: if T[z - c * x_i][i - 1] is true: set T[z][i] to true In other places while converting the algo, I had more problems because in lines like 'or i = 1 to k' converting it to python gives me an error saying "TypeError: 'int' object is not utterable" Any help or suggestions would be amazing. I have learned the syntax in python but haven't done anything with algorithms yet(so please bare with me). Thanks in advance.
Sometimes contact information is incomplete but can be inferred from existing data. Gender is often missing from data but easy to determine based on first name. One solution is to check names against existing data. A query can be run against correctly know valid name/gender pairs and the gender with the most occurrences of that name wins. But what about new names and alternate spellings? It turns out that there are features that are indicative of one gender or another. For example, it is more likely that a name ending in ‘a’ is female rather than male. There are also other patterns such as the last two letters of a name. We could write a series of heuristics to make a determination but that does not seem like a scalable idea. I’d like to be able to apply this approach to other languages and not have to learn the ins and outs of each. What we need to do is figure out which features indicate which gender and how strongly they do so. I think ML tends to scare a lot of people. When I’m recommending a ML solution to someone, I tend to call it a statistical approach to the problem. So I’m going to call this solution a statistical approach. What we are doing is classifying the data into one of two categories, male or female. For this I chose one of my favourite classifiers, Naive Bayes. I’m a fan of Naive Bayes because it’s basis is simple to understand and preforms decently well (in my experience). I’m a big fan of the NLTK’s (Natural Language Toolkit) easy interface to classifiers such as Naive Bayes and it’s what I used for this project. First, we’re going to need some data to train the classifier on to see which features indicate which gender and how much we can trust the feature. I grabbed training data from the US Census website and wrote an importer module for it in Python. Second, we need a feature extractor to take a name and spit out features we think may indicate the gender well. I wrote a simple extractor that takes the last and last two letters and spits them out as a feature as well as if the last letter is a vowel: def _nameFeatures(self,name): name=name.upper() return { 'last_letter': name[-1], 'last_two' : name[-2:], 'last_is_vowel' : (name[-1] in 'aeiouy') } Third, we need to test the classifier. We need to be sure that we separate the training data set from the test data set. If we just wanted to do a lookup, a hash table would be much more efficient. We’re interested in the classifier’s ability to determine the gender based on names it has not encountered before. So we randomly shuffle the data and split. I chose to split 80% for training and 20% for testing but that’s something you can play with. Fourth, we need to learn which features matter. The NLTK provides a nice method which will tell us which features were most useful in determining the gender. This way we can concentrate on features that really matter. I’ve done a lot of the wrapper work for you and put it up on github.Checkout the gender prediction code here. If you run genderPredictor.py it will automatically train and test the genderPredictor module.You can also import genderPredictor into your own code and run the methods manually. The most useful method to use within your own code is classify(name) which takes a name and spits out the gender. You can modify _nameFeatures to play around and test other feature ideas.If you find something that works better, please let me know and I’ll incorporate your idea and give you credit. Hope this is useful and interesting; let me know what you think.
The __init__ method, like other methods and functions returns None by default in the absence of a return statement, so you can write it like either of these: class Foo: def __init__(self): self.value=42 class Bar: def __init__(self): self.value=42 return None But, of course, adding the return None doesn't buy you anything. I'm not sure what you are after, but you might be interested in one of these: class Foo: def __init__(self): self.value=42 def __str__(self): return str(self.value) f=Foo() print f.value print f prints: 42 42
Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour... Alors, comme j'ai toujours du temps, de la place sur mes hdd, et de la suite dans les idées ... Toujours au sujet de la tentative d'Hybrydiser la Cubuntu 13.04 32 bits ... Voir post ci-dessus . J'ai réinstallé, j'ai fais les maj système en commande, j'ai été obligé d'installer la dernière version du kernel en commandes ( 3.8.0-23), toujours des soucis avec le gestionnaire de maj de la 13.04 ... Et j'ai tenté de réinstaller le HY-D-V1 en commandes ... Voici le retour ... bernard@bernard:~$ sudo add-apt-repository ppa:olivelinux36/hydv1-desktop-dev-raring [sudo] password for bernard: Vous allez ajouter le PPA suivant à votre système : desktop Python Webkit Gtk HTML Javascript Plus d’info : https://launchpad.net/~olivelinux36/+archive/hydv1-desktop-dev-raring Appuyez sur [ENTRÉE] pour continuer ou Ctrl-C pour annuler l’ajout gpg: le porte-clefs « /tmp/tmp_staj9/secring.gpg » a été créé gpg: le porte-clefs « /tmp/tmp_staj9/pubring.gpg » a été créé gpg: demande de la clef 3C3C3D70 sur le serveur hkp keyserver.ubuntu.com gpg: /tmp/tmp_staj9/trustdb.gpg : base de confiance créée gpg: clef 3C3C3D70 : clef publique « Launchpad PPA for larrieu » importée gpg: Quantité totale traitée : 1 gpg: importées : 1 (RSA: 1) OK bernard@bernard:~$ sudo apt-get update Atteint http://fr.archive.ubuntu.com raring Release.gpg Atteint http://ppa.launchpad.net raring Release.gpg Atteint http://fr.archive.ubuntu.com raring-updates Release.gpg Atteint http://security.ubuntu.com raring-security Release.gpg Atteint http://ppa.launchpad.net raring Release Atteint http://fr.archive.ubuntu.com raring-backports Release.gpg Atteint http://extras.ubuntu.com raring Release.gpg Atteint http://archive.canonical.com raring Release.gpg Atteint http://security.ubuntu.com raring-security Release Atteint http://fr.archive.ubuntu.com raring Release Atteint http://extras.ubuntu.com raring Release Atteint http://ppa.launchpad.net raring/main i386 Packages Atteint http://archive.canonical.com raring Release Atteint http://security.ubuntu.com raring-security/main Sources Atteint http://fr.archive.ubuntu.com raring-updates Release Atteint http://extras.ubuntu.com raring/main Sources Atteint http://archive.canonical.com raring/partner Sources Atteint http://security.ubuntu.com raring-security/restricted Sources Atteint http://fr.archive.ubuntu.com raring-backports Release Atteint http://extras.ubuntu.com raring/main i386 Packages Atteint http://archive.canonical.com raring/partner i386 Packages Atteint http://fr.archive.ubuntu.com raring/main Sources Atteint http://security.ubuntu.com raring-security/universe Sources Atteint http://fr.archive.ubuntu.com raring/restricted Sources Atteint http://security.ubuntu.com raring-security/multiverse Sources Atteint https://dl.google.com stable Release.gpg Atteint http://fr.archive.ubuntu.com raring/universe Sources Atteint http://security.ubuntu.com raring-security/main i386 Packages Atteint https://dl.google.com stable Release Atteint http://fr.archive.ubuntu.com raring/multiverse Sources Atteint http://security.ubuntu.com raring-security/restricted i386 Packages Atteint http://fr.archive.ubuntu.com raring/main i386 Packages Atteint https://dl.google.com stable/main i386 Packages Atteint http://security.ubuntu.com raring-security/universe i386 Packages Atteint http://fr.archive.ubuntu.com raring/restricted i386 Packages Atteint http://security.ubuntu.com raring-security/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com raring/universe i386 Packages Atteint http://fr.archive.ubuntu.com raring/multiverse i386 Packages Atteint http://security.ubuntu.com raring-security/main Translation-en Atteint http://fr.archive.ubuntu.com raring/main Translation-fr Ign http://ppa.launchpad.net raring/main Translation-fr_FR Atteint http://security.ubuntu.com raring-security/multiverse Translation-en Ign http://ppa.launchpad.net raring/main Translation-fr Atteint http://fr.archive.ubuntu.com raring/main Translation-en Ign http://extras.ubuntu.com raring/main Translation-fr_FR Ign http://archive.canonical.com raring/partner Translation-fr_FR Ign http://extras.ubuntu.com raring/main Translation-fr Ign http://archive.canonical.com raring/partner Translation-fr Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-fr Ign http://extras.ubuntu.com raring/main Translation-en Ign http://ppa.launchpad.net raring/main Translation-en Ign http://archive.canonical.com raring/partner Translation-en Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-en Atteint http://security.ubuntu.com raring-security/restricted Translation-en Atteint http://fr.archive.ubuntu.com raring/restricted Translation-fr Atteint http://fr.archive.ubuntu.com raring/restricted Translation-en Atteint http://security.ubuntu.com raring-security/universe Translation-en Atteint http://fr.archive.ubuntu.com raring/universe Translation-fr Atteint http://fr.archive.ubuntu.com raring/universe Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/main Sources Atteint http://fr.archive.ubuntu.com raring-updates/restricted Sources Atteint http://fr.archive.ubuntu.com raring-updates/universe Sources Atteint http://fr.archive.ubuntu.com raring-updates/multiverse Sources Atteint http://fr.archive.ubuntu.com raring-updates/main i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/restricted i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/universe i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/main Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/multiverse Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/restricted Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/universe Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/main Sources Atteint http://fr.archive.ubuntu.com raring-backports/restricted Sources Atteint http://fr.archive.ubuntu.com raring-backports/universe Sources Atteint http://fr.archive.ubuntu.com raring-backports/multiverse Sources Ign http://security.ubuntu.com raring-security/main Translation-fr_FR Atteint http://fr.archive.ubuntu.com raring-backports/main i386 Packages Ign http://security.ubuntu.com raring-security/main Translation-fr Ign http://security.ubuntu.com raring-security/multiverse Translation-fr_FR Ign http://security.ubuntu.com raring-security/multiverse Translation-fr Atteint http://fr.archive.ubuntu.com raring-backports/restricted i386 Packages Ign http://security.ubuntu.com raring-security/restricted Translation-fr_FR Atteint http://fr.archive.ubuntu.com raring-backports/universe i386 Packages Ign http://security.ubuntu.com raring-security/restricted Translation-fr Atteint http://fr.archive.ubuntu.com raring-backports/multiverse i386 Packages Ign http://security.ubuntu.com raring-security/universe Translation-fr_FR Ign http://security.ubuntu.com raring-security/universe Translation-fr Atteint http://fr.archive.ubuntu.com raring-backports/main Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/multiverse Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/restricted Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/universe Translation-en Ign https://dl.google.com stable/main Translation-fr_FR Ign https://dl.google.com stable/main Translation-fr Ign https://dl.google.com stable/main Translation-en Ign http://fr.archive.ubuntu.com raring/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring/universe Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/main Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/multiverse Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/restricted Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/universe Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/universe Translation-fr Lecture des listes de paquets... Fait bernard@bernard:~$ sudo apt-get install hydv1desktop Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Les paquets suivants ont été installés automatiquement et ne sont plus nécessaires : apt-clone archdetect-deb bogl-bterm casper discover discover-data dpkg-repack gir1.2-timezonemap-1.0 libdebconfclient0 libdebian-installer4 libdiscover2 localechooser-data lvm2 ncurses-term plymouth-x11 python3-pyicu rdate squashfs-tools ubiquity-casper ubiquity-ubuntu-artwork user-setup xresprobe Veuillez utiliser « apt-get autoremove » pour les supprimer. Les NOUVEAUX paquets suivants seront installés : hydv1desktop 0 mis à jour, 1 nouvellement installés, 0 à enlever et 34 non mis à jour. Il est nécessaire de prendre 8 202 ko dans les archives. Après cette opération, 9 128 ko d'espace disque supplémentaires seront utilisés. Réception de : 1 http://ppa.launchpad.net/olivelinux36/hydv1-desktop-dev-raring/ubuntu/ raring/main hydv1desktop i386 0.2.0 [8 202 kB] 8 202 ko réceptionnés en 24s (329 ko/s) Sélection du paquet hydv1desktop précédemment désélectionné. (Lecture de la base de données... 212136 fichiers et répertoires déjà installés.) Dépaquetage de hydv1desktop (à partir de .../hydv1desktop_0.2.0_i386.deb) ... update-alternatives: erreur: le chemin alternatif /usr/bin/start_hydv1 n'existe pas update-alternatives: erreur: le chemin alternatif /usr/bin/start_hydv1 n'existe pas update-alternatives: erreur: l'alternative /usr/bin/start_hydv1 pour x-session-manager n'est pas enregistrée ; pas de configuration rm: impossible de supprimer «/var/lib/dpkg/info/hydv1desktop.postrm»: Aucun fichier ou dossier de ce type Paramétrage de hydv1desktop (0.2.0) ... Fichier de configuration « /etc/skel/.config/dconf/user » ==> Fichier du système créé par vous ou par un script. ==> Fichier également présent dans le paquet fourni par le responsable du paquet. Que voulez-vous faire ? Vos options sont les suivantes : Y ou I  : installer la version du responsable du paquet N ou O  : garder votre version actuellement installée D  : afficher les différences entre les versions Z  : suspendre ce processus pour examiner la situation L'action par défaut garde votre version actuelle. *** user (Y/I/N/O/D/Z) [défaut=N] ? Z Tapez « exit » lorsque vous aurez fini. root@bernard:/# exit exit Fichier de configuration « /etc/skel/.config/dconf/user » ==> Fichier du système créé par vous ou par un script. ==> Fichier également présent dans le paquet fourni par le responsable du paquet. Que voulez-vous faire ? Vos options sont les suivantes : Y ou I  : installer la version du responsable du paquet N ou O  : garder votre version actuellement installée D  : afficher les différences entre les versions Z  : suspendre ce processus pour examiner la situation L'action par défaut garde votre version actuelle. *** user (Y/I/N/O/D/Z) [défaut=N] ? Y dpkg : avertissement : hydv1desktop :échec de la liaison de « /etc/skel/.config/dconf/user » à « /etc/skel/.config/dconf/user.dpkg-old » : Aucun fichier ou dossier de ce type Installation de la nouvelle version du fichier de configuration /etc/skel/.config/dconf/user ... update-alternatives: utilisation de « /usr/bin/start_hydv1 » pour fournir « /usr/bin/x-session-manager » (x-session-manager) en mode manuel bernard@bernard:~$ Au sujet du fichier /etc/skel/.config/dconf/user . pour installer la version du HY-D-V1 ,j'ai renommé le fichier ==> user , en ==> cacher-user Puis j'ai poursuivi l’installation ... L'installation semble se poursuivre sans erreur ... Au reboot, en lançant une session avec le HY-D-V1 ... Et voila à quoi j'ai encore droit ... Je tente de lancer en passant par /usr/bin/start-hydv1 , en graphique ... Même punition ... En terminal, ==> start_hydv1 ==> pas plus de succès ... J'ai remis le fichier original ==> user ... l'OS fonctionne à nouveau, mais pas le HY-D-V1 . Bon ,et bien , je laisse çà en attente, si quelqu'un de la Team Hybryde passe par ici, et qu'il sait ce qu'il faut faire .... @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop (résolu ) Salut a tous , Qui sait comment réduire la taille des icônes (48 ?======>32)dans le panneau gauche des favoris dans hybryde fus.13.04 ...merci cordialement , Jibel Dernière modification par jibel (Le 11/06/2013, à 19:48) Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonsoir... Qui sait comment réduire la taille des icônes Et bien ,je ne savais pas... Mais je me suis rappelé avoir lu, sans trop comprendre ,ceci ; Alors, comme dernièrement j'ai "trifouillé" un peu dans les thèmes .... J'ai fais ce que dis chrisripp ... Dans (Attention .themes ;dossier cacher) ... ==> /home/.themes/HYDV1/ ... J'ai copier/coller sur place le thème Hydv1-Original ... Je l'ai renommé ==> mon-theme-02 Dans ce thème renommé je suis allé, comme le dit chrisripp à ==> /home/.themes/HYDV1/mon-theme-02/css/style.css J'ai ouvert le fichier ==> style.css et dans la section ==> LEFT DASH WINDOW , rubrique==> /* image in the left dash */ ... J'ai changé ==> width:40px;height:40px; pour ==> width:25px;height:70px; J'ai enregistré, changé de thème, puis revenu sur le thème renommé ... Regardes la tête des icônes à gauche.... C'est çà que tu cherches à faire?? ... Évidement, avec les tailles en pixel qui te conviennent ... Tiens tiens!!!.. Çà me donne des idées, je ne savais pas trop comment faire certaines modifs dans le thèmes ,de Fusion 12.04 dans laquelle j'ai installé le HY-D-V1 ... Les tailles du cadre et des icônes ajoutées, pour lancer Mate et Cinnamon, dont j'ai ajouté les meta paquets ... Je crois que le tuto de chrisripp va bien m'aider, pour mettre à égalité Fusion 12.04 et 13.04 ... J'y vais de ce pas ... Merci à lui ... @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop Bonjour Babdu89, Je n’étais pas allé sur le site d'hybryde , j'ai cherché ailleurs , dans ubuntu-tweak il y avait ce genre de manip ,selon la version ! puis avec Unity , aussi , on pouvait changer cette taille ! J'ai trouvé le script , j'ai modifié la taille , enregistrer le changement , redémarrer la bécane .....et je ne vois pas de changement réel de taille des icônes ?Elles me paraissent , encore très grandes ? Il y a 12 icones , si j'arrive a les réduires a une taille qui me convient , +/- 1 tiers cette taille , là! je pourrais en mettre 3/4 de plus !? Est-ce que je me suis trompé dans le choix du "background left" ? Que j'ai réduis a 30 pix Screen a l'appui ....? Sais pas si c’était la bonne manip ! @ + merci Jibel Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour. @ jibel ... Est-ce que je me suis trompé dans le choixdu "background left" ? Que j'ai réduis a 30 pix Screen a l'appui ....? Sais pas si c’était la bonne manip ! Oui,oui !!! ... Ci-dessus ... J'ai décrit la manip que j'ai faite. J'ai donné le chemin du dossier (Hydv1-Original) à modifier . La section et la rubrique ,où il faut indiquer les tailles des icônes ... Et le screen ,image toute la manip ... Ouvre la fenêtre en grand, pour voir çà comme il faut ... Tu devrais tout voir . À moins que tu aies encore des problèmes d'affichage sur ta machine, comme lorsque tu as voulu télécharger l'iso ,la première foi ... Attention !!! ... Je vois sur ton screen que tu fais les manips sur un fichier /.themes/HYDV1/Hydv1-Original/css Le thème ==> Hydv1-Original ... Tu n'as pas fait de sauvegarde du dossier ,et renommer ce dossier, pour faire les manips dessus??? .... Ne pas oublier de remettre la taille de ce que tu as modifié comme çà l'était avant manip ... C'est à çà que sert la sauvegarde du thème que tu vas modifier ...Revenir en arrière ... Chez toi remettre la taille comme ceci ... .bar_background_left { width:70px; height:30px; background:rgba(0,0,0,0.6); Bon courage . @+. Babdu89 . Dernière modification par Babdu89 (Le 11/06/2013, à 10:30) J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop @ jibel ... Par curiosité ... Sans modifier la taille des icônes dans le thème ==> Hydv1-Original ... J'ai ajouté une "bardée" d'icônes " (le terminal + Firefox) ... Sans cliquer sur les icônes, en passant la souris et en utilisant la molette , j'ai accès à tous les icônes ... Bon ,au premier coup d'oeil , tout n'est pas visible, mais il y a la place pour en mettre encore d'avantage ... As tu essayé çà ,au moins ... Çà pemet de garder une taille assez "confortable"de présentation des icônes .... La même chose avec la taille modifiée dans le fichier copier ... J'ai mis==> /* image in the left dash */ .dash_image { cursor: default; padding: 5px; margin-left:5px; width:12px;height:12px; -webkit-transition:all 0.2s ease-in; On voit bien tous les icônes, mais c'est petit, et si on en rajoute, il faut utiliser la molette de la souris à nouveau, pour les voir ... Alors?!?!???... @+. Babdu89 . Dernière modification par Babdu89 (Le 11/06/2013, à 11:11) J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop @ Babdu89, J'ai fais ce que tu as dis ,renommer le HY-D-V1 en mon theme02 et comme tu as dis , faire les manips avec mon renommé thème02 ====> modifier la manip précédente :Chez toi remettre la taille comme ceci ... .bar_background_left { width:70px; height:30px; background:rgba(0,0,0,0.6); Ensuite retour sur le "renomé" refaire les modifs "ou elles doivent être faites" C'est a dire Tu n'as pas fait de sauvegarde du dossier ,et renommer ce dossier, pour faire les manips dessus??? .... maintenant SI .....j'ai mis 30 et 30 pix pour la taille , enregistrer fermer , rouvrir et je n'ai pas du tout ce que tu as toi sur tes screens ??Pourtant , c’était exactement ce que je voulais??J'ai testé une "inflation d'icones sur le dash gauche , et bien je peux en mettre une ...et c'est tout , ça n'accepte pas plus que ce qu'il y a comme icônes ...pour le moment:mad: Y-a un truc qui m'echappe , encore , tu vas dire , pourquoi renommer ce fichier? pourquoi ne pas faire les modifs directement sur le theme , les manips sur le fichier modifié ne doivent pas etre affectés sur le fichier original ? Non ? sais pas ? Toujours est -il que la tailles des icônes sont toujours les mêmes ?? A voir ça plus tard , au plaisir @ + Jibel Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop @ jibel... J'ai fais ce que tu as dis , renommer le HY-D-V1 en mon theme02et comme tu as dis , faire les manips avec mon renommé thème02 ====> modifier la manip précédente : Bon ,je pense avoir compris où tu te trompes ... Tu vas dans ton dossier personnel ... Tu ouvres /.themes ...Tu ouvres /HYDV1 (ce n'est pas lui que l'on renomme) ... ==> donc il faut le remettre en ==> HYDV1 Tu vas voir un seul thème il me semble ==> Hydv1-Original ... C'est ce dossier là qu'il faut copier/coller sur place, et tu renommes la copie, en ==> theme02 ... C'est dans ce dossier renommer ==> theme02 que tu vas ouvrir en cascade (/.themes/HYDV1/theme02/css/style_css ) jusqu'à ce que tu vois le fichier ==> style_css ... Tu fais une copie sur place de ce fichier, tu vas avoir ==> style_css + style_css(copie) , et tu fais tes tests de modif dans le fichier original ... La copie te permet de revenir en arrière si tu fais des bêtises ... Voila , je pense être plus clair ... @ tous ... De mon côté ,la mise à égalité entre Fusion 12.04 et 13.04 avance j'ai modifié modifier les thèmes de la 12.04 pour ajouter les icônes qui lancent Mate et Cinnamon ... Avec le tuto de chrisripp, j'ai réussi à faire quelque chose de correcte graphiquement, sur les thèmes de la 12.04 ... J'ai changé le fichier /usr/share/hydv1/templates/lib/desktop.js , par celui que josepe36 m'a envoyé, (je pense que c'est celui du HY-D-V1 de la 13.04 ...) . J'ai copier les nouveaux thèmes de la 13.04, et çà marche ... J'ai fais ces manips sur deux clones de ma Fusion 12.04 ... Çà marche ... Je suis entrain de faire les manips sur mon poste de travail: Fusion 12.04, qui attendait bien sagement que toutes les manips soient testées et fonctionnent ... J'y ai installé le HY-D-V1 version 12.04, en supprimant le dossier hydv1, en local depuis synaptic ,dans l'onglet "Origine" ...Sinon, çà ne s'installe pas, et on n'a pas "Magic" ... Je n'ai plus qu'à ajouter Mate et Cinnamon , et à mettre en place les thèmes ... @+. Babdu89 ... J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop @Babdu89 , Ah bon , tu dis : Dans  (Attention  .themes  ;dossier cacher) ... ==> /home/.themes/HYDV1/   ... J'ai copier/coller sur place le thème Hydv1-Original ... Je l'ai renommé ==> mon-theme-02 Dans ce thème renommé je suis allé, comme le dit chrisripp à ==> /home/.themes/HYDV1/mon-theme-02/css/style.css J'ai ouvert le fichier ==> style.css et dans la section ==> LEFT DASH WINDOW , rubrique==> /* image in the left dash */  ... J'ai changé ==> width:40px;height:40px;           pour ==> width:25px;height:70px; Et c'est ce que j'ai fais , il me semble que ce que tu dis est autre chose ?Non ? J'insiste lourdement , je ne vois pas pourquoi faire une copie de la copie de la copie ( je blague , bien sur ) S'il y a un original , faire les manips avec ! Ça ne devrait pas poser de PB ,quand on connait ou faire les modifs , que tu as bien expliquées même si on se trompe dans les modifs du script , on peut revenir en arrière et les refaires , le script sera toujours a sa place , modif ou pas modif , copie /coller ou pas ... Et c'est ce que j'ai compris et fais .......... faire les modifs a partir du dossier renommé qui n'est en fait qu'une copie sans influence, la preuve ça n'a rien changé) sur les manips concernées pour le HY-D-V1 original et son fichier style.css Je n'ai pas compris , au vue des screens avec cette ribambelles d'icones dans le dash ?? Y-a QQchose qui m’échappe ?? Je sais que je suis un peu lent a la comprenette , mais tout de même Ce genre de modifs qui sont faites a partir de scripts dûment réfléchis , peuvent si on n'y fait pas attention , poser PB . Il existe QQpart une "foutue" app's qui devrait faire le boulot sans risque je l'ai vu et utilisé , ou est -elle?? U.Tweak, unity , paramètre de bureau , ça doit quand même se trouver QQpart ? ============================================================================================================== Comme je ne suis pas breton pour rien , j'ai voulu en avoir le coeur net , j'ai refais cette manip directement a partir de theme=========>HY-D-V1====>et la suite====> style.css=====> les modifs adéquats et voila ...J'ai mes icônes a la taille que je désirais , c'est y pas mieux comme ça ? merci pour ton aide Babdu 89 ......:) @+ Jibel Dernière modification par jibel (Le 11/06/2013, à 19:44) Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonsoir... Alors au sujet des manips ... je ne vois pas pourquoi faire une copie de la copie de la copie ( je blague , bien sur big_smile) S'il y a un original , faire les manips avec ! Ça ne devrait pas poser de PB , quand on connait ou faire les modifs , que tu as bien expliquées même si on se trompe dans les modifs du script , on peut revenir en arrière et les refaires , le script sera toujours a sa place , modif ou pas modif , copie /coller ou pas Lorsque j'ai à modifier des fichiers systèmes . J'ai pris pour habitude de faire des copies de sauvegarde des fichiers à modifier ... Sage précaution il me semble ... Si je me plante complètement, je peux revenir en arrière facilement. J'efface les fichiers modifiés, et je remets dans l'état d'origine les fichiers originaux ... Mon système re-fonctionne normalement . Je n'ai pas à chercher, quelles manips ont étés faites, pour les refaire à l'envers au risque de me tromper, et de tout embrouiller ... Bon ,maintenant , chacun fait comme il veux . faire les modifs a partir du dossier renommé qui n'est en fait qu'une copie sans influence, la preuve ça n'a rien changé) sur les manips concernées pour le HY-D-V1 original et son fichier style.css Là ,nous sommes devant un ensemble de fichiers dans un dossier ... Le thème . Le dossier renommé apparaît en tant que thème lui aussi dans le dash de droite . Si tu fais des modifs dans ce dossier ... Il faut, comme le dit chrisripp "rafraîchir" le thème , pour que l'on voit des effets les modifs faites ... "Rafraîchir" ==> On clique sur un autre thème , et on clique à nouveau sur le thème modifier, pour voir les effets de la modif . C'est ce que j'ai fais chez moi, et j'ai vu les effets des modifs ... Je n'ai pas compris , au vue des screens avec cette ribambelles d'icones dans le dash ??Y-a QQchose qui m’échappe ?? Alors , tu trouves comment réduire la taille des icônes ... Donc çà te permet d'en mettre plus .OK !!!... Mais tu en mets tellement plus, qu'à un moment, tu ne vas plus bien voir à quoi correspondent les icônes, à force de diminuer leur taille ... J'ai eu la curiosité de ne pas diminuer la taille des icônes des favoris ... D'en ajouter, d'en ajouter ... Jusqu'à ce que je ne voit plus si çà charge ,ou pas dans le dash de gauche ... Sans rien faire de plus, j'ai passé la souris sur le dash de gauche, et utilisé la molette ==> monter ,descendre , et j'ai vu les toutes icônes ajoutés ... Donc pour moi, je pense que changer la taille des icônes ne sert à rien, vu que l'on peut faire du "csrolling" sur le dash de gauche ... Il faut juste se souvenir que les icônes sont disponibles, grâce à un coup de molette de la souris .... Ce genre de modifs qui sont faites a partir de scripts dûment réfléchis , peuvent si on n'y fait pas attention , poser PB . Il existe QQpart une "foutue" app's qui devrait faire le boulot sans risque je l'ai vu et utilisé , ou est -elle?? U.Tweak, unity , paramètre de bureau , ça doit quand même se trouver QQpart ? Non!. ... Je en penses pas .... Ce n'est pas spécifique à Hybryde , comme l'était le "HY-Geek" avec la 11.10 il me semble ... Cette application graphique que josepe36 avait créée , modifiait le graphisme d'HYbryde ... Pas de Ubuntu . Là Ubuntu tweak &&&, c'est pour les modifs des environnements , mais pas pour changer quoi que ce soit dans les scripts d'Hybryde ... Heureusement d'ailleurs, car je ne te dis pas les soucis pour josepe36 , avec tous les "bidouilleurs du coin" , que nous sommes ... Comme je ne suis pas breton pour rien , j'ai voulu en avoir le coeur net , j'ai refais cette manip directement a partir de theme=========>HY-D-V1====>et la suite====> style.css=====> les modifs adéquats et voila ...J'ai mes icônes a la taille que je désirais , c'est y pas mieux comme ça ? Oui oui!! ... Jusqu'à ce que tu remplisses à nouveau le dash de gauche avec d'autres icônes de favoris .... @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop @Babdu89, bonsoir , J'ai pris pour habitude de faire des copies de sauvegarde des fichiers à modifier ... Sage précaution il me semble . je suis parfaitement d'accord avec ça , mais dans ce cas bien précis et avec tes indications données , il m'a semblé ne pas courir de risque en tentant cette manip .... de cette façon? "Rafraîchir" ==> On clique sur un autre thème , et on clique à nouveau sur le thème modifier, pour voir les effets de la modif . ??.... Je comprends +/- la finalité , en faisant cette manœuvre comme j'ai fais et que je redémarre la bécane , je verrais , aussi , le résultat , sinon je recommence J'ai bluffé !Tu as de toute façon raison dans l'absolu .... Ça a marché , tant mieux pour moi [b]Mais tu en mets tellement plus, qu'à un moment, tu ne vas plus bien voir à quoi correspondent les icônes, à force de diminuer leur taille ...[/b] Mais surtout a une taille correcte 30 pix pour moi, pas moins , 40 pix c'est trop gros , Jusqu'à ce que tu remplisses à nouveau le dash de gauche avec d'autres icônes de favoris ... Pas plus que ceux dont j'ai besoin , une douzaine , que je peux interchanger a mon gré au fur et a mesure de mes besoins , Il faut juste se souvenir que les icônes sont disponibles, grâce à un coup de molette de la souris .... ben , justement , chez moi ça ne scrolle pas des masses , c'est OK avec une page web ou autre chose , mais pas là?....... En tout cas , je suis content , Hybryde Fus. ça roule bien a part QQs petits détails Tiens , justement , je ne trouve pas l'icone du "screensaver" dans le catalogue des app's je suis obligé de le démarrer avec ....Synapse ?Ah bon? Si tu sais ou elle est cachée.?..... @+ de te lire , J.B. Dernière modification par jibel (Le 11/06/2013, à 23:55) Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour... Tiens , justement , je ne trouve pas l'icone du "screensaver" dans le catalogue des app's je suis obligé de le démarrer avec ....Synapse ?Ah bon? Si tu sais ou elle est cachée.?..... Et bien justement, il me semble que il n'y a plus d'économiseur d'écran installé avec les version de Ubuntu 12.04 et 13.04 ... Comme Hybryde est basée dessus, il n'y en a pas à priori ... Mon screensaver, c'est le bouton marche/arrêt de l'écran , je trouve çà plus efficace ... @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop @Babdu89, Bonjour, C'est bizarre , comment ce fait-il , s'il n'est plus la que je l'ouvre avec synaptic je ne pige pas a moins qu'il faille créer une icônes de lancement pour le screensaver ? je ne sais pas ? je suis le maniac de la bécane ouverte en tout temps sans repos , a la cravache et j'aime bien avoir un joli écran de veille , je ne sais pas si c'est bien de laisser toujours allumé , il y a des pour et des contres @+ jibel Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bon... Alors, je ne suis pas un adepte de ces machins là... Mais tu attises ma curiosité ... Donc dans synaptic, je vois aussi ; xscreensaver, qui marche. Cinnamon-screensaver, qui ne marche pas. Mate-screensaver, qui ne marche pas non plus . Gnome-screensaver, qui n'est pas installé . je l'installe ,mais il ne marche pas, enfin ,je n'ai pas accès à des réglages . Alors je teste xscreensaver ... xscreensaver J'ajoute un paquet,(xscreenesaver-gl) pour avoir plus de choix. Et je lance le truc. Je regarde dans ==> alacarte , il figure bien dans ==> Outils systèmes ==> preférences ... Je l'ai édité, mai rien y fait, il ne figure pas dans les menus d'Hybryde, donc il ne pourra pas être placé dans les favoris du dash de gauche ... Mais !!!... En passant par Unity, on ouvre le dash,dans la rechershe ==> xscrennsaver , et on glisse l'icône sur le bureau ... Un double clic==> message qui dit application non fiable &&&. Un clic droit==>propriétés==>permissions==> rendre exécutable ==> et voila on a une belle icône sur le bureau ... (au bout de mon pointeur) . Un double clic ... Voila, moi je le désactive, et si il m'enquiquine je le désinstalle ... je suis le maniac de la bécane ouverte en tout temps sans repos , a la cravache et j'aime bien avoir un joli écran de veille , je ne sais pas si c'est bien de laisser toujours allumé , il y a des pour et des contres Chez moi çà tourne toute la journée, mais lorsque je ne m'en sert pas, j’éteins l'écran ... @+. Babdu89 . Dernière modification par Babdu89 (Le 12/06/2013, à 16:10) J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop @Babdu89 je vois ça ,et je l'avais fais aussi poser l'icone sur le bureau , je ne veux pas que mon joli bureau soit encombré par des icônes partout , je préfère avoir comme dit plus haut les icônes favorites Point / dans le dash de gauche , mais c'est ce que je veux ..... Je suis allé dans /usr/share/applications =====> il est la. Je suis persuadé qu'on peut créer un lanceur / icone a partir de root ou autre pour avoir SON icone préféré .qui viendrait s'ajouter au menu des app's d'HY-D-V1 , y-a pas de raison ! Je l'avais fais avec unity , et comme de juste , je n'ai pas gardé la formule magique Par contre , et je trouve ça étrange , a moins que ça soit une volonté de josepe , pas sur le HY-D-V1 mais sur les autres environnements OUI ? Je les fais fonctionner sur tout les environnements sans PB Pour que screensaver fonctionne au top il faut ne pas hésiter a rajouter des trucs& machins dans synaptic(paquets) la c'est bien y-a de quoi s'amuser.......Il ne me faut pas grand chose , a moi ,pour me satisfaire.........Une bonne baguette , un saucisson et un bon verre de pinard et l'affaire est faite aller @ + jibel Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour... @ jibel ... Stp, nous n'allons pas "encombrer" le sujet du HY-D-V1, avec "nos histoires" de clonage , qui n'ont rien à voir avec ce sujet .... Si tu le veux bien , nous reprenons çà en MP , je te réponds en MP de suite ... Merci pour les lecteurs de ce sujet ... @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop PB de connexion ,voici le screen : http://hpics.li/86c8762 je te reponds en MP des que je suis rentré , merci au camarades @+ lol PB connexion ... Ah OK OK!!! ... Dès que tu me contactes en MP, nous supprimons ces messages inutiles .... Merci . Vu le screen ,tu vas pouvoir cloner, on fait çà ce soir si tu veux . @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne Elric1984 Re : HY-D-V1 un nouveau Desktop j'ai tester le ppa sur ma 13.04 (amd 64 sais pas si ça change quelque chose) et j'ai elric@elric-CQ1150FRm:~$ sudo add-apt-repository ppa:olivelinux36/hydv1-desktop-dev-raring [sudo] password for elric: Vous allez ajouter le PPA suivant à votre système : desktop Python Webkit Gtk HTML Javascript Plus d’info : https://launchpad.net/~olivelinux36/+archive/hydv1-desktop-dev-raring Appuyez sur [ENTRÉE] pour continuer ou Ctrl-C pour annuler l’ajout gpg: le porte-clefs « /tmp/tmpl4m81y/secring.gpg » a été créé gpg: le porte-clefs « /tmp/tmpl4m81y/pubring.gpg » a été créé gpg: demande de la clef 3C3C3D70 sur le serveur hkp keyserver.ubuntu.com gpg: /tmp/tmpl4m81y/trustdb.gpg : base de confiance créée gpg: clef 3C3C3D70 : clef publique « Launchpad PPA for larrieu » importée gpg: Quantité totale traitée : 1 gpg: importées : 1 (RSA: 1) OK elric@elric-CQ1150FRm:~$ sudo apt-get update Réception de : 1 http://ppa.launchpad.net raring Release.gpg [316 B] Atteint http://fr.archive.ubuntu.com raring Release.gpg Réception de : 2 http://ppa.launchpad.net raring Release [9 773 B] Atteint http://extras.ubuntu.com raring Release.gpg Atteint http://fr.archive.ubuntu.com raring-updates Release.gpg Atteint http://deb.opera.com stable Release.gpg Atteint http://fr.archive.ubuntu.com raring-backports Release.gpg Atteint http://extras.ubuntu.com raring Release Atteint http://fr.archive.ubuntu.com raring-proposed Release.gpg Atteint http://deb.opera.com stable Release Réception de : 3 http://security.ubuntu.com raring-security Release.gpg [933 B] Atteint http://extras.ubuntu.com raring/main Sources Atteint http://fr.archive.ubuntu.com raring Release Réception de : 4 http://ppa.launchpad.net raring/main amd64 Packages [14 B] Atteint http://fr.archive.ubuntu.com raring-updates Release Atteint http://extras.ubuntu.com raring/main amd64 Packages Atteint http://deb.opera.com stable/non-free amd64 Packages Atteint http://fr.archive.ubuntu.com raring-backports Release Atteint http://repo.steampowered.com precise Release.gpg Réception de : 5 http://www.openprinting.org lsb3.1 Release.gpg [230 B] Réception de : 6 http://ppa.launchpad.net raring/main i386 Packages [421 B] Atteint http://extras.ubuntu.com raring/main i386 Packages Réception de : 7 http://security.ubuntu.com raring-security Release [40,8 kB] Atteint http://fr.archive.ubuntu.com raring-proposed Release Atteint http://deb.opera.com stable/non-free i386 Packages Atteint http://fr.archive.ubuntu.com raring/main Sources Atteint http://fr.archive.ubuntu.com raring/restricted Sources Atteint http://fr.archive.ubuntu.com raring/universe Sources Atteint http://repo.steampowered.com precise Release Atteint http://fr.archive.ubuntu.com raring/multiverse Sources Atteint http://www.openprinting.org lsb3.1 Release Ign http://www.openprinting.org lsb3.1 Release Atteint http://fr.archive.ubuntu.com raring/main amd64 Packages Atteint http://fr.archive.ubuntu.com raring/restricted amd64 Packages Atteint http://fr.archive.ubuntu.com raring/universe amd64 Packages Atteint http://fr.archive.ubuntu.com raring/multiverse amd64 Packages Atteint http://repo.steampowered.com precise/steam Sources Réception de : 8 http://security.ubuntu.com raring-security/main Sources [30,2 kB] Ign http://www.openprinting.org lsb3.1/gutenprint amd64 Packages/DiffIndex Atteint http://fr.archive.ubuntu.com raring/main i386 Packages Atteint http://fr.archive.ubuntu.com raring/restricted i386 Packages Atteint http://fr.archive.ubuntu.com raring/universe i386 Packages Ign http://ppa.launchpad.net raring/main Translation-fr_FR Ign http://extras.ubuntu.com raring/main Translation-fr_FR Réception de : 9 http://security.ubuntu.com raring-security/restricted Sources [14 B] Atteint http://fr.archive.ubuntu.com raring/multiverse i386 Packages Ign http://www.openprinting.org lsb3.1/gutenprint i386 Packages/DiffIndex Ign http://extras.ubuntu.com raring/main Translation-fr Atteint http://repo.steampowered.com precise/steam amd64 Packages Atteint http://fr.archive.ubuntu.com raring/main Translation-fr Ign http://extras.ubuntu.com raring/main Translation-en Ign http://ppa.launchpad.net raring/main Translation-fr Réception de : 10 http://security.ubuntu.com raring-security/universe Sources [6 506 B] Atteint http://fr.archive.ubuntu.com raring/main Translation-en Ign http://ppa.launchpad.net raring/main Translation-en Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-fr Atteint http://fr.archive.ubuntu.com raring/multiverse Translation-en Réception de : 11 http://security.ubuntu.com raring-security/multiverse Sources [694 B] Atteint http://fr.archive.ubuntu.com raring/restricted Translation-fr Atteint http://fr.archive.ubuntu.com raring/restricted Translation-en Réception de : 12 http://security.ubuntu.com raring-security/main amd64 Packages [81,3 kB] Atteint http://fr.archive.ubuntu.com raring/universe Translation-fr Atteint http://repo.steampowered.com precise/steam i386 Packages Ign http://deb.opera.com stable/non-free Translation-fr_FR Atteint http://fr.archive.ubuntu.com raring/universe Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/main Sources Ign http://deb.opera.com stable/non-free Translation-fr Ign http://deb.opera.com stable/non-free Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/restricted Sources Réception de : 13 http://security.ubuntu.com raring-security/restricted amd64 Packages [14 B] Atteint http://fr.archive.ubuntu.com raring-updates/universe Sources Atteint http://fr.archive.ubuntu.com raring-updates/multiverse Sources Atteint http://fr.archive.ubuntu.com raring-updates/main amd64 Packages Réception de : 14 http://security.ubuntu.com raring-security/universe amd64 Packages [23,6 kB] Atteint http://fr.archive.ubuntu.com raring-updates/restricted amd64 Packages Atteint http://fr.archive.ubuntu.com raring-updates/universe amd64 Packages Atteint http://fr.archive.ubuntu.com raring-updates/multiverse amd64 Packages Réception de : 15 http://security.ubuntu.com raring-security/multiverse amd64 Packages [1 154 B] Atteint http://fr.archive.ubuntu.com raring-updates/main i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/restricted i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/universe i386 Packages Réception de : 16 http://security.ubuntu.com raring-security/main i386 Packages [80,6 kB] Atteint http://fr.archive.ubuntu.com raring-updates/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com raring-updates/main Translation-en Réception de : 17 http://security.ubuntu.com raring-security/restricted i386 Packages [14 B] Atteint http://fr.archive.ubuntu.com raring-updates/multiverse Translation-en Réception de : 18 http://security.ubuntu.com raring-security/universe i386 Packages [24,2 kB] Réception de : 19 http://security.ubuntu.com raring-security/multiverse i386 Packages [1 394 B] Atteint http://fr.archive.ubuntu.com raring-updates/restricted Translation-en Atteint http://fr.archive.ubuntu.com raring-updates/universe Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/main Sources Atteint http://fr.archive.ubuntu.com raring-backports/restricted Sources Atteint http://fr.archive.ubuntu.com raring-backports/universe Sources Atteint http://fr.archive.ubuntu.com raring-backports/multiverse Sources Atteint http://fr.archive.ubuntu.com raring-backports/main amd64 Packages Atteint http://fr.archive.ubuntu.com raring-backports/restricted amd64 Packages Atteint http://fr.archive.ubuntu.com raring-backports/universe amd64 Packages Atteint http://fr.archive.ubuntu.com raring-backports/multiverse amd64 Packages Atteint http://fr.archive.ubuntu.com raring-backports/main i386 Packages Atteint http://security.ubuntu.com raring-security/main Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/restricted i386 Packages Atteint http://fr.archive.ubuntu.com raring-backports/universe i386 Packages Atteint http://fr.archive.ubuntu.com raring-backports/multiverse i386 Packages Atteint http://security.ubuntu.com raring-security/multiverse Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/main Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/multiverse Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/restricted Translation-en Atteint http://security.ubuntu.com raring-security/restricted Translation-en Atteint http://fr.archive.ubuntu.com raring-backports/universe Translation-en Atteint http://fr.archive.ubuntu.com raring-proposed/universe amd64 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/main amd64 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/multiverse amd64 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/restricted amd64 Packages Atteint http://security.ubuntu.com raring-security/universe Translation-en Atteint http://fr.archive.ubuntu.com raring-proposed/universe i386 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/main i386 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/restricted i386 Packages Atteint http://fr.archive.ubuntu.com raring-proposed/main Translation-fr Atteint http://fr.archive.ubuntu.com raring-proposed/main Translation-en Atteint http://fr.archive.ubuntu.com raring-proposed/multiverse Translation-fr Atteint http://fr.archive.ubuntu.com raring-proposed/multiverse Translation-en Atteint http://fr.archive.ubuntu.com raring-proposed/restricted Translation-fr Atteint http://fr.archive.ubuntu.com raring-proposed/restricted Translation-en Atteint http://fr.archive.ubuntu.com raring-proposed/universe Translation-fr Atteint http://fr.archive.ubuntu.com raring-proposed/universe Translation-en Atteint http://www.openprinting.org lsb3.1/gutenprint amd64 Packages Atteint http://www.openprinting.org lsb3.1/gutenprint i386 Packages Ign http://repo.steampowered.com precise/steam Translation-fr_FR Ign http://repo.steampowered.com precise/steam Translation-fr Ign http://www.openprinting.org lsb3.1/gutenprint Translation-fr_FR Ign http://www.openprinting.org lsb3.1/gutenprint Translation-fr Ign http://repo.steampowered.com precise/steam Translation-en Ign http://www.openprinting.org lsb3.1/gutenprint Translation-en Ign http://security.ubuntu.com raring-security/main Translation-fr_FR Ign http://security.ubuntu.com raring-security/main Translation-fr Ign http://security.ubuntu.com raring-security/multiverse Translation-fr_FR Ign http://security.ubuntu.com raring-security/multiverse Translation-fr Ign http://security.ubuntu.com raring-security/restricted Translation-fr_FR Ign http://security.ubuntu.com raring-security/restricted Translation-fr Ign http://security.ubuntu.com raring-security/universe Translation-fr_FR Ign http://security.ubuntu.com raring-security/universe Translation-fr Ign http://fr.archive.ubuntu.com raring/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring/universe Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/main Translation-fr Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/multiverse Translation-fr Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/restricted Translation-fr Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-updates/universe Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/main Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/multiverse Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/restricted Translation-fr Ign http://fr.archive.ubuntu.com raring-backports/universe Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-backports/universe Translation-fr Ign http://fr.archive.ubuntu.com raring-proposed/main Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-proposed/multiverse Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-proposed/restricted Translation-fr_FR Ign http://fr.archive.ubuntu.com raring-proposed/universe Translation-fr_FR 302 ko réceptionnés en 10s (29,5 ko/s) Lecture des listes de paquets... Fait W: Erreur de GPG : http://www.openprinting.org lsb3.1 Release : Les signatures suivantes n'ont pas pu être vérifiées car la clé publique n'est pas disponible : NO_PUBKEY 7A4B44C2D2A2203E elric@elric-CQ1150FRm:~$ sudo apt-get install hydv1desktop Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Certains paquets ne peuvent être installés. Ceci peut signifier que vous avez demandé l'impossible, ou bien, si vous utilisez la distribution unstable, que certains paquets n'ont pas encore été créés ou ne sont pas sortis d'Incoming. L'information suivante devrait vous aider à résoudre la situation : Les paquets suivants contiennent des dépendances non satisfaites : hydv1desktop:i386 : Dépend: nautilus:i386 mais ne sera pas installé Dépend: metacity:i386 mais ne sera pas installé E: Impossible de corriger les problèmes, des paquets défectueux sont en mode « garder en l'état ». Ubuntu 13.10 intel i5/nvidia bassiste a ses heures très perdue Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour.Il n'y a pas encore de version en 64 bits des PPA du HY-D-V1 12.04 et 13.04 . Çà ne marche qu'avec le 32 bits . @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne tuxmarc Re : HY-D-V1 un nouveau Desktop Bonjour à tous les Hybrydiens J'ai téléchargé la dernière version 32 bits, collé le tout sur Multisystem, lancé et ....... c'est encore plus chouette que je pensais Suite logique des choses, lancer Gparted pour trouver où je vais le mettre sur le multiboot, ça y est, il y a une partition qui l'attent et là je me suis mis à chercher le programme d'installation. Là, je sèche ! Avec Magic, j'ai fouiné, pas trouvé et comme il y a une fonction de recherche, j'ai tenté "instal" .... rien, j'ai tenté "Hybryd" .... rien Où est il planqué le programme d'installation ?? Help ! Vive Richard Stalmann, Linus Torvalds, et tous les fondus de Linux. De l'Ordinosaure fait à 90% de récup, à un portable LDLC neuf sans système, en passant par une tour, un serveur et une carte mère sans boitier, tous libres !! Collection de 15 DD tous bien élevés au Linux sous la mère et se baladant d'une machine à l'autre. Parrain Linux sur www.parrain-linux.com et www.parrains.linux.free.fr Hors ligne jibel Re : HY-D-V1 un nouveau Desktop Salut Tuxmarc, dans le bureau HY-D-V1 en bas,( applications ,Hybryde, Magic) application=======>accessoires ======>install hybryd , et zou c'est parti @+ Jibel Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour. Ah!grillé !!! ... Salut jibel . Je repond quanrd même. Pour installer la version en 32 bits sur ta machine, ce qui est possible. Pour Hybryde Fusion 13.04 Il faut en session live aller dans le menu "Applications" ; "Accessoires" et tu vas trouver l'icône de lancement de l'installation de Hybryde Fusion. Pour Hybryde Fusion 12.04; En session live. C'est dans "Applications " Systèmes" que tu trouveras l'icône de lancement de l'installation de Hybryde Fusion. Comme Hybryde est basée sur Ubuntu, l'installation est identique à celle de Ubuntu. On peut aussi taper dans un terminal: ubiquity Ce qui démarre l'installateur. @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne jibel Re : HY-D-V1 un nouveau Desktop Bonjour Babdu89, "Ah!grillé !!! ... Salut jibel wink . Je repond quanrd même." t'as vu avec quelle rapidité j'ai répondu 8-) C'est normal , je me suis remis intensément a mon sport ! je viens de faire une M a J d'Hybryd 205Mo téléchargés dont Chromium , FF et autres app's, tout c'est bien passé ... rien d'anormal a signaler ! pourvu que ça dure , au plaisir de te lire ...@+ jibel Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Babdu89 Re : HY-D-V1 un nouveau Desktop Bonjour. @ jibel . Rappel . Mises à jours systèmes ,OK pas de soucis. Mais surtout pas de mise à niveau vers la 13.10 lors-qu'elle sera proposée, sinon Hybryde ne marche plus. ... À moins que josepe36 aie fait ce qu'il fallait pour que l'on puisse faire la mise à niveau d'Hybryde vers une version suivante de Ubuntu . Là il faut qu'il nous dise. je viens de faire une M a J d'Hybryd 205Mo téléchargés dont Chromium , FF et autres app's, tout c'est bien passé ... rien d'anormal a signaler ! pourvu que ça dure , Alors il faut en profiter pour en faire un clone sur un autre de tes hdd, avant que çà ne tourne mal . Ce n'est pas ce que je te souhaite, mais on ne sait jamais. Tu fais bien plus de modifs, installations de logiciels et paramétrages sur tes Os que moi sur les miens. Alors... @+. Babdu89 . Dernière modification par Babdu89 (Le 12/07/2013, à 11:50) J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne tuxmarc Re : HY-D-V1 un nouveau Desktop Merci Jibel, Merci Babdu69 C'était très discret mais grâce à vous deux, je l'ai débusqué le coquin Curieux, dans magic > accessoires > j'ai retapé "install" et il ne me propose que la logithèque Muon, bon tout ça c'est pas grave. C'est parti pour l'installation !!!! BANZAI !!! Vive Richard Stalmann, Linus Torvalds, et tous les fondus de Linux. De l'Ordinosaure fait à 90% de récup, à un portable LDLC neuf sans système, en passant par une tour, un serveur et une carte mère sans boitier, tous libres !! Collection de 15 DD tous bien élevés au Linux sous la mère et se baladant d'une machine à l'autre. Parrain Linux sur www.parrain-linux.com et www.parrains.linux.free.fr Hors ligne
I am migrating several hundred stored procedures from one server to another, so I wanted to write a stored procedure to execute an SP on each server and compare the output for differences. In order to do this, I would normally use this syntax to get the results into tables: select * into #tmp1 from OpenQuery(LocalServer,'exec usp_MyStoredProcedure') select * into #tmp2 from OpenQuery(RemoteServer,'exec usp_MyStoredProcedure') I then would union them and do a count, to get how many rows differ in the results: select * into #tmp3 from ((select * from #tmp1) union (select * from #tmp2)) select count(*) from #tmp1 select count(*) from #tmp3 However, in this case, my stored procedure contains an OpenQuery, so when I try to put the exec into an OpenQuery, the query fails with the error: The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "RemoteServer" was unable to begin a distributed transaction. Are there any good workarounds to this? Or does anybody have any clever ideas for things I could do to make this process go more quickly? Because right now, it seems that I would have to run the SP on each server, script the results into tmp tables, then do the compare. That seems like a poor solution! Thank you for taking the time to read this, and any help would be appreciated greatly!
I am struggling to understand the proper syntax for executing a subquery in SQLAlchemy when the value needs to be returned (i.e. not used in the WHERE). I am using the declarative approach. There are two models being used: class ProjectInvoices(Base): InvoiceID = Column(Integer(unsigned=True), default=0, primary_key=True, autoincrement=True) MasterProjectID = Column(Integer(unsigned=True), index=True, nullable=False) ExpenseAmount = Column(Numeric(10, 2), default=0) HoursAmount = Column(Numeric(10, 2), default=0) IsVoid = Column(Boolean, default=0, index=True) IsSubmit = Column(Boolean, default=0, index=True) class ProjectMasters(Base): MasterProjectID = Column(Integer(unsigned=True), default=0, primary_key=True, autoincrement=True) MasterProjectName = Column(Unicode(255)) MasterProjectMemo = Column(UnicodeText) IsActive = Column(Boolean, default=0, index=True) The point of the query is to determine the current amount invoiced for each project by using a subquery to sum the related invoices. There are other reasons this is being done in a subquery rather than just a join so I really need to figure out the subquery issue. This is an example of my current SA query: sqry = session.query( func.sum( func.ifnull(ProjectInvoices.ExpenseAmount, 0) + func.ifnull(ProjectInvoices.HoursAmount, 0))).label('billed_total') ).filter(and_(ProjectInvoices.IsVoid == 0, ProjectInvoices.IsSubmit == 1) ).subquery() result = session.query( ProjectMasters.MasterProjectID, ProjectMasters.MasterProjectName, sqry.columns.billed_total.label('invoice_total') ).filter(ProjectMasters.IsActive == 1).all() I have a feeling this is going to be embarrassing simple but I can't seem to crack the code on getting this to work. I have tried just about every sample I can find with mixed results. If I leave out the .correlate() argument I receive the following error: 'Alias' object has no attribute 'MasterProjectID' I have also tried adding the following statement to the end of the subquery() without any luck: .correlate(ProjectMasters.MasterProjectID, ProjectInvoices.MasterProjectID) If I do include the correlate argument then I receive the following error: TypeError: Boolean value of this clause is not defined Thanks for the help in advance...
Where can I find an online interactive console for programming language or api? @kuszi Put a great answer as a comment to the question, but I almost missed it because it was a comment rather than the answer. This link goes to a huuuge list of REPs and REPLs for tons of languages. repl.it supports multiple languages including Python, Ruby, Lua, Scheme, CoffeeScript, QBasic, Forth,...the list goes on. http://www.codepad.org/? It has support for a few languages, including perl, scheme, c/c++, python, lua and more. You can play around with jsScheme for Scheme, but it's a toy and shouldn't replace a console-based interpreter. Google Chrome Python shell https://chrome.google.com/extensions/detail/gdiimmpmdoofmahingpgabiikimjgcia You can try this http://doc.pyschools.com/console. It is actually an editor, and is good for testing your python code online when you do not have it installed on your computer. python web console, and I was able to run the code below # Script text here import itertools g = itertools.chain("AB", range(2)) print g.next() print g.next() print g.next() print g.next() http://repl.it/ is a Python in a browser without Java or Silverlight (as well as dozen of other languages compiled to JavaScript). http://lotrepls.appspot.com/ is a console that works reasonably well for all these scripting languages: Just hit CTRL+SPACE to switch languages or use the metacommand '/switch', for example '/switch clojure' to start coding in clojure.
Can someone tell me how to send a mail in a HTML format with sendmail in python? I would like to send this: <pre>some code</pre> Python version is 2.4.3 and can't be updated. # assemble the mail content from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText message = MIMEMultipart('alternative') message.add_header('Subject', 'subject goes here') # add a few more add_header calls here for things like "To", "Cc", "From" message.attach(MIMEText('some code')) # plain text alternative message.attach(MIMEText('<html><pre>some code</pre></html>', # html content 'html')) # pipe the mail to sendmail sendmail = os.popen('sendmail recipient@example.org', 'w') sendmail.write(message.as_string()) if sendmail.close() is not None: print 'error: failed to send mail :-(' You may check the code of webpy micro-framework for various methods of sending email, including the sendmail: https://github.com/webpy/webpy/blob/master/web/utils.py#L1415 Simply give the HTML code in the message and also mention the mime version and content as text/html. http://www.tutorialspoint.com/python/python_sending_email.htm I find a easy way to do this: When I run my script, I write my output in a file (mail.txt), then at the end, I just call: os.popen('cat mail.txt | sendmail -t') mail.txt content: To: my.mail@gmail.com MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="123" Subject: My subject This is a MIME-encapsulated message --123 Content-Type: text/html <html> <head> <title>HTML E-mail</title> </head> <body> <pre>Some code</pre> </body> </html> Maybe is not the best way to do this, but works fine for me...
toma222 [HOW TO] adesklets : configuration des desklets Il existe désormais un article sur le wiki concernant Adesklets donc je vous conseille de vous y fier, ce tutoriel n'étant plus mis à jour. J'ouvre ce deuxième post au sujet de adesklets, afin de permettre une meilleure lisibilité de l'ensemble.Celui-ci a donc pour but la configuration des desklets de adesklets, donc on considère que adesklets fonctionne déjà (sinon merci de poster sur l'un des deux sujets : adesklets : installation sous Breezy ou adesklets : installation sous Dapper ou Edgy). Configuration des desklets Ici, il faut comprendre que le système est différent de celui de gdesklets. En effet, dans celui-ci il suffit de glisser le desklet qui nous intéresse dans le programme, de double-cliquer dessus et de faire clique-droit pour pouvoir le configurer de façon graphique. Pour adesklets, les choses paraissent plus compliquées, mais c'est loin d'être insurmontable. Tout d'abord, il faut télécharger l'archive du desklet qui nous intéresse et la décompresser (on peut par exemple créer un répertoire dans son home où on stockera tous les desklets). Dans le dossier décompressé, on trouvera plusieurs fichiers intéressants : - le README. A lire impérativement, on peut y trouver des informations utiles (comme les dépendances nécessaires) au bon fonctionnement du desklet. - un fichier config.txt. C'est en éditant ce fichier qu'on pourra configurer notre desklet (dimensions, couleurs, icônes...). Ce fichier s'avère généralement bien fait et dépend du desklets en question donc je ne rentrerais pas dans les détails. - un dossier contenant les images du desklet (que l'on peut changer dans certains, par exemple pour moi les boutons de xmms_bar). - enfin, le fichier nom_du_desklet.py. C'est ce fichier qui permet de lancer notre desklet. On peut par exemple double-cliquer dessus et lancer dans un terminal. On nous demande alors si l'on veut le tester (dans ce cas il ne se relancera pas la prochaine fois qu'on démarre adesklets) ou l'enregistrer (pour qu'il apparaisse au prochain démarrage de adesklets). Remarque : il se peut que vous rencontriez une erreur concernant le police VeraBD lors du lancement d'un desklets. Dans ce cas, vous pouvez par exemple la remplacer par Vera dans le fichier de configuration du desklet concerné. Quelques astuces pour certains desklets Je reprend quelques astuces citées dans le premier post. - System Monitor : il se peut que la configuration par défaut du desklet pose problème. Par exemple, par défaut il y a un module pour la batterie, donc si vous n'avez pas de portable ou qu'il n'a pas de gestion de la batterie, il vous faut supprimer la partie correspondante dans le config. txt (en pensant à compléter le ) et ] si nécessaires). Il se peut également que les chemins indiqués ne correspondent pas à votre configuration (par exemple j'ai du modifier /proc/acpi/thermal_zone/TRM/temperature en /proc/acpi/thermal_zone/THRM/temperature) - Calendar (astuce donnée par mariop31) : pour mettre le calendrier en français, ajouter dans Calendar.py les lignes : import locale locale.setlocale(locale.LC_ALL,'fr_FR.UTF-8') - Weather (repris du post de Aldones) : pour connaître le code de votre ville, à entrer dans le config.txt à la ligne 'location', allez sur http://fr.weather.com/?from=footer, entrez le nom de votre ville et récupérez dans la barre d'adresses le code (4 lettres et 4 chiffres). Vous pouvez mettre ici tous les problèmes rencontrés sur les desklets, les astuces que vous auriez trouvé et toutes les remarques sont évidemment les bienvenues. Pensez également à aller faire un tour sur http://adesklets.sourceforge.net/ et pourquoi pas si vous vous débrouillez en anglais à poster sur leur forum. Dernière modification par toma222 (Le 01/08/2007, à 19:02) Hors ligne Doppler Re : [HOW TO] adesklets : configuration des desklets ça peut servir : http://adesklets.sourceforge.net/doc/fr Hors ligne toma222 Re : [HOW TO] adesklets : configuration des desklets Oui, effectivement j'ai pas pensé à le donner, merci (je l'ajoute dans la partie installation). Dernière modification par toma222 (Le 06/12/2005, à 17:31) Hors ligne Doppler Re : [HOW TO] adesklets : configuration des desklets Un peu d'aide pour débuter avec Modubar et Yab (en pensant à ceux qui ne pratiquent pas l'anglais et pour remercier Toma, Rapass et vous zot' de votre aide ) Modubar est un une barre de lancement qui déchire En fait c'est Yab améliorée, Modubar en reprend la base et y ajoute juste la possibilité d'intégrer des "modules" à la barre. Pour exemple Modubar comporte un module lors de sa mise en place, l'horloge. On peut en mettre d'autres, encore faut il savoir les concevoir pour le moment (mais ça risque changer)... Si vous n'avez que faire de l'horloge et des futurs modules, prennez Yab, c'est exactement pareil sans cette option. Si vous avez envie du joujou sachez qu'il ne consomme pas plus de ressources dans l'état (avec l'horloge en fonction) que Yab. Prérequis: adesklets 0.4.0 ou plus, ainsi que toutes ses dépendances, sont requis pour faire fonctionner cette appli correctement. N'importe quelle machine capable de faire tourner Yab ne devrait avoir aucun problème à faire de même avec Modubar. Et puis évidement Modubar ou Yab que l'on trouve par là http://adesklets.sourceforge.net/desklets.html Installation: c'est comme pour les autres desklets, du moins ceux qui ne demandent pas de paquets spécifiques, en dix secondes c'est fait. Paramétrer les lanceurs: Une fois la barre affichée on trouve les cholies icones qui lancent emacs, firefox, gimp, le terminal et xmms. C'est sympathique mais évidement on veut améliorer tout ça. Dans le fichier config.txt on va trouver les lignes suivantes: 'icons': [('emacs.png', 'GNU Emacs', 'emacs'), ('firefox.png', 'Firefox', 'firefox'), ('gimp.png', 'The GIMP', 'gimp-2.0'), ('terminal.png', 'Terminal', 'xterm'), ('xmms.png', 'XMMS', 'xmms')], C'est ici que l'on va paramétrer les lanceurs. Pour commencer, leur ordre: c'est simple la première ligne de la partie de code qui nous interesse (concernant emacs) affichera le premier lanceur en partant de la gauche, ainsi de suite. Pour chaque lanceur on a un paramétrage de type: ('l'adresse de l'icone', 'la légende qui s'affiche sous l'icone du lanceur', 'la commande qu'il déclanche'), ('firefox.png', 'Firefox', 'firefox'), Si on veut dans l'ordre firefox, evolution et le terminal ça donne: 'icons': [('firefox.png', 'Firefox', 'firefox'), ('evolution.png', 'Evolution', 'evolution')], ('/home/toto/adesklets/modubar-0.0.1/icons/terminal.png', 'Terminal', 'xterm')], Pour que cela fonctionne il faut d'une part avoir envoyé au préalable une icone en png nommé evolution dans .../modubar-0.0.1/icons/ et d'autre part s'appeller toto et avoir un dossier nommé adesklets dans son dossier perso etc... Si c'est le cas tout va bien sinon adaptez avec la direction où se trouve l'icone que vous visez, cela fonctionne aussi. Vous avez le choix, soit appeller une icone contenue dans le dossier icons de modubar en donnant juste son nom, ou bien aller chercher n'importe quelle icone (en png) n'importe où. Aprés enregistrement des modifications (Les sauvegardes sont tes amies...) et restart d'adesklets ça doit rouler. Autres paramètres pour les icones En réglant les nombres suivants (nb de pixels) la taille maximale des icones varie 'icon_max_height': 80, 'icon_max_width': 80, idem pour leur taille minimale 'icon_min_height': 54, 'icon_min_width': 54, Pour accélérer ou ralentir la vitesse de grossissement des icones modifiez 1.0 (seconde) ci dessous: - par 2.0 par exemple (effet lent) ou par 0.0 (pas d'effet) 'icon_maximize_threshold': 1.0, Dernier paramètre de la catégorie, l'espacement des icones, modifiez juste la valeur de: 'icon_spacing': 5, Les légendes ne vous plaisent pas ? Pour changer la police, remplacez Vera par Impact ou une autre dans la ligne suivante: (les noms de polices contenant un espace font planter) 'caption_font': 'Vera', Pour sa taille modifiez la valeur (comme 16 par exemple) dans : 'caption_size': 16, Et si l'on veut qu'elle soit rouge et non grises, on change 'AAAAAA' par 'FF0000' ici: (toute couleur héxadécimale devrait faire l'affaire) 'caption_color': 'AAAAAA', Pour modifier l'aspect de l'effet d'aparition de la légende bidouillez ces lignes - remplacer True par False pour supprimer l'effet - augmenter 0.5 permettra de faire durer l'effet (pendant x seconde) - modifier le nombre de pas - ici 30 - influence la fluidité 'caption_fade_in': True, 'caption_fade_in_duration': 0.5, 'caption_fade_in_steps': 30, Vous voulez les légendes au dessus des icones et non en dessous ? Changez False par True ici : 'caption_above': False, Et pour en finir avec les légendes cette ligne permet de modifier le temps qu'elles restent affichées après le passage de la souris. Cela doit avoir une utilité mais perso j'laisse comme ça, ça a l'air d'une formule pour exprimer "le moins de temps possible" 'caption_delay': 0.10000000000000001, Pour ce qui est de l'aspect de la barre... Trop large ? Trop fine ? Modifiez l'épaisseur en triturant : 'bar_height': 32, Les couleurs se décident par ces lignes - Background 1 = dégradé sur le fond de la barre vertical partant du haut vers le bas - Background 2 = idem mais partant du bas et en allant vers le haut - Foreground = contour de la barre Il ne reste plus qu'à modifier les couleurs ^^ j'vais tester pour voir si des fois des images... 'bar_background_1': 'AAAAAA', 'bar_background_2': 'AAAAAA', 'bar_foreground': '000000', De la transparence ? Pour régler l'opacité des backgrounds il suffit de jouer sur le pourcentage suivant: (100 opaque - None invisible) 'bar_opacity_1': 100, 'bar_opacity_2': None, Un dernier mot sur les dégradés, on peut jouer sur leur angle en modifiant le degré exprimé ici: 'bar_gradient_angle': 0, Les Clics Deux lignes bonus qui sont forts sympatiques... Clic effect va permettre de modifier la teinte (en %) qui est superposée à l'icone quand on clique dessus - alpha détermine l'opacité - red green et blue sont les teintes permettant ainsi l'accés au prisme RVB, on va pouvoir faire dans la finesse ! Clic effect duration laisse la possibilité d'augmenter la durée de l'effet (en secondes) après le clic, bien pratique aussi ^^ 'click_effect': 'tint(alpha=100,red=100,green=100,blue=100);', 'click_effect_duration': 0.10000000000000001, Que reste t'il ? Et bien les réglages des modules (mod_etc...) et donc de l'horloge pour commencer. Je n'ai aucune idée de tout ce que peuvent contenir les modules ni comment les réaliser, à découvrir ^^ Pour les paramétrages en tout cas vous devriez pouvoir expérimenter ça par vous même. Les lignes mod_background, mod_clock_font et autres devraient vous être compréhensibles maintenant. En fait il faut juste éviter de toucher à: 'modules': [('clock', 1)], Cette ligne sert à ajouter des modules, ça devrait venir plus tard... Enjoy Dernière modification par Doppler (Le 07/12/2005, à 06:27) Hors ligne toma222 Re : [HOW TO] adesklets : configuration des desklets Merci Doppler . Hors ligne geronimoO Re : [HOW TO] adesklets : configuration des desklets bonjour, je repost mon pb avec le desklet SystemMonitor, quand je le test voici le message d'erreur, et vu mes connaissances en C (quasi nul ) j'y arrive pas: Traceback (most recent call last): File "./SystemMonitor.py", line 1107, in ? EventHandler(dirname(__file__)).pause() File "./SystemMonitor.py", line 974, in __init__ adesklets.Events_handler.__init__(self) File "usr/lib/python2.4/site-packages/adesklets/events_handler.py", line 157, in __init__ File "./SystemMonitor.py", line 989, in ready join(self.basedir,'config.txt')) File "./SystemMonitor.py", line 265, in __init__ adesklets.ConfigFile.__init__(self, identifier, filename) File "usr/lib/python2.4/site-packages/adesklets/configfile.py", line 162, in __init__ File "usr/lib/python2.4/site-packages/adesklets/configfile.py", line 205, in _load_and_save File "usr/lib/python2.4/site-packages/adesklets/configfile.py", line 41, in __call__ File "/usr/lib/python2.4/compiler/transformer.py", line 52, in parse return Transformer().parsesuite(buf) File "/usr/lib/python2.4/compiler/transformer.py", line 129, in parsesuite return self.transform(parser.suite(text)) File "<string>", line 95 'background images': ['images/shared/bg_top.png', ^ SyntaxError: invalid syntax si quelqu'un a une idée...elle sera la bienvenue " Un bon indien est un indien mort " Général Sheridan, cavalerie des Etats Unis. Hors ligne toma222 Re : [HOW TO] adesklets : configuration des desklets Salut, juste pour info, les desklets sont programmés en python, pas en C. Je te post mon config.txt si ça peut t'aider : id0 = {'background colour': (210, 210, 210, 130), 'background images': ['images/shared/bg_top.png', 'images/shared/bg_middle.png', 'images/shared/bg_bottom.png'], 'meters': [('CPUMeter', {'horizontal padding': 8, 'icon': 'images/icons/cpu.png', 'krell': 'images/shared/krell.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'vertical padding': 8}), ('MemoryMeter', {'horizontal padding': 8, 'icon': 'images/icons/memory.png', 'krell': 'images/shared/krell.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update speed': 10, 'vertical padding': 8}), ('SwapMeter', {'horizontal padding': 8, 'icon': 'images/icons/swap.png', 'krell': 'images/shared/krell_blue.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update speed': 30, 'vertical padding': 8}), ('DiskSpaceMeter', {'horizontal padding': 8, 'icon': 'images/icons/diskfree.png', 'krell': 'images/shared/krell_blue_small.png', 'meter font name': 'Vera', 'meter font size': 6, 'trough': 'images/shared/trough_small.png', 'update speed': 60, 'vertical padding': 2}), ('TemperatureMeter', {'file': '/proc/acpi/thermal_zone/THRM/temperature', 'horizontal padding': 8, 'icon': 'images/icons/temperature.png', 'krell': 'images/shared/krell_red.png', 'max_temp': 100.0, 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update_speed': 30, 'vertical padding': 8})], 'text colour': (0, 0, 0, 200), 'update speed': 1} Hors ligne geronimoO Re : [HOW TO] adesklets : configuration des desklets Salut, juste pour info, les desklets sont programmés en python, pas en C. Je te post mon config.txt si ça peut t'aider : merki;) je test ça et vous tiens au courant PS: bon je sais pas s'il y a du mieux mais voila le message d'erreur: ./config.txt: line 2: syntax error near unexpected token `(' ./config.txt: line 2: `id0 = {'background colour': (210, 210, 210, 130),' Dernière modification par geronimoO (Le 07/12/2005, à 16:38) " Un bon indien est un indien mort " Général Sheridan, cavalerie des Etats Unis. Hors ligne Aldones Re : [HOW TO] adesklets : configuration des desklets Hello ! id0 = {'background colour': (210, 210, 210, 130), 'background images': ['images/shared/bg_top.png', 'images/shared/bg_middle.png', 'images/shared/bg_bottom.png'], 'meters': [('CPUMeter', {'horizontal padding': 8, 'icon': 'images/icons/cpu.png', 'krell': 'images/shared/krell.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'vertical padding': 8}), ('MemoryMeter', {'horizontal padding': 8, 'icon': 'images/icons/memory.png', 'krell': 'images/shared/krell.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update speed': 10, 'vertical padding': 8}), ('SwapMeter', {'horizontal padding': 8, 'icon': 'images/icons/swap.png', 'krell': 'images/shared/krell_blue.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update speed': 30, 'vertical padding': 8}), ('NetworkMeter', {'horizontal padding': 8, 'icon': 'images/icons/network.png', 'interface name': 'eth0', 'krell': ['images/shared/krell_green_small.png', 'images/shared/krell_red_small.png'], 'max down speed': 400, 'max up speed': 80, 'meter font name': 'Vera', 'meter font size': 7, 'trough': 'images/shared/trough_small.png', 'update speed': 2, 'vertical padding': 4}), ('DiskIOMeter', {'disk name': 'hda', 'horizontal padding': 8, 'icon': 'images/icons/disk.png', 'krell': ['images/shared/krell_green_small.png', 'images/shared/krell_red_small.png'], 'max read speed': 10240, 'max write speed': 10240, 'meter font name': 'Vera', 'meter font size': 7, 'trough': 'images/shared/trough_small.png', 'update speed': 2, 'vertical padding': 4}), ('DiskSpaceMeter', {'horizontal padding': 8, 'icon': 'images/icons/diskfree.png', 'krell': 'images/shared/krell_blue_small.png', 'meter font name': 'Vera', 'meter font size': 6, 'trough': 'images/shared/trough_small.png', 'update speed': 60, 'vertical padding': 2})], 'text colour': (0, 0, 0, 200), 'update speed': 1} id20 = {'background colour': (210, 210, 210, 130), 'background images': ['images/shared/bg_top.png', 'images/shared/bg_middle.png', 'images/shared/bg_bottom.png'], 'meters': [('CPUMeter', {'horizontal padding': 8, 'icon': 'images/icons/cpu.png', 'krell': 'images/shared/krell.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'vertical padding': 8}), ('MemoryMeter', {'horizontal padding': 8, 'icon': 'images/icons/memory.png', 'krell': 'images/shared/krell.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update speed': 10, 'vertical padding': 8}), ('SwapMeter', {'horizontal padding': 8, 'icon': 'images/icons/swap.png', 'krell': 'images/shared/krell_blue.png', 'meter font name': 'VeraBd', 'meter font size': 8, 'trough': 'images/shared/trough.png', 'update speed': 30, 'vertical padding': 8}), ('NetworkMeter', {'horizontal padding': 8, 'icon': 'images/icons/network.png', 'interface name': 'eth0', 'krell': ['images/shared/krell_green_small.png', 'images/shared/krell_red_small.png'], 'max down speed': 400, 'max up speed': 80, 'meter font name': 'Vera', 'meter font size': 7, 'trough': 'images/shared/trough_small.png', 'update speed': 2, 'vertical padding': 4}), ('DiskIOMeter', {'disk name': 'hda', 'horizontal padding': 8, 'icon': 'images/icons/disk.png', 'krell': ['images/shared/krell_green_small.png', 'images/shared/krell_red_small.png'], 'max read speed': 10240, 'max write speed': 10240, 'meter font name': 'Vera', 'meter font size': 7, 'trough': 'images/shared/trough_small.png', 'update speed': 2, 'vertical padding': 4})], 'text colour': (0, 0, 0, 200), 'update speed': 1} id21 = {'background colour': (210, 210, 210, 130), 'background images': ['images/shared/bg_top.png', 'images/shared/bg_middle.png', 'images/shared/bg_bottom.png'], 'meters': [('DiskSpaceMeter', {'horizontal padding': 8, 'icon': 'images/icons/diskfree.png', 'krell': 'images/shared/krell_blue_small.png', 'meter font name': 'Vera', 'meter font size': 6, 'trough': 'images/shared/trough_small.png', 'update speed': 60, 'vertical padding': 2})], 'text colour': (0, 0, 0, 200), 'update speed': 1} A copier/coller dans ton config.txt de sysmonitor, il fonctionne nickel Hors ligne da_last_dodo Re : [HOW TO] adesklets : configuration des desklets Bonjour, Est ce que quelqu'un sait comment faire pour que le fond (de SystemMonitor biensûr !) soit transparent ? J'ai enlevé la ligne background color.... et ça n'a rien donné. Merci d'avance Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7 Hors ligne Doppler Re : [HOW TO] adesklets : configuration des desklets Salut Dodo, de ce que je comprend il n'y a pas de ligne pour paramétrer le pourcentage de transparence comme avec Yab. SystemMonitor appelle bg_bottom.png , bg_middle.png et bg_top.png qui sont les images de fond. Le seul moyen qui me vient c'est d'ouvrir ces fichiers dans Gimp, et de là faire un fond totalement transparent puis de sauver. ça devrait faire l'affaire mais c'est pas pratique. Edition: essaie de coller un None à la place des valeurs dans : 'background images': ['images/shared/bg_top.png', 'images/shared/bg_middle.png', 'images/shared/bg_bottom.png'], J'ai pas system alors je suis pas sur du comment ^^ Dernière modification par Doppler (Le 07/12/2005, à 19:34) Hors ligne da_last_dodo Re : [HOW TO] adesklets : configuration des desklets Merci pour ta réponse Doppler. SystemMonitor n'aime pas trop ta suggestion "None" [shez@ubuntu:~/Apps/SystemMonitor-0.1.3]$ python SystemMonitor.py Traceback (most recent call last): File "SystemMonitor.py", line 1107, in ? EventHandler(dirname(__file__)).pause() File "SystemMonitor.py", line 974, in __init__ adesklets.Events_handler.__init__(self) File "/usr/lib/python2.4/site-packages/adesklets/events_handler.py", line 157, in __init__ self.ready() File "SystemMonitor.py", line 1019, in ready self.run_display() File "SystemMonitor.py", line 1049, in run_display bg_top = adesklets.load_image(join(self.basedir,self.config["background images"][0])) File "/usr/lib/python2.4/site-packages/adesklets/commands.py", line 646, in load_image return comm.out() File "/usr/lib/python2.4/site-packages/adesklets/commands_handler.py", line 103, in out raise ADESKLETSError(4,message) adesklets.error_handler.ADESKLETSError: adesklets command error - could not load image './None' - file does not exist Sinon, pour transformer les images que tu as cité en images transparent avec Gimp, on fait comment (je ne suis pas un pro du Gimp ) ? Dernière modification par da_last_dodo (Le 07/12/2005, à 19:44) Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7 Hors ligne Doppler Re : [HOW TO] adesklets : configuration des desklets Ici je viens d'ouvrir l'un des trois png en question dans Gimp, j'ai fait un control A control X et hop enregistrer. ça a l'air d'aller... Bon pour le coup c'est 100% transparent ^^ ps désolé pour les erreurs, c'était une idée comme ça... Dernière modification par Doppler (Le 07/12/2005, à 19:48) Hors ligne da_last_dodo Re : [HOW TO] adesklets : configuration des desklets Merci pour l'astuce pour faire les transparents (plutot une image vide avec les mêmes dimensions, mais bon...). Puis, j'ai mis le background color à 0, 0, 0, 0 Et maintenant, tout fonctionne ! Je vais enfin me passer de conky (qui est un p'tit peu moche à mon gout) Encore une fois merci Doppler ps : juste un dernier truc, ou est ce que je peut trouver les équivalence pour les couleurs en 4 chiffres (style 0, 0, 0, 0 correspont à transparent...) ? Dernière modification par da_last_dodo (Le 07/12/2005, à 20:03) Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7 Hors ligne Doppler Re : [HOW TO] adesklets : configuration des desklets Dirien chuis trop content de pouvoir aider pour une fois ^^ C'est vrai que faire apparaitre une image vierge c'est franchement inutile, autant rien faire apparaitre. Doit y avoir moyen... à trouver... PS à ton PS: aucune idée, ça ressemble à un alpha=0 red=0 green=0 blue=0 (en %) mais à part ça... bon faut vraiment que j'installe system monitor ^^ Dernière modification par Doppler (Le 07/12/2005, à 20:16) Hors ligne Doppler Re : [HOW TO] adesklets : configuration des desklets Classe ! Viva Tux n' Tosh ^^ Hors ligne belou Re : [HOW TO] adesklets : configuration des desklets da_last_dodo : ta montre avec date, c'est un desklets qui va avec adesklets ou gdesklets ou est ce qu on peut le trouver ? Hors ligne da_last_dodo Re : [HOW TO] adesklets : configuration des desklets C'était un gdesklet (je me suis converti au adesklets maintenant ;-) ) Au niveau ressources, je trouve que gdesklets pompe énormement. Voici mon nouveau bureau (j'ai qu'un 15" et on vite fait le tour avec le nombre de desklets) Dernière modification par da_last_dodo (Le 08/12/2005, à 22:48) Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7 Hors ligne geronimoO Re : [HOW TO] adesklets : configuration des desklets oller dans ton config.txt de sysmonitor, il fonctionne nickel merci je test de suite! PS: merci ça fonctionne merci a toi Aldones! Dernière modification par geronimoO (Le 09/12/2005, à 12:34) " Un bon indien est un indien mort " Général Sheridan, cavalerie des Etats Unis. Hors ligne geronimoO Re : [HOW TO] adesklets : configuration des desklets bon j'ai un pb assez particulier, voir étrange j'ai pris le config.txt de Aldones, le desklets se lance. Maintenant je voudrais modifier certaines choses comme la connection au web qui chez moi se fait par eth0 et non ppp0. J'edit le fichier, le modifie (en root ) et l'enregistre. Si je retourne dans ce fichier mes modifs ont jusqu'à la bien été prise en compte. Maintenant je lance le desklet, mon interface web est inactive. Je ferme mon desklet, retourne sous le fichier config.txt, il s'est remis comme auparavant! J'ai tenté en le modifiant et fermant la session, en enlevant les droits utilisateurs dessus, rien n'y fait! help " Un bon indien est un indien mort " Général Sheridan, cavalerie des Etats Unis. Hors ligne seb2py Re : [HOW TO] adesklets : configuration des desklets C'est vrai que faire apparaitre une image vierge c'est franchement inutile, autant rien faire apparaitre. Doit y avoir moyen... à trouver... Chez moi, j'ai simplement modifié la ligne comme suit : id1 = {'background_image': '', et j'ai un fond transparent !!! Sous Ubuntu Precise / Unity Hors ligne Bismut Re : [HOW TO] adesklets : configuration des desklets J'ai un problème peut-être similaire... J'essaie de faire fonctionner Yab et System Monitor... Après moultes bidouillages, j'arrive enfin à faire afficher les 2 desklets au lancement de adesklets. Malheureusement, certaines modifications des fichiers de config. n'ont aucun effet. Par exemple, les 2 desklets se lancent en haut à gauche, l'un sur l'autre... Je les déplace, ok... mais si je ferme et je relance, paf, ils sont de nouveau en haut à gauche... J'ai trouvé un fichier .adesklets dans mon répertoire perso. qui indique apparemment l'ensemble de mes desklets et leur position : Je spécifie bien à Yab par exemple d'être à 600 - 600 mais s'ouvre quand même en haut à gauche... Bref, rien ne semble y faire... une idée ? PS : Un clic droit et Configure sur un Desklet ne fait absolument rien, c'est normal ? Dernière modification par Bismut (Le 19/12/2005, à 22:04) Mac Mini 2009 avec Archlinux Asus EeePC S101 avec Archlinux HTC Magic avec Android Hors ligne toma222 Re : [HOW TO] adesklets : configuration des desklets Essaies de supprimer le fichier .adesklets et de réenregister tes desklets. Le configure par clic droit qui ne donne rien, c'est normal. De toute façon, si ça marchait, ça t'ouvrirais juste le fichier config.txt de ton desklet. Hors ligne belou Re : [HOW TO] adesklets : configuration des desklets coment qu'on fait pour que mon Modubar soit tjrs visible marre de tjrs afficher bureau pour pouvoir lancer un appli Hors ligne
i am trying to make an inversed document index, therefore i need to know from all unique words in a collection in which doc they occur and how often. i have used this answer in order two create a nested dictionary. The provided solution works fine, with one problem though. First i open the file and make a list of unique words. These unique words i than want to compare with the original file. When there is a match, the frequency counter should be updated and its value be stored in the two dimensional array. output should eventually look like this: word1, {doc1 : freq}, {doc2 : freq} <br> word2, {doc1 : freq}, {doc2 : freq}, {doc3:freq} etc.... Problem is that i cannot update the dictionary variable. When trying to do so i get the error: File "scriptV3.py", line 45, in main freq = dictionary[keyword][filename] + 1 TypeError: unsupported operand type(s) for +: 'AutoVivification' and 'int' I think i need to cast in some way the instance of AutoVivification to int.... How to go? thanks in advance my code: #!/usr/bin/env python # encoding: utf-8 import sys import os import re import glob import string import sets class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value def main(): pad = 'temp/' dictionary = AutoVivification() docID = 0 for files in glob.glob( os.path.join(pad, '*.html') ): #for all files in specified folder: docID = docID + 1 filename = "doc_"+str(docID) text = open(files, 'r').read() #returns content of file as string text = extract(text, '<pre>', '</pre>') #call extract function to extract text from within <pre> tags text = text.lower() #all words to lowercase exclude = set(string.punctuation) #sets list of all punctuation characters text = ''.join(char for char in text if char not in exclude) # use created exclude list to remove characters from files text = text.split() #creates list (array) from string uniques = set(text) #make list unique (is dat handig? we moeten nog tellen) for keyword in uniques: #For every unique word do for word in text: #for every word in doc: if (word == keyword and dictionary[keyword][filename] is not None): #if there is an occurence of keyword increment counter freq = dictionary[keyword][filename] #here we fail, cannot cast object instance to integer. freq = dictionary[keyword][filename] + 1 print(keyword,dictionary[keyword]) else: dictionary[word][filename] = 1 #extract text between substring 1 and 2 def extract(text, sub1, sub2): return text.split(sub1, 1)[-1].split(sub2, 1)[0] if __name__ == '__main__': main()
Introduction web2py[web2py] est un framework web libre et open-source pour le développement agile et sécurisé d'applications web pilotées par base de données; il est écrit en Python[python] et programmable en Python. web2py est un framework complet, contenant donc tous les composants nécessaires pour construire des applications web totalement fonctionnelles. web2py est conçu pour guider le développeur web à suivre les bonnes pratiques de l'ingénierie logicielle, telles que l'utilisation du pattern Modèle Vue Contrôleur (MVC). web2py sépare la représentation des données (modèle) de la présentation des données (la vue) et également de la logique applicative et de ses flux de travail (le contrôleur). web2py fournit des librairies pour aider le développeur à dessiner, implémenter et tester chacune des trois parties séparément, et les faire fonctionner ensemble. web2py est construit pour la sécurité. Cela signifie qu'il élimine automatiquement la plupart des problèmes qui peuvent amener à des failles de sécurité, en suivant des pratiques bien établies. Par exemple, toute entrée est validée (pour éviter les injections), toute sortie est contrôlée (pour éviter le cross-site scripting), et tout fichier uploadé est renommé (pour éviter toute attaque traverse de répertoireà. web2py fait attention aux principaux problèmes de sécurité, afin que les développeurs aient le moins de chande d'introduire des failles dans leur développement. web2py inclut une couche d'abstraction à la base de données (Database Abstraction Layer -DAL) qui écrit les requêtes SQL[sql-w] dynamiquement afin que vous, développeurs, n'ayez pas à le faire. Cette couche d'abstraction (DAL) sait parfaitement comment générer les requêtes SQL de manière transparente pour SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix] et Ingres[ingresdb]. La couche d'abstraction peut également générer des appels de fonction pour le Datastore Google lorsqu'elle fonctionne sur les Google App Engine (GAE)[gae]. De manière expérimentale, nous supportons plus de bases de données et de nouvelles sont constamment ajoutées. Veuillez vérifier le site web de web2py et la mailing list pour trouver les connecteurs les plus récents. Une fois qu'une ou plusieurs tables ont été définies, web2py génère automatiquement une interface d'aministration web complète pour accéder à la base de données et aux tables. web2py diffère des autres frameworks web du fait que ce soit le seul à totalement adopter le paradigme Web 2.0, où le web est l'ordinateur. En fait, web2py ne nécessite aucune installation ou configuration; il fonctionne sur n'importe quelle architecture qui peut exécuter du Python (Windows, Windows CE, Mac OS X, iOS, et Unix/Linux), et le développement, le déploiement, et les phases de maintenance phases pour les applications peuvent être faites via une interface web locale ou distante. web2py fonctionne avec CPython (l'implémentation C) et PyPy (Python écrit en Python), sur les versions Python 2.5, 2.6, et 2.7. web2py fournit un système de tickets pour les erreurs remontées. Si une erreur survient, un ticket est attribué à l'utilisateur et l'erreur est enregistrée pour l'administrateur. web2py est open source et distribué sous la licence LGPG version 3. Une autre fonctionnalité importante de web2py est que nous, ses développeurs, travaillons à maintenir une rétro-compatibilité pour les versions futures. Ce maintien est assuré depuis la sortie de la première release de web2py en Octobre 2007. De nouvelles fonctionnalités ont été ajoutées et des bugs ont été corrigés, mais si le programme fonctionnait avec web2py 1.0, alors ce programme fonctionnera même mieux aujourd'hui. Trouvez ici quelques exemples de déclarations web2py qui illustrent leur pouvoir et leur simplicité. Le code suivant : db.define_table('person', Field('name'), Field('image', 'upload')) créé une table de base de données appelée "person" avec deux champs : "name", une chaîne de caractères ; et "image", quelque chose qui a besoin d'être uploadé (l'image actuelle dans ce cas). Si la table existe déjà mais ne correspond pas à cette définition, elle va être modifiée en conséquence. Etant donné la table définie ci-dessus, le code suivant : form = SQLFORM(db.person).process() créé un formulaire d'insertion pour cette tables qui permet aux utilisateurs d'uploader les images. Cela valide également le formulaire soumis, renomme l'image envoyée de manière sécurisée, stocke l'image dans un fichier, insère l'enregistrement correspondant dans la base de données, évite une double soumission, et modifie éventuellement le formulaire lui-même en ajoutant les messages d'erreur si les données transmises par l'utilisateur ne sont pas valides. Ce code embarque un wiki totalement fonctionnel contenant tags, recherche, nuage de tags, permissions, pièces jointes, et le support: def index(): return auth.wiki() Alors que le code suivant : @auth.requires_permission('read','person') def f(): .... empêche les visiteurs d'accéder à la fonction f à moins que le visiteur soit un membre du groupe ayant les droits de "lecture" sur les enregistrement de la table "person". Si le visiteur n'est pas connecté, il est redirigé sur une page d'identification (fournie automatiquement par défaut par web2py). web2Py supporte également les composants, c'est à dire les actions qui peuvent être chargées dans une vue et intéragir avec le visiteur via des requêtes Ajax sans avoir à recharger la page entière. Ceci est fait via l'assistant LOAD qui autorise un design très modulaire des applications; ce sujet est traité dans le chapitre 3 dans le contexte du wiki et un peu plus en détails dans le dernier chapitre de ce livre. Cette 5ème édition de ce livre décrit web2py 2.4.1 et les versions suivantes. Principes La programmation Python respecte typiquement les principes de base suivants : Ne pas se répéter soi-même. Il ne devrait y avoir qu'une seule façon de faire les choses. Explicite est mieux qu'implicite. web2py englobe totalement les deux premiers principes en forçant le développeur à utiliser les pratiques d'ingénierie logicielle du son décourageant toute répétition de code. web2py accompagne le développeur à travers quasiment toutes les tâches communes dans le développement d'application web (création et traitement des formulaires, gestion des sessions, des cookies, des erreurs, etc...) web2py diffère des autres frameworks par rapport au troisième principe, entrant parfois en conflit avec les deux autres. En particulier, web2py n'importe pas les applications utilisateur, mais les exécute dans un contexte prédéfini. Ce contexte révèle les mots-clés Python, aussi bien que les mots-clés web2py. Pour certains, ceci peut apparaître comme magique, mais cela ne devrait pas. Simplement, en pratique, quelques modules sont déjà importés sans que vous l'ayez fait. web2py essaie d'éviter ces caractéristiques ennuyantes des autres frameworks qui forcent le développeur à importer les mêmes modules en haut de chaque modèle et contrôleur. web2py, en important ses propres modules, fait gagner du temps et évite des erreurs, qui plus est en respectant l'esprit du "ne te répète pas toi-même" et "il ne devrait y avoir qu'une façon de faire les choses". Si le développeur souhaite utiliser d'autres modules Python ou des modules tiers, ces modules doivent être importés explicitement, comme dans n'importe quel autre programme Python. Frameworks web A son niveau le plus fondamental, une application web consiste en un ensemble de programmes (ou fonctions) qui sont exécutées lorsque l'URL correspondante est visitée. La sortie du programme est retournée au visiteur et rendue par le navigateur. Le but des frameworks web est d'autoriser les développeurs à construire de nouvelles applications rapidement, facilement et sans erreurs. C'est faisable en fournissant les APIs et les outils qui réduisent et simplifient la quantité de code requise. Les deux approches classiques pour le developpement d'applications web sont: Le premier modèle est celui qui est suivi, par exemple, immédiatement par des scripts CGI. Le second modèle est suivi, par exemple, par PHP[php] (où le code est en PHP, un langage similaire au C), ASP (où le code est en Visual Basic), et JSP (où le code est en Java). Ci-dessous, un exemple de programme PHP qui retrouve les données depuis une base de données lors de son exécution, et qui retourne une page HTML affichant les enregistrement sélectionnés : <html><body><h1>Records</h1><? mysql_connect(localhost,username,password); @mysql_select_db(database) or die( "Unable to select database"); $query="SELECT * FROM contacts"; $result=mysql_query($query); mysql_close(); $i=0; while ($i < mysql_numrows($result)) { $name=mysql_result($result,$i,"name"); $phone=mysql_result($result,$i,"phone"); echo "<b>$name</b><br>Phone:$phone<br /><br /><hr /><br />"; $i++; } ?></body></html> Le problème avec cette approche est que le code est embarqué dans l'HTML, et ce même code a besoin de générer du contenu HTML additionel. Il a également besoin de générer des déclarations SQL pour requêter la base de données, et en mélangeant ces différentes couches de l'application, la lecture et la maintenance du code devient très difficile. Cette situation est d'autant plus difficile pour des applications Ajax, que la complexité augmente avec le nombre de pages (fichiers) qui constituent l'application. Cette fonctionnalité présentée dans l'exemple ci-dessus peut être exprimée avec seulement deux lignes de code Python dans web2py : def index(): return HTML(BODY(H1('Records'), db().select(db.contacts.ALL))) Dans cet exemple simple, la structure de la page HTML est représentée de manière programmée par les objets HTML, BODY, et H1; la base de données db est requêtée par la commande select; et finalement, tout est sérialisé dans l'HTML. Notons bien que db n'est pas un mot-clé mais bien une variable définie par l'utilisateur. Cette terminologie sera utilisée tout au long du document pour représenter la connection à la base de données pour éviter toute confusion. Les frameworks web sont généralement catégorisés comme l'un des types suivants : Un framework "glue" est un framework construit en assemblant (en collant ensemble) plusieurs composants tiers. Un framework "complet" est construit en créant des composants prévus spécifiquement pour être étroitement intégrés et fonctionnels ensemble. web2py est un framework complet. Presque tous ses composants sont construits de zéro et sont prévus pour fonctionner ensemble, mais fonctionnant aussi bien en dehors du framework web2py. Pour exemple, la couche d'abstration à la base de données (DAL) or les templates de langues peuvent être utilisés indépendamment du framework web2Py en important gluon.dal ou gluon.template dans vos propres propres applications Python. gluon est le nom du module web2py qui contient des librairies système. Quelques librairies web2py, telles que la construction pour le traitement des tables de la base de données par les formulaires, ont des dépendances avec d'autres parties de web2Py. web2py peut également fonctionner avec des librairies Python tierces, incluant d'autres templates de langue et couches d'abstrations à la base de données, mais ne seront pas aussi bien intégrés que les composants originaux. Modèle-Vue-Contrôleur wzb2py encourage le développeur à séparer la représentation des données (le modèle), la présentation des données (la vue) et le traitement du flux applicatif (le contrôleur). Reconsidérons l'exemple précédent et voyons comment il est possible de construire une application web2py autour. Ci-après, un exemple d'interface d'édition MVC web2py : Le flux générique d'une requête web2py est décrit dans le diagramme suivant : Dans le diagramme : Le serveur peut être intégré au serveur web we2py où bien un serveur tiers, tel qu'un serveur Apache. Le serveur prend en charge le multi-threading . "main" est l'application WSGI principale. Elle exécute toutes les tâches communes et englobe les application utilisateur. Il gère les cookies, les sessions, les transactions, le routage d'URL et le routage inverse, ainsi que le déploiement. Elle peut proposer et diffuser des fichiers statiques si le serveur ne le fait pas encore. Les composants Modèle (Model), Vue (View) et Contrôleur (Controller) construisent l'application utilisateur. Plusieurs applications peuvent être hébergées sur une même instance web2py. Les flèches en pointillés représentent la communication avec le(s) moteur(s) de base de données. Les requêtes à la base peuvent être écrites en langage SQL pur (déconseillé) ou en utilisant la couche d'abstration à la base de données (recommandé), afin que le code de l'application web2py ne soit pas dépendant d'un moteur spécifique de base de données. Le répartiteur créé le lien entre les URL demandées et un appel de fonction dans le contrôleur. La sortie de la fonction peut être une chaîne de caractères ou un dictionnaire de symboles (une table de hash). Les données contenues dans le dictionnaire sont affichées par une vue. Si le visiteur demande une page HTML (comportement par défaut), le dictionnaire est rendu comme page HTML. Si le visiteur demande la même page en XML, web2py essaie de trouver une vue qui peut effectuer le rendu du dictionnaire en XML. Le développeur peut créer des vues pour effectuer des rendus dans n'importe lequel des protocoles déjà supportés (HTML, XML, JSON, RSS, CSV, et RTF) ou dans des protocoles personnalisés additionels. Tous les appels sont englobés dans une transaction, et n'impote quelle exception non traitée entraînera l'annulation de la transaction. Si la requête réussit, la transaction est validée. web2py prend également en charge les sessions et les cookies de session automatiquement, et lorsqu'une transaction est validée, la session est alors stockée, à moins qu'un autre comportement n'ait été spécifié. Il est possible d'enregistrer des tâches récurrentes (via cron) pour démarrer de manière programmée et/ou après l'exécution de certaines actions. Par ce moyen, il est possible de démarrer de longues tâches intensives en arrière-plan sans ralentir la navigation. Ci-après, une application minimale et complète MVC, en trois fichiers : "db.py" est le modèle : db = DAL('sqlite://storage.sqlite') db.define_table('contact', Field('name'), Field('phone')) Une connexion à la base de données est établie (dans cet exemple, une base de données SQLite est stockée dans le fichier storage.sqlite) et une table nommée contact est définie. Si la table n'existe pas, web2Py la créé et, de manière transparente en arrière-plan, génère le code SQL approprié pour le moteur de base de données choisi et utilisé. Le développeur peut voir la requête SQL générée mais n'a pas besoin de changer le code si le système de base de données, par défaut en SQLite, est remplacé par MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres ou Google App Engine (SQL et NoSQL). Une fois la table définie et créée, web2py génère également une interface de gestion web entièrement fonctionnel pour la base de données, appelée appadmin, pour accéder à la base et à ses tables. "default.py" est le contrôleur : def contacts(): grid=SQLFORM.grid(db.contact, user_signature=False) return locals() Dans web2py, les URLs sont liées à des modules Python et à des appels de fonction. Dans ce cas, le contrôleur contient une fonction unique (ou "action") appelé contacts. Une action peut retourner une châine de caractères (la page web) ou un dictionnaire Python (un ensemble de paires clé:valeur) ou un ensemble de variables locales (comme dans cet exemple). Si la fonction retourne un dictionnaire, le tout est transmis à une vue avec le même nom que le nom de la fonction (ou du contrôleur), qui effectue le rendu de la page en retour. Dans cet exemple, la fonction contacts génère une grille de select/search/create/update/delete pour la table db.contact et renvoie la grille à la vue. "default/contacts.html" est la vue: {{extend 'layout.html'}} <h1>Manage My Contacts</h1> {{=grid}} Cette vue est appelée automatiquement par web2py après que la fonction associée du contrôleur (action) ait été exécutée. Le but de cette vue est d'effectuer le rendu des variables contenues par le dictionnaire retourné (dans notre cas grid) en HTML. Le fichier de vue est écrit en HTML, mais peut embarquer du code Python délimité par les balises spéciales {{ et }}. Ceci diffère un peu du code d'exemple PHP, car le seul code embarqué dans l'HTML est le code de "couche de présentation". Le fichier "layout.html" au début de la vue est fournie par web2py et constitue la mise en page pour toutes les applications web2py. Ce fichier peut facilement être modifié ou remplacé. Pourquoi Web2py web2py est l'un des nombreux frameworks d'application web, mais il est devenu très persuasif grâce à de nombreuses fonctionnalités uniques. web2py était à la base développé comme un outil d'apprenrissage, avec les motivations principales suivantes : Facilité pour les utilisateurs à apprendre le développement côté serveur sans compromettre de fonctionnalité. Pour cette raison, web2py ne requiert aucune installation ou configuration, n'a pas de dépendences (à l'exception de la distribution du code source qui requiert Python 2.5 et ses librairies standard), et présente la plupart de ses fonctiionnalités via une interface web, incluant un Environnement de Développement Intégré avec les outils de débogage et une interface pour la base de données. web2py a été stable dès le premier jour grâce à une approche descendante; c'est à dire que l'API a été dessinée avant d'être implémentée. Même si de nouvelles fonctionnalités ont été ajoutées, web2py n'a jamais cessé sa rétro-compatibilité, et ne l'arrêtera pas lorsque de nouvelles fonctionnalités seront ajoutées dans le futur. web2py s'intéresse de manière pro-active aux plus importantes failles de sécurité qui peuvent tourmenter les applications web les plus modernes comme déterminé par OWASP[owasp]ci-après. web2py est très léger. Le coeur du système (librairies), incluant la couche d'abstration à la base de données, les modèles de langues, et tous les assistants ne pèsent que 1.4MO. Le code source entier incluant les des exemples d'application et les images pèsent environ 10.4MO. web2py a une empreinte très petite et est très rapide. Il utilise le serveur web WSGI Rocket rocketdéveloppé par Timothy Farrell. Sa rapidité est comparable à celle obtenue grâce au module Apache mod_wsgi, et supporte SSL et IPv6. web2py utilise la syntaxe Python pour les modèles, les contrôleurs et les vues, mais n'importe pas les modèles et contrôleurs (comme font tous les autres frameworks) - au lieu de cela, il les exécute. Cela signifie que les applications peuvent être installées, déinstallées et modifiées sans avoir à redémarrer le serveur web (même en production), et différentes applications peuvent co-exister sans qu'il y ait d'interférence entre les modules. web2py utilise une couche d'abstraction à la base de données (Database Abstraction Layer - DAL) au lieu d'un d'un Mapping Objet-Relationnel (Object Relational Mapper - ORM). D'un point de vue conceptuel, ceci signifie que différentes tables de la base de données sont mappées en différentes instances d'une classe Tableet non pas en différentes classes, alors que les enregistrements sont mappés en instances d'une classeRowet non en instances d'une classe de la table correspondate. D'un point de vue pratique, cela signifie que la syntaxe SQL effectue des correspondances presque une à une en syntaxe DAL, et qu'il n'y a aucune meta-classe complexe à programmer comme dans la plupart des ORM, ce qui ajouterait de la latence. Ci-après, une capture d'écran de l'interface admin principale de web2py : Sécurité L'"Open Web Application Security Project" [owasp] (OWASP) est une communauté internationale libre et ouverte avec pour principal but l'amélioration de la sécurité des applications logicielles. OWASP a listé le top 10 des problèmes de sécurité entraînant un risque pour les applications web. Cette liste est copiée ici, avec une description pour chacune sur l'impact avec web2Py : cross site scripting"Cross Site Scripting (XSS): les failles XSS apparaissent lorsqu'une application utilise des données fournies par l'utilisateur et les envoie à un navigateur web sans effectuer une première validation ou encodage du contenu. XSS permet aux attaquants d'exécuter des scripts sur le navigateur de la victime qui peuvent détourner des sessions utilisateur, dégrader des sites web, potentiellement injecter des virus, etc..."web2py, par défaut, rejette toute variable injectée dans la vue, pour éviter tout XSS. injection flaws"Les failles d'injection : ces failles, particulièrement en injection SQL, sont communes aux applications web. Une injection arrive lorsque les données fournies par l'utilisateur sont envoyées à un interpréteur comme commande ou requête. Les données de l'attaquant brouillent l'interpréteur en exécutant des commandes inattendues ou en changeand des données."web2py inclut une couche d'abstraction à la base de données rendant l'injection SQL impossible. Normalement, les déclarations SQL ne sont pas écrités par le développeur. Au lieu de cela, la requête SQL est générée dynamiquement par la couche d'abstraction à la base de données, s'assurant ainsi que toute donnée à insérer dans la base est correctement formatée. malicious file execution"Exécution de fichier malicieux : du code vulnérable à de l'inclusion de fichier distant (Remote File Inclusion - RFI) permet à un attaquant d'inclure du code et des données hostiles, résultant en des attaques dévastatrices, telle qu'une mise en péril d'un serveur entier."web2py n'autorise que les fonctions exposées à être exécutées, évitant ainsi l'exécution de fichier malicieux. Les fonctions importées ne sont jamais exposées; seules les actions sont exposées. web2py utilise un interface d'aministration web qui rend très facile le suivi de ce qui est exposé et de ce qui ne l'est pas. insecure object reference"Référence directe à un oject non sécurité : une référence directe à un objet peut survenir lorsqu'un développeur expose une référence à l'implémentation d'un objet interne, tel qu'un fichier, un répertoire, un enregistrement en base de données ou une clé, comme une URL ou un paramètre de formulaire. Les attaquants peuvent manipuler ces références pour obtenir l'accès à d'autres objets sans autorisation."web2py n'expose aucun objet interne; de plus, web2py valide toutes les URLs, évitant ainsi les attaques transverses de répertoire (directory travesal attacks). web2py fournit également un mécanisme simple pour crééer des formulaires qui valident automatiquement toutes les valeurs en entrée. CSRF"Les requêtes criminelles Cross-Site (Cross Site Request Forgery - CSRF): Une attaque CSRF force le navigateur d'une victime connectée à envoyer une requête pré-authentifiée à une application web vulnérable, forçant ainsi le navigateur de la victime à exécuter une action hostile au bénéfice de l'attaquant. CSRF peut être aussi puissant que l'application web qu'il attaque."web2py évite les CSRF aussi bien que les doubles soumissions accidentelles de formulaires en assigant un jeton aléatoire éphémère à chaque formulaire. De plus, web2py utilise un UUID pour les cookies de session. information leakageimproper error handling"Les fuites d'information et la prise en charge d'erreurs incorrectes : Les applications peuvent non intentionnellement laisser des fuites d'information sur leur configuration, des travaux internes, ou porter atteinte à l'intimité à travers une variété de problèmes applicatifs. Les attaquants utilisent cette faiblesse pour voler des données sensibles, ou conduire à des attaques plus sérieuses."web2py inclut un système de ticket. AUcune erreur ne peut résulter en code qui serait exposé à l'utilisateur. Toutes les erreurs sont loguées et un ticket est assigné à l'utilisateur autorisant le suivi de l'erreur. Mais les erreurs et le code source impliqué ne sont uniquement accessibles que par l'administrateur. "Authentification cassée et gestion de session : les identifiants de compte et les jetons de session ne sont souvent pas protégés correctement. Les attaquants peuvent détourner les mots de passe, les clés ou les jetons d'authentifications pour utiliser l'identité d'autres utilisateurs." web2Py fournit un mécanisme intégré pour l'authentification administrateur, et gère les sessions indépendamment pour chaque application. L'interface d'administration force l'utilisation de cookies de session sécurisés lorsque le client n'est pas en "localhost". Pour les applications, une puissante API basée sur des contrôles d'accès par rôle (Role Base Access Control) est inclue. cryptographic store"Stockage cryptographique non sécurisé : les applications web utilisent très rarement les fonctions de cryptographie correctement pour protéger les données et les identifiants de connexion. Les attaquants utilisent des données faiblement protégées pour effectuer du vol d'identification et autres crimes, telles que les fraudes de carte de crédit."web2py utilise les algorithmes de hachage MD5 ou HMAC+SHA-512 pour protéger les mots de passe stockés. Les autres algorithmes sont également disponibles. secure communications"Communications non sécurisées : les applications échouent fréquemment pour chiffrer le trafic réseau lorsqu'il est nécessaire de protéger des communications sensibles."web2py inclut le serveur[ssl]Rocket WSGI incluant le support SSL activé par défaut, mais peut également utiliser Apache ou Lighttpd et le module mod_ssl pour fournir la couche de chiffrement SSL des communications. access restriction"Echec de restriction d'accès à certaines URL : La plupart du temps, une application protège uniquement les fonctionnalités sensibles en évitant l'affichage de liens ou URLs à des utilisateurs non autorisés. Les attaquants peuvent utiliser cette faiblesse pour accéder et exécuter des opérations non autorisées en accédant à ces URLs directement."web2py effectue un lien entre chaque requête URL te les modules et fonctions Python. web2py fournit un mécanisme pour déclarer quelles fonctions sont publiques et lesquelles nécessitent une authentification préalable pour autorisation. L'API de contrôle d'accès par rôle autorise les développeurs à restreindre l'accès à n'importe quelle fonction en se basant sur le login, l'appartenance à un groupe ou les permissions de groupe. Les permissions sont très granulaires et peuvent être combinées avec des filtres de base de données pour permettre, par exemple, de donner un accès à certaines tables spécifiques et/ou à des enregistrements. web2py permet également d'utiliser les URLs signées numériquement et fournit une API pour signer numériquement les callbacks Ajax. web2py a été revu pour sa sécurité et vous pouvez trouver le résultat de cette revue en référence [pythonsecurity]. Dans la boîte Vous pouvez télécharger web2py depuis le site web officiel : http://www.web2py.com web2py est composé des éléments suivants : librairies: fournissent le coeur des fonctionnalités de web2py et sont accessibles de manière programmable. serveur web: le serveur web WSGI Rocket. l'application admin: utilisée pour créer, dessiner et gérer les autres applications web2py.adminfournir un Environnement de Développement Intégré (EDI) web complet pour construire des applications web2py. Il inclut également d'autres fonctionnalités, telles qu'un moteur de test et un shell web. les applications exemples: contiennent de la documentation et des exemples interactifs. Lesexemplessont un clone du site web officiel web2py.com, et incluent la documentation epydoc. l'application bienvenue: le template de base pour n'importe quelle autre application. Par défaut, il inclut un menu déroulant pur CSS et un système d'authentification d'utilisateur (présenté dans le chapitre 9). web2py est distribué en code source, et en fichiers binaires pour Microsoft Windows et Mac OS X. La distribution du code source peut être utilisée sur n'importe quelle plateforme où Python est installé et inclut les composants ci-après mentionnés. Pour exécuter le code source, vous avez besoin de Python 2.5, 2.6 ou 2.7 pré-installé sur le système. Vous aurez également besoin d'installer l'un des moteurs de base de données supportés. Pour des tests et des applications nécessitant peu de requêtes, vous pouvez utiliser la base de données SQLite, inclue avec Python 2.7. Les versions binaires de web2py (pour Windows et Mac OS X) incluent un interpréteur Python 2.7 et une base de données SQLite. Techniquement, ces deux composants ne font pas partie de web2py. En les incluant dans les distributions binaires, cela vous permet uniquement de démarrer web2py directement. L'image suivante montre la structure globale de web2py : Tout en bas, nous pouvons trouver l'interpréteur. En remontant, nous trouvons le serveur web (rocket), les librairies, et les applications. Chaque application possède son propre schéma MVC (modèles, contrôleurs, vues, modules, langages, bases de données, et fichiers statiques). Chaque application inclut son propre code d'administration de la base (appadmin). TOutes les instances web2py démarrent avec trois applications : welcome (l'application de base), admin (l'EDI web), et les exemples (copie du site web et exemples). A propos de ce livre Ce livre inclut les chapites suivants, suite à cette introduction : Le chapitre 2 est une introduction minimaliste à Python. Il suppose une connaissance des concepts de la programmation procédurale et orientée objet tels que les boucles, les conditions, les appels de fonctions et de classes, et les principales syntaxes Python. Il couvre également les exemples de modules Python qui sont utilisés à tout au long de ce livre. Si vous connaissez déjà bien Python, vous pouvez passer ce chapitre. Le chapitre 3montre comment démarrer web2py, parle de l'interface d'administration, et guide le lecteur à travers des exemples variés en augmentant la complexité: une application qui retourne une chaine de caractères, une application compteur, un blog, et une application complète de wiki qui autorise l'envoi d'images et de commentaires, fournit l'authentification, les autorisations, les services web et un flux RSS. En lisant ce chapitre, vous serez peut être amené à vous référer au chapitre 2 pour des syntaxes Python génériques et aux chapitres suivants pour des références plus détaillées sur les fonctions qui sont utilisées. Le chapitre 4 couvre plus particulièrement la structure du coeur de web2py et les librairies : le mapping d'URL, les requêtes, les réponses, les sessions, le cache, l'ordonnanceur, le cron, l'internationalisation et les flux de travail généraux. Le chapitre 5 est une référence pour le template de langue utilisée pour la construction des vues. Il montre comment embarquer du code Python dans du code HTML, et explique comment utilise les assistants (objets permettant la génération de code HTML). Le chapitre 6 couvre la couche d'abstraction à la base de données, ou DAL (Database Abstraction Layer). La syntaxe de la DAL est présentée à travers une série d'exemples. Le chapitre 7 couvre les formulaires, la validation de ces formulaires et leur traitement. FORM est un assistant bas-niveau pour la construction de formulaires. SQLFORM est un constructeur de formulaire haut-niveau. Dans le chapitre 7, nous verrons également des API Création/Lecture/Mise à jour/Suppression (Create/Read/Update/Delete - CRUD) Le chapitre 8 couvre les fonctionnalités de communication, d'envoi d'emails et de SMS. Le chapitre 9 couvre l'authentification, les autorisations et le mécanisme de contrôle d'accès basé sur les rôles disponible dans web2py. La configuration mail et CAPTCHA sont également présentées ici, puisqu'utilisées pour l'authentification. Dans la troisième édition de ce livre, une partie a été ajoutée pour les authentifications possibles avec l'intégration de mécanismes tiers tels que OpenID, OAuth, Google, Facebook, Linkedin, etc... Le chapitre 10 est au sujet de la création de services web dans web2py. Nous fournissons des exemples d'intégration avec le Google Web Toolkit via Pyjamas, et avec Adobe Flash via PyAMF. Le chapitre 11 est à propos de web2py et des possibilités avec jQuery. web2py est construit principalement pour de la programmation côté serveur, mais inclut jQuery, puiqu'elle s'avère être la meilleure librairie JavaScript disponible pour les effets et Ajax. Dans ce chapitre, nous discuterons donc des possibilités d'intégration de jQuery avec web2py. Le chapitre 12 présente les composants et plugins web2py comme une possibilité de construire des applications modulables. Nous fournissons un exemple de plugin qui implémente les principales fonctionnalités, telles que la mise en forme de diagrammes, les commentaires et les tags. Le chapitre 13 explique le déploiement en production d'applications web2py. Plus spécifiquement, le déploiement un serveur web LAMP est présenté (ce qui est considéré comme étant la principale alternative de déploiement). Des serveurs web alternatifs sont également présentés, ainsi que la configuration d'une base de données PostgreSQL. D'autres points sont présentés comme l'exécution en tant que service sur un environnement Microsoft Windows, et le déploiement sur certaines plateformes spécifiques incluant Google Applications Engine, Heroku, et PythonAnywhere. Dans ce chapitre, les problèmes de sécurité et s'évolutivité sont également soulevés. Le chapitre 14 contient une variété d'autres possibilités pour résoudre des tâches spécifiques, incluant les mises à jour, le geocoding, la pagination, l'API Twitter et bien plus encore. Ce livre couvre uniquement les fonctionnalités de base de web2py et l'API fournie avec web2py. Ce livre ne couvre pas les appliances web2py (i.e. des applications prêtes à l'emploi). Vous pouvez télécharger les appliances web2py depuis le site correspondant [appliances]. Vous pouvez trouver des sujets complémentaires discutés dans les usergroup[usergroup]. Il y a également AlterEgo[alterego], l'ancien blog de web2py et sa FAQ. Ce livre a été écrit en utilisant la syntaxe markmin et automatiquement converti en HTML, LaTeX et PDF. Support Le principal canal de support est le usergroup[usergroup], avec ses dizaines de posts par jour. Même si vous êtes un débutant, n'hésitez pas demander - nous serons ravis de pouvoir vous aider. Il y a également un système de suivi de bug officiel sur http://code.google.com/p/web2py/issues . Enfin, une information importante, vous pouvez obtenir du support professionnel (voir le site web pour plus de détails). Contribute Toute aide est vraiment appréciée. Vous pouvez aider les autres utilisateurs sur les groupes utilisateur, ou en envoyant directement des patchs sur le programme (sur le site GitHub https://github.com/web2py/web2py). Même si vous trouvez une erreur dans ce livre, ou si vous avez une amélioration à apporter, le meilleur moyen de le faire est de patcher le livre directement (sous le dossier source sur le repository à https://github.com/mdipierro/web2py-book). Eléments de style PEP8 [style] contient des bonnes pratiques de style lorsque l'on développe en Python. Vous verrez que web2py ne suit pas toujours ces règles. Ce n'est ni par oubli ni par négligence; c'est notre conviction que les utilisateurs devraient suivre ces règles et nous les y encourageons. Nous avons choisi de ne pas suivre certaines de ces règles en définissant les objects d'assistants afin de minimiser la probabilité de conflits de noms avec des objets définis par l'utilisateur. Par exemple, la classe qui représente une <div> est appelée DIV, alors que si l'on se réfère à la référence Python, elle devrait avoir été appelée Div. Nous pensons que, pour cet exemple spécifique, utiliser une déclaration tout en majuscule "DIV", est un choix plus naturel. De plus, cette approche laisse aux programmeurs la liberté de créer une classe appelée "Div" s'ils le souhaitent. Notre syntaxe s'intègre également de manière naturelle à la notation DOM pour la plupart des navigateurs (incluant, par exemple, Firefox). En se référant au guide de style Python, toutes les chaines de caractères majuscules devraient être utilisée pour des constantes et non pour des variables. En continuant avec notre exemple, même en considérant que DIV est une classe, c'est une classe spéciale qui ne devrait jamais être modifiée par l'utilisateur car une telle modification impacterait toutes les autres applications web2py. Par ailleurs, nous pensons qu'en qualifiant la classe DIV comme quelquechose de constant, ceci justifie totalement cette notation. En résumé, les conventions suivantes sont respectées : Les assistants HTML et les validateurs sont en majuscultes pour les raisons évoquées précédemment (par exemple, DIV,A,FORM,URL). L'objet de traduction Test en majuscule malgré le fait que ce soit une instance de classe et non une classe. Logiquement, l'objet de traduction exécute une action similaire aux assistants HTML, et affecte une partie du rendu de la présentation. Aussi,Tnécessite d'être facile à localiser dans le code et doit avoir un nom court. Les classes DAL suivent le guide de style Python (la première lettre uniquement en majuscule), par exemple Table,Field,Query,Row,Rows, etc... Dans tous les autres cas, nous espérons avoir suivi, autant que possible, le Guide de Style Python (PEP8). Par exemple, toutes les instances d'objets sont en minuscules (request, response, session, cache), et toutes les classes internes sont en majuscules. Dans tous les exemples de ce libre, les mots-clés web2py sont mis en gras, alors que les chaines de caractères et les commentaires sont mis en italique. Licence web2py est distribué sous licence LGPL version 3. Le texte complet de la licence est disponible en référence [lgpl3]. En respect de la licence LGPL, vous pouvez: redistribuer web2py avec vos application (en incluant les versions binaires officielles) mettre à disposition vos applications utilisant les librairies officielles web2py sous la licence que vous souhaitez Cependant vous devez: être clair dans votre documentation en mentionnant l'utilisation de web2py dans votre application mettre à disposition toute modification des librairies web2py sous licence LGPLv3 The license includes the usual disclaimer: THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. **Versions précédentes* Les versions précédentes de web2py, 1.0.*-1.90.*, ont été mises à disposition sous la licence GPL2 avec une exception commerciale, qui pour des raisons pratiques, était très similaire à la licence courante LGPLv3. Contenu tiers distribué avec web2py web2py contient du contenu tiers dans le répertoire gluon/contrib et des fichiers JavaScript et CSS variés. Ces fichiers sont distribués avec web2py sous leurs licences originales, comme énoncé dans les fichiers. Reconnaissances web2py est développé et sous copyright de Massimo Di Pierro. La première version (1.0) a été mise en ligne en Octobre 2007. Depuis, elle a été adoptée par de nombreux utilisateurs, et certains d'entre eux ont contribué aux rapports de bugs, aux tests, au débug, aux patchs et à la relecture de ce livre. La plupart des développeurs et des contributeurs sont, par ordre alphabétique : Adam Bryzak, Adam Gojdas, Adrian Klaver, Alain Boulch, Alan Etkin, Alec Taylor, Alexandre Andrade, Alexey Nezhdanov, Alvaro Justen, Anand Vaidya, Anatoly Belyakov, Ander Arbelaiz, Anders Roos, Andrew Replogle, Andrew Willimott, Angelo Compagnucci, Angelo and Villas, Annet Vermeer, Anthony Bastardi, Anton Muecki, Antonio Ramos, Arun Rajeevan, Attila Csipa, Ben Goosman, Ben Reinhart, Benjamin, Bernd Rothert, Bill Ferret, Blomqvist, Boris Manojlovic, Branko Vukelic, Brent Zeiben, Brian Cottingham, Brian Harrison, Brian Meredyk, Bruno Rocha, CJ Lazell, Caleb Hattingh, Carlos Galindo, Carlos Hanson, Carsten Haese, Cedric Meyer, Charles Law, Charles Winebrinner, Chris Clark, Chris May, Chris Sanders, Christian Foster Howes, Christopher Smiga, Christopher Steel, Clavin Sim, Cliff Kachinske, Corne Dickens, Craig Younkins, Dan McGee, Dan Ragubba, Dane Wright, Danny Morgan, Daniel Gonz, Daniel Haag, Daniel Lin, Dave Stoll, David Adley, David Harrison, David Lin, David Marko, David Wagner, Denes Lengyel, Diaz Luis, Dirk Krause, Dominic Koenig, Doug Warren, Douglas Philips, Douglas Soares de Andrade, Douglas and Alan, Dustin Bensing, Elcio Ferreira, Eric Vicenti, Erwin Olario, Falko Krause, Farsheed Ashouri, Felipe Meirelles, Flavien Scheurer, Fran Boon, Francisco Gama, Fred Yanowski, Friedrich Weber, Gabriele Alberti, Gergely Kontra, Gergely Peli, Gerley Kontra, Gilson Filho, Glenn Caltech, Graham Dumpleton, Gregory Benjamin, Gustavo Di Pietro, Gyuris Szabolcs, Hamdy Abdel-Badeea, Hans C. v. Stockhausen, Hans Donner, Hans Murx, Huaiyu Wang, Ian Reinhart Geiser, Iceberg, Igor Gassko, Ismael Serratos, Jan Beilicke, Jay Kelkar, Jeff Bauer, Jesus Matrinez, Jim Karsten, Joachim Breitsprecher, Joakim Eriksson, Joe Barnhart, Joel Carrier, Joel Samuelsson, John Heenan, Jon Romero, Jonas Rundberg, Jonathan Benn, Jonathan Lundell, Jose Jachuf, Joseph Piron, Josh Goldfoot, Josh Jaques, Jose Vicente de Sousa, Jurgis Pralgauskis, Keith Yang, Kenji Hosoda, Kenneth Lundstr, Kirill Spitsin, Kyle Smith, Larry Weinberg, Limodou, Loren McGinnis, Louis DaPrato, Luca De Alfaro, Luca Zachetti, Lucas D'Avila, Madhukar R Pai, Manuele Presenti, Marc Abramowitz, Marcel Hellkamp, Marcel Leuthi, Marcello Della Longa, Margaret Greaney, Maria Mitica, Mariano Reingart, Marin Prajic, Marin Pranji, Marius van Niekerk, Mark Kirkwood, Mark Larsen, Mark Moore, Markus Gritsch, Mart Senecal, Martin Hufsky, Martin Mulone, Martin Weissenboeck, Mateusz Banach, Mathew Grabau, Mathieu Clabaut, Matt Doiron, Matthew Norris, Michael Fig, Michael Herman, Michael Howden, Michael Jursa, Michael Toomim, Michael Willis, Michele Comitini, Miguel Goncalves, Miguel Lopez, Mike Amy, Mike Dickun, Mike Ellis, Mike Pechkin, Milan Melena, Muhammet Aydin, Napoleon Moreno, Nathan Freeze, Niall Sweeny, Niccolo Polo, Nick Groenke, Nick Vargish, Nico de Groot, Nico Zanferrari, Nicolas Bruxer, Nik Klever, Olaf Ferger, Oliver Dain, Olivier Roch Vilato, Omi Chiba, Ondrej Such, Ont Rif, Oscar Benjamin, Osman Masood, Ovidio Marinho Falcao Neto, Pai, Panos Jee, Paolo Betti, Paolo Caruccio, Paolo Gasparello, Paolo Valleri, Patrick Breitenbach, Pearu Peterson, Peli Gergely, Pete Hunt, Peter Kirchner, Phyo Arkar Lwin, Pierre Thibault, Pieter Muller, Piotr Banasziewicz, Ramjee Ganti, Richard Gordon, Richard Ree, Robert Kooij, Robert Valentak, Roberto Perdomo, Robin Bhattacharyya, Roman Bataev, Ron McOuat, Ross Peoples, Ruijun Luo, Running Calm, Ryan Seto, Salomon Derossi, Sam Sheftel, Scott Roberts, Sebastian Ortiz, Sergey Podlesnyi, Sharriff Aina, Simone Bizzotto, Sriram Durbha, Sterling Hankins, Stuart Rackham, Telman Yusupov, Thadeus Burgess, Thomas Dallagnese, Tim Farrell, Tim Michelsen, Tim Richardson, Timothy Farrell, Tito Garrido, Tyrone Hattingh, Vasile Ermicioi, Vidul Nikolaev Petrov, Vidul Petrov, Vinicius Assef, Vladimir Donnikov, Vladyslav Kozlovsky, Vladyslav Kozlovskyy, Wang Huaiyu, Wen Gong, Wes James, Will Stevens, Yair Eshel, Yarko Tymciurak, Yoshiyuki Nakamura, Younghyun Jo, Zahariash. Je suis sûr que j'oublie des personnes, et j'en suis désolé. Je remercie particulièrement Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran et Patrick pour leurs contributions majeures à web2py et Anthony, Alvaro, Brian, Bruno, Denes, Dane Denny, Erwin, Felipe, Graham, Jonathan, Hans, Kyle, Mark, Margaret, Michele, Nico, Richard, Roberto, Robin, Roman, Scott, Shane, Sharriff, Sriram, Sterling, Stuart, Thadeus, Wen (et les autres) pour leur relecture précise des différentes version de ce livre. Leur contribution est inestimable. Si vous trouvez des erreurs dans ce libre, elles sont exclusivement de ma faute, probablement introduite par une édition de dernière minute. Je remercie également Ryan Steffen de Wiley Custom Learning Solutions pour son aide lors de la publication de la première édition de ce livre. web2py contient du code des auteurs suivants, que je tiens vraiment à remercier : Guido van Rossum pour Python[python], Peter Hunt, Richard Gordon, Timothy Farrell pour le serveur web Rocket[rocket], Christopher Dolivet pour EditArea[editarea], Bob Ippolito pour simplejson[simplejson], Simon Cusack et Grant Edwards pour pyRTF[pyrtf], Dalke Scientific Software pour pyRSS2Gen[pyrss2gen], Mark Pilgrim pour feedparser[feedparser], Trent Mick pour markdown2[markdown2], Allan Saddi pour fcgi.py, Evan Martin pour le module Python memcache[memcache], John Resig pour jQuery[jquery] Je remercie Helmut Epp (proviseur de DePaul University), David Miller (Doyen du College of Computing and Digital Media of DePaul University), et Estia Eichten (membre de MetaCryption LLC), pour leur confiance continue et leur support. Enfin, je souhaite remercier ma femme, Claudia, et mon fils, Marco, pour m'avoir supporté durant les nombreuses heures que j'ai passées à développer web2py, en échangeant des emails avec des utilisateurs et collaborateurs, et en écrivant ce livre. Ce livre leur est dédié. top
Selected ramblings of a geospatial tech nerd Best bang for your analytical buck As (geo)data scientists, we spend much of our time working with data models that try (with varying degrees of success) to capture some essential truth about the world while still being as simple as possible to provide a useful abstraction. Inevitably, complexity starts to creep into every model and we don’t often stop to assess the value added by that complexity. When working with models that require a large number of parameters and a huge domain of potential inputs that are expensive to collect, it becomes difficult to answer the question: What parameters of the model are the most sensitive? In other words, if I am going to spend my resources obtaining/refining data for this model, where should I focus my efforts in order to get the best bang for the buck? If I spend weeks working on deriving a single parameter for the model, I want some assurance that the parameter is critically important to the model’s prediction. The flip-side, of course, is that if a parameter is not that important to the model’s predictive power, I could save some time by perhaps just using some quick-and-dirty approximation. SALib: a python module for testing model sensitivity I was thrilled to find SALib which implements a number of vetted methods for quantitatively assessing parameter sensitivity. There are three basic steps to running SALib: Define the parameters to test, define their domain of possible values and generate nsets of randomized input parameters. Run the model ntimes and capture the results. Analyze the results to identify the most/least sensitive parameters. I’ll leave the details of these steps to the SALib documentation. The beauty of the SALib approach is that you have the flexibility[1] to run any model in any way you want, so long as you can manipulate the inputs and outputs adequately. Case Study: Climate effects on forestry I wanted to compare a forest growth and yield model under different climate change scenarios in order to assess what the most sensitive climate-related variables were. I identified 4 variables: Climate model (4 global circulation models) Representative Concentration Pathways (RCPs; 3 different emission trajectories) Mortality factor for species viability (0 to 1) Mortality factor for equivalent elevation change (0 to 1) In this case, I was using the Forest Vegetation Simulator(FVS) which requires a configuration file for every model iteration. So, for Step 2, I had to iterate through each set of input variables and use them to generate an appropriate configuration file. This involved translating the real numbers from the samples into categorical variables in some cases. Finally, in order to get the result of the model iteration, I had to parse the outputs of FVS and do some post-processing to obtain the variable of interest (the average volume of standing timber over 100 years). So the flexibility of SALib comes at a slight cost: unless your model works directly with the file formatted for SALib, the input and outputs may require some data manipulation. After running the all required iterations of the model[2] I was able to analyze the results and assess the sensitivity of the four parameters. Here’s the output of SALib’s analysis (formatted slightly for readability): Parameter First_Order First_Order_Conf Total_Order Total_Order_Confcirculation 0.193685 0.041254 0.477032 0.034803rcp 0.517451 0.047054 0.783094 0.049091mortviab -0.007791 0.006993 0.013050 0.007081mortelev -0.005971 0.005510 0.007162 0.006693 The first order effects represent the effect of that parameter alone. The total order effects are arguably more relevant to understanding the overall interaction of that parameter with your model. The “Conf” columns represent confidence and can be interpreted as error bars. In this case, we interpret the output as follows: Parameter Total Order Effect circulation 0.47 +- 0.03 (moderate influence) rcp 0.78 +- 0.05 (dominant parameter) mortviab 0.01 +- 0.007 (weak influence) mortelev 0.007 +- 0.006 (weak influence) We can graph each of the input parameters against the results to visualize this: Note that the ‘mortelev’ component is basically flat (as the factor increases, the result stays the same) whereas the choice of ‘rcp’ has a heavy influence (as emissions increase to the highest level, the resulting prediction for timber volumes are noticeably decreased). The conclusion is that the climate variables, particularly the RCPs related to human-caused emissions, were the strongest determinants[1] of tree growth for this particular forest stand. This ran counter to our initial intuition that the mortality factors would play a large role in the model. Based on this sensitivity analysis, we may be able to avoid wasting effort on refining parameters that are of minor consequence to the output. Footnotes: Compared to more tightly integrated, model-specific methods of sensitivity analysis 20 thousand iterations took approximately 8 hours; sensitivity analysis generally requires lots of processing Note that the influence of a parameter says nothing about direct causality Simple leaftlet-based template for mapping tabular point data on a slippy map Anyone who’s worked with spatial data and the web has run across the need to take some simple tabular data and put points on an interactive map. It’s the fundamental ”Hello World” of web mapping. Yet I always find myself spending way too much time solving this seemingly simple problem. When you consider zoom levels, attributes, interactivity, clustering, querying, etc… it becomes apparent that interactive maps require a bit more legwork. But that functionality is fairly consistent case-to-case so I’ve developed a generalized solution that works for the majority of basic use cases out there: The idea is pretty generic but useful for most point marker maps: Data is in tabular delimited-text (csv, etc.) with two required columns: latandlng Points are plotted on full-screen Leaflet map Point markers are clustered dynamically based on zoom level. Clicking on a point cluster will zoom into the extent of the underlying features. Hovering on the point will display the name. Clicking will display a popup with columns/properties displayed as an html table. Full text filtering with typeahead Completely client-side javascript with all dependencies included or linked via CDN Usage Grab the leaflet-simple-csv zip file and unzip it to a location accessible through a web server. Copy the config.js.templatetoconfig.js Visit the index.html page to confirm everything is working with the built-in example. Customize your config.jsfor your dataset. An example config: var dataUrl = 'data/data.csv'; var maxZoom = 9; var fieldSeparator = '|'; var baseUrl = 'http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg'; var baseAttribution = 'Data, imagery and map information provided by <a href="http://open.mapquest.co.uk" target="_blank">MapQuest</a>, <a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> and contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank">CC-BY-SA</a>'; var subdomains = '1234'; var clusterOptions = {showCoverageOnHover: false, maxClusterRadius: 50}; var labelColumn = "Name"; var opacity = 1.0; The example dataset: Country|Name|lat|lng|AltitudeUnited States|New York City|40.7142691|-74.0059738|2.0United States|Los Angeles|34.0522342|-118.2436829|115.0United States|Chicago|41.8500330|-87.6500549|181.0United States|Houston|29.7632836|-95.3632736|15.0... I make no claims that this is the “right” way to do it but leveraging 100% client-side javascript libraries and native delimited-text formats seems like the simplest approach. Many of the features included here (clustering, filtering) are useful enough to apply to most situations and hopefully you’ll find it useful. A common task in many of my data workflows involves summarizing geospatial raster datasets based on vector geometries (i.e. zonal statistics). Despite many alternatives (starspan, the QGIS Zonal Statistics plugin, ArcPy and R) there were none that were open source fast enough flexible enough worked with python data structures We’d written a wrapper around starspan for madrona (see madrona.raster_stats ) but relying on shell calls and an aging, unmaintained C++ code base was not cutting it. So I set out to create a solution using numpy, GDAL and python. The rasterstats package was born. Example Let’s jump into an example. I’ve got a polygon shapefile of continental US state boundaries and a raster dataset of annual precipitation from the North American Environmental Atlas. >>> states = "/data/workspace/rasterstats_blog/boundaries_contus.shp" >>> precip = "/data/workspace/rasterstats_blog/NA_Annual_Precipitation_GRID/NA_Annual_Precipitation/data/na_anprecip/hdr.adf" The raster_stats function is the main entry point. Provide a vector and a raster as input and expect a list of dicts, one for each input feature. >>> from rasterstats import raster_stats >>> rain_stats = raster_stats(states, precip, stats="*", copy_properties=True) >>> len(rain_stats) # continental US; 48 states plus District of Columbia 49 Print out the stats for a given state: >>> [x for x in rain_stats if x['NAME'] == "Oregon"][0] {'COUNTRY': 'USA', 'EDIT': 'NEW', 'EDIT_DATE': '20060803', 'NAME': 'Oregon', 'STATEABB': 'US-OR', 'Shape_Area': 250563567264.0, 'Shape_Leng': 2366783.00361, 'UIDENT': 124704, '__fid__': 35, 'count': 250510, 'majority': 263, 'max': 3193.0, 'mean': 779.2223903237395, 'median': 461.0, 'min': 205.0, 'minority': 3193, 'range': 2988.0, 'std': 631.539502512283, 'sum': 195203001.0, 'unique': 2865} Find the three driest states: >>> [(x['NAME'], x['mean']) for x in sorted(rain_stats, key=lambda k: k['mean'])[:3]] [('Nevada', 248.23814034118908), ('Utah', 317.668743027571), ('Arizona', 320.6157232064074)] And write the data out to a csv. from rasterstats import stats_to_csv with open('out.csv', 'w') as fh: fh.write(stats_to_csv(rain_stats)) Geo interface The basic usage above shows the path of an entire OGR vector layer as the first argument. But raster-stats also supports other vector features/geometries. Well-Known Text/Binary GeoJSON string and mappings Any python object that supports the geo_interface Single objects or iterables In this example, I use a geojson-like python mapping to specify a single geometry >>> geom = {'coordinates': [[ [-594335.108537269, -570957.932799394], [-422374.54395311, -593387.5716581973], [-444804.1828119133, -765348.1362423564], [-631717.839968608, -735441.9510972851], [-594335.108537269, -570957.932799394]]], 'type': 'Polygon'} >>> raster_stats(geom, precip, stats="min median max") [{'__fid__': 0, 'max': 1011.0, 'median': 451.0, 'min': 229.0}] Categorical We’re not limited to descriptive statistics for continuous rasters either; we can get unique pixel counts for categorical rasters as well. In this example, we’ve got a raster of 2005 land cover (i.e. general vegetation type). Note that we can specify only the stats that make sense and the categorical=True provides a count of each pixel value. >>> landcover = "/data/workspace/rasterstats_blog/NA_LandCover_2005.img" >>> veg_stats = raster_stats(states, landcover, stats="count majority minority unique", copy_properties=True, nodata_value=0, categorical=True) >>> [x for x in veg_stats if x['NAME'] == "Oregon"][0] {1: 999956, 3: 6, 5: 3005, 6: 198535, 8: 2270805, 10: 126199, 14: 20883, 15: 301884, 16: 17452, 17: 39246, 18: 28872, 19: 2174, 'COUNTRY': 'USA', 'EDIT': 'NEW', 'EDIT_DATE': '20060803', 'NAME': 'Oregon', 'STATEABB': 'US-OR', 'Shape_Area': 250563567264.0, 'Shape_Leng': 2366783.00361, 'UIDENT': 124704, '__fid__': 35, 'count': 4009017, 'majority': 8, 'minority': 3, 'unique': 12} Of course the pixel values alone don’t make much sense. We need to interpret the pixel values as land cover classes: Value, Class_name 1 Temperate or sub-polar needleleaf forest 2 Sub-polar taiga needleleaf forest 3 Tropical or sub-tropical broadleaf evergreen 4 Tropical or sub-tropical broadleaf deciduous 5 Temperate or sub-polar broadleaf deciduous 6 Mixed Forest 7 Tropical or sub-tropical shrubland 8 Temperate or sub-polar shrubland 9 Tropical or sub-tropical grassland 10 Temperate or sub-polar grassland 11 Sub-polar or polar shrubland-lichen-moss 12 Sub-polar or polar grassland-lichen-moss 13 Sub-polar or polar barren-lichen-moss 14 Wetland 15 Cropland 16 Barren Lands 17 Urban and Built-up 18 Water 19 Snow and Ice So, for our Oregon example above we can see that, despite Oregon’s reputation as a lush green landscape, the majority land cover class (#8) is “Temperate or sub- polar shrubland” at 2.27m pixels out of 4 millions total. There’s a lot more functionality that isn’t covered in this post but you get the picture… please check it out and let me know what you think. We’ve begun to rely on the interactivity provided by UTFGrids in many of our recent web maps. (Quick recap: UTFGrids are “invisible” map tiles that allow direct interactivity with feature attributes without querying the server.) Earlier this year, I created the initial OpenLayers UTFGrid support and was glad to see it accepted into OpenLayer 2.12 (with some enhancements). With the client-side javascript support in place, the only missing piece in the workflow was to create the UTFGrid .json files. We had expirimented with several alternate UTFGrid renderers but Mapnik’s rendering was by far the fastest and produced the best results. Using Tilemill was a convenient way to leverage the Mapnik UTFGrid renderer but it came at the cost of a somewhat circuitious and manual workflow: Load the data up into Tilemill, Configure interactivity fields Export to .mbtiles Convert to .json files What we really needed was a script to take a polygon shapefile and render the UTFGrids directly to files. Mapnik would provide the rendering while the Global Map Tiles python module would provide the logic for going back and forth between geographic coordinates and tile grid coordinates. From there it’s just a matter of determining the extent of the data set and, for a specified set of zoom levels, looping through and using Mapnik to render the UTFGrid to a .json file in Z/X/Y.json directory structure. If we have a mercator polygon shapefile of ecoregions and want to render UTFGrids for zoom levels 3 through 5 using the dom_desc and div_desc attributes, we could use a command like $ ./create_utfgrids.py test_data/bailey_merc.shp 3 5 ecoregions -f dom_desc,div_desc WARNING: This script assumes a polygon shapefile in spherical mercator projection. If any of these assumptions are not true, don't count on the results! * Processing Zoom Level 3 * Processing Zoom Level 4 * Processing Zoom Level 5 and inspect the output (e.g. zoom level 5, X=20, Y=18) $ cat ecoregions/5/20/18.json | python -mjson.tool { "data": { "192": { "div_desc": "RAINFOREST REGIME MOUNTAINS", "dom_desc": "HUMID TROPICAL DOMAIN" }, ... "grid": [ " !!!!!!!!!#####$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%", ... Some caveats: This currently only works for polygon datasets in a Web Mercator projection. It’s only tested with shapefiles as it assumes a single-layer datasource at the moment. Full OGR Datasource support would not be too difficult to add for PostGIS, etc. It assumes a top-origin tile scheme (as do OSM and Google Maps). Supporting TMS bottom-origin schemes in the future should be straightforward. Requires OGR and Mapnik >= 2.0 with python bindings. Finding windows binaries for the required version of Mapnik may be difficult so using OSX/Linux is recommended at this time. Many thanks to Dane Springmeyer for his help on UTFGrid related matters and and to Klokan Petr Přidal for his MapTiler docs Madrona: A software framework for effective place-based decision making My work at Ecotrust mainly revolves around creating web-based spatial analysis tools - software to bring data-driven science to the place-based descision making process. This began several years ago when I joined the MarineMap team. Since working with Ecotrust, we’ve taken the MarineMap software far beyond it’s original niche. What was once a specific tool for marine protected area planning has now become a powerful framework for all sorts of web-based spatial tools in the realms of marine, forestry, conservation planning, aquatic habitat restoration, etc. So, in a sense, Madrona is a recognition of that evolution. Over the last year we’ve distilled the best ideas from our most successful tools into a suite of software building blocks that can be mixed and matched to create cutting-edge software for decision support and spatial planning at any scale. These building blocks are already at the heart of our work and now we’re ready to share them with you. So what is Madrona from a developer’s perspective? A set of pythondjangoapps that provide models, views and templates for representing spatial features and solving problems specific to spatial decision tools. A RESTful APIfor accessing spatial features A collection of javascriptlibraries (based on JQuery) to provide a web-based interface to the API. In short, we think its a great platform for spatial tools and we want to open it up to the wider developer audience. Ecotrust already has many madrona-based apps in the wild (with many more in development) but we’re hoping to get other folks using (and contributing to) the Madrona framework in the future.
I'm looking at writing a super-class for all my Google App Engine datastore classes that looks something like this: class MemcacheMixin(object): @classmethod def cache_get_by_id(cls, id, parent=None): if memcache.has_key(...): ... ... class MyEntity(db.Model, MemcacheMixin): ... obj = MyEntity.cache_get_by_id(...) The idea being that I'll almost always want to cache datastore objects, and I don't want to repeat myself. I assume someone must have already addressed this need and written a general-purpose tool for caching this stuff that integrates nicely into how the datastore classes work. But, I haven't found it. Any recommendations?
This is not a comparison of features. I am trying to explain web2py to Java programmers. In J2EE and Java based frameworks the separation between the Model (the data representation), the View (the presentation layer) and the Controller (the business logic and workflow) is achieved by the following components: (I am quoting this source) web2py provides equivalent functionalities but uses the Python language instead of Java. This is a typical Java serverlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); } } Here is the equivalent web2py controller function def HelloWorld(): return 'Hello World' Notice that: A web2py controller function can return a string (as in the above example). In this case the string is returned to the browser. The most common situation is that the controller function returns a set of variables stored in a Python dictionary. In this case the dictionary is transformed into a web page by the associated view. For example def HelloWorld(): return dict(message='Hello World') This page would ber rendered by a view called HelloWorld.html. If such view does not exist, the built-in generic.html is used instead. This allows to create controllers and fully functional web application without writing any HTML. The view, the presentation layer, is typically added as a last step in development. In web2py, the controller has access to the following objects (request, response, session, cache) and they can be used, for example, to read request GET/POST variables and environment variables (according to the WSGI specs) as in this example: def HelloWorld(): return dict(message='Hello '+request.env.remote_addr) As for Java serverlets, every call to a web2py controller action is executed in its own thread. Thus multiple requests can be executed concurrently. web2py comes with its own SSL enabled web server you also works with Apache, Lightpd and any server that supports WSGI or FastCGI or CGI. A typical Java Server Page looks like this: <html> <body> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:forEach var="i" begin="1" end="10"> Hello Number ${i}<br/> </c:forEach> </body> </html> In web2py the same code reads <html> <body> {{for i in range(1,10):}} Hello Number {{=i}}<br/> {{pass}} </body> </html> The code in {{ }} is pure Python code (not a subset). Blocks start with a line ending in colon and stop with the keyword pass. As in JSP, web2py views can extend and include other views: {{extend 'layout.html'}} {{for i in range(1,10):}} Hello Number {{=i}}<br/> {{pass}} layout.html comes with web2py but it is easy to create other layouts using HTML or using our layout designer. Notice that: Any web application needs persistence. In Java this is achieved by JavaBeans. There are JavaBeans to handle session variables and there are JavaBeans to interact with the database. web2py uses three distinct mechanisms to handle persistence: sessions, ORM, and cache. Consider the following web2py controller that implements a counter def count(): if not sessin.c: session.c=1 else: session.c+=1 return dict(message='Counted up to %i' % session.c) session is a built-in object used to store session variables. When queried for an attribute that does not exist (if session.c) is False. When an attribute is set (session.c=1) this is stored in the session. By default sessions are stored in files and locked when used. Optionally they can be stored in the database. Almost any Python object can be stored into a session. web2py automatically creates session cookies. J2EE, out of the box, does not have something equivalent to an ORM. Perhaps you can get one from a third party vendor but I have never seen one. web2py's ORM provides a API to interact with the database that is completely independent on the database backed. This is not the same as JDBC! JDBC is all about connecting to the database, sending SQL queries and a retrieving response but the developer still has to write SQL and the SQL queries depend on the dialect of the database back-end. If you develop your Java+JDBC app using Oracle and you decide to move to Postgresql (or vice versa), you have to rewrite most of the SQL queries. The web2py ORM (as any Python ORM) writes the SQL for you, in real time, with no overhead, preventing SQL injections, for any supported database back-end. The web2py ORM (like many Python ORM) seamlessly work with SQLIte, MySQL, PostgreSQL, Oracle, and (with limitations) on Google Big Tables. The web2py ORM (unlikely many Python ORM) does migrations. It means after you connect to the database and define a table, if the table does not exist, it will create it; if it exists but is different, it will alter it accordingly. Here is an example or ORM usage: db=SQLDB('sqlite://mydb.db') db.define_table('user', SQLField('name')) db.user.insert(name='massimo') rows=db().select(db.user.ALL) The first line connects to the database (here a file-based sqlite database). In the case of sqlite, if the file does not exist it is created. The second and third lines define a table "user". If the table does not exist, web2py generates the 'CREATE TABLE....' for the specific SQL dialect and sends it to the database server. The fourth line inserts a record. The fifth line selects all fields for all users from the database table user. The first three lines trigger web2py not just to create/alter the table but also to generate a web based administrative interface for this database. web2py provides API to build complex queries like rows=db(db.user.name.like('mas%')&(db.user.name!='massimo'))\ .select(orderby=db.user.name,groupby=db.user.name,limitby=(0,10)) and more complex like joins, left joins, multiple joins, nested selects. The ORM access is always transaction safe. The transaction is committed when a web page returns without error else the error is logged and the transaction is rolled back. In web2py db.define_table(....) statements are stored in model files since they constitute a description of the data representation. The reader can create web2py models using our model builder web2py can cache any function in ram (cache.ram), on disk (cache.disk), or using memcache. Any function includes results of select, controller functions, views, etc. Here is how to cache a controller for 60 seconds @cache(request.env.path_info,60,cache.ram) def HelloWorld(): return dict(message='Hello World') and here is how to cache a select for 60 seconds. rows=db().select(db.user.ALL,cache=(cache.ram,60)) web2py does not have JavaBeans because it does not need them. According to [SUN(http://java.sun.com/developer/technicalArticles/J2EE/j2ee_ws/) "Building an XML-RPC style web service using the J2EE 1.4 platform involves five steps:" Here we just list the example SUN provides for the second step: import java.rmi.RemoteException; public class MathImpl implements MathFace { public int add(int a, int b) throws RemoteException { return a + b; } } In web2py there is only this second step (we honestly do not understand why J2EE needs the other four). You just write in a controller: def add(a,b): return a+b def handler(): return response.xmlrpc(request,(add,)) The second function is the controller (which we choose to call "handler") and it exposes as XML-RPC the function add. One can expose multiple functions via the same "handler" function. We really do not feel we need to add any comment here. In web2py: T('this is a message') (and as usual no need to import anything since you are supposed to use T) You web2py you can also do T('this is message %(name)s',dict(name='xxx')) it-it.py ) in the admin interface. web2py comes in one executable package including an SSL enabled web server, the sqlite database, a web administratve interface that allows you to create/edit/deploy and manage all your applications. Exception are automatically caught by web2py which logs the traceback, the code causing the exception, and issues a ticket to the visitor that triggered the exception. No code is exposed to the visitor, not even by mistake, ever. web2py includes libraries for generating CREATE/UPDATE/DELETE forms from your database tables. web2py incudes libraries for handling AJAX, JSON, REST, RSS, ATOM, RTF, CSV, WIKI (markdown) and some more protocols. web2py has helpers that help you build objects that can be serialized in HTML or XML. Any correct HTML/XML can be generated using exclusively helpers. web2py code runs on the Google App Engine. web2py packages everything you need in one binary file that you don't even need to install. I keep mine on a USB stick. You just click on it and it start web server, the sqlite database, fires the browser for access to the administrative interface. web2py deals with static files for you, streams them when they are large (both in upload and download), and automatically supports IF_MODIFIED_SINCE and PARTIAL CONTENT. You can do streaming audio and video without any extra tools or settings. web2py can map URLs using regular expressions so that you can use it to handle legacy URLs. web2py has no configuration files. You just create an empty app via the shell or the web based admin interface and create/edit your models, controllers and views (using an editor or the web based admin interface).
Leo 7 Re : A quoi ressemble votre environnement - printemps/été 2012 J'adore ton unity Mario_26 Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli. Merci d'avance A+ hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures ! Hors ligne Major Grubert Re : A quoi ressemble votre environnement - printemps/été 2012 Très élégant, tu as les sources ? Hors ligne cherrak Re : A quoi ressemble votre environnement - printemps/été 2012 J'adore ton unity Mario_26 smile Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli. Merci d'avance A+ Quand a moi j'aimerai bien ton conky stp (ma copine l'adore) Tres beau bureau en tous cas titou345 Re : A quoi ressemble votre environnement - printemps/été 2012 J'adore ton unity Mario_26 Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli. Merci d'avance A+ C'est un des (beaux) fonds d'écran par défaut de Ubuntu 12.04 que tu peux retrouver ici : Machin a dit truc-bidule. Bref, moi je suis cultivé quoi. Hors ligne titou345 Re : A quoi ressemble votre environnement - printemps/été 2012 Comment tu appliques les thèmes d'icônes sur Precise ? Machin a dit truc-bidule. Bref, moi je suis cultivé quoi. Hors ligne Laurent_chébran Re : A quoi ressemble votre environnement - printemps/été 2012 Comment tu appliques les thèmes d'icônes sur Precise ? Tu vas planter ton ficher dans usr/share/icons en démarrant nautilus en root et ensuite tu changes le thème en passant par gnome-tweak-tool.. Hors ligne Leo 7 Re : A quoi ressemble votre environnement - printemps/été 2012 @titou345: Merci hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures ! Hors ligne titou345 Re : A quoi ressemble votre environnement - printemps/été 2012 titou345 a écrit : Comment tu appliques les thèmes d'icônes sur Precise ? Tu vas planter ton ficher dans usr/share/icons en démarrant nautilus en root et ensuite tu changes le thème en passant par gnome-tweak-tool.. Merci à toi. J'avais un doute sur la compatibilité de Gnome-tweak-tool avec la dernière version de Unity. Machin a dit truc-bidule. Bref, moi je suis cultivé quoi. Hors ligne hells_dark Re : A quoi ressemble votre environnement - printemps/été 2012 Très élégant, tu as les sources ? conky #!/usr/bin/conky -d -c ## .conkyrc configuration alignment top_right background yes cpu_avg_samples 2 default_color fff # szary 5f5f5f default_outline_color 000000 # Black default_shade_color 000000 # Black double_buffer yes draw_borders no draw_graph_borders no draw_outline no draw_shades no gap_x 0 gap_y 450 max_specials 1024 max_user_text 10000 maximum_width 150 minimum_size 150 net_avg_samples 2 no_buffers yes override_utf8_locale yes own_window yes own_window_colour 000000 # Black own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager own_window_transparent yes #own_window_type normal pad_percents 2 short_units yes stippled_borders 3 text_buffer_size 8000 total_run_times 0 update_interval 1.0 uppercase no use_spacer right use_xft yes xftalpha 1 xftfont Freesans:pixelsize=9 TEXT ${font helvetica:pixelsize=11} ${offset 50}Galaxy S3 ${offset 50}${texeci 180 ~/.conky/scripts/rebours.sh 05/03/2012} ${offset 50}Ubuntu 12.04 ${offset 50}${texeci 180 ~/.conky/scripts/rebours.sh 04/26/2012} ${offset 50}Mails ${offset 50}${texeci 180 python ~/.conky/scripts/check_gmail_cpt.py} message(s) ${image ~/.conky/images/android.png -p 20,25} ${image ~/.conky/images/ubuntu.png -p 20,72} ${image ~/.conky/images/mail.gif -p 20,118} compte à rebours #!/bin/bash # Conky CountDown - Script de compte à rebours upd=$(date +%s -d $1) acts=$(date +%m/%d/%Y) act=$(date +%s -d $acts) diff=$(($upd-$act)) jours=$(($diff/3600/24)) if [ $jours -le 0 ] then echo "Date atteinte !" else echo "$jours jours" fi exit 0 gmail import os import string #Enter your username and password below within double quotes # eg. username="username" and password="password" username="username" password="password" com="wget -O - https://"+username+":"+password+"@mail.google.com/mail/feed/atom --no-check-certificate" temp=os.popen(com) msg=temp.read() index=string.find(msg,"<fullcount>") index2=string.find(msg,"</fullcount>") fc=int(msg[index+11:index2]) print fc Hors ligne Major Grubert Re : A quoi ressemble votre environnement - printemps/été 2012 merci, je regarde ça demain Hors ligne Theo46300 Re : A quoi ressemble votre environnement - printemps/été 2012 Tous bureau sont très jolis ici Très beau bureau hells_dark tu pourrai donné le lien du wallpaper stp. Dernière modification par Theo46300 (Le 04/05/2012, à 07:07) Ubuntu 12.04 (32 bit)-gnome-shell Packard-bell easynote mx51 Une fois que l'on a découvert Linux on ne peut plus s'en passer. Hors ligne The Uploader Re : A quoi ressemble votre environnement - printemps/été 2012 Après le Xfce "à la Unity", voici le Xfce "à la Gnome Shell" : http://forum.xfce.org/viewtopic.php?id=6928 La classe! Dernière modification par The Uploader (Le 04/05/2012, à 11:17) Passer de Ubuntu 10.04 à Xubuntu 12.04 LTS Archlinux + KDE sur ASUS N56VV. ALSA, SysV, DBus, Xorg = Windows 98 ! systemd, kdbus, ALSA + PulseAudio, Wayland = modern OS (10 years after Windows, but still...) ! Deal with it ! Hors ligne Major Grubert Re : A quoi ressemble votre environnement - printemps/été 2012 GS c'est avant tout un mode exposition, pas tellement une apparence. Enfin je trouve. Hors ligne Mario_26 Re : A quoi ressemble votre environnement - printemps/été 2012 Salut ! @ Leo 7 : Effectivement c'est un des Wall qui se trouve dans Ubuntu 12.04... @ cherrak : Le Conky se trouve sur Gnome Look ici, à toi de l'adapter à ta sauce Je vois énormement de Arch, bien que nous somme sur le forum de Ubuntu... Je vous montre donc la mienne Très simple mais aussi très efficace !! ++ Hors ligne cherrak Re : A quoi ressemble votre environnement - printemps/été 2012 Ok merci ! Tres joli bureau Major Grubert Re : A quoi ressemble votre environnement - printemps/été 2012 Petit succès pour toi hells Pour moi, top bureau : . Gnome shell : une preuve du bon goût . Un conky discret et élégant . Un fond d'écran distingué On partage les mêmes valeurs Hors ligne Heliox Re : A quoi ressemble votre environnement - printemps/été 2012 [HS] Pour ceux que ça intéresse, sur Fedora il est possible d'avoir les thèmes Ambiance et Radiance (ceux inclus par défaut avec Ubuntu) dans Gnome 3 : # yum install light-theme-gnome Reste Gnome-Shell qui n'est pas en accord avec ces thèmes… [/HS] Dernière modification par Heliox (Le 05/05/2012, à 12:33) titou345 Re : A quoi ressemble votre environnement - printemps/été 2012 Très épuré, très classe, bravo. Tu utilises Gnome Shell avec Ubuntu ? Quel est ton thème ? Merci. Dernière modification par titou345 (Le 06/05/2012, à 00:23) Machin a dit truc-bidule. Bref, moi je suis cultivé quoi. Hors ligne Leo 7 Re : A quoi ressemble votre environnement - printemps/été 2012 hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures ! Hors ligne pololasi Re : A quoi ressemble votre environnement - printemps/été 2012 Voici le mien du moment, sous crunchbang : Toujours aussi classe et précis tes environnements. Thinkpad X 200 ; Intel Core2 Duo CPU P8600 ; 2 Go de DDR3 ; Intel 4500MHD Xubuntu 14.04.1 LTS 64 bits Athlon XP 3000+ ; Asus A7V400MX ; ATI Radeon X1600 ; 2 giga de ram Xubuntu 12.04.3 LTS 32 bits Hors ligne
Linux-based container infrastructure is an emerging cloud technology based on fast and lightweight process virtualization. It provides its users an environment as close as possible to a standard Linux distribution. As opposed to para-virtualization solutions (Xen) and hardware virtualization solutions (KVM), which provide virtual machines (VMs), containers do not create other instances of the operating system kernel. Due to the fact that containers are more lightweight than VMs, you can achieve higher densities with containers than with VMs on the same host (practically speaking, you can deploy more instances of containers than of VMs on the same host). Another advantage of containers over VMs is that starting and shutting down a container is much faster than starting and shutting down a VM. All containers under a host are running under the same kernel, as opposed to virtualization solutions like Xen or KVM where each VM runs its own kernel. Sometimes the constraint of running under the same kernel in all containers under a given host can be considered a drawback. Moreover, you cannot run BSD, Solaris, OS/x or Windows in a Linux-based container, and sometimes this fact also can be considered a drawback. The idea of process-level virtualization in itself is not new, and it already was implemented by Solaris Zones as well as BSD jails quite a few years ago. Other open-source projects implementing process-level virtualization have existed for several years. However, they required custom kernels, which was often a major setback. Full and stable support for Linux-based containers on mainstream kernels by the LXC project is relatively recent, as you will see in this article. This makes containers more attractive for the cloud infrastructure. More and more hosting and cloud services companies are adopting Linux-based container solutions. In this article, I describe some open-source Linux-based container projects and the kernel features they use, and show some usage examples. I also describe the Docker tool for creating LXC containers. The underlying infrastructure of modern Linux-based containers consists mainly of two kernel features: namespaces and cgroups. There are six types of namespaces, which provide per-process isolation of the following operating system resources: filesystems (MNT), UTS, IPC, PID, network and user namespaces (user namespaces allow mapping of UIDs and GIDs between a user namespace and the global namespace of the host). By using network namespaces, for example, each process can have its own instance of the network stack (network interfaces, sockets, routing tables and routing rules, netfilter rules and so on). Creating a network namespace is very simple and can be done with the following iproute command: ip netns add myns1. With the ip netns command, it also is easy to move one network interface from one network namespace to another, to monitor the creation and deletion of network namespaces, to find out to which network namespace a specified process belongs and so on. Quite similarly, when using the MNT namespace, when mounting a filesystem, other processes will not see this mount, and when working with PID namespaces, you will see by running the ps command from that PID namespace only processes that were created from that PID namespace. The cgroups subsystem provides resource management and accounting. It lets you define easily, for example, the maximum memory that a process may use. This is done by using cgroups VFS operations. The cgroups project was started by two Google developers, Paul Menage and Rohit Seth, back in 2006, and it initially was called “process containers”. Neither namespaces nor cgroups intervene in critical paths of the kernel, and thus they do not incur a high performance penalty, except for the memory cgroup, which can incur significant overhead under some workloads. Linux-Based Containers Basically, a container is a Linux process (or several processes) that has special features and that runs in an isolated environment, configured on the host. You might sometimes encounter terms like Virtual Environment (VE) and Virtual Private Server (VPS) for a container. The features of this container depend on how the container is configured and on which Linux-based container is used, as Linux-based containers are implemented differently in several projects. I mention the most important ones in this article: OpenVZ: the origins of the OpenVZ project are in a proprietary server virtualization solution called Virtuozzo, which originally was started by a company called SWsoft, founded in 1997. In 2005, a part of the Virtuozzo product was released as an open-source project, and it was called OpenVZ. Later, in 2008, SWsoft merged with a company called Parallels. OpenVZ is used for providing hosting and cloud services, and it is the basis of the Parallels Cloud Server. Like Virtuozzo, OpenVZ also is based on a modified Linux kernel. In addition, it has command-line tools (primarily vzctl) for management of containers, and it makes use of templates to create containers for various Linux distributions. OpenVZ also can run on some unmodified kernels, but with a reduced feature set. The OpenVZ project is intended to be fully mainlined in the future, but that could take quite a long time. Google containers: in 2013, Google released the open-source version of its container stack, lmctfy (which stands for Let Me Contain That For You). Right now, it’s still in the beta stage. The lmctfy project is based on using cgroups. Currently, Google containers do not use the kernel namespaces feature, which is used by other Linux-based container projects, but using this feature is on the Google container project roadmap. Linux-VServer: an open-source project that was first publicly released in 2001, it provides a way to partition resources securely on a host. The host should run a modified kernel. LXC: the LXC (LinuX Containers) project provides a set of userspace tools and utilities to manage Linux containers. Many LXC contributors are from the OpenVZ team. As opposed to OpenVZ, it runs on an unmodified kernel. LXC is fully written in userspace and supports bindings in other programming languages like Python, Lua and Go. It is available in most popular distributions, such as Fedora, Ubuntu, Debian and more. Red Hat Enterprise Linux 6 (RHEL 6) introduced Linux containers as a technical preview. You can run Linux containers on architectures other than x86, such as ARM (there are several how-tos on the Web for running containers on Raspberry PI, for example). I also should mention the libvirt-lxc driver, with which you can manage containers. This is done by defining an XML configuration file and then running virsh start, virsh console and visrh destroy to run, access and destroy the container, respectively. Note that there is no common code between libvirt-lxc and the userspace LXC project. LXC Container Management First, you should verify that your host supports LXC by running lxc-checkconfig. If everything is okay, you can create a container by using one of several ready-made templates for creating containers. In lxc-0.9, there are 11 such templates, mostly for popular Linux distributions. You easily can tailor these templates according to your requirements, if needed. So, for example, you can create a Fedora container called fedoraCT with: lxc-create -t fedora -n fedoraCT The container will be created by default under /var/lib/lxc/fedoraCT. You can set a different path for the generated container by adding the --lxcpath PATH option. The -t option specifies the name of the template to be used, (fedora in this case), and the -n option specifies the name of the container (fedoraCT in this case). Note that you also can create containers of other distributions on Fedora, for example of Ubuntu (you need the debootstrap package for it). Not all combinations are guaranteed to work. You can pass parameters to lxc-create after adding --. For example, you can create an older release of several distributions with the -R or -r option, depending on the distribution template. To create an older Fedora container on a host running Fedora 20, you can run: lxc-create -t fedora -n fedora19 -- -R 19 You can remove the installation of an LXC container from the filesystem with: lxc-destroy -n fedoraCT For most templates, when a template is used for the first time, several required package files are downloaded and cached on disk under /var/cache/lxc. These files are used when creating a new container with that same template, and as a result, creating a container that uses the same template will be faster next time. You can start the container you created with: lxc-start -n fedoraCT And stop it with: lxc-stop -n fedoraCT The signal used by lxc-stop is SIGPWR by default. In order to use SIGKILL in the earlier example, you should add -k to lxc-stop: lxc-stop -n fedoraCT -k You also can start a container as a dæmon by adding -d, and then log on into it with lxc-console, like this: lxc-start -d -n fedoraCT lxc-console -n fedoraCT The first lxc-console that you run for a given container will connect you to tty1. If tty1 already is in use (because that’s the second lxc-console that you run for that container), you will be connected to tty2 and so on. Keep in mind that the maximum number of ttys is configured by the lxc.tty entry in the container configuration file. You can make a snapshot of a non-running container with: lxc-snapshot -n fedoraCT This will create a snapshot under /var/lib/lxcsnaps/fedoraCT. The first snapshot you create will be called snap0; the second one will be called snap1 and so on. You can time-restore the snapshot at a later time with the -r option—for example: lxc-snapshot -n fedoraCT -r snap0 restoredFdoraCT You can list the snapshots with: lxc-snapshot -L -n fedoraCT You can display the running containers by running: lxc-ls --active Managing containers also can be done via scripts, using scripting languages. For example, this short Python script starts the fedoraCT container: #!/usr/bin/python3 import lxc container = lxc.Container("fedoraCT") container.start() Container Configuration A default config file is generated for every newly created container. This config file is created, by default, in /var/lib/lxc/<containerName>/config, but you can alter that using the --lxcpath PATH option. You can configure various container parameters, such as network parameters, cgroups parameters, device parameters and more. Here are some examples of popular configuration items for the container config file: You can set various cgroups parameters by setting values to the lxc.cgroup.[subsystem name] entries in the config file. The subsystem name is the name of the cgroup controller. For example, configuring the maximum memory a container can use to be 256MB is done by setting lxc.cgroup.memory.limit_in_bytes to be 256MB. You can configure the container hostname by setting lxc.utsname. There are five types of network interfaces that you can set with the lxc.network.type parameter: empty, veth, vlan,macvlan and phys. Using veth is very common in order to be able to connect a container to the outside world. By using phys, you can move network interfaces from the host network namespace to the container network namespace. There are features that can be used for hardening the security of LXC containers. You can avoid some specified system calls from being called from within a container by setting a secure computing mode, or seccomp, policy with the lxc.seccomp entry in the configuration file. You also can remove capabilities from a container with the lxc.cap.drop entry. For example, setting lxc.cap.drop = sys_module will create a container without the CAP_SYS_MDOULE capability. Trying to run insmod from inside this container will fail. You also can define Apparmor and SELinux profiles for your container. You can find examples in the LXC README and inman 5 lxc.conf. Docker Docker is an open-source project that automates the creation and deployment of containers. Docker first was released in March 2013 with Apache License Version 2.0. It started as an internal project by a Platform-as-a-Service (PaaS) company called dotCloud at the time, and now called Docker Inc. The initial prototype was written in Python; later the whole project was rewritten in Go, a programming language that was developed first at Google. In September 2013, Red Hat announced that it will collaborate with Docker Inc. for Red Hat Enterprise Linux and for the Red Hat OpenShift platform. Docker requires Linux kernel 3.8 (or above). On RHEL systems, Docker runs on the 2.6.32 kernel, as necessary patches have been backported. Docker utilizes the LXC toolkit and as such is currently available only for Linux. It runs on distributions like Ubuntu 12.04, 13.04; Fedora 19 and 20; RHEL 6.5 and above; and on cloud platforms like Amazon EC2, Google Compute Engine and Rackspace. Docker images can be stored on a public repository and can be downloaded with the docker pull command—for example, docker pull ubuntu or docker pull busybox. To display the images available on your host, you can use thedocker images command. You can narrow the command for a specific type of images (fedora, for example) with docker images fedora. On Fedora, running a Fedora docker container is simple; after installing the docker-io package, you simply start the docker dæmon with systemctl start docker, and then you can start a Fedora docker container with docker run -i -t fedora /bin/bash. Docker has git-like capabilities for handling containers. Changes you make in a container are lost if you destroy the container, unless you commit your changes (much like you do in git) withdocker commit <containerId> <containerName/containerTag>. These images can be uploaded to a public registry, and they are available for downloading by anyone who wants to download them. Alternatively, you can set a private Docker repository. Docker is able to create a snapshot using the kernel device mapper feature. In earlier versions, before Docker version 0.7, it was done using AUFS (union filesystem). Docker 0.7 adds “storage plugins”, so people can switch between device mapper and AUFS (if their kernel supports it), so that Docker can run on RHEL releases that do not support AUFS. You can create images by running commands manually and committing the resulting container, but you also can describe them with a Dockerfile. Just like a Makefile will compile code into a binary executable, a Dockerfile will build a ready-to-run container image from simple instructions. The command to build an image from a Dockerfile is docker build. There is a tutorial about Dockerfiles and their command syntax on the Docker Web site. For example, the following short Dockerfile is for installing the iperfpackage for a Fedora image: FROM fedora MAINTAINER Rami Rosen RUN yum install -y iperf You can upload and store your images for free on the Docker public index. Just like with GitHub, storing public images is free and just requires you to register an account. The Checkpoint/Restore Feature The CRIU (Checkpoint/Restore in userspace) project is implemented mostly in userspace, and there are more than 100 little patches scattered in the kernel for supporting it. There were several attempts to implement Checkpoint/Restore in kernel space solely, some of them by the OpenVZ project. The kernel community rejected all of them though, as they were too complex. The Checkpoint/Restore feature enables saving a process state in several image files and restoring this process from the point at which it was frozen, on the same host or on a different host at a later time. This process also can be an LXC container. The image files are created using Google’s protocol buffer (PB) format. The Checkpoint/Restore feature enables performing maintenance tasks, such as upgrading a kernel or hardware maintenance on that host after checkpointing its applications to persistent storage. Later on, the applications are restored on that host. Another feature that is very important in HPC is load balancing using live migration. The Checkpoint/Restore feature also can be used for creating incremental snapshots, which can be used after a crash occurs. As mentioned earlier, some kernel patches were needed for supporting CRIU; here are some of them: A new system call named kcmp() was added; it compares two processes to determine if they share a kernel resource. A socket monitoring interface called sock_diag was added to UNIX sockets in order to be able to find the peer of a UNIX domain socket. Before this change, the ss tool, which relied on parsing of /proc entries, did not show this information. A TCP connection repair mode was added. A procfs entry was added (/proc/PID/map_files). Let’s look at a simple example of using the criu tool. First, you should check whether your kernel supports Checkpoint/Restore, by running criu check --ms. Look for a response that says "Looks good." Basically, checkpointing is done by: criu dump -t <pid> You can specify a folder where the process state files will be saved by adding -D folderName. You can restore with criu restore <pid>. Summary In this article, I’ve described what Linux-based containers are, and I briefly explained the underlying cgroups and namespaces kernel features. I have discussed some Linux-based container projects, focusing on the promising and popular LXC project. I also looked at the LXC-based Docker engine, which provides an easy and convenient way to create and deploy LXC containers. Several hands-on examples showed how simple it is to configure, manage and deploy LXC containers with the userspace LXC tools and the Docker tools. Due to the advantages of the LXC and the Docker open-source projects, and due to the convenient and simple tools to create, deploy and configure LXC containers, as described in this article, we presumably will see more and more cloud infrastructures that will integrate LXC containers instead of using virtual machines in the near future. However, as explained in this article, solutions like Xen or KVM have several advantages over Linux-based containers and still are needed, so they probably will not disappear from the cloud infrastructure in the next few years. Acknowledgements Thanks to Jérôme Petazzoni from Docker Inc. and to Michael H. Warfield for reviewing this article. Resources Google Containers: https://github.com/google/lmctfy OpenVZ: http://openvz.org/Main_Page Linux-VServer: http://linux-vserver.org LXC: http://linuxcontainers.org libvirt-lxc: http://libvirt.org/drvlxc.html Docker: https://www.docker.io Docker Public Registry: https://index.docker.io (Via LinuxJournal.com)
wich is the method to get datas of a Treeview? I have some rows and I'd like to save the data in an XML file, but I don't know how to keep the rows datas to pass to the XML function creator. Thanks a lot! Thanks for your reply! Here some code: def create_xml(self, path, model): from lxml import etree print len(model) #that's work self.model = self.treeview.get_model() if(len(model) > 0): root = etree.Element("lista_tareas") iter = self.model.get_iter_first() contatore = 1 while iter: #from here doesn't work, # 'gtk.ListStore' object has no attribute 'COL_DESCRIZIONE' descrizione_c = self.model.get_value(iter, self.model.COL_DESCRIZIONE) data_limite_c = model.get_value(iter, COL_DATA_LIMITE) priorita_c = model.get_value(iter, COL_PRIORITA) realizzato_c = model.get_value(iter, COL_REALIZZATO) root.append(etree.Element("tarea", _id = contatore, realizzato = realizzato_c, data_limite = data_limite_c, priorita = priorita_c)) root.appendSubElement(tarea, "description") tarea.text = descrizione_c iter = model.iter_next(iter) outFile = open('homemade.xml', 'w') doc.write(outFile) This is the button who call the function: self.save_button.connect("clicked", self.create_xml, self.model_add)
I'm a newbie in python programming and I have problem with my coding as the output doesn't display age correctly in days and seconds (as shown on 'output' below) Output Please enter your birthday Year:1985 Month (1-12):5 Date:8 Your age is 10024 days, 0:00:00 Can anyone assist further why and how to fix this problem? Code print "Please enter your birthday " bd_y=int(input("Year:")) bd_m=int(input("Month (1-12):")) bd_d=int(input("Date:")) from datetime import date now = date.today () age = date(int(bd_y), int(bd_m), int(bd_d)) print ("Your age is " + str(now-age)) Thanks in advance :)
It seems that Django capitalizes the first letter when setting the form field for that model field: ... defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text } You could create your own custom model field that overwrites the capfirst (by passing the label as kwarg): from django.db import models class UpcappedModelField(models.Field): def formfield(self, form_class=forms.CharField, **kwargs): return super(UpcappedModelField, self).formfield(form_class=forms.CharField, label=self.verbose_name, **kwargs)
I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial: What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following: mydaemon = Daemon __svc_regClass__(mydaemon, "foo", "foo display", "foo description") __svc_install__(mydaemon) Where svc_install, handles the initalization, by calling Daemon.init() and passing some arguments to it. But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas? class Daemon(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): self.run() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def start(self): pass def stop(self): self.SvcStop() def run(self): pass def __svc_install__(cls): win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType = win32service.SERVICE_AUTO_START ) print "Installed" except Exception, err: print str(err) def __svc_regClass__(cls, name, display_name, description): #Bind the values to the service name cls._svc_name_ = name cls._svc_display_name_ = display_name cls._svc_description_ = description try: module_path = sys.modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path = executable module_file = os.path.splitext(os.path.abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
toto2849 Connexion VPN automatique (NetworkManager) Bonjour,:D -Actuellement en stage il met demandé de mettre en place une connexion VPN qui se lance automatiquement au démarrage du pc ne laissant juste à l'utilisateur une boite de dialogue demandant login+pass.:rolleyes: -J'ai déjà installé le plugin "network-manager-pptp" tout est ok la connexion fonctionne ! Cependant j'aimerais que celle-ci se lance d'elle même au démarrage du système malheureusement j'ai beau cocher la case "connexion automatique" rien n'y fait ! Bref je me penche actuellement sur une solution qui puisse en ligne de commande lancer la connexion VPN ! -Le must serait que l'on affiche une boite de dialogue au démarrage demandant les login (user+pass) puis de lancer la connexion dans la foulé. Si la demande des identifiants se fait par l'intermédiaire d'un script shell en console cela me conviendra amplement. Voila voila merci à ceux qui auront le courage de lire ce message jusqu'à la fin et merci à ceux qui pourrons m'éclairer ! (n'hésiter pas à me demander plus de précision si besoin...) Cordialement, Anthony Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) UP personne ? J'ai vu ceci sur le site suivant... mais RIEN ! Je ne sais pas comment activer automatiquement cette connexion.... Quelques infos peu utile ... http://projects.gnome.org/NetworkManage … Connection Dernière modification par toto2849 (Le 04/06/2009, à 22:19) Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) Décidément personne peut m'aider ?? Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) hop un UP pour la route....:rolleyes: Hors ligne killman Re : Connexion VPN automatique (NetworkManager) je n' ai pas eu le temps de me pencher sur la question, mais tu devrais essayer de rédiger un script qui lance la connexion cliente sur le vpn, si tu veux automatiser ça. Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) -Tout d'abord merci d'avoir répondu à mon problème car j'ai cru que tout le monde s'en foutait... -Donc pour te répondre, oui en effet c'est ce que j'ai pensé aussi; d'ailleurs j'en ai commencé un morceau mais je ne connait pas les raccourcis me permettant de lancer en shell la connexion vpn de NetworkManager... Bien entendu si quelqu'un peut me proposer une méthode alternative qui ne passerait pas par ce gestionnaire cela me conviendra aussi ! Voici pour le moment ce que j'ai pu faire....mais je connais pas grand chose en script: #!/bin/sh #saisie des login echo "Saisir nom d'utilisateur : " read utilisateur echo "Saisir mot de passe : " read -s passe #lancement de la connexion vpn org.freedesktop.NetworkManager.ppp_starter ...mais cela est faux... Comme dit plus haut j'ai trouvé sur leur site 2/3 truc comme "org.freedesktop.NetworkManager.VPN.Connection" mais es applicable pour lancer une connexion par la console ? j'ai tenté mais rien...peut être un soucis de syntaxe ? Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Moi, j'ai une solution avec NetworkManager. Il s'agit d'un service qui utilise d-bus pour piloter le NetworkManager. Le principe est assez simple, mais le script est assez complexe. ... Suite aux différents échanges qui ont été fait sur le sujet, j'utilise ce post, pour proposer une solution simple et accessible aux néophytes. Cette solution permet de lancer automatiquement une connexion vpn et qu'elle se reconnecte automatiquement en cas de coupure. Remarques : - Cette solution n'est pas forcément compatible avec d'ancienne version d'ubuntu. - Pour une utilisation avancée, voir les autres posts de cette discussion, en particulier le post #28 (http://forum.ubuntu-fr.org/viewtopic.ph … 7#p3225667) de Papou qui propose des scripts qui permettent de lancer la connexion automatique "à la demande". - Pour ceux qui auraient déjà mis en place le script connection-service, celui-ci a un peu évolué, il faut donc le mettre à jour. Voici, la démarche, en deux étapes, à suivre : - ajouter ce script exécutable 02-loop-vpn dans /etc/NetworkManager/dispatcher.d/ en ayant pris soin de renseigner le nom de la connexion vpn /etc/NetworkManager/dispatcher.d/02-loop-vpn : #!/bin/bash # Script de lancement de connection VPN avec verification CONNECTION_NAME="Connexion VPN 1" while ! connection-service "$CONNECTION_NAME" status do connection-service "$CONNECTION_NAME" start sleep 30 done Soit, en ligne de commande : sudo gedit /etc/NetworkManager/dispatcher.d/02-loop-vpn copier/coller le code ci-dessus dans le fichier, et renseigner le champ CONNECTION_NAME avec le nom utilisé par le Network Manager pour votre connexion sudo chmod +x /etc/NetworkManager/dispatcher.d/02-loop-vpn - ajouter ce script exécutable connection-service dans /usr/local/bin/ /usr/local/bin/connection-service : #!/bin/bash ############ # SETTINGS # ############ get_connections_paths() { dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \ | grep "object path" | cut -d '"' -f2 } get_connection_settings() { dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings } get_connection_string_setting() { echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2 } get_connection_id() { get_connection_string_setting "$1" "id" } get_connection_type() { get_connection_string_setting "$1" "type" } get_device_type_by_connection_type() { echo "$1" | grep -q "ethernet" && echo 1 && return echo "$1" | grep -q "wireless" && echo 2 && return echo 0 } find_connection_path() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` [ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path" done } find_connection_path_everywhere() { find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1" find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1" } print_connections_ids() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } print_connections_ids_everywhere() { print_connections_ids "org.freedesktop.NetworkManagerSystemSettings" print_connections_ids "org.freedesktop.NetworkManagerUserSettings" } ########### # DEVICES # ########### get_devices_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \ | grep "object path" | cut -d '"' -f2 } get_device_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \ | grep variant | awk '{print $3}' } get_device_type() { get_device_property "$1" "DeviceType" } get_device_path_by_device_type() { device_path_by_device_type="/" for device_path in `get_devices_paths` do device_type=`get_device_type "$device_path"` [ "$device_type" = "$1" ] && device_path_by_device_type="$device_path" done echo "$device_path_by_device_type" } ####################### # ACTIVES CONNECTIONS # ####################### get_actives_connections_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \ | grep "object path" | cut -d '"' -f2 } get_last_active_connection_path() { get_actives_connections_paths | tail -n 1 } get_parent_connection_path_by_device_type() { parent_connection_path="/" [ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path` echo "$parent_connection_path" } get_active_connection_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \ | grep variant | awk -F '"' '{print $2}' } get_active_connection_service() { get_active_connection_property "$1" "ServiceName" } get_active_connection_path() { get_active_connection_property "$1" "Connection" } get_active_connection_path_by_connection_path() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` [ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path" done } print_actives_connections_ids() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` connection_settings=`get_connection_settings "$service" "$path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } ############## # START/STOP # ############## start_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_connection_settings=`get_connection_settings $my_connection_complete_path` my_connection_type=`get_connection_type "$my_connection_settings"` my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"` my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'` my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'` my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"` my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"` echo "connection_service=$my_connection_service" echo "connection_path=$my_connection_path" echo "connection_device_path=$my_connection_device_path" echo "parent_connection_path=$my_parent_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path" } stop_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path` echo "active_connection_path=$my_active_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path" } ######## # MAIN # ######## invalid_arguments() { echo "Usage: `basename "$0"` connexion_name start|stop" echo "Connexion disponibles:" print_connections_ids_everywhere echo "Connexion actives:" print_actives_connections_ids exit 0 } [ "$#" != 2 ] && invalid_arguments case "$2" in "start") start_connection "$1" ;; "stop") stop_connection "$1" ;; "restart") stop_connection "$1" start_connection "$1" ;; "status") if print_actives_connections_ids | grep -q -x "$1" then echo "Connexion \"$1\" active" exit 0 else echo "Connexion \"$1\" inactive" exit 1 fi ;; *) invalid_arguments ;; esac Soit, en ligne de commande : sudo gedit /usr/local/bin/connection-service copier/coller le code ci-dessus dans le fichier, puis sudo chmod +x /usr/local/bin/connection-service Enjoy it! Dernière modification par coredump (Le 30/01/2010, à 11:21) Hors ligne legrosschmoll Re : Connexion VPN automatique (NetworkManager) Ca n'a pas l'air d 'intéresser toto2849 mais moi oui. Si tu pouvais poster ta solution Merci d'avance Precise sur W500 Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Désolé, si je réponds un peu tard, ça fait un moment que je consulte pas le forum. Voici ma solution, si ça t'intéresse toujours ou si ça intéresse quelqu'un d'autre. L'origine du problème a deux sources par rapport au VPN avec Network Manager : - quand on coche "Connecter automatiquement", ceci n'est pas pris en compte - quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs) (En général, je trouve que le Network Manager a de légers disfonctionnements qui démontrent à mon avis quelques problèmes de conceptions ...) Les scripts que je propose tente de remédier à cela. Leur but est de connecter automatiquement le VPN et de le reconnecter automatiquement si il se déconnecte. (Avec de légères modifications, ça pourrait se comporter différemment selon le besoin.) Le principe est de se lancer et de s'arrêter en fonction d'une autre connexion parente (eth0 par exemple). Puis de surveiller d-bus pour voir : - si les paramètres de la connexion VPN sont disponibles (quand l'utilisateur se connecte) - si la connexion VPN ne s'est pas déconnectée Il y a deux scripts : 02-service-vpn -> à mettre dans /etc/NetworkManager/dispatcher.d/ (lance ou arrête "checkVPN" en fonction de la connexion parente) checkVPN -> à mettre dans /usr/local/bin/ (script python qui surveille que la connexion VPN soit toujours bien connecter) Tous deux doivent être exécutables. checkVPN dépend d'un autre fichier : nm_utils.py -> à mettre dans /usr/local/bin/ (outils pour piloter le nm en python) Il y a deux champs à renseigner dans le script 02-service-vpn : ETH_INTERFACE_NAME : l'interface de la connexion parente (par exemple : eth0) VPN_CONNECTION_NAME : le nom de la connexion VPN qui a été renseigner dans le network manager (Pour que ça marche pour plusieurs utilisateurs, il faut pour chacun définir la connexion VPN.) (Il y a aussi la possibilité de décommenter des lignes pour avoir des traces.) /etc/NetworkManager/dispatcher.d/02-service-vpn : #!/bin/bash ETH_INTERFACE_NAME="eth0" # The name of the VPN connection to activate VPN_CONNECTION_NAME="Connexion VPN" # Or the uuid of the VPN connection to activate #VPN_CONNECTION_NAME="UUID=abcf8915-bb27-4634-94e6-04c65261a73e" SERVICE_VPN_LOG="/dev/null" #SERVICE_VPN_LOG="/tmp/serviceVPN.log" CHECK_VPN_LOG="/dev/null" #CHECK_VPN_LOG="/tmp/checkVPN.log" echo `date`": $0 $@" >> "$SERVICE_VPN_LOG" [ "$1" != "$ETH_INTERFACE_NAME" ] && exit 0 case "$2" in "up") echo "Starting CheckVPN ... ("`which checkVPN`")" >> "$SERVICE_VPN_LOG" # On vérifie que checkVPN ne tourne pas déjà if [ "`pgrep checkVPN`" == "" ] then echo "CheckVPN started." >> "$SERVICE_VPN_LOG" checkVPN "$VPN_CONNECTION_NAME" > "$CHECK_VPN_LOG" 2>&1 & else echo "CheckVPN already running !" >> "$SERVICE_VPN_LOG" fi ;; "down") echo "Stoping checkVPN ..." >> "$SERVICE_VPN_LOG" if [ "`pgrep checkVPN`" == "" ] then echo "CheckVPN not running !" >> "$SERVICE_VPN_LOG" else pkill checkVPN echo "CheckVPN stopped." >> "$SERVICE_VPN_LOG" fi ;; *) echo "Nothing to do" >> "$SERVICE_VPN_LOG" ;; esac /usr/local/bin/checkVPN : #!/usr/bin/python -u # coding=UTF-8 import sys import dbus from dbus.mainloop.glib import DBusGMainLoop import gobject from nm_utils import * VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None # Default values : # The name of the VPN connection to activate #VPN_CONNECTION_NAME = "Connexion VPN 1" # or the uuid of the VPN connection to activate #VPN_CONNECTION_UUID = "fabf8915-bb27-4634-94e6-04c65261a73e" if len(sys.argv) > 1: vpn_argument = sys.argv[1] VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None if (vpn_argument[:5] == "UUID="): VPN_CONNECTION_UUID = vpn_argument[5:] print "VPN_CONNECTION_UUID=%s" % (VPN_CONNECTION_UUID) else: VPN_CONNECTION_NAME = vpn_argument print "VPN_CONNECTION_NAME=%s" % (VPN_CONNECTION_NAME) if (not VPN_CONNECTION_UUID) and (not VPN_CONNECTION_NAME): print "Usage : "+sys.argv[0]+" connexion_vpn_name" print "Liste des connexions diponibles :" print_connections_infos() sys.exit(1) vpn_connection_infos = {'vpn_connection_settings': None, 'vpn_connection_path': None} def get_vpn_connection_settings(): if VPN_CONNECTION_UUID: return get_connection_settings_by_uuid(VPN_CONNECTION_UUID) if VPN_CONNECTION_NAME: return get_connection_settings_by_name(VPN_CONNECTION_NAME) return None def get_vpn_connection_path(): if VPN_CONNECTION_UUID: return get_active_connection_path_by_uuid(VPN_CONNECTION_UUID) if VPN_CONNECTION_NAME: return get_active_connection_path_by_name(VPN_CONNECTION_NAME) return None def get_eth_active_connection_path(): try: active_connections_paths = get_active_connections_paths() active_connections_paths_count = len(active_connections_paths) if active_connections_paths_count == 0: return None return active_connections_paths[active_connections_paths_count-1] except Exception as exception: print exception return None def update_vpn_connection_settings(): vpn_connection_settings = get_vpn_connection_settings() vpn_connection_infos['vpn_connection_settings'] = vpn_connection_settings print "update_vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings) def update_vpn_connection_path(): vpn_connection_path = get_vpn_connection_path() vpn_connection_infos['vpn_connection_path'] = vpn_connection_path print "update_vpn_connection_path: vpn_connection_path=%s" % vpn_connection_path def start_connection(settings, active_connection_path): def reply_handler(opath): vpn_connection_path = opath vpn_connection_infos['vpn_connection_path'] = vpn_connection_path def error_handler(*args): print args proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') iface.ActivateConnection(get_connection_settings_type(settings), get_connection_settings_path(settings), dbus.ObjectPath("/"), active_connection_path, reply_handler=reply_handler, error_handler=error_handler) def checkVPN(): vpn_connection_settings = vpn_connection_infos['vpn_connection_settings'] # Do nothing if vpn connection settings don't exist print "checkVPN: vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings) if not vpn_connection_settings: return vpn_connection_path = vpn_connection_infos['vpn_connection_path'] # Do nothing if vpn connection already exist print "checkVPN: vpn_connection_path=%s" % vpn_connection_path if vpn_connection_path: return eth_connection_path = get_eth_active_connection_path() print "checkVPN: eth_connection_path=%s" % eth_connection_path # Do nothing if eth connection don't exist if not eth_connection_path: return start_connection(vpn_connection_settings, eth_connection_path) def handle_connection_settings_changed(): print "handle_connection_settings_changed" update_vpn_connection_settings() checkVPN() def handle_connections_changed(): print "handle_connections_changed" update_vpn_connection_path() checkVPN() def all_signal_receiver(*args, **kwargs): if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings"): handle_connection_settings_changed() if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings.Connection")\ and (kwargs['signal_name'] == "Updated"): handle_connection_settings_changed() if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManager")\ and (kwargs['signal_name'] == "PropertiesChanged")\ and args[0].has_key('ActiveConnections'): handle_connections_changed() DBusGMainLoop(set_as_default=True) dbus.SystemBus().add_signal_receiver(all_signal_receiver, interface_keyword='dbus_interface', member_keyword='signal_name') update_vpn_connection_settings() update_vpn_connection_path() checkVPN() gobject.MainLoop().run() /usr/local/bin/nm_utils.py : # coding=UTF-8 import dbus # Get connection settings from settings type and settings path # (settings type is 'org.freedesktop.NetworkManagerSystemSettings' or 'org.freedesktop.NetworkManagerUserSettings') def get_connection_settings(settings_type, settings_path): proxy = dbus.SystemBus().get_object(settings_type, settings_path) iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection') settings = iface.GetSettings() settings['settings-type'] = settings_type settings['settings-path'] = settings_path return settings # Get differents informations from connection settings def get_connection_settings_type(settings): return settings['settings-type'] def get_connection_settings_path(settings): return settings['settings-path'] def get_connection_settings_uuid(settings): return settings['connection']['uuid'] def get_connection_settings_name(settings): return settings['connection']['id'] # Get all settings paths associated to a type of settings def get_connections_settings_paths(settings_type): try: proxy = dbus.SystemBus().get_object(settings_type, '/org/freedesktop/NetworkManagerSettings') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings') return iface.ListConnections() except Exception as exception: print " !!! get_connections_settings_paths:" print exception return [] # Get all connections settings associated to a type of settings def get_connections_settings_by_type(settings_type): connections_settings = [] for settings_path in get_connections_settings_paths(settings_type): connection_settings = get_connection_settings(settings_type, settings_path) connections_settings.append(connection_settings) return connections_settings # Get all connections settings def get_all_connections_settings(): return get_connections_settings_by_type('org.freedesktop.NetworkManagerUserSettings') + \ get_connections_settings_by_type('org.freedesktop.NetworkManagerSystemSettings') # Get the esssential informations of the connection def get_connection_infos(settings): if settings: conn = settings['connection'] return "%s (type=%s, UUID=%s)" % (conn['id'], conn['type'], conn['uuid']) else: return None # Print the list of connections def print_connections_infos(): for connection_settings in get_all_connections_settings(): print get_connection_infos(connection_settings) # Get connection settings from the settings UUID def get_connection_settings_by_uuid(uuid): try: for settings in get_all_connections_settings(): if get_connection_settings_uuid(settings) == uuid: return settings except Exception as exception: print exception return None # Get connection settings from the settings UUID def get_connection_settings_by_name(name): try: for settings in get_all_connections_settings(): if get_connection_settings_name(settings) == name: return settings except Exception as exception: print exception return None # Get list of active connections paths def get_active_connections_paths(): proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') return iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') # Get connection settings from the connection path def get_connection_settings_by_connection_path(connection_path): proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', connection_path) iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') settings_type = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'ServiceName') settings_path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') return get_connection_settings(settings_type, settings_path) # Get list of active connections paths def get_active_connections_settings(): actives_connections_settings = [] for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) settings['connection-path'] = connection_path actives_connections_settings.append(settings) return actives_connections_settings # Look for connexion path in active connexions with particular uuid def get_active_connection_path_by_uuid(uuid): try: for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) if get_connection_settings_uuid(settings) == uuid: return connection_path except Exception as exception: print exception return None # Look for connexion path in active connexions with particular name def get_active_connection_path_by_name(name): try: for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) if get_connection_settings_name(settings) == name: return connection_path except Exception as exception: print exception return None Voilà, ça peut certainement être amélioré ou généralisé, mais j'espère au moins que ça pourra te dépanner. Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) En tout cas, ca en dépanne d'autres ! merci bp pour ce boulot coredump, ca marche nickel, et c'est en plus trés propre, pas grand chose à redire, si ce n'est merci ! Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Merci ElFabio pour ton soutien et content que ça puisse te servir. Une solution plus propre serait de trouver une correction au niveau du network manager ou de l'applet (est-ce que l'applet KDE marche ?). Si j'avais un peu de temps et plus d'expérience dans la rédaction d'articles, j'aurais bien fait un tuto sur l'utilisation de d-bus pour contrôler le NM, car la documentation à ce sujet est assez maigre sur le net. Voici quand même quelques liens qui m'ont été utiles : - http://doc.ubuntu-fr.org/networkmanager … e_commande - http://doc.ubuntu-fr.org/dbus - http://old.nabble.com/dbus-and-OpenVPN- … 05375.html - http://projects.gnome.org/NetworkManage … /spec.html - http://linuxfr.org/forums/15/27406.html - http://dbus.freedesktop.org/doc/dbus-py … orial.html Je recommande aussi l'interface graphique d-feet pour s'exercer à utiliser d-bus (pratique aussi pour retrouver les API des services). (Quand on veut être "listener" - à l'écoute - d'un service, la commande dbus-monitor aussi est pratique.) Et pour ceux qui voudraient piloter NM à l'aide de d-bus, voici quelques exemples de lignes de commande qui permettent de le faire : Afficher la liste des chemins des définitions des connexion selon leurs appartenances (système - disponibles pour tous les utilisateurs / personnel - propre à l'utilisateur) : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings" \ org.freedesktop.NetworkManagerSettings.ListConnections (ou --dest="org.freedesktop.NetworkManagerUserSettings") Afficher les paramètres d'une connexion selon son appartenance et connaissant son chemin dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings/0" \ org.freedesktop.NetworkManagerSettings.Connection.GetSettings (ou --dest="org.freedesktop.NetworkManagerUserSettings") Afficher la liste des chemins des connexions actives : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager" string:"ActiveConnections" Afficher une propriété d'une connexion active connaissant son chemin : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager/ActiveConnection/2" \ org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager.Connection.Active" string:"nom_de_la_propriete" "nom_de_la_propriete" est à renseigner. Par exemple, "nom_de_la_propriete" peut-être "ServiceName" ou "Connection" pour connaître l'appartenance et le chemin de la définition de la connexion. Arrêter une connection active connaissant son chemin : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.DeactivateConnection objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2" Démarrer une connexion : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerSystemSettings" objpath:"/org/freedesktop/NetworkManagerSettings/0" objpath:"/org/freedesktop/NetworkManager/Devices/0" objpath:"/" ou dans le cas d'une connection vpn : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerUserSettings" objpath:"/org/freedesktop/NetworkManagerSettings/1" objpath:"/" objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2" Le problème de cette commande est qu'il faut passer en argument de la commande le chemin du device (ethN ou rien pour le vpn) et le chemin de la connexion active dont elle dépend (si elle n'utilise pas de device). Malheureusement ces informations ne sont pas évidentes à déduire. Pour terminer voici un exemple de script utilisant ces commandes et permettant de démarrer ou d'arrêter une connexion en lui passant le nom de la connexion. Pour l'utiliser, nommer le fichier "connection-service", le rendre exécutable et placer le dans "/usr/local/bin/", puis taper : connection-service "nom_de_la_connexion" start|stop Par exemple : connection-service "Connection VPN 1" start /usr/local/bin/connection-service : #!/bin/bash ############ # SETTINGS # ############ get_connections_paths() { dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \ | grep "object path" | cut -d '"' -f2 } get_connection_settings() { dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings } get_connection_string_setting() { echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2 } get_connection_id() { get_connection_string_setting "$1" "id" } get_connection_type() { get_connection_string_setting "$1" "type" } get_device_type_by_connection_type() { echo "$1" | grep -q "ethernet" && echo 1 && return echo "$1" | grep -q "wireless" && echo 2 && return echo 0 } find_connection_path() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` [ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path" done } find_connection_path_everywhere() { find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1" find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1" } print_connections_ids() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } print_connections_ids_everywhere() { print_connections_ids "org.freedesktop.NetworkManagerSystemSettings" print_connections_ids "org.freedesktop.NetworkManagerUserSettings" } ########### # DEVICES # ########### get_devices_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \ | grep "object path" | cut -d '"' -f2 } get_device_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \ | grep variant | awk '{print $3}' } get_device_type() { get_device_property "$1" "DeviceType" } get_device_path_by_device_type() { device_path_by_device_type="/" for device_path in `get_devices_paths` do device_type=`get_device_type "$device_path"` [ "$device_type" = "$1" ] && device_path_by_device_type="$device_path" done echo "$device_path_by_device_type" } ####################### # ACTIVES CONNECTIONS # ####################### get_actives_connections_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \ | grep "object path" | cut -d '"' -f2 } get_last_active_connection_path() { get_actives_connections_paths | tail -n 1 } get_parent_connection_path_by_device_type() { parent_connection_path="/" [ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path` echo "$parent_connection_path" } get_active_connection_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \ | grep variant | awk -F '"' '{print $2}' } get_active_connection_service() { get_active_connection_property "$1" "ServiceName" } get_active_connection_path() { get_active_connection_property "$1" "Connection" } get_active_connection_path_by_connection_path() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` [ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path" done } print_actives_connections_ids() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` connection_settings=`get_connection_settings "$service" "$path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } ############## # START/STOP # ############## start_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_connection_settings=`get_connection_settings $my_connection_complete_path` my_connection_type=`get_connection_type "$my_connection_settings"` my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"` my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'` my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'` my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"` my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"` echo "connection_service=$my_connection_service" echo "connection_path=$my_connection_path" echo "connection_device_path=$my_connection_device_path" echo "parent_connection_path=$my_parent_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path" } stop_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path` echo "active_connection_path=$my_active_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path" } ######## # MAIN # ######## invalid_arguments() { echo "Usage: `basename "$0"` connexion_name start|stop" echo "Connexion disponibles:" print_connections_ids_everywhere echo "Connexion actives:" print_actives_connections_ids exit 0 } [ "$#" != 2 ] && invalid_arguments case "$2" in "start") start_connection "$1" ;; "stop") stop_connection "$1" ;; "restart") stop_connection "$1" start_connection "$1" ;; "status") if print_actives_connections_ids | grep -q -x "$1" then echo "Connexion \"$1\" active" exit 0 else echo "Connexion \"$1\" inactive" exit 1 fi ;; *) invalid_arguments ;; esac Dernière modification par coredump (Le 28/01/2010, à 13:21) Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) effectivement, tu as bien potassé ton d-bus ! et de rien pour le soutien, c'est le moins que je puisse faire, surtout que j'utilise maintenant ton script tous les jours ! vraiment exactement ce que je recherchais ! Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Par les temps qui courent, il vaut mieux surfer bien couvert Hors ligne Brunod Re : Connexion VPN automatique (NetworkManager) Salut, Je te félicite anticipativement parce que là, en congé, je n'en ai pas besoin; mais à la rentrée, faudra que je me penche dessus ! Merci ! Wanted : >>> un emploi dans la sécurité informatique et réseau <<< Windows est un système d'exploitation de l'homme par l'ordinateur. Linux, c'est le contraire ... --> état de la conversion : 36 pc linux Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) À noter, que le script "connection-service" défini dans mon post #11 ci-dessus peut aussi être utilisé pour connecter automatiquement le VPN. Pour cela, créer un script "vpn-autostart" exécutable dans "/usr/local/bin/", /usr/local/bin/vpn-autostart : #!/bin/bash # Délai de 10 secondes pour laisser le temps à nm-applet de démarrer sleep 10 && connection-service "Connection VPN 1" start Ajouter ensuite un programme "VPN" dans la liste des "Applications au démarrage" avec comme commande : vpn-autostart Ceci démarrera la connexion "Connection VPN 1" à l'ouverture de la session. Et pour reconnecter automatiquement la connexion en cas de coupure, ajouter ce script "02-loop-vpn" exécutable dans "/etc/NetworkManager/dispatcher.d/": /etc/NetworkManager/dispatcher.d/02-loop-vpn : #!/bin/bash [ "$2" = "vpn-down" ] && vpn-autostart Et voilà ! Hors ligne lynn Re : Connexion VPN automatique (NetworkManager) Bonjour, Merci à toi coredump pour ces scripts de connection automatique pour VPN. Ils fonctionnent parfaitement Comme tu le dis si bien : - quand on coche "Connecter automatiquement", ceci n'est pas pris en compte - quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs) A quand un Network Manager complètement fonctionnel ? Parce que c'est vrai que ce genre de "détails" est quand même bien ch...t. En attendant, merci encore coredump et je pense que ce post va intéresser pas mal de monde .....:P Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Merci encore une fois coredump pour ce tutoriel trés pratique et directement utilisable, j'en profite pour abuser un peu de tes compétences pour te poser une question concernant l'usage de tes scripts (j'utilise en particulier checkVPN) : aprés maintenant plusieurs jours d'utilisation, je remarque qu'au fur et à mesure de mes reconnexions automatique à mon provider VPN (lors d'une déconnexion), le débit global des téléchargements (dans mon client torrent préféré...) a tendance à se contracter fortement (divisé par 2 ou 3), et un simple redémarrage du PC permet de revenir à un débit normal. Pour info je me connecte en WiFi, et peut être n'est ce pas du à l'utilisation de tes scripts, mais est ce que ca ne pourrait pas venir d'un "engorgement" de process qui s'accumulent en taches de fond suite à de multiples déconnexion/reconnexion VPN, je ne pense pas trop parce qu'en faisant un ps aux je n'en trouve pas trace et qu'en plus ton script me parait vraiment trés propre, mais je n'ai pas d'explications plausibles... est ce que tu aurais déjà rencontré le même genre de soucis ou aurais tu une idée de leur origine ? Je te souhaite une trés bonne année, Hors ligne rogerjm Re : Connexion VPN automatique (NetworkManager) Bravo coredump pour ce post (qui n'est pas loin d'être un article ). Tout ce que tu y as décrit m'a été très utile pour configurer mon VPN et le lancer automatiquement, mais aussi m'a appris plein de choses. Bonne année Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Bonne année à tous ! Au sujet de ton problème, ElFabio, je ne pense pas pouvoir t'aider beaucoup. À vue de nez, voici mes impressions : - Concernant le script de reconnexion, ça m'étonnerait qu'il puisse provoquer un "engorgement". La plupart du temps il est au repos (en attente d'évènements) et quand il bosse, il ne fait jamais que quelques petites opérations. Le seul petit souci que je verrais, serait le délai de reconnexion. En cas de coupure, il cherche instantanément à se reconnecter et ce n'est peut-être pas très bon. J'ai remarqué qu'en cas de coupure, la reconnexion ne se fait pas toujours à la première tentative. Le fait d'envoyer des requêtes de reconnexion aussi proches n'est peut-être pas très bon. En même temps, une fois qu'il s'est reconnecté, je n'ai pas observé pour ma part de diminution de la bande passante. Mais, si tu veux chercher dans cette voie, tu peux essayer avec l'autre méthode (elle n'utilise pas de process en fond de tâche) et jouer sur le délai de reconnection. Les autres pistes pourraient venir à mon avis de la connexion Wifi, du client torrent ou du service VPN : - Pour la connexion Wifi, j'ai entendu dire que le peer-to-peer n'est pas très bon. J'ai eu à une époque un fournisseur internet wifi qui interdisait de faire du peer-to-peer sur son réseau (sinon ça le faisait planter). De cette époque, j'ai pris l'habitude de faire du warez, je n'utilise les torrents que de façon ponctuel, donc je n'ai pas trop d'expérience à ce sujet. Tout ce que je peux te dire, c'est que je ne rencontre pas ce problème avec les boards warez et JDownloader. Pour explorer cette piste, il faudrait que tu es la possibilité de tester la différence avec une connexion filaire, ou consulter les forums sur les torrents et le Wifi. - Pour le client torrent, peut-être que le fait d'avoir des coupures le perturbe. Une possibilité pourrait être de le relancer quand tu observes une diminution de débit et voir si ça change quelque chose. Ou voir si tu observes aussi sur cette baisse de débit sur un test de bande passante (avec speedtest.net, par exemple). - Le fournisseur VPN peut-être aussi offre de moins bon service au bout d'une certaine durée de connexion. Là, si tu as la possibilité d'essayer une autre connexion VPN pour voir la différence. Ou provoquer volontairement les coupures VPN depuis l'applet du Network Manager pour voir si ce sont bien les coupures qui font baisser le débit. En gros, essaye de voir, et si c'est possible, si ton problème persiste : - sans vpn (mais ça, tu le sais surement déjà) - ou avec une connexion réseau filaire - ou en redémarrant le client torrent - ou en redémarrant le Network Manager (sudo service network-manager restart, NetworkManager pour les versions d'ubuntu plus anciennes) - ou en espaçant les délais entre les reconnections - ou avec un autre fournisseur VPN (personnellement, j'utilise HideMyNet, un peu payant) ça t'aidera peut-être mieux à localiser ton problème qu'en redémarrant le pc. Bonne chance ! Dernière modification par coredump (Le 02/01/2010, à 12:14) Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Déjà je te remercie pour avoir pris autant de temps pour me répondre, je vais essayer de reparcourir les pistes que tu as mentionné mais, effectivement, ce sont également sensiblement les mêmes que celles que j'avais regardé jusque-là. Mes premieres impresssions tendraient à confirmer les tiennes, le probléme semblerait effectivement provenir davantage de la connexion en Wifi, puisque j'utilise également tes scripts sur un PC fixe en ethernet avec le même provider VPN, et je ne rencontre pas ce genre de problème. J'avais déjà éliminé la piste du provider VPN dont je suis personnellement trés satisfait (il s'agit de TorrentFreedom), et d'ailleurs le fait qu'en redémarrant le PC je retrouve un débit normal tend également à confirmer que le pb ne vient pas de là. D'ailleurs je n'ai pas, comme tu le mentionnes pour toi, de problémes de connexion particulier au VPN, la connexion se fait trés rapidement, par contre, en revanche, il se produit des déconnexions au VPN de façon trés régulière voire périodique (presque toutes les 30mn), ce qui me fait également pencher vers un probléme WiFi ou plutôt de passerelle (Livebox dans mon cas actuel) voire de FAI... Je vais par contre également regarder du côté de ton 2eme script pour voir si j'observe des changements. En tout cas, merci pour ton temps et ta réponse, ca me permet de disposer d'un 2eme avis "éclairé" sur le sujet ! Hors ligne hybernatus Re : Connexion VPN automatique (NetworkManager) Fiou... merci pour ce script et tout ton boulot, je me suis abonné hier à Ipredator (ayant trouvé un super tuto, et n'y connaissant rien en réseaux, j'ai fait au plus simple ^^ ) et j'ai remarqué qu'il se déconnecte de temps en temps... ce qui est un peu c*n tout de même quand on veut une connexion sécurisée et anonyme je trouve J'essairai d'appliquer ça dès que je trouve la motiv merci ! Mes photos: http://www.hyb.me/photos Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Salut coredump, je reviens juste vers toi pour te faire un petit debriefing : ta deuxiéme solution (via connection-service) a résolu mes problémes de "coupure" intempestive et réguliére du VPN, je l'ai un peu aménagé à ma sauce, notamment pour disposer d'une connexion 'manuelle' au VPN et non un lancement automatique au démarrage, mais, que ce soit en Wi-Fi ou en Ethernet, cela fonctionne maintenant parfaitement. Donc encore merci pour ton travail, et bonne continuation ! Hors ligne Papou Re : Connexion VPN automatique (NetworkManager) Merci Coredump pour ces scripts très utiles. La reconnection automatique c'est nickel .... sauf quand c'est le modem qui décroche de l'ADSL et met un peu de temps pour redémarrer, la reconnection au VPN n'aboutit alors pas et l'accès internet se retrouve en direct quelques secondes plus tard. Serait-il possible de faire encore mieux ? Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ... Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Tout d'abord merci ElFabio pour ton retour d'expérience. A mon avis : - la première solution (en python) est plus fiable, car le service tourne en tâche de fond et ne dépend pas de la connexion de l'utilisateur, mais plus complexe et donc plus difficile à maintenir, - la deuxième (en shell) est plus simple et plus clair, et donc plus adaptable et plus facile à maintenir, et par expérience marche bien. Et en définitif, je conseillerai donc plutôt celle-ci. Pour rappel, cette méthode est décrite dans le post #15 avec le script "connection-service" de la fin du poste #11. (Si je trouve un peut de temps, j'en ferais bien la synthèse dans un tuto ...) Ensuite par rapport à Papou, si tu veux que le vpn se reconnecte quand ta connexion adsl se reconnecte (j'imagine que tu utilises la deuxième méthode et qu'il ne s'agit pas d'une connexion adsl pppoe ?), tu peux essayer d'ajouter cette ligne dans le script /etc/NetworkManager/dispatcher.d/02-loop-vpn : [ "$2" = "up" ] && vpn-autostart (Pour voir si ça marche, tu peux essayer en redémarrant à la main ton modem en cours de connexion.) Dernière modification par coredump (Le 18/01/2010, à 15:45) Hors ligne Papou Re : Connexion VPN automatique (NetworkManager) coredump, Merci pour ta réponse. j'utilise la deuxième méthode et il s'agit d'une connexion adsl pppoe. L'inconvénient d'ajouter la ligne "[ "$2" = "up" ] && vpn-autostart" est qu'il devient alors impossible de déconnecter volontairement le VPN pour les applications qui ne le supporte pas (sauf a écrire un script de déconnexion volontaire qui va déplacer le fichier 02-loop-vpn en dehors de dispatcher). D'autre part, il me semble avoir remarqué que le problème est que la connection VPN échoue parfois (timeout d'environ 10 sec ? ) et qu'il n'y a alors pas de deuxième essai. Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ... Hors ligne
There are two lists/arrays and I want to assign one by one. import Mybench process = [] benchmarks = options.benchmark.split(',') for bench_name in benchmarks: process.append(getattr(Mybench, bench_name)) Assume another list (cpus) is also created. Now I want to do this: i = 0 for i, cpu in cpus: print "cpu", i, "assigned to ", process[i] cpu.workload = process[i] i = i+1 However in the output I see: cpu 0 assigned to <orphan LiveProcess> LiveProcess() is returned from Mybench. How can I fis that?
I was recently working on one small tool for Midgard Project, and had to deal with a new framework: PyGI. Strictly speaking, it’s not “totally new”, but it is: a) new for me b) just starts to get attention from application developers. PyGI is a project, which implements dynamic bindings to GObject based libraries for Python using GObject Introspection. Initially, it was a separate project, these days it is merged into main PyGObect. If you read my previous posts, this is kinda what we want to implement for PHP in GObject for PHP project, but for Python. For the project, I used Python 3. This choice led to the requirement of installing latest versions of software, but the good news is, that coming Ubuntu Natty has a good initial set of software. So, I had to install: Python 3.1 (3.2 should work too) GObject Introspection 0.10.x PyGObject 2.28.0 (2.27.x-dev series are ok too) If you plan to work with ØMQ, as I did, be sure to grab PyZMQ 2.1 series (easy_install will probably work) The main library, I worked with — libmidgard2 — supports GObject introspection, so I didn’t need to install anything python-related to make it work. Ok. Here are some hints on coding using PyGI. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # to use introspection-friendly library use import statement similar to this from gi.repository import Midgard # global functions are available directly in imported package Midgard.init() # constructors are ALWAYS called with "named" parameters config = Midgard.Config(dbtype = "SQLite", database = "testdb") # library errors are thrown as exceptions import gobject try: do_something() except gobject.GError as e: print(e.message) # want to know name of objects GType? print(obj.__class__.__gtype__.name) # want to get list of non-object properties of some GObject? property_names = [pspec.name for pspec in obj.props if not pspec.value_type.is_classed()] # need to get names of all classes, which inherit from your GObject's class? # (note: Midgard.Object is the class to be replaced by your class) child_names = [gtype.name for gtype in Midgard.Object.__gtype__.children]
My python scripts run fine from IDLE, but when I try to run them from the command-line, things go wrong. First I had trouble importing pygame, but I added C:\Python27\Lib\site-packages to the PYTHONPATH environment variable and all was well, I thought. However, now when I attempt to run something from the command line, I get this: C:\Users\Ian Sinke\Documents\Pong>python pong.py 'import site' failed; use -v for traceback Traceback (most recent call last): File "pong.py", line 3, in ? import pygame File "C:\Python27\Lib\site-packages\pygame\__init__.py", line 27, in ? import sys, os, string File "C:\Python27\Lib\os.py", line 63, in ? import ntpath as path File "C:\Python27\Lib\ntpath.py", line 401 backslash, dot = (u'\\', u'.') if isinstance(path, unicode) else ('\\', '.') ^ SyntaxError: invalid syntax Any ideas? This is not a localize problem; when I try to run another script from the command line, I get this: C:\Users\Ian Sinke\Documents>python app.py 'import site' failed; use -v for traceback Traceback (most recent call last): File "app.py", line 4, in ? import urllib2 File "C:\Python27\Lib\urllib2.py", line 92, in ? import base64 File "C:\Python27\Lib\base64.py", line 346 with open(args[0], 'rb') as f: ^ SyntaxError: invalid syntax and that syntax is definitely OK... Pong.py begins like this: #import sys import math import pygame import time from pygame.locals import * # Helper functions def centerdist(paddletop, balltop): return balltop - paddletop - 30 # Constants BLACK = 0, 0, 0 pygame.init()
toto2849 Connexion VPN automatique (NetworkManager) Bonjour,:D -Actuellement en stage il met demandé de mettre en place une connexion VPN qui se lance automatiquement au démarrage du pc ne laissant juste à l'utilisateur une boite de dialogue demandant login+pass.:rolleyes: -J'ai déjà installé le plugin "network-manager-pptp" tout est ok la connexion fonctionne ! Cependant j'aimerais que celle-ci se lance d'elle même au démarrage du système malheureusement j'ai beau cocher la case "connexion automatique" rien n'y fait ! Bref je me penche actuellement sur une solution qui puisse en ligne de commande lancer la connexion VPN ! -Le must serait que l'on affiche une boite de dialogue au démarrage demandant les login (user+pass) puis de lancer la connexion dans la foulé. Si la demande des identifiants se fait par l'intermédiaire d'un script shell en console cela me conviendra amplement. Voila voila merci à ceux qui auront le courage de lire ce message jusqu'à la fin et merci à ceux qui pourrons m'éclairer ! (n'hésiter pas à me demander plus de précision si besoin...) Cordialement, Anthony Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) UP personne ? J'ai vu ceci sur le site suivant... mais RIEN ! Je ne sais pas comment activer automatiquement cette connexion.... Quelques infos peu utile ... http://projects.gnome.org/NetworkManage … Connection Dernière modification par toto2849 (Le 04/06/2009, à 22:19) Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) Décidément personne peut m'aider ?? Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) hop un UP pour la route....:rolleyes: Hors ligne killman Re : Connexion VPN automatique (NetworkManager) je n' ai pas eu le temps de me pencher sur la question, mais tu devrais essayer de rédiger un script qui lance la connexion cliente sur le vpn, si tu veux automatiser ça. Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) -Tout d'abord merci d'avoir répondu à mon problème car j'ai cru que tout le monde s'en foutait... -Donc pour te répondre, oui en effet c'est ce que j'ai pensé aussi; d'ailleurs j'en ai commencé un morceau mais je ne connait pas les raccourcis me permettant de lancer en shell la connexion vpn de NetworkManager... Bien entendu si quelqu'un peut me proposer une méthode alternative qui ne passerait pas par ce gestionnaire cela me conviendra aussi ! Voici pour le moment ce que j'ai pu faire....mais je connais pas grand chose en script: #!/bin/sh #saisie des login echo "Saisir nom d'utilisateur : " read utilisateur echo "Saisir mot de passe : " read -s passe #lancement de la connexion vpn org.freedesktop.NetworkManager.ppp_starter ...mais cela est faux... Comme dit plus haut j'ai trouvé sur leur site 2/3 truc comme "org.freedesktop.NetworkManager.VPN.Connection" mais es applicable pour lancer une connexion par la console ? j'ai tenté mais rien...peut être un soucis de syntaxe ? Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Moi, j'ai une solution avec NetworkManager. Il s'agit d'un service qui utilise d-bus pour piloter le NetworkManager. Le principe est assez simple, mais le script est assez complexe. ... Suite aux différents échanges qui ont été fait sur le sujet, j'utilise ce post, pour proposer une solution simple et accessible aux néophytes. Cette solution permet de lancer automatiquement une connexion vpn et qu'elle se reconnecte automatiquement en cas de coupure. Remarques : - Cette solution n'est pas forcément compatible avec d'ancienne version d'ubuntu. - Pour une utilisation avancée, voir les autres posts de cette discussion, en particulier le post #28 (http://forum.ubuntu-fr.org/viewtopic.ph … 7#p3225667) de Papou qui propose des scripts qui permettent de lancer la connexion automatique "à la demande". - Pour ceux qui auraient déjà mis en place le script connection-service, celui-ci a un peu évolué, il faut donc le mettre à jour. Voici, la démarche, en deux étapes, à suivre : - ajouter ce script exécutable 02-loop-vpn dans /etc/NetworkManager/dispatcher.d/ en ayant pris soin de renseigner le nom de la connexion vpn /etc/NetworkManager/dispatcher.d/02-loop-vpn : #!/bin/bash # Script de lancement de connection VPN avec verification CONNECTION_NAME="Connexion VPN 1" while ! connection-service "$CONNECTION_NAME" status do connection-service "$CONNECTION_NAME" start sleep 30 done Soit, en ligne de commande : sudo gedit /etc/NetworkManager/dispatcher.d/02-loop-vpn copier/coller le code ci-dessus dans le fichier, et renseigner le champ CONNECTION_NAME avec le nom utilisé par le Network Manager pour votre connexion sudo chmod +x /etc/NetworkManager/dispatcher.d/02-loop-vpn - ajouter ce script exécutable connection-service dans /usr/local/bin/ /usr/local/bin/connection-service : #!/bin/bash ############ # SETTINGS # ############ get_connections_paths() { dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \ | grep "object path" | cut -d '"' -f2 } get_connection_settings() { dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings } get_connection_string_setting() { echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2 } get_connection_id() { get_connection_string_setting "$1" "id" } get_connection_type() { get_connection_string_setting "$1" "type" } get_device_type_by_connection_type() { echo "$1" | grep -q "ethernet" && echo 1 && return echo "$1" | grep -q "wireless" && echo 2 && return echo 0 } find_connection_path() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` [ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path" done } find_connection_path_everywhere() { find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1" find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1" } print_connections_ids() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } print_connections_ids_everywhere() { print_connections_ids "org.freedesktop.NetworkManagerSystemSettings" print_connections_ids "org.freedesktop.NetworkManagerUserSettings" } ########### # DEVICES # ########### get_devices_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \ | grep "object path" | cut -d '"' -f2 } get_device_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \ | grep variant | awk '{print $3}' } get_device_type() { get_device_property "$1" "DeviceType" } get_device_path_by_device_type() { device_path_by_device_type="/" for device_path in `get_devices_paths` do device_type=`get_device_type "$device_path"` [ "$device_type" = "$1" ] && device_path_by_device_type="$device_path" done echo "$device_path_by_device_type" } ####################### # ACTIVES CONNECTIONS # ####################### get_actives_connections_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \ | grep "object path" | cut -d '"' -f2 } get_last_active_connection_path() { get_actives_connections_paths | tail -n 1 } get_parent_connection_path_by_device_type() { parent_connection_path="/" [ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path` echo "$parent_connection_path" } get_active_connection_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \ | grep variant | awk -F '"' '{print $2}' } get_active_connection_service() { get_active_connection_property "$1" "ServiceName" } get_active_connection_path() { get_active_connection_property "$1" "Connection" } get_active_connection_path_by_connection_path() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` [ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path" done } print_actives_connections_ids() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` connection_settings=`get_connection_settings "$service" "$path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } ############## # START/STOP # ############## start_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_connection_settings=`get_connection_settings $my_connection_complete_path` my_connection_type=`get_connection_type "$my_connection_settings"` my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"` my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'` my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'` my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"` my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"` echo "connection_service=$my_connection_service" echo "connection_path=$my_connection_path" echo "connection_device_path=$my_connection_device_path" echo "parent_connection_path=$my_parent_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path" } stop_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path` echo "active_connection_path=$my_active_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path" } ######## # MAIN # ######## invalid_arguments() { echo "Usage: `basename "$0"` connexion_name start|stop" echo "Connexion disponibles:" print_connections_ids_everywhere echo "Connexion actives:" print_actives_connections_ids exit 0 } [ "$#" != 2 ] && invalid_arguments case "$2" in "start") start_connection "$1" ;; "stop") stop_connection "$1" ;; "restart") stop_connection "$1" start_connection "$1" ;; "status") if print_actives_connections_ids | grep -q -x "$1" then echo "Connexion \"$1\" active" exit 0 else echo "Connexion \"$1\" inactive" exit 1 fi ;; *) invalid_arguments ;; esac Soit, en ligne de commande : sudo gedit /usr/local/bin/connection-service copier/coller le code ci-dessus dans le fichier, puis sudo chmod +x /usr/local/bin/connection-service Enjoy it! Dernière modification par coredump (Le 30/01/2010, à 11:21) Hors ligne legrosschmoll Re : Connexion VPN automatique (NetworkManager) Ca n'a pas l'air d 'intéresser toto2849 mais moi oui. Si tu pouvais poster ta solution Merci d'avance Precise sur W500 Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Désolé, si je réponds un peu tard, ça fait un moment que je consulte pas le forum. Voici ma solution, si ça t'intéresse toujours ou si ça intéresse quelqu'un d'autre. L'origine du problème a deux sources par rapport au VPN avec Network Manager : - quand on coche "Connecter automatiquement", ceci n'est pas pris en compte - quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs) (En général, je trouve que le Network Manager a de légers disfonctionnements qui démontrent à mon avis quelques problèmes de conceptions ...) Les scripts que je propose tente de remédier à cela. Leur but est de connecter automatiquement le VPN et de le reconnecter automatiquement si il se déconnecte. (Avec de légères modifications, ça pourrait se comporter différemment selon le besoin.) Le principe est de se lancer et de s'arrêter en fonction d'une autre connexion parente (eth0 par exemple). Puis de surveiller d-bus pour voir : - si les paramètres de la connexion VPN sont disponibles (quand l'utilisateur se connecte) - si la connexion VPN ne s'est pas déconnectée Il y a deux scripts : 02-service-vpn -> à mettre dans /etc/NetworkManager/dispatcher.d/ (lance ou arrête "checkVPN" en fonction de la connexion parente) checkVPN -> à mettre dans /usr/local/bin/ (script python qui surveille que la connexion VPN soit toujours bien connecter) Tous deux doivent être exécutables. checkVPN dépend d'un autre fichier : nm_utils.py -> à mettre dans /usr/local/bin/ (outils pour piloter le nm en python) Il y a deux champs à renseigner dans le script 02-service-vpn : ETH_INTERFACE_NAME : l'interface de la connexion parente (par exemple : eth0) VPN_CONNECTION_NAME : le nom de la connexion VPN qui a été renseigner dans le network manager (Pour que ça marche pour plusieurs utilisateurs, il faut pour chacun définir la connexion VPN.) (Il y a aussi la possibilité de décommenter des lignes pour avoir des traces.) /etc/NetworkManager/dispatcher.d/02-service-vpn : #!/bin/bash ETH_INTERFACE_NAME="eth0" # The name of the VPN connection to activate VPN_CONNECTION_NAME="Connexion VPN" # Or the uuid of the VPN connection to activate #VPN_CONNECTION_NAME="UUID=abcf8915-bb27-4634-94e6-04c65261a73e" SERVICE_VPN_LOG="/dev/null" #SERVICE_VPN_LOG="/tmp/serviceVPN.log" CHECK_VPN_LOG="/dev/null" #CHECK_VPN_LOG="/tmp/checkVPN.log" echo `date`": $0 $@" >> "$SERVICE_VPN_LOG" [ "$1" != "$ETH_INTERFACE_NAME" ] && exit 0 case "$2" in "up") echo "Starting CheckVPN ... ("`which checkVPN`")" >> "$SERVICE_VPN_LOG" # On vérifie que checkVPN ne tourne pas déjà if [ "`pgrep checkVPN`" == "" ] then echo "CheckVPN started." >> "$SERVICE_VPN_LOG" checkVPN "$VPN_CONNECTION_NAME" > "$CHECK_VPN_LOG" 2>&1 & else echo "CheckVPN already running !" >> "$SERVICE_VPN_LOG" fi ;; "down") echo "Stoping checkVPN ..." >> "$SERVICE_VPN_LOG" if [ "`pgrep checkVPN`" == "" ] then echo "CheckVPN not running !" >> "$SERVICE_VPN_LOG" else pkill checkVPN echo "CheckVPN stopped." >> "$SERVICE_VPN_LOG" fi ;; *) echo "Nothing to do" >> "$SERVICE_VPN_LOG" ;; esac /usr/local/bin/checkVPN : #!/usr/bin/python -u # coding=UTF-8 import sys import dbus from dbus.mainloop.glib import DBusGMainLoop import gobject from nm_utils import * VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None # Default values : # The name of the VPN connection to activate #VPN_CONNECTION_NAME = "Connexion VPN 1" # or the uuid of the VPN connection to activate #VPN_CONNECTION_UUID = "fabf8915-bb27-4634-94e6-04c65261a73e" if len(sys.argv) > 1: vpn_argument = sys.argv[1] VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None if (vpn_argument[:5] == "UUID="): VPN_CONNECTION_UUID = vpn_argument[5:] print "VPN_CONNECTION_UUID=%s" % (VPN_CONNECTION_UUID) else: VPN_CONNECTION_NAME = vpn_argument print "VPN_CONNECTION_NAME=%s" % (VPN_CONNECTION_NAME) if (not VPN_CONNECTION_UUID) and (not VPN_CONNECTION_NAME): print "Usage : "+sys.argv[0]+" connexion_vpn_name" print "Liste des connexions diponibles :" print_connections_infos() sys.exit(1) vpn_connection_infos = {'vpn_connection_settings': None, 'vpn_connection_path': None} def get_vpn_connection_settings(): if VPN_CONNECTION_UUID: return get_connection_settings_by_uuid(VPN_CONNECTION_UUID) if VPN_CONNECTION_NAME: return get_connection_settings_by_name(VPN_CONNECTION_NAME) return None def get_vpn_connection_path(): if VPN_CONNECTION_UUID: return get_active_connection_path_by_uuid(VPN_CONNECTION_UUID) if VPN_CONNECTION_NAME: return get_active_connection_path_by_name(VPN_CONNECTION_NAME) return None def get_eth_active_connection_path(): try: active_connections_paths = get_active_connections_paths() active_connections_paths_count = len(active_connections_paths) if active_connections_paths_count == 0: return None return active_connections_paths[active_connections_paths_count-1] except Exception as exception: print exception return None def update_vpn_connection_settings(): vpn_connection_settings = get_vpn_connection_settings() vpn_connection_infos['vpn_connection_settings'] = vpn_connection_settings print "update_vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings) def update_vpn_connection_path(): vpn_connection_path = get_vpn_connection_path() vpn_connection_infos['vpn_connection_path'] = vpn_connection_path print "update_vpn_connection_path: vpn_connection_path=%s" % vpn_connection_path def start_connection(settings, active_connection_path): def reply_handler(opath): vpn_connection_path = opath vpn_connection_infos['vpn_connection_path'] = vpn_connection_path def error_handler(*args): print args proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') iface.ActivateConnection(get_connection_settings_type(settings), get_connection_settings_path(settings), dbus.ObjectPath("/"), active_connection_path, reply_handler=reply_handler, error_handler=error_handler) def checkVPN(): vpn_connection_settings = vpn_connection_infos['vpn_connection_settings'] # Do nothing if vpn connection settings don't exist print "checkVPN: vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings) if not vpn_connection_settings: return vpn_connection_path = vpn_connection_infos['vpn_connection_path'] # Do nothing if vpn connection already exist print "checkVPN: vpn_connection_path=%s" % vpn_connection_path if vpn_connection_path: return eth_connection_path = get_eth_active_connection_path() print "checkVPN: eth_connection_path=%s" % eth_connection_path # Do nothing if eth connection don't exist if not eth_connection_path: return start_connection(vpn_connection_settings, eth_connection_path) def handle_connection_settings_changed(): print "handle_connection_settings_changed" update_vpn_connection_settings() checkVPN() def handle_connections_changed(): print "handle_connections_changed" update_vpn_connection_path() checkVPN() def all_signal_receiver(*args, **kwargs): if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings"): handle_connection_settings_changed() if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings.Connection")\ and (kwargs['signal_name'] == "Updated"): handle_connection_settings_changed() if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManager")\ and (kwargs['signal_name'] == "PropertiesChanged")\ and args[0].has_key('ActiveConnections'): handle_connections_changed() DBusGMainLoop(set_as_default=True) dbus.SystemBus().add_signal_receiver(all_signal_receiver, interface_keyword='dbus_interface', member_keyword='signal_name') update_vpn_connection_settings() update_vpn_connection_path() checkVPN() gobject.MainLoop().run() /usr/local/bin/nm_utils.py : # coding=UTF-8 import dbus # Get connection settings from settings type and settings path # (settings type is 'org.freedesktop.NetworkManagerSystemSettings' or 'org.freedesktop.NetworkManagerUserSettings') def get_connection_settings(settings_type, settings_path): proxy = dbus.SystemBus().get_object(settings_type, settings_path) iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection') settings = iface.GetSettings() settings['settings-type'] = settings_type settings['settings-path'] = settings_path return settings # Get differents informations from connection settings def get_connection_settings_type(settings): return settings['settings-type'] def get_connection_settings_path(settings): return settings['settings-path'] def get_connection_settings_uuid(settings): return settings['connection']['uuid'] def get_connection_settings_name(settings): return settings['connection']['id'] # Get all settings paths associated to a type of settings def get_connections_settings_paths(settings_type): try: proxy = dbus.SystemBus().get_object(settings_type, '/org/freedesktop/NetworkManagerSettings') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings') return iface.ListConnections() except Exception as exception: print " !!! get_connections_settings_paths:" print exception return [] # Get all connections settings associated to a type of settings def get_connections_settings_by_type(settings_type): connections_settings = [] for settings_path in get_connections_settings_paths(settings_type): connection_settings = get_connection_settings(settings_type, settings_path) connections_settings.append(connection_settings) return connections_settings # Get all connections settings def get_all_connections_settings(): return get_connections_settings_by_type('org.freedesktop.NetworkManagerUserSettings') + \ get_connections_settings_by_type('org.freedesktop.NetworkManagerSystemSettings') # Get the esssential informations of the connection def get_connection_infos(settings): if settings: conn = settings['connection'] return "%s (type=%s, UUID=%s)" % (conn['id'], conn['type'], conn['uuid']) else: return None # Print the list of connections def print_connections_infos(): for connection_settings in get_all_connections_settings(): print get_connection_infos(connection_settings) # Get connection settings from the settings UUID def get_connection_settings_by_uuid(uuid): try: for settings in get_all_connections_settings(): if get_connection_settings_uuid(settings) == uuid: return settings except Exception as exception: print exception return None # Get connection settings from the settings UUID def get_connection_settings_by_name(name): try: for settings in get_all_connections_settings(): if get_connection_settings_name(settings) == name: return settings except Exception as exception: print exception return None # Get list of active connections paths def get_active_connections_paths(): proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') return iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') # Get connection settings from the connection path def get_connection_settings_by_connection_path(connection_path): proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', connection_path) iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') settings_type = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'ServiceName') settings_path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') return get_connection_settings(settings_type, settings_path) # Get list of active connections paths def get_active_connections_settings(): actives_connections_settings = [] for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) settings['connection-path'] = connection_path actives_connections_settings.append(settings) return actives_connections_settings # Look for connexion path in active connexions with particular uuid def get_active_connection_path_by_uuid(uuid): try: for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) if get_connection_settings_uuid(settings) == uuid: return connection_path except Exception as exception: print exception return None # Look for connexion path in active connexions with particular name def get_active_connection_path_by_name(name): try: for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) if get_connection_settings_name(settings) == name: return connection_path except Exception as exception: print exception return None Voilà, ça peut certainement être amélioré ou généralisé, mais j'espère au moins que ça pourra te dépanner. Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) En tout cas, ca en dépanne d'autres ! merci bp pour ce boulot coredump, ca marche nickel, et c'est en plus trés propre, pas grand chose à redire, si ce n'est merci ! Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Merci ElFabio pour ton soutien et content que ça puisse te servir. Une solution plus propre serait de trouver une correction au niveau du network manager ou de l'applet (est-ce que l'applet KDE marche ?). Si j'avais un peu de temps et plus d'expérience dans la rédaction d'articles, j'aurais bien fait un tuto sur l'utilisation de d-bus pour contrôler le NM, car la documentation à ce sujet est assez maigre sur le net. Voici quand même quelques liens qui m'ont été utiles : - http://doc.ubuntu-fr.org/networkmanager … e_commande - http://doc.ubuntu-fr.org/dbus - http://old.nabble.com/dbus-and-OpenVPN- … 05375.html - http://projects.gnome.org/NetworkManage … /spec.html - http://linuxfr.org/forums/15/27406.html - http://dbus.freedesktop.org/doc/dbus-py … orial.html Je recommande aussi l'interface graphique d-feet pour s'exercer à utiliser d-bus (pratique aussi pour retrouver les API des services). (Quand on veut être "listener" - à l'écoute - d'un service, la commande dbus-monitor aussi est pratique.) Et pour ceux qui voudraient piloter NM à l'aide de d-bus, voici quelques exemples de lignes de commande qui permettent de le faire : Afficher la liste des chemins des définitions des connexion selon leurs appartenances (système - disponibles pour tous les utilisateurs / personnel - propre à l'utilisateur) : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings" \ org.freedesktop.NetworkManagerSettings.ListConnections (ou --dest="org.freedesktop.NetworkManagerUserSettings") Afficher les paramètres d'une connexion selon son appartenance et connaissant son chemin dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings/0" \ org.freedesktop.NetworkManagerSettings.Connection.GetSettings (ou --dest="org.freedesktop.NetworkManagerUserSettings") Afficher la liste des chemins des connexions actives : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager" string:"ActiveConnections" Afficher une propriété d'une connexion active connaissant son chemin : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager/ActiveConnection/2" \ org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager.Connection.Active" string:"nom_de_la_propriete" "nom_de_la_propriete" est à renseigner. Par exemple, "nom_de_la_propriete" peut-être "ServiceName" ou "Connection" pour connaître l'appartenance et le chemin de la définition de la connexion. Arrêter une connection active connaissant son chemin : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.DeactivateConnection objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2" Démarrer une connexion : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerSystemSettings" objpath:"/org/freedesktop/NetworkManagerSettings/0" objpath:"/org/freedesktop/NetworkManager/Devices/0" objpath:"/" ou dans le cas d'une connection vpn : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerUserSettings" objpath:"/org/freedesktop/NetworkManagerSettings/1" objpath:"/" objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2" Le problème de cette commande est qu'il faut passer en argument de la commande le chemin du device (ethN ou rien pour le vpn) et le chemin de la connexion active dont elle dépend (si elle n'utilise pas de device). Malheureusement ces informations ne sont pas évidentes à déduire. Pour terminer voici un exemple de script utilisant ces commandes et permettant de démarrer ou d'arrêter une connexion en lui passant le nom de la connexion. Pour l'utiliser, nommer le fichier "connection-service", le rendre exécutable et placer le dans "/usr/local/bin/", puis taper : connection-service "nom_de_la_connexion" start|stop Par exemple : connection-service "Connection VPN 1" start /usr/local/bin/connection-service : #!/bin/bash ############ # SETTINGS # ############ get_connections_paths() { dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \ | grep "object path" | cut -d '"' -f2 } get_connection_settings() { dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings } get_connection_string_setting() { echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2 } get_connection_id() { get_connection_string_setting "$1" "id" } get_connection_type() { get_connection_string_setting "$1" "type" } get_device_type_by_connection_type() { echo "$1" | grep -q "ethernet" && echo 1 && return echo "$1" | grep -q "wireless" && echo 2 && return echo 0 } find_connection_path() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` [ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path" done } find_connection_path_everywhere() { find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1" find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1" } print_connections_ids() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } print_connections_ids_everywhere() { print_connections_ids "org.freedesktop.NetworkManagerSystemSettings" print_connections_ids "org.freedesktop.NetworkManagerUserSettings" } ########### # DEVICES # ########### get_devices_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \ | grep "object path" | cut -d '"' -f2 } get_device_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \ | grep variant | awk '{print $3}' } get_device_type() { get_device_property "$1" "DeviceType" } get_device_path_by_device_type() { device_path_by_device_type="/" for device_path in `get_devices_paths` do device_type=`get_device_type "$device_path"` [ "$device_type" = "$1" ] && device_path_by_device_type="$device_path" done echo "$device_path_by_device_type" } ####################### # ACTIVES CONNECTIONS # ####################### get_actives_connections_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \ | grep "object path" | cut -d '"' -f2 } get_last_active_connection_path() { get_actives_connections_paths | tail -n 1 } get_parent_connection_path_by_device_type() { parent_connection_path="/" [ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path` echo "$parent_connection_path" } get_active_connection_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \ | grep variant | awk -F '"' '{print $2}' } get_active_connection_service() { get_active_connection_property "$1" "ServiceName" } get_active_connection_path() { get_active_connection_property "$1" "Connection" } get_active_connection_path_by_connection_path() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` [ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path" done } print_actives_connections_ids() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` connection_settings=`get_connection_settings "$service" "$path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } ############## # START/STOP # ############## start_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_connection_settings=`get_connection_settings $my_connection_complete_path` my_connection_type=`get_connection_type "$my_connection_settings"` my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"` my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'` my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'` my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"` my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"` echo "connection_service=$my_connection_service" echo "connection_path=$my_connection_path" echo "connection_device_path=$my_connection_device_path" echo "parent_connection_path=$my_parent_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path" } stop_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path` echo "active_connection_path=$my_active_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path" } ######## # MAIN # ######## invalid_arguments() { echo "Usage: `basename "$0"` connexion_name start|stop" echo "Connexion disponibles:" print_connections_ids_everywhere echo "Connexion actives:" print_actives_connections_ids exit 0 } [ "$#" != 2 ] && invalid_arguments case "$2" in "start") start_connection "$1" ;; "stop") stop_connection "$1" ;; "restart") stop_connection "$1" start_connection "$1" ;; "status") if print_actives_connections_ids | grep -q -x "$1" then echo "Connexion \"$1\" active" exit 0 else echo "Connexion \"$1\" inactive" exit 1 fi ;; *) invalid_arguments ;; esac Dernière modification par coredump (Le 28/01/2010, à 13:21) Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) effectivement, tu as bien potassé ton d-bus ! et de rien pour le soutien, c'est le moins que je puisse faire, surtout que j'utilise maintenant ton script tous les jours ! vraiment exactement ce que je recherchais ! Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Par les temps qui courent, il vaut mieux surfer bien couvert Hors ligne Brunod Re : Connexion VPN automatique (NetworkManager) Salut, Je te félicite anticipativement parce que là, en congé, je n'en ai pas besoin; mais à la rentrée, faudra que je me penche dessus ! Merci ! Wanted : >>> un emploi dans la sécurité informatique et réseau <<< Windows est un système d'exploitation de l'homme par l'ordinateur. Linux, c'est le contraire ... --> état de la conversion : 36 pc linux Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) À noter, que le script "connection-service" défini dans mon post #11 ci-dessus peut aussi être utilisé pour connecter automatiquement le VPN. Pour cela, créer un script "vpn-autostart" exécutable dans "/usr/local/bin/", /usr/local/bin/vpn-autostart : #!/bin/bash # Délai de 10 secondes pour laisser le temps à nm-applet de démarrer sleep 10 && connection-service "Connection VPN 1" start Ajouter ensuite un programme "VPN" dans la liste des "Applications au démarrage" avec comme commande : vpn-autostart Ceci démarrera la connexion "Connection VPN 1" à l'ouverture de la session. Et pour reconnecter automatiquement la connexion en cas de coupure, ajouter ce script "02-loop-vpn" exécutable dans "/etc/NetworkManager/dispatcher.d/": /etc/NetworkManager/dispatcher.d/02-loop-vpn : #!/bin/bash [ "$2" = "vpn-down" ] && vpn-autostart Et voilà ! Hors ligne lynn Re : Connexion VPN automatique (NetworkManager) Bonjour, Merci à toi coredump pour ces scripts de connection automatique pour VPN. Ils fonctionnent parfaitement Comme tu le dis si bien : - quand on coche "Connecter automatiquement", ceci n'est pas pris en compte - quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs) A quand un Network Manager complètement fonctionnel ? Parce que c'est vrai que ce genre de "détails" est quand même bien ch...t. En attendant, merci encore coredump et je pense que ce post va intéresser pas mal de monde .....:P Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Merci encore une fois coredump pour ce tutoriel trés pratique et directement utilisable, j'en profite pour abuser un peu de tes compétences pour te poser une question concernant l'usage de tes scripts (j'utilise en particulier checkVPN) : aprés maintenant plusieurs jours d'utilisation, je remarque qu'au fur et à mesure de mes reconnexions automatique à mon provider VPN (lors d'une déconnexion), le débit global des téléchargements (dans mon client torrent préféré...) a tendance à se contracter fortement (divisé par 2 ou 3), et un simple redémarrage du PC permet de revenir à un débit normal. Pour info je me connecte en WiFi, et peut être n'est ce pas du à l'utilisation de tes scripts, mais est ce que ca ne pourrait pas venir d'un "engorgement" de process qui s'accumulent en taches de fond suite à de multiples déconnexion/reconnexion VPN, je ne pense pas trop parce qu'en faisant un ps aux je n'en trouve pas trace et qu'en plus ton script me parait vraiment trés propre, mais je n'ai pas d'explications plausibles... est ce que tu aurais déjà rencontré le même genre de soucis ou aurais tu une idée de leur origine ? Je te souhaite une trés bonne année, Hors ligne rogerjm Re : Connexion VPN automatique (NetworkManager) Bravo coredump pour ce post (qui n'est pas loin d'être un article ). Tout ce que tu y as décrit m'a été très utile pour configurer mon VPN et le lancer automatiquement, mais aussi m'a appris plein de choses. Bonne année Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Bonne année à tous ! Au sujet de ton problème, ElFabio, je ne pense pas pouvoir t'aider beaucoup. À vue de nez, voici mes impressions : - Concernant le script de reconnexion, ça m'étonnerait qu'il puisse provoquer un "engorgement". La plupart du temps il est au repos (en attente d'évènements) et quand il bosse, il ne fait jamais que quelques petites opérations. Le seul petit souci que je verrais, serait le délai de reconnexion. En cas de coupure, il cherche instantanément à se reconnecter et ce n'est peut-être pas très bon. J'ai remarqué qu'en cas de coupure, la reconnexion ne se fait pas toujours à la première tentative. Le fait d'envoyer des requêtes de reconnexion aussi proches n'est peut-être pas très bon. En même temps, une fois qu'il s'est reconnecté, je n'ai pas observé pour ma part de diminution de la bande passante. Mais, si tu veux chercher dans cette voie, tu peux essayer avec l'autre méthode (elle n'utilise pas de process en fond de tâche) et jouer sur le délai de reconnection. Les autres pistes pourraient venir à mon avis de la connexion Wifi, du client torrent ou du service VPN : - Pour la connexion Wifi, j'ai entendu dire que le peer-to-peer n'est pas très bon. J'ai eu à une époque un fournisseur internet wifi qui interdisait de faire du peer-to-peer sur son réseau (sinon ça le faisait planter). De cette époque, j'ai pris l'habitude de faire du warez, je n'utilise les torrents que de façon ponctuel, donc je n'ai pas trop d'expérience à ce sujet. Tout ce que je peux te dire, c'est que je ne rencontre pas ce problème avec les boards warez et JDownloader. Pour explorer cette piste, il faudrait que tu es la possibilité de tester la différence avec une connexion filaire, ou consulter les forums sur les torrents et le Wifi. - Pour le client torrent, peut-être que le fait d'avoir des coupures le perturbe. Une possibilité pourrait être de le relancer quand tu observes une diminution de débit et voir si ça change quelque chose. Ou voir si tu observes aussi sur cette baisse de débit sur un test de bande passante (avec speedtest.net, par exemple). - Le fournisseur VPN peut-être aussi offre de moins bon service au bout d'une certaine durée de connexion. Là, si tu as la possibilité d'essayer une autre connexion VPN pour voir la différence. Ou provoquer volontairement les coupures VPN depuis l'applet du Network Manager pour voir si ce sont bien les coupures qui font baisser le débit. En gros, essaye de voir, et si c'est possible, si ton problème persiste : - sans vpn (mais ça, tu le sais surement déjà) - ou avec une connexion réseau filaire - ou en redémarrant le client torrent - ou en redémarrant le Network Manager (sudo service network-manager restart, NetworkManager pour les versions d'ubuntu plus anciennes) - ou en espaçant les délais entre les reconnections - ou avec un autre fournisseur VPN (personnellement, j'utilise HideMyNet, un peu payant) ça t'aidera peut-être mieux à localiser ton problème qu'en redémarrant le pc. Bonne chance ! Dernière modification par coredump (Le 02/01/2010, à 12:14) Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Déjà je te remercie pour avoir pris autant de temps pour me répondre, je vais essayer de reparcourir les pistes que tu as mentionné mais, effectivement, ce sont également sensiblement les mêmes que celles que j'avais regardé jusque-là. Mes premieres impresssions tendraient à confirmer les tiennes, le probléme semblerait effectivement provenir davantage de la connexion en Wifi, puisque j'utilise également tes scripts sur un PC fixe en ethernet avec le même provider VPN, et je ne rencontre pas ce genre de problème. J'avais déjà éliminé la piste du provider VPN dont je suis personnellement trés satisfait (il s'agit de TorrentFreedom), et d'ailleurs le fait qu'en redémarrant le PC je retrouve un débit normal tend également à confirmer que le pb ne vient pas de là. D'ailleurs je n'ai pas, comme tu le mentionnes pour toi, de problémes de connexion particulier au VPN, la connexion se fait trés rapidement, par contre, en revanche, il se produit des déconnexions au VPN de façon trés régulière voire périodique (presque toutes les 30mn), ce qui me fait également pencher vers un probléme WiFi ou plutôt de passerelle (Livebox dans mon cas actuel) voire de FAI... Je vais par contre également regarder du côté de ton 2eme script pour voir si j'observe des changements. En tout cas, merci pour ton temps et ta réponse, ca me permet de disposer d'un 2eme avis "éclairé" sur le sujet ! Hors ligne hybernatus Re : Connexion VPN automatique (NetworkManager) Fiou... merci pour ce script et tout ton boulot, je me suis abonné hier à Ipredator (ayant trouvé un super tuto, et n'y connaissant rien en réseaux, j'ai fait au plus simple ^^ ) et j'ai remarqué qu'il se déconnecte de temps en temps... ce qui est un peu c*n tout de même quand on veut une connexion sécurisée et anonyme je trouve J'essairai d'appliquer ça dès que je trouve la motiv merci ! Mes photos: http://www.hyb.me/photos Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Salut coredump, je reviens juste vers toi pour te faire un petit debriefing : ta deuxiéme solution (via connection-service) a résolu mes problémes de "coupure" intempestive et réguliére du VPN, je l'ai un peu aménagé à ma sauce, notamment pour disposer d'une connexion 'manuelle' au VPN et non un lancement automatique au démarrage, mais, que ce soit en Wi-Fi ou en Ethernet, cela fonctionne maintenant parfaitement. Donc encore merci pour ton travail, et bonne continuation ! Hors ligne Papou Re : Connexion VPN automatique (NetworkManager) Merci Coredump pour ces scripts très utiles. La reconnection automatique c'est nickel .... sauf quand c'est le modem qui décroche de l'ADSL et met un peu de temps pour redémarrer, la reconnection au VPN n'aboutit alors pas et l'accès internet se retrouve en direct quelques secondes plus tard. Serait-il possible de faire encore mieux ? Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ... Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Tout d'abord merci ElFabio pour ton retour d'expérience. A mon avis : - la première solution (en python) est plus fiable, car le service tourne en tâche de fond et ne dépend pas de la connexion de l'utilisateur, mais plus complexe et donc plus difficile à maintenir, - la deuxième (en shell) est plus simple et plus clair, et donc plus adaptable et plus facile à maintenir, et par expérience marche bien. Et en définitif, je conseillerai donc plutôt celle-ci. Pour rappel, cette méthode est décrite dans le post #15 avec le script "connection-service" de la fin du poste #11. (Si je trouve un peut de temps, j'en ferais bien la synthèse dans un tuto ...) Ensuite par rapport à Papou, si tu veux que le vpn se reconnecte quand ta connexion adsl se reconnecte (j'imagine que tu utilises la deuxième méthode et qu'il ne s'agit pas d'une connexion adsl pppoe ?), tu peux essayer d'ajouter cette ligne dans le script /etc/NetworkManager/dispatcher.d/02-loop-vpn : [ "$2" = "up" ] && vpn-autostart (Pour voir si ça marche, tu peux essayer en redémarrant à la main ton modem en cours de connexion.) Dernière modification par coredump (Le 18/01/2010, à 15:45) Hors ligne Papou Re : Connexion VPN automatique (NetworkManager) coredump, Merci pour ta réponse. j'utilise la deuxième méthode et il s'agit d'une connexion adsl pppoe. L'inconvénient d'ajouter la ligne "[ "$2" = "up" ] && vpn-autostart" est qu'il devient alors impossible de déconnecter volontairement le VPN pour les applications qui ne le supporte pas (sauf a écrire un script de déconnexion volontaire qui va déplacer le fichier 02-loop-vpn en dehors de dispatcher). D'autre part, il me semble avoir remarqué que le problème est que la connection VPN échoue parfois (timeout d'environ 10 sec ? ) et qu'il n'y a alors pas de deuxième essai. Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ... Hors ligne
I want to tell inherited methods apart from overloaded or newly defined methods. Is that possible with Python? Example: class A(object): def spam(self): print 'A spam' def ham(self): print 'A ham' class B(A): def spam(self): print 'Overloaded spam' def eggs(self): print 'Newly defined eggs' Desired functionality: >>> magicmethod(B.spam) 'overloaded' >>> magicmethod(B.ham) 'inherited' >>> magicmethod(B.eggs) 'newly defined' Is there a "magic method" like in the example, or some way to tell those types of method implementations apart?
You are here: Home ‣ Dive Into Python 3 ‣ Difficulty level: ♦♦♦♦♢ ❝ You’ll find the shame is like the pain; you only feel it once. ❞ — Marquise de Merteuil, Dangerous Liaisons Real artists ship. Or so says Steve Jobs. Do you want to release a Python script, library, framework, or application? Excellent. The world needs more Python code. Python 3 comes with a packaging framework called Distutils. Distutils is many things: a build tool (for you), an installation tool (for your users), a package metadata format (for search engines), and more. It integrates with the Python Package Index (“PyPI”), a central repository for open source Python libraries. All of these facets of Distutils center around the setup script, traditionally called setup.py. In fact, you’ve already seen several Distutils setup scripts in this book. You used Distutils to install httplib2 in HTTP Web Services and again to install chardet in Case Study: Porting chardet to Python 3. In this chapter, you’ll learn how the setup scripts for chardet and httplib2 work, and you’ll step through the process of releasing your own Python software. # chardet's setup.py from distutils.core import setup setup( name = "chardet", packages = ["chardet"], version = "1.0.2", description = "Universal encoding detector", author = "Mark Pilgrim", author_email = "mark@diveintomark.org", url = "http://chardet.feedparser.org/", download_url = "http://chardet.feedparser.org/download/python3-chardet-1.0.1.tgz", keywords = ["encoding", "i18n", "xml"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic", ], long_description = """\ Universal character encoding detector ------------------------------------- Detects - ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants) - Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese) - EUC-JP, SHIFT_JIS, ISO-2022-JP (Japanese) - EUC-KR, ISO-2022-KR (Korean) - KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic) - ISO-8859-2, windows-1250 (Hungarian) - ISO-8859-5, windows-1251 (Bulgarian) - windows-1252 (English) - ISO-8859-7, windows-1253 (Greek) - ISO-8859-8, windows-1255 (Visual and Logical Hebrew) - TIS-620 (Thai) This version requires Python 3 or later; a Python 2 version is available separately. """ ) ☞ chardetandhttplib2are open source, but there’s no requirement that you release your own Python libraries under any particular license. The process described in this chapter will work for any Python software, regardless of license. ⁂ Releasing your first Python package is a daunting process. (Releasing your second one is a little easier.) Distutils tries to automate as much of it as possible, but there are some things you simply must do yourself. ⁂ To start packaging your Python software, you need to get your files and directories in order. The httplib2 directory looks like this: httplib2/ ① | +--README.txt ② | +--setup.py ③ | +--httplib2/ ④ | +--__init__.py | +--iri2uri.py .txt extension, and it should use Windows-style carriage returns. Just because setup.py unless you have a good reason not to. You do not have a good reason not to..py file, you should put it in the root directory along with your “read me” file and your setup script. But httplib2 is not a single .py file; it’s a multi-file module. But that’s OK! Just put the httplib2 directory in the root directory, so you have an __init__.py file within an httplib2/ directory within the httplib2/ root directory. That’s not a problem; in fact, it will simplify your packaging process. The chardet directory looks slightly different. Like httplib2, it’s a multi-file module, so there’s a chardet/ directory within the chardet/ root directory. In addition to the README.txt file, chardet has HTML-formatted documentation in the docs/ directory. The docs/ directory contains several .html and .css files and an images/ subdirectory, which contains several .png and .gif files. (This will be important later.) Also, in keeping with the convention for (L)GPL-licensed software, it has a separate file called COPYING.txt which contains the complete text of the LGPL. chardet/|+--COPYING.txt|+--setup.py|+--README.txt|+--docs/| || +--index.html| || +--usage.html| || +--images/ ...|+--chardet/ | +--__init__.py | +--big5freq.py | +--... ⁂ The Distutils setup script is a Python script. In theory, it can do anything Python can do. In practice, it should do as little as possible, in as standard a way as possible. Setup scripts should be boring. The more exotic your installation process is, the more exotic your bug reports will be. The first line of every Distutils setup script is always the same: from distutils.core import setup This imports the setup() function, which is the main entry point into Distutils. 95% of all Distutils setup scripts consist of a single call to setup() and nothing else. (I totally just made up that statistic, but if your Distutils setup script is doing more than calling the Distutils setup() function, you should have a good reason. Do you have a good reason? I didn’t think so.) The setup() function can take dozens of parameters. For the sanity of everyone involved, you must use named arguments for every parameter. This is not merely a convention; it’s a hard requirement. Your setup script will crash if you try to call the setup() function with non-named arguments. The following named arguments are required: Although not required, I recommend that you also include the following in your setup script: ☞Setup script metadata is defined in PEP 314. Now let’s look at the chardet setup script. It has all of these required and recommended parameters, plus one I haven’t mentioned yet: packages. from distutils.core import setup setup( name = 'chardet', packages = ['chardet'], version = '1.0.2', description = 'Universal encoding detector', author='Mark Pilgrim', ... ) The packages parameter highlights an unfortunate vocabulary overlap in the distribution process. We’ve been talking about the “package” as the thing you’re building (and potentially listing in The Python “Package” Index). But that’s not what this packages parameter refers to. It refers to the fact that the chardet module is a multi-file module, sometimes known as… a “package.” The packages parameter tells Distutils to include the chardet/ directory, its __init__.py file, and all the other .py files that constitute the chardet module. That’s kind of important; all this happy talk about documentation and metadata is irrelevant if you forget to include the actual code! ⁂ The Python Package Index (“PyPI”) contains thousands of Python libraries. Proper classification metadata will allow people to find yours more easily. PyPI lets you browse packages by classifier. You can even select multiple classifiers to narrow your search. Classifiers are not invisible metadata that you can just ignore! To classify your software, pass a classifiers parameter to the Distutils setup() function. The classifiers parameter is a list of strings. These strings are not freeform. All classifier strings should come from this list on PyPI. Classifiers are optional. You can write a Distutils setup script without any classifiers at all. Don’t do that. You should always include at least these classifiers: "Programming Language :: Python" and "Programming Language :: Python :: 3". If you do not include these, your package will not show up in this list of Python 3-compatible libraries, which linked from the sidebar of every single page of pypi.python.org."Operating System :: OS Independent". Multiple Operating System classifiers are only necessary if your software requires specific support for each platform. (This is not common.) I also recommend that you include the following classifiers: Developers, End Users/Desktop, Science/Research, and System Administrators.Framework classifier. If not, omit it. By way of example, here are the classifiers for Django, a production-ready, cross-platform, BSD-licensed web application framework that runs on your web server. (Django is not yet compatible with Python 3, so the Programming Language :: Python :: 3 classifier is not listed.) Programming Language :: Python License :: OSI Approved :: BSD License Operating System :: OS Independent Development Status :: 5 - Production/Stable Environment :: Web Environment Framework :: Django Intended Audience :: Developers Topic :: Internet :: WWW/HTTP Topic :: Internet :: WWW/HTTP :: Dynamic Content Topic :: Internet :: WWW/HTTP :: WSGI Topic :: Software Development :: Libraries :: Python Modules Here are the classifiers for chardet, the character encoding detection library covered in Case Study: Porting chardet to Python 3. chardet is beta quality, cross-platform, Python 3-compatible, LGPL-licensed, and intended for developers to integrate into their own products. Programming Language :: Python Programming Language :: Python :: 3 License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Operating System :: OS Independent Development Status :: 4 - Beta Environment :: Other Environment Intended Audience :: Developers Topic :: Text Processing :: Linguistic Topic :: Software Development :: Libraries :: Python Modules And here are the classifiers for httplib2, the library featured in the HTTP Web Services chapter. httplib2 is beta quality, cross-platform, MIT-licensed, and intended for Python developers. Programming Language :: Python Programming Language :: Python :: 3 License :: OSI Approved :: MIT License Operating System :: OS Independent Development Status :: 4 - Beta Environment :: Web Environment Intended Audience :: Developers Topic :: Internet :: WWW/HTTP Topic :: Software Development :: Libraries :: Python Modules By default, Distutils will include the following files in your release package: README.txtsetup.py.py files needed by the multi-file modules listed in the packages parameter.py files listed in the py_modules parameter That will cover all the files in the httplib2 project. But for the chardet project, we also want to include the COPYING.txt license file and the entire docs/ directory that contains images and HTML files. To tell Distutils to include these additional files and directories when it builds the chardet release package, you need a manifest file. A manifest file is a text file called MANIFEST.in. Place it in the project’s root directory, next to README.txt and setup.py. Manifest files are not Python scripts; they are text files that contain a series of “commands” in a Distutils-defined format. Manifest commands allow you to include or exclude specific files and directories. This is the entire manifest file for the chardet project: include COPYING.txt ① recursive-include docs *.html *.css *.png *.gif ② COPYING.txt file from the project’s root directory.recursive-include command takes a directory name and one or more filenames. The filenames aren’t limited to specific files; they can include wildcards. This line means “See that docs/ directory in the project’s root directory? Look in there (recursively) for .html, .css, .png, and .gif files. I want all of them in my release package.” All manifest commands preserve the directory structure that you set up in your project directory. That recursive-include command is not going to put a bunch of .html and .png files in the root directory of the release package. It’s going to maintain the existing docs/ directory structure, but only include those files inside that directory that match the given wildcards. (I didn’t mention it earlier, but the chardet documentation is actually written in XML and converted to HTML by a separate script. I don’t want to include the XML files in the release package, just the HTML and the images.) ☞Manifest files have their own unique format. See Specifying the files to distribute and the manifest template commands for details. To reiterate: you only need to create a manifest file if you want to include files that Distutils doesn’t include by default. If you do need a manifest file, it should only include the files and directories that Distutils wouldn’t otherwise find on its own. There’s a lot to keep track of. Distutils comes with a built-in validation command that checks that all the required metadata is present in your setup script. For example, if you forget to include the version parameter, Distutils will remind you. c:\Users\pilgrim\chardet>c:\python31\python.exe setup.py checkrunning check warning: check: missing required meta-data: version Once you include a version parameter (and all the other required bits of metadata), the check command will look like this: c:\Users\pilgrim\chardet>c:\python31\python.exe setup.py checkrunning check ⁂ Distutils supports building multiple types of release packages. At a minimum, you should build a “source distribution” that contains your source code, your Distutils setup script, your “read me” file, and whatever additional files you want to include. To build a source distribution, pass the sdist command to your Distutils setup script. c:\Users\pilgrim\chardet>c:\python31\python.exe setup.py sdistrunning sdist running check reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' creating chardet-1.0.2 creating chardet-1.0.2\chardet creating chardet-1.0.2\docs creating chardet-1.0.2\docs\images copying files to chardet-1.0.2... copying COPYING -> chardet-1.0.2 copying README.txt -> chardet-1.0.2 copying setup.py -> chardet-1.0.2 copying chardet\__init__.py -> chardet-1.0.2\chardet copying chardet\big5freq.py -> chardet-1.0.2\chardet ... copying chardet\universaldetector.py -> chardet-1.0.2\chardet copying chardet\utf8prober.py -> chardet-1.0.2\chardet copying docs\faq.html -> chardet-1.0.2\docs copying docs\history.html -> chardet-1.0.2\docs copying docs\how-it-works.html -> chardet-1.0.2\docs copying docs\index.html -> chardet-1.0.2\docs copying docs\license.html -> chardet-1.0.2\docs copying docs\supported-encodings.html -> chardet-1.0.2\docs copying docs\usage.html -> chardet-1.0.2\docs copying docs\images\caution.png -> chardet-1.0.2\docs\images copying docs\images\important.png -> chardet-1.0.2\docs\images copying docs\images\note.png -> chardet-1.0.2\docs\images copying docs\images\permalink.gif -> chardet-1.0.2\docs\images copying docs\images\tip.png -> chardet-1.0.2\docs\images copying docs\images\warning.png -> chardet-1.0.2\docs\images creating dist creating 'dist\chardet-1.0.2.zip' and adding 'chardet-1.0.2' to it adding 'chardet-1.0.2\COPYING' adding 'chardet-1.0.2\PKG-INFO' adding 'chardet-1.0.2\README.txt' adding 'chardet-1.0.2\setup.py' adding 'chardet-1.0.2\chardet\big5freq.py' adding 'chardet-1.0.2\chardet\big5prober.py' ... adding 'chardet-1.0.2\chardet\universaldetector.py' adding 'chardet-1.0.2\chardet\utf8prober.py' adding 'chardet-1.0.2\chardet\__init__.py' adding 'chardet-1.0.2\docs\faq.html' adding 'chardet-1.0.2\docs\history.html' adding 'chardet-1.0.2\docs\how-it-works.html' adding 'chardet-1.0.2\docs\index.html' adding 'chardet-1.0.2\docs\license.html' adding 'chardet-1.0.2\docs\supported-encodings.html' adding 'chardet-1.0.2\docs\usage.html' adding 'chardet-1.0.2\docs\images\caution.png' adding 'chardet-1.0.2\docs\images\important.png' adding 'chardet-1.0.2\docs\images\note.png' adding 'chardet-1.0.2\docs\images\permalink.gif' adding 'chardet-1.0.2\docs\images\tip.png' adding 'chardet-1.0.2\docs\images\warning.png' removing 'chardet-1.0.2' (and everything under it) Several things to note here: MANIFEST.in).COPYING.txt and the HTML and image files in the docs/ directory.dist/ directory. Within the dist/ directory the .zip file that you can distribute. c:\Users\pilgrim\chardet>dir distVolume in drive C has no label. Volume Serial Number is DED5-B4F8 Directory of c:\Users\pilgrim\chardet\dist 07/30/2009 06:29 PM <DIR> . 07/30/2009 06:29 PM <DIR> .. 07/30/2009 06:29 PM 206,440 chardet-1.0.2.zip 1 File(s) 206,440 bytes 2 Dir(s) 61,424,635,904 bytes free ⁂ In my opinion, every Python library deserves a graphical installer for Windows users. It’s easy to make (even if you don’t run Windows yourself), and Windows users appreciate it. Distutils can create a graphical Windows installer for you, by passing the bdist_wininst command to your Distutils setup script. c:\Users\pilgrim\chardet>c:\python31\python.exe setup.py bdist_wininstrunning bdist_wininst running build running build_py creating build creating build\lib creating build\lib\chardet copying chardet\big5freq.py -> build\lib\chardet copying chardet\big5prober.py -> build\lib\chardet ... copying chardet\universaldetector.py -> build\lib\chardet copying chardet\utf8prober.py -> build\lib\chardet copying chardet\__init__.py -> build\lib\chardet installing to build\bdist.win32\wininst running install_lib creating build\bdist.win32 creating build\bdist.win32\wininst creating build\bdist.win32\wininst\PURELIB creating build\bdist.win32\wininst\PURELIB\chardet copying build\lib\chardet\big5freq.py -> build\bdist.win32\wininst\PURELIB\chardet copying build\lib\chardet\big5prober.py -> build\bdist.win32\wininst\PURELIB\chardet ... copying build\lib\chardet\universaldetector.py -> build\bdist.win32\wininst\PURELIB\chardet copying build\lib\chardet\utf8prober.py -> build\bdist.win32\wininst\PURELIB\chardet copying build\lib\chardet\__init__.py -> build\bdist.win32\wininst\PURELIB\chardet running install_egg_info Writing build\bdist.win32\wininst\PURELIB\chardet-1.0.2-py3.1.egg-info creating 'c:\users\pilgrim\appdata\local\temp\tmp2f4h7e.zip' and adding '.' to it adding 'PURELIB\chardet-1.0.2-py3.1.egg-info' adding 'PURELIB\chardet\big5freq.py' adding 'PURELIB\chardet\big5prober.py' ... adding 'PURELIB\chardet\universaldetector.py' adding 'PURELIB\chardet\utf8prober.py' adding 'PURELIB\chardet\__init__.py' removing 'build\bdist.win32\wininst' (and everything under it)c:\Users\pilgrim\chardet>dir distc:\Users\pilgrim\chardet>dir dist Volume in drive C has no label. Volume Serial Number is AADE-E29F Directory of c:\Users\pilgrim\chardet\dist 07/30/2009 10:14 PM <DIR> . 07/30/2009 10:14 PM <DIR> .. 07/30/2009 10:14 PM 371,236 chardet-1.0.2.win32.exe 07/30/2009 06:29 PM 206,440 chardet-1.0.2.zip 2 File(s) 577,676 bytes 2 Dir(s) 61,424,070,656 bytes free Distutils can help you build installable packages for Linux users. In my opinion, this probably isn’t worth your time. If you want your software distributed for Linux, your time would be better spent working with community members who specialize in packaging software for major Linux distributions. For example, my chardet library is in the Debian GNU/Linux repositories (and therefore in the Ubuntu repositories as well). I had nothing to do with this; the packages just showed up there one day. The Debian community has their own policies for packaging Python libraries, and the Debian python-chardet package is designed to follow these conventions. And since the package lives in Debian’s repositories, Debian users will receive security updates and/or new versions, depending on the system-wide settings they’ve chosen to manage their own computers. The Linux packages that Distutils builds offer none of these advantages. Your time is better spent elsewhere. ⁂ Uploading software to the Python Package Index is a three step process. setup.py sdist and setup.py bdist_* To register yourself, go to the PyPI user registration page. Enter your desired username and password, provide a valid email address, and click the Register button. (If you have a PGP or GPG key, you can also provide that. If you don’t have one or don’t know what that means, don’t worry about it.) Check your email; within a few minutes, you should receive a message from PyPI with a validation link. Click the link to complete the registration process. Now you need to register your software with PyPI and upload it. You can do this all in one step. c:\Users\pilgrim\chardet>c:\python31\python.exe setup.py register sdist bdist_wininst upload①running register We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quitYour selection [default 1]:1②Username:MarkPilgrim③Password:Registering chardet to http://pypi.python.org/pypi④Server response (200): OKrunning sdist⑤... output trimmed for brevity ...running bdist_wininst⑥... output trimmed for brevity ...running upload⑦Submitting dist\chardet-1.0.2.zip to http://pypi.python.org/pypi Server response (200): OK Submitting dist\chardet-1.0.2.win32.exe to http://pypi.python.org/pypi Server response (200): OK I can store your PyPI login so future submissions will be faster. (the login will be stored in c:\home\.pypirc)Save your login (y/N)?n⑧ setup.py parameters. Next, it builds a source distribution (sdist) and a Windows installer (bdist_wininst), then uploads them to PyPI (upload). Congratulations, you now have your own page on the Python Package Index! The address is http://pypi.python.org/pypi/, where NAMENAME is the string you passed in the name parameter in your setup.py file. If you want to release a new version, just update your setup.py with the new version number, then run the same upload command again: c:\Users\pilgrim\chardet>c:\python31\python.exe setup.py register sdist bdist_wininst upload ⁂ Distutils is not the be-all and end-all of Python packaging, but as of this writing (August 2009), it’s the only packaging framework that works in Python 3. There are a number of other frameworks for Python 2; some focus on installation, others on testing and deployment. Some or all of these may end up being ported to Python 3 in the future. These frameworks focus on installation: These focus on testing and deployment: ⁂ On Distutils: setup() functionsite-packages directory On other packaging frameworks: ☜ ☞ © 2001–11 Mark Pilgrim
Here's a script to show a summary of La Liga. Save it somewhere (such as Documents/laliga.py). Use the command "python /Users/xxxx/Documents/laliga.py" to run it. #!/usr/bin/python import urllib2 from xml.dom.minidom import parseString hometeam="Barcelona" # Replace this with your team url="http://www.footbo.com/widgets/xml/LeagueTable.aspx?id=193770" file = urllib2.urlopen(url) data = file.read() file.close() data = data.replace(hometeam, hometeam.upper()) #parse xml dom = parseString(data) print "POS CLUB PLD GD PTS" #loop through <entry> elements entry=dom.getElementsByTagName('LeagueTableRow') for node in entry: position=node.getAttribute('Position') name=node.getAttribute('TeamName') played=node.getAttribute('GamesPlayed') goalDifference=node.getAttribute('GoalsDifference') points=node.getAttribute('Points') print "%3s %-20s %3s %4s %3s" % (position, name, played, goalDifference, points)
Published on O'Reilly Network (http://www.oreillynet.com/) See this if you're having trouble printing code examples by Cameron Laird and Boudewijn Rempt 07/07/2000 Editor's note -- Seldom do I run across an article on application development that is just plain fun. I have one here. There are four characters in this story talking about the Qt authoring environment: Cameron Laird, Boudewijn Rempt, Thomas, and Paul. Cameron and Boudewijn are real life developers. Thomas and Paul are composite characters that represent real views. The discussion among them is lively and informative. Last Wednesday Thomas, a fellow hacker, came by for a visit. He's heard our praise of the Python language and Qt graphical user interface (GUI) toolkit. Thomas, though, is a doubter, one who needs to see for himself. He arrived with a demand to be shown "what all the fuss is about." So we did: Thomas: Well, I'm a Windows developer mainly. That's where the money is, isn't it? Why should I use a cross-platform GUI toolkit when there's a perfectly good native one, and that's MFC (Microsoft Foundation Classes). Boudewijn: True, you are a Windows developer ... for now -- you won't be one for ever. Even Nathan Myhrvold, chief technologist at Microsoft until last year, thinks that Windows will have been replaced by another system in five years time. You might want to grab the opportunity to have your app running everywhere. Cameron: That's not all. Even though MFC is native, we think we make better Windows applications with Qt than if we were using MFC. Frankly, it looks to me as though Microsoft is coming to a similar conclusion; they appear to be de-emphasizing MFC, and certainly not investing more in it. Qt's design is a strong one. Signals and slots (the "callback" mechanism in Qt) make for safer programming than MFC's hooks. Qt is savvy about Unicode from the ground up; internationalization simply works the way it should. Boudewijn: It's hard to show you a side-by-side comparison of Qt and MFC, because MFC is so thin a layer on the C foundations of Windows - Qt is C++ from the ground up. In contrast with MFC, it's very easy to create a reusable component that can work as well as a document view as in a dialog window: class complicatedWidget(QWidget): def __init__(self, *args): ... class aDialog(QDialog): def __init__(self, *args): self.layout=QGridLayout(self, 1, 1) self.widget=complicatedWidget(self, "dialog view") self.layout.addWidget(self.widget, 0, 0) ... class aWindow(QMainWindow): def __init__(self, *args): self.view=complicatedWidget(self, "main view") self.setCaption("Main Window") self.setCentralWidget(self.view) ... The only difference is that a main window has a built-in layout manager. Thomas: Hmmm. Well, maybe ... Suppose I do decide to go cross-platform; shouldn't I use Tkinter? The IDLE treeview. Boudewijn: You could. It's quite good ... But maybe just a little old-fashioned. It's simply missing several of the features I know you'll expect. If you want to use a treeview, you have to construct one yourself. Look at the IDLE (IDLE is the Tkinter development environment written in and bundled with the standard Python distribution) treeview, for example -- they're still working the bugs out of that one, and it's currently at about 500 lines of code. I will say this, though: Whatever toolkit you choose, buy Grayson's Python and Tkinter Programming. It's a delight to read, and handles all aspects of GUI design. Thomas: I've looked a bit at the market for Linux, and Gnome sounds good. So shouldn't I develop two version of my apps, one for Windows and one for Gnome? Boudewijn: You might like Gnome -- but will your users? Not everyone is drawn to the dark side of interface design. What I mean is that the Gnome people designed for looks and theme-ability before they tried to achieve stability and functionality. Standard Gnome looks cool, but not very businesslike. Cameron: I like the Gnome guys: They're imaginative and energetic. They're just not done, though. Qt is far more mature. GTK (Gnome's toolkit) copies Qt's signals and slots mechanism, but really doesn't do it as well. Thomas: What's this stuff about the license? I just read that I've got to pay an enormous amount of money for the Windows version of PyQt! That's not open source! Boudewijn: That's not entirely correct. To generate a PyQt application for Windows, you do need to buy a developers license of the main Qt library for Windows. That'll set you back $1550 USD. PyQt itself is free. In fact, if you want to distribute a compiled version of PyQt for Windows with a Qt run-time dll, there's nothing to stop you. Be the first to sell a commercial Python/Qt development environment for Windows! As for open source, you're half-right. You can't use Qt for free on Windows, but the Unix/X11 license is certified Open Source TM. Thomas: Why are we even talking about PyQt? Qt itself is starting to interest me, but PyQt is only version 0.12. That's deep alpha -- as steady as strawberry jelly! Cameron: Phil (Thompson, the originator and maintainer of PyQt) counts differently than most of us. For him, version 0.10 followed 0.9. Anyway, beyond that, he's careful with the software he puts out. You can trust PyQt. It's stable. Boudewijn: It's very, very stable. There are bugs, of course, but they are quickly fixed. In over a year of PyQt development, I've had one serious problem that took a while to fix -- and I could still work around that one. Thomas: KDE doesn't run on Windows, though, right? What's the point of using Qt then? Cameron: This takes some explanation. "KDE" means about four different things. The acronym is for "desktop environment," which is what Unix people used to call a "window manager," plus more. KDE is also an application development framework and an office application suite. KDE stuff is all built with Qt -- as the KDEers explain their decision, "It's the best toolkit for Unix." Boudewijn: It is a bit complicated. Qt itself is available both for Windows and for Unix/X11. So's PyQt. Apps written in PyQt run unmodified on both platforms, too. However, if you want nice KDE extensions, like extra-de-luxe widgets, components, or integration with the KDE desktop, you have to use a second set of bindings: PyKDE. PyKDE depends on PyQt. Cameron: ... which is fine, of course. PyKDE needs the full KDE API (application programming interface), though, so PyKDE only works where you have KDE, which means only for Unix with X11. Boudewijn: What's nice is that it's quite easy to write an app that integrates with KDE when it's available, but degrades gracefully to pure Qt if KDE isn't present. I can show you how. #!/usr/bin/env python import sys, os from qt import * try from kdecore import * from kdeui import * Application=KApplication Mainwin=KTMainWindow except ImportError: Application=QApplication MainWin=QMainWindow class MainWindow(MainWin) def __init__(self, *args): apply(MainWin.__init__,(self,)+ args) .... def main(argv): app=Application(sys.argv, "kpybrowser") appwin=MainWindow() appwin.show() return app.exec_loop() if __name__=="__main__": main(sys.argv) At this point Paul joined us. Paul has developed Unix applications for ages. He's now looking longingly at the market Linux offers. Paul: I heard what you told the youngster. Look at me: I've got an enormous amount of Motif code and experience. Why should I switch? Boudewijn: I honestly don't know. Should you switch? Do you still believe Motif has a future? When a commercial organization opens up a bit of legacy code, as the Open Group just did with Motif, or Borland with their database, I figure it's often the beginning of the end. ... It's better than keeping legacy stuff in a safe, but it's not promising. Paul, look me in the eyes and tell me truthfully: Are you still having fun developing with Motif? Maybe you owe it to yourself to have some fun. Just try Python and Qt for a small personal project. I know I never had as much fun programming as I have now with PyQt ... Paul: What interests me is Unicode. Using Unicode with Motif is a real problem -- it has been solved, more than once, but never really satisfactorily. I'm bit jealous of Thomas here, who has excellent Unicode support in Windows. Thomas: I wish! It really only works for NT. Unicode for Windows 95 is ridiculous. I don't worry about it, though. Why should I use it at all? English was good enough for Saint Paul, so seven-bit ASCII should be good enough for you, Paul. Boudewijn: Qt offers advantages for both of you. With Qt you've got full Unicode support both on Unix/X11 and on Windows 95/NT/2000. And don't think you don't need it. Even people who don't know an aigu from an umlaut now expect their applications to keep em-dash and en-dash straight, not to mention hyphens. If you do mathematics, you want all those mathematical symbols, don't you? Anyway, more and more of the world is computerizing. Do you think the Indians want to give up their devanagari script as they come online? Unicode is our best chance for a universal character set that everyone can use to exchange data. Grab that chance! I've got a nice little example of a Unicode-aware character selection window on my Web site, for example. Cameron: I'll say it again: This is an example of how Qt is more native than native toolkits. MFC might be the default choice for Windows, but it doesn't give you the consistency of features between W95 and NT that Qt does. Paul: I've got a technical question. Qt is a C++ library, right? I don't want to develop in C or C++ anymore -- it takes far too much time. So Python suits me fine. But how does PyQt handle C++'s pesky overloaded methods? Boudewijn: Just fine. Phil has written an intelligent wrapper library that handles overloaded method selection based on the types of the actual parameter values present in the function call. Within Python, you can't create overloaded methods yourself, but there's no problem using the C++ overloaded methods. Look at this bit of code, where we first create a listviewitem without a parent, and then one with a parent: ... listItemParent=QListViewItem(self, "Parent") listItemChild=QListViewItem(listitemparent,"Child") ... Cameron: Phil told me, "I always think of myself as the author of SIP." SIP is his general-purpose system for binding together C++ and Python objects. The point is, he's done a lot to make it work properly. If you're anything like us, you'll find it easier accessing Qt through Python than with C++. Paul: I've heard Qt is European. Is that right? Is it more popular in Europe than in the United States? Cameron: Qt is the product of Trolltech, which is a Norwegian company. Boudewijn: Likewise, a large amount of the KDE effort comes from Europe. The first Qt book was in German, and it has been translated into Japanese. I'm a European myself; I don't really know how popular Qt is in America, but it's pretty popular in these parts. Cameron: North Americans are relatively fonder of GTK. It's a major religious issue for some people. There are plenty of Qt users hereabouts, though. There's a little suspicion around the world that U.S. software tends to be buggier and/or pricier. What's most certain is that Qt is a good Unicode citizen, and that's a big win in many places. With Python 1.6 supporting Unicode well, it makes PyQt a very attractive combination for internationalized application development. Paul and Thomas: Well, we'll give it a try. What's the current release? Boudewijn: The latest release of PyQt/PyKDE is 0.12. The license is no longer GPL (General Public License), but similar to the X11 license. A few bugs were fixed, a few functions added. But the most important new feature is the addition of the themes.py script. Yes! Full theme-able applications written in pure Python! Who doesn't want his app to look like it's crafted from expensive teakwood ... Cameron: Before you go, I want to strongly recommend you read Trolltech's Qt documentation. It's one of the best features of the toolkit, and equally applicable if you're a PyQt developer. I think you'll like what you find. Cameron Laird is the vice president of Phaseit, Inc. and frequently writes for the O'Reilly Network and other publications. Boudewijn Rempt is a senior developer with Tryllian, a mobile agent company. He has worked with PyQt since its inception. Related Articles Qt Attracting Interest Among Application Developers Visual Design With Qt Discuss this article in the O'Reilly Network Forum. Return to the O'Reilly Network Hub. Copyright © 2009 O'Reilly Media, Inc.
AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Re, La suppression des logs se fait au démarrage de l'appli, pas du mediacenter ! (en tout cas chez moi ça marche). Pour le systray, je t'ai ajouté une petit image clicable gnome J'ai ajouté la possibilité de créer/supprimer les lanceurs depuis l'appli (il est aussi possible de le faire depuis install_lanceur.py directement.) Pour l'installation, je pense pas nécessaire de faire un script dédié, il suffit juste de coller le dossier dans médiacenter et lancer start.py (c'est à la portée de tout le monde !). Pour le full_install (ton mediacenter et mon script), pareil, suffit de coller le dossier contenant l'ensemble où l'on veut , lancer start.py, c'est tout ! J'ai modifié le module de gestion des fichiers conf, il renumerote aussi lors d'un ajout. A ce sujet, ca serait peut être bien de modifier le script perl qui gère ça dans mediacenter, pour que lui aussi renumerote correctement ? J'y connait rien en perl, mais je suis sure qu'une âme charitable sur ce forum pourrait s'y atteler (ca devrait pas être dur, 5 mn pour qql'un qui maîtrise perl ) ... c'est du pinaillage, j'avoue ! Enfin, ça c'est toi qui décide, c'est toi qui gère ta version du médiacenter Je pense que tout est OK !!! EDIT: Jai tjrs cette erreur : apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName Dans mon fichier de conf → Listen 192.168.1.20:26180 Si ca lui convient pas, pourquoi la config se mets sur cette adresse ??? Dernière modification par AnsuzPeorth (Le 10/03/2010, à 20:07) Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bon, Y a un bug que je comprends pas trop, faudra que je m'y atèle serieux.... Problème de path pour la création des lanceurs (incomprehensible !) .... C'est pas commode sous python les path ! si je lance en console, de mon n'importe où, ca fonctionne, si je lance direct ou depuis le lanceur, plus accès à cette boite de dialogue .....!!!! Je comprends po!!! Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr A y est .... (c'est vraiment spécial les path sous python, ou alors il existe une fonction que je ne connais pas..,ca doit être ça, sinon ....) Enfin, le principal, c'est que ça fonctionne ! http://gwebradio.googlecode.com/files/G … ter.tar.gz Hors ligne perolrom Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bonjour Pour le message d'erreur, c'est un message qui n'a aucun impact, je n'ai jamais regardé comment l'enlever Effectivement, la modification du fichier configure pour re-numéroter les partages serait bien mais il faudrait alors regarder si on a besoin de changer aussi cela lorsque les gens passe par le site web pour rajouter/supprimer des partages Je t'avoue que j'ai eu la flemme de regarder toute cette partie en détails (je maitrise bien php pour les page web mais un peu moins perl) Je regarde ta nouvelle version ce soir A+ Rom1 Hors ligne perolrom Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Salut! Tout semble OK, il ne me manque l'icône que tu as rajouté pour envoyer l'appli au systray. A+ Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Salut! Tout semble OK, il ne me manque l'icône que tu as rajouté pour envoyer l'appli au systray. A+ ??? Ah bon, c'est une icones systeme pourtant ! Si tu pouvais regarder si elle est chez toi ? /usr/share/icons/hicolor/16x16/apps/application-gnome.png Thx Hors ligne perolrom Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Voici ce que j'ai dans le dossier : rom1@rom1laptop:~$ ls -l /usr/share/icons/hicolor/16x16/apps/ total 596 -rw-r--r-- 1 root root 685 2009-10-05 14:07 alacarte.png -rw-r--r-- 1 root root 725 2009-10-14 21:34 bluetooth-active.png -rw-r--r-- 1 root root 725 2009-10-14 21:33 bluetooth.png -rw-r--r-- 1 root root 899 2009-10-30 11:02 brasero.png -rw-r--r-- 1 root root 692 2009-03-05 04:28 ccsm.png -rw-r--r-- 1 root root 702 2009-11-06 00:10 checkbox.png -rw-r--r-- 1 root root 645 2009-10-20 02:56 cheese.png -rw-r--r-- 1 root root 367 2009-08-24 16:17 classviewer-class.png -rw-r--r-- 1 root root 332 2009-08-24 16:17 classviewer-macro.png -rw-r--r-- 1 root root 321 2009-08-24 16:17 classviewer-member.png -rw-r--r-- 1 root root 320 2009-08-24 16:17 classviewer-method.png -rw-r--r-- 1 root root 310 2009-08-24 16:17 classviewer-namespace.png -rw-r--r-- 1 root root 287 2009-08-24 16:17 classviewer-other.png -rw-r--r-- 1 root root 355 2009-08-24 16:17 classviewer-struct.png -rw-r--r-- 1 root root 293 2009-08-24 16:17 classviewer-var.png -rw-r--r-- 1 root root 797 2009-10-29 16:59 empathy.png -rw-r--r-- 1 root root 732 2009-10-20 07:46 eog.png -rw-r--r-- 1 root root 840 2009-11-11 10:04 evince.png -rw-r--r-- 1 root root 617 2009-11-03 23:37 evolution-mail.png -rw-r--r-- 1 root root 617 2009-11-03 23:37 evolution-memos.png -rw-r--r-- 1 root root 769 2009-11-03 23:37 evolution.png -rw-r--r-- 1 root root 818 2009-11-03 23:37 evolution-tasks.png -rw-r--r-- 1 root root 856 2009-10-20 03:17 file-roller.png -rw-r--r-- 1 root root 477 2009-10-14 01:36 filezilla.png -rw-r--r-- 1 root root 1054 2009-11-06 11:26 f-spot.png -rw-r--r-- 1 root root 429 2009-12-08 13:38 gdm-xnest.png -rw-r--r-- 1 root root 866 2009-10-12 19:49 gdu-check-disk.png -rw-r--r-- 1 root root 594 2009-10-12 19:49 gdu-detach.png -rw-r--r-- 1 root root 696 2009-10-12 19:49 gdu-eject.png -rw-r--r-- 1 root root 709 2009-10-12 19:49 gdu-encrypted-lock.png -rw-r--r-- 1 root root 640 2009-10-12 19:49 gdu-encrypted-unlock.png -rw-r--r-- 1 root root 783 2009-10-12 19:49 gdu-error.png -rw-r--r-- 1 root root 730 2009-10-12 19:49 gdu-info.png -rw-r--r-- 1 root root 657 2009-10-12 19:49 gdu-mount.png -rw-r--r-- 1 root root 626 2009-10-12 19:49 gdu-raid-array.png -rw-r--r-- 1 root root 690 2009-10-12 19:49 gdu-raid-array-start.png -rw-r--r-- 1 root root 541 2009-10-12 19:49 gdu-raid-array-stop.png -rw-r--r-- 1 root root 662 2009-10-12 19:49 gdu-smart-failing.png -rw-r--r-- 1 root root 689 2009-10-12 19:49 gdu-smart-healthy.png -rw-r--r-- 1 root root 658 2009-10-12 19:49 gdu-smart-threshold.png -rw-r--r-- 1 root root 636 2009-10-12 19:49 gdu-smart-unknown.png -rw-r--r-- 1 root root 778 2009-10-12 19:49 gdu-unmountable.png -rw-r--r-- 1 root root 721 2009-10-12 19:49 gdu-unmount.png -rw-r--r-- 1 root root 757 2009-10-12 19:49 gdu-warning.png -rw-r--r-- 1 root root 830 2009-08-24 16:17 geany.png -rw-r--r-- 1 root root 765 2010-01-05 17:29 gimp.png -rw-r--r-- 1 root root 699 2009-09-22 11:26 gnome-aisleriot.png -rw-r--r-- 1 root root 855 2009-09-22 11:26 gnome-blackjack.png -rw-r--r-- 1 root root 546 2010-01-28 12:43 gnome-brightness-applet.png -rw-r--r-- 1 root root 665 2009-10-20 12:08 gnome-codec-install.png -rw-r--r-- 1 root root 743 2009-10-20 11:35 gnome-cpu-frequency-applet.png -rw-r--r-- 1 root root 613 2009-10-20 08:03 gnome-display-properties.png -rw-r--r-- 1 root root 651 2009-10-20 11:35 gnome-eyes-applet.png -rw-r--r-- 1 root root 568 2009-09-22 11:26 gnome-glchess.png -rw-r--r-- 1 root root 675 2009-09-22 11:26 gnome-glines.png -rw-r--r-- 1 root root 562 2009-09-22 11:26 gnome-gnect.png -rw-r--r-- 1 root root 749 2009-09-22 11:26 gnome-gnibbles.png -rw-r--r-- 1 root root 649 2009-09-22 11:26 gnome-gnometris.png -rw-r--r-- 1 root root 856 2009-09-22 11:26 gnome-iagno.png -rw-r--r-- 1 root root 801 2010-01-28 12:43 gnome-inhibit-applet.png -rw-r--r-- 1 root root 554 2009-09-22 11:26 gnome-klotski.png -rw-r--r-- 1 root root 598 2009-09-22 11:26 gnome-mahjongg.png -rw-r--r-- 1 root root 736 2009-09-22 11:26 gnome-mines.png -rw-r--r-- 1 root root 598 2009-09-23 13:20 gnome-nettool.png -rw-r--r-- 1 root root 824 2009-10-20 08:03 gnome-network-properties.png -rw-r--r-- 1 root root 887 2009-10-19 15:59 gnome-panel-clock.png -rw-r--r-- 1 root root 444 2009-10-19 15:59 gnome-panel-drawer.png -rw-r--r-- 1 root root 740 2009-10-19 15:59 gnome-panel-fish.png -rw-r--r-- 1 root root 711 2009-10-19 15:59 gnome-panel-force-quit.png -rw-r--r-- 1 root root 571 2009-10-19 15:59 gnome-panel-launcher.png -rw-r--r-- 1 root root 812 2009-10-19 15:59 gnome-panel-notification-area.png -rw-r--r-- 1 root root 354 2009-10-19 15:59 gnome-panel.png -rw-r--r-- 1 root root 160 2009-10-19 15:59 gnome-panel-separator.png -rw-r--r-- 1 root root 390 2009-10-19 15:59 gnome-panel-window-list.png -rw-r--r-- 1 root root 545 2009-10-19 15:59 gnome-panel-window-menu.png -rw-r--r-- 1 root root 400 2009-10-19 15:59 gnome-panel-workspace-switcher.png -rw-r--r-- 1 root root 1404 2010-01-28 12:43 gnome-power-manager.png -rw-r--r-- 1 root root 738 2010-01-28 12:43 gnome-power-statistics.png -rw-r--r-- 1 root root 864 2009-09-22 11:26 gnome-robots.png -rw-r--r-- 1 root root 876 2009-09-22 11:26 gnome-samegnome.png -rw-r--r-- 1 root root 748 2009-10-20 08:03 gnome-settings-default-applications.png -rw-r--r-- 1 root root 846 2009-10-07 18:58 gnome-sound-recorder.png -rw-r--r-- 1 root root 667 2009-10-20 11:35 gnome-sticky-notes-applet.png -rw-r--r-- 1 root root 490 2009-09-22 11:26 gnome-sudoku.png -rw-r--r-- 1 root root 641 2009-09-22 11:26 gnome-tali.png -rw-r--r-- 1 root root 838 2009-09-22 11:26 gnome-tetravex.png -rw-r--r-- 1 root root 917 2009-10-07 18:58 gnome-volume-control.png -rw-r--r-- 1 root root 26840 2009-10-07 18:58 gnome-volume-control.svg -rw-r--r-- 1 root root 782 2009-10-06 10:41 gparted.png -rw-r--r-- 1 root root 613 2009-11-05 12:37 gsd-xrandr.png -rw-r--r-- 1 root root 3479 2009-05-15 00:24 gsmartcontrol.png -rw-r--r-- 1 root root 761 2009-10-15 19:01 hook-notifier.png -rw-r--r-- 1 root root 746 2009-10-20 11:35 invest-applet.png -rw-r--r-- 1 root root 793 2008-11-24 17:08 jockey-kde.png -rw-r--r-- 1 root root 713 2008-11-24 17:08 jockey.png -rw-r--r-- 1 root root 865 2009-09-24 19:18 lpi-bug.png -rw-r--r-- 1 root root 7040 2009-09-24 19:18 lpi-bug.svg -rw-r--r-- 1 root root 981 2009-09-24 19:18 lpi-help.png -rw-r--r-- 1 root root 572 2009-09-24 19:18 lpi-translate.png -rw-r--r-- 1 root root 8019 2009-09-24 19:18 lpi-translate.svg -rw-r--r-- 1 root root 768 2009-10-12 19:49 nautilus-gdu.png -rw-r--r-- 1 root root 874 2009-11-23 12:19 nautilus.png -rw-r--r-- 1 root root 473 2009-10-15 04:48 nm-device-wired.png -rw-r--r-- 1 root root 601 2009-10-15 04:48 nm-no-connection.png -rw-r--r-- 1 root root 595 2009-10-15 04:48 nm-vpn-standalone-lock.png lrwxrwxrwx 1 root root 44 2009-11-05 08:14 nxclient-admin.png -> /usr/NX/share/icons/16x16/nxclient-admin.png lrwxrwxrwx 1 root root 46 2009-11-05 08:14 nxclient-desktop.png -> /usr/NX/share/icons/16x16/nxclient-desktop.png lrwxrwxrwx 1 root root 43 2009-11-05 08:14 nxclient-icon.png -> /usr/NX/share/icons/16x16/nxclient-icon.png lrwxrwxrwx 1 root root 45 2009-11-05 08:14 nxclient-wizard.png -> /usr/NX/share/icons/16x16/nxclient-wizard.png -rw-r--r-- 1 root root 949 2010-02-20 09:51 ooo-base.png -rw-r--r-- 1 root root 986 2010-02-20 09:51 ooo-calc.png -rw-r--r-- 1 root root 972 2010-02-20 09:51 ooo-draw.png -rw-r--r-- 1 root root 880 2010-02-20 09:51 ooo-gulls.png -rw-r--r-- 1 root root 651 2010-02-20 09:51 ooo-impress.png -rw-r--r-- 1 root root 872 2010-02-20 09:51 ooo-math.png -rw-r--r-- 1 root root 850 2010-02-20 09:51 ooo-printeradmin.png -rw-r--r-- 1 root root 947 2010-02-20 09:51 ooo-web.png -rw-r--r-- 1 root root 796 2010-02-20 09:51 ooo-writer.png -rw-r--r-- 1 root root 3618 2010-02-20 09:51 openofficeorg3-base.png -rw-r--r-- 1 root root 3629 2010-02-20 09:51 openofficeorg3-calc.png -rw-r--r-- 1 root root 3606 2010-02-20 09:51 openofficeorg3-draw.png -rw-r--r-- 1 root root 3608 2010-02-20 09:51 openofficeorg3-impress.png -rw-r--r-- 1 root root 3607 2010-02-20 09:51 openofficeorg3-math.png -rw-r--r-- 1 root root 963 2010-02-20 09:51 openofficeorg3-printeradmin.png -rw-r--r-- 1 root root 1043 2010-02-20 09:51 openofficeorg3-startcenter.png -rw-r--r-- 1 root root 3586 2010-02-20 09:51 openofficeorg3-writer.png -rw-r--r-- 1 root root 685 2009-10-20 05:33 orca.png -rw-r--r-- 1 root root 678 2009-10-12 19:49 palimpsest.png -rw-r--r-- 1 root root 878 2009-05-23 05:49 qutecom.png -rw-r--r-- 1 root root 898 2009-10-15 19:01 reboot-notifier.png -rw-r--r-- 1 root root 745 2010-01-16 17:32 rhythmbox.png -rw-r--r-- 1 root root 773 2009-10-19 12:21 seahorse.png -rw-r--r-- 1 root root 1005 2009-10-19 12:21 seahorse-preferences.png -rw-r--r-- 1 root root 595 2009-10-23 12:51 session-properties.png -rw-r--r-- 1 root root 913 2010-01-13 10:43 softwarecenter.png -rw-r--r-- 1 root root 697 2009-10-15 19:01 software-update-available.png -rw-r--r-- 1 root root 697 2009-10-15 19:01 software-update-urgent.png -rw-r--r-- 1 root root 795 2009-10-23 05:08 time-admin.png -rw-r--r-- 1 root root 617 2009-10-06 09:36 tomboy.png -rw-r--r-- 1 root root 911 2009-11-11 10:08 totem.png -rw-r--r-- 1 root root 841 2010-01-13 21:22 transmission.png -rw-r--r-- 1 root root 986 2009-12-21 20:43 ubuntuone-client.png -rw-r--r-- 1 root root 1031 2010-03-01 13:11 ubuntu-tweak.png -rw-r--r-- 1 root root 964 2009-11-02 09:05 update-manager.png -rw-r--r-- 1 root root 821 2009-10-19 14:36 vinagre.png Hors ligne perolrom Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr L'icone dont tu parles fait partie de gnome-app-install qui n'est pas installé par défaut http://packages.ubuntu.com/search?searchon=contents&keywords=application-gnome.png&mode=filename&suite=karmic&arch=any Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Ah bon, je me souviens plus d'avoir installé ça moi !!!! (ca commence à remonter aussi, suis tjrs sous hardy ) Je l'ai ajouté au package, qqles kilos de plus, c'est pas bien méchant ! Le post 1 a été mis à jour. lien Gm9diaCenter :http://gwebradio2.googlecode.com/files/ … 1.1.tar.gz lien full (mediacenter et Gm9diaCenter):http://gwebradio2.googlecode.com/files/ … ull.tar.gz Dernière modification par AnsuzPeorth (Le 12/03/2010, à 00:31) Hors ligne ovalie Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bonjour, petit souci quand je veux installer les lanceur : ACTION ajouter lanceur menu applications Traceback (most recent call last): File "/home/ubuntu/mediacenter/Gm9diaCenter/install_lanceur.py", line 54, in ajout f_app=open(lanceur_app,'w') IOError: [Errno 2] Aucun fichier ou dossier de ce type: '/home/ubuntu/.local/share/applications/Gm9diaCenter.desktop' je n'y comprend rien... (je suis sous lucid) Hors ligne AnsuzPeorth-out Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bjr, Ce message apparait car le dossier n'existe pas !!! Je vois que l'utilisateur est ubuntu, tu ne serais pas en live ? J'ai pas fait d'essais sous lucid, mais je pense qu'il a garder l'architecture des dossiers qd même ? Il suffit de créer le dossier, normalement, les logiciels installés en user installent leurs lanceurs dans ce dossier. Le dossier local est caché (point devant son nom), CTRL+h pour les afficher. /home/<user>/.local/share/applications Hors ligne ovalie Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Merci, non je ne suis pas en live, j'ai mis "ubuntu" comme nom d'utilisateur. j'ai créé le dossier "application" dans /home/ubuntu/.local/share/ puis ca a fonctionné. sous karmic je n'avais pas eu a faire ça et mon nom était aussi ubuntu. est ce normal que j'ai eu à créer ce dossier? quoi qu'il en soit maintenant c'est bon. Encore merci Hors ligne AnsuzPeorth-out Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr est ce normal que j'ai eu à créer ce dossier? Tu n'as surement pas encore installé de soft en local, c'est sans doute pour ça ! Maintenant c'est fait, les autres softs n'auront plus à le faire (mais je pensais que c'était d'origine...faudra que je modifie mon script en sorte ...) Hors ligne fabeer Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr salut et merci pour le boulot qui a été fait...pour ma part je touche au but....j'arrive a voir la liste des films qui sont sur le dd du pc,depuis le média center de la tv...mais quand je clic pour démarrer la lecture, ça me dit :"chargement de la vidéo en cours" et puis ça retourne sur l'écran de sélection des films...une idée du problème? Edit: et une question bete en passant....comment creer un raccourci sur le bureau pour demarrer l'interface graphique? Merci par avance Edit 2: problèmes resolus: pour le premier avec un reboot electrique du decodeur TV,pour le deuxieme,en cherchant un peu,un click droit sur la fenetre du programme et on envoie une icone sur le bureau...Merci a vous pour ce super travail Dernière modification par fabeer (Le 13/08/2010, à 16:45) Hors ligne Gérard Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bonsoir, J'ai fait toutes les manipulations décrites. Lorsque je lance install_lanceur.py, la petite fenêtre dans laquelle on choisi de cocher où mettre l'icone de lancement. Un lanceur se met bien dans le dossier "applications /accessoires" Sur le bureau un icone de dossier sous-titré Gm9diaCenter.desktop. Lorsque j'essaye de lancer le programme avec cette icone, qui est installée sur le bureau voici le message qui m'est retourné : Lanceur d'application non fiable Le lanceur d'application « Gm9diaCenter.desktop » n'est pas marqué comme fiable. Si vous ne connaissez pas la provenance de ce fichier, son lancement est potentiellement dangereux. Je suis sous Ubuntu 10.10 Lorsque j'avais la version 10.04 tous fonctionnait bien. D'où peu provenir le problème ? Merci par avance pour l'aide apportée Gérard Dernière modification par Gérard (Le 25/10/2010, à 19:19) En retard dans ce bas monde, pas en avance dans l'autre ! Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Lorsque j'avais la version 10.04 tous fonctionnait bien. D'où peu provenir le problème ? Peux être que les normes .desktop se sont renforcées, en tout cas, il y a une vérification maintenant ! (on se croirait sous windows !) En ce moment, j'ai pas bien le temps d'y regarder (je suis sous hardy encore, donc ...). Il faudrait que tu crée ton lanceur sur le bureau et dans le menu. Il devra pointer sur start.py qui se trouve dans le dossier Gm9diaCenter, qui lui même se trouve dans le dossier mediacenter, selon ton installation. Hors ligne Gérard Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bonsoir AnsuzPeorth Aucun résultat. Rien ne se lance, dommage, ton programme était génial. J'attends si tu avais un peu de temps à consacrer. Bonne fin de semaine Cordialement En retard dans ce bas monde, pas en avance dans l'autre ! Hors ligne tcit Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Re, apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName ? essaye ça Cela avait fonctionné chez moi...mais je ne peux plus essayer pour les raisons que rom1 comprendra (j'ai plus le mediacenter). Sinon pourrait-on essayer de distribuer le programme en .deb ? Y a des méthodes pour le python. Le développeur pourrait reprendre les fichiers glade et les faire passer sur quickly. Sinon y a Py2deb qui pourrait peut-etre marcher. Je dis cela car j'ai essayé moi même de faire mon petit programme tout a fait identique en packet (ici si ca intéresse qqn). mais cela n'avait jamais fonctionné, je n'avais en plus pas le temps... Dernière modification par tcit (Le 03/11/2010, à 21:43) Hors ligne Kanor Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr J'ai trouvé un bug le status affiché n'est pas correct j'ai une correction possible mais c'est vraiment pas jolie dans actionmedia.py def status(): #os.chdir(os.pardir) lacmd =subprocess.Popen(['../mediacenter','status'], stdout=subprocess.PIPE) var =lacmd.communicate() #os.chdir('Gm9diaCenter') print 'RESULT status :',var if re.search('running',var[0]): return ' Status : running' elif re.search('stopped',var[0]): return ' Status : stopped' else: return ' Status impossible' tu devrais penser à utiliser des espace à la place des tabulations Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr @Gérard Dsl, mais pa eu le temps d'y regarder... Et j'ai tjrs pas upgrade, donc .... J'ai trouvé un bug le status affiché n'est pas correct j'ai une correction possible mais c'est vraiment pas jolie dans actionmedia.py Ah bon ! quel bug ? Tes modifications ne sont que sur le chemin (.. au lieur des os.chdir qui sont effectivement inutiles, je sais plus pourquoi j'ai fait ça ! Faut dire que c'était mon premier script pygtk !) tu devrais penser à utiliser des espace à la place des tabulations Arfff, fainéantise, qd tu nous tiens ....! C'est plus rapide une tab que des espaces ... Hors ligne Yafa Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bonjour à toutezétous ! Je profite de cette petite appli bien sympatoche depuis bientôt 1 mois et j'aimerais relancer ce sujet avec une petite question ! J'ai configuré le lancement de Gm9diaCenter au démarrage de ma machine, jusque là tout se passe bien. Mon ordinateur s'allume donc avec ce programme actif et l'icône de connexion allumé en vert. Sur ma télévision, à l'allumage du décodeur sfr/neuf, l'ordinateur apparaît déconnecté. J'ai donc besoin de repasser Gm9diaCenter sur Rouge puis sur Vert pour l'obtenir. Une explication à me fournir ? Voire même un solution pour m'économiser cette petite manip' ? Hors ligne AnsuzPeorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bjr, J'avais également ce problème, cela ne vient pas de l'appli, ni même d'apache. C'est le mediacenter qui merdoit. A la page d'acceuil du mediacenter, là où sont les icones activé ou pas, je faisais une détection manuelle en plus, pour que le mediacenter puisse trouver le serveur et les partages. Hors ligne grandtoubab Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Salut, Celui là me donne satisfaction http://forum.sfr.fr/c-/t181645-mediacenter-linux.htm Linux tout seul sur le disque dur Acer Aspire T650 :=)) RAM: 1,7 Gio, CPU: Intel® Pentium(R) 4 CPU 3.06GHz × 2. Carte graphique Gallium 0.4 on ATI RC410 (Radeon Xpress200) Partition 1: Debian Jessie & Gnome Version 3.12, kernel 3.16.2-031602-generic Partition 2: Ubuntu Trusty 14.04 & Unity Hors ligne Yafa Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Merci !! Hors ligne azorth Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr Bonjour, et tout d'abord un grand merci pour cette appli que j'utilise depuis plus d'un an sans souci (sous 10.04). J'ai quelques questions/remarques dû à ma récente installation de Precise Pangolin. J'ai donc installé Ubuntu 12.04 hier et réinstallé quelques indispensables aujourd'hui dont Gm9diaCenter. 1. Problème au lancement du "start.py" Désolé je n'ai malheureusement pas gardé le message d'erreur mais j'ai résolu le problème en installant des paquets "glade" supplémentaires qui ne semblent pas être par défaut dans la distribution 12.04. Maintenant ça semble ok, mais au final je ne sais même pas quel paquet permet l'utilisation correcte de l'appli puisque j'en ai installé plusieurs... >> Si quelqu'un identifie le paquet précis il faudrait peut-être mettre à jour les infos d'installation. 2. Zone de notification Avec Unity, lorsque je je veux mettre en notification avec la patte de Gnome, l'appli n’apparaît pas dans les notifications puisqu'il ne doit pas y avoir les notifications Gnome. Quelqu'un aurait une solution ? 3. Tableau de bord Je retrouve bien l'application via le tableau de bord sans rien faire de spécial (j'imagine grâce a la première exécution ok). Mais celle-ci apparaît dans les filtre "Accessoire". Est-ce qu'il existe un moyen de l'associer au filtre "Multimédia" ? Au final il y a 2 question plus lié a Unity qu'a l'application mais si vous avez des réponse je suis preneur Hors ligne
The proper way to do it is have a self submitting forms that redirect to the destination page. Here are two sample controllers: def page1(): form=FORM('your name:',INPUT(_name="name"),INPUT(_type="submit")) if form.accepts(session.vars,session): session.name=form.vars.name redirect(URL(r=request,f='page2')) return dict(form=form) def page2(): return dict(message='hello %s'%session.name)
Greetings Pythonists and fans of British humor. Today, we're going to take a look at a great little Python module called PyGNOME. With this piece of software in hand, we can, without fear of being forced to use some other uncomfortable programming language, dive into the big world of GUI (Graphical User Interface) programming. You see, PyGNOME gives us a complete Python interface for dealing with the GNOME (GNU Network Object Model Environment) development/desktop environment. In this article, we will take a closer look at something called panel applets, which are essential elements on the GNOME desktop. Panel applets are usually developed in C, but this article will teach you how to use PyGNOME to develop GNOME panel applets with Python! This question may sound trivial to some of you, but the answer is not that obvious. Most people think of GNOME as a modern desktop environment. While that is true, GNOME is much more than a desktop environment; it is also a complete framework for GUI development. The GNOME development framework provides libraries and components that programers can use to easily build standardized GUI applications and utilities. And, in addition to a desktop environment and GUI development standard, GNOME is also a large set of free software, including everything from word processors to CD players. All these software components follow the GNOME standard, and they therefore look and act basically the same. The GNOME desktop comes with the panel, the bar that is located at the bottom of your GNOME desktop. From the panel, you can access your menus and quick-launchers. In addition, the panel can hold small programs, usually referred to as applets. Applets are programs designed to run inside another program. They are mini-applications. GNOME panel applets run on the panel instead of in a window of their own. If, however, you ignore the difference in where they are located, panel applets are just like any other program. Everything you can implement in a "real" GNOME program can also be implemented in a panel applet. (Although, when developing an applet you will have a much smaller area of the screen to work with). So, why would you want to develop applets instead of real GNOME applications? Well, this depends on what kind of program you want to create. If you're out to develop an advanced office suite a la StarOffice, or a spreadsheet program like Microsoft Excel, panel applets are not for you! On the other hand, if you want to develop a CD or MP3 player, and you want to be able to control this program all the time, no matter what other programs you're running, you should probably do it as a panel applet. This is the whole idea with panel applets: to have access to certain programs permanently, without having to bother about minimizing and/or maximizing other windows. The panel is always visible, and therefore so are the applets on the panel. Figure 1. Taskbar applet with the Gimp currently running (click for full view). Figure 1 shows a typical GNOME panel. The elements on this panel are, from left to right, the GNOME menus, four launchers, the pager applet, the taskbar applet (with The Gimp currently running), and the date/time applet (currently showing the time 12:54 PM). What we want to do is to create a program that resides on the panel, just as the pager, taskbar, and date/time applets do in Figure 1. We, however, don't just want to develop applets; we want to do it with Python. For this, we need to install the PyGNOME package. PyGNOME gives you access to the GNOME development libraries through Python. We will start out by downloading and installing PyGNOME on your system. You can get PyGNOME here. At the time of this writing, the latest version was 1.0.53. When the download is complete, go to the directory where you saved the file and issue the following command: tar xvfz gnome-python-1.0.53.tar.gz This will extract the files and place them in a directory called gnome-python-1.0.53. Now, go into this directory and run the configure script (which will make sure PyGNOME is compiled to suit your system): ./configure --prefix=/usr configure now starts to examine your system, making sure everything is in place. Note that you need to change the --prefix option to suit your system. However, /usr should be correct for most systems (like Red Hat Linux). If configure exits with an error message, the problem is most likely a missing package. Then you just need to install that package and try again. For example, if configure reports it can't find the Python headers, you need to install the python-devel package. Anyway, when configure exits without any errors (the last line should read creating config.h), you are ready to start the compilation. This is done by simply running make, as follows: make The compilation will now start. This can take a while, especially if you're on a slow system with not much RAM. After compiling, it's time to start the installation. (If you did not perform the last few commands as the superuser, you must change to your superuser or root account for the next command to work.) Use the following command to install your compiled package: make install You should now have PyGNOME installed under /usr/lib/python1.5/site-packages, and we're ready to start our panel applet production! We will create a very simple panel applet to give you a view of how applets should be created. This example applet shows a label with a frame around it. This probably won't give you any revolutionary ideas of how panel applets can be used, but you'll learn the PyGNOME basics. With a basic understanding of "usual" Gtk+ and/or GNOME programming, you won't have any problem extending this example. Let's take a look at the example program: 1: # Import the GNOME applet routines: 2: import gnome.applet 3: 4: # Import the Gtk+ routines: 5: import gtk 6: 7: # The main() function: 8: def main(): 9: # Create an instance of the AppletWidget class: 10: myapplet = gnome.applet.AppletWidget("Simple Applet") 11: 12: # Create a label to be shown inside the applet: 13: label = gtk.GtkLabel("O'Reilly") 14: 15: # Create a frame: 16: frame = gtk.GtkFrame() 17: 18: # Add the label to the frame: 19: frame.add(label) 20: 21: # Show the label: 22: label.show() 23: 24: # Show the frame: 25: frame.show() 26: 27: # Add the frame to the applet: 28: myapplet.add(frame) 29: 30: # Set the tooltip text for the applet: 31: myapplet.set_tooltip("This is a very simple panel applet.") 32: 33: # Show the applet: 34: myapplet.show() 35: 36: # Get into the Gtk main-loop: 37: gtk.mainloop() 38: 39: # This is plain old Python, so you should understand this: 40: if __name__ == '__main__': main() If you have any GUI programming experience, the comments in the listing are probably enough for you. However, let us go through the example anyway, to make sure everything is clear. To begin with, we import the GNOME applet and Gtk+ routines at lines 2 and 5. We do this, as you probably understand, to get access to the GNOME and Gtk+ routines that we want to use. The heart of every GNOME panel applet is the AppletWidget object. An object of this class represents the panel applet in whole; it is this object that makes our program a panel applet, and not a usual "window-program." The AppletWidget instance of this example is created on line 10 and is called myapplet. Also note that we pass an argument to the AppletWidget constructor. This is a string representing the name of the applet. Line 13 creates a GtkLabel instance, (label), and inserts the text "O'Reilly" into it. Line 16 creates a GtkFrame object, (frame). By inserting the label into the frame on line 19, we get a nice frame around the text (no kidding!!). The calls at lines 22 and 25 show the label and the frame on screen. Line 28 makes the frame a child of the AppletWidget object. Since label is a child of frame, label will automatically become a child of myapplet. On line 31, we set the so-called "tooltip" for our applet. The tooltip is the text that is shown if you hold the mouse pointer over the applet for a while. A tooltip is usually a short description of the program in question (as in this case). On line 34, we make the applet visible, and on line 37, we get into the Gtk+ main loop, which will take care of all user interaction. To save yourself some typing, download the example from here. Make sure you save it in a safe place. Figure 2. A simple applet running on the GNOME panel (click for full view). It's time to test our new, unbelievably advanced and sophisticated (ehrm...) applet. To start it, you do as you would with any other Python program: python lst1.py If everything is in place, the applet should now start and be visible on your panel. Of course, you need to have the GNOME panel running for this to work. Figure 2 shows our simple applet running on a GNOME panel. Figure 3. The standard applet-menu (click for full-size view). Our applet is the "O'Reilly" label with the frame around it, between the taskbar and the date/time applet. It has no functions or features, but it's our applet! However, all applets have a standard applet-menu. To see this, click with your right mouse button somewhere on the applet. From the menu that now pops up, you can remove or move the applet and also add other applets to the panel. This menu is also shown in Figure 3. To bring up the tooltip, hold your mouse pointer over the applet for a little while. A tooltip like the one shown in Figure 4 should show up. That was that, congratulations to your first PyGNOME applet! Figure 4. The tooltip menu. This article has taught you the basics of GNOME panel applet development with Python and the PyGNOME module. Although we have only touched the surface of this quite large subject, you should now have a basic understanding of what GNOME panel applets are, and when/why they are good. When developing applets, it's important to remember that you can implement everything in an applet that you can in a "real" GNOME program; every GNOME/Gtk+ widget or feature can be used in an applet. Remember, a good panel applet can do everything a larger program can, it will just have the advantage of always being accessible. Did anyone say size matters? C'mon, get serious! Daniel Solin is a freelance writer and Linux consultant whose specialty is GUI programming. His first book, SAMS Teach Yourself Qt Programming in 24 hours, was published in May, 2000. Discuss this article in the O'Reilly Network Python Forum. Return to the Python DevCenter. Copyright © 2009 O'Reilly Media, Inc.
The canonical docs for this project can be found on readthedocs.org PyCap (Python and REDCap) is a simple library for communicating with REDCap projects from Python applications. It mimics the REDCap API as much as possible and is designed to be very easy to use. To begin, you’ll need access to a REDCap server, a project within that server, and an API key for said project which can be obtained from your REDCap administrator. from redcap import Project api_url = 'https://redcap.example.edu/api/' api_key = 'SomeSuperSecretAPIKeyThatNobodyElseShouldHave' project = Project(api_url, api_key) Some helpful API calls occur during project creation: # Primary field, REDCap calls this the unique field print project.def_field id # A list of raw field names... print project.field_names ('id', 'age_at_testing', 'dob', 'test1_ss', ...) # ...and their labels print project.field_labels ('Identifier', 'Age at Day of Testing', 'Date of Birth', 'Test 1 Standard Score',...) # List of forms print project.forms ('demographics', 'test_1', ...) # If this is a longitudinal database... print project.events, project.arm_nums, project.arm_names ('event1', 'event2',...), ('arm1', 'arm2',...), ('Visit1', 'Visit2',...) The two most useful functions of the project object are .export_records and .import_records: from my_module import modify data = project.export_records() # data is a list of dicts new_data = modify(data) project.import_records(new_data) For more complete examples, please see the docs. Install with pip (or easy_install): $ pip install PyCap Or download the package from github (see buttons below) and: $ cd < downloads > $ < unzip/untar > $ python setup.py install Or to use the most up-to-date codebase, which hopefully isn’t broken: $ git clone git://github.com/sburns/PyCap.git $ cd PyCap $ python setup.py install OR $ pip install -e git+git@github.com:sburns/PyCap.git@master#eqq=PyCap
I'm rusty in SQL and completely new to SQL Alchemy, but have an upcoming project which uses both. So I thought I write something to get comfortable. Suffering from a hangover I decided to write something to keep track of alcohol levels. I have events where participate and consumeusers. Those are my three basic tables (with one helper tabledrinksguestlist, for a m:n relationship between usersandevents). drinks list the drinks available at all events to all users all the time (no need to map anything). users are created from time to time, so are events. all users can join all events, so I use the guestlist table to map those. Now to the heart of the question: I need to keep track at what time which user consumes which drink on which event. I try to solve this whit another table shots (see below) but I'm not sure if this a good solution. In SQL Alchemy it might look somewhat like this (or not, but this is what I came up with so far):: guestlist_table = Table('guestlist', Base.metadata, Column('event_id', Integer, ForeignKey('events.id')), Column('user_id', Integer, ForeignKey('users.id')) ) class Event(Base): __tablename__ = 'events' id = Column(Integer, primary_key=True) name = Column(String(80), nullable=False) started = Column(DateTime, nullable=False, index=True, default=datetime.datetime.now ) users = relationship("User", secondary=guestlist_table, backref="events") # ... class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False, unique=True, index=True) birthdate = Column(Date, nullable=False) weight = Column(Integer, nullable=False) sex = Column(Boolean, nullable=False) # ... class Drink(Base): __tablename__ = 'drinks' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) volume = Column(Numeric(5,2), nullable=False) percent = Column(Numeric(5,2), nullable=False) # ... class Shots(Base): __tablename__ = 'shots' id = Column(Integer, primary_key=True) at = Column(DateTime, nullable=False, default=datetime.datetime.now ) user_id = Column(Integer, ForeignKey('users.id'), index=True) event_id = Column(Integer, ForeignKey('events.id'), index=True) drink_id = Column(Integer, ForeignKey('drinks.id')) user = relationship("User", backref="shots") event = relationship("Event", backref="shots") drink = relationship("Drink", uselist=False) # one-to-one, no backref needed The thing is I kinda feel I overlooked something. And frankly I'm absolute lost on how to query it? Here are the queries I would make most of the time: I at least need to get all the shots consumed on a event (probably sorted by user) I also sometimes need all shots for a specific user (probably sorted by event) And a lot of counting: Number of shots per event Number of shots per user Number of shots a user downed at a event Is the shots table a okay way to manage this?
[This post is by Elliott Hughes, a Software Engineer on the Dalvik team. — Tim Bray] If you don’t write native code that uses JNI, you can stop reading now. If you do write native code that uses JNI, you really need to read this. What’s changing, and why? Every developer wants a good garbage collector. The best garbage collectors move objects around. This lets them offer very cheap allocation and bulk deallocation, avoids heap fragmentation, and may improve locality. Moving objects around is a problem if you’ve handed out pointers to them to native code. JNI uses types such as jobject to solve this problem: rather than handing out direct pointers, you’re given an opaque handle that can be traded in for a pointer when necessary. By using handles, when the garbage collector moves an object, it just has to update the handle table to point to the object’s new location. This means that native code won’t be left holding dangling pointers every time the garbage collector runs. In previous releases of Android, we didn’t use indirect handles; we used direct pointers. This didn’t seem like a problem as long as we didn’t have a garbage collector that moves objects, but it let you write buggy code that still seemed to work. In Ice Cream Sandwich, even though we haven't yet implemented such a garbage collector, we've moved to indirect references so you can start detecting bugs in your native code. Ice Cream Sandwich features a JNI bug compatibility mode so that as long as your AndroidManifest.xml’s targetSdkVersion is less than Ice Cream Sandwich, your code is exempt. But as soon as you update your targetSdkVersion, your code needs to be correct. CheckJNI has been updated to detect and report these errors, and in Ice Cream Sandwich, CheckJNI is on by default if debuggable="true" in your manifest. A quick primer on JNI references In JNI, there are several kinds of reference. The two most important kinds are local references and global references. Any given jobject can be either local or global. (There are weak globals too, but they have a separate type, jweak, and aren’t interesting here.) The global/local distinction affects both lifetime and scope. A global is usable from any thread, using that thread’s JNIEnv*, and is valid until an explicit call to DeleteGlobalRef(). A local is only usable from the thread it was originally handed to, and is valid until either an explicit call to DeleteLocalRef() or, more commonly, until you return from your native method. When a native method returns, all local references are automatically deleted. In the old system, where local references were direct pointers, local references were never really invalidated. That meant you could use a local reference indefinitely, even if you’d explicitly called DeleteLocalRef() on it, or implicitly deleted it with PopLocalFrame()! Although any given JNIEnv* is only valid for use on one thread, because Android never had any per-thread state in a JNIEnv*, it used to be possible to get away with using a JNIEnv* on the wrong thread. Now there’s a per-thread local reference table, it’s vital that you only use a JNIEnv* on the right thread. Those are the bugs that ICS will detect. I’ll go through a few common cases to illustrate these problems, how to spot them, and how to fix them. It’s important that you do fix them, because it’s likely that future Android releases will utilize moving collectors. It will not be possible to offer a bug-compatibility mode indefinitely. Common JNI reference bugs Bug: Forgetting to call NewGlobalRef() when stashing a jobject in a native peer If you have a native peer (a long-lived native object corresponding to a Java object, usually created when the Java object is created and destroyed when the Java object’s finalizer runs), you must not stash a jobject in that native object, because it won’t be valid next time you try to use it. (Similar is true of JNIEnv*s. They might be valid if the next native call happens on the same thread, but they won’t be valid otherwise.) class MyPeer { public: MyPeer(jstring s) { str_ = s; // Error: stashing a reference without ensuring it’s global. } jstring str_; }; static jlong MyClass_newPeer(JNIEnv* env, jclass) { jstring local_ref = env->NewStringUTF("hello, world!"); MyPeer* peer = new MyPeer(local_ref); return static_cast<jlong>(reinterpret_cast<uintptr_t>(peer)); // Error: local_ref is no longer valid when we return, but we've stored it in 'peer'. } static void MyClass_printString(JNIEnv* env, jclass, jlong peerAddress) { MyPeer* peer = reinterpret_cast<MyPeer*>(static_cast<uintptr_t>(peerAddress)); // Error: peer->str_ is invalid! ScopedUtfChars s(env, peer->str_); std::cout << s.c_str() << std::endl; } The fix for this is to only store JNI global references. Because there’s never any automatic cleanup of JNI global references, it’s critically important that you clean them up yourself. This is made slightly awkward by the fact that your destructor won’t have a JNIEnv*. The easiest fix is usually to have an explicit ‘destroy‘ function for your native peer, called from the Java peer’s finalizer: class MyPeer { public: MyPeer(JNIEnv* env, jstring s) { this->s = env->NewGlobalRef(s); } ~MyPeer() { assert(s == NULL); } void destroy(JNIEnv* env) { env->DeleteGlobalRef(s); s = NULL; } jstring s; }; You should always have matching calls to NewGlobalRef()/DeleteGlobalRef(). CheckJNI will catch global reference leaks, but the limit is quite high (2000 by default), so watch out. If you do have this class of error in your code, the crash will look something like this: JNI ERROR (app bug): accessed stale local reference 0x5900021 (index 8 in a table of size 8) JNI WARNING: jstring is an invalid local reference (0x5900021) in LMyClass;.printString:(J)V (GetStringUTFChars) "main" prio=5 tid=1 RUNNABLE | group="main" sCount=0 dsCount=0 obj=0xf5e96410 self=0x8215888 | sysTid=11044 nice=0 sched=0/0 cgrp=[n/a] handle=-152574256 | schedstat=( 156038824 600810 47 ) utm=14 stm=2 core=0 at MyClass.printString(Native Method) at MyClass.main(MyClass.java:13) If you’re using another thread’s JNIEnv*, the crash will look something like this: JNI WARNING: threadid=8 using env from threadid=1 in LMyClass;.printString:(J)V (GetStringUTFChars) "Thread-10" prio=5 tid=8 NATIVE | group="main" sCount=0 dsCount=0 obj=0xf5f77d60 self=0x9f8f248 | sysTid=22299 nice=0 sched=0/0 cgrp=[n/a] handle=-256476304 | schedstat=( 153358572 709218 48 ) utm=12 stm=4 core=8 at MyClass.printString(Native Method) at MyClass$1.run(MyClass.java:15) Bug: Mistakenly assuming FindClass() returns global references FindClass() returns local references. Many people assume otherwise. In a system without class unloading (like Android), you can treat jfieldID and jmethodID as if they were global. (They’re not actually references, but in a system with class unloading there are similar lifetime issues.) But jclass is a reference, and FindClass() returns local references. A common bug pattern is “static jclass”. Unless you’re manually turning your local references into global references, your code is broken. Here’s what correct code should look like: static jclass gMyClass; static jclass gSomeClass; static void MyClass_nativeInit(JNIEnv* env, jclass myClass) { // ‘myClass’ (and any other non-primitive arguments) are only local references. gMyClass = env->NewGlobalRef(myClass); // FindClass only returns local references. jclass someClass = env->FindClass("SomeClass"); if (someClass == NULL) { return; // FindClass already threw an exception such as NoClassDefFoundError. } gSomeClass = env->NewGlobalRef(someClass); } If you do have this class of error in your code, the crash will look something like this: JNI ERROR (app bug): attempt to use stale local reference 0x4200001d (should be 0x4210001d) JNI WARNING: 0x4200001d is not a valid JNI reference in LMyClass;.useStashedClass:()V (IsSameObject) Bug: Calling DeleteLocalRef() and continuing to use the deleted reference It shouldn’t need to be said that it’s illegal to continue to use a reference after calling DeleteLocalRef() on it, but because it used to work, so you may have made this mistake and not realized. The usual pattern seems to be where native code has a long-running loop, and developers try to clean up every single local reference as they go to avoid hitting the local reference limit, but they accidentally also delete the reference they want to use as a return value! The fix is trivial: don’t call DeleteLocalRef() on a reference you’re going to use (where “use” includes “return”). Bug: Calling PopLocalFrame() and continuing to use a popped reference This is a more subtle variant of the previous bug. The PushLocalFrame() and PopLocalFrame() calls let you bulk-delete local references. When you call PopLocalFrame(), you pass in the one reference from the frame that you’d like to keep (typically for use as a return value), or NULL. In the past, you’d get away with incorrect code like the following: static jobjectArray MyClass_returnArray(JNIEnv* env, jclass) { env->PushLocalFrame(256); jobjectArray array = env->NewObjectArray(128, gMyClass, NULL); for (int i = 0; i < 128; ++i) { env->SetObjectArrayElement(array, i, newMyClass(i)); } env->PopLocalFrame(NULL); // Error: should pass 'array'. return array; // Error: array is no longer valid. } The fix is generally to pass the reference to PopLocalFrame(). Note in the above example that you don’t need to keep references to the individual array elements; as long as the GC knows about the array itself, it’ll take care of the elements (and any objects they point to in turn) itself. If you do have this class of error in your code, the crash will look something like this: JNI ERROR (app bug): accessed stale local reference 0x2d00025 (index 9 in a table of size 8) JNI WARNING: invalid reference returned from native code in LMyClass;.returnArray:()[Ljava/lang/Object; Wrapping up Yes, we asking for a bit more attention to detail in your JNI coding, which is extra work. But we think that you’ll come out ahead on the deal as we roll in better and more sophisticated memory management code.
I have problems when try to import pywhois module, i can import my own module but still have troubles when import pywhois. I moved the pywhois folder in my project folder domain, the screentshot is below: This is the import and calling statment below: import part: from pywhois import * calling part: w = whois('hackbo.com') self.response.out.write(w) The problems is it will always throw a http 500 error, error text is below: Traceback (most recent call last): File "/home/li/Desktop/google_appengine/google/appengine/ext/webapp/__init__.py", line 700, in __call__ handler.get(*groups) File "/home/li/Desktop/google_appengine/domain/main.py", line 43, in get w = whois('hackbo.com') File "pywhois/__init__.py", line 12, in whois text = nic_client.whois_lookup(None, domain, 0) File "pywhois/whois.py", line 157, in whois_lookup result = self.whois(query_arg, nichost, flags) File "pywhois/whois.py", line 100, in whois s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) AttributeError: 'module' object has no attribute 'socket' What is this error means? why i could import my own module but can not import pywhois?
I'm trying to write some Python code that will traverse each directory in the current working directory and report the total size (in bytes) under each directory, regardless of how deep each directory itself goes. This is just for a learning project, I realize there are already other ways to get this information through the shell. Here's some code I have so far: # get name of current working directory start_directory = os.getcwd() # create dictionary to hold the size of each folder in # the current working directory top_level_directory_sizes = {} # initialize directory for i in os.listdir(start_directory): if os.path.isdir(i): top_level_directory_sizes[i] = 0 # traverse all paths from current working directory for dirpath, dirnames, filenames in os.walk(start_directory): for f in filenames: fp = os.path.join(dirpath, f) #increment appropriate dictionary element: += os.path.getsize(fp) for k,v in top_level_directory_sizes.iteritems(): print k, v So the output will hopefully look something like this: algorithms 23,754 bytesarticles 1,234 bytesbooks 123,232 bytesimages 78,232 bytestotal 226,452 bytes
I have generated an image using PIL. How can I save it to a string in memory?The Image.save() method requires a file. I'd like to have several such images stored in dictionary. You can probably use the StringIO class to get a wrapper around strings that behaves like a file. The StringIO object provides the same interface as a file, but saves the contents just in memory: import StringIO output = StringIO.StringIO() image.save(output) contents = output.getvalue() output.close() This might lead to a image.save(output, format="GIF") save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO: buf= StringIO.StringIO() im.save(buf, format= 'JPEG') jpeg= buf.getvalue() sth's solution didn't work for me It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case You can bypass the format detection by setting the format yourself in a parameter import StringIO output = StringIO.StringIO() format = 'PNG' # or 'JPEG' or whatever you want image.save(output, format) contents = output.getvalue() output.close() When you say "I'd like to have number of such images stored in dictionary", it's not clear if this is an in-memory structure or not. You don't need to do any of this to meek an image in memory. Just keep the If you're going to write your dictionary to a file, you might want to look at The "format" (.jpeg, .png, etc.) only matters on disk when you are exchanging the files. If you're not exchanging files, format doesn't matter.
lukophron [python]Monsieur Cinéscript Salut, Suite à une demande, j'ai pondu un script python pour mettre à jour la liste des films trouvés sur le topic-jeu Quel film c'est ? Ça tourne, ça remplit son objectif (et son deuxième objectif qui était de me remettre à apprendre Python ^^) Maintenant, il y aurait mieux. Je poste ici pour avoir quelques retours de codeurs, et fixer certains des objectifs d'amélioration. questionnement actuel : - algo à revoir ? tu m'étonnes... - pourquoi tt0080684 ne renvoie pas la date ? Vos idées, conseils, pistes, remarques, sont les bienvenus ! 120311 : modif unicode130123 : modif trialpha (clarification), balise [imdb] insensible à la casse130401 : modif balise *]130610 : v0.9.6 unicode mon amour, le GMT c'est le pied130713 : v0.9.7 python2.7, correction parse imdb, addons log + envoi topic dédié + détails140201 : v0.9.9 bordel140614 : v1.0.0 message dans le topic pour signalement140622 : v1.1.1 tests140911 : v1.1.2 (?) Dernière modification par lukophron (Le 11/09/2014, à 19:58) Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne lukophron Re : [python]Monsieur Cinéscript #!/usr/bin/env python # -*- coding: utf-8 -*- # ### mise à jour de la liste des films du jeu Monsieur Cinéma sur forum.ubuntu-fr ### # # misajourv1.py # # python2.7 # dep : mechanize # # un fichier joint pour accéder au compte # un fichier créé si besoin pour sauvegarder la liste # # licence internationale DTFWYW # licence fr SCVSVPTPUB import urllib2 import locale import re import time import mechanize import htmlentitydefs import unicodedata from random import choice version = 'v1.1.2' locale.setlocale(locale.LC_ALL,'fr_FR.utf8') def cleanString(s): if isinstance(s,str): s = unicode(s,"utf-8","replace") s=unicodedata.normalize('NFD',s) return s def compare (a, b): # pour épurer et trier les titres a = a.lstrip() b = b.lstrip() if a[0] == '(': a = a.split(')')[1] if b[0] == '(': b = b.split(')')[1] a = a.lstrip() b = b.lstrip() return locale.strcoll(a, b) def unescape(text): # code html -> unicode fonction trouvée sur le net def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) def trialpha(liste) : # tri par ordre alphabétique la liste brute dicfilm = {} trukipasspa = {ord(u'\u0152'):u'oe' , ord(u'\u0153'):u'oe'} for i in liste: i = i.lstrip().rstrip() if i[0] == '(': a = i.split(')')[1] a = cleanString(a.lstrip()) else : a = cleanString(i) a = a.translate(trukipasspa) dicfilm[i]= a[0].lower() liste_alpha = [] for i in range(28) : liste_alpha.append([]) alfab = 'abcdefghijklmnopqrstuvwxyz' for i in dicfilm.items(): if i[1] in alfab : liste_alpha[alfab.index(i[1])+1].append(i[0]) elif i[1].isdigit() : liste_alpha[0].append(i[0]) else : liste_alpha[27].append(i[0]) #liste_globale = [j for i in liste_alpha for j in i] for i in range(28): liste_alpha[i].sort(cmp=compare) liste_imprim = u'[center][b]N°[/b][/center]\n[code]'+(u' | ').join(liste_alpha[0])+u'''[/code]\n\n''' nbr = 1 for i in 'abcdefghijklmnopqrstuvwxyz?'.upper(): liste_imprim += u'[center][b]'+i+u'[/b][/center]\n[code]'+(u' | ').join(liste_alpha[nbr])+u'''[/code]\n\n''' nbr+=1 return liste_imprim.encode('utf8') def recupost(urltopic) : # récupère le deuxième message du topique et en extrait # la liste actuelle, les codes imdb déjà utilisés, l'id du post, la dernière page parcourue print 'récupération du message-liste' print urltopic for i in range(5): try: pageraw = urllib2.urlopen(urltopic) print 'première page récupérée '+urltopic break except: print 'récupération échouée, nouvelle tentative dans 3 secondes' if i==4: print 'échec de la récupération - sortie' raise time.sleep(3) page = pageraw.read() pageraw.close() #print page imdrex = re.compile('\<code>\[imdb\sliste\](.*?)\[/imdb\]</code>') listrex = re.compile('<p style="text-align: center"><strong>.*?</strong></p><div class="codebox"><pre><code>(.*?)</code></pre></div>') numprex = re.compile('la page #([\d]+)') postex = re.compile('<div id="p(\d+)"\sclass=') if imdrex.search(page): liste_imdb = imdrex.search(page).group(1) liste_imdb = liste_imdb.split() else : print 'liste imdb absente ?' liste_imdb = [] liste_titres = [] if listrex.search(page) : for i in listrex.findall(page) : liste_titres += unescape(i.decode('utf8')).split(' | ') else : print 'liste de titres absente ?' if postex.search(page) : postid = postex.findall(page)[1] else : print 'ID du post introuvable' postid = 0 #raise if numprex.search(page) : numpage = numprex.search(page).group(1) else : print 'n° de dernière page mise à jour non trouvée, placé à 1 par défaut' numpage = 1 print '\n message récupéré pour mise à jour\n' return liste_imdb, liste_titres, postid, numpage def recupbalise(numpage, url, old_imdb) : # retourne les balises des films trouvés à rajouter # la dernière page farfouillée # le nouvel url, si le topic est fermé # le dernier film trouvé listall = [] dernier = ['','',0] newurl = url numpage = int(numpage) suivex = re.compile('>Suiv.</a>') titrex = re.compile('[\[imdb\]|\[*\]](tt\d+)[\[/imdb\]|\[/*\]]', re.I) closerex = re.compile('<p class="postlink conr">Discussion fermée</p>') postmsrex = re.compile('<div class="postmsg">(.*?)</div>', re.DOTALL) linkrex = re.compile('<a href="(.*?)">') while numpage < 300 : # limite non-nécessaire si le code n'est pas beugué, mieux vaut prévenir... print 'recherche des codes imdb sur la page '+str(numpage) print url+'&p='+str(numpage) for i in range(5): try : pageraw = urllib2.urlopen(url+'&p='+str(numpage)) break except : if i==4: print 'échec de connection avec le forum - sortie' raise print 'page du forum inaccessible - nouvelle tentative dans 3 secondes' time.sleep(3) page = pageraw.read() pageraw.close() #titre = titrex.findall(page) titre = [] [titre.append(x) for x in titrex.findall(page)\ if (x not in old_imdb and x not in titre)] if titre : dernier[1] = titre[-1] dernier[2] = numpage print titre [listall.append(x) for x in titre if x not in listall] if suivex.search(page) : numpage +=1 else: if closerex.search(page) : print '\ntopic fermé, recherche du nouveau topic' posts = postmsrex.findall(page) lastpost = posts[-1] print lastpost if linkrex.search(lastpost) : numpage = 1 newurl = linkrex.search(lastpost).group(1) print 'Nouveau topic détecté: '+newurl else : print "Topique détecté fermé, mais pas de nouveau url ?" break break #listall = list(set(listall)) return numpage, listall, newurl, dernier def titrimdb(films, dernier): # cherche les titres des films en fonction de leur numéro imdb print '\nrecherche des titres des nouveaux films sur imdb' print films nouvfilm = [] title = re.compile('<title>(.*?)</title>') tab = re.compile('<td>(.*?)</td>') cookieJar = mechanize.CookieJar() handlers = [ urllib2.HTTPHandler(), urllib2.HTTPCookieProcessor(cookieJar), ] opener = urllib2.build_opener(*handlers) headers = { 'Accept': 'text/html,application/xhtml+xml,'\ 'application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Language': 'en-US,en;q=0.8,fr;q=0.6', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.19 '\ '(KHTML, like Gecko) Ubuntu/12.04 '\ 'Chromium/18.0.1025.151 Chrome/18.0.1025.151 '\ 'Safari/535.19', } for i in films: page = '' url='http://www.imdb.com/title/'+i+'/releaseinfo' for j in range(5): print 'Balise '+i+' : ', try : request = urllib2.Request( url=url, headers=headers ) connection = opener.open(request) if connection.geturl()==url: page = connection.read() else : print "\nATTENTION : vérifier la balise "+i+'\n' break except urllib2.HTTPError, exc: if exc.code == 404: print "404 Page non trouvée !" print "\nATTENTION : vérifier la balise "+i+'\n' break else: print "La requête HTTP a échoué avec le code %d (%s)" % (exc.code, exc.msg) print "\nATTENTION : vérifier la balise "+i+'\n' break except urllib2.URLError, exc: print "Echec. Cause:", exc.reason print 'page imdb inaccessible, nouvelle tentative dans 3 secondes' if j==4: print 'échec de connection avec IMDb - sortie' raise time.sleep(3) original = '' titre = title.search(page).group(1) titre = unescape(titre) titre = titre.split(' - ')[0] tableau = tab.findall(page) for k in tableau : if 'original title' in k.lower() : if original and original != unescape(tableau[tableau.index(k)+1]): original += ' ('+unescape(tableau[tableau.index(k)+1])+')' else : original = unescape(tableau[tableau.index(k)+1]) date = titre.split().pop() if original != '' : titre = original+' '+date if titre[:2].lower() in ["l'","d'"] : titre = titre[:2]+' '+titre[2:] titest = titre.split() if titest[0].lower() in ['le','la','les',"l'",'the','a']: # vérifier le formatage voulu (mon, ma, mes ?) titest[0]='('+titest[0]+')' titre = ' '.join(titest) titre = cleanString(titre) print titre nouvfilm.append((i, titre)) if i == dernier[1] : dernier[0] = titre time.sleep(1) print 'recherche imdb terminée' if nouvfilm == []: print 'pas de nouveau film, donc' else : print '\ntitres ajoutés :' print [t for (i, t) in nouvfilm] return nouvfilm, dernier def message(liste_imdb, liste_titres, nbr_titres, numpage, dernier, picfilm): # façonne le nouveau message-liste texte = """[b]LISTE DES FILMS DÉJÀ CITÉS :[/b] ~+~+~+~+~+~+~+~+~ Dernière mise à jour de la Liste : """ texte += time.strftime('le %d/%m/%Y, à %H:%M:%S (GMT)',time.gmtime()) texte += """, jusqu'à la page #""" texte += str(numpage) texte += """ Dernier film ajouté : """ texte += dernier[0].encode('utf8') texte += """ [i]balise """ texte += dernier[1] + ", page " texte += str(dernier[2])+"""[/i] Nombre de films trouvés : """ texte += str(nbr_titres) texte += """ ~+~+~+~+~+~+~+~+~ """ texte += trialpha(liste_titres) texte += """ Liste des balises utilisées[code][imdb liste]""" texte += liste_imdb.encode('utf8') texte += """[/imdb][/code]""" texte += picfilm.encode('utf8') #texte.decode('utf8') return texte def notification(numpage, new_numpage, new_film): #façonne le message de notification de mise à jour texte = """Bonjour, mise à jour effectuée depuis la page """ texte += str(numpage) texte += """ jusqu'à la page """ texte += str(new_numpage) texte += """ """ texte += choice(["j'balise !", "Merci de signaler les erreurs",\ "ça va sinon ?", "Winter is coming.", "Merci d'errer les signalements"]) texte += """[code]""" for i in new_film : texte += """ Balise """ texte += i[0].encode('utf8') texte += """ : """ texte += i[1].encode('utf8') texte += """[/code]""" return texte def modifpost(msg, msg2, login, password, postid, tid): # envoie les messages - liste + notification print 'envoi des post en cours...' # modifie le post liste for i in range(5) : try : print 'modification du post-liste' cookieJar = mechanize.CookieJar() opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookieJar)) opener.addheaders = [("User-agent","Mozilla/5.0")] mechanize.install_opener(opener) fp = mechanize.urlopen("http://forum.ubuntu-fr.org/login.php") forms = mechanize.ParseResponse(fp) fp.close() #print forms[1] form = forms[1] form["req_username"] = login form["req_password"] = password fp = mechanize.urlopen(form.click()) fp.close() print 'opening http://forum.ubuntu-fr.org/edit.php?id='+str(postid) fp = mechanize.urlopen('http://forum.ubuntu-fr.org/edit.php?id='+str(postid)) forms = mechanize.ParseResponse(fp) fp.close() #print forms[0] form = forms[1] form["req_message"] = msg fp = mechanize.urlopen(form.click()) fp.close() print 'modification faite' break except: print 'post échoué, nouvelle tentative dans 3 secondes' if i==4: print 'échec - sortie' raise time.sleep(3) #notifie la mise à jour for i in range(5) : try : print "envoi du post signalant les ajouts" print 'opening http://forum.ubuntu-fr.org/post.php?tid='+tid fp2 = mechanize.urlopen('http://forum.ubuntu-fr.org/post.php?tid='+tid) forms2 = mechanize.ParseResponse(fp2) fp2.close() #print forms2[0] form2 = forms2[1] form2["req_message"] = msg2 fp2 = mechanize.urlopen(form2.click()) fp2.close() print 'envoi réalisé' break except: print 'post échoué, nouvelle tentative dans 3 secondes' if i==4: print 'échec - sortie' raise time.sleep(3) def modiflocal(msg): # pour un test en local et la sauvegarde try : with open('liste.bak', 'w') as f : f.write(msg) print 'ok, liste.bak mis à jour' except : print 'sauvegarde locale impossible' def recupostID(urltopic) : postex = re.compile('<div id="p(\d+)"\sclass=') for i in range(5): try: pageraw = urllib2.urlopen(urltopic) print 'page récupérée '+urltopic break except: print 'récupération échouée, nouvelle tentative dans 3 secondes' if i==4: print 'échec de la récupération - sortie' raise time.sleep(3) page = pageraw.read().decode('utf-8') pageraw.close() if postex.search(page) : postid = postex.findall(page)[1] else : print 'ID du post introuvable' raise return postid def sendimage(url_server, url_image): # envoie l'image sur un serveur imrex = re.compile('\[img\](.*?)\[/img\]', re.I) print 'envoi de l\'image pour modif\' en ligne' cookieJar = mechanize.CookieJar() opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookieJar)) opener.addheaders = [("User-agent","Mozilla/5.0")] mechanize.install_opener(opener) fp = mechanize.urlopen(url_server) forms = mechanize.ParseResponse(fp) fp.close() form = forms[0] print 'envoi du formulaire' form["url_list"] = url_image form["optsize"] = ['3'] form["adult"] = ["no"] #print form fp = mechanize.urlopen(form.click()) response = fp.read() fp.close() url_thumb = imrex.search(response).group(1) print 'image réduite accessible : ' +url_thumb return url_thumb def getpic(titre): # va chercher une pic ! print "recherche d'une image..." imrex = re.compile('imgurl:&quot;(.*?)&quot;', re.I) jeveurex = re.compile('gif|nopicture|youtube') cookieJar = mechanize.CookieJar() opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookieJar)) opener.addheaders = [("User-agent","Mozilla/5.0")] mechanize.install_opener(opener) cherche = "http://www.bing.com/images/search?q=movie+"+'+'.join(titre.split())+"&adlt=off" print cherche fp = mechanize.urlopen(cherche) response = fp.read() fp.close() listall = imrex.findall(response) for i in range(len(listall)): if jeveurex.search(listall[i]): continue else : print listall[i] ima = listall[i] break if ima : return ima else : ima = 'http://clzimages.com/movie/large/43/43_d_46984_0_Python.jpg' return ima def main(): # on y arrive... ###scinder en fonctions ? (cf picfilm) ++options print "mise à jour en cours... "+version with open('tchernia','r') as f : url_qfc = f.readline().rstrip('\n\r') login = f.readline().rstrip('\n\r') password = f.readline().rstrip('\n\r') try : tid = url_qfc.split('=')[1].rstrip('&p') except : tid = 'ERROR : url invalide ?' try : urltopic = url_qfc.split('&')[0] except : urltopic = url_qfc print 'id du topic en cours = '+tid #`a changer si liste à part old_imdb, old_titres, postid, numpage = recupost(urltopic) print 'page en cours = '+str(numpage) new_numpage, new_imdb, newurl, dernier = recupbalise(numpage, url_qfc, old_imdb) print 'page atteinte : '+str(new_numpage)+'\n' #s1 = set(new_imdb) #s2 = set(old_imdb) #new_imdb = list(s1-s2) if new_imdb != []: new_film, dernier = titrimdb(new_imdb, dernier) else : print 'pas de nouveau film, sortie sans modification de la liste' quit() new_imdb = old_imdb + new_imdb # ! modification après avoir récupéré les titres new_liste = [t for (i, t) in new_film] + old_titres new_liste = list(set(new_liste)) new_liste.sort(cmp=compare) new_imdb.sort() if new_imdb : imdb_str = ' '.join(new_imdb) else : imdb_str = '' nbr_titres = len(new_liste) #cherchpic = choice(new_liste) try : cherchpic = choice(new_liste) except : print "bug python, choix annulé" cherchpic = "python" print "\nle choix du jour : "+cherchpic try : ima = urllib2.unquote(getpic(cleanString(cherchpic).encode("utf-8"))) thumb = sendimage('http://postimage.org/index.php?um=web', ima) picfilm =""" [center]un (quel)film(c) au hasard [url="""+ima+"][img="+cherchpic+"]"+thumb+"[/img][/url][/center]" except : print "bug envoi image" picfilm = " " msg = message(imdb_str, new_liste, nbr_titres, new_numpage, dernier, picfilm) msg2 = notification(numpage, new_numpage, new_film) print '\nnouvelle liste créée \n' print 'modification de la liste locale' modiflocal(msg) if urltopic != newurl : try : tid = newurl.split('=')[1].rstrip('&p') except : print 'ERROR : nouvel url invalide ? '+newurl print '\nTopic changé, recherche du nouveau post sur le topic '+tid postid = recupost('http://forum.ubuntu-fr.org/viewtopic.php?id='+tid)[2] print 'modification du fichier local avec la nouvelle url' print newurl with open('tchernia', 'r') as file : tchernia = file.readlines() tchernia[0] = 'http://forum.ubuntu-fr.org/viewtopic.php?id='+tid+'\n' with open('tchernia', 'w') as file : file.writelines(tchernia) print '\nmessage à envoyer sur le fil' try : if raw_input(msg2): print "go go go" modifpost(msg, msg2, login, password, postid, tid) except : print '\néchec des posts' print '\n ... mise à jour terminée ' if __name__ == "__main__": main() Dernière modification par lukophron (Le 11/09/2014, à 20:02) Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Je copie toujours le code que tu donnes en page 1 comme tu me l'avais dit ! Sinon j'ai copié celui-là et : ./misajour.py File "./misajour.py", line 457 print 'opening [url=http://forum.ubuntu-fr.org/edit.php?id=+str(postid)]http://forum.ubuntu-fr.org/edit.php?id='+str(postid)[/url] ^ SyntaxError: invalid syntax Hors ligne lukophron Re : [python]Monsieur Cinéscript ok, on va rester ici histoire de ne pas s'embrouiller plus avant j'ai mal posté et le forum a rajouté des balises automatiquement, je modifie ça, tu peux y aller, ça va passer... Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Voila : ./misajour.py import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. from: can't read /var/mail/BeautifulSoup ./misajour.py: ligne 26: version : commande introuvable ./misajour.py: ligne 28: Erreur de syntaxe près du symbole inattendu « locale.LC_ALL,'fr_FR.utf8' » ./misajour.py: ligne 28: `locale.setlocale(locale.LC_ALL,'fr_FR.utf8')' Hors ligne lukophron Re : [python]Monsieur Cinéscript je te confirme que ça tourne chez moi, avec le code posté en #2 il manque peut-être les premières lignes chez toi (#!/usr/bin/env python, etc) vérifie/refais ton copier-coller Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne grim7reaper Re : [python]Monsieur Cinéscript Je confirme, ça c’est la sortie d’un script python lu par un shell… Hors ligne SystemeD Re : [python]Monsieur Cinéscript Je lance ton script dans une console et j'obtiens ça : ./misajour.py import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. import: unable to grab mouse `': Ressource temporairement non disponible @ error/xwindow.c/XSelectWindow/9012. from: can't read /var/mail/BeautifulSoup ./misajour.py: ligne 26: version : commande introuvable ./misajour.py: ligne 28: Erreur de syntaxe près du symbole inattendu « locale.LC_ALL,'fr_FR.utf8' » ./misajour.py: ligne 28: `locale.setlocale(locale.LC_ALL,'fr_FR.utf8')' Vous dites que ça marche mais alors pourquoi les deux derniers films : Friday et Trois Enfants Dans Le Désordre ne sont pas ajoutés à la liste ? Hors ligne grim7reaper Re : [python]Monsieur Cinéscript Le script a peut-être des bugs, mais le fait de lancer du Python avec un interpréteur Shell ça va pas aider hein Essaye : python misajour.py Au moins tu seras sûr de lance le bon truc (et là, lukophron pourra commencer à débugger si nécessaire…). Hors ligne lukophron Re : [python]Monsieur Cinéscript refais ton copier-coller à partir de là! si je le lance chez moi, je n'ai pas de soucis. Peut-être qu'il y a un soucis dans le script, mais pour l'instant c'est dans ta façon de l'utiliser, le problème. Et s'il y a un bug dans le script, il n'enverra pas le nouveau post, donc ne t'embête pas à chercher Les nouveaux films ne sont pas ajoutés, parce j'ai fait exprès de ne pas envoyer le post, pour qu'on puisse être sûrs que tout va bien chez toi. Comme tu peux voir, tout va bien, mais il n'envoie pas le post mise à jour en cours... v0.9.1a url du topic = http://forum.ubuntu-fr.org/viewtopic.php?id=831321 id du topic = 831321 récupération du message-liste première page récupérée http://forum.ubuntu-fr.org/viewtopic.php?id=831321 message récupéré pour mise à jour page en cours = 94 recherche des codes imdb sur la page 94 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=94 ['tt1302555', 'tt0188321'] recherche des codes imdb sur la page 95 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=95 ['tt0113118'] recherche des codes imdb sur la page 96 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=96 ['tt0187557', 'tt0084855'] page atteinte : 96 recherche des titres des nouveaux films sur imdb appuyer sur 'o' ou 'n' pour accepter ou refuser un film ['tt0113118', 'tt0187557', 'tt0188321', 'tt0084855'] Balise : tt0113118 --- Accepter le titre : Friday (1995) ?o titre ajouté Balise : tt0187557 --- Accepter le titre : Trois enfants... dans le désordre (1966) ?o titre ajouté Balise : tt0188321 --- Accepter le titre : (Les) brûlés (1959) ?o titre ajouté Balise : tt0084855 --- Accepter le titre : (The) Verdict (1982) ?o titre ajouté recherche imdb terminée nouveaux films : ['Friday (1995)', u'Trois enfants... dans le d\xe9sordre (1966)', u'(Les) br\xfbl\xe9s (1959)', '(The) Verdict (1982)'] message modifié, à envoyer sauvegarde locale ok, liste.bak mis à jour ... mise à jour terminée Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Là, ça a l'air de gazer impec ! ~/Bureau/monsieur cinema$ python misajour.py mise à jour en cours... v0.9.1a url du topic = http://forum.ubuntu-fr.org/viewtopic.php?id=831321 id du topic = 831321 récupération du message-liste première page récupérée http://forum.ubuntu-fr.org/viewtopic.php?id=831321 message récupéré pour mise à jour page en cours = 94 recherche des codes imdb sur la page 94 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=94 ['tt1302555', 'tt0188321'] recherche des codes imdb sur la page 95 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=95 ['tt0113118'] recherche des codes imdb sur la page 96 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=96 ['tt0187557', 'tt0084855'] page atteinte : 96 recherche des titres des nouveaux films sur imdb appuyer sur 'o' ou 'n' pour accepter ou refuser un film ['tt0113118', 'tt0187557', 'tt0188321', 'tt0084855'] Balise : tt0113118 --- Accepter le titre : Friday (1995) ?o titre ajouté Balise : tt0187557 --- Accepter le titre : Trois enfants... dans le désordre (1966) ?o titre ajouté Balise : tt0188321 --- Accepter le titre : (Les) brûlés (1959) ?o titre ajouté Balise : tt0084855 --- Accepter le titre : (The) Verdict (1982) ?o titre ajouté recherche imdb terminée nouveaux films : ['Friday (1995)', u'Trois enfants... dans le d\xe9sordre (1966)', u'(Les) br\xfbl\xe9s (1959)', '(The) Verdict (1982)'] message modifié, à envoyer sauvegarde locale ok, liste.bak mis à jour modification du post en cours... misajour.py:447: DeprecationWarning: operating in backwards-compatibility mode forms = ClientForm.ParseResponse(fp) <POST http://forum.ubuntu-fr.org/login.php?action=in application/x-www-form-urlencoded <HiddenControl(form_sent=1) (readonly)> <HiddenControl(redirect_url=/login.php) (readonly)> <TextControl(req_username=)> <PasswordControl(req_password=)> <SubmitControl(<None>=connexion) (readonly)>> opening http://forum.ubuntu-fr.org/edit.php?id=8252041 misajour.py:459: DeprecationWarning: operating in backwards-compatibility mode forms = ClientForm.ParseResponse(fp) <GET http://forum.ubuntu-fr.org/search_ubuntufr.php application/x-www-form-urlencoded <TextControl(q=Recherche rapide....)> <SelectControl(tsearch=[wiki, *forum, planet])> <SubmitControl(<None>=ok) (readonly)>> modification faite ... mise à jour terminée Hors ligne lukophron Re : [python]Monsieur Cinéscript Dernière modification par monsieur cinéma (Aujourd'hui à 18:11) ok cool Je réfléchis à l'interface graphique, qui comportera aussi des améliorations au sujet de la recherche. Mais je ne sais pas si j'aurais le temps avant de repartir en vadrouilles (je peux en avoir plein comme pas du tout). Du coup ça te va pour l'instant ? c'est fonctionnel comme script (intérêt/utilisation/rendu) ? Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Ça me semble bien, il reste à le préserver des malfaisants.... Hors ligne SystemeD Re : [python]Monsieur Cinéscript La mise à jour avec ton bébé est hyper agréable comparé à ce qu'il fallait faire avant tout à la mano.... Hors ligne lukophron Re : [python]Monsieur Cinéscript Ok, tant mieux, on en reste là pour l'instant du coup. Je garde un oeil pour le changement après 100 pages de topic. Ça me semble bien, il reste à le préserver des malfaisants.... c'est-à-dire ? Si tu parles de gars qui postent des fausses balises, oui faut être vigilants. Du coup, c'était bien vu de demander de passer par une validation pendant la mise à jour. Après si c'est fait exprès, ça ne devrait pas durer longtemps après signalement... Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Ok, tant mieux, on en reste là pour l'instant du coup. Je garde un oeil pour le changement après 100 pages de topic.6steme1 a écrit : Ça me semble bien, il reste à le préserver des malfaisants.... c'est-à-dire ? Si tu parles de gars qui postent des fausses balises, oui faut être vigilants. Du coup, c'était bien vu de demander de passer par une validation pendant la mise à jour. Après si c'est fait exprès, ça ne devrait pas durer longtemps après signalement... Je pense que tu devrais effacer toutes les traces du script sur les topics et ne le poster que dans le mail de Monsieur cinéma comme ça seuls les détenteurs du code pourront mettre à jour comme cela se faisait à la main. Dernière modification par 6steme1 (Le 04/11/2012, à 18:44) Hors ligne lukophron Re : [python]Monsieur Cinéscript Je pense que tu devrais effacer toutes les traces du script sur les topics et ne le poster que dans le mail de Monsieur cinéma comme ça seuls les détenteurs du code pourront mettre à jour comme cela se faisait à la main. On en a déjà parlé : Tu ne peux pas faire la mise à jour sans les codes de connexion de Monsieur Cinéma. Ils ne sont pas dans le script, mais dans un des deux fichiers joints. Ces fichiers joints (tchernia et liste.bak) sont effectivement envoyés sur le mail, donc et uniquement aux Messieurs Ciné. Pas de soucis, on peut laisser le script. Pour aller plus loin et t'expliquer avec le code (pas de panique ! on va faire simple ! euh, enfin essayer... ) : Une fonction en prog c'est comme une fonction en math, elle prend une ou plusieurs valeurs et te renvoie une ou plusieurs valeurs. Ca, c'est la fonction qui modifie la liste sur le forum : def = fonction modifpost = nom de la fonction entre parenthèse, les variables def modifpost(msg, login, password, postid): [...] tu vois 'login' et 'password' ? bon, ce sont des variables, j'aurais pu les appeler x et y mais c'est moins clair ^^. Elles ont une valeur. Cette valeur est définie là : def main(): [...] f = open('tchernia','r') url = f.readline().rstrip('\n\r') login = f.readline().rstrip('\n\r') password = f.readline().rstrip('\n\r') f.close() [...] la fonction principale ouvre le ficher 'tchernia' (open('tchernia')), lit les lignes (readline), et y trouve l'adresse web du topic cinéma, le login et mot de passe de Monsieur Cinéma. Donc ces codes d'accès ne sont pas directement dans le script. Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Ok, vu ! J'avais zappé les deux fichiers. Sinon, les fonctions dans le Pascal, c'est pareil et je connais ! Hors ligne lukophron Re : [python]Monsieur Cinéscript ok, ok ! Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne lukophron Re : [python]Monsieur Cinéscript 6steme1 tu peux faire la mise à jour stp ? (tant que je suis dispo) normalement en deux fois : une pour l'ancien topique et passer au nouveau, la deuxième pour le nouveau topique. avec les retours ici stp ! Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Aïe ! (3eme essai) ~/Bureau/monsieur cinema$ ./misajour.py mise à jour en cours... v0.9.1a url du topic = http://forum.ubuntu-fr.org/viewtopic.php?id=831321 id du topic = 831321 récupération du message-liste première page récupérée http://forum.ubuntu-fr.org/viewtopic.php?id=831321 message récupéré pour mise à jour page en cours = 104 recherche des codes imdb sur la page 104 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=104 ['tt0330229', 'tt0084516', 'tt0217869'] topic fermé, recherche du nouveau topic <p>Messieurs dames, <a href="http://forum.ubuntu-fr.org/viewtopic.php?pid=11591061#p11591061">on ferme</a>.</p> Nouveau topic détecté: http://forum.ubuntu-fr.org/viewtopic.php?pid=11591061#p11591061 page atteinte : 1 recherche des titres des nouveaux films sur imdb appuyer sur 'o' ou 'n' pour accepter ou refuser un film [] recherche imdb terminée pas de nouveau film, donc message modifié, à envoyer sauvegarde locale ok, liste.bak mis à jour Topic changé, recherche du nouveau post récupération du message-liste première page récupérée http://forum.ubuntu-fr.org/viewtopic.php?id=11591061#p11591061 liste imdb absente ? liste de titres absente ? ID du post introuvable Traceback (most recent call last): File "./misajour.py", line 572, in <module> main() File "./misajour.py", line 547, in main postid = recupost('http://forum.ubuntu-fr.org/viewtopic.php?id='+tid)[2] File "./misajour.py", line 226, in recupost raise TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType Hors ligne lukophron Re : [python]Monsieur Cinéscript ha, bah j'm'a trompé d'un caractère ! change ça, et roule ! (je crois...) sed -i '/newurl/ s/&p/#p/' /CHEMIN/VERS/FICHIER/misajour.py misajour.py edit explicative :première ligne "sed..." pour changer '&p' en '#p' Dernière modification par lukophron (Le 23/11/2012, à 18:36) Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne SystemeD Re : [python]Monsieur Cinéscript Retour : ~/Bureau/monsieur cinema$ ./misajour.py mise à jour en cours... v0.9.1a url du topic = http://forum.ubuntu-fr.org/viewtopic.php?id=831321 id du topic = 831321 récupération du message-liste première page récupérée http://forum.ubuntu-fr.org/viewtopic.php?id=831321 message récupéré pour mise à jour page en cours = 104 recherche des codes imdb sur la page 104 http://forum.ubuntu-fr.org/viewtopic.php?id=831321&p=104 ['tt0330229', 'tt0084516', 'tt0217869'] topic fermé, recherche du nouveau topic <p>Messieurs dames, <a href="http://forum.ubuntu-fr.org/viewtopic.php?pid=11591061#p11591061">on ferme</a>.</p> Nouveau topic détecté: http://forum.ubuntu-fr.org/viewtopic.php?pid=11591061#p11591061 page atteinte : 1 recherche des titres des nouveaux films sur imdb appuyer sur 'o' ou 'n' pour accepter ou refuser un film [] recherche imdb terminée pas de nouveau film, donc message modifié, à envoyer sauvegarde locale ok, liste.bak mis à jour Topic changé, recherche du nouveau post récupération du message-liste première page récupérée http://forum.ubuntu-fr.org/viewtopic.php?id=11591061#p11591061 liste imdb absente ? liste de titres absente ? ID du post introuvable Traceback (most recent call last): File "./misajour.py", line 572, in <module> main() File "./misajour.py", line 547, in main postid = recupost('http://forum.ubuntu-fr.org/viewtopic.php?id='+tid)[2] File "./misajour.py", line 226, in recupost raise TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType Hors ligne lukophron Re : [python]Monsieur Cinéscript bon, pas sûr que tu ais fait le 'sed'... mais c'est ma faute, j'aurais dû tester avant d'inclure ces modif' la dernière fois. J'ai pas le temps là, je verrai ça ce we tu peux faire la mise à jour en changeant la première ligne du fichier tchernia remplace http://forum.ubuntu-fr.org/viewtopic.php?id=831321 par http://forum.ubuntu-fr.org/viewtopic.php?id=1112581 en ne modifiant rien d'autre (pas de nouvelle ligne, espace, etc) Le danger avec les glands est qu'ils prennent racines. Corneille Hors ligne
In my project (using Python, Html & Jinja2) I have a home_page with movie pictures that each picture leads to a specific page with the movie data. When I try to present the page with the movie data I'm getting the following error(I tried to remove each element such as removing moving.summary and the error then flagged on the above paramter): Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__ rv = self.handle_exception(request, response, e) File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1530, in __call__ rv = self.router.dispatch(request, response) File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1102, in __call__ return handler.dispatch() File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "C:\Users\User\Desktop\imovie-good\main.py", line 77, in get self.response.out.write(template.render(template_values)) File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 894, in render return self.environment.handle_exception(exc_info, True) File "C:\Users\User\Desktop\imovie-good\movie_data.html", line 7, in top-level template code <td> Movie Name: {{movie_data.name}}</td> UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128) This is my python code: import webapp2 import jinja2 import os import datetime import time import cgi from google.appengine.ext import db from google.appengine.api import users from google.appengine.api import images jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) class Movie(db.Model): name = db.StringProperty() release_date = db.StringProperty() duration = db.StringProperty() director = db.StringProperty() actors = db.StringProperty(multiline=True) summary = db.StringProperty(multiline=True) picture = db.BlobProperty() trailer = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class Movie_Data(webapp2.RequestHandler): def get(self): movie_key = self.request.get('movie_key') movie_data = Movie.get(movie_key) template_values = {'movie_data': movie_data} template = jinja_environment.get_template('movie_data.html') self.response.out.write(template.render(template_values)) class Image(webapp2.RequestHandler): def get(self): movie = db.get(self.request.get('img_id')) if movie.picture: self.response.headers['Content-Type'] = 'image/jpeg' self.response.out.write(movie.picture) else: self.response.out.write("No Image") class Main(webapp2.RequestHandler): def get(self): movies = db.GqlQuery("SELECT * " "FROM Movie " "ORDER BY release_date DESC LIMIT 5") template_values = { 'movies': movies} template = jinja_environment.get_template('home_page.html') self.response.out.write(template.render(template_values)) class Admin(webapp2.RequestHandler): def get(self): template_values = {} template = jinja_environment.get_template('admin.html') self.response.out.write(template.render(template_values)) def post(self): name = self.request.get('name') release_date = self.request.get('release_date') c = time.strptime(release_date,"%m/%d/%Y") release_date = time.strftime("%m%d%Y",c) duration = self.request.get('duration') director = self.request.get('director') actors = self.request.get('actors') summary = self.request.get('summary') picture = self.request.get('img') trailer = self.request.get('trailer') movie = Movie(key_name = name) movie.release_date = release_date movie.duration = duration movie.director = director movie.actors = actors movie.summary = summary movie.picture = db.Blob(picture) movie.trailer = trailer movie.put() self.redirect('/') app = webapp2.WSGIApplication([('/admin', Admin), ('/', Main), ('/img', Image), ('/movie_data', Movie_Data)], debug=True) This is my html for the home_page: <html> <body> <table> <th>Top Movies</th> {% for movie in movies %} <tr> <td>{{movie.key().name() }} &nbsp</td> </tr> <tr> <td><a href = "/movie_data?movie_key = {{movie.key()}}"> <img src = "/img?img_id={{movie.key()}}"> </td> </tr> {% endfor %} <a href = "/admin">admin</a> </table> </body> </html> This is my movie_data html code: <html> <body> <div> <table> <tr> <td rowspan ="6">{{ movie_data.picture }}</td> <td> Movie Name: {{movie_data.name}}</td> </tr> <tr> <td> Release Date: {{movie_data.release_date}}</td> </tr> <tr> <td> Duration (minutes): {{movie_data.duration}}</td> </tr> <tr> <td> Director: {{movie_data.director}}</td> </tr> <tr> <td> Actors: {{movie_data.actors}}</td> </tr> <tr> <td> Summary: {{movie_data.summary}}</td> </tr> <tr> <td colspan ="2"> {{movie_data.trailer}} </td> </table> </div> </body> </html>
/proc/$pid/maps /proc/$pid/mem shows the contents of $pid's memory mapped the same way as in the process, i.e., the byte at offset x in the pseudo-file is the same as the byte at address x in the process. If an address is unmapped in the process, reading from the corresponding offset in the file returns EIO (Input/output error). For example, since the first page in a process is never mapped (so that dereferencing a NULL pointer fails cleanly rather than unintendedly accessing actual memory), reading the first byte of /proc/$pid/mem always yield an I/O error. The way to find out what parts of the process memory are mapped is to read /proc/$pid/maps. This file contains one line per mapped region, looking like this: 08048000-08054000 r-xp 00000000 08:01 828061 /bin/cat 08c9b000-08cbc000 rw-p 00000000 00:00 0 [heap] The first two numbers are the boundaries of the region (addresses of the first byte and the byte after last, in hexa). The next column contain the permissions, then there's some information about the file (offset, device, inode and name) if this is a file mapping. See the proc(5) man page or Understanding Linux /proc/id/maps for more information. Here's a proof-of-concept script that dumps the contents of its own memory. #! /usr/bin/env python import re maps_file = open("/proc/self/maps", 'r') mem_file = open("/proc/self/mem", 'r', 0) for line in maps_file.readlines(): # for each mapped region m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r])', line) if m.group(3) == 'r': # if this is a readable region start = int(m.group(1), 16) end = int(m.group(2), 16) mem_file.seek(start) # seek to region start chunk = mem_file.read(end - start) # read region contents print chunk, # dump contents to standard output maps_file.close() mem_file.close() /proc/$pid/mem If you try to read from the mem pseudo-file of another process, it doesn't work: you get an ESRCH (No such process) error. The permissions on /proc/$pid/mem (r--------) are more liberal than what should be the case. For example, you shouldn't be able to read a setuid process's memory. Furthermore, trying to read a process's memory while the process is modifying it could give the reader an inconsistent view of the memory, and worse, there were race conditions that could trace older versions of the Linux kernel (according to this lkml thread, though I don't know the details). So additional checks are needed: The process that wants to read from /proc/$pid/mem must attach to the process using ptrace with the PTRACE_ATTACH flag. This is what debuggers do when they start debugging a process; it's also what strace does to a process's system calls. Once the reader has finished reading from /proc/$pid/mem, it should detach by calling ptrace with the PTRACE_DETACH flag. The observed process must not be running. Normally calling ptrace(PTRACE_ATTACH, …) will stop the target process (it sends a STOP signal), but there is a race condition (signal delivery is asynchronous), so the tracer should call wait (as documented in ptrace(2)). A process running as root can read any process's memory, without needing to call ptrace, but the observed process must be stopped, or the read will still return ESRCH. In the Linux kernel source, the code providing per-process entries in /proc is in fs/proc/base.c, and the function to read from /proc/$pid/mem is mem_read. The additional check is performed by check_mem_permission. Here's some sample C code to attach to a process and read a chunk its of mem file (error checking omitted): sprintf(mem_file_name, "/proc/%d/mem", pid); mem_fd = open(mem_file_name, O_RDONLY); ptrace(PTRACE_ATTACH, pid, NULL, NULL); waitpid(pid, NULL, 0); lseek(mem_fd, offset, SEEK_SET); read(mem_fd, buf, _SC_PAGE_SIZE); ptrace(PTRACE_DETACH, pid, NULL, NULL); I've already posted a proof-of-concept script for dumping /proc/$pid/mem on another thread.
cledesol Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Merci de cette précision. C'est vrai aussi qu'en général c'est le soir que je me loggue sur mon PC .... Donc, la météo du jour ... je l'ai vue en réel CM : Asus M4A88TD-M µ : AMD Phenom II X6 1055T / RAM 4 Go Video : EVGA GeForce GTS450 1Go - Ubuntu 64 bits Version 14.04 avec Unity Notebook Asus A2500D Dual boot Ubuntu et Xubuntu 14.04 Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Merci de cette précision. C'est vrai aussi qu'en général c'est le soir que je me loggue sur mon PC .... Donc, la météo du jour ... je l'ai vue en réel moi c'est le contraire, mais je crois que météo France auras plus pour vocation de test qu'autre chose (il me fatigue à modifier le nombre d'info toutes la journée). Je vais voir ce que je peut faire avec un site plus contant dans sont nombres d'infos journalière, ce sera certainement previmeteo.com car après tous, ils nous propose plein de façon différent de récupérer les infos météo. Hors ligne cledesol Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Tu as raison; c'est pénible de programmer quand les données en entrées ne sont pas constantes. Je ne connaissais pas le site "previmeteo", mais il a l'air pas mal du tout. Bon courage pour la suite. Si tu veux que je teste, pas de problème. CM : Asus M4A88TD-M µ : AMD Phenom II X6 1055T / RAM 4 Go Video : EVGA GeForce GTS450 1Go - Ubuntu 64 bits Version 14.04 avec Unity Notebook Asus A2500D Dual boot Ubuntu et Xubuntu 14.04 Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Me revoilà de retour sur les ondes. Tout d'abord un grand bravo à Didier-T et Levi59 pour le travail effectué sur les scripts. N'étant pas en mesure moi-même de faire grand chose sur les scripts, je me contente donc de tester et de faire part de mes remarques afin de les perfectionner ou les modifier. Tout d'abord une petite impression d'écran pour expliciter les 2 bugs que je rencontre :1/ Affichage des icônes du vent Comme je l'ai déjà indiqué, lorsque je lance le conky en terminal, j'ai régulièrement un message d'erreur du genre : cp: la cible «/home/gilles/conky/meteo/images/conky/v1.png» n'est pas un répertoire cp: la cible «/home/gilles/conky/meteo/images/conky/v4.png» n'est pas un répertoire Ce qui se traduit par le fait que les icônes du vent qui déclenchent ce message d'erreur ne sont pas actualisées. Du coup, nous avons des icônes qui ne correspondent pas à la direction du vent. Cela se produit sur certaines icônes, et de manière aléatoire. Ce ne sont pas toujours les mêmes qui posent problème. On voit ici des icônes de vent d'Est, avec une description de vent SE. Le problème viendrait peut être du script de formatage des icônes ? Ou bien suis je le seul à avoir ce bug ? Tant que nous sommes dans les icônes du vent, est il possible d'avoir, comme cela se passait avec conkyForecast, des icônes de différentes couleurs en fonction de la force du vent ? Car actuellement, ce n'est pas le cas, elles sont toujours vertes, y compris pour du vent de + de 50 km/h2/ Affichage du pourcentage de probabilité de pluie: Comme cela est visible sur l'impression d'écran, j'ai un bug graphique avec un petit rectangle rouge pour tous les chiffres des pourcentage de pluie pour les soirées, ce qui correspond aux chiffres des lignes paires sur le fichier 'precipitation'. J'ai tout essayé pour tenter d'effacer ce bug, rien n'y fait. Si je demande d'afficher uniquement un chiffre d'une ligne paire, ce bug est toujours présent. Est il possible de régler ce problème ?3/ Améliorations possibles du script : Etant donné que le code de la localité est défini dans le shell du script, je pense qu'il pourrait être intéressant d'extraire 2 données du fichier ICS : Le nom de la localité et ses coordonnées : BEGIN:VEVENT SEQUENCE:1 CLASS:PUBLIC CREATED:20111028T000000Z LAST-MODIFIED:20111028T000000Z GEO:43.45000076;5.23000002 UID:1319803200-0-0 DTSTAMP:20111028T120000Z DTSTART;VALUE=DATE:20111028 ORGANIZER;CN=Weather Underground:MAILTO:support@wunderground.com DESCRIPTION:Friday - Partly Cloudy. High 21 C Wind SE 32 km/h. \nFriday Night - Chance of Rain. Low 15 C Wind East 32 km/h.Chance of precipitation 20%. LOCATION:Marseille\, France A savoir les lignes 'GEO' et 'LOCATION' (la mention du pays est superflue). Ainsi, il est possible de les appeler et les faire afficher dans le conky. Concernant les températures : Dans le fichier messages.wun les températures sont précédées des mentions 'Maxi' ou 'Mini'. Ces mentions peuvent toujours être rentrées 'à la main' dans le conky. Il me semble plus intéressant que de n'extraire que les données chiffrées brutes, et donc supprimer ces mention maxi ou mini du fichier messages.wun Traductions dans le script : Rajouter 'Rain' 'Pluie' - Changer 'Clear' 'Ensoleillé' par 'Clear' 'Dégagé' car, la nuit, ensoleillé ne veut rien dire.4/ Evolution du script Qu'il s'agisse du script wunderground ou celui de Météo France sur lequel travaillait Didier-T : Dans les 2 cas nous n'avons que l'affichage de prévisions, et en aucun cas l'affichage des données météo en live. Aussi, il me semble intéressant de rajouter ces données là (qui peuvent se substituer à la 1° partie du messages.wun, qui sont les prévisions de la journée. Pour ce faire, j'ai trouvé un script python, qui permet d'aller chercher la T° et les conditions météo en cours chez Wunderground. Le voici : #!/usr/bin/python # # Fetches Weather info from Weather Underground # # Usage: ./wundergound.py zipcode # # International: # * Go to http://www.wunderground.com/ # * Find your city # * Click the RSS icon # * Station ID is the number that follows /stations/ in the url # # # Values are either True or False metric=True international=True import sys import feedparser def usage(): print("Usage:") if international: print(" ./wunderground.py StationID") else: print(" ./weunderground.py zipcode") sys.exit(1) if not len(sys.argv) == 2: usage() location=sys.argv[1] if international: url="http://rss.wunderground.com/auto/rss_full/global/stations/" else: url="http://rss.wunderground.com/auto/rss_full/" feed=feedparser.parse(url+location) if not feed.feed: # Assume Error print("Error") sys.exit(1) current=feed['items'][0].title if metric: temp=current.split(",")[0].split(":")[1].split("/")[1].strip() else: temp=current.split(",")[0].split(":")[1].split("/")[0].strip() condition=current.split(",")[1].split("-")[0].strip() print(temp, "-", condition) Je pense qu'il est également possible par le même biais d'aller chercher les données relatives au vent... Les problèmes à régler avec ce script sont les suivants : Comment faire afficher ces données dans le conky ? Une ligne telle que celle ci dans le conky ${execi 600 /home/chemin du conky/wunderground 'zip code'} fait apparaître une ligne d'affichage avec Température - condition météo. C'est pas terrible. Comment faire associer les conditions météo avec l'icône du temps qui y est associée ? Je laisse ces questions à toute la connaissance dans l'écriture des scripts des spécialistes Je suis prêt à tester toutes les propositions qui seront faites ! The ship is sinking normally... Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Bonjour Phyllinux, Pour ton soucis n°2 tu peut tenter de changer de police de caractère, sa devrais régler le problème. pour le reste il faudrait que tu compresse ton répertoire de travail pour le mettre en ligne, et que tu nous fournisses ton conkyrc. Bien sure je prend bonne note de tes remarques pour la suite. Je savais pas que les icônes de vent changeaient de couleur en fonction de la vitesse (pourrais tu m'indiquer les paliers). Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) J'ai essayé de changer la police, mais pas d'évolution . J'ai toujours le même bug, quelle que soit la police utilisée. Concernant les couleurs en fonction des vitesses du vent, je ne sais pas quels sont les paliers définis dans conkyforecast, et je n'ai pas réussi à trouver dans quel fichier cela était défini. Je pense cependant que l'on peut partir sur la base suivante : De 0 à 25 : Vert De 26 à 50 : Orange > 50 km/h : Rouge Pour le répertoire de travail, je fais un fichier et je le poste tout à l'heure The ship is sinking normally... Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Voici le répertoire compressé : C'est le répertoire Conky, qui est directement dans mon Home Répertoire conky pour test En dernière ligne du conky se rajoute le lien vers le script d'affichage de carte satellite dont je n'ai pas mis le script dans cette archive The ship is sinking normally... Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ Phyllinux bon pour le problème des icônes vent tu met a la fin de ton DirShell un / dans le fichier formatage-icones-meteo.sh (retire le sa devrais régler le problème) DirShell="$HOME/conky/meteo" Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Non, j'ai fait la modif, et cela ne règle rien du tout. Aujourd'hui, je n'ai qu'une seule icône qui pose problème, celle du vent pour la soirée du jour en cours (la v2.png): gilles@ubuntu:~$ conky -c /home/gilles/conky/meteo/conkyrc1 Conky: forked to background, pid is 27310 gilles@ubuntu:~$ Conky: desktop window (1400045) is subwindow of root window (102) Conky: window type - override Conky: drawing to created window (0x6600001) Conky: drawing to double buffer cp: la cible «/home/gilles/conky/meteo/images/conky/v2.png» n'est pas un répertoire Mais comme je disais, c'est aléatoire, je peux très bien avoir ce message d'erreur pour 5 ou 6 icônes du vent The ship is sinking normally... Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ Phyllinux, essai ceci toujours le même script (c'est lui qui pose probleme) il faut modifier la ligne suivante (ligne 27) cp ${DirShell}/images/vent/$fichier.png ${DirShell}/images/conky/v$n.png en cp "${DirShell}/images/vent/$fichier.png" ${DirShell}/images/conky/v$n.png sa devrait fonctionner chez moi sa règle définitivement le problème. Dernière modification par Didier-T (Le 05/11/2011, à 17:04) Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Un problème de réglé Plus de message d'erreur pour les icônes du vent ! Bravo Ne pas oublier de mettre à jour les fichiers au début du topic The ship is sinking normally... Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Sinon, il y a une autre alternative. Au lieu de Weather Underground, Météo France, Weather.com, il existe aussi ACCUWEATHER. Et avec le dernier script de TeoBigusGeekus, on peut arriver à cela : Au passage, on voit que c'est un début de semaine pourri sur La Canebière! Pour la marche à suivre, voir ici : conky Accuweather post #2 Si quelqu'un sait retravailler le script pour pouvoir traduire les 'Conditions Météo' (Pluie, Soleil, Couvert...), ainsi que les jours, je suis preneur, ainsi que TeoBigusGeekus d'ailleurs Je recherche également comment extraire les icônes, les conditions météo et les températures pour pouvoir les insérer dans un autre conky (l'horloge avec la météo intégrée qui tourne actuellement sous conkyforecast). Je sais qu'il est toujours possible de faire afficher les points qui m'intéressent en faisant tourner le script et en allant les chercher. Mais c'est aussi simple si ils sont dans un fichier généré (à l'image du fichier messages.wun). Merci pour vos propositions The ship is sinking normally... Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ Phyllinux, Tu peut obtenir les infos directement en français sans avoir à les traduire, il suffit de sélectionner la langue désirée dans le menu "Select Your Language" pour toi l'adresse web est Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Bonjour a tous, j'ai regardé le script que nous indiquait Phyllinux dans sont dernier post. fichier "acc_int_images" après quelque modification pour qu'il fonctionne correctement sur les pages météo en français du site accuweather.com acc_int_images #!/bin/bash # Modifié par Didier-T (forum.ubuntu-fr.org) pour utilisation sur les pages française de Accuweather DirShell="$HOME/Accuweather_Conky_Int_Images" #copier votre adresse Accuweather ici address="http://www.accuweather.com/fr/fr/%c3%aele-de-france/argenteuil/quick-look.aspx" #function: test_image test_image () { case $1 in 1) echo 1su ;; 2) echo 2msu ;; 3) echo 3psu ;; 4) echo 4ic ;; 5) echo 5h ;; 6) echo 6mc ;; 7) echo 7c ;; 8) echo 8d ;; 11) echo 9f ;; 12) echo 10s ;; 13) echo 11mcs ;; 14) echo 12psus ;; 15) echo 13t ;; 16) echo 14mct ;; 17) echo 15psut ;; 18) echo 16r ;; 19) echo 17fl ;; 20) echo 18mcfl ;; 21) echo 19psfl ;; 22) echo 20sn ;; 23) echo 21mcsn ;; 24) echo 22i ;; 25) echo 23sl ;; 26) echo 24fr ;; 29) echo 25rsn ;; 30) echo 27ho ;; 31) echo 28co ;; 32) echo 26w ;; 33) echo 29cl ;; 34) echo 31mcl ;; 35) echo 32pc ;; 36) echo 33ic ;; 37) echo 34h ;; 38) echo 35mc ;; 39) echo 36pcs ;; 40) echo 37mcs ;; 41) echo 38pct ;; 42) echo 39mct ;; 43) echo 40mcfl ;; 44) echo 41mcsn ;; esac } kill -STOP $(pidof conky) killall wget rm ${DirShell}/*.png rm ${DirShell}/messages_raw wget --save-cookies ${DirShell}/cookie -O ${DirShell}/curr_cond_raw $address addr_week=$(echo $address|sed 's/quick.*$/forecast.aspx/') wget --load-cookies ${DirShell}/cookie -O ${DirShell}/week_raw $addr_week #Current Conditions - curr_cond file egrep -i 'CurrentTemp|CurrentText|RealFeelValue|WindsValue|HumidityValue|DewPointValue|PressureValue|PressureTenValue|VisibilityValue|SunriseValue|SunsetValue|imgCurConCondition' ${DirShell}/curr_cond_raw > ${DirShell}/curr_cond sed -i 's/\(^.*blue\/\|_int.*$\|^.*">\|<\/span>.*$\|&deg;C\)//g' ${DirShell}/curr_cond curr_cond_raw_image=$(sed -n 1p ${DirShell}/curr_cond) sed -i 1s/$curr_cond_raw_image/$(test_image $curr_cond_raw_image)/ ${DirShell}/curr_cond cp ${DirShell}/Forecast_Images/$(sed -n 1p ${DirShell}/curr_cond).png ${DirShell}/cc.png sed -i 's/Unavailable/N\/A/g' ${DirShell}/curr_cond #Forecast of the week - week file egrep -i 'lundi|mardi|mercredi|jeudi|vendredi|samedi|dimanche|&deg|lblDesc|imgIcon' ${DirShell}/week_raw > ${DirShell}/week sed -i '1d' ${DirShell}/week sed -i 's/\(^.*lblDate">\|^.*lblDesc">\|^.*Label1">\|^.*lblRealFeel">\|^.*lblHigh">\|^.*lblRealFeelValue">\|^.*blue\/\|_int.jpg.*$\|<\/span>.*$\|&deg;C\)//g' ${DirShell}/week sed -i -e 's/[lL]undi/LUNDI/' -e 's/[Mm]ardi/MARDI/' -e 's/[Mm]ercredi/MERCREDI/' -e 's/[Jj]eudi/JEUDI/' -e 's/[Vv]endredi/VENDREDI/' -e 's/[Ss]amedi/SAMEDI/' -e 's/[Dd]imanche/DIMANCHE/' ${DirShell}/week for (( i=2; i<=67; i+=5 )) do sed -i "${i}s/ .*$//" ${DirShell}/week done for (( i=1; i<=66; i+=5 )) do image_raw=$(sed -n "${i}"p ${DirShell}/week) sed -i ${i}s/$image_raw/$(test_image $image_raw)/ ${DirShell}/week cp ${DirShell}/Forecast_Images/$(sed -n ${i}p ${DirShell}/week).png ${DirShell}/$i.png done #messages and messages_curr files for (( i=3; i<=68; i+=5 )) do sed -n ${i}p ${DirShell}/week >> ${DirShell}/messages_raw done sed -n 1p ${DirShell}/messages_raw | cut -c -60 > ${DirShell}/messages_curr sed -n 8p ${DirShell}/messages_raw | cut -c -60 >> ${DirShell}/messages_curr for (( i=1; i<=4; i++)) do no=$(sed -n ${i}p ${DirShell}/messages_curr|wc -m) if (( no<=31 )); then sed -i $i"s/$/\n/" ${DirShell}/messages_curr i=$((i+1)) elif (( no>31 )); then sed -i $i"s/^\(.\{31\}\)/\1\n/" ${DirShell}/messages_curr i=$((i+1)) fi done cat ${DirShell}/messages_raw | cut -c -40 > ${DirShell}/messages for (( i=1; i<=28; i++)) do no=$(sed -n ${i}p ${DirShell}/messages|wc -m) if (( no<=21 )); then sed -i $i"s/$/\n/" ${DirShell}/messages i=$((i+1)) elif (( no>21 )); then nbesp=$(awk '{ x=0; x+=gsub("\\ ",""); print x }' ${DirShell}/messages | sed -n "$(($i))p") pos=$(($(($nbesp/2))+1)) sed -i $i"s/ /\n/$pos" ${DirShell}/messages i=$((i+1)) fi done kill -CONT $(pidof conky) Une petite capture pour montrer le resultat Dernière modification par Didier-T (Le 06/11/2011, à 12:10) Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ Didier-T On y est presque ! La seule information non traduite, c'est celle des conditions météo du moment, comme on peut le voir sur cette capture d'écran : PARTLY SUNNY, ça fait pas trop marseillais comme langue The ship is sinking normally... Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) En s'actualisant, la traduction s'est faite : PARTLY SUNNY est devenu Partiellement Ensoleillé (Même la casse s'est modifiée : De tout majuscule, on est passé à 1° lettre en majuscule, le reste en minuscule). Il ne me reste donc plus qu'à voir comment extraire les données qui m'intéressent pour les basculer également sur mon autre conky : Je serai prêt avant la fermeture de l'accès aux données de weather.com The ship is sinking normally... Hors ligne olitask Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Bonjour En passant à ocelot, je me suis dit que j'allais améliorer mon conky jusque là assez sommaire. Je suis assez déçu de voir se mélanger les posts pour les différents services de meteo ( méteofrance, accuweather wunderground ... ) Pour tout dire, et sans vouloir vous vexer car vous faite bien avancer les choses, c'est vraiment le boxon dans ce thread . Je ne sais pas si c'est possible d'améliorer les choses en regroupant les infos pour chaque fournisseur dans un seul message; enfin passons. Pour en revenir à conky Je tente d'installer le conky de Didier T post 21 et j'ai qqs problèmes -Il semble manquer des icones (celles du repertoire /conky ( les autres étant dispatchées dans différant messages... pas tres pratique ) - il ne semble pas trouver les infos sur le site, pour calais le code est bien 621930 ?? -j'ai ce message d'erreur : sed: impossible de lire /home/olivier/.conky//tt: Aucun fichier ou dossier de ce type Conky: Unable to load image '/home/olivier/.conky/conky/j1.gif' ps j'ai modifié le répertoire test en .conky voilà. Bon dimanche Olivier Dernière modification par olitask (Le 06/11/2011, à 17:33) Hors ligne olitask Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Rebonjour Juste pour rajouter un site qui permet aussi d'avoir les prévisions météorologiques ( les prédictions météorologiques étant un terme réservées à meteo france AMHA) . Il s'agit de www.windguru.cz Il est très utilisé pour les sports nautiques ( voile, kitesurf...). Un utilisateur a déjà tenté de faire qq chose : voir ici Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ olitask, bonjour pour commencer le conky météo france est une impasse car le nombre d'infos change au fur et à mesure que la journée avance, mais voici certainement les raisons de tes soucis : Il doit manquer le chemin "/home/olivier/.conky/conky/" qui sert à charger les icônes météo France le chemin indiqué dans ton DirShell est "$HOME/.conky/" supprime le dernier "/" sa ira mieux Oui 621930 correspond bien à ta ville Dernière modification par Didier-T (Le 06/11/2011, à 17:53) Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ Olitask Il est normal que tu trouves ce topic un peu 'brouillon'. En effet, nous cherchons une alternative à conkyForecast, étant donné que les données utilisées par conkyForecast proviennent du site Weather.com, et que l'accès à ces données sera fermé dans très peu de temps. Du coup, nous tâtonnons afin de trouver une solution qui nous convienne. Nous sommes partis sur les possibilités offertes par Weather Underground (alias Wunderground). De là Didier-T a essayé de récupérer les données provenant du site de Météo France, à l'instar de ce qui était fait par le script téléchargeant les données sur Wunderground. De mon côté, tout en continuant à tester les différents scripts, j'ai trouvé une possibilité avec un autre site météo : Celui d'Accuweather. Ce topic est un donc en quelque sorte un 'laboratoire' où tout le monde apporte ses idées et fait part de ce qu'il a pu trouver. Il s'avère qu'actuellement, le conky le plus abouti est celui utilisant le script récupérant les données d'Accuweather. Tu trouveras le lien sur mon post #38. Didier-T a modifié le script afin d'avoir la totalité des données en français (post #40) au lieu de la version originale en langue anglaise. Donc, si tu veux un conky météo fonctionnel et en français, tu peux partir sur ces bases. De mon côté, je tourne avec celui là, sur lequel je rajoute une couche du script réalisé par Didier-T et Levi59 afin d'obtenir en complément le pourcentage de probabilité de pluie (script avec les données de wunderground), étant donné que Accuweather ne fournit pas ces pourcentages dans les fichiers générés par le script. Bon conky The ship is sinking normally... Hors ligne olitask Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Bonsoir Merci de votre réponse. En fait, il a suffit de créer le répertoire conky a coté de /vent et /metéo. Petit problème , le résultat me donne cela : les icônes sont décalées image , cliquer quel est le paramètre qu'il faut modifier ? Je vais me pencher sur accuweather, mais il faut s'enregistrer sur le forum ubuntu anglais ... merci encore Olivier Hors ligne Phyllinux Re : [Conky] Alternative à weather.com ( icones conkyforecast ) @ Didier-T et Levi59 Je suis satisfait du résultat obtenu avec les script d'Accuweather. Merci Teo pour son script d'origine et merci Didier-T pour la modification avec la traduction J'ai réussi à intégrer les données extraites dans mon autre conky qui donne des infos simplifiées pour la météo. (Je lance mes différents conkys par des scripts Nautilus pour afficher ce que je veux quand je le désire, avec un simple clic droit de souris). Sur ce dernier, j'ai ajouté la couche du script wunderground (merci Didier-T et Levi59 pour leur travail ) pour avoir les pourcentages de probabilité de précipitations. Maintenant, pour être pleinement satisfait du résultat obtenu, il ne me manque plus qu'à régler le problème du bug graphique que j'ai déjà présenté (le petit carré qui se rajoute après le chiffre). Ce bug ne touche que les lignes paires du fichier 'precipitation' généré par le script wunderground. J'ai essayé en changeant la police, en changeant l'ordre d'affichage, rien à faire. Dès que je demande d'afficher un pourcentage pour la nuit, j'ai ce petit carré. L'un d'entre vous pourrait il trouver la raison de ce bug ? Si j'arrive à le supprimer, je serais satisfait à 100% du résultat final ! A titre info, si l'un d'entre vous est intéressé, voici ce que cela donne (avec juste l'affichage des pourcentages de probabilités de pluie dans la journée pour la raison évoquée ci dessus). Je pourrais vous poster les différents fichiers nécessaires. @ Olitask Essaye en mettant {voffset -X} en début de la ligne qui te fait afficher les icônes du vent. Par essais multiples en changeant la valeur du X de ton voffset, tu devrais réussir à trouver le bon positionnement voffset (pixels) Change vertical offset by N pixels. Negative values will cause text to overlap. See also $offset. Souce : Variables pour conky The ship is sinking normally... Hors ligne Didier-T Re : [Conky] Alternative à weather.com ( icones conkyforecast ) Bonsoir Merci de votre réponse. En fait, il a suffit de créer le répertoire conky a coté de /vent et /metéo. Petit problème , le résultat me donne cela : les icônes sont décalées image , cliquer quel est le paramètre qu'il faut modifier ? Je vais me pencher sur accuweather, mais il faut s'enregistrer sur le forum ubuntu anglais ... merci encore Olivier en générale ta ligne d'affichage se présente ainsi ${image "chemin vers l'image/nom de limage" -p -x,y -s 90x90} donc x représente l'axe gauche droite (le plus à gauche étant 0) et y représente l'axe haut bas (le plus haut étant 0) bon courage Hors ligne nc2011 Re : [Conky] Alternative à weather.com ( icones conkyforecast ) bonsoir phillinux je viens d'installer ubuntu et n'e connais donc pas grand chose à linux. je cherchais un moyen d'installer la meteo sur le bureau et suis tombé sur vos recherches. pour ma part, je trouve super ta solution du post #41. ma question est la suivante, quelle est la procédure pour pouvoir l'installer sur le bureau. que dois faire du script? j'ai un petit point particulier, je suis en nouvelle caledonie. alors, nouméa est il pris en compte par le site meteo,? d'autre part désolé pour mes horaires d'envois mais je suis décalé de 10 heures avec vous. merci Hors ligne
Test-Driven Development in Python by Jason Diamond 12/02/2004 Introduction Python's unittest Module Motivation Sample Input Getting Started Baby Steps Refactoring Conclusion Introduction Test-driven development is not about testing. Test-driven development is about development (and design), specifically improving the quality and design of code. The resulting unit tests are just an extremely useful by-product. That's all I'm going to tell you about test-driven development. The rest of this article will show you how it works. Come work on a project with me; we'll build a very simple tool together. I'll make mistakes, fix them, and change designs in response to what the tests tell me. Along the way, we'll throw in a few refactorings, design patterns, and object-oriented design principles. To make this project fun, we'll do it in Python. Python is an excellent language for test-driven development because it (usually) does exactly what you want it to without getting in your way. The standard library even comes with everything you need in order to start developing TDD-style. I assume that you're familiar with Python but not necessarily familiar with test-driven development or Python's unittest module. You need to know only a little in order to start testing. Python's unittest Module Since version 2.1, Python's standard library has included a unittest module, based on JUnit (by Kent Beck and Erich Gamma), the de facto standard unit test framework for Java developers. Formerly known as PyUnit, it also runs on Python versions prior to 2.1 with a separate download. Let's jump right in. Here's a "unit" and its tests--all in one file: import unittest # Here's our "unit". def IsOdd(n): return n % 2 == 1 # Here's our "unit tests". class IsOddTests(unittest.TestCase): def testOne(self): self.failUnless(IsOdd(1)) def testTwo(self): self.failIf(IsOdd(2)) def main(): unittest.main() if __name__ == '__main__': main() Lights Throughout this article, I'll use a traffic light to show the state of the tests. Green indicates that the tests pass, and red warns that they fail. A shining yellow light indicates a problem that prevents us from completing a test. TDD practitioners often talk about receiving a "green light" or "green bar" from the graphical test runner that comes with JUnit. Methods whose names start with the string test with one argument (self) in classes derived from unittest.TestCase are test cases. In the above example, testOne and testTwo are test cases. Grouping related test cases together, test fixtures are classes that derive from unittest.TestCase. In the above example, IsOddTests is a test fixture. This is true even though IsOddTests derives from a class called TestCase, not TestFixture. Trust me on this. Test fixtures can contain setUp and tearDown methods, which the test runner will call before and after every test case, respectively. Having a setUp method is the real justification for fixtures, because it allows us to extract common setup code from multiple test cases into the one setUp method. In Python we typically don't need a tearDown method, because we can usually rely on Python's garbage collection facilities to clean up our objects for us. When testing against a database, however, tearDown could be useful for closing connections, deleting tables, and so on. Looking back at our example, the main function defined in the unittest module makes it possible to execute the tests in the same manner as executing any other script. This function examines sys.argv, making it possible to supply command-line arguments to customize the test output or to run only specific fixtures or cases (use --help to see the arguments). The default behavior is to run all test cases in all test fixtures found in the file containing the call to unittest.main. Executing the test script above should produce output that resembles: .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK If the second test had failed, the output would have looked something like this: .F ====================================================================== FAIL: testTwo (__main__.IsOddTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\jason\projects\tdd-py\test.py", line 14, in testTwo self.failIf(IsOdd(2)) File "C:\Python23\lib\unittest.py", line 274, in failIf if expr: raise self.failureException, msg AssertionError ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=1) Typically, we wouldn't have the tests and the unit being tested in the same file, but it doesn't hurt to start out that way and then extract the code or the tests later. Motivation Guess what I have trouble remembering to do: 0 0 * * * [ `date +\%m` -ne `date -d +4days +\%m` ] \ && mail -s 'Pay the rent!' me-and-my-wife@example.org < /dev/null Related Reading That little puzzle is a line out of my crontab that emails me a reminder to pay the rent on the last four days of each month. Pathetic? Probably. It works, though. I haven't been late paying rent since I started using it. As clever as I thought I was for coming up with this, it wasn't practical for everything--especially for events that occur only once. Also, there's no way I could teach my wife enough bash scripting techniques in order to add a reminder to our calendar. Most people use a good old-fashioned wall calendar for this type of thing. That's not techno-geeky enough for me. I could use Outlook or Evolution or some productivity application, but that would open up a whole new can of worms. We don't use just one computer. We both use multiple computers and operating systems at home and at work. How could we easily synchronize all of those machines? It was after realizing that our email is available to us no matter where we were that I hit upon the motivation for my project. The email reminding me to pay the rent was with me no matter what machine I'm on because I always check my email via IMAP, so my email is accessible from everywhere. Why not email the upcoming events in my calendar to me just like my reminder to pay the rent? Brilliant, I thought. I know just the tools that can do this, too: the BSD calendar application and the new kid on the block, pal. My wife and I have a private wiki that we use for keeping track of notes. It's great. Despite the fact that my wife's an accountant and not a geek, she has no trouble using it. I figured we could use the wiki to edit our calendar file. I would write a little cron job to fetch the calendar file--probably using wget--from the wiki and pipe that into whatever tool best fit our needs. Unfortunately, after looking at both calendar and pal, I discovered that neither was what I was looking for. The calendar file format requires a <tab> character between dates and descriptions. Since I wanted to use our personal wiki to edit the calendar file, inserting <tab> characters would be an issue (upon hitting <tab>, focus jumps out of the text area to the next form control). calendar also doesn't support any of the fancy output options that pal does. The pal format was much too geeky for even me to want to use, and it didn't support the one really important use case I had so far: setting a reminder for the last day of the month. Sample Input My wife and I sat down and came up with something both of us would want to use. Here are some examples: 30 Nov 2004: Dinner with the Darghams. April 10: Happy Anniversary! Wednesday: Piano lesson. Last Thursday: Goody night at book study. Yum. -1: Pay the rent! Unlike the calendar format, a colon separates dates from descriptions. How Pythonic. Like the calendar format, omitted certain fields are wildcards. The April 10 event happens every year. The Last Thursday event happens on the final Thursday of every month of every year. The -1 event happens on the last day of every month of every year too. I took this idea from Python's array subscript syntax, where foo[-1] selects the last element in the foo array. I thought it was a little geeky, but my wife understood it right away. My goal is to write a small application that can run from cron to read a file in this format and email my wife and me the events we have scheduled for the next seven days. That shouldn't be too hard, should it? From this point on, I'm writing this article in real time, having contrived nothing. I didn't write the code first and then write the article--I'm writing the article as I write the code. Yes, I expect to make mistakes. In fact, I'm counting on it. Making mistakes is the best way to learn. Getting Started Being test infected means that I must write this tool by writing all of my unit tests before writing the code I expect the tests to exercise. The first thing I do when starting a new project is to create an empty fixture that fails: import unittest class FooTests(unittest.TestCase): def testFoo(self): self.failUnless(False) def main(): unittest.main() if __name__ == '__main__': main() I do this out of habit, just to make sure I have everything typed in correctly and to test that the test runner can find the fixture. Notice the class named FooTests and its testFoo method. At this point I have no idea what I'm going to test first. I just want to make sure that I have everything ready once things get going. Let's start out easy and test the first example from above with the full day, month, and year specified for the event. In order to create this test, I need know what to test. Am I testing a class? A function? This is where we put on our designer hats for a brief moment and try to use our experience and intuition to come up with some piece to the puzzle that will help us reach our goal. It's OK if we make a mistake here; the tests will reveal that right away, before we invest too much in this design. We certainly don't want to draft any documents filled with diagrams. Save those for later, after we have a clue about what will actually work. For this project, I should probably create objects that can say whether they "match" a given date. These objects will act as a "pattern" for dates. (I'm using regular expressions as a metaphor here.) Eventually, I'll have to write a parser that will read in a file and create these pattern objects, but I'll do that later. These pattern objects are probably an easier place to start. There might be multiple types of patterns--but I won't think about that now, because I could be wrong. Instead, I'll start coding so I can let it tell me what it wants to become: def testMatches(self): p = DatePattern(2004, 9, 28) d = datetime.date(2004, 9, 28) self.failUnless(p.matches(d)) Notice that I changed the name of the method from testFoo to something more appropriate, because I now have an idea about what to test. I've also invented a class name, DatePattern, and a method name, matches. (The datetime module is part of Python 2.3 and up--I had to import it at the top of my file in order to use it.) This test, of course, fails miserably--the DatePattern class doesn't even exist yet! But I at least know now the name of the class I need to implement. I also know the name and signature of one of its methods and the signature for its __init__ method. Here's what I can do with this knowledge: class DatePattern: def __init__(self, year, month, day): pass def matches(self, date): return True Now the test passes! It's time to move on to the next test. You probably think I'm joking, don't you? I'm not. Baby Steps Test-driven development is best when you move in the smallest possible increments. You should only be writing code that makes the current failing test case(s) pass. Once the tests pass, you're done writing code. Stop! The above code is worthless, right? It basically says that every pattern matches every date. How can I justify spending the time to come up with a "real" implementation? By adding another test: def testMatchesFalse(self): p = DatePattern(2004, 9, 28) d = datetime.date(2004, 9, 29) self.failIf(p.matches(d)) We now have one passing test and one failing test. I could change the matches method to return False in order to make this new test case pass, but that would break the old one! I now have no choice but to implement DatePattern correctly so that both tests can pass. Here's what I came up with: class DatePattern: def __init__(self, year, month, day): self.date = datetime.date(year, month, day) def matches(self, date): return self.date == date Both tests now pass. Woo-hoo! I'm not happy with the DatePattern class, though. So far, it's nothing more than a simple wrapper around Python's date class. Why am I not just using date instances for my "patterns"? It might turn out that the DatePattern class is unnecessary, but I'm not going to make that decision on my own. Instead, I'm going to write another test--one that I think will confirm the necessity of the DatePattern class: def testMatchesYearAsWildCard(self): p = DatePattern(0, 4, 10) d = datetime.date(2005, 4, 10) self.failUnless(p.matches(d)) Voilà! This test fails! Why am I so happy about a failing test? My reasoning is simple: this proves that the current implementation of DatePattern is insufficient. It can't be just a simple wrapper around date and therefore can't be just a date. While typing this test, I had to make a decision about how to represent wildcards. What occurred to me first was to use 0. After all, there's no year 0 (contrary to popular belief), month 0, or day 0. This may not have been the best choice, but I'm going to roll with it for now. It's time to make the new test pass (while making sure not to break the old ones): class DatePattern: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def matches(self, date): return ((self.year and self.year == date.year or True) and self.month == date.month and self.day == date.day) To be honest, I'm already starting to feel like I'll need to do some refactoring as I add more wildcard functionality to the class, but I want to write a few more tests first. Let's add a test where the month is a wildcard: def testMatchesYearAndMonthAsWildCards(self): p = DatePattern(0, 0, 1) d = datetime.date(2004, 10, 1) self.failUnless(p.matches(d)) Fixing matches so that the test passes results in this: def matches(self, date): return ((self.year and self.year == date.year or True) and (self.month and self.month == date.month or True) and self.day == date.day) This method is getting uglier every time we touch it--I'm now positive that it will be my first refactoring victim. I now have a test for using wildcards for both years and months. Will I need one for days? A pattern containing nothing but wildcards would match every day. When would that be useful? At this point I can't think of a reason to support wildcard days, so I won't bother writing a test for it. Because of that, I also won't bother implementing any code to support it in the DatePattern class. Remember, code gets written only when there's a failing test that needs the new code in order to pass. This prevents us from writing code that should not exist in our application, which should help keep it from becoming unnecessarily complex. Let's move on. We need to support events that occur on a specified day of every week: def testMatchesWeekday(self): p = DatePattern( Uh, what now? At this point, I realized that the DatePattern class might not be what I want to use for this test. Its __init__ method doesn't accept a weekday. Should I use a different class, or modify the existing one? I decided to modify the existing one for now, as that will require the least amount of work. If this turns out to be a bad idea, I can always refactor later. def testMatchesWeekday(self): p = DatePattern(0, 0, 0, 2) # 2 is Wednesday d = datetime.date(2004, 9, 29) self.failUnless(p.matches(d)) This doesn't pass because DatePattern.__init__ doesn't accept five arguments (counting self). I modified __init__ to look like this: def __init__(self, year, month, day, weekday=0): self.year = year self.month = month self.day = day self.weekday = weekday I gave weekday a default value so that I wouldn't need to update the other test cases. Everything compiles and runs, but the new test case doesn't pass. The astute reader has probably already realized that I'm now passing in 0 for the day argument. There's the wildcard I didn't think I would need--now I need it! Here's my new matches method: def matches(self, date): return ((self.year and self.year == date.year or True) and (self.month and self.month == date.month or True) and (self.day and self.day == date.day or True) and (self.weekday and self.weekday == date.weekday() or True)) Now all of the components of a pattern allow for wildcards. How very interesting. With this new method, testMatchesWeekday passes but testMatchesFalse now fails! What gives? Refactoring I honestly can't tell why testMatchesFalse fails by looking at the code. This is going to call for some simple debugging. Unfortunately, I tried to cram all of the logic for the matches method into one expression (spanning four lines!), so there's no place for me to insert any print statements to help me see which part is failing. It's finally time to do that refactoring I've been wanting to do. The refactoring I want to apply is the Compose Method from Joshua Kerievsky's excellent book, Refactoring to Patterns. By extracting smaller methods from the current matches method, I can not only make matches clearer but also make it possible to debug whichever part is currently causing me grief. This is the result: def matches(self, date): return (self.yearMatches(date) and self.monthMatches(date) and self.dayMatches(date) and self.weekdayMatches(date)) def yearMatches(self, date): if not self.year: return True return self.year == date.year def monthMatches(self, date): if not self.month: return True return self.month == date.month def dayMatches(self, date): if not self.day: return True return self.day == date.day def weekdayMatches(self, date): if not self.weekday: return True return self.weekday == date.weekday() Code Pickiness I recently read a weblog post by Ian Bicking about what he considers to be code smells in Python code. The matches method is now much clearer, don't you agree? It might seem like a ridiculous thing to do, but writing intention-revealing code is much more important than being clever. I was trying to be too clever before and it caused a bug--one that I wouldn't have come across if I had done this from the beginning. After applying this refactoring and rerunning the tests, I expected to see the testMatchesFalse test still failing, but it's now passing. Somewhere in my original logic I made an error, and I have no idea where it was--I'll leave finding it as an exercise for the reader. In the meantime, not only do I have simpler code now but it also actually works the way I expect it to. Take that! Would I have noticed this bug without tests? I have no doubt that I would, but how long would it have been before I realized that this was a problem? With my unit tests, I noticed it immediately, so I knew exactly what to fix. Wildcards essentially work for all of the components I'm testing so far. This is good, but I think the next test will cause trouble. It starts out innocently enough: def testMatchesLastWeekday(self): p = DatePattern(0, 0, 0, 3 Er, I'm stuck again. In case it's not obvious (and it's not--why didn't Python's datetime module define constants for weekdays?), the 3 represents Thursday. How do I indicate that I only want to match the last Thursday in a month? Do I need to add yet another argument to DatePattern.__init__? This is where that sneaking suspicion in the back of my head is finally starting to warrant some closer attention. I might be trying to cram too much functionality into one class. Conclusion I haven't written much code yet, but that's a good thing, since it seems that the code I have written might not have been sufficient for what I want to do with it. Without the tests, I might not have discovered what a mess I was writing until it was too late. At this point, I haven't invested too much time into the DatePattern class, so I won't feel bad about throwing it away if that's what I'll need to do. I have some ideas about how to restructure the code so that it's as simple and yet as functional as I want it to be, but we're going to have to save those for Part 2 of this article, which will be published shortly. Jason Diamond is a consultant specializing in C++, C#, and XML, and is located in sunny Southern California. Return to the Python DevCenter.
I'm looking at implementing an app getting Twitter authorization via Oauth in Java. The first step is getting a request token. Here is a Python example for app engine. To test my code, I am running Python and checking output with Java. Here is an example of Python generating a Hash-Based Message Authentication Code (HMAC): #!/usr/bin/python from hashlib import sha1 from hmac import new as hmac key = "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50" message = "foo" print "%s" % hmac(key, message, sha1).digest().encode('base64')[:-1] Output: $ ./foo.py+3h2gpjf4xcynjCGU5lbdMBwGOc= How does one replicate this example in Java? I've seen an example of HMAC in Java: try { // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104 // In practice, you would save this key. KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5"); SecretKey key = keyGen.generateKey(); // Create a MAC object using HMAC-MD5 and initialize with key Mac mac = Mac.getInstance(key.getAlgorithm()); mac.init(key); String str = "This message will be digested"; // Encode the string into bytes using utf-8 and digest it byte[] utf8 = str.getBytes("UTF8"); byte[] digest = mac.doFinal(utf8); // If desired, convert the digest into a string String digestB64 = new sun.misc.BASE64Encoder().encode(digest); } catch (InvalidKeyException e) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } It uses javax.crypto.Mac, all good. However, the SecretKey constructors take bytes and an algorithm. What's the algorithm in the Python example? How can one create a Java secret key without an algorithm?
Python is an easy and powerful programming language that allows us to write sophisticated programs: Dropbox and BitTorrent are excellent examples. It is common that Python programs are delivered in source code, but in some cases different techniques like obfuscation and compilation are applied to protect the code from curious eyes. But do these techniques really work? In this article we will see some tools that supposedly help us to protect our code and how easily they are subverted. We have two example programs written in Python: the first one is a simple function that asks for a password and shows a message; the second one is the same but this time we have used a class. def main(): a = "toomanysecrets" res = raw_input("Please enter your password: ") if res == a: print "ACCESS GRANTED" else: print "ACCESS DENIED" if __name__ == "__main__": main() secretapp1.py class DoMain: def __init__(self): self.a = "toomanysecrets" def Ask(self): res = raw_input("Please enter your password: ") if res == self.a: print "ACCESS GRANTED" else: print "ACCESS DENIED" if __name__ == "__main__": dm = DoMain() dm.Ask() secretapp2.py Suppose I don’t want to deliver these programs code, then I have several options. Our first option is to obfuscate the code, thus making it difficult to read. Pyobfuscate This program allows you to obfuscate the code but it is still completely valid for the Python interpreter. Here is an example with SecretApp1 and SecretApp2. At a glance our code makes no sense, but if you look closely at the result we see the text strings in the code and we can recognize Python syntax. It is not too difficult to reconstruct the original code from the obfuscated code. Despite its limitations, I invite you to visit the tool website to check its possibilities. Htibctobf This tool was originally written to solve a challenge in a hacking competition at the Hack in the Box conference. I recommend reading this great article to learn more about it. Unlike the previous tool, Htibctobf obfuscates Python code by modifying the AST (Abstract Syntax Trees). When you run this tool, we can see our obfuscated Python code in Fig. 3 and Fig. 4. We can see the obfuscated code, including text strings, despite that it is not too difficult to reconstruct the original code as well. Without a doubt an interesting concept with many possibilities, nevertheless it requires improvements to be useful. In some cases perhaps it is enough to obfuscate the code, but let’s look for other options to protect our code more effectively, therefore we will have to resort to compile our Python code to create an executable. Py2exe Possibly one of the most popular choices to turn Python code into a Windows executable. Py2exe First we have to create a file called Setup that includes a reference to the program we want to build/compile. See setup script. from distutils.core import setup import py2exe setup(console=['secretapp1.py']) setup.py We are now ready to compile our Python code into a Windows executable, so let’s run py2exe. See Fig. 5. Once the building process is completed, py2exe creates a directory called “dist” which includes our executable and some necessary libraries. In Fig. 6 we can see that py2exe completes successfully and we execute our program in exe format. We could now distribute this binary without fear to give out our code or maybe not? Py2exe_extract This tool allows us to extract Python object file within the executable created using py2exe, basically inverting the process. Py2exe_extract In Fig. 7 we can see how we use py2exe_extract to get the object file secretapp1.pyc (the content of this file is platform-independent and is known as Bytecode) from secretapp1.exe. Now let’s explore ways to get the code from this object file. Unwind Unwind is a disassembler for Python Bytecode that can be used to analyze object files “.pyc”. For this example, I’ve written a simple script in Python, mytest.py, that imports the disassembler and analyzes the pyc file. See code below. import unwind print(unwind.disassemble('secretapp1.pyc')) mytest.py With this script you can run the following command and get a disassembly of the object file. See Fig. 8. For low level lovers this will be your favorite choice Uncompyle2 Another option is to use a decompiler like uncompyle2 to get the code directly from the object file “.pyc” without having to go through the disassembly as we previously saw. This tool is powerful and easy to use as you can see in Fig. 9 using a simple command we get the source code for secretapp1.pyc. Wow, we got source code! Throughout the article, we have seen some obfuscation and compilation techniques to protect Python code, but we have also been able to subvert the entire protection quite easily The following are other Python compilers that can be used in Windows, Linux, or MacOS, but they suffer from the same problems described in this article. We could also analyze and subvert binaries using tools such as IDA PRO or Immunity Debugger but I will leave it for a future post. Another interesting tool that I have not mentioned is pyREtic, which is an extensible framework for in-memory Python Bytecode reverse engineering. For an attacker to get the Python code is a matter of time, however to make things really difficult from a defensive point of view we have to combine different protection techniques. Do you protect your Python programs? Which methods do you use? – Simon Roses Femerling
I'm starting to write an app whereby a mobile app (Android/IPhone) will communicate with the GAE backend (Python) through a series of Web API calls using JSON. I can't use Google Accounts for authentication so I need to implement my own auth. I have an idea of how to do this, but I'm not sure if there is a better way. Can anyone help with some code examples/suggestions of how to achieve the below please? Method Mobile app calls a Login method on the server which authenticates and creates a session key in the store and returns this to the app - not sure how to generate the key/session or where on the request/response it should be. On every call, the app passes this key for the server to authenticate and allows the action if it passes. User should not have to login on mobile again unless they explicitly logout or lose the key. Login Method - without key generation class Login(webapp.RequestHandler): def post(self): args = json.loads(self.request.body) email = args['e'] pwd = args['p'] ret = {} user = User.gql('WHERE email = :1', email).get() if user and helpers.check_password(pwd, user.password): ret['ret_code'] = 0 ret['dn'] = user.display_name else: ret['ret_code'] = 1 self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(ret))
I tried a lot but can´t find it out, so I hope you can help me. I am trying to build my own voice recognition app, which doesn´t show up the dialog. I already wrote some code and it works quite fine, but my problem is that the recognizer seems to stop without any errors or other messanges in the LogCat. A strange fact is that the "onRmsChanged" from the "RecognitionListener" interface is still called all the time, but no "onBeginningOfSpeech" is called anymore. If I speak just after the speech recognition has started it works. But it doesn´t if I wait a few seconds. The used API is 4.0.3 and I installed it on my Nexus 7 with the Version 4.2.1 I would really appreciate if you have some good ideas. Some code snippets: My class: class SpeechListener implements RecognitionListener { public void onBeginningOfSpeech() { Log.d(TAG, "onBeginningOfSpeech()"); } public void onBufferReceived(byte[] buffer) { Log.d(TAG, "onBufferReceived()"); } public void onEndOfSpeech() { Log.d(TAG, "onEndOfSpeech()"); } public void onError(int error) { Log.d(TAG, "onError(): " + error); if(error == SpeechRecognizer.ERROR_NO_MATCH) { } else if(error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) { } else { tvOutput.setText("Error: " + error); } } public void onEvent(int eventType, Bundle params) { Log.d(TAG, "onEvent()"); } public void onPartialResults(Bundle partialResults) { Log.d(TAG, "onPartialResults()"); } public void onReadyForSpeech(Bundle params) { Log.d(TAG, "onReadyForSpeech()"); } public void onResults(Bundle results) { Log.d(TAG, "onResults(): " + results); String str = new String(); ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); for(int i = 0; i < data.size(); i++) { str += data.get(i) + "\n"; } tvOutput.setText(tvOutput.getText().toString() + "\n\n" + "Results: " + str); } public void onRmsChanged(float rmsdB) { Log.d(TAG, "onRmsChanged()"); } } And my implementation in the MainActivity: this.srSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this); this.srSpeechRecognizer.setRecognitionListener(new SpeechListener()); this.iSpeechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); this.iSpeechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); this.iSpeechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "voice.recognition.test"); this.iSpeechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10); And so it´s started: srSpeechRecognizer.startListening(iSpeechIntent); Logs with speaking: 12-16 13:50:53.576: D/DreamManagerService(485): Dream finished: android.os.Binder@415bbf38 12-16 13:50:53.576: I/DreamManagerService(485): Leaving dreamland. 12-16 13:50:53.576: I/DreamController(485): Stopping dream: name=ComponentInfo{com.google.android.deskclock/com.android.deskclock.Screensaver}, isTest=false, userId=0 12-16 13:50:53.586: I/PowerManagerService(485): Waking up from dream... 12-16 13:50:53.616: I/ActivityManager(485): No longer want com.google.android.gsf.login (pid 13171): empty #17 12-16 13:50:56.796: I/GoogleRecognitionServiceImpl(1461): #startListening [de-DE] 12-16 13:50:56.806: I/ActivityManager(485): Start proc com.google.android.gsf.login for service com.google.android.gsf.login/com.google.android.gsf.loginservice.GoogleLoginService: pid=13343 uid=10019 gids={50019, 3003, 1007, 1028, 1015, 2001, 3006} 12-16 13:50:56.866: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:56.886: D/dalvikvm(1461): GC_FOR_ALLOC freed 516K, 12% free 8706K/9892K, paused 18ms, total 18ms 12-16 13:50:56.906: D/dalvikvm(1461): GC_CONCURRENT freed 160K, 9% free 9015K/9892K, paused 3ms+2ms, total 21ms 12-16 13:50:56.906: I/AudioService(485): AudioFocus requestAudioFocus() from android.media.AudioManager@4135e960com.google.android.speech.audio.AudioController$1@41261910 12-16 13:50:56.916: I/VS.G3EngineManager(1461): create_rm: m=ENDPOINTER_VOICESEARCH,l=en-US 12-16 13:50:56.916: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:56.916: I/VS.G3EngineManager(1461): Brought up new g3 instance :/system/usr/srec/en-US/endpointer_voicesearch.config for: en-USin: 3 ms 12-16 13:50:56.926: I/ConnectionFactoryImpl(1461): Opening SSL connection: vs.google.com:14259 12-16 13:50:56.966: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.016: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.066: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.116: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.166: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.216: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.266: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.316: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.366: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.416: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.466: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.516: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.566: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.616: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.666: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.716: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.766: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.816: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.866: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.916: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:57.966: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.016: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.066: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.116: I/MainActivity/SpeechListener(13268): onBeginningOfSpeech() 12-16 13:50:58.126: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.176: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.226: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.276: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.326: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.376: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.426: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.476: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.526: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.576: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.626: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.676: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.726: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.776: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.826: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.876: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.926: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:58.976: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.026: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.076: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.126: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.176: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.236: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.286: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.336: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.386: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.436: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.486: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.536: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.586: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.636: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.646: I/MicrophoneInputStream(1461): mic_close 12-16 13:50:59.666: I/AudioService(485): AudioFocus abandonAudioFocus() from android.media.AudioManager@4135e960com.google.android.speech.audio.AudioController$1@41261910 12-16 13:50:59.666: D/dalvikvm(1461): threadid=37: thread exiting, not yet detached (count=0) 12-16 13:50:59.666: I/MainActivity/SpeechListener(13268): onEndOfSpeech() 12-16 13:50:59.676: I/decoder(1461): INFO: recognition time wall: 2.732 sec user: 0.54 sec sys: 0.08 sec 12-16 13:50:59.686: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.736: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.786: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.826: I/MainActivity/SpeechListener(13268): onResults(): Bundle[mParcelledData.dataSize=292] 12-16 13:50:59.836: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.886: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.936: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:50:59.986: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:51:00.046: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:51:00.096: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:51:00.146: D/MainActivity/SpeechListener(13268): onRmsChanged() 12-16 13:51:00.196: D/MainActivity/SpeechListener(13268): onRmsChanged() Logs without speaking: 12-16 13:53:39.246: I/GoogleRecognitionServiceImpl(1461): #startListening [de-DE] 12-16 13:53:39.296: D/dalvikvm(1461): GC_FOR_ALLOC freed 567K, 12% free 8708K/9892K, paused 21ms, total 21ms 12-16 13:53:39.316: D/dalvikvm(1461): GC_CONCURRENT freed 164K, 9% free 9017K/9892K, paused 3ms+2ms, total 21ms 12-16 13:53:39.316: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.316: I/AudioService(485): AudioFocus requestAudioFocus() from android.media.AudioManager@4135e960com.google.android.speech.audio.AudioController$1@41261910 12-16 13:53:39.326: I/VS.G3EngineManager(1461): create_rm: m=ENDPOINTER_VOICESEARCH,l=en-US 12-16 13:53:39.326: I/ConnectionFactoryImpl(1461): Opening SSL connection: vs.google.com:14259 12-16 13:53:39.326: I/VS.G3EngineManager(1461): Brought up new g3 instance :/system/usr/srec/en-US/endpointer_voicesearch.config for: en-USin: 5 ms 12-16 13:53:39.366: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.416: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.466: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.516: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.576: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.626: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.676: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.726: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.776: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.826: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.876: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.926: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:39.976: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.026: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.076: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.136: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.176: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.226: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.286: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.336: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.386: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.436: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.486: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.536: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.586: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.636: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.686: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.736: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.786: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.836: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.886: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.936: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:40.986: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.046: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.096: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.146: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.196: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.246: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.296: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.346: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.396: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.446: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.496: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.546: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.596: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.646: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.696: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.746: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.796: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.846: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.896: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.946: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:41.996: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.046: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.096: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.146: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.196: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.246: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.296: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.356: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.406: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.456: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.506: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.556: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.606: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.656: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.706: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.756: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.806: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.856: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.906: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:42.956: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.006: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.056: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.116: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.156: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.216: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.266: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.316: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.366: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.416: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.466: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.516: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.566: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.616: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.666: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.716: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.766: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.816: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.866: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.916: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:43.966: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.016: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.066: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.116: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.166: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.226: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.276: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.326: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.376: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.426: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.476: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.526: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.576: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.626: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.676: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.726: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.776: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.826: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.876: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.926: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:44.976: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.026: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.076: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.126: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.176: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.226: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.276: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.326: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.376: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.426: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.476: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.526: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.576: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.636: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.676: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.736: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.786: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.836: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.886: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.936: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:45.986: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.036: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.086: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.136: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.186: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.236: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.286: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.336: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.386: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.436: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.486: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.536: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.596: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.636: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.696: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.746: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.796: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.846: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.896: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.946: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:46.996: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.046: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.096: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.146: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.196: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.246: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.296: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.346: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.396: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.446: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.496: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.556: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.596: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.656: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.696: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.746: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.796: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.856: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.906: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:47.956: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.006: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.056: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.106: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.156: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.206: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.256: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.306: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.356: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.406: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.456: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.506: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.556: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.616: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.656: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.706: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.766: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.816: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.866: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.916: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:48.966: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.016: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.066: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.116: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.166: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.216: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.266: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.316: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.366: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.416: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.466: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.516: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.566: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.616: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.666: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.716: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.776: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.816: D/dalvikvm(1461): GC_FOR_ALLOC freed 106K, 9% free 9025K/9892K, paused 32ms, total 32ms 12-16 13:53:49.816: I/dalvikvm-heap(1461): Grow heap (frag case) to 9.282MB for 320656-byte allocation 12-16 13:53:49.836: D/dalvikvm(1461): GC_FOR_ALLOC freed 156K, 11% free 9182K/10208K, paused 19ms, total 19ms 12-16 13:53:49.836: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.886: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.936: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:49.986: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:50.036: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:50.086: D/MainActivity/SpeechListener(13441): onRmsChanged() 12-16 13:53:50.136: D/MainActivity/SpeechListener(13441): onRmsChanged()
Hi I'm coding a site that uses donations as multiple items on a Project. I'm calculating the total amount of donations, but it doesn't seem to work. Do i need an intermediate table between the two models? I was wondering if there's a better to way to do it with Django Aggregation. class Donation(models.Model): user = models.ForeignKey(User) amount= models.DecimalField(max_digits=12, decimal_places=2) def __unicode__(self): return self.user class Project(models.Model): name = models.CharField(max_length=200) donations=models.ManyToManyField(Donation, null=True, blank=True) def __unicode__(self): return self.name def progress(self): donations = self.donations.all() total_donations = 0 for item in donations: total_donations += item.amount return total_donations Thanks for your kind help!
I'm running on 10.8.2. All of a sudden, traditional nameserver lookups are failing on my machine: $ nslookup www.att.com ;; connection timed out; no servers could be reached $ dig www.att.com ; <<>> DiG 9.8.3-P1 <<>> www.att.com ;; global options: +cmd ;; connection timed out; no servers could be reached But operations that use name services work fine: $ scutil -r www.att.com Reachable $ ping www.att.com PING e2318.dscb.akamaiedge.net (23.1.57.145): 56 data bytes 64 bytes from 23.1.57.145: icmp_seq=0 ttl=55 time=22.862 ms 64 bytes from 23.1.57.145: icmp_seq=1 ttl=55 time=26.947 ms ^C --- e2318.dscb.akamaiedge.net ping statistics --- 2 packets transmitted, 2 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 22.862/24.904/26.947/2.043 ms I've tried setting the name server addresses to different destinations via the network system preference (e.g., 4.2.2.2, 208.67.222.222, 208.67.220.220, etc.) but that doesn't seem to make any difference. I'm guessing there is an internal configuration file for the on-board DNS server that isn't getting updated, but I haven't a clue where to look for that.
when I post a comment, do not save, crashes (error: [Errno 111] Connection refused), why? views.py import time from calendar import month_name from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404, render_to_response from django.contrib.auth.decorators import login_required from django.core.context_processors import csrf from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.urlresolvers import reverse from dbe.blog.models import * from django.forms import ModelForm class CommentForm(ModelForm): class Meta: model = Comment exclude = ["post"] def post(request, pk): post = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=post) d = dict(post=post, comments=comments, form=CommentForm(), user=request.user) d.update(csrf(request)) return render_to_response("post.html", d) def delete_comment(request, post_pk, pk=None): if request.user.is_staff: if not pk: pklst = request.POST.getlist("delete") else: pklst = [pk] for pk in pklst: Comment.objects.get(pk=pk).delete() return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[post_pk])) def add_comment(request, pk): p = request.POST if p.has_key("body") and p["body"]: author = "Anonymous" if p["author"]: author = p["author"] comment = Comment(post=Post.objects.get(pk=pk)) cf = CommentForm(p, instance=comment) cf.fields["author"].required = False comment = cf.save(commit=False) comment.author = author notify = True if request.user.username == "ak": notify = False comment.save(notify=notify) return HttpResponseRedirect(reverse("dbe.blog.views.post", args=[pk])) def mkmonth_lst(): if not Post.objects.count(): return [] # set up vars year, month = time.localtime()[:2] first = Post.objects.order_by("created")[0] fyear = first.created.year fmonth = first.created.month months = [] for y in range(year, fyear-1, -1): start, end = 12, 0 if y == year: start = month if y == fyear: end = fmonth-1 for m in range(start, end, -1): months.append((y, m, month_name[m])) return months def month(request, year, month): posts = Post.objects.filter(created__year=year, created__month=month) return render_to_response("list.html", dict(post_list=posts, user=request.user, months=mkmonth_lst(), archive=True)) def main(request): posts = Post.objects.all().order_by("-created") paginator = Paginator(posts, 10) try: page = int(request.GET.get("page", '1')) except ValueError: page = 1 try: posts = paginator.page(page) except (InvalidPage, EmptyPage): posts = paginator.page(paginator.num_pages) return render_to_response("list.html", dict(posts=posts, user=request.user, post_list=posts.object_list, months=mkmonth_lst())) models.py from django.db import models from django.contrib.auth.models import User from django.contrib import admin from django.core.mail import send_mail class Post(models.Model): title = models.CharField(max_length=60) body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.title class Comment(models.Model): created = models.DateTimeField(auto_now_add=True) author = models.CharField(max_length=60) body = models.TextField() post = models.ForeignKey(Post) def __unicode__(self): return unicode("%s: %s" % (self.post, self.body[:60])) def save(self, *args, **kwargs): if "notify" in kwargs and kwargs["notify"] == True: message = "Comment was was added to '%s' by '%s': \n\n%s" % (self.post, self.author, self.body) from_addr = "no-reply@mydomain.com" recipient_list = ["myemail@mydomain.com"] send_mail("New comment added", message, from_addr, recipient_list) if "notify" in kwargs: del kwargs["notify"] super(Comment, self).save(*args, **kwargs) Admin class PostAdmin(admin.ModelAdmin): search_fields = ["title"] display_fields = ["title", "created"] class CommentAdmin(admin.ModelAdmin): display_fields = ["post", "author", "created"] thanks!
Table of Contents PyGTK 2.0 is a set of Python modules which provide a Python interface to GTK+ 2.X. Throughout the rest of this document PyGTK refers to the 2.X version of PyGTK and GTK and GTK+ refer to the 2.X version of GTK+. The primary web site for PyGTK is www.pygtk.org. The primary author of PyGTK is: who is assisted by the developers listed in the AUTHORS file in the PyGTK distribution and the PyGTK community. Python is an extensible, object-oriented interpreted programming language which is provided with a rich set of modules providing access to a large number of operating system services, internet services (such as HTML, XML, FTP, etc.), graphics (including OpenGL, TK, etc.), string handling functions, mail services (IMAP, SMTP, POP3, etc.), multimedia (audio, JPEG) and cryptographic services. In addition there are many other modules available from third parties providing many other services. Python is licensed under terms similar to the LGPL license and is available for Linux, Unix , Windows and Macintosh operating systems. More information on Python is available at www.python.org . The primary Author of Python is: GTK (GIMP Toolkit) is a library for creating graphical user interfaces. It is licensed using the LGPL license, so you can develop open software, free software, or even commercial non-free software using GTK without having to spend anything for licenses or royalties. It's called the GIMP toolkit because it was originally written for developing the GNU Image Manipulation Program (GIMP), but GTK has now been used in a large number of software projects, including the GNU Network Object Model Environment (GNOME) project. GTK is built on top of GDK (GIMP Drawing Kit) which is basically a wrapper around the low-level functions for accessing the underlying windowing functions (Xlib in the case of the X windows system). The primary authors of GTK are: GTK is currently maintained by: GTK is essentially an object oriented application programmers interface (API). Although written completely in C, it is implemented using the idea of classes and callback functions (pointers to functions). There is also a third component called GLib which contains a fewreplacements for some standard calls, as well as some additional functionsfor handling linked lists, etc. The replacement functions are used toincrease GTK's portability, as some of the functions implemented here arenot available or are nonstandard on other unixes such asg_strerror(). Some also contain enhancements to thelibc versions, such as g_malloc that has enhanceddebugging utilities. In version 2.0, GLib has picked up the type system which forms the foundation for GTK's class hierarchy, the signal system which is used throughout GTK, a thread API which abstracts the different native thread APIs of the various platforms and a facility for loading modules. As the last component, GTK uses the Pango library for internationalized text output. This tutorial describes the Python interface to GTK+ and is based on the GTK+ 2.0 Tutorial written by Tony Gale and Ian Main. This tutorial attempts to document as much as possible of PyGTK, but is by no means complete. This tutorial assumes some understanding of Python, and how to create and run Python programs. If you are not familiar with Python, please read the Python Tutorial first. This tutorial does not assume an understanding of GTK; if you are learning PyGTK to learn GTK, please comment on how you found this tutorial, and what you had trouble with. This tutorial does not describe how to compile or install Python, GTK+ or PyGTK. This tutorial is based on: The examples were written and tested on a RedHat 9.0 system. This document is a "work in progress". Please look for updates on www.pygtk.org. I would very much like to hear of any problems you have learning PyGTK from this document, and would appreciate input as to how it may be improved. Please see the section on Contributing for further information. If you encounter bugs please file a bug at bugzilla.gnome.org against the pygtk project. The information at www.pygtk.org about Bugzilla may help. The PyGTK 2.0 Reference Manual is available at http://www.pygtk.org/reference.html. It describes in detail the PyGTK classes. The PyGTK website (www.pygtk.org) contains other resources useful for learning about PyGTK including a link to the extensive FAQ and other articles and tutorials and an active maillist and IRC channel (see www.pygtk.org for details). Johan Dahlin has written a small Python program (pygtkconsole.py)that runs on Linux and allows interactive exploration of PyGTK. The programprovides a Python-like interactive interpreter interface that communicateswith a child process that executes that entered commands. The PyGTK modulesare loaded by default. A simple example session is: moe: 96:1095$ pygtkconsole.py Python 2.2.2, PyGTK 1.99.14 (Gtk+ 2.0.6) Interactive console to manipulate GTK+ widgets. >>> w=Window() >>> b=Button('Hello') >>> w.add(b) >>> def hello(b): ... print "Hello, World!" ... >>> b.connect('clicked', hello) 5 >>> w.show_all() >>> Hello, World! Hello, World! Hello, World! >>> b.set_label("Hi There") >>> This creates a window containing a button which prints a message ('Hello, World!') when clicked. This program makes it easy to try out various GTK widgets and PyGTK interfaces. I also use a program that was developed by Brian McErlean asActiveStaterecipe 65109 with some mods to make it run with PyGTK 2.X. I call itgpython.py. Itworks similar to the pygtkconsole.pyprogram. Both of these programs are known not to work on Microsoft Windows because they rely on Unix specific interfaces.
You're actually looking for some of the more esoteric options for a QListView/QListWidget. At the top level, add QTreeWidget or QTreeView will give you the hierarchy you're looking for, as well as managing the scrolling area. Each Listed Item of the (expanded) QTreeXItem will be a QListView/QListWidget, setting setViewMode(QListView::IconMode) on them. EDIT:Note that to get the precise look you wanted above, you'll probably have to use QListView and use a custom delegate, handling the drawing yourself (unless you can find a theme that will do exactly what you want). However, I've coded up a short PyQt solution below using the Q*Widget classes because they're shorter, and will still demonstrate how to get the right layout. If you're using C++, the same Qt function calls apply, but obviously you might have more or less bookkeeping. import sys from PyQt4 import QtGui, QtCore class displayItem(QtGui.QWidget): #A simple widget to display, just centers a digit in a 100x100 widget def __init__(self,num): QtGui.QWidget.__init__(self) self.size=100 self.resize(self.size,self.size) self.setMinimumSize(self.size,self.size) self.text = num def paintEvent(self,event): p = QtGui.QPainter(self) p.drawText(self.size//2,self.size//2,str(self.text)) app = QtGui.QApplication(sys.argv) widget = QtGui.QTreeWidget() widget.setWindowTitle('simple tree') #Build the list widgets treeItem1 = QtGui.QTreeWidgetItem(widget) treeItem1.setText(0,"TreeWidget Parent") #Sets the "header" for your [+] box list1 = QtGui.QListWidget() #This will contain your icon list list1.setMovement(QtGui.QListView.Static) #otherwise the icons are draggable list1.setResizeMode(QtGui.QListView.Adjust) #Redo layout every time we resize list1.setViewMode(QtGui.QListView.IconMode) #Layout left-to-right, not top-to-bottom listItem = QtGui.QListWidgetItem(list1) listItem.setSizeHint(QtCore.QSize(100,100)) #Or else the widget items will overlap (irritating bug) list1.setItemWidget(listItem,displayItem(1)) listItem = QtGui.QListWidgetItem(list1) #Add a few more items listItem.setSizeHint(QtCore.QSize(100,100)) list1.setItemWidget(listItem,displayItem(2)) listItem = QtGui.QListWidgetItem(list1) listItem.setSizeHint(QtCore.QSize(100,100)) list1.setItemWidget(listItem,displayItem(3)) list1.setAutoFillBackground(True) #Required for a widget that will be a QTreeWidgetItem widget treeSubItem1 = QtGui.QTreeWidgetItem(treeItem1) #Make a subitem to hold our list widget.setItemWidget(treeSubItem1,0,list1) #Assign this list as a tree item treeItem2 = QtGui.QTreeWidgetItem(widget) #Make a fake second parent treeItem2.setText(0,"TreeWidget Parent II") widget.show() #kick off the app in standard PyQt4 fashion sys.exit(app.exec_())
My problem relates to this question: http://stackoverflow.com/questions/1390556/default-ordering-for-m2m-items-by-intermediate-model-field-in-django class Group(models.Model): name = models.CharField(max_length=128) _members = models.ManyToManyField(Person, through='Membership') @property def members(self): return self._members.order_by('membership__date_joined') def __unicode__(self): return self.name I used the best answer's solution as you see here, however, it broke my model form that's based on the group model. When I submit the form, I get _members is required in my model form's error list since the field is required and can no longer submit forms based on this model. The best answer in the prior question suggests a way to mimic the behavior of the field using the property. How would I go about doing this to completely hide _members from the model form? Thanks, Pete
smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu mwoe effectivement y s arrete direct y cree pas les fichiers et sort... je regarde ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola c'est corrige pour le fichier de config, maj dans le git ok ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola hizo bah je vois pas quoi faire de plus, je capte pas ton pb tu es le seul, ce fichier là meme s il y est je veux dire il est vide je vois pas ce que ca changera le soucis c est pourquoi ton dhcp ne cree pas ce fichier surtout Oo tests si tu veux en virant le rm du resolv.conf dans fichier export_dist.sh et dis moi ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Hizoka Re : logiciel creation/remasterisation/clonage de distributions base ubuntu non je suis pas seul ok je teste. Hors ligne Lenslarque Re : logiciel creation/remasterisation/clonage de distributions base ubuntu C'est ok pour moi pour le su, merci Pour le resolv.conf j'ai laissé mon "fix" donc je ne sais pas Hors ligne Hizoka Re : logiciel creation/remasterisation/clonage de distributions base ubuntu etrange... j'ai tout virer (dans le fichier export_dist.sh) ce que tu fais sur le fichier resolv.conf et j'ai ajouté : echo "nameserver 8.8.8.8" > "${DISTDIR}"/chroot/etc/resolv.conf mais malgre ca, pas de fichier ?! et je vois que tu supprime le hosts ? dommage ca veut dire qu'on peut pas le modifier non plus ? Dernière modification par Hizoka (Le 31/10/2012, à 19:56) Hors ligne kezako_06 Re : logiciel creation/remasterisation/clonage de distributions base ubuntu @ smo Merci pour la mise à jour qui a solutionné le problème de ./config/ubukey qui est bien créé. Toutefois le second bug persiste, après l'extraction de l'iso, je reste bloqué à "Preparing chroot, please wait..." qui s'affiche indéfiniment, idem en relançant le programme. Le test a été effectué avec une quantal desktop d'origine. J'ai l'impression qu'il ne reconnaît pas l'environnement chrooté ou quelque chose de ce genre, parce qu'il extrait l'iso autant de fois que le programme est relancé dans un dossier /distrib donné... EDIT : à l'instar de Fedora, Ubuntu est doté d'un gestionnaire de volume logique (LVM) lors de l'installation depuis "Quantal". Peut-être une piste à creuser ? Dernière modification par kezako_06 (Le 31/10/2012, à 21:29) Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola bah alors la franchement je vois hizoka tu fais ca avec une kde ? faudra que j test et le hosts si j le laisse et que tu boot sur un autyre pc ca peut poser soucis donc woe j le vire c est pas logique de le laisser a moins que j me plante mais j pense pas kezako, ok pour la maj, de rien alors apres par contre je capte pas ton pb, tu fais quoi exactement? tu cree un distrib , tu charges un iso ou tu lui en indiques un ? si oui lequel ? et comment ca y te reextrait l iso autant de fois que tu relances le soft ?? details un peu plus si possible ensuite apres avoir lancé le chroot , regardes dans le dossier de la distrib t as un dossier logs et un fichier chrootlog.log, postes le thx edit: un truc possible c est qu il n arrive pas a recup certains fichiers de mon serveur que j ai reinstalle et que j ai pas encore reconfigure, vu que nous on a deja tous les fichiers je m en rend pt etre pas compte je regarderai des que possible (pas trop chez moi en ce moment) Dernière modification par smo (Le 01/11/2012, à 09:24) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne kezako_06 Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola bah alors la franchement je vois hizoka tu fais ca avec une kde ? faudra que j test et le hosts si j le laisse et que tu boot sur un autyre pc ca peut poser soucis donc woe j le vire c est pas logique de le laisser a moins que j me plante mais j pense pas kezako, ok pour la maj, de rien alors apres par contre je capte pas ton pb, tu fais quoi exactement? tu cree un distrib , tu charges un iso ou tu lui en indiques un ? si oui lequel ? et comment ca y te reextrait l iso autant de fois que tu relances le soft ?? details un peu plus si possible ensuite apres avoir lancé le chroot , regardes dans le dossier de la distrib t as un dossier logs et un fichier chrootlog.log, postes le thx edit: un truc possible c est qu il n arrive pas a recup certains fichiers de mon serveur que j ai reinstalle et que j ai pas encore reconfigure, vu que nous on a deja tous les fichiers je m en rend pt etre pas compte je regarderai des que possible (pas trop chez moi en ce moment) Bonjour smo, Pour mes distributions j'utilise des isos précédemment téléchargées, j'ai fait le test avec des "quantal" version desktop et gnobuntu pour le même résultat : "Preparing chroot, please wait..." et aucun fichier log ou chrootlog.log n'est présent. Ce qui me fait dire que l'iso est clonée à l'infini c'est que je me suis retrouvé avec 1.607.697 fichiers dans un seul dossier de travail de /distribs. Une iso de base comportant environ 150.000 fichiers à l'origine, j'ai bien dû essayer de chrooter près d'une dizaine de fois... J'en déduis donc qu'il ne reconnaît pas l'iso préalablement extraite avant le chroot. Par ailleurs, impossible de supprimer totalement un dossier de travail depuis la fonction "supprimer" d'ubukey : la distro disparaît du listing ubukey, mais nautilus prouve simultanément le contraire... Après avoir fait le ménage manuellement d'abord, puis avec Bleachbit, rebooté, etc... les mêmes opérations ont produit les mêmes effets : impossible de chrooter ! Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu hummm very strange !!! alors ce que tu fais refais en une et posts ici le .config/ubukey/logs/log (de tete hein dans dossiers logs en tout cas) ca m fera voir tout ce qu il y a eu dans la console et regarde ensuite, apres creation ce que tu as dans le dossier chroot de ta distrib please et donc ca t fait pareil avec une distrib quantal officielle ?? thx Dernière modification par smo (Le 01/11/2012, à 11:30) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Lenslarque Re : logiciel creation/remasterisation/clonage de distributions base ubuntu Salut à tous Smo je confirme depuis la dernière màj le réseau c'est pire, le fichier est maintenant un lien symbolique sur un fichier qui n'existe pas, sans copier/coller le chemin est un peu long à écrire, mais en gros il pointe sur un chemin de la machine hôte donc il connaît pas. Sinon tu sais pourquoi je ne peux plus mettre à jour mon kernel ? Hors ligne Hizoka Re : logiciel creation/remasterisation/clonage de distributions base ubuntu le hosts si j le laisse et que tu boot sur un autyre pc ca peut poser soucis donc woe j le vire c est pas logique de le laisser a moins que j me plante mais j pense pas Perso je l'utilise pour bloquer les pubs et autres saloperies... la seule chose à modifier c'est cette ligne : 127.0.0.1 localhost hizo-computer faut remplacer le $HOSTNAME, y aurait pas moyen d'integrer ca ? genre dans un fichier de boot (rc.local...) Lenslarque => ca me rassure, ca vient pas de moi Hors ligne Lenslarque Re : logiciel creation/remasterisation/clonage de distributions base ubuntu Lenslarque => ca me rassure, ca vient pas de moi Toutefois le hosts ne pose pas de problème, c'est juste le resolv.conf, tu peux me dire si tu peux faire un dist-upgrade dans ta distrib (dans ubukey) une fois que tu as mis un resolv.conf correct bien sûr. Hors ligne Hizoka Re : logiciel creation/remasterisation/clonage de distributions base ubuntu non non pas de soucis avec le host, j'ai juste vu ca dans mon chroot, j'ai pas de soucis de maj, la connexion est ok, car mon resolv.conf est bien là... par contre aucune maj du noyau... dist-upgrade marche mais bon... Hors ligne Lenslarque Re : logiciel creation/remasterisation/clonage de distributions base ubuntu non non pas de soucis avec le host, j'ai juste vu ca dans mon chroot, j'ai pas de soucis de maj, la connexion est ok, car mon resolv.conf est bien là... par contre aucune maj du noyau... dist-upgrade marche mais bon... Ok oui c'est bien ça, pas de màj du noyau, tu me rassures aussi :-) Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu Ola J rentre chez moi suis dans l métro a l autre bout de paris , j avoue pas pris le temps de tester le lien resolv.conf Vais corriger ça dans quelques minutes mais j parie que ça changera pas ton pb hizo t as essaye en.supprimant le rm du export_dis.sh??? ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola bon j ai fait une modif je test voir ce que ca donne.. piur le hosts hizo tu sais que tu peux faire tes propres scripts perso qui seront inclus dans le chroot hei a toi e n faire un qui modifie le rc.local par exemple et posts le nous apres... on fera a terme une base de scripts en ligne ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola bon j ai fait la modif, je test... hizo. cree toi un script perso pour modifier le rc.local par exemple c est fait pour et proposes le nous apres si tu veux modifier ton hosts edit: git mis a jour, lien ok qui pointe bien sur ../run/resolvconf/resolv.conf comme le live-cd d origine.. peut pas mieux faire là pas besoin de rentrer dans chroot refais juste un iso avec bouton export si tu veux tester hizo lenslarque aucune idee pour maj kernel perso pas de soucis sur les dist-upgrade.. ca t fait quoi ? Dernière modification par smo (Le 02/11/2012, à 00:24) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu woe bah j sais pas une fois boote ca marche pas, j fais sudo dhclient eth0 dans qemu par exemple et ca marche j vois pas trop l rapport avec ubukey là ca fait des annees que j ai pas touche cette partie ca a tjrs fonctionné Oo .... Dernière modification par smo (Le 02/11/2012, à 00:35) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Hizoka Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ola mwoe doit y avoir un bug dans un paquet al j vois pas d autre solution... t as un bouton scripts ou plugins dans ubukey en haut tu verras.. tu fais nouveau y t fera un squelette et voila apres tu l auras automatiquement dans le gestionnaire de plugins ubukey dans le chroot ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Hizoka Re : logiciel creation/remasterisation/clonage de distributions base ubuntu je testerai avec une version sans modif de paquet. Quand je fais nouveau, il me crée rien du tout... Hors ligne smo Re : logiciel creation/remasterisation/clonage de distributions base ubuntu ah oui pt etre que j lance gedit moi de tete me rappel plus si j passai par xdg.... mais bon sinon tu mets tes scripts dans addons/custom du dossier de distributions edit: si j passe par xdg-open pourtant ca devrait t lancer kate ou kedit j sais pas ce que t as def create_plug(self): print _("creating new plugin...") plug = open(os.path.join(self.main_dist_path,'addons/custom/new.sh'), "w") plug.write ('''#!/bin/bash ########### # # Note: # ----- # please always use "xterm -e" and/or zenity # to start/show your scripts # ########### # # Please add a description here, it will be viewable in the # ubukey addons manager under the chroot ! DESCRIPTION="" ############ # # Your code here... ''') plug.close() self.optwin.hide() nfile = os.path.join(self.main_dist_path,'addons/custom/new.sh') try: (pid,t,r,s) = gobject.spawn_async(['/usr/bin/xdg-open', nfile],flags=gobject.SPAWN_DO_NOT_REAP_CHILD,standard_output = True, standard_error = True) except: return data=(nfile) gobject.child_watch_add(pid, self.task_done,data) Dernière modification par smo (Le 02/11/2012, à 10:02) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Hizoka Re : logiciel creation/remasterisation/clonage de distributions base ubuntu edit: si j passe par xdg-open pourtant ca devrait t lancer kate ou kedit j sais pas ce que t as Oui oui mais quelle est la commande exact que tu fais ? creating new plugin... Traceback (most recent call last): File "ubukey.py", line 230, in create_plug self.distribs.create_plug() File "/home/hizoka/Scripts_et_logiciels/logiciels/ubukey/Ubukey/lib/distribs.py", line 159, in create_plug plug = open(os.path.join(self.main_dist_path,'addons/custom/new.sh'), "w") IOError: [Errno 2] Aucun fichier ou dossier de ce type: '/home/hizoka/Scripts_et_logiciels/iso/Non_save/smo/addons/custom/new.sh' A la base il n'y avait pas de dossier custom, et encore moins de fichier new.sh Hors ligne
To remove only spaces use str.replace: sentence = sentence.replace(' ', '') To remove all whitespace characters (space, tab, newline, and so on) you can use split then join: sentence = ''.join(sentence.split()) or a regular expression: import re pattern = re.compile(r'\s+') sentence = re.sub(pattern, '', sentence) If you want to only remove whitespace from the beginning and end you can use strip: sentence = sentence.strip() You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.
tiramiseb Re : configuration des DNS S'il-te-plait, pour des citations utilise la balise "[ quote ]" et non la balise "[ code ]", c'est pénible de devoir défiler horizontalement pour lire les phrases que tu cites... Hors ligne kr2sis Re : configuration des DNS ça y est je sui perdu...:o est ce qu'on peut faire doucement stp ? - doubitchou est non révélé au publique... ok - dans mon fichier /etc/hosts, j'ai ajouté une ligne : [IP publique serveur] doubitchou.fr....ok - pas besoin de créer un fichier de zone chez Gandi...ok je suis vraiment navré seb et je ne remets pas en quetsion tes explications que j'ai réussi à suivre jusqu'à symposion.fr, mais là pour moi tout change dans le cadre d'un nouveau virtual host et je ne sais pas comment on peut enregistrer un autre site .. le dernier encart est whois oki mais n'y a-t-il pas un formulaire ou un fichier qui fasse que doubitchou réponde présent ? apres modif du fichier /etc/hosts, j'a eu ce retour de commande : PING doubitchou.fr (84.101.105.63) 56(84) bytes of data. 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=1 ttl=64 time=0.607 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=2 ttl=64 time=0.508 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=3 ttl=64 time=0.516 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=4 ttl=64 time=0.512 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=5 ttl=64 time=0.531 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=6 ttl=64 time=0.742 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=7 ttl=64 time=0.559 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=8 ttl=64 time=0.591 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=9 ttl=64 time=0.529 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=10 ttl=64 time=0.682 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=11 ttl=64 time=0.598 ms ^C --- doubitchou.fr ping statistics --- 11 packets transmitted, 11 received, 0% packet loss, time 9998ms rtt min/avg/max/mdev = 0.508/0.579/0.742/0.076 ms Hors ligne tiramiseb Re : configuration des DNS Tu as "acheté" symposion.fr auprès d'un registrar, Gandi en l'occurrence. Si tu veux que doubitchou.fr soit disponible pour tout le monde sur Internet, tu dois "acheter" doubitchou.fr de la même manière. Si tu ne veux desservir doubitchou.fr que pour toi, pour faire des tests par exemple, tu peux : - soit te contenter de modifier le fichier /etc/hosts de ton poste client afin de lui dire de pointer vers l'adresse de ton serveur ; - soit mettre en place un serveur DNS local, que ton poste client interrogerait pour obtenir les résolutions DNS qu'il demande. Hors ligne tiramiseb Re : configuration des DNS Tu as tout fait avec succès pour symposion.fr, je ne vois pas ce que tu ne comprends pas quand on remplace symposion.fr par doubitchou.fr... Le fonctionnement est le même. Hors ligne kr2sis Re : configuration des DNS no bah du coup, j'avai compris alors... mais pourquoi je lis partotu qu'il est possible d'avoir plusieurs sites sur un meme serveur et qu'on ne parle pas d'achat de nom de domaine ? je me suis pris la tete comme un barge pour rien puisque comme tu dis j'avais tout fait et le succes je te le laisse car sans toi, j'aurais sombré dans une mélancolie douce et stupide, voire une dépression et tentative de suicide avec horizo et chocolat donc je ne m'obstine plus a chercher comment aoir un autre nom de domaine, je l'achete ou je passe en sous-domaine...c'est ça ? en totu cas un grand mercipour toute l'aide qur tu as pu m'apporter Hors ligne Brunod Re : configuration des DNS ..., je l'achete ou je passe en sous-domaine...c'est ça ? ... Ou tu le fais passer gratuitement par noip, dyndns etc en prenant un suffixe de chez eux. Wanted : >>> un emploi dans la sécurité informatique et réseau <<< Windows est un système d'exploitation de l'homme par l'ordinateur. Linux, c'est le contraire ... --> état de la conversion : 36 pc linux Hors ligne kr2sis Re : configuration des DNS beh ca m'interesse pas vraiment étant donné que le but pour moi d'avoir créé un serveur web, c'etait d'etre en total autonomie et liberté.... donc les nom à rallonge, perso je trouve ca laid, donc j'aviserai quand je pourrait accéder a ce site déjà Hors ligne tiramiseb Re : configuration des DNS mais pourquoi je lis partotu qu'il est possible d'avoir plusieurs sites sur un meme serveur et qu'on ne parle pas d'achat de nom de domaine ? L'achat et la configuration de noms de domaine, c'est une autre question, ce n'est pas nécessairement lié, c'est pourquoi les documentations n'en traitent pas. je l'achete ou je passe en sous-domaine...c'est ça ? Exact. Hors ligne kr2sis Re : configuration des DNS bon, nom de domaine acheté le 26 février et toujours pas visible en public... il se passe quelque chose qu eje ne coprends pas... Hors ligne tiramiseb Re : configuration des DNS Tu parles du domaine symposion.fr ? Chez moi, ce domaine se résoud correctement de la manière suivante : $ host symposion.frsymposion.fr has address 84.101.105.63symposion.fr mail is handled by 50 fb.mail.gandi.net.symposion.fr mail is handled by 10 spool.mail.gandi.net. Par contre, il ne semble pas y avoir de sous-domaine "www" dans ce domaine : $ host www.symposion.fr Host www.symposion.fr not found: 3(NXDOMAIN) Par ailleurs, l'adresse pointé par "symposion.fr" (84.101.105.63, qui est une machine chez SFR (reverse DNS "63.105.101.84.rev.sfr.net")) ne semble desservir aucun service (j'ai testé les connexions suivantes sur cette adresse : HTTP, HTTPS, SSH, SMTP, IMAP, POP). Hors ligne kr2sis Re : configuration des DNS le truc c'est que le logiciel (DUC) de no-ip m'indique cet ip :86.71.56.58 et c'est l'autre ip que j'ai noté dans la feuille de zone chez moi rien ne passe (via le local et l'externe (tel portable orange) et je ne comprends pas ce que tu veux dire dans la dernière partie de ton dernier post ... cela signifie quoi stp ? et u'est ce que je dois faire pour résoudre le probleme si il y a un probleme... merci losque je fais ifconfig ou ipconfig, j'obtiens l'ip 192.168.1.54 ; adresse que j'ai statifié dans la box. est ce que je peux mettre cet ip à la place de celle que me révèle no-ip ?? je ne comprends plus rien avec ces ip et le role de no-ip... des dynDNS ok ! mais si ca change tout le temps, il faut que je change mes config tout le temps....:mad: pas cool Dernière modification par kr2sis (Le 01/03/2013, à 13:39) Hors ligne tiramiseb Re : configuration des DNS Reprenons du début : 1/ où se trouve, physiquement, ton serveur ? 2/ comment as-tu configuré les entrées DNS dans l'interface de Gandi ? Hors ligne kr2sis Re : configuration des DNS le serveur est chez moi la config Gandi, je vais voir ca de suite j'ai touché à 2 ligne @ A 84.101.105.63 www CNAME share-wood.zapto.org share..... et l'ip sont issue de mon inscription no-ip Dernière modification par kr2sis (Le 01/03/2013, à 13:44) Hors ligne tiramiseb Re : configuration des DNS le serveur est chez moi Tu es chez quel opérateur ? Avec les adresses que tu donnes, il semble que tu es chez SFR, probablement avec une Neufbox, c'est ça ? Hors ligne kr2sis Re : configuration des DNS oui je suis chez SFR chez moi et neufbox NB4 Hors ligne tiramiseb Re : configuration des DNS Donc tu as un problème. Une adresse IP chez SFR n'est pas fixe : SFR ne fournit que des adresses IP dynamiques. En pratique il y a de fortes chances que ton adresse IP ne change pas souvent, mais ça peut arriver ; c'est peut-être pour ça qu'actuellemnt tu as des problèmes. Dans ces cas, on préconise un système de type DynDNS. Heureusement, des gars voulaient quelque chose avec Gandi et Gandi propose des fonctionnalités avancées intéressantes, en l'occurrence une API qui permet de faire reconfigurer ton entrée DNS automatiquement. Tu pourras donc trouver à l'adresse suivante un outil permettant de gérer ton DNS de manière dynamique avec Gandi : https://github.com/Chralu/gandyn Par contre je ne pourrai pas t'aider dans la mise en œuvre de cet outil, je ne le connais pas. Hors ligne kr2sis Re : configuration des DNS et no-ip dans tout ca ? Hors ligne tiramiseb Re : configuration des DNS Il semble que ton truc chez No-IP est aussi une solution (plus tarabiscotée) pour ce problème. Je ne connais pas ce service. Dans ce cas, ton problème est peut-être plutôt là : as-tu bien activé ta dernière configuration dans l'interface de Gandi ? Dernière modification par tiramiseb (Le 01/03/2013, à 13:51) Hors ligne tiramiseb Re : configuration des DNS Par ailleurs, entre ces deux solutions je préconiserais fortement d'utiliser Gandyn, qui est plus direct que No-IP car il travaille directement avec les serveurs de Gandi. Hors ligne kr2sis Re : configuration des DNS oki donc faut que je vois avec le service client qui ne me repond pas... je vais essayé de leur telephoner dans ce cas.. donc ce que tu dis pour sfr est valable pour tous ceux qui sont abos chez eux ?? bon à savoir si on me demande.. merci à toi le reste de ma config, je n'y touche pas alors ? (mis à part le fichier de zone une fois le tout installé correctement) Hors ligne tiramiseb Re : configuration des DNS oki donc faut que je vois avec le service client qui ne me repond pas... je vais essayé de leur telephoner dans ce cas.. Tu parles de Gandi ? Si tu as des difficultés à utiliser leurs outils, oui il faut leur demander... Cependant : Tu n'as pas répondu à ma question, tu ne m'as pas dit si tu as bien activé la dernière version de la configuration de tes DNS... donc ce que tu dis pour sfr est valable pour tous ceux qui sont abos chez eux ?? bon à savoir si on me demande.. C'est valable pour tous ceux qui sont chez SFR et chez n'importe quel autre FAI qui n'assure pas des adresses IP fixes. Ceux qui fournissent des IP fixes à ma connaissance en France sont (la liste n'est certainement pas exhaustive) : - Free Telecom - Bouygues - Orange Pro, sur demande - Nerim - OVH Ceux qui ne fournissent PAS d'IP fixe (la liste n'est pas exhaustive) : - Orange (sauf pro) - SFR - Numericable - certainement plein d'autres encore le reste de ma config, je n'y touche pas alors ? (mis à part le fichier de zone une fois le tout installé correctement) Dans la mesure où http://86.71.56.58/ semble bien marcher, en effet ta config je ne pense pas qu'il faille y toucher. Dernière modification par tiramiseb (Le 01/03/2013, à 14:01) Hors ligne kr2sis Re : configuration des DNS Tu n'as pas répondu à ma question, tu ne m'as pas dit si tu as bien activé la dernière version de la configuration de tes DNS... tu veux dire entrer la nouvelle IP ? je vais le faire de ce pas dis-moi question surement bete : ne serait-il pas judicieux de ma part de ne pas signaler d'ip (vu qu'elle change) mais plutot seulement le nom de domaine fourni par no-ip (qui corrrespond à chaque ip dynamique dans mon fichier de zone ?? Dernière modification par kr2sis (Le 01/03/2013, à 14:14) Hors ligne tiramiseb Re : configuration des DNS Tu n'as pas répondu à ma question, tu ne m'as pas dit si tu as bien activé la dernière version de la configuration de tes DNS... tu veux dire entrer la nouvelle IP ? je vais le faire de ce pas Je veux dire : as-tu bien cliqué sur le bouton "Activer" dans l'écran de configuration ? Et as-tu bien attendu 48h après avoir cliqué sur ce bouton ? ne serait-il pas judicieux de ma part de ne pas signaler d'ip (vu qu'elle change) mais plutot seulement le nom de domaine fourni par no-ip (qui corrrespond à chaque ip dynamique dans mon fichier de zone ?? Oui, dans le cas du service fourni par no-IP c'est ce qu'il faut faire. Si tu utilises Gandyn, c'est l'outil qui va lui-même automatiquement configurer Gandi à chaque changement d'adresse IP. Hors ligne kr2sis Re : configuration des DNS Je veux dire : as-tu bien cliqué sur le bouton "Activer" dans l'écran de configuration ? dans l'interface, c'est la ligne qui dit "Numéro de version active" ? si oui c'est actif oui (dsl je suis perdu dans cet interface ) Hors ligne kr2sis Re : configuration des DNS je ne vois plus le site de l'exterieur .. tu le vois toi ? stp Hors ligne
class Quote(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.Text) votes = db.Column(db.Integer) author_id = db.Column(db.Integer, db.ForeignKey('author.id')) date_added = db.Column(db.DateTime,default=datetime.datetime.now()) last_letter = db.Column(db.String(1)) I have a Model that looks like the above. I want last_letter to be the last letter of whatever the content is. Where should I place this logic so that it will occur every time a model is saved? I'm reading about Hybrid Properties and stuff and I'm not sure which way is the correct one to go.
kr2sis configauration de Apache --- help please !!! bonjour autre souci que j'ai négligé par nécessité (il a fallu s'occuper du lourd avant de faire le léger...) : apache je ne sais pas si c'est moi qui comprends rien, mais meme en cherchant partout, je ne trouve pas de tuto qui veuille que je réussisse une bonne configuration de site. j'ai tenté de configurer les fichiers "apache2.conf", "ports.conf", "sites-available" sans succes et toujour sles memes messages qui reviennent Restarting web server: apache2[Sat Feb 23 02:44:24 2013] [error] (EAI 2)Name orservice not known: Could not resolve host name www.tralala.fr -- ignoring![Sat Feb 23 02:44:24 2013] [error] (EAI 2)Name or service not known: Could not resolve host name www.tralala.fr -- ignoring![Sat Feb 23 02:44:24 2013] [error] (EAI 2)Name or service not known: Could not resolve host name www.tralala.fr -- ignoring![Sat Feb 23 02:44:24 2013] [error] (EAI 2)Name or service not known: Could not resolve host name www.tralala.fr -- ignoring!Action 'start' failed.The Apache error log may have more information. failed! voici mes différents fichiers : - ports.conf # If you just change the port or add more ports here, you will likely also # have to change the VirtualHost statement in # /etc/apache2/sites-enabled/000-default # This is also true if you have upgraded from before 2.2.9-3 (i.e. from # Debian etch). See /usr/share/doc/apache2.2-common/NEWS.Debian.gz and # README.Debian.gz NameVirtualHost www.tralala.fr:80 Listen 80 <IfModule mod_ssl.c> # If you add NameVirtualHost *:443 here, you will also have to change # the VirtualHost statement in /etc/apache2/sites-available/default-ssl # to <VirtualHost *:443> # Server Name Indication for SSL named virtual hosts is currently not # supported by MSIE on Windows XP. Listen 443 </IfModule> <IfModule mod_gnutls.c> Listen 443 </IfModule> - sites-available/tralala.fr NameVirtualHost *:80 <VirtualHost www.tralala.fr:80> ServerAdmin webmaster@tralalafr ServerName www.tralala.fr ServerAlias *.tralalafr DocumentRoot /media/home/sftp/home/gintoxic/www/ <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /media/home/sftp/home/gintoxic/www/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog /media/home/sftp/homegintoxic/www/tralala.error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /media/home/sftp/home/gintoxic/www/tralala.access.log combi$ </VirtualHost> - apache2.conf # # Based upon the NCSA server configuration files originally by Rob McCool. # # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See http://httpd.apache.org/docs/2.2/ for detailed information about # the directives. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # The configuration directives are grouped into three basic sections: # 1. Directives that control the operation of the Apache server process as a # whole (the 'global environment'). # 2. Directives that define the parameters of the 'main' or 'default' server, # which responds to requests that aren't handled by a virtual host. # These directives also provide default values for the settings # of all virtual hosts. # 3. Settings for virtual hosts, which allow Web requests to be sent to # different IP addresses or hostnames and have them handled by the # same Apache server process. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "foo.log" # with ServerRoot set to "/etc/apache2" will be interpreted by the # server as "/etc/apache2/foo.log". # ### Section 1: Global Environment # # The directives in this section affect the overall operation of Apache, # such as the number of concurrent requests it can handle or where it # can find its configuration files. # # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the LockFile documentation (available # at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>); # you will save yourself a lot of trouble. # # Do NOT add a slash at the end of the directory path. # ServerRoot "/etc/apache2" # # The accept serialization lock file MUST BE STORED ON A LOCAL DISK. # LockFile ${APACHE_LOCK_DIR}/accept.lock # # PidFile: The file in which the server should record its process # identification number when it starts. # This needs to be set in /etc/apache2/envvars # PidFile ${APACHE_PID_FILE} # # Timeout: The number of seconds before receives and sends time out. # Timeout 300 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive On # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 15 ## ## Server-Pool Size Regulation (MPM specific) ## # prefork MPM # StartServers: number of server processes to start # MinSpareServers: minimum number of server processes which are kept spare # MaxSpareServers: maximum number of server processes which are kept spare # MaxClients: maximum number of server processes allowed to start # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # worker MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadLimit: ThreadsPerChild can be changed to this maximum value during a # graceful restart. ThreadLimit can only be changed by stopping # and starting Apache. # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_worker_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0 </IfModule> # event MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule mpm_event_module> StartServers 2 MaxClients 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestsPerChild 0 </IfModule> # These need to be set in /etc/apache2/envvars User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} # # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy all </Files> # # DefaultType is the default MIME type the server will use for a document # if it cannot otherwise determine one, such as from filename extensions. # If your server contains mostly text or HTML documents, "text/plain" is # a good value. If most of your content is binary, such as applications # or images, you may want to use "application/octet-stream" instead to # keep browsers from trying to display binary files as though they are # text. # DefaultType text/plain # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog ${APACHE_LOG_DIR}/error.log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn # Include module configuration: Include mods-enabled/*.load Include mods-enabled/*.conf # Include all the user configurations: Include httpd.conf # Include ports listing Include ports.conf # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # If you are behind a reverse proxy, you might want to change %h into %{X-Forwa$ # LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" $ LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combin$ LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # Include of directories ignores editors' and dpkg's backup files, # see README.Debian for details. # Include generic snippets of statements Include conf.d/ # Include the virtual host configurations: Include /etc/apache2/sites-enabled/[^.#]* pourriez-vous m'aider svp, je tourne en rond et je ne comprends pas ce qu'il me dit... merci par avance Hors ligne tiramiseb Re : configauration de Apache --- help please !!! Salut, Remplace "www.tralala.fr" par "*" dans la configuration. En fait les arguments à "NameVirtualHost" et à "VirtualHost" ne doivent pas correspondre à l'adresse du site à desservir mais à l'adresse IP sur laquelle écouter (ou alors "*" pour "toutes les adresses IP desservies par le serveur"). L'URL du site est précisée dans ServerName (et éventuellement ServerAlias), comme tu l'as correctement fait. PS : attention, il y a des "tralalafr" dans ta configuration là où on s'attendrait à voir "tralala.fr". je ne comprends pas ce qu'il me dit En clair, il te dit : « Désolé monsieur, tu m'as demandé d'écouter sur l'adresse qui correspond à "www.tralala.fr", alors j'ai essayé de résoudre "www.tralala.fr" mais je n'arrive pas à le résoudre dans mes DNS, je ne peux donc pas savoir sur quelle interface écouter... je suis perdu ! Peux-tu me donner une autre instruction pour que je sache sur quelle(s) interface(s) écouter ? Merci ! » Dernière modification par tiramiseb (Le 23/02/2013, à 09:52) En ligne kr2sis Re : configauration de Apache --- help please !!! salut et merci à toi je viens de modofié comme tu l'as judicieusement signalé mais Restarting web server: apache2[Sat Feb 23 11:25:26 2013] [error] (EAI 2)Name orservice not known: Could not resolve host name www.tralala.fr -- ignoring! ... waiting [Sat Feb 23 11:25:27 2013] [error] (EAI 2)Name or service not known: Could not resolve host name www.tralala.fr -- ignoring!. Hors ligne tiramiseb Re : configauration de Apache --- help please !!! Que donne la commande suivante ? grep -r www.tralala.fr /etc/apache2 En ligne kr2sis Re : configauration de Apache --- help please !!! root@debian-server:~# grep -r www.tralala.fr /etc/apache2 /etc/apache2/sites-enabled/tralala.fr: ServerName www.tralala.fr /etc/apache2/ports.conf:NameVirtualHost www.tralala.fr:80 /etc/apache2/sites-available/tralala.fr: ServerName www.tralala.fr Hors ligne za_ian Re : configauration de Apache --- help please !!! que donne le resultat de la commande ping www.tralala.fr Ne laisser jamais à demain ce que l'on peut faire aujourd'hui! Hors ligne kr2sis Re : configauration de Apache --- help please !!! 64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.023 ms 64 bytes from localhost (127.0.0.1): icmp_req=3 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=4 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=5 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=6 ttl=64 time=0.029 ms 64 bytes from localhost (127.0.0.1): icmp_req=7 ttl=64 time=0.027 ms 64 bytes from localhost (127.0.0.1): icmp_req=8 ttl=64 time=0.027 ms 64 bytes from localhost (127.0.0.1): icmp_req=9 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=10 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=11 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=12 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=13 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=14 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=15 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=16 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=17 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=18 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=19 ttl=64 time=0.027 ms 64 bytes from localhost (127.0.0.1): icmp_req=20 ttl=64 time=0.027 ms 64 bytes from localhost (127.0.0.1): icmp_req=21 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=22 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=23 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=24 ttl=64 time=0.027 ms 64 bytes from localhost (127.0.0.1): icmp_req=25 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=26 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=27 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=28 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=29 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=30 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=31 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=32 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=33 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=34 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=35 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=36 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=37 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=38 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=39 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=40 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=41 ttl=64 time=0.023 ms 64 bytes from localhost (127.0.0.1): icmp_req=42 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=43 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=44 ttl=64 time=0.026 ms 64 bytes from localhost (127.0.0.1): icmp_req=45 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=46 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=47 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=48 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=49 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=50 ttl=64 time=0.025 ms 64 bytes from localhost (127.0.0.1): icmp_req=51 ttl=64 time=0.024 ms 64 bytes from localhost (127.0.0.1): icmp_req=52 ttl=64 time=0.025 ms Hors ligne tiramiseb Re : configauration de Apache --- help please !!! za_ian: ne compliquons pas les choses, il n'est pas nécessaire (et même déconseillé) d'utiliser le FQDN du serveur dans la configuration d'Apache2, alors ne cherchons pas à faire marcher cette résolution de nom. En ligne tiramiseb Re : configauration de Apache --- help please !!! root@debian-server:~# grep -r www.tralala.fr /etc/apache2 /etc/apache2/sites-enabled/tralala.fr: ServerName www.tralala.fr /etc/apache2/ports.conf:NameVirtualHost www.tralala.fr:80 /etc/apache2/sites-available/tralala.fr: ServerName www.tralala.fr Dans le fichier ports.conf, tu n'as pas changé : NameVirtualHost www.tralala.fr:80 en : NameVirtualHost *:80 comme je te l'ai suggéré en #2. Il est donc normal que ça ne marche toujours pas, vu que tu n'as pas corrigé la configuration qui ne marche pas. En ligne kr2sis Re : configauration de Apache --- help please !!! ah aussi un truc : quand je tape mon adresse ip locale, je tombe sur la page "it works" mais je l'ai changé dans tralala en "voici mon nouveau site" mais ca ne pointe pas sur le site mais a priori sur "default" Hors ligne tiramiseb Re : configauration de Apache --- help please !!! quand je tape mon adresse ip locale, je tombe sur la page "it works" Le fichier de configuration 000-default est-il toujours présent dans sites-enabled ? Si oui, alors c'est normal que tu tombes en priorité sur celui-là... ... auquel cas tu dois passer clairement par http://www.tralala.fr pour que ça marche. En ligne kr2sis Re : configauration de Apache --- help please !!! euh non , par contre je l'arrete comment le défilé dans le moniteur ? Hors ligne kr2sis Re : configauration de Apache --- help please !!! chou blanc, google ne trouve pas (je n'ai pas encore de serveur DNS, en passant) Hors ligne kr2sis Re : configauration de Apache --- help please !!! Le fichier de configuration 000-default est-il toujours présent dans sites-enabled ? oui Hors ligne tiramiseb Re : configauration de Apache --- help please !!! euh non , par contre je l'arrete comment le défilé dans le moniteur ? Ctrl-C. Le fichier de configuration 000-default est-il toujours présent dans sites-enabled ? oui Donc, comme je l'ai dit, c'est normal que tu obtiennes le "it works". Deux possibilités : 1/ désactiver ce fichier avec la commande "a2dissite" 2/ accéder à ton site avec la bonne URL (éventuellement en entrant l'adresse du serveur dans le fichier /etc/hosts de ta machine...) En ligne kr2sis Re : configauration de Apache --- help please !!! oki je viens d'aller voir dans sites-enabled et il n'avait pas fai les modifs que tu m'as demandé de faire, donc je l'ai fait puis un restart et j'otiens ça : Restarting web server: apache2[Sat Feb 23 12:09:02 2013] [warn] NameVirtualHost*:80 has no VirtualHosts ... waiting [Sat Feb 23 12:09:03 2013] [warn] NameVirtualHost *:80 has no VirtualHosts. je tourne en rond....:rolleyes: Hors ligne tiramiseb Re : configauration de Apache --- help please !!! Que donne la commande suivante ? grep -r VirtualHost /etc/apache2 En ligne kr2sis Re : configauration de Apache --- help please !!! je n'ai plus de message d'erreur suite au fait d'avoir viré la ligne NameVirtualHost *:80 dans ports.conf mais je ne sais pas si mon probleme est réglé.... comment le savoir d'ailleurs puisque je ne suis pas sur de ma config je vais faire ta ligne de commande et je te rapporte le retour Hors ligne kr2sis Re : configauration de Apache --- help please !!! root@debian-server:~# grep -r VirtualHost /etc/apache2 /etc/apache2/sites-enabled/tralala.fr:NameVirtualHost *:80 /etc/apache2/sites-enabled/tralala.fr:<VirtualHost *:80> /etc/apache2/sites-enabled/tralala.fr:</VirtualHost> /etc/apache2/apache2.conf:# If you do not specify an ErrorLog directive within a <VirtualHost> /etc/apache2/apache2.conf:# logged here. If you *do* define an error logfile fo r a <VirtualHost> /etc/apache2/ports.conf:# have to change the VirtualHost statement in /etc/apache2/ports.conf: # If you add NameVirtualHost *:443 here, you will al so have to change /etc/apache2/ports.conf: # the VirtualHost statement in /etc/apache2/sites-av ailable/default-ssl /etc/apache2/ports.conf: # to <VirtualHost *:443> /etc/apache2/conf.d/localized-error-pages:# even on a per-VirtualHost basis. If you include the Alias in the global server /etc/apache2/conf.d/other-vhosts-access-log:# Define an access log for VirtualHo sts that don't define their own logfile /etc/apache2/sites-available/tralala.fr:NameVirtualHost *:80 /etc/apache2/sites-available/tralala.fr:<VirtualHost *:80> /etc/apache2/sites-available/tralala.fr:</VirtualHost> /etc/apache2/sites-available/default:<VirtualHost *:80> /etc/apache2/sites-available/default:</VirtualHost> /etc/apache2/sites-available/default-ssl:<VirtualHost _default_:443> /etc/apache2/sites-available/default-ssl:</VirtualHost> Hors ligne tiramiseb Re : configauration de Apache --- help please !!! Ok, tu dois avoir NameVirtualHost une seule fois, de préférence dans ports.conf. Donc enlève la ligne NameVirtualHost (qui est correcte) de tralala.fr et mets-la dans ports.conf. En l'état actuel ça marche sans problème, mais déplacer cette ligne sera plus propre d'un point de vue logique. En ligne kr2sis Re : configauration de Apache --- help please !!! message en gros "Forbidden" maintenant sur la page web il reconnait mon ip interne et mon serveur Hors ligne tiramiseb Re : configauration de Apache --- help please !!! Là il faut que tu approfondisse en regardant tes logs (access.log et error.log)... En tout cas le problème de VirtualHost que tu avais au début est corrigé. En ligne kr2sis Re : configauration de Apache --- help please !!! oui et je t'en remercie je vais cherché mais je ne sais pas trop quoi chercher en fait... bon je vais déjà aller voir Hors ligne kr2sis Re : configauration de Apache --- help please !!! error log [Sat Feb 23 12:49:10 2013] [crit] [client 74.125.182.24] (13)Permission denied: /media/home/sftp/home/gintoxic/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable Hors ligne tiramiseb Re : configauration de Apache --- help please !!! C'est un problème de droitS. L'utilisateur qui fait tourner Apache2 (www-data) a besoin d'avoir les droits de lecture sur les fichiers concernés. En ligne
kevin54 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) @yvon22 Merci cela marche bien pour mes fichiers de + 2 jours. Mais pour garder les 3 derniers dimanches, cela est possible avec cette commande ? Hors ligne Fenouille84 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Voici un petit script basic pour avoir le flux RSS du site BBC News (section "words in the news") J'en avais besoin pour mettre en forme ce flux et l'afficher dans conky (le parceur xml natif de conky n'y arrivait pas ). Le script : #!/bin/bash # Version 1.0 # Script pour récupérer le flux RSS du site BBC News - Words in the News #Définit le bon dossier DOSS="$HOME/BBC_News" #Se déplacer dans le répertoire de sauvegarde (le créer s'il n'existe pas) [ -d "$DOSS" ] || mkdir "$DOSS" cd "$DOSS" #Supprime l'ancien fichier rm index.xml #Télécharge le flux wget http://www.bbc.co.uk/worldservice/learningenglish/language/wordsinthenews/index.xml #Ne sélectionne que les titre des articles sed -i -n '/title/p' index.xml #Mise en page et sauvegarde cat index.xml | sed '/archive/d' | cut -d ">" -f2 | cut -d "<" -f1 | sed '1d' > $HOME/BBC_News/news.xml #Affichage des 5 premières news head -5 $HOME/BBC_News/news.xml exit 0 Pour changer le nombre de news afficher, il faut modifier le 5 de l'option head. Par exemple pour en afficher 10 : head -10 $HOME/BBC_News/news.xml Et voilà Pour la partie dans conky, c'est ici. Dernière modification par Fenouille84 (Le 27/03/2010, à 13:07) Hors ligne loverboymj Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) bonjour existe t-il un script pour automatiser un raccourci clavier ? c'est pour, avec compiz, activer le plugin water au démarrage. merci ! Hors ligne Slystone Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Oh goody! Thanks a bunch Fenouille, it sounds real interesting! En ligne soupaloignon Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Bonjour à tous, J'ai souvent besoin de travailler sur des photos venant d'APN. Jusqu'à présent j'utilisais plusieurs scripts différents, chacun faisant une tâche précise. Je les ai regroupé en 1 seul script, pour avoir tout ça sous la main et pouvoir faire plusieurs opérations différentes à la suite. Je le poste ici, si ça peut servir.... Son nom : SP-MSI (SouPaloignon - Multi Script Images) Version : 0.1 Utilisation : Se placer dans le répertoire contenant les photos à traiter, lancer le script. Inutile de sélectionner les photos, le script va travailler sur toutes les photos contenues dans le répertoire (et uniquement dans le répertoire, il n'est pas récursif) Pour le moment le script peut faire : Changer la casse : JPG, JPEG, jpeg => jpg / PNG => png Rajouter un intitulé devant le nom original (jpg et png) Renommer en masse sur X chiffres au choix (jpg et png) NE MARCHE PLUS AVEC KARMIC Génére un fichier pdf des photos du répertoire Générer une planche contact en .jpg des images du répertoire (jpg et png) Créer un dossier contenant une copie des photos, retaillées (jpg et png) Renommer dans l'ordre chronologique des photos venant d'APN différents (jpg) Changer la date : Année et/ou mois et/ou jour (heures/minutes/secondes non changés) (jpg) Changer la date et l'heure (Les heures, minutes et secondes seront les mêmes pour toutes les photos)(jpg) Voir les champs dates des données Exif (jpg) PAS FAIT Créer un dossier contenant une copie des photos jpg au format png PAS FAIT Créer un dossier contenant une copie des photos png au format jpg N'hésitez pas à faire vos retours, vos idées de nouvelles fonctionnalités ou d'optimisation de fonctionnalités existantes. J'ai ouvert un fil dédié pour les retours et améliorations, pour éviter de surcharger celui-ci : http://forum.ubuntu-fr.org/viewtopic.php?pid=3371321 ==> Libérez les huitres du bassin d'Arcachon <== Hors ligne Shrat Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Pourquoi le pdf ne marche pas avec karmic? C'est bizarre comme régression! Hors ligne Julientroploin Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Bonjour les gens, je fais un petit double post, désolé, mais j'ai pensé à votre topic juste après avoir posté ailleurs. Je pense que vous êtes les plus à même de résoudre mon problème : Su mon fixe avec un i5, je voudrait mettre les 4 coeurs du proc en "on demand" au démarrage. Je sais qu'on peut le faire avec une applet gnome mais le problème c'est que à chaque re-démarrage il reviens en "performance". je voudrais automatiser tout ça donc je pensais à un petit script qui se lance à l'ouverture de la session. Un volontaire? Si vous pouviez faire aussi le script réciproque, ce serait parfait et ça aiderait d'autres gens ici : http://forum.ubuntu-fr.org/viewtopic.php?pid=2894028#p2894028 En cumulant ceux qui veulent passer de perf à on demand et ceux qui veulent passer de on demand à perf, on est au moins 6 à avoir ce problème. Merci d'avance, j'espère que ma demande est assez claire. Sinon n'hésitez pas à me relancer ici ou là bas. Fixe : Core i5, 4GoRAM, NVidia 9800GT Silent => Raring64 Portable Compaq Presario2158 : AthlonXP-M2400+, 1GoRAM, ATI Radeon mobility320M => Debian stable+Openbox https://launchpad.net/~julienmbpe Hors ligne Fenouille84 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) [ -- Script OpenBox -- ] Bonjour, J'ai un script OpenBox pour les "pipemenu" qui me liste le contenu de mon dossier perso (/home/math/). Ce menu me permet d'ouvrir mes différents fichiers. Toutefois, il se base sur les extensions de ces fichiers... Et vu que c'est mon dossier personnel : beaucoup de fichiers, donc beaucoup d'extensions ; et de fichiers sans extension !! Je préfèrerais que le script se base sur les types MIME des fichiers et non leur extension, c'est possible ?? Je commence à peine le bash, alors imaginez le python... Voici le script : #!/usr/bin/python import os import random from sys import argv mypath = argv[0] def ext_resolver(filename): ext = filename.split('.')[-1] ext = ext.lower() ext_list = {'avi':'vlc', 'mpg':'vlc', 'flv':'vlc', 'wmv':'vlc', 'wma':'vlc', 'mp3':'vlc', 'wav':'vlc', 'pdf':'acroread', 'py' :'gedit', 'txt':'gedit', 'sh' :'gedit', 'php':'gedit', 'xml':'gedit', 'png':'ristretto', 'jpg':'ristretto', 'bmp':'ristretto', 'gif':'ristretto'} if ext in ext_list: return ext_list[ext] else: return 'echo' def dir_list(dircontent): dirs = [] files = [] for item in dircontent: if os.path.isdir(currentpath + '/' + item): dirs.append(item) else: files.append(item) dirs.sort() files.sort() return dirs, files def replacer(string): return string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&apos;') def gen_menu(dirs, files): curpath = replacer(currentpath) print('<openbox_pipe_menu>') print('<item label="Open in Thunar"><action name="execute"><execute>thunar "' + curpath + '"</execute></action></item>') #print('<item label="Shell here..."><action name="execute"><execute>sh -c "cd ' + curpath + ' &amp;&amp; urxvt "</execute></action></item>') print('<separator />') for thisdir in dirs: thisdir = replacer(thisdir) menuid = str(random.randrange(1,99,1)).zfill(2) print(' <menu execute="' + mypath + ' ' + curpath + '/' + thisdir + '" id="' + thisdir + "-" + menuid + '" label="' + thisdir + '"/>') for thisfile in files: thisfile = replacer(thisfile) print(' <item label="' + thisfile + '">') print(' <action name="execute">') print(' <execute>') print(' ' + ext_resolver(thisfile) + ' "' + curpath + '/' + thisfile + '"') print(' </execute>') print(' </action>') print(' </item>') print('</openbox_pipe_menu>') if len(argv) > 1: currentpath = ' '.join(argv[1:]) else: currentpath = "/home/math" try: content = [x for x in os.listdir(currentpath) if x[0] != '.'] parts = dir_list(content) gen_menu(parts[0], parts[1]) except OSError: print('<openbox_pipe_menu>') print('<separator label="No access" />') print('</openbox_pipe_menu>') Merci pour vos réponses Hors ligne nesthib Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) tu peux utiliser la commande file qui te retourne le type de fichier (voir également l'option --mime-type) Hors ligne loke Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) bonjour, je voudrai savoir s'il est possible de crée un scripts permettant de réunir plusieurs pdf ensemble tout en conservent leurs noms dans l'index du pdf a l'heure actuelle j'utilise ceci dans nautilus-scripts: #!/bin/sh # Reunie les pdf en un seul pdftk *.pdf cat output monfichier.pdf et j'obtienne des pages nommer 1,2 est non pas les nom des fichiers. Merci pour vos réponses Dernière modification par loke (Le 02/04/2010, à 08:47) Hors ligne soupaloignon Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Pourquoi le pdf ne marche pas avec karmic? C'est bizarre comme régression! La solution a été trouvée : http://forum.ubuntu-fr.org/viewtopic.php?pid=3375050#p3375050 ==> Libérez les huitres du bassin d'Arcachon <== Hors ligne bugs néo Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Pour reprendre mon dernier post sur ce topic, je ne vais plus demandé si il est possible de remplacé par minicopier ou super copier mais par un script ou un autre moyen le copier coller, et couper coller de thunar et nautilus par un script ou une fonction telle que cp (qui permet de reprendre les transfères qui avait été arrêté en cour), car ni thunar ni nautilus a ma connaissance ne sont capable de reprendre des transfère qui avait été arrêté en cour. Dernière modification par bugs néo (Le 05/04/2010, à 10:12) jeu de course open source earth-race (le jeu est en réécriture complète depuis janvier, afin de pouvoir aller plus vite par la suite) Hors ligne fove2 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Bonjour, j'ai découvert votre topic aujourd'hui et je dois admette que je trouve l'initiative extrêmement intéressante. aussi voulais-je savoir si dolphin/konqueror supportaient les scripts comme nautilus/thunar, car je voudrais ajouter dans leur menu contextuel des premier une option d'ajout d'icone qui demande au user de choisir un png depuis un sélecteur de fichier, (lequel png, après avoir été choisit se verra être copié dans le répertoire concerné par l'attribution de l'icône et enfin) et qui ajoute dans un .directory un chemin relatif vers l'icone du type icone=./.nomDeLIcone.png sa permet de garder la même icône d'un ordi a un autre possible ? cordialement Hors ligne Fenouille84 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) tu peux utiliser la commande filequi te retourne le type de fichier (voir également l'option--mime-type) euh... C'est à dire ? Je sais utiliser la commande file en console, mais je ne vois pas comment l'inclure dans le script python... Hors ligne nesthib Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) oups désolé j'ai lu trop vite, j'avais pas vu le python… tu peux utiliser les commandes bash (os.system par ex) mais c'est pas le plus propre sinon tu as le module mimetypes mimetypes.guess_extension('file.ext') ou gnomevfs gnomevfs.get_mime_type('file:///home/user/file.ext') Hors ligne Rvay Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Voici un petit script basic pour avoir le flux RSS du site BBC News (section "words in the news") J'en avais besoin pour mettre en forme ce flux et l'afficher dans conky (le parceur xml natif de conky n'y arrivait pas ). Hello Fenouille1984, est-ce qu'il y a moyen de récupérer le descriptif qui va avec le titre ? J'ai regardé le xml mais il ne contient que des titres.. Dernière modification par Rvay (Le 03/04/2010, à 13:04) Hors ligne kyncani Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) @Fenouille84,nesthib : sinon, en python, y'a le module magic fournit par le package python-magic. Il utilise la même libmagic que la commande "file". Il permet de déterminer le type du fichier suivant son contenu. A toi de voir si tu arrives à l'utiliser et si il te convient. Hors ligne Fenouille84 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Hello Fenouille1984, est-ce qu'il y a moyen de récupérer le descriptif qui va avec le titre ? J'ai regardé le xml mais il ne contient que des titres.. Si c'est possible. Edit : tiens, essaye un script du genre : #!/bin/bash # Version 1.0 # Script pour récupérer le flux RSS du site BBC News - Words in the News #Définit le bon dossier DOSS="$HOME/BBC_News" #Se déplacer dans le répertoire de sauvegarde (le créer s'il n'existe pas) [ -d "$DOSS" ] || mkdir "$DOSS" cd "$DOSS" #Supprime l'ancien fichier rm index.xml #Télécharge le flux wget http://www.bbc.co.uk/worldservice/learningenglish/language/wordsinthenews/index.xml #Mise en page du fichier index.xml sed -i '1,19d' index.xml ; sed -i '/title/,/summary/!d' index.xml sed -i '/updated/,/published/d' index.xml cat index.xml | sed '/archive/d' | cut -d ">" -f2 | cut -d "<" -f1 > news.xml #Mise en page finale : news.xml sed -i 's/Words in the News.*$/\n/g' news.xml #Affiche le tout (avec gedit !!) gedit news.xml exit 0 Dernière modification par Fenouille84 (Le 05/04/2010, à 18:16) Hors ligne AnsuzPeorth Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) @Fenouille84 Tjrs pas résolu ton problème d'extensions ??? La solution (vite fait): def ext_resolver(filename): #filename='file://'+filename ext = gnomevfs.get_mime_type(filename) ext_list = { 'image/png':'ristretto' 'image/jpeg':'ristretto' 'video/x-ms-wmv':'vlc'} if ext in ext_list: return ext_list[ext] else: return 'echo' En essayant, j'ai remarquais que l'ajout de 'file://' n'était pas nécessaire, à voir ! Je te laisse remplir le dictionnaire . N'oublie pas l'import gnomevfs ... Amuse toi à tester les mimetypes en console: ~$ python >>> import gnomevfs >>> gnomevfs.get_mime_type('/home/machin.png') 'image/png' Interface graphique pour bash, python ou autre: glade2script Support Tchat: http://chat.jabberfr.org/muckl_int/inde … ade2script (Hors ligne) Hors ligne Fenouille84 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Non, toujours pas résolu. J'y connais rien en programmation, et j'ai trouvé une autre solution pour avoir le menu. Donc je laisse tombé pas grave !! Merci pour vos réponses Je testerai à l'occasion. Dernière modification par Fenouille84 (Le 12/04/2010, à 21:02) Hors ligne Barakuda Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Bonjour, J'ai installé BitChe, un moteur de recherche torrent, via wine Je voudrais lancer transmission, mon client torrent, quand je double-clic sur un des torrent de la liste que me déroule BitChe lorsque je fait une recherche. Le developpeur du logiciel avait pondu çà : #!/bin/sh i=`winepath -u "$*"` gnome-btdownload "$i" Seulement depuis de l'eau à coulé sous les ponts, et btdownload a été remplacé par defaut par transmission J'ai essayé de remplacer gnome-btdownload par transmission mais cela ne fonctionne pas si quelqu'un a une solution sa serai sympa Merci Hors ligne bugs néo Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Personne n'a d'idée pour remplacé les copier coller de nautilus et thunar par cp? ou c'est juste que personne n'y porte d'intérêt? jeu de course open source earth-race (le jeu est en réécriture complète depuis janvier, afin de pouvoir aller plus vite par la suite) Hors ligne AnsuzPeorth Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Personne n'a d'idée pour remplacé les copier coller de nautilus et thunar par cp? ou c'est juste que personne n'y porte d'intérêt? C'est vrai que je vois pas trop l'intérêt, les copier coller de nautilus et thunar sont performants ! Maintenant, si tu veux te pondre un truc avec cp, fait des scripts nautilus, un pour copier (qui récupère les URI des fichiers sélectionnés et les copies dans un fichier) et un script coller qui récupère ces URI depuis le fichier pour les coller à l'endroit où tu a appelé le script coller. Interface graphique pour bash, python ou autre: glade2script Support Tchat: http://chat.jabberfr.org/muckl_int/inde … ade2script (Hors ligne) Hors ligne rmy Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) il existe déjà un script bien évolué à ce sujet,non ? Cherches un peu avec "super copieur" ou un truc comme ça... Je regardes plus tard je n'ai pas le temps là... Hors ligne
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) areN-dimensional. Matrix objects are a subclass of ndarray, so they inherit allthe attributes and methods of ndarrays. The main advantage of numpy matrices is that they provide a convenient notationfor matrix multiplication: if a and b are matrices, then a*b is their matrixproduct. import numpy as np a=np.mat('4 3; 2 1') b=np.mat('1 2; 3 4') print(a) # [[4 3] # [2 1]] print(b) # [[1 2] # [3 4]] print(a*b) # [[13 20] # [ 5 8]] Both matrix objects and ndarrays have .T to return the transpose, but matrixobjects also have .H for the conjugate transpose, and .I for the inverse. In contrast, numpy arrays consistently abide by the rule that operations areapplied element-wise. Thus, if a and b are numpy arrays, then a*b is the arrayformed by multiplying the components element-wise: c=np.array([[4, 3], [2, 1]]) d=np.array([[1, 2], [3, 4]]) print(c*d) # [[4 6] # [6 4]] To obtain the result of matrix multiplication, you use np.dot : print(np.dot(c,d)) # [[13 20] # [ 5 8]] The ** operator also behaves differently: print(a**2) # [[22 15] # [10 7]] print(c**2) # [[16 9] # [ 4 1]] Since a is a matrix, a**2 returns the matrix product a*a.Since c is an ndarray, c**2 returns an ndarray with each component squaredelement-wise. There are other technical differences between matrix objects and ndarrays(having to do with np.ravel, item selection and sequence behavior). The main advantage of numpy arrays is that they are more general than2-dimensional matrices. What happens when you want a 3-dimensional array? Thenyou have to use an ndarray, not a matrix object. Thus, learning to use matrixobjects is more work -- you have to learn matrix object operations, andndarray operations. Writing a program that uses both matrices and arrays makes your life difficultbecause you have to keep track of what type of object your variables are, lestmultiplication return something you don't expect. In contrast, if you stick solely with ndarrays, then you can do everythingmatrix objects can do, and more, except with slightly differentfunctions/notation. If you are willing to give up the visual appeal of numpy matrix productnotation, then I think numpy arrays are definitely the way to go. PS. Of course, you really don't have to choose one at the expense of the other,since np.asmatrix and np.asarray allow you to convert one to the other (aslong as the array is 2-dimensional).
pilote [résolu] impossible d'acceder au site adobe.com bonjours, voici le problème -> Firefox ne peut établir de connexion avec le serveur à l'adresse www.adobe.com -> Opéra: Vous tentez d'accéder à l'adresse http://www.adobe.com/, actuellement injoignable... etc. a priori c'est le seul site à me faire ça ! Je ne sais plus quand ça à commencé - je dirais un mois, peut être plus - et surtout je ne vois pas d'où cela peut provenir une idée ? Dernière modification par pilote (Le 28/01/2010, à 14:13) et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne seb0uil Re : [résolu] impossible d'acceder au site adobe.com salut, Chezmoicamarche Mais autrement, que te donne un ping www.adobe.com chez moi : $ ping www.adobe.com PING www.wip3.adobe.com (192.150.8.60) 56(84) bytes of data. 64 bytes from wwis-dubc1-vip60.adobe.com (192.150.8.60): icmp_seq=1 ttl=242 time=98.4 ms Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com chez moy ping www.adobe.com PING www.wip3.adobe.com (192.150.8.60) 56(84) bytes of data. From plume (192.168.1.2) icmp_seq=1 Destination Host Unreachable ping www.yahoo.com PING www-real.wa1.b.yahoo.com (69.147.76.15) 56(84) bytes of data. 64 bytes from f1.www.vip.re1.yahoo.com (69.147.76.15): icmp_seq=1 ttl=52 time=138 ms j'ai la cervelle éteinte From plume (192.168.1.2) c'est mon apache en local il n'y a vraiment que adobe.com qui me fait ça je sêche... et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com cat /etc/resolv.conf domain lan search lan nameserver 192.168.1.254 192.168.1.254 c'est le routeur /etc/hosts 127.0.0.1 localhost 192.168.1.2 plume dada.lan demo.lan local.lan 192.168.1.254 device.lan # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters ff02::3 ip6-allhosts et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne seb0uil Re : [résolu] impossible d'acceder au site adobe.com Comme ca; je verrais bien ca au niveau de ton routeur qui fait donc office de serveur DNS. Si tu essaies de changer l'IP du serveur dans ton /etc/resolv.conf par celle de ton FAI, est ce que cela est mieux ? Hors ligne spatz Re : [résolu] impossible d'acceder au site adobe.com Ca ne marche pas non plus chez moi et sous Windows aussi. Edit : Ah, ça repart. Dernière modification par spatz (Le 28/01/2010, à 10:53) PLOP ! Blogueur ! Râleur ! Agnostique ! Architecte ! Floodeur ! Gentil ! Chiant ! Fourbe ! Crâneur ! GNU/Windows/Linuxien ! Machiavélique ! Beau ! Républicain ! Intelligent ! Bosseur ! Très Prétentieux ! Scientifique ! Frimeur ! Étudiant ! De bonne foi ! Perverti ! Ubunteros ! Grand ! Sociable! Altruiste ! Provoc' ! Censé ! Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com C'est quand même bizarre ! rien n'y fait même avec les ip OpenDNS /etc/resolv.conf #domain lan #search lan #nameserver 192.168.1.254 ## OpenDNS nameserver 208.67.222.222 nameserver 208.67.220.220 comme ci adobe.com était black-listé quelque part nb: le firewall du routeur On ou Off ; ne résoud rien et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com Je ne sais pas ci ça peut être utile ? voici un trace route -> yahoo.com et un trace route -> adobe.com [b]traceroute YAHOO.COM[/b] Hop____Nom d'hôte____Adresse IP____Temps 1____Temps 2 1____plume____192.168.1.2____0.115ms 1____device.lan____192.168.1.254____23.589ms 1____device.lan____192.168.1.254____99.990ms 2____device.lan____192.168.1.254____99.870ms 2____194-79-94-9.nr.ip.pt____194.79.94.9____206.662ms 3____195.23.197.17____195.23.197.17____205.937ms 4____195.23.197.10____195.23.197.10____199.608ms 5____195.219.185.25____195.219.185.25____206.390ms 6____195.219.185.10____195.219.185.10____210.388ms 7____if-14-0-0.mcore3.NJY-Newark.as6453.net____209.58.124.9____303.938ms 8____if-13-0-0-866.core4.AEQ-Ashburn.as6453.net____216.6.57.82____295.738ms 9____64.86.85.34____6____4.86.85.34____295.393ms 10____ae-6.pat2.dce.yahoo.com____216.115.102.176____302.018ms 11____ae1-p151.msr2.re1.yahoo.com____216.115.108.23____298.587ms 12____no____reply____* 13 (idem) 14 (ibidem) 31____no____reply____* [b]traceroute ADOBE.COM[/b]Hop Nom d'hôte Adresse IP Temps 1 Temps 21____plume____192.168.1.2____0.140ms1____plume____192.168.1.2____2002.923ms Curieux autant qu'étrange !! le premier me semble bordelique, mais c'est peut-être normal, pour ce que j'en sais.. le second abandonne avant même d'avoir essayé et toujours pas la moindre idée de ce qui ce passe ! et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne seb0uil Re : [résolu] impossible d'acceder au site adobe.com Oula, avec quelques heures de retard, je viens de voir que tu pinguais la même ip que moi, c donc pas un pb de DNS !! (c'est ca de pas être réveillé !!) Et tu as quoi comme ip / masque réseau sur ton poste ? Dernière modification par seb0uil (Le 28/01/2010, à 13:13) Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com YEP j'ai trouvé le fichier /etc/network/interfaces était dans un état pas possible avec auto eth0 alors que je suis physiquement branché sur eth1 il y avait longtemps que je n'avais fais un sudo /etc/init.d/networking restart résultat 5 plombes pour obtenir du routeur une adresse ip et des avertissements dans tous les sens j'ais remis ça au proprecat /etc/network/interfaces # The loopback network interface auto lo iface lo inet loopback # The primary network interface iface eth1 inet static address 192.168.1.99 netmask 255.255.255.0 gateway 192.168.1.254 auto eth1 et voila -en 3 secondes ça roule et je peux désormais admirer les jolies couleurs du site adobe.com (je ne m'en lasse pas) pourquoi celui là seul merdais? ... mystère si quelqu'un peut m'expliquer pourquoi ça marchait avec yahoo et pas avec adobe... voilou et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne seb0uil Re : [résolu] impossible d'acceder au site adobe.com si quelqu'un peut m'expliquer pourquoi ça marchait avec yahoo et pas avec adobe... voilou L'adresse IP d'adobe est 192.150.8.60 J'imagine que tu avais un masque du type 255.0.0.0 avec une IP 192.168.1.2 Du coup, il tentait de joindre l'ip d'adobe sur ton réseau local, sans interroger la passerelle. Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com le fameux, netmask bien sûr, j'ai bien survolé -il y à longtemps- quelques docs du genre Introduction aux réseaux IP sans approfondir vraiment ...tant que tout marchait! c'est bien fait pour moi. une bonne occasion en tout cas de rafraîchir tout ça merci. Dernière modification par pilote (Le 28/01/2010, à 16:03) et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne thibaultbarron Re : [résolu] impossible d'acceder au site adobe.com Bonsoir. Je suis désolé de faire ressurgir ce vieux sujet mais je rencontre actuellement le même probleme avec mon mac. Je n'arrive pas à accéder au site d'adobe. Seulement je ne sais pas faire grand chose avec le terminal et je ne connais rien aux réseaux donc je n'ai pas compris comment vous avez résolu le problème. Si quelqu'un peut m'éclairer ca serait super. Merci d'avance Hors ligne pilote Re : [résolu] impossible d'acceder au site adobe.com vieux sujet en effet ; maintenant si ton problême est comparable on peut essayer de trouver une solution... adobe.com IP 192.150.16.117 si ton netmask est plus petit que 255.255.255.0 ça ne passe pas > tu es sur mac > ubuntu sur mac ou osX ? si c'est ubuntu > en console donne le resulta de: (menu>applications>accessoires>terminal) ifconfig si c'est osX > heuuu...de memoire tout ce passe dans preference > network / quels est ta valeur pour netmask ? et a part ça Mrs. Kennedy, comment trouvez vous Dallas ? --------------------------------------------------------- 2.6.32-45-generic-pae #101-Ubuntu SMP Mon Dec 3 15:56:38 UTC 2012 i686 GNU/Linux Hors ligne thibaultbarron Re : [résolu] impossible d'acceder au site adobe.com bonjour et merci pour ta réponse. alors dans préférences, j'ai trouvé un truc qui s'appelle subnet mask de valeur 255.255.255.0 Hors ligne Ignace Re : [résolu] impossible d'acceder au site adobe.com Bonsoir, J'ai un problème similaire, qui est apparu alors que j'étais sous Ubuntu 10.04 , et qui demeure après la mise à niveau 12.04.1 Il y a un site en particulier où je n'arrive plus à me connecter, (alors que je peux m'y connecter sous windows XP). Mes différents navigateurs (Firefox, Epiphany, Chromium) affichent une page comme quoi le site est en construction, ou alors une erreur 404. Voici le site en question (ce n'est pas Adobe cette fois-ci) : http://www.landcruising-slacklines.de J'ai cru que ça venait d'un problème avec Java JRE que j'ai par ailleurs, mais l'administrateur du site vient de m'indiquer qu'il n'utilise pas Java. Un essai dans le terminal : ping http://www.landcruising-slacklines.de ping: unknown host http://www.landcruising-slacklines.de et à titre de comparaison : ping www.facebook.fr 64 bytes from www-slb-10-12-prn1.facebook.com (69.171.237.16): icmp_req=30 ttl=242 time=193 ms Par ailleurs, ifconfig eth1 Link encap:Ethernet HWaddr 00:1d:60:30:de:40 inet adr:192.168.0.11 Bcast:192.168.0.255 Masque:255.255.255.0 adr inet6: 2a01:e35:2e4d:4100:21d:60ff:fe30:de40/64 Scope:Global adr inet6: fe80::21d:60ff:fe30:de40/64 Scope:Lien adr inet6: 2a01:e35:2e4d:4100:dc62:28d8:ffa4:9bdd/64 Scope:Global UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 Packets reçus:141565 erreurs:0 :0 overruns:0 frame:0 TX packets:106156 errors:0 dropped:0 overruns:0 carrier:2 collisions:0 lg file transmission:1000 Octets reçus:185020718 (185.0 MB) Octets transmis:11086029 (11.0 MB) lo Link encap:Boucle locale inet adr:127.0.0.1 Masque:255.0.0.0 adr inet6: ::1/128 Scope:Hôte UP LOOPBACK RUNNING MTU:16436 Metric:1 Packets reçus:5857 erreurs:0 :0 overruns:0 frame:0 TX packets:5857 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 lg file transmission:0 Octets reçus:625550 (625.5 KB) Octets transmis:625550 (625.5 KB) et le contenu de mon fichier etc/network/interfaces est le suivant : auto loiface lo inet loopback Mon ordi est physiquement connecté à Internet par un câble ethernet sur l'interface eht1, sur une Freebox. J'avoue que je ne sais pas comment faire... Ubuntu 12.04 LTS ; Intel Core i5-4690 3,50 GHz ; 8 GO de RAM CM : MSI G97-Z43 A part ça, je ne suis pas un numéro. Hors ligne lynn Re : [résolu] impossible d'acceder au site adobe.com ... Un essai dans le terminal :<metadata lang=INI prob=0.09 /> ping http://www.landcruising-slacklines.de ping: unknown host http://www.landcruising-slacklines.de ... Bonjour, Ton site est accessible, je te le confirme et en enlevant "http://www.", le ping fonctionne Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ignace Re : [résolu] impossible d'acceder au site adobe.com Bonsoir Lynn, Je viens de réessayer, voilà ce que ça donne : ping www.landcruising-slacklines.de/ ping: unknown host www.landcruising-slacklines.de/ ping landcruising-slacklines.de/ ping: unknown host landcruising-slacklines.de/ ping landcruising-slacklines.de PING landcruising-slacklines.de (83.169.23.194) 56(84) bytes of data. 64 bytes from landcruising-slacklines.de (83.169.23.194): icmp_req=1 ttl=51 time=38.0 ms Pourtant, en essayant toutes ces adresses dans mes navigateurs internet, je retombe toujours sur les mêmes messages d'erreur (alors que je sais que le site est accessible) : This site is currently under construction. Please try again later. Comment est-ce possible ? J'ai vidé le cache de Firefox, rien n'y fait... Ubuntu 12.04 LTS ; Intel Core i5-4690 3,50 GHz ; 8 GO de RAM CM : MSI G97-Z43 A part ça, je ne suis pas un numéro. Hors ligne
#0 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 24/08/2010, à 14:57 Nemile Réponses : 809 Bonjour à tous, après avoir lu l'ensemble du topic, et essayé plusieurs manips, je vous poste mon problème. J'ai installé dofus avec la procédure de yoann21, et cela marchait très bien avant ce matin. En effet, en voulant télécharger une mise à jour, l'updater a planté (problème de patch je crois). Sur le coup je n'ai pas regardé les forums, et j'ai désinstallé puis réinstallé dofus. En redémarrant l'updater, celui ci fait la première mise à jour, puis doit redémarrer. Ensuite il redémarre donc, et là il reste 5 secondes, puis se ferme. Je précise que face à ce problème, j'ai désinstallé puis réinstallé plusieurs fois alternativement avec le script de ankama et les paquets de yoann21. Le terminal me répond après lancement de l'updater: "Erreur de segmentation". J'ai installé la version adobeair de yoann21, que j'ai mise à jour par l'intermédiaire du gestionnaire de paquets. Ca n'a pas l'air de changer grand chose. Par ailleurs, et ça n'a pas de rapport avec mon problème, j'ai une livebox, et j'avais trouvé sur internet une solution pour le problème de connexion qui consistait à rajouter une ligne dans un fichier dans etc/.../... donc je vais chercher et si je retrouve je vous poste ça. Merci de votre aide future EDIT: Voilà retrouvé pour ceux qui ont une livebox cette solution a marché pour moi, sans besoin d'utiliser un proxy. "1- Ouvrir /etc/hosts en root sudo gedit /etc/hosts 2- Ajouter l'adresse IP du serveur de dl Ankama, avec l'host demandé par le jeu à la fin du fichier (le jeu cherche dl.ak.ankama.com, et l'IP est celle du serveur final, a337.g.akamai.net. Elle pourrait varier, à la vue de son nom) 213.200.108.51 dl.ak.ankama.com 3- Enregistrer le fichier, quitter gedit et relancer Dofus 2" d'après Rallymen007 sur ce lien http://forum.ubuntu-fr.org/viewtopic.php?id=395299 #2 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 24/08/2010, à 17:35 Nemile Réponses : 809 Voici le résultat nem@nem-laptop:~$ ldd ~/Dofus_Paquet/share/UpLauncher linux-gate.so.1 => (0x00692000) libidn.so.11 => /usr/lib/libidn.so.11 (0x004cb000) liblber-2.4.so.2 => /usr/lib/liblber-2.4.so.2 (0x00110000) libldap_r-2.4.so.2 => /usr/lib/libldap_r-2.4.so.2 (0x0035b000) libgssapi_krb5.so.2 => /usr/lib/libgssapi_krb5.so.2 (0x00b66000) libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0x00693000) libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0x00574000) libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0x0048d000) libpangoft2-1.0.so.0 => /usr/lib/libpangoft2-1.0.so.0 (0x00b36000) libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0x00b1c000) libgio-2.0.so.0 => /usr/lib/libgio-2.0.so.0 (0x00cdd000) libpango-1.0.so.0 => /usr/lib/libpango-1.0.so.0 (0x00dce000) libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0x00138000) libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0x001ae000) libgobject-2.0.so.0 => /usr/lib/libgobject-2.0.so.0 (0x001de000) libgmodule-2.0.so.0 => /usr/lib/libgmodule-2.0.so.0 (0x0011d000) libgthread-2.0.so.0 => /usr/lib/libgthread-2.0.so.0 (0x0044f000) librt.so.1 => /lib/tls/i686/cmov/librt.so.1 (0x00122000) libglib-2.0.so.0 => /lib/libglib-2.0.so.0 (0x00b95000) libXinerama.so.1 => /usr/lib/libXinerama.so.1 (0x0012c000) libSM.so.6 => /usr/lib/libSM.so.6 (0x003eb000) libpng12.so.0 => /lib/libpng12.so.0 (0x00fb1000) libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x00518000) libz.so.1 => /lib/libz.so.1 (0x0021d000) libdl.so.2 => /lib/tls/i686/cmov/libdl.so.2 (0x00130000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00e11000) libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0x00232000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00258000) libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0x00fd6000) libpthread.so.0 => /lib/tls/i686/cmov/libpthread.so.0 (0x00277000) libX11.so.6 => /usr/lib/libX11.so.6 (0x02a18000) libexpat.so.1 => /lib/libexpat.so.1 (0x002bb000) libresolv.so.2 => /lib/tls/i686/cmov/libresolv.so.2 (0x002e2000) libsasl2.so.2 => /usr/lib/libsasl2.so.2 (0x002f6000) libgnutls.so.26 => /usr/lib/libgnutls.so.26 (0x00a68000) libkrb5.so.3 => /usr/lib/libkrb5.so.3 (0x032b3000) libk5crypto.so.3 => /usr/lib/libk5crypto.so.3 (0x0030e000) libcom_err.so.2 => /lib/libcom_err.so.2 (0x00134000) libkrb5support.so.0 => /usr/lib/libkrb5support.so.0 (0x00290000) libkeyutils.so.1 => /lib/libkeyutils.so.1 (0x002b5000) libXext.so.6 => /usr/lib/libXext.so.6 (0x00332000) libXrender.so.1 => /usr/lib/libXrender.so.1 (0x00342000) libXi.so.6 => /usr/lib/libXi.so.6 (0x0034c000) libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0x003a2000) libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0x003aa000) libpangocairo-1.0.so.0 => /usr/lib/libpangocairo-1.0.so.0 (0x003b4000) libXcomposite.so.1 => /usr/lib/libXcomposite.so.1 (0x003c0000) libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0x00c9a000) libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0x003c4000) libcairo.so.2 => /usr/lib/libcairo.so.2 (0x0060a000) libpcre.so.3 => /lib/libpcre.so.3 (0x003f4000) libselinux.so.1 => /lib/libselinux.so.1 (0x003ca000) /lib/ld-linux.so.2 (0x00298000) libICE.so.6 => /usr/lib/libICE.so.6 (0x00425000) libuuid.so.1 => /lib/libuuid.so.1 (0x003e5000) libxcb.so.1 => /usr/lib/libxcb.so.1 (0x00455000) libtasn1.so.3 => /usr/lib/libtasn1.so.3 (0x0043e000) libgcrypt.so.11 => /lib/libgcrypt.so.11 (0x00f07000) libpixman-1.so.0 => /usr/lib/libpixman-1.so.0 (0x06c40000) libdirectfb-1.2.so.0 => /usr/lib/libdirectfb-1.2.so.0 (0x1ff6d000) libfusion-1.2.so.0 => /usr/lib/libfusion-1.2.so.0 (0x0046f000) libdirect-1.2.so.0 => /usr/lib/libdirect-1.2.so.0 (0x004a9000) libxcb-render-util.so.0 => /usr/lib/libxcb-render-util.so.0 (0x00479000) libxcb-render.so.0 => /usr/lib/libxcb-render.so.0 (0x0047e000) libXau.so.6 => /usr/lib/libXau.so.6 (0x00f90000) libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0x00486000) libgpg-error.so.0 => /lib/libgpg-error.so.0 (0x00564000) nem@nem-laptop:~$ EDIT: je suis sous ubuntu 10.04 #3 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 24/08/2010, à 19:14 Nemile Réponses : 809 J'ai essayé à nouveau de tout désinstaller et de tout réinstaller (j'ai vu sur certains forums que ça avait réglé le problème pour certains) mais ça ne change rien. Ma procédure de désinstallation est la suivante: suppression complète des paquets dofus2.0 et adobeair avec le gestionnaire de paquets. #4 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 24/08/2010, à 20:40 Nemile Réponses : 809 Nemile a écrit : J'ai essayé à nouveau de tout désinstaller et de tout réinstaller (j'ai vu sur certains forums que ça avait réglé le problème pour certains) mais ça ne change rien. Ma procédure de désinstallation est la suivante: suppression complète des paquets dofus2.0 et adobeair avec le gestionnaire de paquets. Pour le désinstaller complètement, supprime le répertoire ~/Dofus_paquet après avoir désinstallé le paquet, on sait jamais (même si le script de postrm est censé le faire). Sinon peux-tu me détailler les différentes manip que tu as tenté ? J'ai essayé ça: rm -rf ~/Dofus_Paquet/share/.uplauncher Mais sans succès... #5 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 25/08/2010, à 00:10 Nemile Réponses : 809 Bon j'ai essayé les commandes de narak pour voir, étant complètement perdu, vu que ça marchait avant cette mise à jour, mais sans succès, ça ne change rien. Quand je réinstalle l'uplauncher fait bien la première mise à jour, puis dis qu'il faut le redémarrer, je clique alors sur ok, il redémarre et disparait au bout de quelques secondes. Je ne vois pas d'où vient cette erreur de segmentation. EDIT: Au hasard, si ça peut t'aider: nem@nem-laptop:~$ ls -l $HOME/Dofus_Paquet/share total 10956 -rwxr-xr-x 1 nem nem 1010704 2009-12-02 13:29 7z -rw-r--r-- 1 nem nem 0 2010-08-25 00:24 com.ankama.dofus2.lock -rw-r--r-- 1 nem nem 1394383 2010-04-02 16:16 DofusInvoker.swf -rw-r--r-- 1 nem nem 160 2010-04-02 16:16 games.xml drwxr-xr-x 2 nem nem 4096 2010-08-25 00:24 icon -rwxr-xr-x 1 nem nem 29 2009-12-02 13:41 launch-dofus.sh drwxr-xr-x 3 nem nem 4096 2010-08-25 00:24 META-INF -rw-r--r-- 1 nem nem 59 2010-04-02 16:16 mimetype drwxr-xr-x 4 nem nem 4096 2010-08-25 00:24 reg -rwxr--r-- 1 nem nem 8741140 2010-08-25 00:24 UpLauncher -rw-r--r-- 1 nem nem 7275 2010-08-25 00:24 uplauncher.log -rw-r--r-- 1 nem nem 526 2010-08-25 00:24 uplauncher.xml -rw-r--r-- 1 nem nem 1 2010-08-25 00:24 _upl.crc Je ne vois pas quoi faire d'autre. #6 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 25/08/2010, à 00:31 Nemile Réponses : 809 Peut-être une piste, ce matin j'ai essayé de téléchargé avant l'erreur de patch à 96%. Peut-être que ces 96% ont été effectivement téléchargés et sont quelque part, il faudrait peut-être les supprimer pour que tout se passe bien? Désolé si ce que je dis n'a aucun sens ^^' EDIT: lorsque je tape sudo apt-get remove dofus2.0 --purge pas de problème mais sudo apt-get remove adobeair --purge me renvoit: Suppression de adobeair ... Purge des fichiers de configuration de adobeair ... dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /etc/opt » n'était pas vide, donc il n'a pas été supprimé. dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /var/opt/Adobe AIR/Shared/Adobe/AIR/Updater » n'était pas vide, donc il n'a pas été supprimé. dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /var/opt/Adobe AIR/Shared/Adobe/AIR » n'était pas vide, donc il n'a pas été supprimé. dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /var/opt/Adobe AIR/Shared/Adobe » n'était pas vide, donc il n'a pas été supprimé. dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /var/opt/Adobe AIR/Shared » n'était pas vide, donc il n'a pas été supprimé. dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /var/opt/Adobe AIR » n'était pas vide, donc il n'a pas été supprimé. dpkg : avertissement : lors de la suppression de adobeair, le répertoire « /var/opt » n'était pas vide, donc il n'a pas été supprimé. Est-ce en rapport avec mon problème? #10 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 29/08/2010, à 23:39 Nemile Réponses : 809 Voilà pour la première: nem@nem-laptop:~$ ls -l ~/Dofus_Paquet/share total 10956 -rwxr-xr-x 1 nem nem 1010704 2009-12-02 13:29 7z -rw-r--r-- 1 nem nem 0 2010-08-29 23:37 com.ankama.dofus2.lock -rw-r--r-- 1 nem nem 1394383 2010-04-02 16:16 DofusInvoker.swf -rw-r--r-- 1 nem nem 160 2010-04-02 16:16 games.xml drwxr-xr-x 2 nem nem 4096 2010-08-29 23:35 icon -rwxr-xr-x 1 nem nem 29 2009-12-02 13:41 launch-dofus.sh drwxr-xr-x 3 nem nem 4096 2010-08-29 23:35 META-INF -rw-r--r-- 1 nem nem 59 2010-04-02 16:16 mimetype drwxr-xr-x 4 nem nem 4096 2010-08-29 23:35 reg -rwxr--r-- 1 nem nem 8741140 2010-08-29 23:37 UpLauncher -rw-r--r-- 1 nem nem 7356 2010-08-29 23:37 uplauncher.log -rw-r--r-- 1 nem nem 526 2010-08-29 23:37 uplauncher.xml -rw-r--r-- 1 nem nem 1 2010-08-29 23:36 _upl.crc et voilà pour la deuxième : nem@nem-laptop:~$ ls -l ~/Dofus_Paquet/share/.uplauncher total 1392 -rw-r--r-- 1 nem nem 1413805 2010-08-29 23:37 patch_0.0_2.1.4.32503.1_base_MultiPlatform.zip -rw-r--r-- 1 nem nem 7 2010-08-29 23:37 patch_0.0_2.1.4.32503.1_base_MultiPlatform.zip.crc #11 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 03/09/2010, à 00:43 Nemile Réponses : 809 J'ai installé le nouveau paquet, et j'ai toujours le même problème... Je suis maudit EDIT: Par contre avec cette version, j'ai plus qu'un simple "erreur de segmentation": /usr/bin/Dofus_Uplauncher: line 30: 4714 Erreur de segmentation /opt/Dofus_Paquet/share/UpLauncher Encore cette ligne 30 on dirait... Chez moi la ligne 30 est la fermeture en "fi", bizarre non? #13 Re : -1 » [tuto]Installation de Dofus 2.0 par paquet debian et rpm (pour la doc) » Le 04/09/2010, à 00:32 Nemile Réponses : 809 Mais si on regarde dans "logs" pendant les 5sec ou l'updater est lancé, on voit qu'il télécharge, et à chaque fois qu'on le redémarre il reprend où il en était (comme cela a déjà été dit plus tôt dans le sujet), sauf que ça serait beaucoup trop long de redémarrer en boucle pour tout télécharger. #18 Re : -1 » (3) Conky : Postez vos conkyrc ou certaines parties intéressantes » Le 31/07/2009, à 19:41 Nemile Réponses : 3258 Euh ça bug toujours, voici l'erreur que me retourne conky : Can't locate Mail/POP3Client.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.0 /usr/local/share/perl/5.10.0 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .) at /home/nem/scripts/email.pl line 25. BEGIN failed--compilation aborted at /home/nem/scripts/email.pl line 25. Et voici mon script (j'ai enlevé le mot de passe ^^) : #!/usr/bin/perl # beginning of configuration # pop3 host $pop_host = "pop3.live.com"; # pop3 username $pop_user = "emile_re"; # pop3 password $pop_pass = "monmotdepasse"; # ssl port number $ssl_port = "995"; # ssl protocol $ssl_prot = "tcp"; # number of emails to show $dis_numb = "5"; # end of configuration use emile_re@hotmail.com::POP3Client; use IO::Socket::SSL; my $socket = IO::Socket::SSL->new( PeerAddr => $pop_host, PeerPort => $ssl_port, Proto => $ssl_prot); my $pop = emile_re@hotmail.com::POP3Client->new(); $pop->User($pop_user); $pop->Pass($pop_pass); $pop->Socket($socket); $pop->Connect(); $msg_count = $pop->Count(); for ($i = $msg_count, $j = 0; $i >= $msg_count-($dis_numb-1); $i--, $j++) { foreach ( $pop->Head( $i ) ) { #/^(From|Subject):\s+/i and print $_, "\n"; if ($_ =~ m/^From:/) { ($from) = ($_ =~ m#^From: .*<(.*)>#); $from = substr($from, 0, 30); $out .= "$j = $from\n"; } } #chop $out; `echo -e "$out"> ~/.gmail/.gmail_top`; } $pop->Close(); #20 Re : -1 » (3) Conky : Postez vos conkyrc ou certaines parties intéressantes » Le 31/07/2009, à 20:50 Nemile Réponses : 3258 J'ai trouvé ce script sur gnome-look mais il est en espagnol et je ne connais pas du tout le langage python.. Si quelqu'un pouvait m'éclairer Voici le script : #!/usr/bin/env python #-*- coding: UTF-8 -*- import sys import urllib import feedparser _URL = "http://www.palmeteo.com/hotmailrss/authent.php" usuario = sys.argv[1] password = sys.argv[2] max_correos = int(sys.argv[3]) urllib.FancyURLopener.prompt_user_passwd = lambda self, host, realm: ("%s@hotmail.com" % usuario, password) def ContarCorreo(cant, spam = 0): print 'Hotmail${alignr}%s correo%s nuevo%s%s' % (cant, cant != 1 and 's' or '', cant != 1 and 's' or '', spam > 0 and (' y %s spam' % spam) or '') return def ImprimirCorreo(atom, num): de = atom.entries[num].author asunto = atom.entries[num+1].title print '> %20.20s%s : %20.20s%s' % (de, len(de) >= 25 and '...%s' % de[len(de)-5:len(de)] or '', asunto, len(asunto) >= 25 and '...%s' % asunto[len(asunto)-5:len(asunto)] or '') return def auth(): opener = urllib.FancyURLopener() f = opener.open(_URL) feed = f.read() return feed def readmail(feed): atom = feedparser.parse(feed) nuevos = atom.entries[0].title.split(';') try: correos = int(nuevos[0][0]) spam = int(nuevos[1][1]) ContarCorreo(correos, spam) except ValueError, error: print 'Hotmail: No se pudo obtener el número de correos' correos = 0 spam = 0 if correos > 0: if correos > max_correos: for msg_num in range(max_correos): ImprimirCorreo(atom, ((msg_num * 2) + 1)) continue else: for msg_num in range(correos): ImprimirCorreo(atom, ((msg_num * 2) + 1)) continue return if __name__ == "__main__": f = auth() readmail(f) #21 Re : -1 » probleme de conversion avec downloadhelper » Le 09/05/2010, à 13:40 Nemile Réponses : 0 Bonsoir. Voici mon problème. J'ai un petit écran oled sur mon pc, et je voudrais le désactiver car il affiche un logo ASUS et à force cela risque de brûler l'écran. J'ai donc utilisé le wiki de mon pc (asus g1s) pour ce faire. Il propose un paquet que j'avais déjà installé précédemment sur une autre version d'ubuntu, et qui fonctionnait parfaitement. Il permet de faire plusieurs actions relatives à cet écran, et entre autre de le désactiver avec la commande asusoled -d. Mais quand je rentre cette dernière dans le terminal, il me renvoit la réponse: nem@Nem-Laptop:~$ asusoled -d Could not claim USB interface aren't you root? "rmmod usbhid" and try again... Et ce quelque soit la commande asusoled -X. J'ai essayé avec sudo, j'ai essayé en tapant au préalable "sudo -i" et de taper "rmmod usbhid" mais rien y fait... Quelqu'un aurait-il une petite idée? Merci . Nemile Nemile Réponses : 13 Je relance le sujet J'ai bien créé mon compte MSN avec mon addresse Gmail, ça fonctionne nikel.. Mais comment faire pour changer le pseudo sous lequel les autres nous voients? Parce que là ils voient mon addresse gmail, et lorsque je veux changer l'alias j'ai le droit à: Erreur MSN : Compte Passeport non vérifié Quelqu'un a une idée? Merci
I had items that scraped from a site which i placed them in to json files like below { "author": ["TIM ROCK"], "book_name": ["Truk Lagoon, Pohnpei &amp; Kosrae Dive Guide"], "category": "Travel", } { "author": ["JOY"], "book_name": ["PARSER"], "category": "Accomp", } I want to store them in csv file with one dictionary per one row in which one item per one column as below | author | book_name | category || TIM ROCK | Truk Lagoon ... | Travel || JOY | PARSER | Accomp | i am getting the items of one dictionary in one row but with all the columns combined My pipeline.py code is import csv class Blurb2Pipeline(object): def __init__(self): self.brandCategoryCsv = csv.writer(open('blurb.csv', 'wb')) self.brandCategoryCsv.writerow(['book_name', 'author','category']) def process_item(self, item, spider): self.brandCategoryCsv.writerow([item['book_name'].encode('utf-8'), item['author'].encode('utf-8'), item['category'].encode('utf-8'), ]) return item
We make an observation that when Ai < Bj, then it must be true that Ai < Bj-1. On the other hand, if Bj < Ai, then Bj < Ai-1.. How can it be true for any i and j? It isn't true for all pairs of i and j. The article considers a special situation. First, it is assumed that there are no duplicates, not even in the form of common elements of A and B. Second, the conclusion that Ai < Bj ==> Ai < Bj-1, resp. Bj < Ai ==> Bj < Ai-1 is made under the condition that neither of Bj-1 < Ai < Bj resp. Ai-1 < Bj < Ai holds. So by excluding these configurations, Ai < Bj ==> Ai <= Bj-1 and Bj < Ai ==> Bj <= Ai-1 follow immediately, and the strict inequalities then follow by the assumption that no duplicates exist. We try to approach this tricky problem by comparing middle elements of A and B, which we identify as Ai and Bj. If Ai is between Bj and Bj-1, we have just found the i+j+1 smallest element In array B, there are j elements smaller than Bj, and in array A, there are i elements smaller than Ai (indices start at 0). So if Bj-1 < Ai < Bj, both arrays together contain exactly j + i elements that are smaller than Ai. What changes if there are duplicates? Not much. We still consider the situation where i + j = k-1. Let us assume that Ai <= Bj. What if Ai = Bj? What if Ai < Bj? In case 1., let m be the smallest index such that Am = Ai, and n the smallest index such that Bn = Bj. Then in both arrays together, there are exactly m + n <= i + j = k-1 elements strictly smaller than Ai, and at least (i+1) + (j+1) = (k+1) elements not larger than Ai. Hence the k-th smallest element is equal to Ai. For 2., we have three cases to consider, a) Bj-1 < Ai, b) Bj-1 = Ai, c) Bj-1 > Ai. In case a), we have j elements in B that are not larger than Ai, and they are all strictly smaller, and we have m <= i elements in A that are strictly smaller than Ai (m as above) and an unkown number, but at least i-m+1 elements equal to Ai. So there are exactly j + m <= j + i = k-1 elements in both arrays together that are strictly smaller than Ai, and at least j + m + (i-m+1) = j+i+1 = k elements not larger than Ai, hence the k-th smallest element of both arrays together is equal to Ai. In case b), the same reasoning shows that the k-th smallest element of both arrays together is equal to Ai. In the remaining case, Ai < Bj-1, things become hardly more complicated. Array B contains at least j elements not larger than Bj-1, and array A contains at least i+1 elements strictly smaller than Bj-1, hence the k-th smallest element of both arrays together is at most as large as Bj-1. But it cannot be smaller than Ai (B contains at most j-1 elements smaller than Ai, so both arrays together contain at most i + (j-1) = k-2 elements smaller than Ai). So we can still discard the part below Ai from the array A and the part above Bj-1 from the array B and proceed as without duplicates. All that changed was that a few strict inequalities had to be replaced with weak inequalities. The code (would be more efficient if starting indices and lengths were passed instead of slicing, but slicing yields shorter code): def kthsmallest(A, B, k): if k < 1: return None a_len, b_len = len(A), len(B) if a_len == 0: return B[k-1] # let it die if B is too short, I don't care if b_len == 0: return A[k-1] # see above # Handle edge case: if k == a_len + b_len, we would # get an out-of-bounds index, since i + j <= a_len+b_len - 2 # for valid indices i and j if a_len + b_len == k: if A[-1] < B[-1]: return B[-1] else: return A[-1] # Find indices i and j approximately proportional to len(A)/len(B) i = (a_len*(k-1)) // (a_len+b_len) j = k-1-i # Make sure the indices are valid, in unfortunate cases, # j could be set to b_len by the above if j >= b_len: j = b_len-1 i = k-1-j if A[i] <= B[j]: if j == 0 or B[j-1] <= A[i]: return A[i] # A[i] < B[j-1] <= B[j] return kthsmallest(A[i:], B[:j], k-i) # B[j] < A[i], symmetrical to A[i] < B[j] if i == 0 or A[i-1] <= B[j]: return B[j] # B[j] < A[i-1] return kthsmallest(A[:i], B[j:], k-j)
I'm implementing a Flicker Client for the IPhone, and I am using OAuth I managed to request the tokens successfully as well as redirecting the user to the authentication page, My problem is when I try to ask for the access token I receive: oauth_problem=signature_invalid Here's my header: header OAuth realm="", oauth_callback="oob", oauth_consumer_key="XXXXX", oauth_token="XXXX", oauth_verifier="XXXX", oauth_signature_method="HMAC-SHA1", oauth_signature="XX", oauth_timestamp="1309773699", oauth_nonce="XXX", oauth_version="1.0" and here's my Base String: POST&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Faccess_token& oauth_consumer_key%3DXXXX%26 oauth_nonce%3DXXXX%26 oauth_signature_method%3DHMAC-SHA1%26 oauth_token%3DXXXX%26 oauth_timestamp%3D1309773699%26 oauth_verifier%3DXXXX%26 oauth_version%3D1.0 Thank you in advance,
#2676 Le 15/02/2013, à 19:14 mulder29 Re : TVDownloader: télécharger les médias du net ! Et je reçois python: can't open file alors que j'ai installé Python 2.7.3, hier. Hors ligne #2677 Le 15/02/2013, à 19:26 k3c Re : TVDownloader: télécharger les médias du net ! si tu tapes which python ça affiche quoi ? Dernière modification par k3c (Le 15/02/2013, à 19:28) Hors ligne #2678 Le 15/02/2013, à 20:20 mulder29 Re : TVDownloader: télécharger les médias du net ! ça affiche : /usr/bin/python Hors ligne #2679 Le 15/02/2013, à 22:38 JessicaNichenin Re : TVDownloader: télécharger les médias du net ! j'utilise la version 0.6 du script et cela ne marche plus python get.py http://videos.tf1.fr/unforgettable/episode-16-saison-01-la-fille-de-l-air-7817948.html ['rtmpdump', '-r', 'rtmpte://wske.wat.tv/ondemand/mp4:vod/H264-384x288/31/87/9433187.h264', '-c', '1935', '-m', '10', '-w', 'ebb7a6fbdc9021db95e2bd537d73fabb9717508f085bea50bde75f7a8e27698c', '-x', '343642', '-o', 'episode-16-saison-01-la-fille-de-l-air-7817948.mp4', ' --resume'] Erreur : le sous-process s'est terminé avec (le code d'erreur est 1) Erreur : le sous-process s'est terminé avec (le code d'erreur est 1) Erreur : le sous-process s'est terminé avec (le code d'erreur est 1) Erreur : le sous-process s'est terminé avec (le code d'erreur est 1) Merci pour ce merveilleux script Hors ligne #2680 Le 16/02/2013, à 00:17 k3c Re : TVDownloader: télécharger les médias du net ! Cette version est peu testée, mais télécharge les 3 épisodes de Unforgettable # -*- coding:utf-8 -*- # TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable import subprocess, optparse, re, sys, shlex import socket from urllib2 import urlopen import time, md5, random, urllib2 import bs4 as BeautifulSoup listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.', 'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori', 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1', 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ] def get_wat(id): def base36encode(number): if not isinstance(number, (int, long)): raise TypeError('number must be an integer') if number < 0: raise ValueError('number must be positive') alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' base36 = '' while number: number, i = divmod(number, 36) base36 = alphabet[i] + base36 return base36 or alphabet[0] ts = base36encode(int(time.time())) timesec = hex(int(ts, 36))[2:] while(len(timesec)<8): timesec = "0"+timesec token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest() id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR" return id_url1 def main(): gg@gg-SATELLITE-L755:~$ cat !$ cat hd3.py # -*- coding:utf-8 -*- # TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable import subprocess, optparse, re, sys, shlex import socket from urllib2 import urlopen import time, md5, random, urllib2 import bs4 as BeautifulSoup listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.', 'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori', 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1', 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ] def get_wat(id): def base36encode(number): if not isinstance(number, (int, long)): raise TypeError('number must be an integer') if number < 0: raise ValueError('number must be positive') alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' base36 = '' while number: number, i = divmod(number, 36) base36 = alphabet[i] + base36 return base36 or alphabet[0] ts = base36encode(int(time.time())) timesec = hex(int(ts, 36))[2:] while(len(timesec)<8): timesec = "0"+timesec token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest() id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR" return id_url1 def main(): # timeout en secondes socket.setdefaulttimeout(90) usage = "usage: python tmc_tf1.py [options] <url de l'emission>" parser = optparse.OptionParser( usage = usage ) parser.add_option( "--nocolor", action = 'store_true', default = False, help = 'desactive la couleur dans le terminal' ) parser.add_option( "-v", "--verbose", action = "store_true", default = False, help = 'affiche les informations de debugage' ) ( options, args ) = parser.parse_args() if( len( args ) > 2 or args[ 0 ] == "" ): parser.print_help() parser.exit( 1 ) debut_id = '' html = urlopen(sys.argv[1]).read() nom = sys.argv[1].split('/')[-1:][0] no = nom.split('.')[-2:][0] soup = BeautifulSoup.BeautifulSoup(html) if 'tmc.tv' in str(soup) or 'tf1.fr' in str(soup): debut_id = str(soup.find('div', attrs={'class' : 'unique' })) if 'nt1.tv' in str(soup) or 'hd1.tv' in str(soup): debut_id = str(soup.find('section', attrs={'class' : 'player-unique' })) id = [x.strip() for x in re.findall("mediaId :([^,]*)", debut_id)][0] id_url1 = get_wat(id) opener = urllib2.build_opener() opener.addheaders = [('User-agent', random.choice(listeUserAgents))] data = opener.open(id_url1).read() opener.close() if data[0:4] == 'http': ua = random.choice(listeUserAgents) arguments = 'curl "%s" -L -g -A "%s" -o "%s.mp4"' % (data, ua, no) print arguments process = subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0] if data[0:4] == 'rtmp': host = re.search('rtmpte://(.*)/ondemand', data).group(1) host = host.replace('rtmpte', 'rtmpe') data0 = re.search('rtmpte://(.*)h264', data).group(0) cmds = 'rtmpdump -r "%s" -c 443 -m 10 -w b23434cbed89c9eaf520373c4c6f26e1f7326896dee4b1719e8d9acda0c19e99 -x 343427 -o "%s.mp4" " --resume"' % (data0, str(no)) f = open(str(no), 'w') f.write(cmds) f.close() arguments = shlex.split( cmds ) print arguments cpt = 0 while True: p = subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: print "Erreur : le sous-process s\'est terminé avec (le code d\'erreur est " + str(p.returncode) + ")" # status = False if cpt > 5: break cpt += 1 time.sleep(3) else: # status = True break if __name__ == "__main__": Hors ligne #2681 Le 16/02/2013, à 01:15 angeline Re : TVDownloader: télécharger les médias du net ! Bonsoir à tous. Ce soir, je découvre que "www.francetvinfo.fr" a encore changé de protocole, et plus possible télécharger le journal de France2 le 20 heures. Je suis en Amérique du sud. Est-ce vrai aussi pour vous ? Merci. ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ Hors ligne #2682 Le 16/02/2013, à 08:52 gl38 Re : TVDownloader: télécharger les médias du net ! Le journal de 20h de France 2 du 15/2 se télécharge normalement chez moi (en France). Cordialement, Guy Hors ligne #2683 Le 16/02/2013, à 10:09 k3c Re : TVDownloader: télécharger les médias du net ! @ angeline avec pluzzdl 0.9.4 je viens de télécharger le journal de 20 h gg@gg-SATELLITE-L755:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686) [DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013 [DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] PluzzDL.py ID de l'émission : 77106215 [DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215 [DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv [DEBUG ] PluzzDL.py Lien RTMP : None [DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m [DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8 [DEBUG ] PluzzDL.py Utilisation de DRM : non [DEBUG ] PluzzDL.py Chaine : France 2 [DEBUG ] Historique.py Historique chargé [DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8 [DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k.m3u8 [DEBUG ] PluzzDL.py Nombre de fragments : 242 [INFO ] PluzzDL.py Début du téléchargement des fragments et ça se finit par [DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-240.ts [DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-241.ts [INFO ] PluzzDL.py Fin du téléchargement [INFO ] PluzzDL.py Création du fichier MKV (vidéo finale) ; veuillez attendre quelques instants [INFO ] PluzzDL.py Fin ! [DEBUG ] Historique.py Historique sauvé gg@gg-SATELLITE-L755:~$ Hors ligne #2684 Le 16/02/2013, à 11:29 mulder29 Re : TVDownloader: télécharger les médias du net ! Ah mince, et toujours pas de solution pour moi ? :S Hors ligne #2685 Le 16/02/2013, à 12:16 thom83 Re : TVDownloader: télécharger les médias du net ! Bonjour, @ k3c J'ai testé la version 0.7 ci-dessus (la partie inférieure) avec succès après avoir ajouté le «main()» qui va bien. Est-il possible d'améliorer cette version en favorisant les variantes HD des émissions plutôt qu'en SD, quitte à ce que cela prenne plus de place sur le disque ? Cela ferait une différence sur un écran un peu grand... Dernière modification par thom83 (Le 16/02/2013, à 12:17) Hors ligne #2686 Le 16/02/2013, à 12:33 ynad Re : TVDownloader: télécharger les médias du net ! @ mulder29 voila comment j'ai fait: j'ai créer un répertoire D8 dans ce répertoire j'ai copier coller le script #2646 page 106 de k3C dans un éditeur de texte et sauvegarder en d8.py dans le même répertoire j'ai ouvert un terminal et lancer la commande: python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html si la vidéo est toujours en ligne elle se charge dans ce répertoire ce script est valable pour d8, k3c en a fait d'autres pour tf1 etc. il y a pluzdl pour le site de pluzz. espérant t'aider un peu... Hors ligne #2687 Le 16/02/2013, à 13:39 k3c Re : TVDownloader: télécharger les médias du net ! @ thom83 je prux sortir un hack rapidement, quitte à faire propre plus tard Hors ligne #2688 Le 16/02/2013, à 14:05 mulder29 Re : TVDownloader: télécharger les médias du net ! On me met encore m = re.search('\d{6}$',sys.argv[1]) bash: Erreur de syntaxe près du symbole inattendu « ( » ~$ if m is None: > try: > id = s.findAll('div',attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid'] bash: Erreur de syntaxe près du symbole inattendu « ( » ~$ except: Commande 'except:' non trouvée, vouliez-vous dire : La commande 'except' du paquet 'qmail' (universe) except: : commande introuvable ~$ Display all 2596 possibilities? (y or n) ~$ t 'imposiible de trouver l\'id de la video' > Sans doute là que ça coince. J'ai tapé la ligne de commande dans le Terminal, rien ne se passe. (en revanche, ma flèche du curseur est devenue une croix) Hors ligne #2689 Le 16/02/2013, à 14:10 angeline Re : TVDownloader: télécharger les médias du net ! @K3c, Merci, j'ai le même début, mais pas la même fin cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686) [DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013 [DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] PluzzDL.py ID de l'émission : 77106215 [DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215 [DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv [DEBUG ] PluzzDL.py Lien RTMP : None [DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m [DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8 [DEBUG ] PluzzDL.py Utilisation de DRM : non [DEBUG ] PluzzDL.py Chaine : France 2 [DEBUG ] Historique.py Historique chargé [DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8 [DEBUG ] Navigateur.py Forbidden Traceback (most recent call last): File "/usr/share/pluzzdl/main.py", line 91, in <module> progressFnct = progressFnct ) File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__ downloader.telecharger() File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger self.m3u8 = self.navigateur.getFichier( self.m3u8URL ) File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier page = self.urlOpener.open( requete, timeout = self.timeOut ) File "/usr/lib/python2.7/urllib2.py", line 406, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 519, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 444, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden [DEBUG ] Historique.py Historique sauvé Je sèche. PS.: cela va si mal que cela en France... que les infos ne doivent pas sortir de l'hexagone ? Edit: Oubliez la ligne au dessus... Avec Opera, cela se charge, mais très lentement, (en pointillés) du à mon internet très lent, et ce n'est pas regardable! D'où la nécessité de télécharger. Dernière modification par angeline (Le 16/02/2013, à 14:25) ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ Hors ligne #2690 Le 16/02/2013, à 15:05 k3c Re : TVDownloader: télécharger les médias du net ! @ mulder29 tu exécutes du bash, pas du python @ angeline n'étant pas en France, il te faudrait un proxy France,non ? Hors ligne #2691 Le 16/02/2013, à 15:12 mulder29 Re : TVDownloader: télécharger les médias du net ! ok et comment je fais pour passer en mode "python" ? Hors ligne #2692 Le 16/02/2013, à 15:13 angeline Re : TVDownloader: télécharger les médias du net ! @K3c Par Opera ou Firefox, je ne passe pas par un proxy actuellement. Avec Opera, j'ai droit à un bonus de 50 secondes de pub... qui fonctionne très bien ! Par Firefox, c'est bloqué par AdBlock, mais le journal dans tous les cas arrive trop lentement. Le pb me parait autre part. ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ Hors ligne #2693 Le 16/02/2013, à 15:53 angeline Re : TVDownloader: télécharger les médias du net ! @Kc2 Si je récupère [DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv que je change le "mms" en "rtsp" le journal est téléchargeable par mon downloader préféré ! Mais pas par "pluzzdl" ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ Hors ligne #2694 Le 16/02/2013, à 23:22 angeline Re : TVDownloader: télécharger les médias du net ! C'était trop beau... cela n'a pas duré. [DEBUG ] PluzzDL.py Lien MMS : None [DEBUG ] PluzzDL.py Lien RTMP : None Donc, comment passer par un proxy S.V.P. ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ Hors ligne #2695 Le 16/02/2013, à 23:28 mulder29 Re : TVDownloader: télécharger les médias du net ! Ok, j'ai installé idle, j'ai lancé une python shell et j'ai ouvert mon dossier leafpad d8.py en prenant soin de copier/coller le texte J'ai ensuite copié dans le terminal le lien python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html et... il n'a l'air de rien se passer en fait. Hors ligne #2696 Le 17/02/2013, à 00:11 k3c Re : TVDownloader: télécharger les médias du net ! @ angeline $ pluzzdl --help usage: pluzzdl [options] urlEmission Télécharge les émissions de Pluzz positional arguments: urlEmission URL de l'émission Pluzz a charger optional arguments: -h, --help show this help message and exit -b, --progressbar affiche la progression du téléchargement -p PROXY, --proxy PROXY utilise un proxy HTTP au format suivant http://URL:PORT -s, --sock si un proxy est fourni avec l'option -p, un proxy SOCKS5 est utilisé au format suivant ADRESSE:PORT -v, --verbose affiche les informations de debugage -t, --soustitres récupère le fichier de sous-titres de la vidéo (si disponible) --nocolor désactive la couleur dans le terminal --version show program's version number and exit donc pluzzdl -p http://1.2.3.4:80 ... en supposant que 1.2.3.4:80 est un proxy français valide @ mulder 29 quand je lance ta commande, ça m'affiche python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4" en fait cette procédure lance juste la commande ci-dessus Hors ligne #2697 Le 17/02/2013, à 00:51 angeline Re : TVDownloader: télécharger les médias du net ! @K3c Merci pour la réponse. Cependant, je doute ! J'ai essayé 6/7 proxy... pas un ne veut coopérer. Par un navigateur: Firefox, Opéra, ou Chromium, l'émission passe. Sans proxy. Par pluzzdll, toujours la même interdiction cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686) [DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013 [DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] PluzzDL.py ID de l'émission : 77496935 [DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77496935 [DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J6/740386_jt20h_20130216.wmv [DEBUG ] PluzzDL.py Lien RTMP : None [DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J6/77496935-20130216-,398,632,934,k.mp4.csmil/manifest.f4m [DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8 [DEBUG ] PluzzDL.py Utilisation de DRM : non [DEBUG ] PluzzDL.py Chaine : France 2 [DEBUG ] Historique.py Historique chargé [DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8 [DEBUG ] Navigateur.py Forbidden Traceback (most recent call last): File "/usr/share/pluzzdl/main.py", line 91, in <module> progressFnct = progressFnct ) File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__ downloader.telecharger() File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger self.m3u8 = self.navigateur.getFichier( self.m3u8URL ) File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier page = self.urlOpener.open( requete, timeout = self.timeOut ) File "/usr/lib/python2.7/urllib2.py", line 406, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 519, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 444, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden [DEBUG ] Historique.py Historique sauvé Par chance, France télévision s'est réveillé, et maintenant une URL en mms apparait. Il est 18h ici, je télécharge. Avec proxy j'obtiens: pluzzdl -v -p http://176.31.247.227:8085 http://pluzz.francetv.fr/videos/jt20h.html [DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686) [DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013 [DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html [CRITICAL] PluzzDL.py Impossible de récupérer l'ID de l'émission Mais je pense que peu de proxy laissent passer les infos de vidéo, du moins dans les gratuits. Je reste à l'écoute. Dernière modification par angeline (Le 17/02/2013, à 00:53) ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ Hors ligne #2698 Le 17/02/2013, à 02:17 mulder29 Re : TVDownloader: télécharger les médias du net ! @ mulder 29 quand je lance ta commande, ça m'affiche python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4" en fait cette procédure lance juste la commande ci-dessus Euh, moi, ça reste sur la ligne sur python... et aucune autre réaction o_O Ok, donc il y a vraiment un bug dans mon système et python est inutilisable chez moi. Hors ligne #2699 Le 17/02/2013, à 02:20 k3c Re : TVDownloader: télécharger les médias du net ! si tu tapes dans un terminal python ça t'affiche quoi ? Hors ligne #2700 Le 17/02/2013, à 10:59 mulder29 Re : TVDownloader: télécharger les médias du net ! Ça m'affiche : Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> par rapport à la commande fait précédemment, tu en déduis ? Hors ligne
Im implementing the django comments app. What is the best way to redirect to the current page when post is clicked rather than the post page? I've followed this guide: http://www.omh.cc/blog/2008/mar/9/free-comments-redirection/ My form looks like: {% load comments i18n %} <form action="{% comment_form_target %}" method="post">{% csrf_token %} {% if next %}<div><input type="hidden" name="next" value="{{ next }}" /></div>{% endif %} {% for field in form %} {% if field.is_hidden %} <div>{{ field }}</div> {% else %} {% if field.name != "email" and field.name != "url" %} {% if field.errors %}{{ field.errors }}{% endif %} <p {% if field.errors %} class="error"{% endif %} {% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}> {{ field.label_tag }} {{ field }} </p> {% endif %} {% endif %} {% endfor %} <p class="submit"><input type="submit" name="post" class="submit-post" value="{% trans "Post" %}" /></p> </form> My views.py looks like: def comment_posted( request ): if request.GET['c']: comment_id, post_id = request.GET['c'].split( ':' ) post = Image.objects.get( pk=post_id ) if post: return HttpResponseRedirect( post.get_absolute_url() ) return HttpResponseRedirect( "/" ) My urls.py looks like: urlpatterns = patterns('', url(r'^other/', include('other.urls')), url(r'^live/', include('live.urls')), url(r'^photo/', include('photo.urls')), url(r'^comments/posted/$', 'photo.views.comment_posted'), url(r'^comments/', include('django.contrib.comments.urls')), url(r'^search/', SearchView(template=None, searchqueryset=None, form_class=SearchForm), name='haystack_search'), Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/comments/posted/?c=10 Django Version: 1.3.1 Python Version: 2.6.6 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'other', 'live', 'photo', 'haystack', 'django.contrib.flatpages', 'django.contrib.comments', 'django.contrib.admin', 'django.contrib.admindocs'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware') Traceback: File "/export/mailgrp4_a/sc10jbr/lib/python/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/home/cserv2_a/soc_ug/sc10jbr/WWWdev/dbe/photo/views.py" in comment_posted 17. comment_id, post_id = request.GET['c'].split( ':' ) Exception Type: ValueError at /comments/posted/ Exception Value: need more than 1 value to unpack I think i have modified my views.py incorrectly, any ideas? My app is called photo, my model is called Image. Thanks
I'm just wondering if there is a way (maybe with regex) to validate that an input on a Java desktop app is exactly an string formated as: "YYYY-MM-DD". I've searched but with no success. Thank you Use the following regular expression: ^\d{4}-\d{2}-\d{2}$ as in if (str.matches("\\d{4}-\\d{2}-\\d{2}")) { ... } With the You need more than a e.g. SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd"); boolean isValidDate(string input) { try { format.parse(input); return true; } catch(ParseException e){ return false; } } Unfortunately, Putting it all together: it's necessary to use both to validate format and value: public static boolean isValid(String text) { if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d")) return false; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); df.setLenient(false); try { df.parse(text); return true; } catch (ParseException ex) { return false; } } A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call. It is needed in a multithread context since the SimpleDateFormat is not thread safe: private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); df.setLenient(false); System.out.println("created"); return df; } }; public static boolean isValid(String text) { if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d")) return false; try { format.get().parse(text); return true; } catch (ParseException ex) { return false; } } (same can be done for a Matcher, that also is not thread safe) This will do it regex: String regex = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$"; Assert.assertTrue("Date: matched.", Pattern.matches(regex, "2011-1-1")); Assert.assertFalse("Date (month): not matched.", Pattern.matches(regex, "2011-13-1")); Good luck! I would go with a simple regex which will check that days doesn't have more than 31 days and months no more than 12. Something like: (0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((18|19|20|21)\\d\\d) This is the format "dd-MM-yyyy". You can tweak it to your needs (for example take off the ? to make the leading 0 required - now its optional), and then use a custom logic to cut down to the specific rules like leap years February number of days case, and other months number of days cases. See the DateChecker code below. I am choosing this approach since I tested that this is the best one when performance is taken into account. I checked this (1st) approach versus 2nd approach of validating a date against a regex that takes care of the other use cases, and 3rd approach of using the same simple regex above in combination with SimpleDateFormat.parse(date). Date checker code: class DateChecker { private Matcher matcher; private Pattern pattern; public DateChecker(String regex) { pattern = Pattern.compile(regex); } /** * Checks if the date format is a valid. * Uses the regex pattern to match the date first. * Than additionally checks are performed on the boundaries of the days taken the month into account (leap years are covered). * * @param date the date that needs to be checked. * @return if the date is of an valid format or not. */ public boolean check(final String date) { matcher = pattern.matcher(date); if (matcher.matches()) { matcher.reset(); if (matcher.find()) { int day = Integer.parseInt(matcher.group(1)); int month = Integer.parseInt(matcher.group(2)); int year = Integer.parseInt(matcher.group(3)); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return day < 32; case 4: case 6: case 9: case 11: return day < 31; case 2: int modulo100 = year % 100; //http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) { //its a leap year return day < 30; } else { return day < 29; } default: break; } } } return false; } public String getRegex() { return pattern.pattern(); } } Date checking/testing and performance testing: import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Tester { private static final String[] validDateStrings = new String[]{ "1-1-2000", //leading 0s for day and month optional "01-1-2000", //leading 0 for month only optional "1-01-2000", //leading 0 for day only optional "01-01-1800", //first accepted date "31-12-2199", //last accepted date "31-01-2000", //January has 31 days "31-03-2000", //March has 31 days "31-05-2000", //May has 31 days "31-07-2000", //July has 31 days "31-08-2000", //August has 31 days "31-10-2000", //October has 31 days "31-12-2000", //December has 31 days "30-04-2000", //April has 30 days "30-06-2000", //June has 30 days "30-09-2000", //September has 30 days "30-11-2000", //November has 30 days }; private static final String[] invalidDateStrings = new String[]{ "00-01-2000", //there is no 0-th day "01-00-2000", //there is no 0-th month "31-12-1799", //out of lower boundary date "01-01-2200", //out of high boundary date "32-01-2000", //January doesn't have 32 days "32-03-2000", //March doesn't have 32 days "32-05-2000", //May doesn't have 32 days "32-07-2000", //July doesn't have 32 days "32-08-2000", //August doesn't have 32 days "32-10-2000", //October doesn't have 32 days "32-12-2000", //December doesn't have 32 days "31-04-2000", //April doesn't have 31 days "31-06-2000", //June doesn't have 31 days "31-09-2000", //September doesn't have 31 days "31-11-2000", //November doesn't have 31 days "001-02-2000", //SimpleDateFormat valid date (day with leading 0s) even with lenient set to false "1-0002-2000", //SimpleDateFormat valid date (month with leading 0s) even with lenient set to false "01-02-0003", //SimpleDateFormat valid date (year with leading 0s) even with lenient set to false "01.01-2000", //. invalid separator between day and month "01-01.2000", //. invalid separator between month and year "01/01-2000", /// invalid separator between day and month "01-01/2000", /// invalid separator between month and year "01_01-2000", //_ invalid separator between day and month "01-01_2000", //_ invalid separator between month and year "01-01-2000-12345", //only whole string should be matched "01-13-2000", //month bigger than 13 }; /** * These constants will be used to generate the valid and invalid boundary dates for the leap years. (For no leap year, Feb. 28 valid and Feb. 29 invalid; for a leap year Feb. 29 valid and Feb. 30 invalid) */ private static final int LEAP_STEP = 4; private static final int YEAR_START = 1800; private static final int YEAR_END = 2199; /** * This date regex will find matches for valid dates between 1800 and 2199 in the format of "dd-MM-yyyy". * The leading 0 is optional. */ private static final String DATE_REGEX = "((0?[1-9]|[12][0-9]|3[01])-(0?[13578]|1[02])-(18|19|20|21)[0-9]{2})|((0?[1-9]|[12][0-9]|30)-(0?[469]|11)-(18|19|20|21)[0-9]{2})|((0?[1-9]|1[0-9]|2[0-8])-(0?2)-(18|19|20|21)[0-9]{2})|(29-(0?2)-(((18|19|20|21)(04|08|[2468][048]|[13579][26]))|2000))"; /** * This date regex is similar to the first one, but with the difference of matching only the whole string. So "01-01-2000-12345" won't pass with a match. * Keep in mind that String.matches tries to match only the whole string. */ private static final String DATE_REGEX_ONLY_WHOLE_STRING = "^" + DATE_REGEX + "$"; /** * The simple regex (without checking for 31 day months and leap years): */ private static final String DATE_REGEX_SIMPLE = "(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((18|19|20|21)\\d\\d)"; /** * This date regex is similar to the first one, but with the difference of matching only the whole string. So "01-01-2000-12345" won't pass with a match. */ private static final String DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING = "^" + DATE_REGEX_SIMPLE + "$"; private static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy"); static { SDF.setLenient(false); } private static final DateChecker dateValidatorSimple = new DateChecker(DATE_REGEX_SIMPLE); private static final DateChecker dateValidatorSimpleOnlyWholeString = new DateChecker(DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING); /** * @param args */ public static void main(String[] args) { DateTimeStatistics dateTimeStatistics = new DateTimeStatistics(); boolean shouldMatch = true; for (int i = 0; i < validDateStrings.length; i++) { String validDate = validDateStrings[i]; matchAssertAndPopulateTimes( dateTimeStatistics, shouldMatch, validDate); } shouldMatch = false; for (int i = 0; i < invalidDateStrings.length; i++) { String invalidDate = invalidDateStrings[i]; matchAssertAndPopulateTimes(dateTimeStatistics, shouldMatch, invalidDate); } for (int year = YEAR_START; year < (YEAR_END + 1); year++) { FebruaryBoundaryDates februaryBoundaryDates = createValidAndInvalidFebruaryBoundaryDateStringsFromYear(year); shouldMatch = true; matchAssertAndPopulateTimes(dateTimeStatistics, shouldMatch, februaryBoundaryDates.getValidFebruaryBoundaryDateString()); shouldMatch = false; matchAssertAndPopulateTimes(dateTimeStatistics, shouldMatch, februaryBoundaryDates.getInvalidFebruaryBoundaryDateString()); } dateTimeStatistics.calculateAvarageTimesAndPrint(); } private static void matchAssertAndPopulateTimes( DateTimeStatistics dateTimeStatistics, boolean shouldMatch, String date) { dateTimeStatistics.addDate(date); matchAndPopulateTimeToMatch(date, DATE_REGEX, shouldMatch, dateTimeStatistics.getTimesTakenWithDateRegex()); matchAndPopulateTimeToMatch(date, DATE_REGEX_ONLY_WHOLE_STRING, shouldMatch, dateTimeStatistics.getTimesTakenWithDateRegexOnlyWholeString()); boolean matchesSimpleDateFormat = matchWithSimpleDateFormatAndPopulateTimeToMatchAndReturnMatches(date, dateTimeStatistics.getTimesTakenWithSimpleDateFormatParse()); matchAndPopulateTimeToMatchAndReturnMatchesAndCheck( dateTimeStatistics.getTimesTakenWithDateRegexSimple(), shouldMatch, date, matchesSimpleDateFormat, DATE_REGEX_SIMPLE); matchAndPopulateTimeToMatchAndReturnMatchesAndCheck( dateTimeStatistics.getTimesTakenWithDateRegexSimpleOnlyWholeString(), shouldMatch, date, matchesSimpleDateFormat, DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING); matchAndPopulateTimeToMatch(date, dateValidatorSimple, shouldMatch, dateTimeStatistics.getTimesTakenWithdateValidatorSimple()); matchAndPopulateTimeToMatch(date, dateValidatorSimpleOnlyWholeString, shouldMatch, dateTimeStatistics.getTimesTakenWithdateValidatorSimpleOnlyWholeString()); } private static void matchAndPopulateTimeToMatchAndReturnMatchesAndCheck( List<Long> times, boolean shouldMatch, String date, boolean matchesSimpleDateFormat, String regex) { boolean matchesFromRegex = matchAndPopulateTimeToMatchAndReturnMatches(date, regex, times); assert !((matchesSimpleDateFormat && matchesFromRegex) ^ shouldMatch) : "Parsing with SimpleDateFormat and date:" + date + "\nregex:" + regex + "\nshouldMatch:" + shouldMatch; } private static void matchAndPopulateTimeToMatch(String date, String regex, boolean shouldMatch, List<Long> times) { boolean matches = matchAndPopulateTimeToMatchAndReturnMatches(date, regex, times); assert !(matches ^ shouldMatch) : "date:" + date + "\nregex:" + regex + "\nshouldMatch:" + shouldMatch; } private static void matchAndPopulateTimeToMatch(String date, DateChecker dateValidator, boolean shouldMatch, List<Long> times) { long timestampStart; long timestampEnd; boolean matches; timestampStart = System.nanoTime(); matches = dateValidator.check(date); timestampEnd = System.nanoTime(); times.add(timestampEnd - timestampStart); assert !(matches ^ shouldMatch) : "date:" + date + "\ndateValidator with regex:" + dateValidator.getRegex() + "\nshouldMatch:" + shouldMatch; } private static boolean matchAndPopulateTimeToMatchAndReturnMatches(String date, String regex, List<Long> times) { long timestampStart; long timestampEnd; boolean matches; timestampStart = System.nanoTime(); matches = date.matches(regex); timestampEnd = System.nanoTime(); times.add(timestampEnd - timestampStart); return matches; } private static boolean matchWithSimpleDateFormatAndPopulateTimeToMatchAndReturnMatches(String date, List<Long> times) { long timestampStart; long timestampEnd; boolean matches = true; timestampStart = System.nanoTime(); try { SDF.parse(date); } catch (ParseException e) { matches = false; } finally { timestampEnd = System.nanoTime(); times.add(timestampEnd - timestampStart); } return matches; } private static FebruaryBoundaryDates createValidAndInvalidFebruaryBoundaryDateStringsFromYear(int year) { FebruaryBoundaryDates februaryBoundaryDates; int modulo100 = year % 100; //http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) { februaryBoundaryDates = new FebruaryBoundaryDates( createFebruaryDateFromDayAndYear(29, year), createFebruaryDateFromDayAndYear(30, year) ); } else { februaryBoundaryDates = new FebruaryBoundaryDates( createFebruaryDateFromDayAndYear(28, year), createFebruaryDateFromDayAndYear(29, year) ); } return februaryBoundaryDates; } private static String createFebruaryDateFromDayAndYear(int day, int year) { return String.format("%d-02-%d", day, year); } static class FebruaryBoundaryDates { private String validFebruaryBoundaryDateString; String invalidFebruaryBoundaryDateString; public FebruaryBoundaryDates(String validFebruaryBoundaryDateString, String invalidFebruaryBoundaryDateString) { super(); this.validFebruaryBoundaryDateString = validFebruaryBoundaryDateString; this.invalidFebruaryBoundaryDateString = invalidFebruaryBoundaryDateString; } public String getValidFebruaryBoundaryDateString() { return validFebruaryBoundaryDateString; } public void setValidFebruaryBoundaryDateString( String validFebruaryBoundaryDateString) { this.validFebruaryBoundaryDateString = validFebruaryBoundaryDateString; } public String getInvalidFebruaryBoundaryDateString() { return invalidFebruaryBoundaryDateString; } public void setInvalidFebruaryBoundaryDateString( String invalidFebruaryBoundaryDateString) { this.invalidFebruaryBoundaryDateString = invalidFebruaryBoundaryDateString; } } static class DateTimeStatistics { private List<String> dates = new ArrayList<String>(); private List<Long> timesTakenWithDateRegex = new ArrayList<Long>(); private List<Long> timesTakenWithDateRegexOnlyWholeString = new ArrayList<Long>(); private List<Long> timesTakenWithDateRegexSimple = new ArrayList<Long>(); private List<Long> timesTakenWithDateRegexSimpleOnlyWholeString = new ArrayList<Long>(); private List<Long> timesTakenWithSimpleDateFormatParse = new ArrayList<Long>(); private List<Long> timesTakenWithdateValidatorSimple = new ArrayList<Long>(); private List<Long> timesTakenWithdateValidatorSimpleOnlyWholeString = new ArrayList<Long>(); public List<String> getDates() { return dates; } public List<Long> getTimesTakenWithDateRegex() { return timesTakenWithDateRegex; } public List<Long> getTimesTakenWithDateRegexOnlyWholeString() { return timesTakenWithDateRegexOnlyWholeString; } public List<Long> getTimesTakenWithDateRegexSimple() { return timesTakenWithDateRegexSimple; } public List<Long> getTimesTakenWithDateRegexSimpleOnlyWholeString() { return timesTakenWithDateRegexSimpleOnlyWholeString; } public List<Long> getTimesTakenWithSimpleDateFormatParse() { return timesTakenWithSimpleDateFormatParse; } public List<Long> getTimesTakenWithdateValidatorSimple() { return timesTakenWithdateValidatorSimple; } public List<Long> getTimesTakenWithdateValidatorSimpleOnlyWholeString() { return timesTakenWithdateValidatorSimpleOnlyWholeString; } public void addDate(String date) { dates.add(date); } public void addTimesTakenWithDateRegex(long time) { timesTakenWithDateRegex.add(time); } public void addTimesTakenWithDateRegexOnlyWholeString(long time) { timesTakenWithDateRegexOnlyWholeString.add(time); } public void addTimesTakenWithDateRegexSimple(long time) { timesTakenWithDateRegexSimple.add(time); } public void addTimesTakenWithDateRegexSimpleOnlyWholeString(long time) { timesTakenWithDateRegexSimpleOnlyWholeString.add(time); } public void addTimesTakenWithSimpleDateFormatParse(long time) { timesTakenWithSimpleDateFormatParse.add(time); } public void addTimesTakenWithdateValidatorSimple(long time) { timesTakenWithdateValidatorSimple.add(time); } public void addTimesTakenWithdateValidatorSimpleOnlyWholeString(long time) { timesTakenWithdateValidatorSimpleOnlyWholeString.add(time); } private void calculateAvarageTimesAndPrint() { long[] sumOfTimes = new long[7]; int timesSize = timesTakenWithDateRegex.size(); for (int i = 0; i < timesSize; i++) { sumOfTimes[0] += timesTakenWithDateRegex.get(i); sumOfTimes[1] += timesTakenWithDateRegexOnlyWholeString.get(i); sumOfTimes[2] += timesTakenWithDateRegexSimple.get(i); sumOfTimes[3] += timesTakenWithDateRegexSimpleOnlyWholeString.get(i); sumOfTimes[4] += timesTakenWithSimpleDateFormatParse.get(i); sumOfTimes[5] += timesTakenWithdateValidatorSimple.get(i); sumOfTimes[6] += timesTakenWithdateValidatorSimpleOnlyWholeString.get(i); } System.out.println("AVG from timesTakenWithDateRegex (in nanoseconds):" + (double) sumOfTimes[0] / timesSize); System.out.println("AVG from timesTakenWithDateRegexOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[1] / timesSize); System.out.println("AVG from timesTakenWithDateRegexSimple (in nanoseconds):" + (double) sumOfTimes[2] / timesSize); System.out.println("AVG from timesTakenWithDateRegexSimpleOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[3] / timesSize); System.out.println("AVG from timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) sumOfTimes[4] / timesSize); System.out.println("AVG from timesTakenWithDateRegexSimple + timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) (sumOfTimes[2] + sumOfTimes[4]) / timesSize); System.out.println("AVG from timesTakenWithDateRegexSimpleOnlyWholeString + timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) (sumOfTimes[3] + sumOfTimes[4]) / timesSize); System.out.println("AVG from timesTakenWithdateValidatorSimple (in nanoseconds):" + (double) sumOfTimes[5] / timesSize); System.out.println("AVG from timesTakenWithdateValidatorSimpleOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[6] / timesSize); } } static class DateChecker { private Matcher matcher; private Pattern pattern; public DateChecker(String regex) { pattern = Pattern.compile(regex); } /** * Checks if the date format is a valid. * Uses the regex pattern to match the date first. * Than additionally checks are performed on the boundaries of the days taken the month into account (leap years are covered). * * @param date the date that needs to be checked. * @return if the date is of an valid format or not. */ public boolean check(final String date) { matcher = pattern.matcher(date); if (matcher.matches()) { matcher.reset(); if (matcher.find()) { int day = Integer.parseInt(matcher.group(1)); int month = Integer.parseInt(matcher.group(2)); int year = Integer.parseInt(matcher.group(3)); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return day < 32; case 4: case 6: case 9: case 11: return day < 31; case 2: int modulo100 = year % 100; //http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) { //its a leap year return day < 30; } else { return day < 29; } default: break; } } } return false; } public String getRegex() { return pattern.pattern(); } } } Some useful notes: Hope this helps someone! Construct a SimpleDateFormat with the mask, and then call: SimpleDateFormat.parse(String s, ParsePosition p) For fine control, consider an InputVerifier using the Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site. Would you like to answer one of these unanswered questions instead?
I have this: class MyClass: """A simple example class""" i = 12345 def f(self): print i # self.i will work just fine return 'hello world' When I do: >>> x = MyClass() >>> >>> x.f() I get an error, as expected. My question is: Why do I get the error? Why is there no namespace between the namespace of the function(or method) definition and the global namespace of the module containing the class? Is there any other way to reference i inside f in this case other than using self?
I am debugging a python program with pdb. The program will start a new thread. newThread = Thread(group = None,target = dosomething,name = "thename", args = (),kwargs = {}) def dosomething(): balaba Use the normal pdb command e.g. -b to set break point in the line of the new thread(e.g. line of balaba), seems will not trigger the breakpoint. The question I want to ask is: is there a way I can break into the new thread target function to look into the behavor the new thread?
I feel like I'm missing something terribly obvious, but I can't see it. In ipython (Python 2.7), this works: In [1]: json.loads('[]') Out[1]: [] I'm trying to do the equivalent minimal example in a Django view, to convince myself I can read JSON before moving on to a real data structure: def submit(request): json_string = request.GET['json'] parsed = json.loads(json_string) return HttpResponse(parsed) I call it from my browser by going to http://localhost:8001/submit/?json='[]' And I get ValueError: No JSON object could be decoded. What am I doing wrong, and how do I debug it? Is this some kind of encoding problem? Or am I accessing the content of the GET incorrectly? Or something else? I've tried dumping the variable json_string, both to a file and as an HttpResponse. Both times I get '[]', which sure looks fine... Edit: For the benefit of any other beginners wondering how to debug a POST, Django's error page is returned in the exception. A quick and nasty hack that works is import os def debug_post(post_req): result = None try: result = submit_to_endpoint(post_req) except urllib2.URLError as e: out_fh = open('debug_post.tmp', 'w') out_fh.write(e.read()) out_fh.close() os.system('firefox ' + 'debug.tmp') return result
AuthorPosts March 27, 2013 at 7:48 pm #21468 Do I use widget or custom text? I tried both but not working for me what’s the shortcode if you can give me the sample thx March 28, 2013 at 6:38 am #111949 Kriesi uses the dropcaps shortcode. Go to the page/post editor page and switch to the “Visual” editor mode. In the toolbar click on the “Magic wand” icon and select “Dropcaps” – you can choose between 3 styles (Dropcap 1, 2 and 3). Between the dropcap shortcode tags insert your text content (eg numbers, text, etc.) March 29, 2013 at 4:26 am #111950 Ah I see. For the frontpage of the demo FLEXIBLY TEMPLATES etc texts are shown that way using the template builder > column > direct text input? I can’t replicate the font size and position with this can you give me the codes March 29, 2013 at 5:34 pm #111951April 1, 2013 at 1:01 pm #111952 Hi altious, The frontpage template is actually pulling in the content from the “frontpage” page where the template is chosen in the Page Layout meta box. In that page there is this code: [one_fourth first] Flexible things [dropcap2]1[/dropcap2]The theme uses a flexible template system that enables you to create stunning pages out of the box with no coding knowledge at all [/one_fourth] [one_fourth] Unlimited Skins [dropcap3]2[/dropcap3]The theme comes with several predefined skin options but also utilizes a color and background image switcher, a font-switch for headings and several other layout options. [/one_fourth] [one_fourth] Content Importing [dropcap3]3[/dropcap3]You can now setup a wordpress installation that looks like this demo with just a single click of your mouse. Amazing to get started and accustomed to the theme. [/one_fourth] [one_fourth] eCommerce Ready [dropcap3]4[/dropcap3]The theme comes with an eCommerce plugin (wooCommerce) so you can set up a shop within minutes. Create a full fledged online store or sell a few digital goods. Its up to you [/one_fourth] Regards, Devin April 3, 2013 at 6:24 pm #111953 Devin, I’ve created a page ‘frontpage’ and paste the contents you provide then in template builder I add ‘Post/Page Content’ Element but it shows 3 column and last column below.. not appearing same like your demo April 4, 2013 at 12:57 pm #111954 We would need to see the page live to see what is going on in that case. You can generate your own columns using the shortcode pop up by clicking on the little Magic Wand button in the visual editors menu. After selecting Column Layout and 4 columns and four 1/4 options you’ll get the following: [one_fourth first]Content for 1/4 Column here[/one_fourth] [one_fourth]Content for 1/4 Column here[/one_fourth] [one_fourth]Content for 1/4 Column here[/one_fourth] [one_fourth]Content for 1/4 Column here[/one_fourth] Regards, Devin AuthorPosts The topic ‘How to create the number circle in the demo?’ is closed to new replies.
serial [Résolu] Pb de lag pour la vidéo et le son, disque dur lent Dans un premier temps, j'ai du son (multiplexé via alsa), jusqu'ici pas de problème. Dès que je lis une vidéo, elle rame et le son saute, surtout quand nautilus cherche à créer les vignettes, qu'il n'arrive pas à faire d'ailleurs. Petite précision, sous la Mandrake 10.1 que j'ai en parallèle tout est fluide. Seul hic, dès que le disque est un peu sollicité la lecture d'une musique dans XMMS s'arrête, mais rien ne plante pour autant. Ma configuration est la suivante : ASUS A7N8X-E Deluxe (Nforce2) /dev/hda : udma5, Seagate /dev/sda : udma6, SATA (sil3112a) Maxtor La Ubuntu 5.04 est installée sur le disque SATA. Dernière modification par serial (Le 18/04/2005, à 17:51) Hors ligne serial Re : [Résolu] Pb de lag pour la vidéo et le son, disque dur lent Bon, après quelques investigations j'ai pu déterminer que le problème viennait du hda, voyez donc : # hdparm -I /dev/hda /dev/hda: ATA device, with non-removable media Model Number: ST3120022A Serial Number: 5JT1H48S Firmware Revision: 3.06 Standards: Used: ATA/ATAPI-6 T13 1410D revision 2 Supported: 6 5 4 3 Configuration: Logical max current cylinders 16383 65535 heads 16 1 sectors/track 63 63 -- CHS current addressable sectors: 4128705 LBA user addressable sectors: 234441648 LBA48 user addressable sectors: 234441648 device size with M = 1024*1024: 114473 MBytes device size with M = 1000*1000: 120034 MBytes (120 GB) Capabilities: LBA, IORDY(can be disabled) bytes avail on r/w long: 4 Queue depth: 1 Standby timer values: spec'd by Standard R/W multiple sector transfer: Max = 16 Current = ? Recommended acoustic management value: 128, current value: 0 DMA: mdma0 mdma1 mdma2 udma0 udma1 udma2 udma3 udma4 *udma5 Cycle time: min=120ns recommended=120ns PIO: pio0 pio1 pio2 pio3 pio4 Cycle time: no flow control=240ns IORDY flow control=120ns Commands/features: Enabled Supported: * READ BUFFER cmd * WRITE BUFFER cmd * Host Protected Area feature set * Look-ahead * Write cache * Power Management feature set Security Mode feature set * SMART feature set * FLUSH CACHE EXT command * Mandatory FLUSH CACHE command * Device Configuration Overlay feature set * 48-bit Address feature set SET MAX security extension * DOWNLOAD MICROCODE cmd * SMART self-test * SMART error logging Security: supported not enabled not locked not frozen not expired: security count not supported: enhanced erase HW reset results: CBLID- above Vih Device num = 0 determined by the jumper Checksum: correct Jusque là, pas de problème à ma connaissance. Test de vitesse à deux reprises : # hdparm -t /dev/hda /dev/hda: Timing buffered disk reads: 8 MB in 3.71 seconds = 2.16 MB/sec root@serial:/home/serial # hdparm -t /dev/hda /dev/hda: Timing buffered disk reads: 8 MB in 3.70 seconds = 2.16 MB/sec Problème... DMA activé ? # hdparm -d /dev/hda /dev/hda: using_dma = 0 (off) Non, et bien, réactivons le. # hdparm -d 1 /dev/hda /dev/hda: setting using_dma to 1 (on) HDIO_SET_DMA failed: Operation not permitted using_dma = 0 (off) Ah, bah dis, c'est pas possible ! J'ai tenté cette opération en ayant démonté la partition qui y était liée, mais sans succès. Un petit dmesg pour la route ? [...] eth1: no IPv6 routers present hda: drive_cmd: status=0x51 { DriveReady SeekComplete Error } hda: drive_cmd: error=0x04 { DriveStatusError } ide: failed opcode was: 0xef [...] Rien de bien rassurant, non ? Dernière modification par serial (Le 12/04/2005, à 22:57) Hors ligne serial Re : [Résolu] Pb de lag pour la vidéo et le son, disque dur lent Sous Mandrake 10.1 : # uname -a Linux serial.xxx 2.6.8.1-12mdk #1 Fri Oct 1 12:53:41 CEST 2004 i686 AMD Sempron(tm) 2500+ unknown GNU/Linux # hdparm -t /dev/hda /dev/hda: Timing buffered disk reads: 166 MB in 3.00 seconds = 55.25 MB/sec # hdparm -d /dev/hda /dev/hda: using_dma = 1 (on) Dernière modification par serial (Le 14/04/2005, à 10:59) Hors ligne lamiricore Re : [Résolu] Pb de lag pour la vidéo et le son, disque dur lent As-tu essayé de modifier ton hdparm.conf comme indiqué ici http://forum.ubuntu-fr.org/viewtopic.php?id=2388 Sinon j'avais le même genre de message d'erreur avec un lecteur cd "0x54....": je l'ai changé de port ide et zoup plus d'erreur mais je ne suis pas allé chercher plus loin donc pas d'explication logique à fournir serial Re : [Résolu] Pb de lag pour la vidéo et le son, disque dur lent # hdparm /dev/hda /dev/hda: multcount = 0 (off) IO_support = 1 (32-bit) unmaskirq = 1 (on) using_dma = 0 (off) keepsettings = 0 (off) readonly = 0 (off) readahead = 256 (on) geometry = 16383/255/63, sectors = 120034123776, start = 0 Je rajoute un test en lecture : # hdparm -tT /dev/hda /dev/hda: Timing cached reads: 1572 MB in 2.00 seconds = 785.33 MB/sec Timing buffered disk reads: 12 MB in 3.19 seconds = 3.77 MB/sec Il en est de même pour mon autre disque dur IDE : # hdparm -tT /dev/hdb /dev/hdb: Timing cached reads: 1540 MB in 2.00 seconds = 768.20 MB/sec Timing buffered disk reads: 8 MB in 3.70 seconds = 2.16 MB/sec # hdparm /dev/hdb /dev/hdb: multcount = 0 (off) IO_support = 0 (default 16-bit) unmaskirq = 0 (off) using_dma = 0 (off) keepsettings = 0 (off) readonly = 0 (off) readahead = 256 (on) geometry = 16383/255/63, sectors = 80026361856, start = 0 J'ai cru voir quelques part que cela pourrait être du à la nappe, je verrais ce soir si j'ai le temps, sinon pourquoi cela ne ralentirait pas non plus la lecture, quoique, un test de disque que j'ai trouvé ici, donne un débit de + de 1Go/s. Hors ligne serial Re : [Résolu] Pb de lag pour la vidéo et le son, disque dur lent Comme indiqué ici la compilation du support du contrôleur IDE AMD/Nvidia dans le noyau a résolu mon problème. Edit : il semblerait que ce soit pareil pour les chipsets VIA !! Je suis passé d'une A7N8X-E à une MSI K8T Neo2. Mot clés: disque dur lent, hparm, nforce, saccades, lag, rame (pagaie ?) Dernière modification par serial (Le 21/04/2005, à 22:39) Hors ligne lolo Re : [Résolu] Pb de lag pour la vidéo et le son, disque dur lent Etant nouveau sur Linux et ayant quand même identifier mon problème de saccade des DVD et lenteur des disques durs ide(Installation sur disque SATA et chipset nforce2), je me retrouve devant la solution: "compilation du support du contrôleur IDE AMD/Nvidia dans le noyau" Et là ben ...:( Hors ligne
How do __hash__ and __eq__ use in identification in sets? For example some code that should help to solve some domino puzzle: class foo(object): def __init__(self, one, two): self.one = one self.two = two def __eq__(self,other): if (self.one == other.one) and (self.two == other.two): return True if (self.two == other.one) and (self.one == other.two): return True return False def __hash__(self): return hash(self.one + self.two) s = set() for i in range(7): for j in range(7): s.add(foo(i,j)) len(s) // returns 28 Why? If i use only __eq__() len(s) equals 49. Its ok because as i understand objects (1-2 and 2-1 for example) not same, but represent same domino. So I have added hash function. Now it works the way i want, but i did not understand one thing: hash of 1-3 and 2-2 should be same so they should counted like same object and shouldn't added to set. But they do! Im stuck.
I am looking to be able to write an alternative code to the built in count in python: This code works def count(element,seq): """Counts how often an element occurs ...in a sequence""" mycount = seq.count(element) return mycount but I would like to write it in a for loop (or another way?), I've got this far: def count(element,seq): """Counts how often an element occurs ...in a sequence""" for i in seq: if element == seq: print i I'm not sure how to return the re-occuring elements as an integer. Any help appreciated!!
I have have read several entries regarding dropping several functional functions from future python, including map and reduce. What is the official policy regarding functional extensions? is lambda function going to stay? Well, Python 3.0 and 3.1 are already released, so you can check this out for yourself. The end result was that map and filter were kept as built-ins, and lambda was also kept. The only change was that reduce was moved to the functools module; you just need to do from functools import reduce to use it. Future 3.x releases can be expected to remain backwards-compatible with 3.0 and 3.1 in this respect. In Python 3.x, Python continues to have a rich set of functional-ish tools built in: list comprehensions, generator expressions, iterators and generators, and functions like Python's "Benevolent Dictator For Life" floated the idea of removing lst2 = map(foo, lst) lst3 = [foo(x) for x in lst] lst2 == lst3 # evaluates True Python's Python's plain-old-standard Example: # NOT LEGAL PYTHON lst2 = map(lambda x: if foo(x): x**2; else: x, lst) # perfectly legal Python def lambda_function(x): if foo(x): return x**2 else: return x lst2 = map(lambda_function, lst) del(lambda_function) # can unbind the name if you wish Note that you could actually use the "ternary operator" in a lst2 = map(lambda x: x**2 if foo(x) else x, lst) But some multiline functions are difficult to force into a Python 3.x has lost none of its functional power. There is some general feeling that list comprehensions and generator expressions are probably preferable to total = sum(map(lst, foo)) total2 = sum(foo(x) for x in lst) assert total == total2 # same result In Python 2.x, the In Python 3.x, lst2 = list(map(lambda x: x**2 if foo(x) else x, lst)) Easier to just write the list comprehension! lst2 = [x**2 if foo(x) else x for x in lst]
How do you want to access your hierarchy? If you're always going to be checking for a full path, then as suggested, use a tuple:eg: >>> d["a","b1","c",1,"d"] = value However, if you're going to be doing things like "quickly find all the items below "a -> b1", it may make more sense to store it as a nested hashtable (otherwise you must iterate through all items to find those you're intereted in). For this, a defaultdict is probably the easiest way to store. For example: from collections import defaultdict def new_dict(): return defaultdict(new_dict) d = defaultdict(new_dict) d["a"]["b1"]["c"][1]["d"] = "test" d["a"]["b2"]["c"][2]["d"] = "test2" d["a"]["c"][1]["d"] = "test3" print d["a"]["c"][1]["d"] # Prints test3 print d["a"].keys() # Prints ["c", "b1", "b2"]
I am working on a Django project where a Thing would have a unique 10 digit Key, in addition to the standard auto incrementing ID integerfield. I use a simple random number function to create it. [I'm sure there's a better way to do this too] When a Thing is created, a 10 digit Key is created. I use the .validate_unique() to check the Key's uniqueness. If its not unique, is there a simple way I can recursively call the Key generator (makeKey()) until it passes? Code follows: Models.py: class Thing(models.Model): name=models.CharField(max_length=50) key=models.IntegerField(unique=True) Views.py: def makeKey(): key='' while len(key)<10: n=random.randint(0,9) key+=`n` k=int(key) #k=1234567890 #for testing uniqueness return k def createThing(request): if ( request.method == 'POST' ): f = ThingForm(request.POST) try: f.is_valid() newF=f.save(commit=False) newF.key=makeKey() newF.validate_unique(exclude=None) newF.save() return HttpResponseRedirect(redirect) except Exception, error: print "Failed in register", error else: f = ThingForm() return render_to_response('thing_form.html', {'f': f}) Thank you
I created a django project using django 1.4.2. There is one 'app'(adsite) in this project. And It works. But when I copied some 'py' files into the 'app' folder, I got No module named models error in views.py . and Parent module adsite.adsiteviews.mainhanlder does not exist. Should I register the new files to __init__ in the 'app'? Did new coped files break the import rules? views.py from django.http import HttpResponse from django.template import Context, loader from adsite.models import UserInfo def showusers(request): userlist = UserInfo.objects.all() c = Context({ 'userlist':userlist, }) t = loader.get_template('users.html') return HttpResponse(t.render(c)) copied file: adsiteviews.py class mainhanlder(TemplateView) def get(self): """ """ variables = { 'user': self.get_current_user(), 'mchosts' : MCHOSTS, 'servers' : servers} index_templ = tmpl_lookup.get_template("index.html") body = index_templ.render(**variables) self.write(body) urls.py urlpatterns = patterns('', # Examples: url(r'^$', 'adsite.adsiteviews.mainhandler.as_View()'), url(r'^users/$', 'adsite.views.showusers'), I have no clues about this problem. any suggestions would be appreciated. thx for your time.
Virtualici Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) j'ai tout tenté ! au mieux j'ai ça : ): [sudo] password for boubou: Sorry, try again. sudo: 3 incorrect password attempts boubou@boubou-M51SE:~$ ******* ******* : commande introuvable boubou@boubou-M51SE:~$ les : ******* c'est mon pass. Hors ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) On va changer ton mot de passe. Fais users-admin et là change ton mot de passe pour un truc simple uniquement avec des lettres sans accents Dernière modification par nam1962 (Le 17/11/2013, à 15:21) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne Virtualici Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Je ne comprend pas, il ne veux pas accèpté mon mot de pass, déjà parce-qu'il faut enter l'ancien, ça a fonctionné une fois et après, en plein parcours de ton tuto, j'ai due repondre O/n, "j'ai fais comme dans le tuto" O majuscule, j'ai tout essayé le 0 le o len même, mais rien il me redemande mon mdp, mais il n'en veux pas il était on n'peu plus simple pourtant !!! Bref désolé de faire le boulet comme ça mais merci quand même Dernière modification par Virtualici (Le 17/11/2013, à 16:28) Hors ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Redémarre et retente Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne Vaykadji Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ce que tu peux essayer c'est écrire ton mot de passe autre part, par exemple dans ton navigateur, ou dans un fichier texte. Ensuite tu peux le surligner avec ta souris, le sélectionner, et clic droit > copier. Ensuite dans ton terminal, quand il te demande ton mot de passe, tu fais clic droit et coller, puis tu appuies sur la touche <Enter> de ton clavier. Comme ça, tu es sûr de bien entrer exactement ce que tu veux Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch Hors ligne rb Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) bonsoir en voulant mettre à niveau le portable de ma femme sous ubuntu 12.04 j'ai commencé les actions et la : sudo apt-get install ubuntu-restricted-extras je me retrouve avec , dans le terminal "outil de configuration des paquets"Configuration de ttf-mscorefonts-installer ,un topo microsoft dont je te mets que la fin, il y en a des tonnes et je n'arrive pas à sélectionner l'ensemble pour te mettre une copie. est ce normale @+ Richard Outil de configuration des paquets ┌──────────────┤ Configuration de ttf-mscorefonts-installer ├───────────────┐ │ │ │ MISCELLANEOUS │ │ If you acquired this product in the United States, this EULA is governed │ by the laws of the State of Washington. │ │ If this product was acquired outside the United States, then local laws │ may apply. │ │ Should you have any questions concerning this EULA, or if you desire to │ contact Microsoft for any reason, please contact the Microsoft │ subsidiary serving your country, or write: Microsoft Sales Information │ Center/One Microsoft Way/Redmond, WA 98052-6399. │ │ Reference: http://www.microsoft.com/typography/fontpack/eula.htm │ <Ok> │ │ └───────────────────────────────────────────────────────────────────────────┘ MSI Wind Box DC500-005 - Intel Atom Dual-Core D510 4 Go XubuntuVoyager 14.04 32bits et HandyLinux Hors ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Oui, tu sélectionnes ok avec la touche tab (les deux flèches au dessus du verrouillage majuscules) ce sont les polices de caractères non libres, ça permet de bien interpréter les docs envoyés par les gens du monde W$ Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne rb Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ok Merci MSI Wind Box DC500-005 - Intel Atom Dual-Core D510 4 Go XubuntuVoyager 14.04 32bits et HandyLinux Hors ligne markusolympe Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) ah, ça semble pas mal, je prends, merci ! Hors ligne Virtualici Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Bonjour nam et les autres;) Bon je suis boqué a cette étape : boubou@boubou-M51SE:~$ software-properties-gtk gpg: /tmp/tmpJJAotZ/trustdb.gpg : base de confiance créée boubou@boubou-M51SE:~$ sudo apt-get update [sudo] password for boubou: Sorry, try again. [sudo] password for boubou: Atteint http://fr.archive.ubuntu.com precise Release.gpg Atteint http://fr.archive.ubuntu.com precise-updates Release.gpg Atteint http://fr.archive.ubuntu.com precise-backports Release.gpg Réception de : 1 http://extras.ubuntu.com precise Release.gpg [72 B] Atteint http://archive.canonical.com precise Release.gpg Atteint http://fr.archive.ubuntu.com precise Release Atteint http://fr.archive.ubuntu.com precise-updates Release Atteint http://archive.canonical.com precise Release Atteint http://extras.ubuntu.com precise Release Atteint http://fr.archive.ubuntu.com precise-backports Release Atteint http://security.ubuntu.com precise-security Release.gpg Atteint http://fr.archive.ubuntu.com precise/main Sources Atteint http://archive.canonical.com precise/partner Sources Atteint http://fr.archive.ubuntu.com precise/restricted Sources Atteint http://fr.archive.ubuntu.com precise/universe Sources Atteint http://fr.archive.ubuntu.com precise/multiverse Sources Atteint http://fr.archive.ubuntu.com precise/main i386 Packages Atteint http://fr.archive.ubuntu.com precise/restricted i386 Packages Atteint http://fr.archive.ubuntu.com precise/universe i386 Packages Atteint http://fr.archive.ubuntu.com precise/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com precise/main TranslationIndex Atteint http://fr.archive.ubuntu.com precise/multiverse TranslationIndex Atteint http://extras.ubuntu.com precise/main Sources Atteint http://security.ubuntu.com precise-security Release Atteint http://archive.canonical.com precise/partner i386 Packages Ign http://archive.canonical.com precise/partner TranslationIndex Atteint http://fr.archive.ubuntu.com precise/restricted TranslationIndex Atteint http://fr.archive.ubuntu.com precise/universe TranslationIndex Atteint http://fr.archive.ubuntu.com precise-updates/main Sources Atteint http://fr.archive.ubuntu.com precise-updates/restricted Sources Atteint http://fr.archive.ubuntu.com precise-updates/universe Sources Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Sources Atteint http://extras.ubuntu.com precise/main i386 Packages Ign http://extras.ubuntu.com precise/main TranslationIndex Atteint http://fr.archive.ubuntu.com precise-updates/main i386 Packages Atteint http://fr.archive.ubuntu.com precise-updates/restricted i386 Packages Atteint http://fr.archive.ubuntu.com precise-updates/universe i386 Packages Atteint http://fr.archive.ubuntu.com precise-updates/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com precise-updates/main TranslationIndex Atteint http://fr.archive.ubuntu.com precise-updates/multiverse TranslationIndex Atteint http://fr.archive.ubuntu.com precise-updates/restricted TranslationIndex Atteint http://fr.archive.ubuntu.com precise-updates/universe TranslationIndex Atteint http://fr.archive.ubuntu.com precise-backports/main Sources Atteint http://fr.archive.ubuntu.com precise-backports/restricted Sources Atteint http://security.ubuntu.com precise-security/main Sources Atteint http://fr.archive.ubuntu.com precise-backports/universe Sources Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Sources Atteint http://fr.archive.ubuntu.com precise-backports/main i386 Packages Atteint http://fr.archive.ubuntu.com precise-backports/restricted i386 Packages Atteint http://fr.archive.ubuntu.com precise-backports/universe i386 Packages Atteint http://fr.archive.ubuntu.com precise-backports/multiverse i386 Packages Atteint http://fr.archive.ubuntu.com precise-backports/main TranslationIndex Atteint http://fr.archive.ubuntu.com precise-backports/multiverse TranslationIndex Atteint http://fr.archive.ubuntu.com precise-backports/restricted TranslationIndex Atteint http://fr.archive.ubuntu.com precise-backports/universe TranslationIndex Atteint http://fr.archive.ubuntu.com precise/main Translation-fr_FR Atteint http://fr.archive.ubuntu.com precise/main Translation-fr Atteint http://fr.archive.ubuntu.com precise/main Translation-en Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr_FR Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-fr Atteint http://fr.archive.ubuntu.com precise/multiverse Translation-en Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr_FR Atteint http://fr.archive.ubuntu.com precise/restricted Translation-fr Atteint http://fr.archive.ubuntu.com precise/restricted Translation-en Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr_FR Atteint http://fr.archive.ubuntu.com precise/universe Translation-fr Atteint http://fr.archive.ubuntu.com precise/universe Translation-en Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-fr Atteint http://fr.archive.ubuntu.com precise-updates/main Translation-en Atteint http://security.ubuntu.com precise-security/restricted Sources Atteint http://security.ubuntu.com precise-security/universe Sources Atteint http://security.ubuntu.com precise-security/multiverse Sources Atteint http://security.ubuntu.com precise-security/main i386 Packages Atteint http://security.ubuntu.com precise-security/restricted i386 Packages Atteint http://security.ubuntu.com precise-security/universe i386 Packages Atteint http://security.ubuntu.com precise-security/multiverse i386 Packages Atteint http://security.ubuntu.com precise-security/main TranslationIndex Atteint http://security.ubuntu.com precise-security/multiverse TranslationIndex Atteint http://security.ubuntu.com precise-security/restricted TranslationIndex Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-fr Atteint http://fr.archive.ubuntu.com precise-updates/multiverse Translation-en Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-fr Atteint http://fr.archive.ubuntu.com precise-updates/restricted Translation-en Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-fr Atteint http://fr.archive.ubuntu.com precise-updates/universe Translation-en Atteint http://fr.archive.ubuntu.com precise-backports/main Translation-en Atteint http://fr.archive.ubuntu.com precise-backports/multiverse Translation-en Atteint http://fr.archive.ubuntu.com precise-backports/restricted Translation-en Atteint http://fr.archive.ubuntu.com precise-backports/universe Translation-en Atteint http://security.ubuntu.com precise-security/universe TranslationIndex Atteint http://security.ubuntu.com precise-security/main Translation-en Atteint http://security.ubuntu.com precise-security/multiverse Translation-en Ign http://archive.canonical.com precise/partner Translation-fr_FR Ign http://extras.ubuntu.com precise/main Translation-fr_FR Ign http://archive.canonical.com precise/partner Translation-fr Atteint http://security.ubuntu.com precise-security/restricted Translation-en Ign http://extras.ubuntu.com precise/main Translation-fr Ign http://archive.canonical.com precise/partner Translation-en Ign http://extras.ubuntu.com precise/main Translation-en Atteint http://security.ubuntu.com precise-security/universe Translation-en 72 o réceptionnés en 1s (54 o/s) Lecture des listes de paquets... Fait boubou@boubou-M51SE:~$ sudo apt-get install xfce4-goodies Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Les paquets suivants ont été installés automatiquement et ne sont plus nécessaires : linux-headers-3.2.0-52-generic linux-headers-3.2.0-52 Veuillez utiliser « apt-get autoremove » pour les supprimer. Les paquets supplémentaires suivants seront installés : hddtemp libfam0 libhal-storage1 libhal1 libthunar-vfs-1-2 libthunar-vfs-1-common lm-sensors mousepad squeeze xfce4-artwork xfce4-battery-plugin xfce4-clipman xfce4-clipman-plugin xfce4-cpufreq-plugin xfce4-diskperf-plugin xfce4-fsguard-plugin xfce4-genmon-plugin xfce4-mount-plugin xfce4-sensors-plugin xfce4-smartbookmark-plugin xfce4-timer-plugin xfce4-wavelan-plugin Paquets suggérés : ksensors fam fancontrol sensord read-edid i2c-tools xfprint4 xfce4-cellmodem-plugin xfce4-linelight-plugin xfce4-messenger-plugin xfce4-mpc-plugin xfce4-radio-plugin xfce4-xfapplet-plugin xfswitch-plugin xfce4-hdaps thunar-thumbnailers xfmpc xsensors Les NOUVEAUX paquets suivants seront installés : hddtemp libfam0 libhal-storage1 libhal1 libthunar-vfs-1-2 libthunar-vfs-1-common lm-sensors mousepad squeeze xfce4-artwork xfce4-battery-plugin xfce4-clipman xfce4-clipman-plugin xfce4-cpufreq-plugin xfce4-diskperf-plugin xfce4-fsguard-plugin xfce4-genmon-plugin xfce4-goodies xfce4-mount-plugin xfce4-sensors-plugin xfce4-smartbookmark-plugin xfce4-timer-plugin xfce4-wavelan-plugin 0 mis à jour, 23 nouvellement installés, 0 à enlever et 0 non mis à jour. Il est nécessaire de prendre 11,8 Mo dans les archives. Après cette opération, 22,2 Mo d'espace disque supplémentaires seront utilisés. Souhaitez-vous continuer [O/n] ? O Annulation. boubou@boubou-M51SE:~$ Hors ligne Vaykadji Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) C'est un O, pas un 0 (un "eau" de l'alphabet, pour OUI, pas le zéro), mais je pense que tu l'as compris ça. Essaye avec un "o" minuscule, moi c'est ce que je fais. Essaye également avec un "y" qui est la réponse YES sur une installation en Anglais (on sait jamais que toute la traduction soit pas installée...) Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch Hors ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ou tout simplement la touche entrée (valide dans la plupart des cas) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne Virtualici Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Bon et bien merci, je ne sais pas si j'ai tout fais "bien" car parfois ni le O ni o ni Y ni y ni même Entrer, parfois les double flèches me proposais un (y/n) j'ai toujours mis y, mais parfois ça ne fonctionnais même pô ^^ Mais bon la bécane fonctionne c'est déjà top ! merci Nam A+ ? Hors ligne alca94 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) @ nam1962 Je ne sais pas pourquoi (même dans la Doc en général) ils utilisent "sudo gedit" alors que ça devrait être "gksudo gedit" et je vois que vous également ? http://doc.ubuntu-fr.org/sudo#quand_doi … udokdesudo Hors ligne moko138 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) @alca94 : merci d'enfoncer le clou ! @nam1962 : effectivement, ça serait bien que tu édites ton tuto en ce sens. Depuis que je distingue gksudo de sudo, je ne me retrouve plus avec /home et HD externe en lecture seule. En ligne Vaykadji Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) C'est pareil pourtant, sauf que "sudo gedit" va tourner dans le terminal et demandera de laisser ouvert le terminal alors que "gksudo gedit" va faire appel à gksu pour ouvrir gedit, et donc tourner dans gksu et pas dans le terminal. Dernière modification par Vaykadji (Le 21/11/2013, à 13:43) Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch Hors ligne moko138 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ce n'est pas pareil au niveau des droits admin, cf. lien donné par alca94, et ça a parfois des conséquences embêtantes au redémarrage. En ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Modifié ! Merci du rappel bande de puristes Dernière modification par nam1962 (Le 21/11/2013, à 14:59) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne moko138 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Grand merci, nam1962 ! En ligne jibel Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) @Tous , La guerre du GKsudo VS sudo est déclarée , au premier round sudo a envoyé un uppercut a GKsudo qui c'est retrouvé dans les cordes ....... Qu'elle va être la réponse de GKsudo ? suite au prochain épisode .... Plus grande est la face, plus grand est le dos! Toutes les fautes de frappe, d'orthographe, de grammaire et de syntaxe ci-dessus, sont la propriété intellectuelle de l'auteur.Elles peuvent être reproduites et même corrigées sans l'accord préalable du susdit. Avec Ub.12.04, 14.04, Kub. 13.10, 14.04,Voy 14.04,13.10,13.04,12.04 LTS , Mint 17, hybryde fus13.04 .PC medion akira DD 1T + 2 . Hors ligne Vaykadji Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ah et il faut aussi se rappeler que certaines distributions ne supportent pas la commande gksudo (je pense à Fedora, notamment), alors que sudo est présent partout. Note : La différence entre sudo et gksudo est la suivante : - sudo lance un programme en root en utilisant la configuration de l'utilisateur loggé. - gksudo lance un programme en root en utilisant la configuration root du programme. En fait, utiliser gksudo va permettre de ne pas modifier vos dossiers personnels, qui contiennent des fichiers nécessaires au bon fonctionnement de la session. Cependant, utiliser gksudo va également vous faire perdre vos paramètres personnalisés durant l'utilisation du programme puisqu'il va utiliser les fichiers de configuration root pour se lancer. Il est déconseillé d'utiliser 'sudo' pour un programme avec interface graphique parce que dans de rares cas, ça pourrait causer des dommages importants à votre OS. Source Dernière modification par Vaykadji (Le 21/11/2013, à 19:03) Netbook : Asus EeePC 1005PX : Atom N450 / 2Gb DDR2 - Ubuntu UnityDesktop : i5 4670k / MSI GTX760 / 8Gb DDR3 - Windows 8.1 pro & Ubuntu UnityTablette : Google Nexus 7 2013 'flo' - S4Pro 1,51Ghz / 2Gb RAM - Android 4.4.2 & Ubuntu Touch Hors ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ce n'est plus un tuto : ça devient une encyclopédie ce topic Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne alca94 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ah et il faut aussi se rappeler que certaines distributions ne supportent pas la commande gksudo (je pense à Fedora, notamment), ça s'adresse a un public "ubuntu" .Ferdora doit avoir son propre forum ,non ? Hors ligne metalux Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) nam1962, tu peux S.T.P. m'apporter des précisions sur:1. TLP a un réglage douteux : SATA_LINKPWR_ON_BAT qu'il vaut mieux mettre sur max_performance et son utilité. J'utilise également TLP depuis un certains temps et justement je change cette option pour mettre SATA_LINKPWR_ON_AC=min_power sinon mon PC ressemble plus à un grille-pain....euh grille-mains Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement En ligne nam1962 Re : [Tuto] - Ma personnalisation Xubuntu (et autres variantes) Ça venait d'une observation sur un fofo qui depuis a disparu : ce premier qui me l'a conseillé considérait que min_power était mal géré. De mon côté, ça m'a bien été sur 36 installs. (Mais du coup n'ai pas testé min_power) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com Hors ligne
The following Python script cycles through your Twitter timeline and takes the most recent Tweet that fits certain critera. It will only show tweets that do not include a @reply, a link or a hashtag. It then displays the Tweet as a Quote, neatly divided over as many lines as is necessary, with all HTML entities replaced by their respective Unicode characters, and the name of the poster appended neatly underneath. Demo Installation. Get your API details from Twitter. Twitter has a set of documentation that walks you through this process. Fill in the form on the Twitter developer site and you will receive a CONSUMER KEY, CONSUMERSECRET, ACCESSKEY and ACCESSSECRET. Add these details into the text below where they are requested and copy/paste the script into Notepad. Save as TweetQuote.py. Make a note of the path. Load Terminal and type: 'easy_install tweepy' without the quotes. (tweepy powers this script, if this install fails then you may need to install setuptools for Python) Add the following as a GeekTool shell command 'python /Users..[insert full file path here]../TweetQuote.py' Script import tweepy, os, sys, re # Declare OAuth varibles. CONSUMER_KEY = '...' CONSUMER_SECRET = '...' ACCESS_KEY = '...' ACCESS_SECRET = '...' keyfile = "authkeys.dat" auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) # Break string into multiple lines def para(text): return reduce(lambda line, word, width=50: '%s%s%s' %(line, ' \n'[(len(line)-line.rfind('\n')-1 + len(word.split('\n',1)[0]) >= 50)], word), text.split(' ')) # Convert html entities into Unicode def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&#": try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text return re.sub("&#?\w+;", fixup, text) # Script type = api.home_timeline(count=30) for result in type: if result.text.find('@')==-1 and result.text.find('http://')==-1: twtu = result.user.screen_name twtt = result.text print para(unescape(twtt)) + "\n" + "\n- " + twtu break
kevlar Ella : projet de logiciel d'animation Flash & SVG pour Linux Le projet est aujourd'hui bien avancé : version 0.3.1.2 au 2 Novembre 2010 ! Ella (Elegant Light Linux Animator) est un projet amateur destiné à fournir à la communauté linuxienne un générateur d'animations Flash & SVG wysiwyg, fonctionnel, léger, bien intégré aux environnements fondés sur Gtk 2+. Ce projet est développé sur notre temps libre, c'est pourquoi il avance doucement. Ce logiciel n'a pas la prétention d'égaler l'original propriétaire,mais il essaye d'intégrer le plus grand nombre possible de ses fonctionnalités, avec une dose d'originalité. Merci à ceux qui se sont intéressés à ce projet, et/ou m'ont fourni une aide et plus particulièrement au Team Ella qui existe depuis le 16/5/2010 : xapantu, lovasoa, Brozowski, grim7reaper et moi-même. Grâce aux efforts de Xapantu et Frafa, vous avez des instruments pour le compiler ou l'installer assez facilement. Voici par exemple le script de Frafa : http://forum.ubuntu-fr.org/viewtopic.ph … 3#p3849023 (message #1387, page #56) ; pour obtenir la dernière révision, mitonnée par Xapantu ou Brozowski, vous devez installer les outils bazaar (bzr tools) ; REMARQUES : - pour fonctionner, il faut que les swftools soient présentes ; un coup de sudo apt-get install swftools et c'est réglé ! - il faut ABSOLUMENT utiliser goocanvas version 0.14 ou supérieure ; si elle n'est pas packagée, vous devez la récupérer ici : http://ftp.gnome.org/pub/GNOME/sources/goocanvas/ et la compiler (très simple, très rapide ...) Grâce à Brozowski et Xapantu, le projet est maintenant disponible sous forme de paquet .deb, que vous trouverez ici : https://launchpad.net/~ella-animation/+archive/dev Pour discuter avec nous, nous avons un canal #irc : http://webchat.freenode.net/?channels=#ella Il reste : - à débuguer. - à écrire les fichiers d'aide sous forme de fichier HTML (la votre serait la bienvenue ...) - à continuer la traduction du logiciel : vous pouvez participer aux traductions sur Launchpad. - lovasoa a commencé à travailler sur l'exportation JavaScript. Voici deux videos de démonstration des capacités d'Ella (fin Avril 2010, le logiciel a, depuis, évolué): - ogg :http://kevlar.legtux.org/donnees_publiq … /out-1.ogv - xvid :http://kevlar.legtux.org/donnees_publiq … la/out.avi Vous trouverez à la page #8 ou sur launchpad(partie /doc)la description du format de fichier propre à Ella. Ella est sur Launchpad : https://launchpad.net/ella merci à Xapantu **************************************************************************** Enfin, pour ceux qui ne sont pas rébutés par l'anglais à la sauce froggie, sur tuxfamilly : Ella sur TuxFamilly (en anglais) Dernière modification par kevlar (Le 14/11/2010, à 10:00) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne Daedalus11 Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux C'est à toi de voir la méthode que tu veux employer. un Datadrigview serait intéressant dans la mesure ou le nombre de case est amplifié. Dans ton cas, je te recommande d'aller choper les sources de F4L et de voir ce qu'ils utilisent. Tu vas me dire "Oui mais je ne connais pas Qt". Il n'est pas nécessaire de connaitre Qt pour savoir le controle qu'ils utilisent . les noms de widgets se différencie de très très peu. Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux merci de ta réponse ! - Datadrigview appartient à GTK ? - j'ai les sources de F4L, mais 1), c'est du C++, donc problème, et 2) c'est Qt. EDIT : Datagridview est un contrôle de Windows d'après Google ...:( EDIT 2 : ou alors passer par Vala, C#, Mono ! Dernière modification par kevlar (Le 27/05/2009, à 14:22) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne philarmonie Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Dois-je abandonner ces widgets pour un simple GtkTable ? Mais alors, plus de gestion dynamique ... Pourquoi? ça se redimensionne un GtkTable Dernière modification par philarmonie (Le 27/05/2009, à 17:18) kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux en effet, je viens de m'en apercevoir. Sauvé ! Par contre, tu as vu ce que je souhaite faire : - liberté pour l'utilisateur de créer autant de lignes (correspondant à un calque) qu'il le souhaite. - chaque ligne devra contenir des pixbufs (pris dans 2-3 modèles différents, de petits rectangles). Or, on peut demander un minimum de 512 (j'aime les chiffres informatiques ) pixbufs par ligne ... Avec tout ça, quid de l'utilisation de la mémoire ? Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne philarmonie Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Avec tout ça, quid de l'utilisation de la mémoire ? Ça doit pas être énorme si t'as que trois modèles de pixbuf. Dans chaque case t'as juste un pointeur vers le pixbuf, c'est pas gourmand un pointeur kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux impec ' Je suis en train de passer aux Gtktables, en gardant l'interface de départ. Par contre, faudra voir comment changer le fond du tableau (en blanc, ce serait mieux !) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Dernière modification par kevlar (Le 27/05/2009, à 20:54) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne philarmonie Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Tu parles de la règle sur le screenshot de F4L? Il peut mettre une drawingarea dans chaque case et dessiner dedans les traits et écrire les chiffres 1 case sur 5. Dernière modification par philarmonie (Le 28/05/2009, à 01:14) kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux ce n'est pas à ça que je pense : pour la version Gtk, multiplier les drwingareas, même en 10x24 comme ici, finirait par coûter de la mémoire. Je pense faire ceci : garder la "table" que tu vois sur la copie précédente, mais la glisser dans une scrolledwindow, et AJOUTER au-dessus une scrolledwindow contenant la réglette style "Flash", et cette dernière dans une scrolled window également, mais SANS potentiomètres. Ainsi, deux avantages : - c'est le déplacement du potentiomètre de la grille du scénario qui donnera l'impression de provoquer le déplacement de la réglette. - cette dernière ser faite avec des petits pixmaps sélectionnables. La graduation se fera à travers une Vbox. Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Voici comment je vois l'IHM (ici, je n'ai pas encore le temps de raccorder au code fonctionnel du message #8) La règle est ici faite à l'arrache, mais elle est bien contenue dans une scrolledwindow dont les curseurs sont cachés Dernière modification par kevlar (Le 28/05/2009, à 07:52) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Bon, un autre problème (et j'ai quand même cherché ) : comment savoir quelle case de la GtkTable a été cliquée, sachant que mon interface peut en contenir des milliers (je ne parle pas du branchement de la fonction Call-Back) ? EDIT : il semble que l'on puisse passer en paramètre de la Callback associée à chaque bouton un pointeur sur une structure de données, ou, une chaîne, indiquant automatiquement la cellule cliquée. ON va essayer de se débrouiller avec ça, mais la mémoire file, file ... Dernière modification par kevlar (Le 28/05/2009, à 18:30) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux J'ai un doute ... Est-il possible d'utiliser plusieurs fois une même GtkListStore dans le cadre de vues (GTkTreeView) différentes (comme si on portait plusieurs regards sur le même objet) ; j'ai fait ça : /* Creation de la vue en colonnes (titres) */ pListViewLayers = gtk_tree_view_new_with_model(GTK_TREE_MODEL(pListStore)); /* vue sur le panneau des calques */ pViewLayers = gtk_tree_view_new_with_model(GTK_TREE_MODEL(pListStore)); C'est la variable pListStore qui est commune, ici. Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne philarmonie Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Je dirai que c'est possible. rniamo Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux en gtk+ (version C), c'est possible, tout comme tu peux utiliser que 2 gtkwidget * pour faire ta fenêtre... mais bon Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux OK, mais moi j'essaye toujours d'éviter le gaspillage de RAM. L'idée est de stocker dans un seul GtkListore : - les différents calques utilisés (leur nom) - leur état (visible ou non) - et un ensemble de pointeurs décrivant la ligne de temps de l'animation. Mais, comme j'essaye de refaire une interface Macromedia like, je sépare dans deux ScrolledWindows, d'une part, un bloc 'nom calque+état calque' et dans une autre fenêtre, la 'ligne de temps'. L'autre idée, est qu'avec un GtkLIstore commun, détruire un calque permet de détruire automatiquement la ligne de temps, et de mettre à jour tout aussi automatiquement l'affichage. Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Bonsoir ! Quelqu'un parmi vous est-il déjà parvenu à associer un GtkRuler à autre chose qu'une DrawingArea ? 3 heures que j'essaye d'utiliser l'événement 'motion-notify' sur une GtkTable pour l'envoyer vers un GtkRuler, et bien sûr, ça ne marche pas ! (apparemment seule une DrawingArea gère l'information de position nécessaire ...) Comment faire pour que la règle supérieure soit autre chose qu'une décoration ? Dernière modification par kevlar (Le 07/06/2009, à 20:05) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne philarmonie Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Quand un widget ne gère pas les événements on le met dans une eventBox, et on défini les événements que l'on souhaite gérer. kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Quand un widget ne gère pas les événements on le met dans une eventBox, et on défini les événements que l'on souhaite gérer. déjà essayé Philarmonie. ça ne marche pas, et finit pas une erreur de segmentation (pire cas) ou aucune réaction. Ma copie d'écran : les éléments de la time-line (les rectangles blancs+noirs) sont des icônes faites avec des GtkPixbuf ; pour interagir avec elles (elles sont placées dans une GtkTable) je capture le clic gauche de la souris (et je n'ai pourtant pas besoin d'une eventbox). Et ça marche : je capture ainsi la position virtuelle (calque choisi, position de l'image courante). C'est pourquoi je sèche ...:/ Dernière modification par kevlar (Le 08/06/2009, à 15:40) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne philarmonie Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Effectivement j'ai testé, en plus cette classe gère nativement les événements (donc pas besoin d'un eventBox). Il suffit d'utiliser la méthode add_events et rajouter l'event gtk.gdk.BUTTON_PRESS_MASK. C'est juste que ce widget ne gère pas de base cet événement. Edit: je code en python et voilà un exemple qui gère le clic sur un ruler #!/usr/bin/pyhton import gtk class Win: def __init__(self): self.win = gtk.Window() self.ruler = gtk.HRuler() self.ruler.set_size_request(200, 50) self.ruler.set_range(0, 200, 10, 200) # rajoute la gestion du clic pour le ruler self.ruler.add_events(gtk.gdk.BUTTON_PRESS_MASK) self.win.connect("delete-event", gtk.main_quit) self.win.add(self.ruler) self.ruler.connect('button-press-event', self.press) self.win.show_all() def press(self, widget, event): print 'pressed' if __name__ == '__main__': win = Win() gtk.main() Dernière modification par philarmonie (Le 08/06/2009, à 16:15) kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux vous avez bien de la chance avec Python ; je te donne des extraits du code C chez moi ! 1- créer une macro pour "surcharger" (ce n'est pourtant pas du C++) la méthode de l'objet GtkRuler : #define EVENT_METHOD(i, x) GTK_WIDGET_GET_CLASS(i)->x un peu plus loin, je crée l'IHM de la copie d'écran; je ne détaille pas. Voici néanmoins un extrait des callbacks : /* attachement et affichage de la règle */ gtk_table_attach(GTK_TABLE(pTableLayersTimeLine),TimeLineRuler,0,MAX_FRAMES+2,0,1, GTK_EXPAND|GTK_FILL, GTK_EXPAND|GTK_FILL,0, 0); /* brancher événements souris */ gtk_widget_add_events (pTableLayersTimeLine, GDK_BUTTON_PRESS_MASK |GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK); g_signal_connect (GTK_OBJECT (scrolledLayersTimeLine), "motion_notify_event", G_CALLBACK (bouge_souris), G_OBJECT (TimeLineRuler)); g_signal_connect(GTK_OBJECT(scrolledLayersTimeLine),"button-press-event", G_CALLBACK(clic_souris__window_time_line),NULL); Donc, sur ce que je comprends du langage Python, c'est la même démarche ... et pourtant, seule la callback réagissant à "event-press-button" ... réagit ! Avec ce listing, je récupère bien sûr un clic sur la règle (GtkRuler), mais cela m'est peu utile (c'est lors de l'événement que je transcode les coordonnées de la souris en coordonnées sur la time line) ; or, la présence de la règle fausse les calculs des coordonnées en ordonnées. En effet, je ne peux savoir quelle sera la hauteur réelle de la règle (GtkRuler), chaque utilisateur pouvant utiliser uen police différente ...) Dernière modification par kevlar (Le 08/06/2009, à 16:43) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux cette version de mon programme est déjà éloignée de celle proposée sur le tuto Gtk, qui proposait d'automatiser ainsi l'appel à la callback pour "motion-notify" (et qui ne marche pas du tout chez moi ! J'en fournis une version adaptée à mon programme) : gtk_signal_connect_object( GTK_OBJECT(scrolledLayersTimeLine), "motion_notify_event", (GtkSignalFunc)EVENT_METHOD(TimeLineRuler, motion_notify_event), GTK_OBJECT(TimeLineRuler) ); Dernière modification par kevlar (Le 08/06/2009, à 16:40) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux Je viens de lire ton code Python, et je précise que dans mon cas, le GtkRuler est sur la première ligne d'une GtkTable, que les autres lignes de cette GtkTable contiennent les GdkPixbufs, et que le GtkTable elle-même est intégrée dans une "scrolledwindow" nommé scrolledLayersTimeLine Dernière modification par kevlar (Le 08/06/2009, à 16:39) Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne kevlar Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux sinon, j'ai une autre version du programme n'utilisant plus de GtkRulers, mais une règle fabriquée maison : Dans cette version, l'intérêt est que la règle étant dans une fenêtre séparée, elle reste toujours visible. Mais il reste à implémenter la réaction de la fenêtre de la timeline aux déplacements en continu de la règle ... Ella : projet de logiciel d'animation Flash pour Linux http://forum.ubuntu-fr.org/viewtopic.php?id=321017&p=1 Projet Ella sur launchpad : https://launchpad.net/ella Le retour d'Ella animations avec le projet Renaissance est ici : https://launchpad.net/ella-renaissance et des fichiers de démo ici : http://ellarenaissance.voila.net/index.html Hors ligne
The Problem I first saw the term "tab dump" on Dori Smith's blog, but I immediately recognized the concept. I keep Safari running all the time and with the help of Hao Li's wonderful extension Saft I keep everything in tabs in one window. Among its many features, Saft will let you consolidate your windows into tabs of one window, and it can save the tabs you have open when you close (or crash) Safari, and re-open them automatically when you start Safari again. What it doesn't do is give you a list of all the tabs you have open in text format, suitable for blog or email. I don't currently put tag dumps on the blog because a) I'd feel guilty doing that without adding at least a short comment for each link, which would take too much time, and b) because this isn't really a link blog, more a place for me to bash out example code and tutorials. At least, that's how I think of it. I do however, find Safari teetering on the brink of being unfunctionally slow because I have so many tabs open, and often they're only open because I want to remember to do something with them later, or come back to them, or some other reminder-type function. So I send myself a tab dump on a more-or-less daily basis. Firefox has tools to help you do this, but I haven't seen anything for Safari, possibly because you can't really do it with a Safari plugin, but need to use an InputManager, which is fairly deep magic, and basically a hack, an abuse of the system. On the other hand, I couldn't keep using Safari if it wasn't for Saft, and Saft is an InputManager. Another tool for blocking ads and such (which Saft also does) is PithHelmet, but the interesting thing to me about PithHelmet isn't that it is a popular ad blocker, but that the Mike Solomon (who wrote PithHelmet) decided to not just make an InputManager, but to make the only InputManager you'll ever need. You see, PithHelmet itself is not an InputManager, it is a plugin for SIMBL (also by Solomon), which is an InputManager that loads plugins based on the application(s) they claim to support. InputManagers get loaded by every application (Cocoa apps, at least), so you have to be careful you're in the app you want to modify, and take steps not to break things. SIMBL takes care of the nasty business of being a well-behaved system hack, and your code can assume it is in the right app, because it doesn't get loaded otherwise. The Goal Once I figured out that the only way I was going to get Tab Dumping behaviour into Safari (because Safari tabs don't play well with Javascript, that turned out to be a dead-end), I decided to try writing an InputManager in Python. SIMBL is open-source, so at first I was looking at the code to see what I need to do to create an InputManager (remember, this is a hack, so Apple doesn't document it very well). I also read Mike's essay Armchair Guide To Cocoa Reverse Engineering. What I decided was that, rather than recreate the functionality in SIMBL using Python, I would just create a SIMBL plugin in Python. Getting started wasn't too bad, but I found one issue in the above essay that stumped me for awhile. Mike recommends you put your initialization code into a class method load() which gets called after your class is loaded. I don't know if it is artifact of using PyObjC or what, but my load() method was never getting called. What I did instead was to run the command-line utility class-dump on another SIMBL plugin to see what they were doing. They were using the class method initialize() rather than load and when I switched to that things started working, where by "things" I mean, "I could print to the console to see that my class had loaded." The Solution The next step was to actually do something once I had my code loading into Safari. The tab behaviour of Safari isn't part of WebKit, so it isn't documented anywhere. Once again, I used the handy class-dumputility. This is a fabulous tool which will read any Cocoa library, bundle, or application and produce a pseudo-header file showing all the objects and methods defined. I still had to try a few different paths to get to the tab information I wanted, but it was pretty easy, armed as I was with Python and the output of class-dump. Here is the result: import objc from Foundation import * from AppKit import * class TabDump(NSObject): # We will retain a pointer to the plugin to prevent it # being garbage-collected plugin = None @classmethod # the following is not strictly necessary, but we only # need one instance of our object def sharedInstance(cls): if not cls.plugin: cls.plugin = cls.alloc().init() return cls.plugin @classmethod def initialize(cls): app = NSApp() menu = app.windowsMenu() cls.item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Dump tabs to clipboard', 'tabdump:', '') # should be after "Previous Tab" and "Next Tab" menu.insertItem_atIndex_(cls.item, 6) cls.item.setTarget_(cls.sharedInstance()) def tabdump_(self, source): output = [] app = NSApp() for window in app.windows(): if window.className() == 'BrowserWindow': controller = window.windowController() for browserWebView in controller.orderedTabs(): output.append(browserWebView.mainFrameTitle().encode('utf8')) output.append(browserWebView.mainFrameURL().encode('utf8')) output.append('') self.copyToPasteboard_('\n'.join(output)) def copyToPasteboard_(self, string): pasteboard = NSPasteboard.generalPasteboard() pasteboard.declareTypes_owner_([NSStringPboardType], self) pasteboard.setString_forType_(string, NSStringPboardType) As you can see, on my class being initialized, I create a new menu item and insert it into the Windows menu. This could be more robust, by testing menu item names to make sure I'm in the right place, but it works for me, and simple code is more maintainable code. I create an instance of my object and make it the target of the menu item. Pretty basic stuff. When the tabdump method is called (by selecting the menu item in Safari), it walks through Safari's window objects (of which there are many) until it finds browser windows, then it extracts the tabbed views from the browser windows to get the titles and URLs involved. When it has collected all the title/URL pairs, it turns it into a big string and puts the string on the pasteboard. Here is where we could be a lot fancier. I'm just putting title/URL pairs, separated by newlines in plain text, because that's how I mail them to myself. You could easily create Markdown links or any other format here. You could turn them into HTML and put them on the Pasteboard that way. There's a lot you can do, and the Firefox tool I used to use to do this offered so many options that I was never sure what most of them actually did. Here you can customize the code to do exactly what you need, and keep it simple. Building the plugin I haven't tested this with multiple windows, or with a window with only one tab. It might work, might not. I don't plan on using it that way, and if I do, it's easy enough to fix. Now, there is one more thing you'll need, which is the setup.py script to build it. Assuming you've saved the above code as TabDump.py, the following script should be what you need: ''' Minimalist build file for TabDump.py To build run 'python setup.py py2app' on the command line ''' from distutils.core import setup import py2app plist = dict( NSPrincipalClass='TabDump', CFBundleName='TabDump', SIMBLTargetApplications=[ dict( BundleIdentifier='com.apple.Safari', MinBundleVersion='312', MaxBundleVersion='420')], ) setup( plugin=['TabDump.py'], options=dict(py2app=dict( extension='.bundle', plist=plist, )), ) In the above file, MinBundleVersion and MaxBundleVersion can keep your code from being loaded if an untested version of the application is running. I have more-or-less dummy values there, don't treat them as the right thing to do. The SIMBLTargetApplications key holds a list, so if you want your code to load in other applications, add more dictionaries to the list. Also note that you can build your bundle with python setup.py py2app -A to create a development version (can't ship it that way) that is all symlinks, so you can edit TabDump.py to make changes without having to rebuild the plugin. If you modify the MinBundleVersion or MaxBundleVersion you will have to rebuild to regenerate the property list (or move the property list to be an external file rather than generating it in setup.py), but that should be an infrequent operation. More importantly, you can put a symlink to your bundle in your ~/Library/Application Support/SIMBL/Plugins/ directory. Then you can make changes to the python code and test it by simply restarting Safari. WARNING: If you have a syntax error in your file, Safari will most likely hang on restart. Just force quit it and check your console for the error to fix. The Promise Now, if you've followed along with me so far, I'd like to point out a few things that are really freaking cool about this. Item the first: You now have Python running in Safari. Can you think of anything else you'd like it to do while you're there? I bet you can. Item the second: You can do this in any Cocoa-based application just as easily. Problems in Mail.app? Frustrated by iChat? Just fix it. Take control of your own applications! Make the computer work for you, not the other way around. Item the third: dump-classes gives you the keys to the kingdom. Seriously, the combination of being able to embed Python and get a listing of the objects and methods at will is so powerful that when I got TabDump working late last night and realized what I'd just done (i.e., these three things), I was barely able to get to sleep after that. The possibilities are endless. If you use this and do something cool with it, please drop me a line and tell me about it. I'm really looking forward to hearing about what kind of cool ways we can push our existing applications. Correction [2006-08-30] The class-dump utility rocks, and you should add it to your arsenal of Cocoa tools, along with Python and PyObjC. Since I've found it it has already become indispensable for examining existing applications that I want to, er, adjust. Here's what I've learned so far. First, I want to update my previous post to talk a little bit more about the command-line utility class-dump. This is a fine tool that lets you introspect a Cocoa bundle (plugin, library, or application) and prints out a header file describing all the objects and methods in that bundle. I didn't mention where to get it, and at BarCamp this weekend I gave some mis-information by telling people it came with Apple's developer tools, which is not true. I assumed that's where it came from, because I didn't remember hearing of it before reading Mike Solomon's Armchair Guide to Cocoa Reverse Engineering, which refers to classdump without any explanation of where to get it. I tried it, found class-dump worked (tab-completion is your friend), and assumed it came with my system, when in fact I had installed it earlier after reading about it on another blog (I'm afraid I don't remember where) meaning to try it out, then forgotten about it. So it was there, waiting for me, when I discovered a need for it. So the truth is, class-dump is a utility written by Steve Nygard. He says it provides the same output as the developer tools command otool -ov, but formatted as a header file. Besides the basic output it can also do various kinds of filtering, sorting, and formatting. So this is my Tool of the Week (and then some): class-dump. Use it, love it, thank Steve.
I'm trying to insert data into my database and I get a MYSQL syntax error using this code: import MySQLdb db=MySQLdb.connect(host="localhost",user="root",passwd="",db="database") cursor = db.cursor() sql = "INSERT INTO table1('col1','col2') values ('val1','val2');" cursor.execute(sql) db.commit()
I'm trying to import a CSV, using this code: import csv import sys def load_csv(filename): # Open file for reading file = open(filename, 'r') # Read in file return csv.reader(file, delimiter=',', quotechar='\n') def main(argv): csv_file = load_csv("myfile.csv") for item in csv_file: print(item) if __name__ == "__main__": main(sys.argv[1:]) Here's a sample of my csv file: foo,bar,test,1,2 this,wont,work,because,α And the error: Traceback (most recent call last): File "test.py", line 22, in <module> main(sys.argv[1:]) File "test.py", line 18, in main for item in csv_file: File "/usr/lib/python3.2/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 40: ordinal not in range(128) Obviously, It's hitting the character at the end of the CSV and throwing that error, but I'm at a loss as to how to fix this. Any help? This is: Python 3.2.3 (default, Apr 23 2012, 23:35:30) [GCC 4.7.0 20120414 (prerelease)] on linux2
The Python compiler optimizes access to local variables by recognizing at compile time whether the barenames a function is accessing are local (i.e., barenames assigned or otherwise bound within the function). So if you code: def lv1(d): locals().update(d) print zap the compiler "knows" that barename zap is NOT local (not assigned in function lv1) and so it compiles code to access it as a global instead -- whatever d contains won't matter. If you prefer slow and bloated code, you can defeat the optimization by using an exec inside the function -- when the compiler sees the keyword exec, it KNOWS you're trying to make your code as slow, bloated and buggy as possible, and so it cooperates by not optimizing in any way, just about. So, the following code works as you desire: def lv1(d): exec "" locals().update(d) print zap lv1({'zap': 23}) it emits 23 as you want. I hope it's clear from the above "deadpan humor" that the technique is not recommended, but I'd better spell it out very explicitly: for the dubious syntactic pleasure of writing print zap in lieu of print locals()['zap'], you ARE paying a hefty price in terms of performance. Still, like all sorts of dangerous tools that can be useful in rare use cases for really experienced guru-level programmers who really truly know what they're doing and why, exec is there, available for you to use (or mis-use) at your whim: Python does NOT stand in your way!-)
I'm new to both Python and Django and am struggling with what I'm sure is a very simple thing. I'm using PyCharm as my ide and am attempting to follow quickstart guide [here][1]. I setup a virtual env as per the tutorial. The project is "DjangoProjectApp" and the app is "Lunch" With the files shown below and a browser pointed to http://localhost:8000/admin/ I get the error: ImportError at /admin/No module named 'DjangoProjects.Lunch' But if I comment out the second url route in urls.py then it works. What is the correct way for me to import this module? Thanks. urls.py: from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'DjangoProjects.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^lunch/$', 'DjangoProjects.Lunch.views.index') ) views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render_to_response def index(request): return render_to_response('index.html') index.html hello world! settings.py """ Django settings for DjangoProjects project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'd^d9v4j(1maq-&_8^a+kgicmagxwbv*9m$!2st&vqz$5_h$441' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Lunch', 'django.contrib.admin', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'DjangoProjects.urls' WSGI_APPLICATION = 'DjangoProjects.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/'
Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Si c'est Floyd Pepper... Eh mais c'est l'week-end ! Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Bonjour, Golgoth devait en bricoler un mais il n'a pas dis quand! Hors ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Dans l'année ? Ras&#039; Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Lolilol de lève-tard Va t'faire shampouiner en GMT-4 ! http://blag.xserver-x.org/ Les types awesome n'ont rien à prouver. À personne. Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Dans l'année ? Oui, mais il n'a pas dit quelle année !! Dernière modification par pierguiard (Le 09/06/2012, à 12:35) Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 1 1748 FloydPepper 2 1520 pierguiard 3 1463 MdMax 4 1247 Azurea 5 1179 souen 6 938 Ras&#039; 7 725 raspouillas 8 552 Arcans 9 428 peterp@n 10 359 golgoth42 11 277 omc 12 268 mindiell 13 219 Πυλάδης 14 176 pololasi 15 117 edge_one 16 101 nathéo 17 99 karameloneboudeplus 18 61 agarwood 19 60 Niltugor 20 52 1101011 20 52 jeyenkil 22 43 Crocoii 23 42 nakraïou 23 42 DaveNull 25 40 Biaise 26 39 Clem_ufo 27 38 Atem18 28 22 marinmarais 29 18 Ju 30 13 Le grand rohr sha 30 13 ljere 32 10 Phoenix 32 10 FLOZz 32 10 sakul 32 10 SopolesRâ 36 6 wiscot 36 6 timsy 36 6 Slystone 36 6 Hibou57 36 6 tshirtman 36 6 marting 36 6 c4nuser 43 4 Morgiver 43 4 :!pakman 45 3 Phoenamandre 45 3 gonzolero 45 3 helly 45 3 Le Rouge 49 1 herewegoagain 49 1 TheUploader 49 1 Kyansaa 49 1 Xiti29 Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. En ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Mon bonjour du petit matin ... A quoi bon un compteur. Merci @Floyd Pepper ... Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] De rien Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. En ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] yop Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Bonjour On devrait prendre des conjoints comme on prend des députés, pour cinq ans ; après cela, le conjoint essayerait de se faire réélire. Hors ligne souen Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Salut Tu es programmé, mais tu es libre. Ubuntu Studio "Si il n'y a pas de solution, c'est qu'il n'y a pas problème !" (sagesse Shadok) Hors ligne Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] J'en parlerai à ma femme tiens, on va fêter nos 5 ans de mariage ;P Hors ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Bonne fête @Mindiell ... ps:Et à votre femme ... Dernière modification par raspouillas (Le 10/06/2012, à 10:50) Ras&#039; Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 5 ans ! C'est long ! Va t'faire shampouiner en GMT-4 ! http://blag.xserver-x.org/ Les types awesome n'ont rien à prouver. À personne. Hors ligne Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Allons Ras, Plus c'est long, plus c'est bon ! @raspouillas: thanks ! Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] @Floyd Pepper tu peux me passer le code du compteur que je puisse le mettre sur mon serveur Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] je crois qu'il compte a la main! Hors ligne compteur des leve tot Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] test manuel 1 1754 FloydPepper 2 1521 pierguiard 3 1463 MdMax 4 1247 Azurea 5 1180 souen 6 938 Ras&#039; 7 731 raspouillas 8 552 Arcans 9 428 peterp@n 10 359 golgoth42 11 277 omc 12 269 mindiell 13 219 Πυλάδης 14 176 pololasi 15 117 edge_one 16 101 nathéo 17 99 karameloneboudeplus 18 61 agarwood 19 60 Niltugor 20 52 1101011 20 52 jeyenkil 22 43 Crocoii 23 42 nakraïou 23 42 DaveNull 25 40 Biaise 26 39 Clem_ufo 27 38 Atem18 28 22 marinmarais 29 18 Ju 30 16 ljere 31 13 Le grand rohr sha 32 10 Phoenix 32 10 FLOZz 32 10 sakul 32 10 SopolesRâ 36 6 wiscot 36 6 timsy 36 6 Slystone 36 6 Hibou57 36 6 tshirtman 36 6 marting 36 6 c4nuser 43 4 Morgiver 43 4 :!pakman 45 3 Phoenamandre 45 3 gonzolero 45 3 helly 45 3 Le Rouge 49 1 herewegoagain 49 1 TheUploader 49 1 Kyansaa 49 1 Xiti29 Dernière modification par ljere (Le 11/06/2012, à 07:13) Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Merci à ljere de s'inquiéter de ma santé Donc pour faire court : - golgoth42 à fait une adaptation du compteur des [alcooliques] couche-tard pour ce fil. - ça à bien fonctionné jusqu'au changement de topic … - une correction devait être apportée à cette adaptation, je n'y crois plus Depuis je poste (de manière aléatoire : c'est voulu, pour ménager le suspense) un compteur fait à la mano avec l'aide de calc. wouala! Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. En ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Wouahhh Si c'est pas réactif !!! pour comparaison je poste le mien (des fois qui ai des erreurs, de saisie de ma part bien-sûr) 1 1754 FloydPepper 2 1521 pierguiard 3 1463 MdMax 4 1247 Azurea 5 1180 souen 6 938 Ras&#039; 7 731 raspouillas 8 552 Arcans 9 428 peterp@n 10 359 golgoth42 11 277 omc 12 269 mindiell 13 219 Πυλάδης 14 176 pololasi 15 117 edge_one 16 101 nathéo 17 99 karameloneboudeplus 18 61 agarwood 19 60 Niltugor 20 52 1101011 20 52 jeyenkil 22 43 Crocoii 23 42 nakraïou 23 42 DaveNull 25 40 Biaise 26 39 Clem_ufo 27 38 Atem18 28 22 marinmarais 29 18 Ju 30 16 ljere 31 13 Le grand rohr sha 32 10 Phoenix 32 10 FLOZz 32 10 sakul 32 10 SopolesRâ 36 6 wiscot 36 6 timsy 36 6 Slystone 36 6 Hibou57 36 6 tshirtman 36 6 marting 36 6 c4nuser 43 4 Morgiver 43 4 :!pakman 45 3 Phoenamandre 45 3 gonzolero 45 3 helly 45 3 Le Rouge 49 1 herewegoagain 49 1 TheUploader 49 1 Kyansaa 49 1 Xiti29 Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. En ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] je suppose donc qu'ils ont la meme erreur que moi └─> ./Nouveau\ compteur.py lecture de la page http://forum.ubuntu-fr.org/viewtopic.php?pid=9590061#p9590061 page récupéré, travail en cours edit found error ->['<em>Derni\xc3\xa8re modification par pierguiard (Hier \xc3\xa0 12:35)</em>'] lecture scores courants Traceback (most recent call last): File "./Nouveau compteur.py", line 304, in <module> main("url",["count","count10days"]) File "./Nouveau compteur.py", line 264, in main scores.append(Score([(line.split(' ')[0]),exp.split(line)[1].split('\n')[0]])) IndexError: list index out of range Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Si c'est mon message qui pose problème, vire le. Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] vite fait, les "seules" erreurs que je trouve se trouve ici 30 13 Le grand rohr sha 30 16 ljere30 11 ljere 31 13 Le grand rohr sha avec en premières valeurs ton compteur : place, points, pseudo et à la suite "mon compteur : place , points, pseudo Edit : après vérif il y a également une erreur dans le Nb de points de mindiell, c'est forcement une erreur de saisie (désolé pour lui). Dernière modification par Floyd Pepper (Le 10/06/2012, à 19:45) Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. En ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] mon test n'est pas concluant il y a en effet pas mal d'erreur non pierguiard ton message ne pose aucun souci c'est juste la réédition de ton message qui est bien prise en compte Dernière modification par ljere (Le 10/06/2012, à 20:55) Hors ligne
Numerical Python For the past few months, I've been covering different software packages for scientific computations. For my next several articles, I'm going to be focusing on using Python to come up with your own algorithms for your scientific problems. Python seems to be completely taking over the scientific communities for developing new code, so it is a good idea to have a solid working knowledge of the fundamentals so you can build solutions to your own problems. In this article, I start with NumPY. My next article will cover SciPy, and then I'll look at some of the more complicated modules available in the following article. So, let's start with the root module from which almost all other scientific modules are built, NumPY. Out of the box, Python supports real numbers and integers. You also can create complicated data structures with lists, sets and so on. This makes it very easy to write algorithms to solve scientific problems. But, just diving in naively, without paying attention to what is happening under the hood, will lead to inefficient code. This is true with all programming languages, not just Python. Most scientific code needs to squeeze every last available cycle out of the hardware. One of the things to remember about Python is that it is a dynamic language where almost all functions and operators are polymorphic. This means that Python doesn't really know what needs to be done, at a hardware level, until it hits that operation. Unfortunately, this rules out any optimizations that can be made by rearranging operations to take advantage of how they are stored in memory and cache. One property of Python that causes a much larger problem is polymorphism. In this case, Python needs to check the operands of any operator or function to see what type it is, decide whether this particular operand or function can handle these data types, then use the correct form of the operand or function to do the actual operation. In most cases, this is not really an issue because modern computers have become so fast. But in many scientific algorithms, you end up applying the same operations to thousands, or millions, of data points. A simple example is just taking the square of the first 100,000 numbers: import time a = range(100000) c = [] starttime = time.clock() for b in a: c.append(b*b) endtime = time.clock() print "Total time for loop: ", (endtime - starttime) This little program uses the range function to create a list of thefirst 100,000 integers. You need to import the time module to get accessto the system clock to do timing measurements. Running this on my desktoptakes approximately 0.037775 seconds (remember always to make severalmeasurements, and take the average). It takes this much time becausefor every iteration of the loop, Python needs to check the type of theb variable before trying to use the multiplication operator. What canyou do if you have even more complicated algorithms? This is where NumPY comes in. The key element that NumPY introduces is an N-dimensional array object. The great flexibility of Python lists, allowing all sorts of different types of elements, comes at a computational cost. NumPY arrays deal with this cost by introducing restrictions. Arrays can be multidimensional, and they must all be the same data type. Once this is done, you can start to take some shortcuts by taking advantage of the fact that you already know what the type of the elements is. It adds extra overloading functions for the common operators and functions to help optimize uses of arrays. All of thenormal arithmetic operators work on NumPY arrays in an element-wisefashion. So, to get the squares of the elements in an array, it wouldbe as simple as array1 * array1. NumPY also uses external standard, optimized libraries written in C or FORTRAN to handle many of the actual manipulations on these array data types. This is handled by libraries like BLAS or lapack. Python simply does an initial check of each of the arrays in question, then hands them as a single object to the external library. The external library does all of the hard work, then hands back a single object containing the result. This removes the need for Python to check each element when using the loop notation above. Using NumPY, the earlier example becomes: import numpy import time a = numpy.arange(1000000) starttime = time.clock() c = a * a endtime = time.clock() print "Total time used: ", (endtime - starttime) Running this toy code results in an average run time of 0.011167 seconds for this squaring operation. So the time is cut by one third, and the readability of the code is simplified by getting rid of the loop construct. I've dealt only with one-dimensional arrays so far, but NumPY supports multidimensional arrays just as easily. If you want to define a two-dimensional array, or a matrix, you can set up a small one with something like this: a = numpy.array([[1,2,3,4], [2,3,4,5]]) Basically, you are creating a list of lists, where each of the sub-listsis each of the rows of your matrix. This will work only if each of thesub-lists is the same size—that is, each of the rows has the same numberof columns. You can get the total number of elements in this matrix,with the property a.size. The dimensions of the matrix are stored inthe property a.shape. In this case, the size is 8, and the shape is(2, 4), or two rows and four columns. What shape did the array in theearlier example have? If you go ahead and check, you should see thatthe shape is (1000000). The other key properties of these arrays are: ndim: the number of dimensions. dtype: the data type of the elements. itemsize: the size in bytes of each element. data: the buffer that stores the actual data. You also can reshape arrays. So if you wanted to take the earlier example of the first 100,000 integers and turn it into a three-dimensional array, you could do something like this: old_array = numpy.arange(100000) new_array = old_array.reshape(10,100,100) This will give you a new 3-D array laid out into a 10x100x100 element cube. Now, let's look at some of the other functions available to apply toarrays. If you remember from earlier, all of the standard arithmeticoperations are overloaded to operate on arrays one element at a time. But,most matrix programming languages use the multiplication element to meanmatrix multiplication. This is something to keep in mind when you startusing Python. To get a true matrix multiplication, you need to use thedot() function. If you have two matrices, A and B, you can multiplythem with numpy.dot(A, B). Many of the standard mathematical functions,like cosine, sine, square root and so on, are provided by NumPY and arecalled universal functions. Just like with the arithmetic operators,these universal functions are applied element-wise across the array. Inscience, several common functions are used. You can getthe transpose of a matrix with the object functiona.transpose(). Ifyou need to get the inverse of a matrix, there is the module functioninv(), so you would executenumpy.inv(a). The trace is also a modulefunction, given by numpy.trace(a). Even more complicatedfunctions are available. You can solve systems of equations with NumPY. Ifyou have a matrix of coefficients given by a, and a vector of numbersrepresenting the right-hand side of your equations given by y, you cansolve this system with numpy.solve(a,y). In manysituations, you maybe interested in finding the eigenvalues and eigenfunctions of a givensystem. If so, you can use numpy.eig(array1) to getthose values. The last thing I want to look at here is a class that provides even more shortcuts, at the cost of more restrictions. Matrices (2-D arrays) are so prevalent that NumPY provides a special class to optimize operations using them as much as possible. To create a new matrix, say a 2x2 matrix, you would write: A = numpy.matrix('1.0, 2.0; 3.0, 4.0') Now, you can get the transpose with just A.T. Similarly, the inverseis found with A.I. The multiplication operation will do actual matrixmultiplication when you use matrix objects. So, given two matrix objectsA and B, you can do matrix multiplication with A*B. The solve functionstill works as expected on systems of equations that are defined usingmatrix objects. Lots of tips and tricks available on the NumPYWeb site, which is well worth a look, especially as you start out. This short introduction should get you started in thinking of Python as a viable possibility in "real" numerical computations. The NumPY module provides a very strong foundation to build up complex scientific workflows. Next month, I'll look at one of the available modules, SciPY. Until then, play with all of the raw number-crunching possibilities provided by NumPY. Joey Bernard has a background in both physics and computer science. This serves him well in his day job as a computational research consultant at the University of New Brunswick. He also teaches computational physics and parallel programming. Geolocation Give new life to old phones and tablets with these tips! Lucidchart Memory Ordering in Modern Microprocessors, Part I Source Code Scanners for Better Code Linux Systems Administrator Tech Tip: Really Simple HTTP Server with Python Senior Perl Developer Technical Support Rep Putlocker!! Watch Begin Again Online 2014 Streaming Full Movie
Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Sur amazon, j'ai trouvé ce livre "Python - Les Fondamentaux du langage - La Programmation pour les scientifiques. de Matthieu Brucher" Très bon livre, dans la mesure où tu sais déjà programmer et que tu es intéressé par la partie scientifique, il te conviendra parfaitement. Après, je ne suis pas un grand spécialiste de Python, mais il me semble faire une bonne présentation du langage. Certains trouvent que le niveau y est un peu soutenu. Il semble avoir plutôt bonne presse chez les habitués de Python. Quelques réponses pèle-mêle : Ce n'est pas tant que je suis habitué à des matrices creuses (même si j'en utilise pas mal), mais à faire des benchmarks sur des machines dédiés au calcul et pour ne pas être trop perturbé par les à-côtés, il vaut mieux faire des calculs un peu long. Oui, j'ai déjà inversé des matrices 100000x100000 -- oui, c'est long. Si j'ai ajouté un affichage, c'est parce que je suis habitué à utiliser des options de compilations agressives et, sur des benchmarks, le risque est que le code ne fasse plus rien. Cela dit, il vaut mieux, en effet, n'afficher qu'une seule case de la matrice. Par contre, je pense que Python remplace avantageusement Matlab : on évite d'être dépendant d'un fournisseur, Python est capable de faire tout ce que Matlab peut faire, mais en étant plus généraliste. D'autant qu'il s'interface très bien avec Fortran, C et C++ (utiliser Boost.Python). Par contre, on peut être amené dans certain cas à devoir coder des éléments pour lesquelles il existe déjà une bibliothèque sous Matlab. Cela dit, je suis désolé, mais je ne connais pas assez bien Python pour pouvoir faire une présentation exhaustive de ses bibliothèques dédiés aux scientifiques. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage J'ai commandé le livre. Après lecture, je posterai un avis (je ne sais pas quel est le meilleur post pour cela). J'envisagerai alors plus sérieusement la possibilité de coder un projet plus complexe en python, pour comparer. Pour ce qui est de notre benchmark, la différence entre python et le fortran compilé avec les produits INTEL ne semble pas énorme (sur ce cas simple, il est vrai). Je vais même voir s'il n'y a pas moyen de recompiler numpy avec MKL. Je vais aussi essayer de comprendre pourquoi gfortran donne de si mauvais résultats. Et... je vais aussi un peu travailler ! Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Je vais aussi essayer de comprendre pourquoi gfortran donne de si mauvais résultats. Je préfère G95 à GFortran. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Après lecture, je posterai un avis (je ne sais pas quel est le meilleur post pour cela) * le HS ayant peut être assez duré (mes excuses, ce n'était pas l'intention), le mieux sera sans doute d'ouvrir un nouveau post (sauf si Le Farfadet Spacial pense le contraire, c'est son sujet). Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! le HS ayant peut être assez duré (mes excuses, ce n'était pas l'intention), le mieux sera sans doute d'ouvrir un nouveau post (sauf si Le Farfadet Spacial pense le contraire, c'est son sujet). Il n'est sans doute pas nécessaire d'ouvrir un sujet juste pour la critique d'un seul livre et certains scientifiques peuvent venir ici alors qu'ils cherchent un langage adapté à leurs besoins : alors, ce livre pourrait les intéresser, donc il reste sans doute pertinent de donner son avis ici. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne mydjey Re : Petit guide pour aider au choix d'un langage Je reviens dans ce topic demander quelques infos. J'ai commencé la prog il y'a quelques temps avec le C. Même si le bouquin que j'utilise est très didactique.... Comment dire ? C'est chaud le C et un peu décourageant. Début de semaine je suis tombé sur un site qui explique les bases du python. Waoou ! En 2 heures on va dire, j'ai fait ce que j'ai mis plus d'une semaine à apprendre en C. Ma question :Quelle est pour vous le bouquin le plus sympa pour débuter avec python ? Sachant que pour le moment je dispose de ses 3 bouquins en pdf : * Le Swinnen * A byte of Python * Plongez au cœur de python (dive into python) Bien que très connu, j'ai lu que vous trouviez le Swinnen bof, bof. Des 3 lequel vous parait le mieux ? J'ai aussi vu que Farfadet Spatial propose : Python : Petit guide à l'usage du développeur agile J'ai regardé un peu les commentaires sur Amazon. Et je me demande si il est bien écris pour le débutant en programmation ce bouquin ? Il explique les bases de python ? Les boucles, les conditions, donne des explications sur la programmation OO, comment mettre en place son code dans Linux etc... ? Merci pour vos avis. Mon site : http://mydjey.eu/ Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage /me a "python - syntaxe, conception et optimisation" de tarek ziadé, qui prends vraiment par la main, depuis les bases jusqu'a un niveau intermédiaire (mais tout à fait solide), mais bon, c'est un bouquin irl, pas un pdf. (mais bon, ça à l'aire de bien correspondre à ta demande). pour le développement agile, je suppose que le bouquin se focalise plus sur des pratiques de développement en général encouragé dans la communauté python, l'écriture de test unitairs, l'intégration continue, ce genre de choses… enfin, je pense que les boucle et toute la base du langage, le tuto python en ligne (en anglais mais bon) est tout à fait adapté. edit: correction du titre. Dernière modification par tshirtman (Le 17/03/2010, à 00:47) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Attention, il y a une erreur dans notre petit benchmark. Le code python ci-dessus produit des array, et l'opérateur * sur des array réalise la multiplication élément par élément, et non la multiplication matricielle. Pour obtenir la multiplication matricielle, il faut utiliser le type matrix from numpy import * for i in range(10): A = matrix(random.rand(1000,1000)) B = matrix(random.rand(1000,1000)) C = A * B ce qui donne time python test.pyreal 0m17.783suser 0m17.561ssys 0m0.200s Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Attention, il y a une erreur dans notre petit benchmark. Comme quoi, il fallait se méfier, mais je vous avais prévenus : je n'avais pas testé. ce qui donne time python test.py real 0m17.783s user 0m17.561s sys 0m0.200s Hé bien, je dois dire que je ne m'y attendais pas du tout, je n'étais pas resté là-dessus. Peux-tu faire ce test plusieurs fois (par exemple trois fois), faire la moyenne, puis donner la valeur. Cela ne va pas être trop éloigné, mais cela permettra d'avoir un chiffre assez indépendant du système. Ce serait bien de comparer avec la même chose en Fortran sur le même système. Après, il faudra voir avec une application plus réaliste, comme un petit code d'éléments finis, mais je suis prêt à réviser mon point de vue s'il s'avère que la concurrence est possible. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage J'ai réalisé le test 4 fois en python et 4 fois en fortran Résultats Fortran REAL : 0.50875USER : 0.40900SYS : 0.01900 Résultats Python REAL : 17.959USER : 17.431SYS : 0.1680 Il y a quand même une nette différence. J'essaye de compiler numpy avec les librairies MKL mais je n'y suis pas encore arrivé. Si tu en as le temps, peux-tu écrire le même code en C++ pour comparer ? J'ai reçu le livre mentionné plus haut hier. Je l'ai déjà pas mal parcouru et pour l'instant mon impression est plutôt négative. Je formulerai un avis plus honnête après une lecture complète. Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Attention, il semble qu'il y aie encore une erreur, mais cette fois dans mon code FORTRAN, il semble qu'il ne calcule pas du tout le produit, ce qui explique sa grande rapidité ! Si j'utilise la fonction intrinsèque matmul plutot que blas, fortran met 13 secondes. Si je compile numpy avec ATLAS, celui met 7 secondes... Bref, rien de concluant pour les bench. Tout dépend des librairies utilisées. En effet pour l'instant c'est en python que je vais le plus vite pour faire mon produit ! j'ai commencé un code FEM en python, je vous tiens au courant. Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Si tu en as le temps, peux-tu écrire le même code en C++ pour comparer ? Ma soutenance a lieu lundi, il faudra attendre un peu. N'hésitez pas à me relancer en fin de semaine si je n'ai rien fourni. Bref, rien de concluant pour les bench. Ce n'est guère surprenant. j'ai commencé un code FEM en python, je vous tiens au courant. Oui, c'est plutôt un tel code qui permet de juger. Pour là où j'en suis resté, le facteur de ralentissement de Python le rend impropre pour faire plus qu'un modèle jouet -- c'est-à-dire, pour ceux qui pensent qu'il s'agit d'un terme péjoratif, d'un modèle exploratoire pour étudier certains points théoriques. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage c'est-à-dire, pour ceux qui pensent qu'il s'agit d'un terme péjoratif, d'un modèle exploratoire pour étudier certains points théoriques. la simplicité du language et sa proximité avec les expression mathématique a en effet cet avantage, permettre de comparer simplement plusieurs algos en termes d'efficacité, quitte à réimplémenter dans un language plus rapide si nécessaire, l'algo qui aura été trouvé le plus rapide. Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! la simplicité du language et sa proximité avec les expression mathématique a en effet cet avantage, permettre de comparer simplement plusieurs algos en termes d'efficacité, quitte à réimplémenter dans un language plus rapide si nécessaire, l'algo qui aura été trouvé le plus rapide. C'est-à-dire que pour les algorithmes, il y a l'analyse de complexité en temps et en espace, c'est beaucoup plus significatif qu'une implémentation, qui peut être bogué, entre autre. Non, un modèle-jouet, c'est surtout utilisé pour étudier un phénomène particulier en entrant autant que possible dans un cas idéal, c'est-à-dire en l'isolant de tout autre phénomène. Il existe des choses basées sur Python pour réaliser cela facilement et efficacement, mais je ne retrouve plus le nom. À bientôt. Le Farfadet Spatial Édition : je suis en train de me dire qu'on pourrait penser qu'il y a acharnement, je précise donc que je n'ai aucune dent contre Tshirtman -- ni contre Python, d'ailleurs. Dernière modification par Le Farfadet Spatial (Le 21/03/2010, à 01:15) L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage je le prends pas comme de l'acharnement, et je pense qu'on pourrait tout à fait penser la même chose de mes interventions ^^, tu as des choses intéressantes à dire sur l'intérêt des langages pour diverses utilisations, on peut être d'accord ou pas, mais il n'y a pas de mal à les dire. en effet, mon interventions sur les algos était réductrice par rapport au concept de modele objet. Pour ce dont tu parles sans retrouver le nom, tu penses peut être au mocking pour simuler l'environnement autour du cas étudié? bien que ce ne soit pas spécifique au python je pense. Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Bonne chance pour ta soutenance Farfardet ! Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Pour ce dont tu parles sans retrouver le nom, tu penses peut être au mocking pour simuler l'environnement autour du cas étudié? bien que ce ne soit pas spécifique au python je pense. Non, ce n'est pas ça. C'est quelque chose de purement éléments-finis. J'essayerais de chercher le nom. En gros, tu écris les équations dirigeant ton modèle et les conditions aux limites sous une forme très proche de la façon naturelle d'écrire des équations, tu donnes ton maillage et tout le reste est automatique. Pour ceux qui connaissent, un équivalent de FreeFEM, mais en Python. Bonne chance pour ta soutenance Farfardet ! Merci. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage l'interface de getfem++ pour python peut être ? Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! l'interface de getfem++ pour python peut être ? Non plus... J'essayerais de retrouver. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Bonjour, J'ai avancé dans l'écriture d'un code FEM en python, et pour l'instant un gros problème apparaît. Les fonctions optimisées de numpy sont très rapides, elles ne posent pas de problème. Par contre, les performances de python se font sentir pour tout ce qui est autour ! Principalement, la vitesse d'accès aux éléments d'un dictionnaire ou la vitesse d'itération sur des listes rend l'entreprise inenvisageable pour des problèmes de taille raisonnable. Par exemple, pour un maillage de 10 000 tetrahèdres, il faut presque une heure juste pour construire la matrice ! Je vais écrire un exemple minimal pour que tout cela soit plus concret. Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Si tu as des problèmes de ce coté là, l'utilisation de psyco peut aider beaucoup. import psyco psyco.full() Au début de ton code, rien à faire de plus. Malheureusement, ça ne marche que sur x86 (ça réalise de la compilation just in time, le projet pypy promet de résoudre ça et d'amener de telles performances sur toutes les plateformes.) Dernière modification par tshirtman (Le 26/03/2010, à 12:59) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Malheureusement, cela n'a pas l'air ce changer quoi que soit chez moi. Je vais essayer plusieurs choses 1) Pour l'instant j'utilise des dictionnaires qui prennent des objets comme clés. J'ai lu quelque part que les dictionnaires allaient plus vite en prenant des caractères. Je vais essayer de modifier cela 2) Les itérations sur des listes d'objet semblent extrêmement lentes. Est-ce qu'il n'y a pas une astuce pour booster cela, en définissant mieux les __hash__ ou quelque chose du genre ? 3) Je vais installer python 3 pour voir ! Pour en revenir au sujet du post, si je ne résous pas ces problèmes, je ne conseillerai pas Python pour du calcul scientifique de "moyenne performance" Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Pas de problème, mais c'est un peu long et complexe Voici les classes définissant les objets géométriques class node: """ node class """ def __init__(self,num,x,y,z): self._globNum = num self._x = x self._y = y self._z = z def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def numberOfNodes(self): return 1 def getInterpolation(self,U,u,v,w): return u(1) ######################################################################## class line(node): """ line class """ def __init__(self,num,tag,partition,node1,node2): self._globNum = num self._tag = tag self._partition = partition self._node1 = node1 self._node2 = node2 def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def getTag(self): return self._tag def getPartition(self): return self._partition def getNodes(self): return [self._node1,self._node2] def numberOfNodes(self): return 2 def getShapesFunctions(self,u,v,w): shf = [ 0.5 * (1-u), 0.5 * (1+u) ] return shf def getGradShapesFunctions(self,u,v,w): gx = [-0.5 , 0.5] gy = [ 0.0 , 0.0] gz = [ 0.0 , 0.0] gdsf = [ gx , gy , gz] return gdsf def getInterpolation(self,U,u,v,w): shf = self.getShapesFunctions(u,v,w) value = shf(0) * U(0) + shf(1) * U(1) return value ######################################################################## class triangle(node): """ triangle class """ def __init__(self,num,tag,partition,node1,node2,node3): self._globNum = num self._tag = tag self._partition = partition self._node1 = node1 self._node2 = node2 self._node3 = node3 def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def getTag(self): return self._tag def getPartition(self): return self._partition def getNodes(self): return [self._node1,self._node2,self._node3] def numberOfNodes(self): return 3 def getShapesFunctions(self,u,v,w): shf = [ (1 - u - v) , u , v ] return shf def getGradShapesFunctions(self,u,v,w): gx = [ -1.0 , 1.0 , 0.0] gy = [ -1.0 , 0.0 , 1.0] gz = [ 0.0 , 0.0 , 0.0] gdsf = [ gx , gy , gz] return gdsf def getInterpolation(self,U,u,v,w): shf = self.getShapesFunctions(u,v,w) value = shf(0) * U(0) + shf(1) * U(1) + shf(2) * U(2) return value ######################################################################### class tetrahedron(node): """ tetrahedron class """ def __init__(self,num,tag,partition,node1,node2,node3,node4): self._globNum = num self._tag = tag self._partition = partition self._node1 = node1 self._node2 = node2 self._node3 = node3 self._node4 = node4 def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def getTag(self): return self._tag def getPartition(self): return self._partition def getNodes(self): return [self._node1,self._node2,self._node3,self._node4] def numberOfNodes(self): return 4 def getShapesFunctions(self,u,v,w): shf = [ (1 - u - v - w) , u , v , w] return shf def getGradShapesFunctions(self,u,v,w): gx = [ -1.0 , 1.0 , 0.0 , 0.0 ] gy = [ -1.0 , 0.0 , 1.0 , 0.0 ] gz = [ -1.0 , 0.0 , 0.0 , 1.0 ] gdsf = [ gx , gy , gz] return gdsf def getInterpolation(self,U,u,v,w): shf = self.getShapesFunctions(u,v,w) value = shf(0) * U(0) + shf(1) * U(1) + shf(2) * U(2) + shf(3) * U(3) return value ######################################################################################## La classe définissant le maillage from geom import * class mesh : """ mesh class """ def __init__(self,file_name): """ constructor of the mesh class, from a gmsh file """ self._NODES = [] self._LINES = [] self._TRIANGLES = [] self._TETRAHEDRONS = [] #open the file f = open(file_name,"r") # nodes lecture str = "a" while str != "$Nodes": str = f.readline().strip() self._numNodes = int(f.readline()) for i in xrange(self._numNodes): str = f.readline().strip().split() n = node(int(str[0]) , float(str[1]) , float(str[2]) , float(str[3])) self._NODES.append(n) str = f.readline() # elements lecture str = f.readline() self._numElements = int(f.readline()) for i in xrange(self._numElements): str = f.readline().strip().split() if str[1] == "1": num = int(str[0]) tag = int(str[3]) partition = int(str[5]) numNode1 = int(str[6]) - 1 numNode2 = int(str[7]) - 1 node1 = self._NODES[numNode1] node2 = self._NODES[numNode2] n = line(num,tag,partition,node1,node2) self._LINES.append(n) elif str[1] == "2": num = int(str[0]) tag = int(str[3]) partition = int(str[5]) numNode1 = int(str[6]) - 1 numNode2 = int(str[7]) - 1 numNode3 = int(str[8]) - 1 node1 = self._NODES[numNode1] node2 = self._NODES[numNode2] node3 = self._NODES[numNode3] n = triangle(num,tag,partition,node1,node2,node3) self._TRIANGLES.append(n) elif str[1] == "4": num = int(str[0]) tag = int(str[3]) partition = int(str[5]) numNode1 = int(str[6]) - 1 numNode2 = int(str[7]) - 1 numNode3 = int(str[8]) - 1 numNode4 = int(str[9]) - 1 node1 = self._NODES[numNode1] node2 = self._NODES[numNode2] node3 = self._NODES[numNode3] node4 = self._NODES[numNode4] n = tetrahedron(num,tag,partition,node1,node2,node3,node4) self._TETRAHEDRONS.append(n) else: if str[1] != "15": print "There are non implemented type of element in the mesh" print "-Mesh reading" print "Mesh file name :", file_name print "Number of nodes :", self._numNodes print "Number of lines :", len(self._LINES) print "Number of triangles :", len(self._TRIANGLES) print "Number of tetrahedrons :", len(self._TETRAHEDRONS) print "-End of mesh reading " # close the file f.close() def getNumNodes(self): return self._numNodes def getElementsByTag(self,dim,tag): """ function returning a list of elements of dimension 'dim' and tag 'tag' """ elements = [] if dim == 1: for line in self._LINES: if line.getTag() == tag: elements.append(line) elif dim == 2: for triangle in self._TRIANGLES: if triangle.getTag() == tag: elements.append(triangle) elif dim == 3: for tetrahedron in self._TETRAHEDRONS: if tetrahedron.getTag() == tag: elements.append(tetrahedron) return elements def getVerticesByTag(self,dim,tag): """ function returning a list a elements if dimension 'dim' and tag 'tag' """ elements = self.getElementsByTag(dim,tag) vertices = set([]) for elem in elements : a = elem.getNodes() vertices.update(a) return vertices ############################################################################################## La classe gérant les degrés de libertés from geom import * from collections import * from linear_system import * class dofkey: def __init__(self,node,name): self._node = node self._name = name def __eq__(self,other): node = other.getNode() name = other.getName() if (self._node == node) and (self._name == name): return True else: return False def __hash__(self): value = hash(self._name) return value def getNode(self): return self._node def getName(self): return self._name class dof_manager: def __init__(self): self._numbering = defaultdict() self._fixed = defaultdict() def fixVertex(self,node,name,val): dof = dofkey(node,name) self._fixed[dof]=val def numberVertex(self,node,name): dof = dofkey(node,name) if self._fixed.get(dof,"_") == "_": self._numbering[dof]=(len(self._numbering)) def fixVertices(self,nodes,name,val): fix = self.fixVertex for node in nodes: fix(node,name,val) def numberVertices(self,nodes,name): number = self.numberVertex for node in nodes: number(node,name) def getNumberingSize(self): return len(self._numbering) def getFixedSize(self): return len(self._fixed) def linkToLinearSystem(self,lsys): self._lsys = lsys def fixInSolution(self,node,name,val): dof = dofkey(node,name) num = self._numbering.get(dof,-1) if not num == -1: self._lsys.fixInSolution(num,val) def addToMatrix(self,dofi,dofj,val): if (dofi in self._numbering.keys()): if (dofj in self._numbering.keys()): R = self._numbering[dofi] C = self._numbering[dofj] self._lsys.addToMatrix(R,C,val) else: R = self._numbering[dofi] F = self._fixed[dofj] self._lsys.addToRHS(R,-val*F) def addToRHS(self,dofi,val): if (dofi in self._numbering.keys()): R = self._numbering[dofi] self._lsys.addToRHS(R,val) def assembleInMatrix(self,node1,node2,n,local): unknows = ["RHO","P","UX","UY","UZ","Y","e","eps","T","k","h","YEQ","DEFF"] for i in xrange(n-1): f = "X" + str(i+1) unknows.append(f) unknows.append("XN") for i in xrange(n-1): f = "T" + str(i+1) unknows.append(f) unknows.append("TN") for i in xrange(13+2*n): dofi = dofkey(node1,unknows[i]) for j in xrange(13+2*n): dofj = dofkey(node2,unknows[j]) self.addToMatrix(dofi,dofj,local[i,j]) def assembleInVector(self,node1,n,local): unknows = ["RHO","P","UX","UY","UZ","Y","e","eps","T","k","h","DEFF"] for i in xrange(n-1): f = "X" + str(i+1) unknows.append(f) unknows.append("XN") for i in xrange(n-1): f = "T" + str(i+1) unknows.append(f) unknows.append("TN") for i in xrange(13+2*n): dofi = dofkey(node1,unknows[i]) self.addToRHS(dofi,local[i]) def getNewDofValue(self,node,name): dof = dofkey(node,name) if (dof in self._numbering.keys()): R = self._numbering[dof] val = self._lsys.getFromNewSolution(R) else: val = self._fixed[dof] return val def getOldDofValue(self,node,name): dof = dofkey(node,name) if (dof in self._numbering.keys()): R = self._numbering[dof] val = self._lsys.getFromOldSolution(R) else: val = self._fixed[dof] return val def systemSolve(self): self._lsys.solve() def getSolution(self): return self._lsys.getSolution() Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage le programme principal, qui ne fait que numéroter les variables # -*- coding: utf8 -*- # from geom import * from mesh import * from dof_manager import * # Paramètres du problème # nombre de noeuds dans les grains n = 10 # incrément d'espace dans les grains dr = 0.0008 # incrément de temps dT = 10 #Températures de l'air à l'entrée Ta = [50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50] #Teneur en eau de l'air a l'entrée Y = 0.005 #Vitesse de l'air Va = 1.0 # Lecture du maillage maillage = mesh("lit.msh") # Obtention des différents éléments Entree_1 = maillage.getVerticesByTag(2,40) Entree_2 = maillage.getVerticesByTag(2,29) Entree_3 = maillage.getVerticesByTag(2,18) Entree_4 = maillage.getVerticesByTag(2,95) Entree_5 = maillage.getVerticesByTag(2,84) Entree_6 = maillage.getVerticesByTag(2,66) Entree_7 = maillage.getVerticesByTag(2,55) Entree_8 = maillage.getVerticesByTag(2,44) Entree_9 = maillage.getVerticesByTag(2,48) Entree_10 = maillage.getVerticesByTag(2,36) Entree_11 = maillage.getVerticesByTag(2,25) Entree_12 = maillage.getVerticesByTag(2,14) Entree_13 = maillage.getVerticesByTag(2,91) Entree_14 = maillage.getVerticesByTag(2,80) Entree_15 = maillage.getVerticesByTag(2,70) Entree_16 = maillage.getVerticesByTag(2,59) Entree_17 = maillage.getVerticesByTag(2,112) Parois = maillage.getVerticesByTag(2,601) Sortie = maillage.getVerticesByTag(2,602) Elements = maillage.getVerticesByTag(3,603) # Assembleur print "\n-Begining of assembler building-" assem = dof_manager() for i in xrange(17): Entree = "Entree_" + str(i+1) assem.fixVertices(Entree,"UX",0) assem.fixVertices(Entree,"UY",0) assem.fixVertices(Entree,"UZ",Va) assem.fixVertices(Entree,"T" ,Ta[i]) assem.fixVertices(Entree,"Y" ,Y) assem.fixVertices(Parois,"UX",0) assem.fixVertices(Parois,"UY",0) assem.fixVertices(Parois,"UZ",0) assem.fixVertices(Sortie,"P",101325) assem.numberVertices(Elements,"RHO") assem.numberVertices(Elements,"P") assem.numberVertices(Elements,"UX") assem.numberVertices(Elements,"UY") assem.numberVertices(Elements,"UZ") assem.numberVertices(Elements,"Y") assem.numberVertices(Elements,"e") assem.numberVertices(Elements,"eps") assem.numberVertices(Elements,"T") assem.numberVertices(Elements,"k") assem.numberVertices(Elements,"h") assem.numberVertices(Elements,"YEQ") assem.numberVertices(Elements,"DEFF") assem.numberVertices(Elements,"X1") for i in xrange(2,n): f = "X" + str(i) assem.numberVertices(Elements,f) assem.numberVertices(Elements,"XN") assem.numberVertices(Elements,"T1") for i in xrange(2,n): f = "T" + str(i) assem.numberVertices(Elements,f) assem.numberVertices(Elements,"TN") print "-End of assembler building-\n" Hors ligne