text
stringlengths
256
65.5k
I am getting following logcat messages while registering the Android device using cordova push notification plugin. 01-25 19:33:34.871: V/GCMRegistrar(6495): Is registered on server: false 01-25 19:33:34.871: D/GCMRegistrar(6495): resetting backoff for com.example.homework 01-25 19:33:34.941: V/GCMRegistrar(6495): Registering app com.example.homework of senders 19845108581 01-25 19:33:35.011: D/memalloc(6495): ashmem: Mapped buffer base:0x534bb000 size:1536000 fd:90 01-25 19:33:35.011: D/CordovaLog(6495): report:deviceready 01-25 19:33:35.011: I/Web Console(6495): report:deviceready at file:///android_asset/www/js/index.js:122 01-25 19:33:35.162: V/GCMBroadcastReceiver(6495): onReceive: com.google.android.c2dm.intent.REGISTRATION 01-25 19:33:35.162: V/GCMBroadcastReceiver(6495): GCM IntentService class: com.arellomobile.android.push.PushGCMIntentService 01-25 19:33:35.172: V/GCMBaseIntentService(6495): Acquiring wakelock 01-25 19:33:35.192: D/GCMBaseIntentService(6495): handleRegistration: registrationId = null, error = SERVICE_NOT_AVAILABLE, unregistered = null 01-25 19:33:35.192: D/GCMBaseIntentService(6495): Registration error: SERVICE_NOT_AVAILABLE 01-25 19:33:35.192: I/GCMIntentService(6495): Received recoverable error: SERVICE_NOT_AVAILABLE 01-25 19:33:35.192: D/GCMBaseIntentService(6495): Scheduling registration retry, backoff = 2788 (3000) 01-25 19:33:35.192: D/Socket_Alarm(6495): registerHTCSocketMonitorCallBack 01-25 19:33:35.192: D/Socket_Alarm(6495): set mSocketMonitor 01-25 19:33:35.192: D/Socket_Alarm(6495): HTCSocketMonitorImpl::HTCSocketMonitorImpl 01-25 19:33:35.352: V/GCMBaseIntentService(6495): Releasing wakelock 01-25 19:33:36.603: D/DroidGap(6495): onMessage(spinner,stop) 01-25 19:35:03.978: V/webview(6495): hitTestResult use fallback I am setting the correct values for projectid and appid in javascript file. And also my android device is configured with Google account. I am following this guide http://www.pushwoosh.com/programming-push-notification/android-gcm-push-notifications-guide/ Any suggestion would be helpful.
Perhabs Tahoma is a TrueType font, and you need to register it first. According to the user guide of ReportLab you need to do this: from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) canvas.setFont('Vera', 32) canvas.drawString(10, 150, "Some text encoded in UTF-8") canvas.drawString(10, 100, "In the Vera TT Font!") The canvas object has a getAvailableFonts method that should return all currently registered (and therefore usable) fonts.
October 25th, 2011 at 6:06 pm by Dr. Drang I’ve written about this so many times in the past, I’m not sure I can link to every iteration. The idea is to show—on the Desktop via NerdTool—the name, the artist, the rating, the album, and the album artwork of the iTunes track currently playing. Like this: The album artwork part broke under Lion and the Lion-compatible version of NerdTool, so I had to do a little code surgery. Rather than taking you through the convoluted history of this code, I’m going to try to present everything you need in one post. The text info The text is generated through a Python script called itunes-playing, which I keep, along with most of the scripts I write, in my ~/bin/ folder. It uses the third-party appscript library, which gives Python the AppleScript-like ability to control other Mac applications. So before you try to use itunes-playing, you’ll have to install appscript. Since appscript needs to be compiled, you’ll first have to install Xcode, which is a free—albeit lengthy— download from the Mac App Store. Be aware that installing what the MAS calls Xcode doesn’t actually install Xcode itself; it installs an Xcode installer that you’ll then have to run. I screwed this up a couple of weeks ago. Forgot that installing Xcode 4 from the Mac App Store only installs the installer. Now installing from the installer that I installed from… In summary: Install the Xcode installer from the Mac App Store. Run the Xcode installer. Install the appscriptPython library. There are lots of ways to do this third step. If you’re not a big Python user, my suggestion is to do this from the Terminal: sudo easy_install appscript and type your administrator password when prompted for it. You may be wondering whether all this preliminary bullshit is worth it. I can’t answer for you, but for me installing Xcode and appscript are things I’d be doing anyway so there’s no extra burden. OK, onto itunes-playing itself. It’s a short script that pulls the information about the current track from iTunes and formats it. python: 1: #!/usr/bin/env python 2: 3: from appscript import * 4: 5: template = '"%s" by %s (%d)\n from %s' 6: info = '' 7: 8: iTunesCount = app('System Events').processes[its.name == 'iTunes'].count() 9: if iTunesCount > 0: 10: iTunes = app('iTunes') 11: if iTunes.player_state.get() == k.playing: 12: track = iTunes.current_track.get() 13: who = track.artist.get() 14: what = track.name.get() 15: onwhat = track.album.get() 16: stars = track.rating.get()/20 17: info = template % (what, who, stars, onwhat) 18: print info Lines 8-9 check to see if iTunes is running. Line 11 check to see if it’s playing. If both of those are true, it pulls the information out of iTunes and prints it, otherwise it prints an empty string. I have NerdTool set to run this command via python ~/bin/itunes-playing every 10 seconds and display it, right justified in 14-point white Lucida Grande Bold, down near the lower right corner of my screen. The album artwork The next script is an embarrassingly convoluted and deeply nested AppleScript. It started out as a fairly simple AppleScript, but it grew in complexity as I added provisions to handle situations that I didn’t consider originally. I probably should rewrite it entirely in Python and appscript, but I don’t feel up to it yet. And for all its Rube Goldbergian intricacies, it does work. It’s called itunes-art, and it’s also kept in ~/bin/. Its purpose is to get the album artwork for the playing track and write it, in PNG format, to a particular file. NerdTool, in turn, looks for that file to display on the Desktop. If iTunes isn’t playing, or if there’s no artwork for the track, a transparent PNG image is written to that file instead. Here’s the code. 1: -- Paths and stuff 2: set JPEGFromiTunes to ((path to home folder) as text) & ¬ 3: "Pictures:iTunes Artwork:From iTunes:albumArt.jpg" as alias 4: set PNGFromiTunes to ((path to home folder) as text) & ¬ 5: "Pictures:iTunes Artwork:From iTunes:albumArt.png" as alias 6: set TIFFFromiTunes to ((path to home folder) as text) & ¬ 7: "Pictures:iTunes Artwork:From iTunes:albumArt.tiff" as alias 8: set iTunesArtwork to ((path to home folder) as text) & ¬ 9: "Pictures:iTunes Artwork:From iTunes:albumArt.png" 10: set DefaultArtwork to ((path to home folder) as text) & ¬ 11: "Pictures:iTunes Artwork:Default:albumArt.png" 12: set displayArtwork to ((path to home folder) as text) & ¬ 13: "Pictures:iTunes Artwork:albumArt.png" 14: 15: -- Unix versions of the above path strings 16: set unixITunesArtwork to the quoted form of POSIX path of iTunesArtwork 17: set unixDefaultArtwork to the quoted form of POSIX path of DefaultArtwork 18: set unixDisplayArtwork to the quoted form of POSIX path of displayArtwork 19: 20: set whichArt to "blank" 21: tell application "System Events" 22: if exists process "iTunes" then -- iTunes is running 23: tell application "iTunes" 24: if player state is playing then -- iTunes is playing 25: set aLibrary to name of current playlist -- Name of Current Playlist 26: set aTrack to current track 27: set aTrackArtwork to null 28: if (count of artwork of aTrack) ≥ 1 then -- there's an album cover 29: set aTrackArtwork to raw data of artwork 1 of aTrack 30: if (format of artwork 1 of aTrack) contains "JPEG" then 31: set fileRef to ¬ 32: (open for access JPEGFromiTunes with write permission) 33: else 34: if (format of artwork 1 of aTrack) contains "TIFF" then 35: set fileRef to ¬ 36: (open for access TIFFFromiTunes with write permission) 37: else 38: set fileRef to ¬ 39: (open for access PNGFromiTunes with write permission) 40: end if 41: end if 42: write aTrackArtwork to fileRef starting at 0 43: close access fileRef 44: 45: if (format of artwork 1 of aTrack) contains "JPEG" then 46: tell application "Image Events" 47: set theImage to open JPEGFromiTunes 48: save theImage as PNG in unixITunesArtwork 49: end tell 50: else 51: if (format of artwork 1 of aTrack) contains "TIFF" then 52: tell application "Image Events" 53: set theImage to open JPEGFromiTunes 54: save theImage as PNG in unixITunesArtwork 55: end tell 56: end if 57: end if 58: set whichArt to "iTunes" 59: end if 60: end if 61: end tell 62: end if 63: end tell 64: 65: if whichArt is "iTunes" then 66: do shell script "ditto -rsrc " & unixITunesArtwork & space & unixDisplayArtwork 67: else 68: do shell script "ditto -rsrc " & unixDefaultArtwork & space & unixDisplayArtwork 69: end if Yuck. Lines 1-18 define the names and locations of a bunch of files that the script writes and/or reads. They’re all kept in the ~/Pictures/iTunes Artwork/ folder, the contents of which looks like this: The albumArt.png at the top is the one NerdTool looks for. The albumArt.png in the Default folder is the transparent PNG we use when iTunes isn’t playing or the track has no artwork. The albumArt.* files in the From iTunes folder are what the script gets from iTunes. Lines 21-24 make sure iTunes is running and a track is playing. Lines 28-41 get the artwork for the currently playing track, determine its format (JPEG, TIFF, or PNG), and open a file in the From iTunes folder for writing. Lines 42-43 write the data—whatever its format—out to the file and close it. If the artwork is in JPEG or TIFF format, we have to convert it to PNG, which is what Lines 45-57 do. NerdTool can display JPEGs and TIFFs just fine, but because we’re going to tell it to look for a particular file, we have to choose a format—I chose PNG. Finally, Lines 65-68 copy the appropriate file—either Default/albumArt.png or From iTunes/albumArt.png—to the top level of iTunes Artwork where NerdTool can find it. I have NerdTool configured to run the script osascript ~/bin/itunes-art.scpt every 10 seconds, and to look at file://localhost/Users/drdrang/Pictures/iTunes%20Artwork/albumArt.png for the image to display. It’s set to scale the image proportionally and center it in a 150×150 square just above the text. Summary To review, there are three NerdTool entries: A Command entry for the Python script that displays the text. A Command entry for the AppleScript that pulls out the album art and copies it to the right place. A URL entry that displays the copied album art on the Desktop. To run the Python script, you’ll need the appscript library, which means you’ll need Xcode. This is why I can’t simply package this stuff up and give you a ready-to-run, self-installing bundle of code. What about GeekTool? All of these scripts have run at one time or another under GeekTool, and I see no reason to believe they wouldn’t do so now. I prefer NerdTool because GeekTool seems like a bit of a memory hog, but your experience may be different.
I am appending "00000000" to a string and it works fine for the first time. However, when run second time "Junk Characters" are appended instead of "000000". This is the sample code how I am doing it in the actual program. File one.py # File One.py from two import * def One(): while(1): key = Two() key = key + "00000000" print key def main(): One() if __name__ == "__main__": main() File two.py from ctypes import * import binascii handle = None def Two(): global handle libc = CDLL('libthree.so', DEFAULT_MODE, handle) if not handle: handle = libc._handle buffer = create_string_buffer(16) libc.Three(buffer) return binascii.b2a_hex(buffer) File three.c - Generates libthree.so #include "stdio.h" #include "stdlib.h" void Three(char * buffer) { long value = 0x78563412; memcpy(buffer,&value,4); memcpy(buffer + 4,&value,4); memcpy(buffer+ 8,&value,4); memcpy(buffer+ 12,&value,4); return; } int main() { return 0; }
I was wondering if there is an easy way to build an indexable weak ordered set in Python. I tried to build one myself. Here's what I came up with: """ An indexable, ordered set of objects, which are held by weak reference. """ from nose.tools import * import blist import weakref class WeakOrderedSet(blist.weaksortedset): """ A blist.weaksortedset whose key is the insertion order. """ def __init__(self, iterable=()): self.insertion_order = weakref.WeakKeyDictionary() # value_type to int self.last_key = 0 super().__init__(key=self.insertion_order.__getitem__) for item in iterable: self.add(item) def __delitem__(self, index): values = super().__getitem__(index) super().__delitem__(index) if not isinstance(index, slice): # values is just one element values = [values] for value in values: if value not in self: del self.insertion_order[value] def add(self, value): # Choose a key so that value is on the end. if value not in self.insertion_order: key = self.last_key self.last_key += 1 self.insertion_order[value] = key super().add(value) def discard(self, value): super().discard(value) if value not in self: del self.insertion_order[value] def remove(self, value): super().remove(value) if value not in self: del self.insertion_order[value] def pop(self, *args, **kwargs): value = super().pop(*args, **kwargs) if value not in self: del self.insertion_order[value] def clear(self): super().clear() self.insertion_order.clear() def update(self, *args): for arg in args: for item in arg: self.add(item) if __name__ == '__main__': class Dummy: def __init__(self, value): self.value = value x = [Dummy(i) for i in range(10)] w = WeakOrderedSet(reversed(x)) del w[2:8] assert_equals([9,8,1,0], [i.value for i in w]) del w[0] assert_equals([8,1,0], [i.value for i in w]) del x assert_equals([], [i.value for i in w]) Is there an easier way to do this?
loic_e Kubuntu Dapper sur Sony VAIO VGN-FE28H Voici la procédure d'installation utilisée pour installer Kubuntu Dapper sur un Vaio VGN-FE28H: Caractéristiques: Processeur Intel Core Duo Fréquence 1.67 GHz Quantité de RAM 1 Go Type de RAM DDR2-SDRAM Disque dur 160 Go Puce graphique nVIDIA GeForce 7400 Turbo Cache Taille d'écran 15.4" Résolution 1280x800 Connectique 1 PCMCIA Type II, Wifi, 1 port FireWire, 3 ports USB 2.0, VGA, Bluetooth, ExpressCard/34 Carte réseau 10/100 10/100 Modem 56k Oui Système d'exploitation Windows XP Media Center Poids 2.8 kg Attention: Note concernant la garantie: Sony ne fournit pas de cd/dvd de restauration du système, il faut donc le faire au départ avant l'installation d'un autre Os, car en cas de pb, la garantie est invalide si un autre OS est installé. Le backup du système de base nécéssite deux DVDs. (prévoir une heure) Etape 1: J'ai utilisé un outil windows pour supprimer la partition D:, que je n'ai pas reformatée. Etape 2: Installation de Kubuntu via le live-cd, partitionnement sur l'espace libre. (Attention pour les néophytes, veiller à raccorder le pc au reseau pour les mises à jour et l'installation de la localisation) Etape 3: Mise à jour des paquets du système de base sudo apt-get update sudo apt-get dist-upgrade Etape 4: Mise en place d'un noyau SMP (bi-processeurs) Par défaut c'est un kernel 386 qui est installé, il faut donc mettre en place un noyau 686-smp et les restricted-modules sudo apt-get install linux-image-686 sudo apt-get install linux-restricted-modules-686 Etape 5: Modifier son sources-list: sudo cp /etc/apt/sources.list backup_sources.list kdesu /etc/apt/sources.list Ajout des dépots utiles, voici le mien: # If you get errors about missing keys, lookup the key in this file # and run these commands (replace KEY with the key number) # # gpg --keyserver subkeys.pgp.net --recv KEY # gpg --export --armor KEY | sudo apt-key add - KEY # Ubuntu supported packages (packages, GPG key: 437D05B5) deb http://fr.archive.ubuntu.com/ubuntu dapper main restricted deb http://fr.archive.ubuntu.com/ubuntu dapper-updates main restricted deb http://security.ubuntu.com/ubuntu dapper-security main restricted # Ubuntu supported packages (sources, GPG key: 437D05B5) deb-src http://fr.archive.ubuntu.com/ubuntu dapper main restricted deb-src http://fr.archive.ubuntu.com/ubuntu dapper-updates main restricted deb-src http://security.ubuntu.com/ubuntu dapper-security main restricted # Ubuntu community supported packages (packages, GPG key: 437D05B5) deb http://fr.archive.ubuntu.com/ubuntu dapper universe multiverse deb http://fr.archive.ubuntu.com/ubuntu dapper-updates universe multiverse deb http://security.ubuntu.com/ubuntu dapper-security universe multiverse # Ubuntu community supported packages (sources, GPG key: 437D05B5) deb-src http://fr.archive.ubuntu.com/ubuntu dapper universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu dapper-updates universe multiverse deb-src http://security.ubuntu.com/ubuntu dapper-security universe multiverse # Seveas' packages (packages, GPG key: 1135D466) deb http://seveas.theplayboymansion.net/seveas dapper-seveas all # Seveas' packages (sources, GPG key: 1135D466) deb-src http://mirror3.ubuntulinux.nl dapper-seveas all # Cipherfunk multimedia packages (packages, GPG key: 33BAC1B3) #deb ftp://cipherfunk.org/pub/packages/ubuntu/ dapper main # Cipherfunk multimedia packages (sources, GPG key: 33BAC1B3) #deb-src ftp://cipherfunk.org/pub/packages/ubuntu dapper main # kubuntu.org packages for the latest KDE version (packages, GPG key: DD4D5088) deb http://kubuntu.org/packages/kde-latest dapper main # kubuntu.org packages for the latest KDE version (sources, GPG key: DD4D5088) deb-src http://kubuntu.org/packages/kde-latest dapper main # kubuntu.org packages for the latest amaroK version (packages, GPG key: DD4D5088) deb http://kubuntu.org/packages/amarok-latest dapper main # kubuntu.org packages for the latest amaroK version (sources, GPG key: DD4D5088) deb-src http://kubuntu.org/packages/amarok-latest dapper main # Penguin Liberation Front (packages) deb ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ dapper free non-free # Penguin Liberation Front (sources) deb-src ftp://ftp.free.fr/pub/Distributions_Linux/plf/ubuntu/plf/ dapper free non-free # Bleeding edge wine packages (packages) deb http://wine.budgetdedicated.com/apt dapper main # Bleeding edge wine packages (sources) deb-src http://wine.budgetdedicated.com/apt dapper main # Bazaar-NG development (packages, GPG key: 1F44842D) deb http://people.ubuntu.com/~jbailey/snapshot/bzr ./ # Bazaar-NG development (sources, GPG key: 1F44842D) deb-src http://people.ubuntu.com/~jbailey/snapshot/bzr ./ # Xgl/Compiz #deb http://xgl.compiz.info/ dapper main #deb-src http://xgl.compiz.info/ dapper main #deb http://www.beerorkid.com/compiz/ dapper main Etape 6: Installation des drivers nvidia et configuration de X sudo apt-get install nvidia-glx puis editer le fichier /etc/X11/xorg.conf remplacer dans la section device "nv" par "nvidia" Redémarrer X (ctrl +Alt + backspace) voici mon xorg.conf: # /etc/X11/xorg.conf (xorg X Window System server configuration file) # # This file was generated by dexconf, the Debian X Configuration tool, using # values from the debconf database. # # Edit this file with caution, and see the /etc/X11/xorg.conf manual page. # (Type "man /etc/X11/xorg.conf" at the shell prompt.) # # This file is automatically updated on xserver-xorg package upgrades *only* # if it has not been modified since the last upgrade of the xserver-xorg # package. # # If you have edited this file but would like it to be automatically updated # again, run the following command: # sudo dpkg-reconfigure -phigh xserver-xorg Section "Files" FontPath "/usr/share/X11/fonts/misc" FontPath "/usr/share/X11/fonts/cyrillic" FontPath "/usr/share/X11/fonts/100dpi/:unscaled" FontPath "/usr/share/X11/fonts/75dpi/:unscaled" FontPath "/usr/share/X11/fonts/Type1" FontPath "/usr/share/X11/fonts/100dpi" FontPath "/usr/share/X11/fonts/75dpi" # path to defoma fonts FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType" EndSection Section "Module" Load "i2c" Load "bitmap" Load "ddc" Load "dri" Load "extmod" Load "freetype" Load "glx" Load "int10" Load "type1" Load "vbe" EndSection Section "InputDevice" Identifier "Generic Keyboard" Driver "kbd" Option "CoreKeyboard" Option "XkbRules" "xorg" Option "XkbModel" "pc104" Option "XkbLayout" "us" EndSection Section "InputDevice" Identifier "Configured Mouse" Driver "mouse" Option "CorePointer" Option "Device" "/dev/input/mice" Option "Protocol" "ExplorerPS/2" Option "ZAxisMapping" "4 5" Option "Emulate3Buttons" "true" EndSection Section "InputDevice" Identifier "Synaptics Touchpad" Driver "synaptics" Option "SendCoreEvents" "true" Option "Device" "/dev/psaux" Option "Protocol" "auto-dev" Option "HorizScrollDelta" "0" EndSection Section "InputDevice" Driver "wacom" Identifier "stylus" Option "Device" "/dev/wacom" # Change to # /dev/input/event # for USB Option "Type" "stylus" Option "ForceDevice" "ISDV4" # Tablet PC ONLY EndSection Section "InputDevice" Driver "wacom" Identifier "eraser" Option "Device" "/dev/wacom" # Change to # /dev/input/event # for USB Option "Type" "eraser" Option "ForceDevice" "ISDV4" # Tablet PC ONLY EndSection Section "InputDevice" Driver "wacom" Identifier "cursor" Option "Device" "/dev/wacom" # Change to # /dev/input/event # for USB Option "Type" "cursor" Option "ForceDevice" "ISDV4" # Tablet PC ONLY EndSection Section "Device" Identifier "NVIDIA Corporation NVIDIA Default Card" Driver "nvidia" BusID "PCI:1:0:0" EndSection Section "Monitor" Identifier "Écran générique" Option "DPMS" HorizSync 28-64 VertRefresh 43-60 EndSection Section "Screen" Identifier "Default Screen" Device "NVIDIA Corporation NVIDIA Default Card" Monitor "Écran générique" DefaultDepth 16 SubSection "Display" Depth 1 Modes "1280x800" EndSubSection SubSection "Display" Depth 4 Modes "1280x800" EndSubSection SubSection "Display" Depth 8 Modes "1280x800" EndSubSection SubSection "Display" Depth 15 Modes "1280x800" EndSubSection SubSection "Display" Depth 16 Modes "1280x800" EndSubSection SubSection "Display" Depth 24 Modes "1280x800" EndSubSection EndSection Section "ServerLayout" Identifier "Default Layout" Screen "Default Screen" InputDevice "Generic Keyboard" InputDevice "Configured Mouse" InputDevice "stylus" "SendCoreEvents" InputDevice "cursor" "SendCoreEvents" InputDevice "eraser" "SendCoreEvents" InputDevice "Synaptics Touchpad" EndSection Section "DRI" Mode 0666 EndSection Etape 7: Connectivité: Bluetooth, sans problème Wifi: fonctionne avec kwifi manager (fourni par défaut dans l'installation, mais peu pratique) J'ai donc installé le paquet knetwork-manager, que je trouve plus pratique, mais qui ne fonctionnait pas du tout sur le VAIO Après quelques recherches, j'ai désinstallé knetwork-manager et remplacé par network-manager-kdeet la... miracle, ça marche. J'ai fait le tri aussi de la configuration de interfaces.conf pour que ça fonctionne: mon interfaces.conf: auto loiface lo inet loopback Etape 8: Son: fonctionne "out of the box" Etape 9: Remarques: Voila, je n'ai pas eu de problèmes depuis.La touche mute fonctionne, mais pas les boutons de volume ni S1/S2, pas encore eu le temps de me pencher dessus. Si un seul bug, quand j'eteinds la machine, je n'ai pas de usplash visible, mais je ne n'ai pas constaté de bug dans les logs, donc pas grave (ce bug n'apparait que quand on utilise les drivers "nvidia", pas de problème avec "nv" J'ai tenté une install de xgl, mais qui s'est avéré trop lent, donc je le deconseille. Serais interéssé par toute info concernant les boutons spéciaux et/ou la gestion avancée de l'énergie/sonypi etc.. Mise à jour: 08 septembre 2006: 1- Problème de usplash avec kernel smp et drivers nvidia-glx: Depuis mon installation, j'avais rencontré le problème suivant: impossible d'utiliser tty, et pas de usplash. Apparemment c'est un bug des derniers drivers Nvidia, qui peut etre facilement corrigé en suivant les infos en bas de page. 2- Acpi et touches spéciales: Pas mal de googling sur l'acpi concernant ce vaio, mais peu d'infos disponibles, mes compétences ss linux étant limité, je fais du surplace. J'ai finalement désinstallé kpowersave pour réinstaller klaptopdaemon, au moins l'hibernation fonctionne, mais au redémarrage, le wifi ne fonctionne plus.. je vais continuer à rechercher dans cette direction... remarque: J'ai testé la machine sur batterie avec et sans Wifi/bluetooth, résultat équivalent, il faut donc jouer sur les paramètres de l'écran maintenant. Important: J'ai voulu tester cette histoire d'acpi avec d'autres distribs, pour lesquelles j'ai trouvé plus d'infos sur sonypi & sony_acpi, notamment gentoo, pas mieux... Les how-to que j'ai trouvé ne fonctionnent pas sur ce vaio. j'imagine que c'est lié soit au kernel, soit à la nvidia7400 (les how-to concernent des kernel 386 et des chipsets graphiques intégrés).Par contre j'ai eu une drole de surprise en bootant sur le live-cd Ubuntu Dapper, car sous Ubuntu, les touches de volume fonctionnent. Qu'y a til de different entre kubuntu et ubuntu à ce niveau ?? Donc si quelqu'un connaissant bien Ubuntu possédant un Vaio Duo etait interessé pour essayer d'echanger des feedbacks ubuntu/kubuntu sur l'acpi, il serait le bienvenu. C'est vraiment dommage, car je trouve que ce laptop est une excellente machine, mais qu'un tel manque d'autonomie nuit vraiment à son utilisation. Sticky: mon blog sur lequel je posterai l'avancée de mes recherches: http://www.especel.info Dernière modification par loic_e (Le 08/09/2006, à 16:43) Hors ligne Tsakos Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Salut, j'ai un Vaio A417M et je serais aussi interessé pour savoir comment on configure les touches speciales (volume, luminosité et S1, S2.). J'aimerais aussi savoir s'il est possible de gerer l'energie autrement parce que la consommation de mon PC est passé du simple au double par rapport à Windows. Merci d'avance. loic_e Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H salut Tsakos, je ne connais pas les caractéristiques de ton Vaio, mais ce qui est certain, c'est que malgré pas mal de recherches il n'y a aucune doc precise sur la configuration des dernieres générations de Vaio. Chez moi aussi, je trouve que le vaio consomme plus ss kubuntu que windows, ce qui est génant. A noter que le paramétrage de kpowersave est sans effet au niveau des paramètres de l'écran, ainsi que le suspend to ram/ to disk ne fonctionne pas. Enfin, concernant les touches F1/F2, je ne compte pas les utiliser, donc I don't care Si tu trouves des informations interessantes concernant l'acpi pour les vaio dual-core, je suis preneur.. bye Dernière modification par loic_e (Le 08/09/2006, à 16:45) Hors ligne loic_e Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Au sujet de la luminosité de l'écran, il est possible de la régler grace à smartdimmer, sur une échelle de 1 à 21. Vérifier que smartdimmer est installé, puis: loic@vaio:~$ smartdimmer nVIDIA SmartDimmer adjustment tool version 0.1. Usage: smartdimmer [OPTION]... Options: -g --get Query brightness level. -s --set <level> Set brightness level (1-21) -i --increase Increase brightness with one level. -d --decrease Decrease brightness with one level. -h --help Prints this help text. loic@vaio:~$ smartdimmer -g SmartDimmer level: 9 loic@vaio:~$ l'écran étant très brillant, je vais comparer l'autonomie du pc avec un réglage à 9. à suivre... Il existe aussi klcddimmer http://www.iwebyoumind.com/index.php?co … st&lang=en , mais je n'arrive pas à l'installer sur le FE28H. loic@vaio:~/sony_acpi/klcddimmer-0.1$ ./configure checking build system type... i686-pc-linux-gnu checking host system type... i686-pc-linux-gnu checking target system type... i686-pc-linux-gnu checking for a BSD-compatible install... /usr/bin/install -c checking for -p flag to install... yes checking whether build environment is sane... yes checking for gawk... no checking for mawk... mawk checking whether make sets $(MAKE)... yes checking for style of include used by make... GNU checking for gcc... gcc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ANSI C... none needed checking dependency style of gcc... gcc3 checking how to run the C preprocessor... gcc -E checking for g++... g++ checking whether we are using the GNU C++ compiler... yes checking whether g++ accepts -g... yes checking dependency style of g++... gcc3 checking whether g++ supports -Wmissing-format-attribute... yes checking whether g++ supports -Wundef... yes checking whether g++ supports -Wno-long-long... yes checking whether g++ supports -Wnon-virtual-dtor... yes checking whether g++ supports -fno-exceptions... yes checking whether g++ supports -fno-check-new... yes checking whether g++ supports -fno-common... yes checking whether g++ supports -fexceptions... yes checking how to run the C++ preprocessor... g++ -E checking whether g++ supports -O0... yes checking whether g++ supports -Wl,--no-undefined... yes checking whether g++ supports -Wl,--allow-shlib-undefined... yes not using lib directory suffix checking for a sed that does not truncate output... /bin/sed checking for egrep... grep -E checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for /usr/bin/ld option to reload object files... -r checking for BSD-compatible nm... /usr/bin/nm -B checking whether ln -s works... yes checking how to recognise dependent libraries... pass_all checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking dlfcn.h usability... yes checking dlfcn.h presence... yes checking for dlfcn.h... yes checking for g77... no checking for f77... no checking for xlf... no checking for frt... no checking for pgf77... no checking for fort77... no checking for fl32... no checking for af77... no checking for f90... no checking for xlf90... no checking for pgf90... no checking for epcf90... no checking for f95... no checking for fort... no checking for xlf95... no checking for ifc... no checking for efc... no checking for pgf95... no checking for lf95... no checking for gfortran... no checking whether we are using the GNU Fortran 77 compiler... no checking whether accepts -g... no checking the maximum length of command line arguments... 32768 checking command to parse /usr/bin/nm -B output from gcc object... ok checking for objdir... .libs checking for ar... ar checking for ranlib... ranlib checking for strip... strip checking if gcc static flag works... yes checking if gcc supports -fno-rtti -fno-exceptions... no checking for gcc option to produce PIC... -fPIC checking if gcc PIC flag -fPIC works... yes checking if gcc supports -c -o file.o... yes checking whether the gcc linker (/usr/bin/ld) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking for shl_load... no checking for shl_load in -ldld... no checking for dlopen... no checking for dlopen in -ldl... yes checking whether a program can dlopen itself... yes checking whether a statically linked program can dlopen itself... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... no configure: creating libtool appending configuration tag "CXX" to libtool checking for ld used by g++... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking whether the g++ linker (/usr/bin/ld) supports shared libraries... yes checking for g++ option to produce PIC... -fPIC checking if g++ PIC flag -fPIC works... yes checking if g++ supports -c -o file.o... yes checking whether the g++ linker (/usr/bin/ld) supports shared libraries... yes checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking for shl_load... (cached) no checking for shl_load in -ldld... (cached) no checking for dlopen... (cached) no checking for dlopen in -ldl... (cached) yes checking whether a program can dlopen itself... (cached) yes checking whether a statically linked program can dlopen itself... (cached) yes appending configuration tag "F77" to libtool checking for msgfmt... /usr/bin/msgfmt checking for gmsgfmt... /usr/bin/msgfmt checking for xgettext... /usr/bin/xgettext checking if C++ programs can be compiled... yes checking for strlcat... no checking if strlcat needs custom prototype... yes - in libkdefakes checking for strlcpy... no checking if strlcpy needs custom prototype... yes - in libkdefakes checking for main in -lutil... yes checking for main in -lcompat... no checking for crypt in -lcrypt... yes checking for socklen_t... socklen_t checking for dnet_ntoa in -ldnet... no checking for dnet_ntoa in -ldnet_stub... no checking for inet_ntoa... yes checking for connect... yes checking for remove... yes checking for shmat... yes checking for sys/types.h... (cached) yes checking for stdint.h... (cached) yes checking for poll in -lpoll... no checking CoreAudio/CoreAudio.h usability... no checking CoreAudio/CoreAudio.h presence... no checking for CoreAudio/CoreAudio.h... no checking if res_init needs -lresolv... yes checking if res_init is available... yes checking for killpg in -lucb... no checking for int... yes checking size of int... 4 checking for short... yes checking size of short... 2 checking for long... yes checking size of long... 4 checking for char *... yes checking size of char *... 4 checking for dlopen in -ldl... (cached) yes checking for shl_unload in -ldld... no checking for size_t... yes checking size of size_t... 4 checking for unsigned long... yes checking size of unsigned long... 4 checking sizeof size_t == sizeof unsigned long... yes checking crt_externs.h usability... no checking crt_externs.h presence... no checking for crt_externs.h... no checking for _NSGetEnviron... no checking for vsnprintf... yes checking for snprintf... yes checking for X... configure: error: Can't find X includes. Please check your installation and add the correct paths! Any help? Peut etre est-ce le meme problème qui empeche klaptopdaemon/kpowersave de gérer la luminosité ? Note: raccourcis + smartdimmer Il est pratique d'affecter smartdimmer -d ou smartdimmer -i à des raccourcis (via kcontrol/régionnabilité/ actions d'entrees/raccourci clavier) par exemple à windows + F6 / windows +F7 Dernière modification par loic_e (Le 11/09/2006, à 11:10) Hors ligne loic_e Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Touches Spéciales...; Voici ce que me renvoie xev sur les touches mute/vol-/vol+: KeyPress event, serial 31, synthetic NO, window 0x2e00001, root 0xed, subw 0x0, time 2575425093, (884,-193), root:(888,425), state 0x0, keycode 160 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 31, synthetic NO, window 0x2e00001, root 0xed, subw 0x0, time 2575425093, (884,-193), root:(888,425), state 0x0, keycode 160 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: KeyPress event, serial 31, synthetic NO, window 0x2e00001, root 0xed, subw 0x0, time 2575427121, (884,-193), root:(888,425), state 0x0, keycode 174 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 31, synthetic NO, window 0x2e00001, root 0xed, subw 0x0, time 2575427121, (884,-193), root:(888,425), state 0x0, keycode 174 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: KeyPress event, serial 31, synthetic NO, window 0x2e00001, root 0xed, subw 0x0, time 2575428180, (884,-193), root:(888,425), state 0x0, keycode 176 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 31, synthetic NO, window 0x2e00001, root 0xed, subw 0x0, time 2575428180, (884,-193), root:(888,425), state 0x0, keycode 176 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: les touches Fn /S1/S2 ne renvoient (hélas) rien... Concernant mes input devices: loic@vaio:~$ cat /proc/bus/input/devices I: Bus=0011 Vendor=0001 Product=0001 Version=ab41 N: Name="AT Translated Set 2 keyboard" P: Phys=isa0060/serio0/input0 S: Sysfs=/class/input/input0 H: Handlers=kbd event0 B: EV=120013 B: KEY=4 2000000 3802078 f840d001 f2ffffdf ffefffff ffffffff fffffffe B: MSC=10 B: LED=7 I: Bus=0011 Vendor=0002 Product=0008 Version=0000 N: Name="PS/2 Mouse" P: Phys=isa0060/serio4/input1 S: Sysfs=/class/input/input1 H: Handlers=mouse0 event1 ts0 B: EV=7 B: KEY=70000 0 0 0 0 0 0 0 0 B: REL=3 I: Bus=0011 Vendor=0002 Product=0008 Version=7321 N: Name="AlpsPS/2 ALPS GlidePoint" P: Phys=isa0060/serio4/input0 S: Sysfs=/class/input/input2 H: Handlers=mouse1 event2 ts1 B: EV=f B: KEY=420 0 70000 0 0 0 0 0 0 0 0 B: REL=3 B: ABS=1000003 I: Bus=0010 Vendor=104d Product=0000 Version=0000 N: Name="Sony Vaio Jogdial" P: Phys= S: Sysfs=/class/input/input3 H: Handlers=mouse2 event3 B: EV=7 B: KEY=40000 0 0 0 0 0 0 0 0 B: REL=100 I: Bus=0010 Vendor=104d Product=0000 Version=0000 N: Name="Sony Vaio Keys" P: Phys= S: Sysfs=/class/input/input4 H: Handlers=kbd event4 B: EV=3 B: KEY=1f ffff0000 0 20000 100000 0 2 0 0 100400 0 40300400 0 0 0 0 I: Bus=0003 Vendor=046d Product=c016 Version=0340 N: Name="Logitech Optical USB Mouse" P: Phys=usb-0000:00:1d.0-1/input0 S: Sysfs=/class/input/input5 H: Handlers=mouse3 event5 ts2 B: EV=7 B: KEY=70000 0 0 0 0 0 0 0 0 B: REL=103 input4 est bien detecté comme clavier "spécial" sony.. Ce que confirme evrouter loic@vaio:~$ sudo evrouter -D /dev/input/event* device 0: /dev/input/event0: AT Translated Set 2 keyboard device 1: /dev/input/event1: PS/2 Mouse device 2: /dev/input/event2: AlpsPS/2 ALPS GlidePoint device 3: /dev/input/event3: Sony Vaio Jogdial device 4: /dev/input/event4: Sony Vaio Keys device 5: /dev/input/event5: Logitech Optical USB Mouse Pas de problème donc pour remapper mute/vol-/Vol+, mais je n'arrive pas à scanner les touches Fn/S1/S2...; ennervant, si quelqu'un a une idée... La webcam "motion-Eye": un peu de googling ne m'a pas permis de trouver d'infos pouvant la faire fonctionner: loic@vaio:~$ lsusb Bus 005 Device 004: ID 0ac8:c002 Z-Star Microelectronics Corp. Il va falloir etre patient. Hors ligne Paul14 Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Merci pour ce post complet, c'est très sympa. Ce PC me tente, je compte installer Ubuntu dessus (comme mon ancien) mais j'ai 2 questions: 1) Est-il VRAIMENT silencieux? Meme sous Ubuntu (Kunbuntu dans ton cas). 2) Sous Windows as-tu pu faire tourner des jeux genre Tomb Raider Legend ou Oblivion? (Ce serait ma seule infidélité à Linux ;-) ) MERCI Hors ligne loic_e Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Oui le pc est vraiment silencieux, le seul peripherique bruyant est le graveur... pas très génant.; Sinon je n'ai pas essayé de jeu sous windows... Je ne regrette pas cet achat, mais ça ne fait que 2 semaines.... wait & see.. Dernière modification par loic_e (Le 15/09/2006, à 13:41) Hors ligne Paul14 Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Merci pour cette rapide réponse. Ca va m'aider. Hors ligne TatrefThekiller Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Un ami a un vgn-fe31h, identique au fe28h, à par le processeur multicoeur. Ca carte wifi est détectée dans le gestionnaire de périphériques, mais impossible de se connecter... Elle n'apparait pas dans iwconfig, ni ifconfig... C'est une 3950abg... Hors ligne k-nine Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Elle n'apparait pas dans iwconfig, ni ifconfig... C'est une 3950abg... Essaie peut-être ça, s'il ne peut pas savoir le nom de son interface, va falloir l'activer au pif : sudo ifconfig wlan0 up Ensuite si elle est présente quand tu fais un iwconfig, tu t'arrêtes là, c'est gagné. Sinon tu remplaces wlan0 par ath0 ou eth0 ou encore eth1, jusqu'à ce qu'elle apparaisse à un iwconfig. Tiens moi au jus Hors ligne TatrefThekiller Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H J'obtiens : "Ignoring unkown interface" avec n'importe quelle commande.... Bizarre... Hors ligne k-nine Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H et avec ça ? sudo iwconfig wlan0 up et en essayant toutes les interfaces possibles Hors ligne TatrefThekiller Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H En fait, j'ai fait ifup eth0, eth1,wlan0... Y a-t-il une différence ? Hors ligne k-nine Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H à prioris non mais as-tu mis sudo devant ? Hors ligne TatrefThekiller Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Oui... Hors ligne antitrust Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Mise à jour 12 Novembre 2006: Installation EDGY: Suite à installation Kubuntu Edgy: Les touches Mute, Vol-/vol+ fonctionnent enfin, ce qui était le cas sur ubuntu dapper mais pas sur kubuntu dapper, allez savoir pourquoi.. Parcontre, pas d'amélioration sur la gestion de l'acpi... ce qui est génant.. De plus on se retrouve avec kmylaptop & power-manager d'installés, les deux etant aussi peu efficaces l'un que l'autre.. D'autant que power-manager ne propose plus de régler la vitesse du processeur.. En plus des problèmes évoqués dans le post original, un autre élément que je regrette est la gestion de fstab.. ce n'est pas un problème spécifique au vaio, car je l'ai constaté sur un autre pc (desktop): j'ai un disque réseau iomega que je monte en ajoutant la ligne suivante dans /etc/fstab //192.168.1.10/NetHDD /media/nethdd smbfs uid=1000,gid=1000,auto,rw,nouser,guest 0 0 Le disque monte bien, automatiquement, mais nulle trace de lui dans le gestionnaire de disques de KDE.. Un nouveau bug .. cat /etc/fstab # /etc/fstab: static file system information. # # <file system> <mount point> <type> <options> <dump> <pass> proc /proc proc defaults 0 0 # /dev/sda2 -- converted during upgrade to edgy UUID=2846f2cc-a1e2-4d8c-9084-39fe154e0b8d / ext3 defaults,errors=remount-ro 0 1 # /dev/sda5 -- converted during upgrade to edgy UUID=2071bb24-394d-4a95-92a4-1389da77c032 none swap sw 0 0 /dev/hda /media/cdrom0 udf,iso9660 user,noauto 0 0 //192.168.1.10/NetHDD /media/nethdd smbfs uid=1000,gid=1000,auto,rw,nouser,guest 0 0loic@vaio:~$ sudo fdisk -l Password: Disque /dev/sda: 160.0 Go, 160041885696 octets 255 têtes, 63 secteurs/piste, 19457 cylindres Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sda1 1 9727 78132096 7 HPFS/NTFS /dev/sda2 * 9728 19080 75127972+ 83 Linux /dev/sda3 19081 19457 3028252+ 5 Extended /dev/sda5 19081 19457 3028221 82 Linux swap / Solaris Avis aux possesseurs de FE28H pour partager vos experiences, notamment sur BERYL qui apparemment ne fonctionne pas avec Une 6200 turbocache.. Le mot de la fin est que je regrette DAPPER. Dernière modification par antitrust (Le 12/11/2006, à 20:14) (K)Ubuntu User # 13751 Acer travelmate 8200 Kubuntu GUTSY Xgl + compiz-fusion Mon blog (k)ubuntu, CMS & CRM: http://www.especel.info Hors ligne Nizarus Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H j'ai le VGN-FE31H avec une ubuntu 6.10 et le wifi est nickel dès le départ. Ce n'est pas le cas pour les touches Fn, S1 et S2 de même que la webcam qui du même modèle que celle du FE28H (ID 0ac8:c002 Z-Star Microelectronics Corp.) @loic_e si tu a des nouvelles sur ce modèle n'hésite pas à nous informer Hors ligne antitrust Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H <<<<<<<UPDATE BERYL J'ai installé beryl + xgl ce weekend, malgré certains posts qui annoncent que ces paquets ne fonctionnent pas ou mal avec une NVIDIA turbocache, aucun souci à déplorer, le système reste rapide. J'ai suivi le tuto d'ubuntu.fr pour beryl/kde. Parcontre niveau acpi pas d'amélioration, tjs impossible de sélectionner la fréquence du cpu. (hibern fonctionne) quel qu'un a t'il réussi à configurer efficacement l'acpi sur un vaio duo? (K)Ubuntu User # 13751 Acer travelmate 8200 Kubuntu GUTSY Xgl + compiz-fusion Mon blog (k)ubuntu, CMS & CRM: http://www.especel.info Hors ligne antitrust Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H @ Nizarus merci bcp pour l'info, la webcam fonctionne enfin! La qualité est pas top, mais c est deja ça... On continue sur les vaios ok?? A++ (K)Ubuntu User # 13751 Acer travelmate 8200 Kubuntu GUTSY Xgl + compiz-fusion Mon blog (k)ubuntu, CMS & CRM: http://www.especel.info Hors ligne Lord Vamp Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Salut à tous.... Bon alors j'i moi aussi un Sony Vaio VGN FE28H et je suis sous la version bêta de Ubuntu 7.04 (Feisty Fawn). Pour ma part, pas de souci particulier à l'installation. Tout se passe bien, rien à signaler. Au démarrage tout est fonctionnel mis à part : - La webcam, non reconnue - Quelques petits soucis pour le drivers Nvidia, mais rien de bien méchant.... Bon par contre je vais de ce pas lire l'article concernant la webcam. Ah oui, apparement mon micro intégré n'est pas reconnu non plus. Ah oui, suite a une manip pour accéder à d'autres résolution (qui a fonctionné), mon clavier a perdu sa touche "ATL GR"...autant vous dire que c'est embêtant !!! Sinon tout le reste est impeccable. Voilà, si vous voulez plus d'info avant de vous lancez sur la bêta, n'hésitez pas ! Hors ligne Lord Vamp Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Salut, Euh non pour le moment je n'ai pas de souci avec les CD audio...:) Je les lis avec sound juicer...et j'ai rien eu à paramétrer Hors ligne Nizarus Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Dans mon cas j'ai beaucoup de soucis avec le lecteur de mon vaio et je viens de me rendre compte que c'est pas le problème du système d'exploitation !! le lecteur n'arrive pas à reconnaitre les CD de données (originaux), les DVD vierges, les DVD de données gravés et ce sous linux et windows !!! par contre pour les DVD originaux, les CD de données gravées et les CD vierges j'ai pas de soucis sous les deux OS !! et en fin pour les CD audio sous linux impossible de les lire mais sous windows c'est comme ça lui chante un fois ça passe et 10 fois ça passe pas !! Hors ligne Lord Vamp Re : Kubuntu Dapper sur Sony VAIO VGN-FE28H Bah essai l'exorcisme :D Sinon, bah.....je vois pas trop..là c'est un souci hardware...faut plancher un peu dessus ... et faire quelques tests ! Hors ligne
I have searched through threads on Stackoverflow and other sites using the Google machine and nothing gives me quite what I am looking for. I am new programming student using Python 3 so most of my stuff is pretty basic. I am writing a program that allows me to encrypt and decrypt a text file using the Caeser cipher. Taking a phrase from the user and applying a user given shift. This is what I am working with right now: Some of the code is just in there as a place holder until I get further along into my program. import string print ("1) Encrypt") print ("2) Decrypt") print ("3) Decrypt w/o Shift") Choice = input("Choice: ") if Choice == '1': message = input("Message: ") shift = int(input("Shift: ")) newmsg = '' for char in message: if char.isupper(): new = (ord(char)-ord('A')) + shift newmsg = chr(new+ord('A')) print (newmsg, end="") else: print(" ") elif Choice == '2': print ("2") elif Choice == '3': print ("3") When I input a test phrase, such as "THIS IS A TEST", it gives me the output, with the correct encryption, but it displays it like this: VJKUKUCVGUB This is with a "shift" of 2 If I add end = ' ' to my print statement, it outputs as: V J K UK UCV G U V If I add end = '' to my print statement, it outputs as: VJKUKUCVGUV I am looking for an output of: VJKU KU C VGUV I know this is something silly that I am overlooking. Any help would be appreciated. Thank you much.
galanga Re : Qarte arte.tv browser (ex Qarte+7) @Christophe: content de voir que cela a commencé à fonctionner... Pour le second cas qui fait une erreur, c'est parce qu'il manque un back slash sur le guillemets fermant de ...3789-visual-crop-medium.jpg ; essayez avec cela : items.append("<item>\n <title>Dominique A Vers les Lueurs</title>\n <link>http://liveweb.arte.tv/fr/video/Dominique_A_Vers_les_Lueurs_Lieu_Unique/</link>\n <pubDate>Mon, 01 Aug 2012 01:00:00 +0200</pubDate>\n <description>Description DominiqueA</description>\n <author>DominiqueA</author>\n <enclosure url=\"http://download.liveweb.arte.tv/o21/liveweb/media/event/3789/3789-visual-crop-medium.jpg\" type=\"image/jpeg\" length=\"0\" />\n <itunes:summary>Summary Dominique A</itunes:summary>\n <itunes:explicit>no</itunes:explicit>\n <itunes:author>DominiqueA</itunes:author>\n <itunes:image href=\"http://liveweb.arte.tv/images/podcast_logo.jpg\" />\n</item>") Je vous conseille vivement d'utiliser un éditeur avec coloration syntaxique pour modifier ces fichiers python, cela permet de voir tout de suite ce genre de petite coquille (j'ai utilisé "pluma" sous Linux Mint 13). Sinon j'ai fait une nouvelle version, plus pratique (pour moi...), en rajoutant une fonction qui permet ensuite de n'avoir plus que l'adresse de la page à indiquer pour introduire la page dans Qarte, ici dans la catégorie Classique (ATTENTION A l'INDENTATION EN PYTHON) : #JGN MANUAL ADDITION: if cat == 'Classique': self.JGNAddPersonalItem(videos[cat], "http://liveweb.arte.tv/fr/video/Berlin___Waldbuhne_2012/") self.JGNAddPersonalItem(videos[cat], "http://liveweb.arte.tv/fr/video/Dominique_A_Vers_les_Lueurs_Lieu_Unique/") Note: il faut changer la catégorie dans le "if" si la catégorie Classique ne vous va pas (voir dans le fichier data.py les variables xxxCATEGORIES). Sans le "if", la page devient disponible dans toutes les catégories de Arte Live Web (c'est plus lent...) Cette nouvelle version va parser le lien indiqué pour récupérer les bonnes informations de descriptions, de titre et d'image (pas la date). Le résultat dans Qarte est plus "zoli" et pratique. Voici le fichier modifié, il vous faut rechercher les commentaires commençant par "JGN" pour savoir où mettre ses propres adresses de pages Arte: parsers.py (modified) Cette version du fichier, en plus de la nouvelle manière d'ajouter des pages à soi comme indiqué ci-dessus, fait pour la partie Arte+7 un chargement de toutes les vidéos disponibles de l'émission Karambolage (il y en a une dizaines). Vous pouvez essayer avec d'autres émissions de Arte, si la page de "rattrapage plus loin que le +7" existe comme pour Karambolage. (aparté pour les autres lecteurs: Il faut mettre ce fichier à la place de /usr/share/qarte-1.3.0/parsers.py et pour avoir les droits d'accès en écriture sur ce fichier, il faut faire dans une console : sudo chmod ugo+rw /usr/share/qarte-1.3.0/parsers.py ) Bien sûr, ce qui précède est d'abord pour mon usage personnel, il n'est à utiliser que par ceux qui veulent bidouiller Dernière modification par galanga (Le 19/08/2012, à 08:29) Hors ligne Cristophe Re : Qarte arte.tv browser (ex Qarte+7) Merci Galanga pour la réponse ! Ça a fonctionné juste en ajoutant le backslash. Je testerai pluss tard la nouvelle "bidouille" qui à priori me semble pluss pratique. Si je n'en dis rien, c'est que ça aura fonctionné. Hors ligne homer01 Re : Qarte arte.tv browser (ex Qarte+7) Tout d'abord un grand merci à VinsS pour ce soft et ensuite à galanga pour la modif. J'apporte mon grain de sel, dans ta modif galanga j'ai ajouté l'extraction de la date, donc dans le module parser.py il faut modifier les imports: from email.utils import parsedate, formatdate et ensuite il faut rajouter dans la fonction JGNAddPersonalItem avant le premier try dateRE = re.compile('<div class="infos">.*<strong>Filmé le&nbsp;(([0-9]{2}/){2}[0-9]{4})</strong>', re.DOTALL) après la ligne desc = "No description" ajouter ceci try: s = (dateRE.search(page[0]).group(1)) logger.info(u"JGN: dateRE result: {0}".format(s)) date = formatdate(time.mktime(time.strptime(s.decode('utf-8', 'replace'),"%d/%m/%Y"))).decode('utf-8', 'ignore') except: date = "No date" et enfin modifié la ligne qui commence par items.append comme suit items.append("<item>\n <title>" + title +"</title>\n <link>" + url + "</link>\n <pubDate>" + date + "</pubDate>\n <description>" + desc + "</description>\n <author>Auteur</author>\n <enclosure url=\"http://download.liveweb.arte.tv/o21/liveweb/media/event/" + visualCropNumber + "/" + visualCropNumber + "-visual-crop-small.jpg\" type=\"image/jpeg\" length=\"0\" />\n <itunes:summary>Summary</itunes:summary>\n <itunes:explicit>no</itunes:explicit>\n <itunes:author>Author</itunes:author>\n <itunes:image href=\"http://liveweb.arte.tv/images/podcast_logo.jpg\" />\n</item>") Bon je suis pas super doué en python donc il y peut être moyen de faire mieux. Enfin un truc qui serait bien ce serait de pouvoir: 1- dans l'interface graphique avoir un bouton qui permet d'ajouter l'url directement à la liste de téléchargement ou alors 2- envoyer l'url en ligne de commande au lancement du soft. Je propose çà, parce que c'est principalement ma compagne qui souhaite récupérer des émissions arte. Et je ne la sens pas trop motiver pour aller trifouiller dans le code pour ajouter l'adresse qui l'interresse...... voila bonne journée Hors ligne lyr@d Re : Qarte arte.tv browser (ex Qarte+7) Amis de la Bricole, Bonsoir! D'abord bravo pour ce soft, jviens de tester ça sous Debian 6, et ça m'a tout l'air de marcher ! A quand le .msi??!! En vérité je suis tombé sur sur ce thread en faisant des petites recherches personnelles sans rapport direct avec le sujet. Je réside à l'étranger (Tunisie), et j'aimerai bien ne plus avoir ce message irritant qui me dit que les vidéos de la plate forme de ma chaine tv favorite ne peuvent pas être diffusées à l'étranger, pour quelque obscure raison de droits d'auteurs... Qu'a cela ne tienne, j'installe Squid sur une VM de mon dédié (resté au pays lui, yek yek yek;)), j'allume OpenVPN, je cfg Firefox, touça.... http://www.monip.org/ m'affiche bien mon IP française. Néanmoins, je me fais toujours jeter par arte+7. Vu que vous avez l'air de connaitre la plate forme, je voulais vous demander : A votre avis, il fait comment le truc pour savoir que je suis pas sur le territoire national alors que pour lui j'ai une IP française? - Hypothèse 1 : La page web s'affiche en http donc passe par le proxy, mais la lecture vidéo ouvre une autre connexion (un autre port???) et donc ne passe pas par le proxy ??? Faudrait alors que je trouve le port concerné et paramètre Squid en conséquence... - Hypothèse 2 : Arte +7 détecte que je passe par un proxy et me jette? C'est vrai que http://www.monip.org/ m'affiche IP : <IP_française> puis "Proxy detecté" puis ORG_IP : <IP locale VPN>, donc il peut savoir. Peut être peut on cfg squid pour être complètement transparent...... Hypothèse 1 / Hypothèse 2... Quelqu'un aurait une idée? Sinon, je peux toujours continuer a utiliser ce soft pour télécharger les vidz sur mon serveur et après les rapatrier à la maison... Mais c'est un peu lourd le bureau à distance a travers ma connexion, d'ou ma deuxième question / suggestion : Ce soft sous forme d' interface web??? C'est vachement plus léger, et l'InterOuaibe, c'est l'avenir! (y parait:)) Merci! Dernière modification par lyr@d (Le 26/08/2012, à 01:48) Hors ligne galanga Re : Qarte arte.tv browser (ex Qarte+7) @Cristophe: de rien ! @homer01: merci pour l'ajout de la gestion de la date. Pour ceux qui veulent en profiter, je l'ai intégré dans le fichier parsers.py (même lien que ci-dessus, pensez à recharger la page du lien pour avoir la dernière version). Pour l'option 1-, c'est justement cela que j'avais suggéré au début, avant de me mettre à bidouiller Pour l'option 2-, c'est une bonne idée, et plus facile à implémenter pour les bidouilleurs comme nous. @lyr@d: je ne saurais pas aider plus qu'en disant ceci : a/ avec des outils d'espionnage réseau (comme là ou là, ou tout simplement netstat), peut-être que vous arriverez à voir s'il y a une connexion "souterraine" de la lecture vidéo sur un autre port. b/ pour les proxys, je regarde sur ce site quand j'en ai besoin dans Firefox (je suis en Belgique, une fois) : http://www.xroxy.com/proxy-country-FR.htm (défaut : la liste change tout le temps, les proxys indiqués sont temporaires) et il faut faire gaffe effectivement au type de proxy... et pour la vitesse à la colonne latency. Dernière modification par galanga (Le 29/08/2012, à 19:52) Hors ligne Jarvis Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, un petit script fait à l'arrache pour télécharger les vidéos d'arte tv : #!/usr/bin/perl $arteurl = $ARGV[0]; $file_download = $ARGV[1]; $definition = "hd"; #hd or sd @wget=`wget -qO- $arteurl | grep "http://videos.arte.tv/fr/do_delegate/.*xml"`; @foo = map(/(http:\/\/.*xml)\"/,@wget); @wget2=`wget -qO- @foo | grep fr | grep xml`; @foo2 = map(/(http:\/\/.*xml)\"/,@wget2); @wget3=`wget -qO- @foo2 | grep "$definition" | grep rtmp`; @foo3 = map(/(rtmp:\/\/.*)\</,@wget3); system "rtmpdump -r @foo3 -o $file_download.flv"; ./download-arte.pl url_arte fichier output @ noireaude : si t'es fan de gedit, je te conseille de jeter un œil à Vim (un brin plus complet quand même). Hors ligne mardi_gras Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, @ VinsS, popololo et d'autres j'utilisais qarte+7 sur ubuntu 11.04. je viens de passer sur Voyager 12.04 (Xubuntu) et je ne parviens pas à utiliser qarte. est-ce que qarte fonctionne sous Xubuntu 12.04? il semblerait qu'il y ait un problème avec Xubuntu. quand je tape la commande qarte dans un terminal, j'obtiens : Erreur de segmentation (core dumped) apparemment, d'après le forum, je ne suis pas le seul mais je ne parviens pas à suivre et décrypter... si vous pouvez me donner un coupe de pouce... merci! je suis accroc à ce programme et j'espère que ça va pouvoir s'arranger! Hors ligne lyr@d Re : Qarte arte.tv browser (ex Qarte+7) Merci pour les conseil, et ce script m'a l'air sympathique, je verrai si je peux faire une petite interface web... Donc j'ai trouvé le problème, hypothèse 2, le proxy est détecté par ARTE qui bloque en conséquence. Donc pour la postérité, pour visionner les vidéos arte depuis l'étranger en passant par un serveur perso (loué chez un hébergeur, ou chez le pote resté au pays qui a la fibro) avec squid comme proxy, il faut modifier le paramètre forwarded_for de on (par défaut) à delete. Avec ça, squid n'écrit pas votre adresse IP "locale" (en aval du proxy) dans les requetes http, et arte+7 ne détecte pas l'entourloupe. En espérant que ça soit utile à quelqu'un! Hors ligne mardi_gras Re : Qarte arte.tv browser (ex Qarte+7) [résolu] après avoir relu à tête reposée les posts du forum, je viens de voir que le problème était lié au thème utilisé par voyager (à savoir "ambiance voyager dark"). en utilisant un autre thème, le problème est réglé. pourquoi? comment? j'en sais rien mais ça marche. Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, On n'a pas chômé durant les vacances à ce que je vois. De prime abord, je dirais qu'il n'y a pas de difficulté à ajouter une possibilité d'entrer un lien de page et de laisser le programme se débrouiller, mais où se situent ces pages par rapport au site http://liveweb.arte.tv/fr ? Parce que si ces pages proviennent des sous-pages "Tous les spectacles", "Tous les évènements", "La Blogothèque", etc., je pensais déjà rajouter ces catégories qui représentent toutes ensemble une centaine de concerts. C'est bien la rentrée donc. Dernière modification par VinsS (Le 06/09/2012, à 08:25) Hors ligne zealand84 Re : Qarte arte.tv browser (ex Qarte+7) Bonjour VinsS et un grand merci pour ce magnifique programme. J'ai été confronté au problème de thème avec pour effet le message d'erreur " Erreur de segmentation (core dumped)" au quel j'ai pu faire face en revenant à un thème installé par défaut sous précise (Ambiance). Ceci dit, vous serait-il possible d'envisager de corriger, un jour ce bug, afin de pouvoir utiliser Qarte avec un thème différent. Je suis autant accro à Qarte qu'à mon thème préféré (Cupertino SL) Encore une fois Bravo et merci pour la qualité de l'indispensable Qarte... Cordialement. Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Salut, @ zealand84, ce n'est pas un problème qui provient de Qarte. L'application est censée fonctionner avec n'importe quel thème, la personnalisation de l'interface est faite au moyen de feuilles de style après construction de celle-ci. Il faut lancer Qarte en console avec l'option -d pour savoir ce qui se passe. $ qarte -d Le message d'erreur 'Erreur de segmentation' n'est pas la cause du plantage, ce message est émit par le serveur (Linux himself) suite au plantage de l'appli, les messages d'erreurs de Python et de Qt ne sont pas traduits. Dernière modification par VinsS (Le 08/09/2012, à 13:35) Hors ligne zealand84 Re : Qarte arte.tv browser (ex Qarte+7) Merci VinsS pour ta réponse. Après la mise à jour proposée par le gestionnaire de mise à jour tout fonctionne parfaitement, je ne suis plus en mesure de te donner les infos relative à un "qarte -d" et j'en suis désolé. Je ne manquerais pas de te signaler ce que je pourrais recueillir comme infos dans la suite de l'utilisation de Qarte. Merci à toi. Hors ligne pacbits Re : Qarte arte.tv browser (ex Qarte+7) Salut, Tout d'abord merci pour le développement de ce script/application. Voilà voilà j'ai un gros problème: je vous explique ; J'ai quitté Ubuntu pour Xubuntu, ensuite j'ai découvert Voyager qui est installé depuis hier. Hélas Qarte ne fonctionne pas sur Voyager. Je note que Qarte fonctionnait parfaitement sur Ubuntu et Xubuntu. Lorsque je clique sur Qarte via menu/multimédia : aucun résultat, aucun message d'erreur. Si je tente de l'exécuter via le terminal : j'ai l'erreur "Erreur de segmentation (core dumped)" Et en dernier recours j'essaye qarte -d └─> qarte Erreur de segmentation (core dumped) └─> qarte -d 01:56:31: INFO - qarte Qarte-1.3.0 01:56:31: INFO - qarte Python 2.7.3 on Linux-3.2.0-30-generic-pae-i686-with-Ubuntu-12.04-precise 01:56:31: INFO - qarte File system encoding: UTF-8 01:56:31: INFO - qarte System encoding: utf-8 01:56:31: INFO - qarte Locale encoding: ('fr_FR', 'UTF-8') Erreur de segmentation (core dumped) Est-ce que vous pouvez m'aider à résoudre ce problème. Merci d'avance. Dernière modification par pacbits (Le 11/09/2012, à 02:05) Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Dernières nouvelles. J'ai posté [1] une version 1.3.1 qui ne nécessite plus FLVStreamer. C'est donc RTMPdump qui sert aussi pour arte+7. Ceci afin de répondre aux distributions qui considèrent ces deux librairies en conflit. Mageia par exemple. C'est une archive tar.gz, un .deb suivra. Le site arte+7 a opéré ces derniers jours des changements importants au niveau de leur plate-forme. Les mises en ligne d'émission et la réactivité du site s'en sont légèrement ressentis. Par contre, ce qui est plus important comme changement, les trois premiers épisodes des Tudor sont mis en ligne sous un format nécessitant M.$. Silverlight comme visionneuse. Qarte n'est pas du tout conçu pour retrouver les liens des streams destinés à cette visionneuse, hélas. J'ignore s'il s'agit d'un cas particulier ou si cela deviendra la norme. Pour ceux que cela intéressent, Moonlight [2] peut remplacer Silverlight dans la plupart des navigateurs. Hors ligne david96 Re : Qarte arte.tv browser (ex Qarte+7) Mauvais signe tout ça En ligne david96 Re : Qarte arte.tv browser (ex Qarte+7) Espérons le. En ligne finchou Re : Qarte arte.tv browser (ex Qarte+7) david96 a écrit : Mauvais signe tout ça Pas sur en fait, cela semble limité à la série Les Tudor. J'ai aussi constaté ce PB avec les Tudor , j'ai d'abord pensé à un verrouillage type DRM, est-il possible de contourner le PB en utilisant Quarte-1.10 avec Moonlight sur Firefox?? Cordialement Compaq presario 17XL274 CPU Pentium III 600 Mhz HDD 12Gb RAM 512 Mb Linux Mint 13 maya sur base ubuntu 12.04 precise pangolin Hors ligne catalona Re : Qarte arte.tv browser (ex Qarte+7) bonjour a tous je viens d'installer QARTE-1-2 . Avec arte liveWeb je peu enregistrer sans probleme mais avec arte+7 je ne peu que enregistrer "ARTE journal" pour le reste des videos on signal "ERREUR telechargement interrompu" si vous avez la solution merci d'avance Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Nouvelle version 1.4.0 Au rayon des nouveautés: Ajout de 'Tracks' et 'La Blogothèque' dans la page Arte Live Web La catégorie Jazz à été complétée du partenaire Jazz Live. La catégorie Musique du Monde à été complétée du partenaire Mondomix. Ajout d'une page pour les autres partenaires d'Arte Live Web, du moins une partie. Ceci représente plus ou moins 500 concerts. D'autres partenaires peuvent être ajoutés sans modification du code, il suffit de poster le nom de ce partenaire sur ce forum. Voir la liste [1] Ajout d'une boîte de dialogue pour entrer directement un lien de vidéo. Dans le menu 'Extra' cliquez 'Custom searching' Entrez l'url de la vidéo et cliquez 'O.K.' Si le lien est valide le nom de la vidéo s'affichera, cliquez 'Add' et elle sera ajoutée au panier de téléchargement de la page 'Extra' Comment trouver un lien de vidéo ? Exemple: je suis sur la page Rock en Seine <http://liveweb.arte.tv/fr/part/Rock_en_Seine/> et j'aimerai télécharger 'Eagles Of Death Metal', je clique droit sur le fond de page et je choisis 'Code source de la page'. Le code s'affiche dans une nouvelle fenêtre. Au début de cette page je trouve le lien de la feuille rss <link rel="alternate" type="application/atom+xml" title="Les dernières vidéos d'ARTE Live Web :: Rock en Seine" href="http://download.liveweb.arte.tv/o21/liveweb/rss/partner-640-fr.rss" /> Je télécharge cette page dans une console avec wget wget http://download.liveweb.arte.tv/o21/liveweb/rss/partner-640-fr.rss J'ouvre ce fichier dans mon bloc-notes et là je cherche le bloc de lignes qui contient le concert qui m'intéresse. Dans mon exemple, ceci: ... <item> <title>Rock en Seine : Eagles Of Death Metal</title> <link>http://liveweb.arte.tv/fr/video/Rock_en_Seine_Eagles_Of_Death_Metal/</link> <pubDate>Sat, 25 Aug 2012 21:00:00 +0200</pubDate> <description>&lt;p&gt;&lt;a href="http://www.eaglesofdeathmetal.com/"&gt;Eagles Of Death Metal&lt;/a&gt; ne joue ni des chansons des &lt;a href="http://www.eaglesband.com/"&gt;Eagles&lt;/a&gt;, ni du death metal. Le nom du groupe semble issu d&amp;rsquo;une conversation avin&amp;eacute;e entre Josh Homme et un quidam dont l&amp;rsquo;histoire n&amp;rsquo;a pas daign&amp;eacute; retenir le nom. Si le groupe est apparu pour la premi&amp;egrave;re fois sur l&amp;rsquo;une des compilations &lt;em&gt;Desert Session&lt;/em&gt; de Josh Homme, et si on le retrouve au sein du groupe ainsi que, ..... Il suffit maintenant de rentrer le contenu des balises <link> </link> soit http://liveweb.arte.tv/fr/video/Rock_en … ath_Metal/ dans la boîte de dialogue du menu 'Extra' et de cliquer O.K. J'ai mis un tar.gz et un all.deb sur mon site [2] et le ppa est en cours. [1] http://liveweb.arte.tv/searchPartner.do … ayElements [2] http://www.oqapy.eu (Téléchargements) Dernière modification par VinsS (Le 24/09/2012, à 21:34) Hors ligne cracolinux Re : Qarte arte.tv browser (ex Qarte+7) VinsS , je te remercie au nom de ma femme car cette feignante ne veut pas s'inscrire sur le forum. Elle se sert de Qarte sans arrêt et je suis obligé de faire le ménage de temps en temps car le disque dur s'en prend plein les dents C'est vraiment très beau et ça fonctionne super bien ! bravo ! .... PS : moi zaussi je me sers de qarte... Pixup : postez vos images vite et bien « Ne devenez jamais pessimiste. Un pessimiste a plus souvent raison qu'un optimiste, mais l'optimiste s'amuse plus — et aucun des deux ne peut arrêter la marche du monde. » R.Heinlein Hors ligne
I'm designing a model for a posting system where an entry contains an image with or without a comment. An user can reply to it as either a comment or as an image entry as well. As there can be more properties for ImageEntry, I came up with this design with Polymodel. Not sure if this is the best way to do this. Storage-wise, is CommentEntry less than ImageEntry? Any suggestions would be great. class Entry(polymodel.PolyModel): comment = db.TextProperty() reply_to = db.SelfReferenceProperty() # reference to the entry created_at = properties.DateTimeProperty(auto_now_add=True) updated_at = properties.DateTimeProperty(auto_now=True) class CommentEntry(Entry): created_by = db.ReferenceProperty(User, collection_name='comment_entries') class ImageEntry(Entry): created_by = db.ReferenceProperty(User, collection_name='image_entries') image_url = db.LinkProperty(indexed=False) slug = db.StringProperty(indexed=False)
I am trying to use a textarea form entry which I have some javascript code to count and limit the character count, whose max_length and size are dynamic (ie these attributes are alterable after model creation). In order to include this functionality in the django form textarea widget I suppose I would have to create a custom widget, although im not sure how to tie in the javascript code in the template really. For changing the textarea size, i suppose I would pass a variable into the form creation from the view to generate the textarea widget instance. Otherwise for now I am simply creating the inputs in the template in html/js and then submitting the POST data to the django view, and retrieving it using getitem, then saving the data directly to my models. Which works of course, but is not very django'y, and perhaps is somehow vulnerable without the built-in django validation and clean data functions. So two questions I guess: (a) If I create a custom django form widget, how do I apply my javascript function to the textarea fields in the template (includes "onkeypress=jstextcounter...") and (b) If I continue just retrieving the post data in the view without a django form, is there a vulnerability and what should I do to ensure the data is well-validated? (page already requires user login, not a public comment box) Or maybe someone has created such a custom form widget before and knows a good snippet somewhere? Cheers... EDITSo thanks to MovieYoda's help, I got this working and some reading over dynamic forms in django. And with a %d substitute I can dynamically change the maxChars attribute for my js function. In forms.py I have: text=forms.CharField(max_length = 1000, widget=forms.widgets.Textarea()) def __init__(self, *args, **kwargs): size = kwargs.pop('size') maxChars = kwargs.pop('maxChars') super(MyForm, self).__init__(*args, **kwargs) self.fields['text'].widget.attrs['onkeypress'] = 'return textCounter(this, this.form.counter, %d);' % maxChars self.fields['text'].widget.attrs['rows'] = size self.fields['text'].widget.attrs['cols'] = '40' Where the js function 'textCounter' in the template is limiting the number of characters, using the maxChars variable. <script type="text/javascript"> function textCounter( field, countfield, maxLimit) { if ( field.value.length > maxLimit ) { field.value = field.value.substring( 0, maxLimit ); return false; } else { countfield.value = maxLimit - field.value.length; } } </script> And in the view create the form with the kwargs inputs: FormInstance = MyForm(size=1, maxChars=5)
I am very new to Python. I am using the transpose operator in the numpy package: >>> import numpy as np >>> X = np.array([[1,2,3],[4,5,6]]) >>> np.T(X) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> np.T(X) AttributeError: 'module' object has no attribute 'T' Why is it that this is an error, yet X.T works? Furthermore, X.np.T fails. On the other hand, np.fft.fft(X) succeeds, but X.fft.fft fails. Thanks all!
So, I have two models and one holds a foreign key reference to the other: Model1: blah = models.ForeignKey(Model2) I also have the following admins for Model2: model2admin(models.ModelAdmin) inline = [model1inline] model1admin(admin.TabularLine): def queryset(self, request): qs = super(model2admin, self).queryset(request) return qs.filter(...) I'm trying to filter the queryset in the model1admin for instances of model2 (It makes sense to me because when you click on one of the items on the admin page, it would be a single model instance). So how would I do that? In the documentation, I only see some functions in which you can have obj as an argument but I think those are only "callable" for display.
Sets or retrieves the text in the grid cells. The text is assigned to the individual cell or to the array of cells depending on the type and the number of arguments in the setCellText() method (see the examples below). Does not encode the html controls characters (<, >, ", &) - the text containing correct html markup will be displayed as html. This is a faster method than using cell data property because the text is inserted into the grid cells as is without any transformations. However using the cell data property together with the cell format converter allows processing the data before display, for example, encoding the text strings or applying specific date or number formats. When the cell content is assigned through the cell text property - the cell format converter can be used to provide reverse transformation (textToValue) for the correct sorting of the grid rows. During the editing the cell text property is continuously updated (on each keystroke, copy/paste or drag-n-drop event). Each text change triggers onCellTextChanging and onCellTextChanged events which can be used to check or modify the entered text. var value = obj.getCellText(); obj.setCellText(value); obj.onCellTextChanging = function(value){...}; obj.onCellTextChanged = function(value){...}; obj.onCellTextError = function(value){...}; 2-d Array var myCells = [ ["Cell <i>text</i>", "123", "5/18/2004"], ["<a href='#'>More...</a>", "456", "1/12/2006"] ] obj.setCellText(myCells); // assign cells content 1-d array (per row) obj.setCellText(["Cell <i>text</i>", "123", "5/18/2004"], 0); // row-0 obj.setCellText(["<a href='#'>More...</a>", "456", "1/12/2006"], 1); // row-1 Function obj.setCellText(function(col, row){return myCells[row][col]}); Single cell obj.setCellText("Item <1>", 0, 0); // col-0, row-0 onCellTextChanging event can be used to restrict the cell text (filter characters) during editing - obj.onCellTextChanging = function(text, column, row){ if (text.match(/[^0-9.+-]/)){ return "error"; // prevent non-digits } }
freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Ok donc bien installé. Peux tu lancer vlc en debug avec : vlc -vvv et essayer de lire ton DVD, tu nous colles ensuite le resultat de ton terminal avec http://paste.ubuntu.com/ Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) en debug ça veut direque je rajoute -d ? donc je tape : vlc -vvv -d "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Non tu lance ce que j'ai écris : vlc -vvv et essayer de lire ton DVD, tu nous colles ensuite le resultat de ton terminal avec http://paste.ubuntu.com/ Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) ok dvd toujours illisible "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) J'ai demander que tu nous donnes ce qui s'affiche dans la console ! Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) désolé je l'ai fait par le lien tastebin mais ai dû faire une erreur ça donne donc ça et à la fin la fenêtre de VLC s'ouvre VLC media player 2.0.3 Twoflower (revision 2.0.2-93-g77aa89e) [0x8dfe908] main libvlc debug: VLC media player - 2.0.3 Twoflower [0x8dfe908] main libvlc debug: Copyright © 1996-2012 VLC authors and VideoLAN [0x8dfe908] main libvlc debug: revision 2.0.2-93-g77aa89e [0x8dfe908] main libvlc debug: configured with ./configure '--enable-static' '--build=i686-linux-gnu' 'CFLAGS=-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security' 'CPPFLAGS=-D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security' 'LDFLAGS=-Wl,-Bsymbolic-functions -Wl,-z,relro' '--config-cache' '--disable-maintainer-mode' '--disable-silent-rules' '--disable-update-check' '--enable-fast-install' '--prefix=/usr' '--docdir=/usr/share/doc/vlc-nox' '--sysconfdir=/etc' '--with-binary-version=0ubuntu0.12.04.1' '--enable-a52' '--enable-aa' '--enable-bluray' '--enable-bonjour' '--enable-caca' '--enable-dbus' '--enable-dca' '--enable-dirac' '--enable-directfb' '--enable-dvbpsi' '--enable-dvdnav' '--enable-faad' '--enable-flac' '--enable-fluidsynth' '--enable-freetype' '--enable-fribidi' '--enable-gnutls' '--enable-jack' '--enable-kate' '--enable-libass' '--enable-libmpeg2' '--enable-libproxy' '--enable-libxml2' '--enable-lirc' '--enable-live555' '--enable-mad' '--enable-mkv' '--enable-mod' '--enable-mpc' '--enable-mtp' '--enable-mux_ogg' '--enable-ncurses' '--enable-notify' '--enable-ogg' '--enable-oss' '--enable-pulse' '--enable-qt4' '--enable-realrtsp' '--enable-samplerate' '--enable-schroedinger' '--enable-sdl' '--enable-shout' '--enable-skins2' '--enable-smb' '--enable-speex' '--enable-svg' '--enable-taglib' '--enable-theora' '--enable-twolame' '--enable-upnp' '--enable-vcd' '--enable-vcdx' '--enable-vorbis' '--enable-x264' '--enable-zvbi' '--with-kde-solid=/usr/share/kde4/apps/solid/actions/' '--disable-dxva2' '--disable-gnomevfs' '--disable-goom' '--disable-portaudio' '--disable-projectm' '--disable-sqlite' '--disable-telx' '--enable-alsa' '--enable-atmo' '--enable-dc1394' '--enable-dv' '--enable-fbosd' '--enable-libva' '--enable-linsys' '--enable-omxil' '--enable-pvr' '--enable-udev' '--enable-v4l2' '--enable-crystalhd' '--enable-mmx' '--enable-sse' '--disable-neon' '--disable-altivec' 'build_alias=i686-linux-gnu' [0x8dfe908] main libvlc debug: searching plug-in modules [0x8dfe908] main libvlc debug: loading plugins cache file /usr/lib/vlc/plugins/plugins.dat [0x8dfe908] main libvlc debug: recursively browsing `/usr/lib/vlc/plugins' [0x8dfe908] main libvlc debug: saving plugins cache /usr/lib/vlc/plugins/plugins.dat [0x8dfe908] main libvlc debug: plug-ins loaded: 420 modules [0x8dfe908] main libvlc debug: opening config file (/home/laura/.config/vlc/vlcrc) [0x8dfe908] main libvlc debug: translation test: code is "fr" laura@flocky:~$ vlc -vvv VLC media player 2.0.3 Twoflower (revision 2.0.2-93-g77aa89e) [0x97f4908] main libvlc debug: VLC media player - 2.0.3 Twoflower [0x97f4908] main libvlc debug: Copyright © 1996-2012 VLC authors and VideoLAN [0x97f4908] main libvlc debug: revision 2.0.2-93-g77aa89e [0x97f4908] main libvlc debug: configured with ./configure '--enable-static' '--build=i686-linux-gnu' 'CFLAGS=-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security' 'CPPFLAGS=-D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security' 'LDFLAGS=-Wl,-Bsymbolic-functions -Wl,-z,relro' '--config-cache' '--disable-maintainer-mode' '--disable-silent-rules' '--disable-update-check' '--enable-fast-install' '--prefix=/usr' '--docdir=/usr/share/doc/vlc-nox' '--sysconfdir=/etc' '--with-binary-version=0ubuntu0.12.04.1' '--enable-a52' '--enable-aa' '--enable-bluray' '--enable-bonjour' '--enable-caca' '--enable-dbus' '--enable-dca' '--enable-dirac' '--enable-directfb' '--enable-dvbpsi' '--enable-dvdnav' '--enable-faad' '--enable-flac' '--enable-fluidsynth' '--enable-freetype' '--enable-fribidi' '--enable-gnutls' '--enable-jack' '--enable-kate' '--enable-libass' '--enable-libmpeg2' '--enable-libproxy' '--enable-libxml2' '--enable-lirc' '--enable-live555' '--enable-mad' '--enable-mkv' '--enable-mod' '--enable-mpc' '--enable-mtp' '--enable-mux_ogg' '--enable-ncurses' '--enable-notify' '--enable-ogg' '--enable-oss' '--enable-pulse' '--enable-qt4' '--enable-realrtsp' '--enable-samplerate' '--enable-schroedinger' '--enable-sdl' '--enable-shout' '--enable-skins2' '--enable-smb' '--enable-speex' '--enable-svg' '--enable-taglib' '--enable-theora' '--enable-twolame' '--enable-upnp' '--enable-vcd' '--enable-vcdx' '--enable-vorbis' '--enable-x264' '--enable-zvbi' '--with-kde-solid=/usr/share/kde4/apps/solid/actions/' '--disable-dxva2' '--disable-gnomevfs' '--disable-goom' '--disable-portaudio' '--disable-projectm' '--disable-sqlite' '--disable-telx' '--enable-alsa' '--enable-atmo' '--enable-dc1394' '--enable-dv' '--enable-fbosd' '--enable-libva' '--enable-linsys' '--enable-omxil' '--enable-pvr' '--enable-udev' '--enable-v4l2' '--enable-crystalhd' '--enable-mmx' '--enable-sse' '--disable-neon' '--disable-altivec' 'build_alias=i686-linux-gnu' [0x97f4908] main libvlc debug: searching plug-in modules [0x97f4908] main libvlc debug: loading plugins cache file /usr/lib/vlc/plugins/plugins.dat [0x97f4908] main libvlc debug: recursively browsing `/usr/lib/vlc/plugins' [0x97f4908] main libvlc debug: saving plugins cache /usr/lib/vlc/plugins/plugins.dat [0x97f4908] main libvlc debug: plug-ins loaded: 420 modules [0x97f4908] main libvlc debug: opening config file (/home/laura/.config/vlc/vlcrc) [0x97f4908] main libvlc debug: translation test: code is "fr" [0x97f4908] main libvlc debug: CPU has capabilities MMX MMXEXT SSE SSE2 SSE3 SSSE3 SSE4.1 SSE4.2 FPU [0x97f4908] main libvlc debug: looking for memcpy module: 4 candidates [0x97f4908] main libvlc debug: using memcpy module "memcpymmxext" [0x997e928] main input debug: Creating an input for 'Bibliothèque' [0x997e928] main input debug: Input is a meta file: disabling unneeded options [0x997e928] main input debug: using timeshift granularity of 50 MiB, in path '/tmp' [0x997e928] main input debug: `file/xspf-open:///home/laura/.local/share/vlc/ml.xspf' gives access `file' demux `xspf-open' path `/home/laura/.local/share/vlc/ml.xspf' [0x997e928] main input debug: creating demux: access='file' demux='xspf-open' location='/home/laura/.local/share/vlc/ml.xspf' file='/home/laura/.local/share/vlc/ml.xspf' [0x9815d40] main demux debug: looking for access_demux module: 3 candidates [0x9815d40] main demux debug: no access_demux module matching "file" could be loaded [0x9815d40] main demux debug: TIMER module_need() : 1.739 ms - Total 1.739 ms / 1 intvls (Avg 1.739 ms) [0x997e928] main input debug: creating access 'file' location='/home/laura/.local/share/vlc/ml.xspf', path='/home/laura/.local/share/vlc/ml.xspf' [0x9806010] main access debug: looking for access module: 2 candidates [0x9806010] filesystem access debug: opening file `/home/laura/.local/share/vlc/ml.xspf' [0x9806010] main access debug: using access module "filesystem" [0x9806010] main access debug: TIMER module_need() : 0.624 ms - Total 0.624 ms / 1 intvls (Avg 0.624 ms) [0x98060e8] main stream debug: Using stream method for AStream* [0x98060e8] main stream debug: starting pre-buffering [0x98060e8] main stream debug: received first data after 0 ms [0x98060e8] main stream debug: pre-buffering done 296 bytes in 0s - 3525 KiB/s [0x997de28] main stream debug: looking for stream_filter module: 7 candidates [0x997de28] main stream debug: no stream_filter module matching "any" could be loaded [0x997de28] main stream debug: TIMER module_need() : 1.851 ms - Total 1.851 ms / 1 intvls (Avg 1.851 ms) [0x997de28] main stream debug: looking for stream_filter module: 1 candidate [0x997de28] main stream debug: using stream_filter module "stream_filter_record" [0x997de28] main stream debug: TIMER module_need() : 0.393 ms - Total 0.393 ms / 1 intvls (Avg 0.393 ms) [0x997e928] main input debug: creating demux: access='file' demux='xspf-open' location='/home/laura/.local/share/vlc/ml.xspf' file='/home/laura/.local/share/vlc/ml.xspf' [0x9977c88] main demux debug: looking for demux module: 1 candidate [0x9977c88] playlist demux debug: using XSPF playlist reader [0x9977c88] main demux debug: using demux module "playlist" [0x9977c88] main demux debug: TIMER module_need() : 0.617 ms - Total 0.617 ms / 1 intvls (Avg 0.617 ms) [0x9976d60] main demux meta debug: looking for meta reader module: 2 candidates [0x9976d60] lua demux meta debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/meta/reader [0x9976d60] lua demux meta debug: Trying Lua scripts in /usr/lib/vlc/lua/meta/reader [0x9976d60] lua demux meta debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/reader/filename.luac [0x9976d60] lua demux meta debug: Trying Lua scripts in /usr/share/vlc/lua/meta/reader [0x9976d60] main demux meta debug: no meta reader module matching "any" could be loaded [0x9976d60] main demux meta debug: TIMER module_need() : 4.147 ms - Total 4.147 ms / 1 intvls (Avg 4.147 ms) [0x997e928] main input debug: `file/xspf-open:///home/laura/.local/share/vlc/ml.xspf' successfully opened [0x988d1e8] main xml reader debug: looking for xml reader module: 1 candidate [0x988d1e8] main xml reader debug: using xml reader module "xml" [0x988d1e8] main xml reader debug: TIMER module_need() : 1.180 ms - Total 1.180 ms / 1 intvls (Avg 1.180 ms) [0x9977c88] playlist demux debug: parsed 0 tracks successfully [0x997e928] main input debug: EOF reached [0x9977c88] main demux debug: removing module "playlist" [0x997de28] main stream debug: removing module "stream_filter_record" [0x9806010] main access debug: removing module "filesystem" [0x997e928] main input debug: TIMER input launching for 'Bibliothèque' : 11.425 ms - Total 11.425 ms / 1 intvls (Avg 11.425 ms) [0x9977c88] main interface debug: looking for interface module: 1 candidate [0x9977c88] main interface debug: using interface module "hotkeys" [0x9977c88] main interface debug: TIMER module_need() : 0.497 ms - Total 0.497 ms / 1 intvls (Avg 0.497 ms) [0x997ecf8] main interface debug: looking for interface module: 1 candidate [0x9805bc0] main playlist debug: playlist threads correctly activated [0x997ecf8] main interface debug: using interface module "inhibit" [0x997ecf8] main interface debug: TIMER module_need() : 5.034 ms - Total 5.034 ms / 1 intvls (Avg 5.034 ms) [0x98085b8] main interface debug: looking for interface module: 1 candidate [0x9805bc0] main playlist debug: rebuilding array of current - root Liste de lecture [0x9805bc0] main playlist debug: rebuild done - 0 items, index -1 [0x98085b8] main interface debug: using interface module "globalhotkeys" [0x98085b8] main interface debug: TIMER module_need() : 2.021 ms - Total 2.021 ms / 1 intvls (Avg 2.021 ms) [0x97f4908] main libvlc: Lancement de vlc avec l'interface par défaut. Utilisez « cvlc » pour démarrer VLC sans interface. [0x9808338] main interface debug: looking for interface module: 6 candidates [0xb0b9ab68] main generic debug: looking for extension module: 1 candidate [0xb0b9ab68] lua generic debug: Opening Lua Extension module [0xb0b9ab68] lua generic debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/extensions [0xb0b9ab68] lua generic debug: Trying Lua scripts in /usr/lib/vlc/lua/extensions [0xb0b9ab68] lua generic debug: Trying Lua scripts in /usr/share/vlc/lua/extensions [0xb0b9ab68] main generic debug: using extension module "lua" [0xb0b9ab68] main generic debug: TIMER module_need() : 0.275 ms - Total 0.275 ms / 1 intvls (Avg 0.275 ms) [0x9808338] main interface debug: using interface module "qt4" [0x9808338] main interface debug: TIMER module_need() : 824.880 ms - Total 824.880 ms / 1 intvls (Avg 824.880 ms) [0x97f4908] main libvlc debug: exiting [0x97f4908] main libvlc debug: deactivating the playlist [0x9805bc0] main playlist debug: deactivating the playlist [0x988b418] main playlist export debug: saving Bibliothèque to file /home/laura/.local/share/vlc/ml.xspf [0x988b418] main playlist export debug: looking for playlist export module: 1 candidate [0x988b418] main playlist export debug: using playlist export module "export" [0x988b418] main playlist export debug: TIMER module_need() : 0.890 ms - Total 0.890 ms / 1 intvls (Avg 0.890 ms) [0x988b418] main playlist export debug: removing module "export" [0x9805bc0] main playlist debug: playlist correctly deactivated [0x97f4908] main libvlc debug: removing all services discovery tasks [0x97f4908] main libvlc debug: removing all interfaces [0x9808338] main interface debug: removing module "qt4" [0x9808338] qt4 interface debug: requesting exit... [0x9808338] qt4 interface debug: waiting for UI thread... [0x9808338] qt4 interface debug: QApp exec() finished [0x9808338] qt4 interface debug: Video is not needed anymore [0x9808338] qt4 interface debug: Killing extension dialog provider [0x9808338] qt4 interface debug: ExtensionsDialogProvider is quitting... [0xb0b9ab68] main generic debug: removing module "lua" [0xb0b9ab68] lua generic debug: Deactivating all loaded extensions [0xb0b9ab68] lua generic debug: All extensions are now deactivated [0x98085b8] main interface debug: removing module "globalhotkeys" [0x997ecf8] main interface debug: removing module "inhibit" [0x9977c88] main interface debug: removing module "hotkeys" [0x9805bc0] main playlist debug: destroying [0x97f4908] main libvlc debug: TIMER ML Load : Total 13.641 ms / 1 intvls (Avg 13.641 ms) [0x97f4908] main libvlc debug: TIMER Items array build : Total 0.126 ms / 1 intvls (Avg 0.126 ms) [0x97f4908] main libvlc debug: TIMER ML Dump : Total 1.493 ms / 1 intvls (Avg 1.493 ms) [0x97f4908] main libvlc debug: removing stats [0x97f4908] main libvlc debug: removing module "memcpymmxext" [0x97f4908] main libvlc debug: opening config file (/home/laura/.config/vlc/vlcrc) "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Tu es sur que tu as essayé de lire un DVD ? ça n'apparait pas dans ton log. En dernier recours tu as toujours ce logiciel proprietaire payant : Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) oui ai bien essayé le disque patine et ne démarre pas.... "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) ah oui évidemment je m'y suis mal pris voilà le résultat que tu attends je pense VLC media player 2.0.3 Twoflower (revision 2.0.2-93-g77aa89e) [0x8290908] main libvlc debug: VLC media player - 2.0.3 Twoflower [0x8290908] main libvlc debug: Copyright © 1996-2012 VLC authors and VideoLAN [0x8290908] main libvlc debug: revision 2.0.2-93-g77aa89e [0x8290908] main libvlc debug: configured with ./configure '--enable-static' '--build=i686-linux-gnu' 'CFLAGS=-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security' 'CPPFLAGS=-D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security' 'LDFLAGS=-Wl,-Bsymbolic-functions -Wl,-z,relro' '--config-cache' '--disable-maintainer-mode' '--disable-silent-rules' '--disable-update-check' '--enable-fast-install' '--prefix=/usr' '--docdir=/usr/share/doc/vlc-nox' '--sysconfdir=/etc' '--with-binary-version=0ubuntu0.12.04.1' '--enable-a52' '--enable-aa' '--enable-bluray' '--enable-bonjour' '--enable-caca' '--enable-dbus' '--enable-dca' '--enable-dirac' '--enable-directfb' '--enable-dvbpsi' '--enable-dvdnav' '--enable-faad' '--enable-flac' '--enable-fluidsynth' '--enable-freetype' '--enable-fribidi' '--enable-gnutls' '--enable-jack' '--enable-kate' '--enable-libass' '--enable-libmpeg2' '--enable-libproxy' '--enable-libxml2' '--enable-lirc' '--enable-live555' '--enable-mad' '--enable-mkv' '--enable-mod' '--enable-mpc' '--enable-mtp' '--enable-mux_ogg' '--enable-ncurses' '--enable-notify' '--enable-ogg' '--enable-oss' '--enable-pulse' '--enable-qt4' '--enable-realrtsp' '--enable-samplerate' '--enable-schroedinger' '--enable-sdl' '--enable-shout' '--enable-skins2' '--enable-smb' '--enable-speex' '--enable-svg' '--enable-taglib' '--enable-theora' '--enable-twolame' '--enable-upnp' '--enable-vcd' '--enable-vcdx' '--enable-vorbis' '--enable-x264' '--enable-zvbi' '--with-kde-solid=/usr/share/kde4/apps/solid/actions/' '--disable-dxva2' '--disable-gnomevfs' '--disable-goom' '--disable-portaudio' '--disable-projectm' '--disable-sqlite' '--disable-telx' '--enable-alsa' '--enable-atmo' '--enable-dc1394' '--enable-dv' '--enable-fbosd' '--enable-libva' '--enable-linsys' '--enable-omxil' '--enable-pvr' '--enable-udev' '--enable-v4l2' '--enable-crystalhd' '--enable-mmx' '--enable-sse' '--disable-neon' '--disable-altivec' 'build_alias=i686-linux-gnu' [0x8290908] main libvlc debug: searching plug-in modules [0x8290908] main libvlc debug: loading plugins cache file /usr/lib/vlc/plugins/plugins.dat [0x8290908] main libvlc debug: recursively browsing `/usr/lib/vlc/plugins' [0x8290908] main libvlc debug: saving plugins cache /usr/lib/vlc/plugins/plugins.dat [0x8290908] main libvlc debug: plug-ins loaded: 420 modules [0x8290908] main libvlc debug: opening config file (/home/laura/.config/vlc/vlcrc) [0x8290908] main libvlc debug: translation test: code is "fr" [0x8290908] main libvlc debug: CPU has capabilities MMX MMXEXT SSE SSE2 SSE3 SSSE3 SSE4.1 SSE4.2 FPU [0x8290908] main libvlc debug: looking for memcpy module: 4 candidates [0x8290908] main libvlc debug: using memcpy module "memcpymmxext" [0x841a928] main input debug: Creating an input for 'Bibliothèque' [0x841a928] main input debug: Input is a meta file: disabling unneeded options [0x841a928] main input debug: using timeshift granularity of 50 MiB, in path '/tmp' [0x841a928] main input debug: `file/xspf-open:///home/laura/.local/share/vlc/ml.xspf' gives access `file' demux `xspf-open' path `/home/laura/.local/share/vlc/ml.xspf' [0x841a928] main input debug: creating demux: access='file' demux='xspf-open' location='/home/laura/.local/share/vlc/ml.xspf' file='/home/laura/.local/share/vlc/ml.xspf' [0x82b1d40] main demux debug: looking for access_demux module: 3 candidates [0x82b1d40] main demux debug: no access_demux module matching "file" could be loaded [0x82b1d40] main demux debug: TIMER module_need() : 1.224 ms - Total 1.224 ms / 1 intvls (Avg 1.224 ms) [0x841a928] main input debug: creating access 'file' location='/home/laura/.local/share/vlc/ml.xspf', path='/home/laura/.local/share/vlc/ml.xspf' [0x82a2010] main access debug: looking for access module: 2 candidates [0x82a2010] filesystem access debug: opening file `/home/laura/.local/share/vlc/ml.xspf' [0x82a2010] main access debug: using access module "filesystem" [0x82a2010] main access debug: TIMER module_need() : 0.336 ms - Total 0.336 ms / 1 intvls (Avg 0.336 ms) [0x82a20e8] main stream debug: Using stream method for AStream* [0x82a20e8] main stream debug: starting pre-buffering [0x82a20e8] main stream debug: received first data after 0 ms [0x82a20e8] main stream debug: pre-buffering done 296 bytes in 0s - 8501 KiB/s [0x8419e28] main stream debug: looking for stream_filter module: 7 candidates [0x8419e28] main stream debug: no stream_filter module matching "any" could be loaded [0x8419e28] main stream debug: TIMER module_need() : 0.658 ms - Total 0.658 ms / 1 intvls (Avg 0.658 ms) [0x8419e28] main stream debug: looking for stream_filter module: 1 candidate [0x8419e28] main stream debug: using stream_filter module "stream_filter_record" [0x8419e28] main stream debug: TIMER module_need() : 0.134 ms - Total 0.134 ms / 1 intvls (Avg 0.134 ms) [0x841a928] main input debug: creating demux: access='file' demux='xspf-open' location='/home/laura/.local/share/vlc/ml.xspf' file='/home/laura/.local/share/vlc/ml.xspf' [0x8413c88] main demux debug: looking for demux module: 1 candidate [0x8413c88] playlist demux debug: using XSPF playlist reader [0x8413c88] main demux debug: using demux module "playlist" [0x8413c88] main demux debug: TIMER module_need() : 0.210 ms - Total 0.210 ms / 1 intvls (Avg 0.210 ms) [0x8412d60] main demux meta debug: looking for meta reader module: 2 candidates [0x8412d60] lua demux meta debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/meta/reader [0x8412d60] lua demux meta debug: Trying Lua scripts in /usr/lib/vlc/lua/meta/reader [0x8412d60] lua demux meta debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/reader/filename.luac [0x8412d60] lua demux meta debug: Trying Lua scripts in /usr/share/vlc/lua/meta/reader [0x8412d60] main demux meta debug: no meta reader module matching "any" could be loaded [0x8412d60] main demux meta debug: TIMER module_need() : 1.466 ms - Total 1.466 ms / 1 intvls (Avg 1.466 ms) [0x841a928] main input debug: `file/xspf-open:///home/laura/.local/share/vlc/ml.xspf' successfully opened [0x83291e8] main xml reader debug: looking for xml reader module: 1 candidate [0x83291e8] main xml reader debug: using xml reader module "xml" [0x83291e8] main xml reader debug: TIMER module_need() : 0.439 ms - Total 0.439 ms / 1 intvls (Avg 0.439 ms) [0x8413c88] playlist demux debug: parsed 0 tracks successfully [0x841a928] main input debug: EOF reached [0x8413c88] main demux debug: removing module "playlist" [0x8419e28] main stream debug: removing module "stream_filter_record" [0x82a2010] main access debug: removing module "filesystem" [0x841a928] main input debug: TIMER input launching for 'Bibliothèque' : 4.959 ms - Total 4.959 ms / 1 intvls (Avg 4.959 ms) [0x8413c88] main interface debug: looking for interface module: 1 candidate [0x8413c88] main interface debug: using interface module "hotkeys" [0x8413c88] main interface debug: TIMER module_need() : 0.170 ms - Total 0.170 ms / 1 intvls (Avg 0.170 ms) [0x841acf8] main interface debug: looking for interface module: 1 candidate [0x82a1bc0] main playlist debug: playlist threads correctly activated [0x841acf8] main interface debug: using interface module "inhibit" [0x841acf8] main interface debug: TIMER module_need() : 4.897 ms - Total 4.897 ms / 1 intvls (Avg 4.897 ms) [0x82a1bc0] main playlist debug: rebuilding array of current - root Liste de lecture [0x82a1bc0] main playlist debug: rebuild done - 0 items, index -1 [0x82a45b8] main interface debug: looking for interface module: 1 candidate [0x82a45b8] main interface debug: using interface module "globalhotkeys" [0x82a45b8] main interface debug: TIMER module_need() : 1.349 ms - Total 1.349 ms / 1 intvls (Avg 1.349 ms) [0x8290908] main libvlc: Lancement de vlc avec l'interface par défaut. Utilisez « cvlc » pour démarrer VLC sans interface. [0x82a4338] main interface debug: looking for interface module: 6 candidates [0xb0ba8650] main generic debug: looking for extension module: 1 candidate [0xb0ba8650] lua generic debug: Opening Lua Extension module [0xb0ba8650] lua generic debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/extensions [0xb0ba8650] lua generic debug: Trying Lua scripts in /usr/lib/vlc/lua/extensions [0xb0ba8650] lua generic debug: Trying Lua scripts in /usr/share/vlc/lua/extensions [0xb0ba8650] main generic debug: using extension module "lua" [0xb0ba8650] main generic debug: TIMER module_need() : 0.364 ms - Total 0.364 ms / 1 intvls (Avg 0.364 ms) [0x82a4338] main interface debug: using interface module "qt4" [0x82a4338] main interface debug: TIMER module_need() : 236.600 ms - Total 236.600 ms / 1 intvls (Avg 236.600 ms) [0x82a1bc0] main playlist debug: adding item `dvd' ( dvd:///dev/dvd ) [0x82a4338] qt4 interface debug: Adding a new MRL to recent ones: dvd:///dev/dvd [0x82a1bc0] main playlist debug: rebuilding array of current - root Liste de lecture [0x82a1bc0] main playlist debug: rebuild done - 1 items, index -1 [0x82a1bc0] main playlist debug: processing request item: dvd, node: null, skip: 0 [0x82a1bc0] main playlist debug: resyncing on dvd [0x82a1bc0] main playlist debug: dvd is at 0 [0x82a1bc0] main playlist debug: starting playback of the new playlist item [0x82a1bc0] main playlist debug: resyncing on dvd [0x82a1bc0] main playlist debug: dvd is at 0 [0x82a1bc0] main playlist debug: creating new input thread [0xb4e00618] main input debug: Creating an input for 'dvd' [0xb4e00618] main input debug: using timeshift granularity of 50 MiB, in path '/tmp' [0xb4e00618] main input debug: `dvd:///dev/dvd' gives access `dvd' demux `' path `/dev/dvd' [0xb4e00618] main input debug: creating demux: access='dvd' demux='' location='/dev/dvd' file='/dev/dvd' [0xaf900960] main demux debug: looking for access_demux module: 2 candidates libdvdnav: Using dvdnav version 4.2.0 libdvdread: Using libdvdcss version 1.2.12 for DVD access [0xafa00560] main input debug: Creating an input for 'dvd' [0x82a1bc0] main playlist debug: meta ok for (null), need to fetch art [0xafa027d0] main demux meta debug: looking for meta fetcher module: 1 candidate [0xafa027d0] lua demux meta debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/meta/fetcher [0xafa027d0] lua demux meta debug: Trying Lua scripts in /usr/lib/vlc/lua/meta/fetcher [0xafa027d0] lua demux meta debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/fetcher/tvrage.luac [0xafa027d0] main demux meta debug: using meta fetcher module "lua" [0xafa027d0] main demux meta debug: TIMER module_need() : 2.019 ms - Total 2.019 ms / 1 intvls (Avg 2.019 ms) [0xafa027d0] main demux meta debug: removing module "lua" [0x82a1bc0] main playlist debug: searching art for dvd [0xafa02450] main art finder debug: looking for art finder module: 2 candidates [0xafa02450] lua art finder debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/meta/art [0xafa02450] lua art finder debug: Trying Lua scripts in /usr/lib/vlc/lua/meta/art [0xafa02450] lua art finder debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/art/00_musicbrainz.luac [0xafa02450] lua art finder debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/art/01_googleimage.luac [0xafa02450] lua art finder debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/art/02_frenchtv.luac [0xafa02450] lua art finder debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/art/03_lastfm.luac [0xafa02450] lua art finder debug: Trying Lua scripts in /usr/share/vlc/lua/meta/art [0xafa02450] main art finder debug: no art finder module matching "any" could be loaded [0xafa02450] main art finder debug: TIMER module_need() : 2.812 ms - Total 2.812 ms / 1 intvls (Avg 2.812 ms) [0x82a1bc0] main playlist debug: art not found for dvd [0x82a4338] qt4 interface debug: IM: Setting an input libdvdnav: DVD Title: HUNTERS_D4_PAL libdvdnav: DVD Serial Number: 3BBDE8D5___MVB__ libdvdnav: DVD Title (Alternative): libdvdnav: Unable to find map file '/home/laura/.dvdnav/HUNTERS_D4_PAL.map' libdvdnav: DVD disk reports itself with Region mask 0x00fd0000. Regions: 2 libdvdread: Attempting to retrieve all CSS keys libdvdread: This can take a _long_ time, please be patient libdvdread: Get key for /VIDEO_TS/VIDEO_TS.VOB at 0x000001cd libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_01_0.VOB at 0x000002ab libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_01_1.VOB at 0x00019a2f libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_02_0.VOB at 0x0022147c libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_02_1.VOB at 0x0022f161 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_03_0.VOB at 0x0025622c libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_03_1.VOB at 0x00256279 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_04_0.VOB at 0x0025e758 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_04_1.VOB at 0x0025e7a5 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_05_0.VOB at 0x002660f7 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_05_1.VOB at 0x00266144 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_06_0.VOB at 0x0026a869 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_06_1.VOB at 0x0026a8b6 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_07_0.VOB at 0x0027455b libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_07_1.VOB at 0x002745a8 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_08_0.VOB at 0x0027babf libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_08_1.VOB at 0x0027bb0c libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_09_0.VOB at 0x002846fb libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_09_1.VOB at 0x00284748 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_10_0.VOB at 0x002872f3 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_10_1.VOB at 0x00287340 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_11_0.VOB at 0x00289eee libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_11_1.VOB at 0x00289f3b libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_12_0.VOB at 0x0028caef libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_12_1.VOB at 0x0028cb3c libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_13_0.VOB at 0x00333e30 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_13_1.VOB at 0x00333e7d libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_14_0.VOB at 0x00364a26 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_14_1.VOB at 0x00364a73 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_15_0.VOB at 0x00370dad libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_15_1.VOB at 0x00370dfa libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_16_0.VOB at 0x00379dd5 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_16_1.VOB at 0x00379e22 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_17_0.VOB at 0x00382f7f libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_17_1.VOB at 0x00382fcc libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_18_0.VOB at 0x0038379c libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_18_1.VOB at 0x003837e9 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_19_0.VOB at 0x00384794 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_19_1.VOB at 0x003847e1 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_20_0.VOB at 0x003860cc libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_20_1.VOB at 0x00386119 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_21_0.VOB at 0x00387a05 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_21_1.VOB at 0x00387a52 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_22_0.VOB at 0x00387adb libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_22_1.VOB at 0x00387b28 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_23_0.VOB at 0x00387bb4 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_23_1.VOB at 0x00387c01 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_24_0.VOB at 0x00389eaf libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_24_1.VOB at 0x00389efc libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_25_0.VOB at 0x00389f62 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_25_1.VOB at 0x00389faf libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_26_0.VOB at 0x0038a023 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_26_1.VOB at 0x0038a070 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_27_0.VOB at 0x0038a10b libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_27_1.VOB at 0x0038a158 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_28_0.VOB at 0x0038a250 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_28_1.VOB at 0x0038a29d libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_29_0.VOB at 0x0038a397 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_29_1.VOB at 0x0038a3e4 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_30_0.VOB at 0x0038a4ce libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_30_1.VOB at 0x0038a51b libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_31_0.VOB at 0x0038a85e libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_31_1.VOB at 0x0038a8ab libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_32_0.VOB at 0x0038abb0 libdvdread: Elapsed time 0 libdvdread: Get key for /VIDEO_TS/VTS_32_1.VOB at 0x0038abfd libdvdread: Elapsed time 0 libdvdread: Found 32 VTS's libdvdread: Elapsed time 0 [0xaf900960] dvdnav demux debug: trying to go to dvd menu [0xaf900960] main demux debug: using access_demux module "dvdnav" [0xaf900960] main demux debug: TIMER module_need() : 55.895 ms - Total 55.895 ms / 1 intvls (Avg 55.895 ms) [0xaf968f28] main demux meta debug: looking for meta reader module: 2 candidates [0xaf968f28] lua demux meta debug: Trying Lua scripts in /home/laura/.local/share/vlc/lua/meta/reader [0xaf968f28] lua demux meta debug: Trying Lua scripts in /usr/lib/vlc/lua/meta/reader [0xaf968f28] lua demux meta debug: Trying Lua playlist script /usr/lib/vlc/lua/meta/reader/filename.luac [0xaf968f28] lua demux meta debug: Trying Lua scripts in /usr/share/vlc/lua/meta/reader [0xaf968f28] main demux meta debug: no meta reader module matching "any" could be loaded [0xaf968f28] main demux meta debug: TIMER module_need() : 1.036 ms - Total 1.036 ms / 1 intvls (Avg 1.036 ms) [0xb4e00618] main input debug: `dvd:///dev/dvd' successfully opened [0xaf900960] dvdnav demux debug: DVDNAV_HOP_CHANNEL [0xb4e00618] main input error: ES_OUT_RESET_PCR called [0xaf900960] dvdnav demux debug: DVDNAV_VTS_CHANGE [0xaf900960] dvdnav demux debug: - vtsN=2 [0xaf900960] dvdnav demux debug: - domain=8 [0xb4e00618] main input error: ES_OUT_RESET_PCR called [0xaf900960] dvdnav demux debug: DVDNAV_CELL_CHANGE [0xaf900960] dvdnav demux debug: - cellN=1 [0xaf900960] dvdnav demux debug: - pgN=1 [0xaf900960] dvdnav demux debug: - cell_length=36000 [0xaf900960] dvdnav demux debug: - pg_length=36000 [0xaf900960] dvdnav demux debug: - pgc_length=36000 [0xaf900960] dvdnav demux debug: - cell_start=0 [0xaf900960] dvdnav demux debug: - pg_start=0 [0xaf900960] dvdnav demux debug: DVDNAV_SPU_CLUT_CHANGE [0xaf900960] dvdnav demux debug: DVDNAV_SPU_STREAM_CHANGE [0xaf900960] dvdnav demux debug: - physical_wide=0 [0xaf900960] dvdnav demux debug: - physical_letterbox=0 [0xaf900960] dvdnav demux debug: - physical_pan_scan=1 [0xaf900960] dvdnav demux debug: buttonUpdate not done b=1 t=0 [0xb4e00618] main input debug: selecting program id=0 [0xaf9880c8] main decoder debug: looking for decoder module: 30 candidates [0xaf9880c8] main decoder debug: using decoder module "spudec" [0xaf9880c8] main decoder debug: TIMER module_need() : 15.860 ms - Total 15.860 ms / 1 intvls (Avg 15.860 ms) [0xaf9880c8] spudec decoder debug: invalid starting packet (size < 4 or pts <=0) [0xaf9880c8] spudec decoder debug: spu size: 0, i_pts: 0 i_buffer: 128 [0xaf900960] dvdnav demux debug: DVDNAV_AUDIO_STREAM_CHANGE [0xaf900960] dvdnav demux debug: - physical=0 [0xaf900960] dvdnav demux warning: cannot get next block (Error reading NAV packet.) [0xaf900960] dvdnav demux debug: jumping to first title [0xaf900960] dvdnav demux debug: DVDNAV_HOP_CHANNEL [0xb4e00618] main input error: ES_OUT_RESET_PCR called [0xaf9880c8] spudec decoder debug: invalid starting packet (size < 4 or pts <=0) [0xaf9880c8] spudec decoder debug: spu size: 0, i_pts: 0 i_buffer: 128 [0xaf900960] dvdnav demux debug: DVDNAV_VTS_CHANGE [0xaf900960] dvdnav demux debug: - vtsN=1 [0xaf900960] dvdnav demux debug: - domain=2 [0xb4e00618] main input error: ES_OUT_RESET_PCR called [0xaf9880c8] spudec decoder debug: invalid starting packet (size < 4 or pts <=0) [0xaf9880c8] spudec decoder debug: spu size: 0, i_pts: 0 i_buffer: 128 [0xaf9880c8] main decoder debug: removing module "spudec" [0xaf9880c8] main decoder debug: killing decoder fourcc `spu ', 0 PES in FIFO [0xb4e00618] main input debug: Program doesn't contain anymore ES [0xaf900960] dvdnav demux debug: DVDNAV_CELL_CHANGE [0xaf900960] dvdnav demux debug: - cellN=1 [0xaf900960] dvdnav demux debug: - pgN=1 [0xaf900960] dvdnav demux debug: - cell_length=22176000 [0xaf900960] dvdnav demux debug: - pg_length=22176000 [0xaf900960] dvdnav demux debug: - pgc_length=399798000 [0xaf900960] dvdnav demux debug: - cell_start=0 [0xaf900960] dvdnav demux debug: - pg_start=0 [0xaf900960] dvdnav demux debug: DVDNAV_SPU_CLUT_CHANGE [0xaf900960] dvdnav demux debug: DVDNAV_SPU_STREAM_CHANGE [0xaf900960] dvdnav demux debug: - physical_wide=128 [0xaf900960] dvdnav demux debug: - physical_letterbox=128 [0xaf900960] dvdnav demux debug: - physical_pan_scan=128 [0xaf900960] dvdnav demux debug: buttonUpdate not done b=1 t=1 [0xaf900960] dvdnav demux debug: DVDNAV_AUDIO_STREAM_CHANGE [0xaf900960] dvdnav demux debug: - physical=0 [0xb4e00618] main input debug: Buffering 0% [0xaf900960] dvdnav demux debug: buttonUpdate not done b=1 t=1 [0xaf900960] dvdnav demux warning: cannot get next block (Error reading from DVD.) [0x82a1bc0] main playlist debug: finished input [0x82a1bc0] main playlist debug: dying input [0xaf900960] main demux debug: removing module "dvdnav" [0xb4e00618] main input debug: Program doesn't contain anymore ES [0x82a1bc0] main playlist debug: dead input [0x82a1bc0] main playlist debug: changing item without a request (current 0/1) [0x82a1bc0] main playlist debug: nothing to play [0x82a4338] qt4 interface debug: IM: Deleting the input "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Bon alors efface ton dossier .libdvdcss dans /home/laura Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) je le trouve où /home/laura ? DÉSOLÉ pour le niveau de mes questions mais comme tu t'en es rendu compte t'as pas un pro au bout du fil là..... "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) /home/laura c'est ton dossier personnel , effectivement il te manque les bases. Dans l'explorateur de fichier, fait CTRL H pour voir les dossiers cachés qui commencent par . Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) ok Bon .dvdcss gît dans ma corbeille maintenant "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) tu peux rafficher ton log vlc maintenant ? Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) bien volontiers mais ...euh c'est quoi le log chef ?... "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Humm, y a moyen de prendre le controle a distance de ta machine ? Réponds moi en privée si tu veux. Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Salut ARTAXERXES , j'ai peu de temps ces jours ci pour prendre le controle a distance de ta machine. peux tu nous repréciser si tu arrives a lire de vieux DVD, Non sony/disney ? En tous cas ce n'est pas un problème de libdvdcss, ton dvd est bien decrypté. Dernière modification par freechelmi (Le 15/11/2012, à 15:34) Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Salut Freechelmi et merci pour ta réponse. Alors j'ai 3 cas de figure : - j'ai réussi à lire sans pb un (mais un seul !)dvd de 2009 donc c'est possible -la plupart des dvd sont illisibles en laissant l'écran du lecteur vlc en visuel -certains autres affichent image et son de la page d'accueil mais quand on clique sur lancer le film, ça patine, écran noir vlc et même souvent impossible après de quitter l'application il faut ouvrir le lecteur de dvd manuellement pour sortir le dvd voilà je te remercie pour ton aide. Ne t'en fais pas j'ai le temps, nécessité faisant loi ! Encore merci pour ton aide artaxerxes "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Merci de préciser si tous les Dvds qui ne passent pas viennent du méme studio , par exemple Disney Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) non...du japonais, un peu de tout en fait.... "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne Phil_ Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Bonjour, Je viens de passer d'Ubuntu 10.04 à 12.04 et je suis tombé sur le même problème. Au départ j'ai pensé que c'était avec les DVD protégés contre la copie et que j'avais mal installé certaines bibliothèques mais après quelques essais avec différents DVD (protégés ou pas) seul un faisait planter VLC. Ce DVD fonctionnait normalement sur Ubuntu 10.04 avec la vieille version de VLC. Il est aussi lu sans problème avec Xine qui est installé par défaut sur Ubuntu. J'en suis arrivé à la conclusion qu'il s'agissait d'un bug de VLC sur ce DVD particulier. Ce que confirme plus ou moins la liste des changements de la dernière version qui vient de sortir (2.0.4) : http://www.videolan.org/developers/vlc-branch/NEWS: Fix numerous DVD (dvdnav) crashes Il suffit peut-être d'attendre que cette version soit dans dépôts d'Ubuntu. Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) @artaxerxes : Du coup peux tu confirmer que tu as les même problème avec Totem et smplayer ? il ne semble pas y avoir de mise a jour de la lib elle même, mais bien de VLC. Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) salut freechelmi, oui même prb avec totem et smplayer. En lançant le dvd avec smplayer, après avoir affiché l'image d'accueil, l'appli a carrément planté la machine arta "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne freechelmi Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Bon j'ai peut etre une piste ( j'ai un probleme similaire sur un de mes portables) . peux tu lancer sudo lshw -C disk et non donner la marque et le model du lecteur DVD ? Peux tu aussi nous donner la sortie de la commande : sudo regionset et plus particulièrement cella là : drive plays discs from region(s): 2, mask=0xFD Réponds non (n) pour l'instant quand regionset te demande s'il veut modifier lé région. PS : il faut vraiment qu'on fasse une GUI pour regionset ! Dernière modification par freechelmi (Le 11/11/2012, à 16:18) Hors ligne ARTAXERXES Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU) Salut Freechelmi, alors quand je lance sudo lshw -C disk j'obtiens *-disk description: ATA Disk produit: V4-CT128V4SSD2 identifiant matériel: 0 information bus: scsi@0:0.0.0 nom logique: /dev/sda version: S5FA numéro de série: 200007568 taille: 119GiB (128GB) fonctionnalités: partitioned partitioned:dos configuration: ansiversion=5 signature=000d227f *-cdrom description: DVD-RAM writer produit: DVD-RAM UJ8B0 fabriquant: MATSHITA identifiant matériel: 1 information bus: scsi@2:0.0.0 nom logique: /dev/cdrom nom logique: /dev/cdrw nom logique: /dev/dvd nom logique: /dev/dvdrw nom logique: /dev/sr0 version: 1.10 fonctionnalités: removable audio cd-r cd-rw dvd dvd-r dvd-ram configuration: ansiversion=5 status=nodisc pour sudo regionset ça donne : sudo: regionset: command not found et enfin la sortie de drive plays discs from region(s): 2, mask=0xFD bash: Erreur de syntaxe près du symbole inattendu « ( » j'ai essayé d'enlever les guillements mais ça donne Commande 'drive' non trouvée, vouliez-vous dire : La commande 'drivel' du paquet 'drivel' (universe) drive : commande introuvable j'ai contacté le constructeur car aucune marque ni modèle n'apparaissent sur mon lecteur dvd. Je te donne les caractéristiques de mon portable si çapeut aider : LDLC Aurore BB3-13-4-S1 LDLC SO DIMM ' GODDR3-SDRAM DDR1333 PC 10600 CL9 Pc portable W253 EUQHD 15.6 Intel core 13-2370M 3M 2.40GHZ FC-PGA10 TRAY CRUCIAL V4 128gb, sata 3gb/s 2.5 inch SSD Voilà je te remercie bien chaleureusement à bientôt "Les justes seront comme des soleils". Ubuntu 12.04 sur Portable LDLC Aurore BB3-13-4-S1. Disque SSD120 Go. 4Go de mémoire. Intel Core i3-2370M Hors ligne
Soipacon [Tuto] Wallpapoz enfin ça marche !!!! Enfin j'ai trouvé un How To concernant wallpapoz. C'est trés bien fait et même sans être bilingue c'est facile. En tout cas chez moi ça marche impec sur Breezy noyau 686. http://ubuntuforums.org/showthread.php? … =wallpapoz Hors ligne Bob Morane Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour à tous, je vois qu'une solution a déjà été postée. Marche t'elle pour tout le monde? J'avais contacté par mail Akbar, le développeur de ce petit programme, je pense avoir une solution qui marche. Qui sait, peut-être même la solution qui marchera chez tout le monde. Elle est en tout cas différente de celle signalée ci dessus. Voici comment procéder : 1. télécharger les sources de Wallpapoz là http://wallpapoz.sourceforge.net/ 2. extraire le tout 3. créer un dossier "bin" malencontreusement oublié dans l'archive. Cela permettra à la commande make de fonctionner 4. ouvrir un terminal et cd /votre/dossier (ou clic droit sur le dossier ouvrir un terminal si vous avez installé le paquet nautilus-open-terminal bien pratique) 5. make 6. sudo sh install.sh /usr/local (si vous voulez installer dans /usr/local) Vous avez maintenant dans menu-application-accessoire un objet Wallpapoz. Il lance le script de configuration. Celui-ci va créer un fichier caché avec vos réglages. Le truc important est le démon qui va changer vos bureaux. Et c'est là que chez certains çà marche, et parfois pas. Ne cliquez pas sur "start daemon" dans l'écran GUI, vous ne saurez pas si ca marche. Allez dans votre terminal et tapez daemon_wallpapoz. Si après vous n'avez plus la possibilité d'entrer de commande, c'est que le démon fonctionne. Si par contre vous recevez un message "segmentation fault / erreur de segmentation", il ne fonctionne pas. Etrangement il semble que chez certains il fonctionne, et parfois pas. Akbar n'a pas réussi à corriger cette erreur du démon dans le code source, et il semble qu'elle soit unique à Ubutnu. Mais il a réussi à éviter le problème en recodant le démon en python et non en c++ Vous avez donc besoin du démon en python. Pour le moment il n'est pas sur le site. Akbar portera l'ensemble démon et GUI sur Python plus tard. Pour le moment voici le code du démon en python ## daemon_wallpapoz.py # # This file will check desktop continously and change wallpaper # with preferences from configuration file from xml.dom import minidom import xml import os import sys import array import time import threading import random ## number -- global variable # # this is index of wallpaper list of workspaces # for example: number[0] is index of wallpaper list in first workspace number = array.array('i') ## delay -- global variable, how many time will wallpaper list thread # # has to wait before it manipulate its index delay = 1.0 ## random -- global variable, is wallpaper list thread randomize its index randomvar = 0 exit_code = 0 ## XMLProcessing -- class for processing wallpapoz xml file class XMLProcessing: ## The constructor def __init__(self, file): try: self.xmldoc = minidom.parse(file) except IOError: print "There is no configuration file. Create it first by running wallpapoz!" sys.exit() except xml.parsers.expat.ExpatError: print "The configuration file is corrupted. Remove it then create it again with wallpapoz!" sys.exit() self.wallpapoz_node = self.xmldoc.childNodes[1] self.workspace_node_list = self.wallpapoz_node.getElementsByTagName('workspace') self.workspace_num = self.workspace_node_list.length ## class method -- get delay time that wallpaper list thread manipulate its index def delay(self): return self.wallpapoz_node.attributes["interval"].value ## class method -- whether the wallpaper list thread randomize its index def is_random(self): return self.wallpapoz_node.attributes["random"].value ## class method -- method for fill list with wallpaper path file def fill_list(self): worklist = [] for i in range(self.workspace_num): worklist.append( [] ) index = -1 for file in self.workspace_node_list: file_node_list = file.getElementsByTagName('file') index = index + 1 for node in file_node_list: if node.nodeName == "file": worklist[index].append(node.firstChild.data) return worklist ## class method -- to know how many workspace we use def get_workspace_num(self): return self.workspace_num ## System -- class for knowing current desktop and change wallpaper # # with calling external program class System: ## class method to know what workspace we are in now def current_desktop(self): desktop = os.popen('xprop -root _NET_CURRENT_DESKTOP').read() return int(desktop[33] + desktop[34]) ## class method def change_wallpaper(self, wallpaper): os.system('gconftool-2 -t string -s /desktop/gnome/background/picture_filename ' + "\"" + wallpaper + "\"") ## AsyncIndex -- class for making thread that manipulating index wallpaper list class AsyncIndex(threading.Thread): ## constructor def __init__(self, index): threading.Thread.__init__(self) self.index = index ## the function that thread will execute def run(self): if randomvar == 1: number[self.index] = 0 size = len(worklist[self.index]) while True: number[self.index] = int(random.random() * size) time.sleep(delay) else: while True: number[self.index] = 0 for i in worklist[self.index]: time.sleep(delay) number[self.index] = number[self.index] + 1 ## the main program if __name__ == "__main__": # generate seed for random number random.seed() # the configuration file file = os.environ['HOME'] + "/.wallpapoz/wallpapoz.xml" # call the xmlprocessing class to read it wallpapozxml = XMLProcessing(file) # fill the workspace list worklist = wallpapozxml.fill_list() # how many workspace we use total_workspace = wallpapozxml.get_workspace_num() # create the index for wallpaper list thread number.fromlist( range( total_workspace ) ) # create the system class ( to change wallpaper and read current desktop ) # by calling external program system = System() # previous workspace previous_desktop = -1 # previous wallpaper list index previous_index = -1 # get the delay time and random preferences delay = 60 * float(wallpapozxml.delay()) randomvar = int(wallpapozxml.is_random()) # create the thread wallpaper_list = [] for i in range(total_workspace): wallpaper_list.append(AsyncIndex(i)) wallpaper_list[i].start() # the daemon that works forever while True: try: # don't get rush time.sleep(1) # what workspace we are in now? cur_desk = system.current_desktop() # requirement for changing wallpaper # 1. we change workspace # 2. index of wallpaper list change if previous_desktop != cur_desk or previous_index != number[cur_desk]: # if we move to workspace that we don't use, just ignore if cur_desk >= total_workspace: continue # command to change wallpaper system.change_wallpaper(worklist[cur_desk][number[cur_desk]]) # our previous workspace and index of wallpaper list previous_desktop = cur_desk previous_index = number[cur_desk] # ok, we stop this daemon except KeyboardInterrupt: # now it's time for the main thread to exit os._exit(0) 7. copier le code python dans un fichier texte. Le nommer daemon_wallpapoz.py 8. sudo cp daemon_wallpapoz.py /usr/local/daemon_wallpapoz.py lancez le avec la commande python daemon_wallpapoz.py tout devrait marcher. Vérifiez que vous avez des fonds d'écran différent sur vos différents bureaux. Le démon aura besoin de quelques secondes pour changer correctement vos bureaux. Si tout marche, ajoutez une entrée à votre session pour le lancer à l'ouverture de session. Hors ligne ced_668 Re : [Tuto] Wallpapoz enfin ça marche !!!! Lorsque je lance le daemon il m'affiche: File "daemon_wallpapoz.py", line 36 try: ^ IndentationError: expected an indented block A quoi c'est due? J'ai vraiment tout esayer pour installer le logiciel et je commence a etre un peu desesperer!! Hors ligne ced_668 Re : [Tuto] Wallpapoz enfin ça marche !!!! En fait le text proposer ci dessu est plein d'erreur de copie, faite la meme manip mais recuperer plutot le texte a partir du lien fournit dans le premier post et la ca marche nickel!!!!!!!!!!!!!!!!!! Hors ligne zempa Re : [Tuto] Wallpapoz enfin ça marche !!!! A noter qu'avec la version 0.3, wallpapoz est desormais ecrit en python. Il y a un script d'installation (en python). Toutefois, il est possible de lancer wallpapoz depuis le repertoire desarchivé sans installation. voir le fichier install. Defursac Re : [Tuto] Wallpapoz enfin ça marche !!!! avec la version 0.3 faut-il toujours faire les étapes 7 et 8 proposées par Bob Morane ? Parce que je l'ai pas fait... et je n'ai pas de wallpapers différents sur mes bureaux. Apparement ça serait alors un démon qui permet de changer de wallpaper toutes les x minutes. Est-ce normal ? Au fait je suis sur Dapper, avec Aiglx Compiz...mais même en switchant sur Metacity ça ne fonctionne pas ! Merci de votre aide [EDIT] En fait, les préférences du démon ne m'indiquent qu'un seul bureau... est-ce normal ? Dernière modification par Defursac (Le 26/05/2006, à 09:21) Si vous ne partez pas en vacances, mettez un déodorant bleu dans la chasse d'eau ; vous aurez l'impression de faire pipi dans le Pacifique. Jean-Louis Fournier Hors ligne chizum Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour, J'ai installé wallpapoz, la dernière version, mais le seul problème, c'est que je n'ai que 2 bureaux dans le wallpapoz. Donc, je ne peux mettre que 2 papiers peint sur mes 2 bureaux, et les 2 autres ont le papier peint défini pour le 2ème bureau. En clair, aur le 1er bureau j'ai l'image 1.png, sur le 2ème, 3ème et 4ème, le'image 2.png!! Comment changer cela? D'avance merci La vague allègre du présent, sur l'avenir des chimères c'est brisée, pour se répandre librement sur le sable fin du passé... Hors ligne chizum Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour, le problème est résolu.:) 1- télécharger wallpapoz sous //wallpapoz.sourceforge.net/temp/wallpapoz-0.3.tar.bz2 2- décompresser le pac dans votre répertoire /home/votre_nom 3- ouvrez un terminal et tapez: $cd nom_dossier_wallpapoz 4- toujours dans le terminal : $ sudo python install.py install Wallpapoz est installé Reste une petite manip à effectuer pour lancer le démon au démarrage de la distribution. Dans le Tableau de bord, rendez-vous dans Système/Préférences/Sessions. Dans Programmes au démarrage, cliquer sur Ajoutez puis Parcourir. Rechercher et sélectionner daemon_wallpapoz.py dans /usr/bin/, puis cliquer sur Ouvrir. Valider et Fermer. Redémarrer votre distribution. "Après avoir également installé Wallpapoz sous Edgy, le redémarrage ne semble pas indispensable." Moi je l’ai fait car cela ne fonctionnait pas ! Vous trouverez le raccourçi de Wallpapoz dans Applications/Accessoires. Lancer Wallpapoz.Important - Avant d’effectuer des modifications dans Wallpapoz: tuer le démon: cliquer sur Kill Daemon. Important - Lorsque vous avez terminé vos modifications : sauvegarder les modifications : cliquer sur Save redémarrer le démon : cliquer sur Restart Daemon. Personnellement, j'ai gardé tous les fichiers, afin de pouvoir désinstaller wallpapoz. Pour ça, tapez dans un terminal: $ sudo python install.py uninstall Wallpapoz est désinstallé. La vague allègre du présent, sur l'avenir des chimères c'est brisée, pour se répandre librement sur le sable fin du passé... Hors ligne PatAnnie Re : [Tuto] Wallpapoz enfin ça marche !!!! J'ai installé la dernière version : Wallpapoz 0.4 dans sa version française OK Par contre je n'arrive pas à trouver daemon_wallpapoz.py dans /usr/bin ???? Le terminal répond à : daemon_wallpapoz sans infos sup.... Dois-je mettre un nouveau script au démarrage avec daemon_wallpapoz options ???? Merci de votre aide et A+ Hors ligne S2S Re : [Tuto] Wallpapoz enfin ça marche !!!! lu pour moi v0.4, et le il ce lance (la commande daemon_wallpapoz reste en attente) mais rien ne ce passe si je n'ouvre pas le gui et click sur restart daemon. j'utilise les depot officiel. le daemon ce trouve la: /usr/bin/daemon_wallpapoz. j'ai essayer de le mettre la: /usr/local/daemon_wallpapoz.py sans resultat le path en dur, rien!y a t'il des argument a passer pour le redemarer par un script ? ---edit--- complete avec le post de 'chizum' en passant par 'parcourir' ca marche, erreur de syntaxe peut etre. la commande fonctionnant pour moi est: /usr/bin/daemon_wallpapoz.py (j'avais copier 'daemon_wallpapoz' en 'daemon_wallpapoz.py' et pas essayer avec 'daemon_wallpapoz' original sans le '.py' ) Dernière modification par S2S (Le 10/11/2007, à 14:48) portable: Toshiba Qosmio x500 12Q fixe: P5N72-T Premium//Core2Quad-Q9550//7950GT//2048DDR2 OS: 10.04 - 10.10 - 11.04, 7 ... qui croit tout savoir, n'en saura jamais plus ... Hors ligne Omnisilver Re : [Tuto] Wallpapoz enfin ça marche !!!! Hello, J'ai refondu la page sur le wiki, il y a maintenant toutes les infos dont on pourrait avoir besoin : http://doc.ubuntu-fr.org/wallpapoz Hors ligne MuLoChE Re : [Tuto] Wallpapoz enfin ça marche !!!! Pour ceux qui n'ont pas le fichier daemon_wallpapoz. regarder plutôt vers: /usr/bin/X11. A noter qu'il y autant de dossier X11 que de bureau. choisissez le fichier daemon_wallpapoz le plus recent, c'est à dire le 1er dans le 1er dossier. arff j'ai du mal désoler il est tard Hors ligne michug Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour à tous J'ai écrit quelques scripts bash et python qui utilisent «wallpapoz» et me permettent de changer mon fond d'écran toutes les minutes, en affichant une photo sélectionnée aléatoirement dans mon arborescence photo(plus de 33000) et en écrivant une légende concernant la photo, date de création, photographe, sujet de l'album, commentaires, etc.... Ces informations étant écrites dans la photo. Je suis sur ubuntu 11.10 avec unity et ça fonctionne très bien depuis plusieurs années sur les différentes version de ubuntu. Je l'ai également testé sur 12.04. Récemment j'ai posté un message sur le forum dans la rubrique «Astuces et scripts» message «Affichage aléatoire des photos en fond d'écran» où je décris mon application. Si vous êtes intéressé, répondez-moi sur mon message «Affichage aléatoire des photos en fond d'écran» Hors ligne
This is by no means a complete answer, but if there are multiple images in the tif and if you know the size in advance, you can standardize the image samples prior to classifying them. You would cut up the image into all the possible rectangles in the tif. So when you create a classifier (I don't mention the methods here), the end result would take a synthesis of classifying all of the smaller rectangles. So if given a tif , the 'arrow' or 'flower' images are 16px by 16px , say, you can use Python PIL to create the samples. from PIL import Image image_samples = [] im = Image.open("input.tif") sample_dimensions = (16,16) for box in get_all_corner_combinations(im, sample_dimensions): image_samples.append(im.crop(box)) classifier = YourClassifier() classifications = [] for sample in image_samples: classifications.append (classifier (sample)) label = fuse_classifications (classifications) Again, I didn't talk about the learning step of actually writing YourClassifier. But hopefully this helps with laying out part of the problem. There is a lot of research on the subject of learning to classify images as well as work in cleaning up noise in images before classifying them. Consider browsing through this nice collection of existing Python machine learning libraries. http://scipy-lectures.github.com/advanced/scikit-learn/index.html There are many techniques that relate to images as well.
I have a model with managed = False. class SampleModel(models.Model): apple = models.CharField(max_length=30) orange = models.CharField(max_length=30) class Meta: managed = False I have a unit test which creates a SampleModel, however when I run the test I get: DatabaseError: no such table: SAMPLE_SAMPLE_MODEL The django docs - https://docs.djangoproject.com/en/dev/ref/models/options/#managed documents the following: For tests involving models with managed=False, it's up to you to ensure the correct tables are created as part of the test setup. How can I actually "create" the tables during the test setup? Or alternatively, how can I make it so that when I am running tests, this model has "managed = True" for the duration of the test? In the real application, this model is actually backed by a view in the database. However for the during of the test, I would like to treat this as a table and be able to insert test data in there.
I'm trying to use the new fbsr_{{appID}} cookie. I'm using the following functions to parse it, but when I try to get the access_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing functions? If not, what could be the problem? more info: I managed to log users in without cookies using the oauth link which redirects back into my site with the code as a parameter, so it can't be the app id, app secret or the redirect_uri. Another reason is that these have different error messages. def base64_url_decode(inp): padding_factor = (4 - len(inp) % 4) % 4 inp += "="*padding_factor return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/')))) def parse_signed_request(signed_request, secret): l = signed_request.split('.', 2) encoded_sig = l[0] payload = l[1] sig = base64_url_decode(encoded_sig) data = json.loads(base64_url_decode(payload)) if data.get('algorithm').upper() != 'HMAC-SHA256': logging.error('Unknown algorithm') return None else: expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: return None else: logging.debug('valid signed request received..') return data args = {} args['client_id'] = fbapp_id args['redirect_uri'] = site_url args['client_secret'] = fbapp_secret args['code'] = code response = urllib.urlopen('https://graph.facebook.com/oauth/access_token?'+urllib.urlencode(args)) # ... here i'm getting the error back from the server: error validating verification code...
I am really new to programming... But here is my question : I cannot post images but the plot I wish to have is a "crown" (two concentric circle with radius a I mean, mathematically speaking is really easy to define but how can I do it with a python program ? I thought of something like this : def Fm1(X, Y): r =r = sqrt(1.*X**2+1.*Y**2) cos = 1.*X/r sin = 1.*Y/r teta = where( sin >= 0. , arccos(cos) , -arccos(cos) ) teta = where(r == 0. , 0., teta) return r, teta def F(r,teta): X = r*cos(teta) Y = r*sin(teta) return X,Y Those are simply the function that let you pass from the cartesian to the polar coordinates, and then : r=sy.linspace(a,b,N+1) # radius division t=sy.linspace(0,2.*pi,2**NN) #angle (theta) division R,T=meshgrid(r,t) #creating a mesh X,Y = F(R,T)#transform from polar to cartesian #Plotting : fig=plt.figure() ax=fig.add_subplot(111) ax.plot(X, Y) plt.show() But the result is : concentric polygons. I wish I had N+1 circles at equidistance from radius a to radius b and 2**NN lines (origin center and a given angle). Sorry I know it's really a trivial question, Thanks
Assuming I have a system of three Classes.The GameClass creates instances of both other classes upon initialization. class FieldClass: def __init__( self ): return def AnswerAQuestion( self ): return 42 class PlayerClass: def __init__( self ): return def DoMagicHere( self ): # Access "AnswerAQuestion" located in the "FieldClass" instance in "GameClass" pass class GameClass: def __init__( self ): self.Field = FieldClass() self.Player = PlayerClass() What would be the best way of accessing AnswerAQuestion() located in FieldClass from within the instance of PlayerClass? Do I have to pass a reference to the FieldClassinstance toPlayerClass? Is there another, better way of solving this? Doing the above would make me have to include an additional variable in PlayerClassto hold theFieldClassinstance. Is there a completely different way of managing class relationships in Python?
I'm writing a script that will print a random line of text from a file into an XCHAT channel. So far it works fine, but I want to add one last bit of functionality. I have logs with, for example, "Oct 23 12:07:59 (nickname> " appearing before every line of text. I just want to print the parts of the lines that follow the "(nickname>", how can I do this? __module_name__ = "ran.py" __module_version__ = "1.0" __module_description__ = "script to add random text to channel messages" import xchat import random def ran(message): message = random.choice(open("E:/logs/myfile.log", "r").readlines()) return(message) def ran_cb(word, word_eol, userdata): message = '' message = ran(message) xchat.command("msg %s %s"%(xchat.get_info('channel'), message)) return xchat.EAT_ALL xchat.hook_command("ran", ran_cb, help="/ran to use")
Ce cours est visible gratuitement en ligne. Ce cours existe en livre papier. Ce cours existe en eBook. Vous pouvez obtenir un certificat de réussite à l'issue de ce cours. J'ai tout compris ! Jusqu'à présent, nous avons testé des instructions d'une façon linéaire : l'interpréteur exécutait au fur et à mesure le code que vous saisissiez dans la console. Mais nos programmes seraient bien pauvres si nous ne pouvions, de temps à autre, demander à exécuter certaines instructions dans un cas, et d'autres instructions dans un autre cas. Dans ce chapitre, je vais vous parler des structures conditionnelles, qui vont vous permettre de faire des tests et d'aller plus loin dans la programmation. Les conditions permettent d'exécuter une ou plusieurs instructions dans un cas, d'autres instructions dans un autre cas. Vous finirez ce chapitre en créant votre premier « vrai » programme : même si vous ne pensez pas encore pouvoir faire quelque chose de très consistant, à la fin de ce chapitre vous aurez assez de matière pour coder un petit programme dans un but très précis. Vos premières conditions et blocs d'instructions Forme minimale en if Les conditions sont un concept essentiel en programmation (oui oui, je me répète à force mais il faut avouer que des concepts essentiels, on n'a pas fini d'en voir). Elles vont vous permettre de faire une action précise si, par exemple, une variable est positive, une autre action si cette variable est négative, ou une troisième action si la variable est nulle. Comme un bon exemple vaut mieux que plusieurs lignes d'explications, voici un exemple clair d'une condition prise sous sa forme la plus simple. Cela étant posé, revenons à nos conditions : >>> # Premier exemple de condition >>> a = 5 >>> if a > 0: # Si a est supérieur à 0 ... print("a est supérieur à 0.") ... a est supérieur à 0. >>> Détaillons ce code, ligne par ligne : La première ligne est un commentaire décrivant qu'il s'agit du premier test de condition. Elle est ignorée par l'interpréteur et sert juste à vous renseigner sur le code qui va suivre. Cette ligne, vous devriez la comprendre sans aucune aide. On se contente d'affecter la valeur 5 à la variable a. Ici se trouve notre test conditionnel. Il se compose, dans l'ordre : du mot clé ifqui signifie « si » en anglais ; de la condition proprement dite, a > 0, qu'il est facile de lire (une liste des opérateurs autorisés pour la comparaison sera présentée plus bas) ; du signe deux points, « : », qui termine la condition et est indispensable : Python affichera une erreur de syntaxe si vous l'omettez. Ici se trouve l'instruction à exécuter dans le cas où aest supérieur à0. Après que vous ayez appuyé surEntréeà la fin de la ligne précédente, l'interpréteur vous présente la série de trois points qui signifie qu'il attend la saisie dubloc d'instructionsconcerné avant de l'interpréter. Cette instruction (et les autres instructions à exécuter s'il y en a) est indentée, c'est-à-dire décalée vers la droite. Des explications supplémentaires seront données un peu plus bas sur les indentations. L'interpréteur vous affiche à nouveau la série de trois points et vous pouvez en profiter pour saisir une nouvelle instruction dans ce bloc d'instructions. Ce n'est pas le cas pour l'instant. Vous appuyez donc sur Entréesans avoir rien écrit et l'interpréteur vous affiche le message « a est supérieur à 0 », ce qui est assez logique vu queaest effectivement supérieur à0. Il y a deux notions importantes sur lesquelles je dois à présent revenir, elles sont complémentaires ne vous en faites pas. La première est celle de bloc d'instructions. On entend par bloc d'instructions une série d'instructions qui s'exécutent dans un cas précis (par condition, comme on vient de le voir, par répétition, comme on le verra plus tard…). Ici, notre bloc n'est constitué que d'une seule instruction (la ligne 4 qui fait appel à print). Mais rien ne vous empêche de mettre plusieurs instructions dans ce bloc. a = 5 b = 8 if a > 0: # On incrémente la valeur de b b += 1 # On affiche les valeurs des variables print("a =",a,"et b =",b) La seconde notion importante est celle d'indentation. On entend par indentation un certain décalage vers la droite, obtenu par un (ou plusieurs) espaces ou tabulations. Les indentations sont essentielles pour Python. Il ne s'agit pas, comme dans d'autres langages tels que le C++ ou le Java, d'un confort de lecture mais bien d'un moyen pour l'interpréteur de savoir où se trouvent le début et la fin d'un bloc. Forme complète (if, elif et else) Les limites de la condition simple en if La première forme de condition que l'on vient de voir est pratique mais assez incomplète. Considérons, par exemple, une variable a de type entier. On souhaite faire une action si cette variable est positive et une action différente si elle est négative. Il est possible d'obtenir ce résultat avec la forme simple d'une condition : >>> a = 5 >>> if a > 0: # Si a est positif ... print("a est positif.") ... if a < 0: # a est négatif ... print("a est négatif.") Amusez-vous à changer la valeur de a et exécutez à chaque fois les conditions ; vous obtiendrez des messages différents, sauf si a est égal à 0. En effet, aucune action n'a été prévue si a vaut 0. Cette méthode n'est pas optimale, tout d'abord parce qu'elle nous oblige à écrire deux conditions séparées pour tester une même variable. De plus, et même si c'est dur à concevoir par cet exemple, dans le cas où la variable remplirait les deux conditions (ici c'est impossible bien entendu), les deux portions de code s'exécuteraient. La condition if est donc bien pratique mais insuffisante. L'instruction else: Le mot-clé else, qui signifie « sinon » en anglais, permet de définir une première forme de complément à notre instruction if. >>> age = 21 >>> if age >= 18: # Si age est supérieur ou égal à 18 ... print("Vous êtes majeur.") ... else: # Sinon (age inférieur à 18) ... print("Vous êtes mineur.") Je pense que cet exemple suffit amplement à exposer l'utilisation de else. La seule subtilité est de bien se rendre compte que Python exécute soit l'un, soit l'autre, et jamais les deux. Notez que cette instruction else doit se trouver au même niveau d'indentation que l'instruction if qu'elle complète. De plus, elle se termine également par deux points puisqu'il s'agit d'une condition, même si elle est sous-entendue. L'exemple de tout à l'heure pourrait donc se présenter comme suit, avec l'utilisation de else : >>> a = 5 >>> if a > 0: ... print("a est supérieur à 0.") ... else: ... print("a est inférieur ou égal à 0.") Mais… le résultat n'est pas tout à fait le même, si ? Non, en effet. Vous vous rendrez compte que, cette fois, le cas où a vaut 0 est bien pris en compte. En effet, la condition initiale prévoit d'exécuter le premier bloc d'instructions si a est strictement supérieur à 0. Sinon, on exécute le second bloc d'instructions. Si l'on veut faire la différence entre les nombres positifs, négatifs et nuls, il va falloir utiliser une condition intermédiaire. L'instruction elif: Le mot clé elif est une contraction de « else if », que l'on peut traduire très littéralement par « sinon si ». Dans l'exemple que nous venons juste de voir, l'idéal serait d'écrire : si aest strictement supérieur à0, on dit qu'il est positif ; sinon si aest strictement inférieur à0, on dit qu'il est négatif ; sinon, ( ane peut qu'être égal à0), on dit alors queaest nul. Traduit en langage Python, cela donne : >>> if a > 0: # Positif ... print("a est positif.") ... elif a < 0: # Négatif ... print("a est négatif.") ... else: # Nul print("a est nul.") De même que le else, le elif est sur le même niveau d'indentation que le if initial. Il se termine aussi par deux points. Cependant, entre le elif et les deux points se trouve une nouvelle condition. Linéairement, le schéma d'exécution se traduit comme suit : On regarde si aest strictement supérieur à0. Si c'est le cas, on affiche « a est positif » et on s'arrête là. Sinon, on regarde si aest strictement inférieur à0. Si c'est le cas, on affiche « a est négatif » et on s'arrête. Sinon, on affiche « a est nul ». Vous pouvez mettre autant de elif que vous voulez après une condition en if. Tout comme le else, cette instruction est facultative et, quand bien même vous construiriez une instruction en if, elif, vous n'êtes pas du tout obligé de prévoir un else après. En revanche, l'instruction else ne peut figurer qu'une fois, clôturant le bloc de la condition. Deux instructions else dans une même condition ne sont pas envisageables et n'auraient de toute façon aucun sens. Sachez qu'il est heureusement possible d'imbriquer des conditions et, dans ce cas, l'indentation permet de comprendre clairement le schéma d'exécution du programme. Je vous laisse essayer cette possibilité, je ne vais pas tout faire à votre place non plus. :-) De nouveaux opérateurs Les opérateurs de comparaison Les conditions doivent nécessairement introduire de nouveaux opérateurs, dits opérateurs de comparaison. Je vais les présenter très brièvement, vous laissant l'initiative de faire des tests car ils ne sont réellement pas difficiles à comprendre. Opérateur Signification littérale < Strictement inférieur à > Strictement supérieur à <= Inférieur ou égal à >= Supérieur ou égal à == Égal à != Différent de Prédicats et booléens Avant d'aller plus loin, sachez que les conditions qui se trouvent, par exemple, entre if et les deux points sont appelés des prédicats. Vous pouvez tester ces prédicats directement dans l'interpréteur pour comprendre les explications qui vont suivre. >>> a = 0 >>> a == 5 False >>> a > -8 True >>> a != 33.19 True >>> L'interpréteur renvoie tantôt True (c'est-à-dire « vrai »), tantôt False (c'est-à-dire « faux »). True et False sont les deux valeurs possibles d'un type que nous n'avons pas vu jusqu'ici : le type booléen (bool). Les variables de ce type ne peuvent prendre comme valeur que vrai ou faux et peuvent être pratiques, justement, pour stocker des prédicats, de la façon que nous avons vue ou d'une façon plus détournée. >>> age = 21 >>> majeur = False >>> if age >= 18: >>> majeur = True >>> À la fin de cet exemple, majeur vaut True, c'est-à-dire « vrai », si l'âge est supérieur ou égal à 18. Sinon, il continue de valoir False. Les booléens ne vous semblent peut-être pas très utiles pour l'instant mais vous verrez qu'ils rendent de grands services ! Les mots-clés and, or et not Il arrive souvent que nos conditions doivent tester plusieurs prédicats, par exemple quand l'on cherche à vérifier si une variable quelconque, de type entier, se trouve dans un intervalle précis (c'est-à-dire comprise entre deux nombres). Avec nos méthodes actuelles, le plus simple serait d'écrire : # On fait un test pour savoir si a est comprise dans l'intervalle allant de 2 à 8 inclus a = 5 if a >= 2: if a <= 8: print("a est dans l'intervalle.") else: print("a n'est pas dans l'intervalle.") else: print("a n'est pas dans l'intervalle.") Cela marche mais c'est assez lourd, d'autant que, pour être sûr qu'un message soit affiché à chaque fois, il faut fermer chacune des deux conditions à l'aide d'un else (la seconde étant imbriquée dans la première). Si vous avez du mal à comprendre cet exemple, prenez le temps de le décortiquer, ligne par ligne, il n'y a rien que de très simple. Il existe cependant le mot clé and (qui signifie « et » en anglais) qui va nous rendre ici un fier service. En effet, on cherche à tester à la fois si a est supérieur ou égal à 2 et inférieur ou égal à 8. On peut donc réduire ainsi les conditions imbriquées : if a>=2 and a<=8: print("a est dans l'intervalle.") else: print("a n'est pas dans l'intervalle.") Simple et bien plus compréhensible, avouez-le. Sur le même mode, il existe le mot clé or qui signifie cette fois « ou ». Nous allons prendre le même exemple, sauf que nous allons évaluer notre condition différemment. Nous allons chercher à savoir si a n'est pas dans l'intervalle. La variable ne se trouve pas dans l'intervalle si elle est inférieure à 2 ou supérieure à 8. Voici donc le code : if a<2 or a>8: print("a n'est pas dans l'intervalle.") else: print("a est dans l'intervalle.") Enfin, il existe le mot clé not qui « inverse » un prédicat. Le prédicat not a==5 équivaut donc à a!=5. not rend la syntaxe plus claire. Pour cet exemple, j'ajoute à la liste un nouveau mot clé, is, qui teste l'égalité non pas des valeurs de deux variables, mais de leurs références. Je ne vais pas rentrer dans le détail de ce mécanisme avant longtemps. Il vous suffit de savoir que pour les entiers, les flottants et les booléens, c'est strictement la même chose. Mais pour tester une égalité entre variables dont le type est plus complexe, préférez l'opérateur « == ». Revenons à cette démonstration : >>> majeur = False >>> if majeur is not True: ... print("Vous n'êtes pas encore majeur.") ... Vous n'êtes pas encore majeur. >>> Si vous parlez un minimum l'anglais, ce prédicat est limpide et d'une simplicité sans égale. Vous pouvez tester des prédicats plus complexes de la même façon que les précédents, en les saisissant directement, sans le if ni les deux points, dans l'interpréteur de commande. Vous pouvez utiliser les parenthèses ouvrantes et fermantes pour encadrer des prédicats et les comparer suivant des priorités bien précises (nous verrons ce point plus loin, si vous n'en comprenez pas l'utilité). Votre premier programme ! À quoi on joue ? L'heure du premier TP est venue. Comme il s'agit du tout premier, et parce qu'il y a quelques indications que je dois vous donner pour que vous parveniez jusqu'au bout, je vous accompagnerai pas à pas dans sa réalisation. Avant de commencer Vous allez dans cette section écrire votre premier programme. Vous allez sûrement tester les syntaxes directement dans l'interpréteur de commandes. Sujet Le but de notre programme est de déterminer si une année saisie par l'utilisateur est bissextile. Il s'agit d'un sujet très prisé des enseignants en informatique quand il s'agit d'expliquer les conditions. Mille pardons, donc, à ceux qui ont déjà fait cet exercice dans un autre langage mais je trouve que ce petit programme reprend assez de thèmes abordés dans ce chapitre pour être réellement intéressant. Je vous rappelle les règles qui déterminent si une année est bissextile ou non (vous allez peut-être même apprendre des choses que le commun des mortels ignore). Une année est dite bissextile si c'est un multiple de 4, sauf si c'est un multiple de 100. Toutefois, elle est considérée comme bissextile si c'est un multiple de 400. Je développe : Si une année n'est pas multiple de 4, on s'arrête là, elle n'est pas bissextile. Si elle est multiple de 4, on regarde si elle est multiple de 100. Si c'est le cas, on regarde si elle est multiple de 400. Si c'est le cas, l'année est bissextile. Sinon, elle n'est pas bissextile. Sinon, elle est bissextile. Solution ou résolution Voilà. Le problème est posé clairement (sinon relisez attentivement l'énoncé autant de fois que nécessaire), il faut maintenant réfléchir à sa résolution en termes de programmation. C'est une phase de transition assez délicate de prime abord et je vous conseille de schématiser le problème, de prendre des notes sur les différentes étapes, sans pour l'instant penser au code. C'est une phase purement algorithmique, autrement dit, on réfléchit au programme sans réfléchir au code proprement dit. Vous aurez besoin, pour réaliser ce petit programme, de quelques indications qui sont réellement spécifiques à Python. Ne lisez donc ceci qu'après avoir cerné et clairement écrit le problème d'une façon plus algorithmique. Cela étant dit, si vous peinez à trouver une solution, ne vous y attardez pas. Cette phase de réflexion est assez difficile au début et, parfois il suffit d'un peu de pratique et d'explications pour comprendre l'essentiel. La fonction input() Tout d'abord, j'ai mentionné une année saisie par l'utilisateur. En effet, depuis tout à l'heure, nous testons des variables que nous déclarons nous-mêmes, avec une valeur précise. La condition est donc assez ridicule. input() est une fonction qui va, pour nous, caractériser nos premières interactions avec l'utilisateur : le programme réagira différemment en fonction du nombre saisi par l'utilisateur. input() accepte un paramètre facultatif : le message à afficher à l'utilisateur. Cette instruction interrompt le programme et attend que l'utilisateur saisisse ce qu'il veut puis appuie sur Entrée. À cet instant, la fonction renvoie ce que l'utilisateur a saisi. Il faut donc piéger cette valeur dans une variable. >>> # Test de la fonction input >>> annee = input("Saisissez une année : ") Saisissez une année : 2009 >>> print(annee) '2009' >>> Il subsiste un problème : le type de la variable annee après l'appel à input() est… une chaîne de caractères. Vous pouvez vous en rendre compte grâce aux apostrophes qui encadrent la valeur de la variable quand vous l'affichez directement dans l'interpréteur. C'est bien ennuyeux : nous qui voulions travailler sur un entier, nous allons devoir convertir cette variable. Pour convertir une variable vers un autre type, il faut utiliser le nom du type comme une fonction (c'est d'ailleurs exactement ce que c'est). >>> type(annee) <type 'str'> >>> # On veut convertir la variable en un entier, on utilise >>> # donc la fonction int qui prend en paramètre la variable >>> # d'origine >>> annee = int(annee) >>> type(annee) <type 'int'> >>> print(annee) 2009 >>> Bon, parfait ! On a donc maintenant l'année sous sa forme entière. Notez que, si vous saisissez des lettres lors de l'appel à input(), la conversion renverra une erreur. Test de multiples Certains pourraient également se demander comment tester si un nombre a est multiple d'un nombre b. Il suffit, en fait, de tester le reste de la division entière de b par a. Si ce reste est nul, alors a est un multiple de b. >>> 5 % 2 # 5 n'est pas un multiple de 21>>> 8 % 2 # 8 est un multiple de 20>>> À vous de jouer Je pense vous avoir donné tous les éléments nécessaires pour réussir. À mon avis, le plus difficile est la phase de réflexion qui précède la composition du programme. Si vous avez du mal à réaliser cette opération, passez à la correction et étudiez-la soigneusement. Sinon, on se retrouve à la section suivante. Bonne chance ! Correction C'est l'heure de comparer nos méthodes et, avant de vous divulguer le code de ma solution, je vous précise qu'elle est loin d'être la seule possible. Vous pouvez très bien avoir trouvé quelque chose de différent mais qui fonctionne tout aussi bien. Attention… la voiiiciiiiiii… # Programme testant si une année, saisie par l'utilisateur, # est bissextile ou non annee = input("Saisissez une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre bissextile = False # On crée un booléen qui vaut vrai ou faux # selon que l'année est bissextile ou non if annee % 400 == 0: bissextile = True elif annee % 100 == 0: bissextile = False elif annee % 4 == 0: bissextile = True else: bissextile = False if bissextile: # Si l'année est bissextile print("L'année saisie est bissextile.") else: print("L'année saisie n'est pas bissextile.") Je vous rappelle que vous pouvez enregistrer vos codes dans des fichiers afin de les exécuter. Je vous renvoie au chapitre sur l'écriture de code Python dans des fichiers pour plus d'informations. Je pense que le code est assez clair, reste à expliciter l'enchaînement des conditions. Vous remarquerez qu'on a inversé le problème. On teste en effet d'abord si l'année est un multiple de 400, ensuite si c'est un multiple de 100, et enfin si c'est un multiple de 4. En effet, le elif garantit que, si annee est un multiple de 100, ce n'est pas un multiple de 400 (car le cas a été traité au-dessus). De cette façon, on s'assure que tous les cas sont gérés. Vous pouvez faire des essais avec plusieurs années et vous rendre compte si le programme a raison ou pas. Un peu d'optimisation Ce qu'on a fait était bien mais on peut l'améliorer. D'ailleurs, vous vous rendrez compte que c'est presque toujours le cas. Ici, il s'agit bien entendu de notre condition, que je vais passer au crible afin d'en construire une plus courte et plus logique, si possible. On peut parler d'optimisation dans ce cas, même si l'optimisation intègre aussi et surtout les ressources consommées par votre application, en vue de diminuer ces ressources et d'améliorer la rapidité de l'application. Mais, pour une petite application comme celle-ci, je ne pense pas qu'on perdra du temps sur l'optimisation du temps d'exécution. Le premier détail que vous auriez pu remarquer, c'est que le else de fin est inutile. En effet, la variable bissextile vaut par défaut False et conserve donc cette valeur si le cas n'est pas traité (ici, quand l'année n'est ni un multiple de 400, ni un multiple de 100, ni un multiple de 4). Ensuite, il apparaît que nous pouvons faire un grand ménage dans notre condition car les deux seuls cas correspondant à une année bissextile sont « si l'année est un multiple de 400 »ou « si l'année est un multiple de 4 mais pas de 100 ». Le prédicat correspondant est un peu délicat, il fait appel aux priorités des parenthèses. Je ne m'attendais pas que vous le trouviez tout seuls mais je souhaite que vous le compreniez bien à présent. # Programme testant si une année, saisie par l'utilisateur, est bissextile ou non annee = input("Saisissez une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0): print("L'année saisie est bissextile.") else: print("L'année saisie n'est pas bissextile.") Du coup, on n'a plus besoin de la variable bissextile, c'est déjà cela de gagné. Nous sommes passés de 16 lignes de code à seulement 7 (sans compter les commentaires et les sauts de ligne) ce qui n'est pas rien. En résumé Les conditions permettent d'exécuter certaines instructions dans certains cas, d'autres instructions dans un autre cas. Les conditions sont marquées par les mot-clés if(« si »),elif(« sinon si ») etelse(« sinon »). Les mot-clés ifetelifdoivent être suivis d'un test (appelé aussi prédicat). Les booléens sont des données soit vraies ( True) soit fausses (False).
A few days ago, I wrote an article on how to use your home computer to get past internet restrictions with SSH but I didn't cover the aspect of the computer running the SSH sever not having a static IP. So here is how to use DynDNS hostname for your dynamic IP. The first thing you need to do is create an https://dyndns.com/ account and then go to My account > My hosts > add a dynamic dns and pick some hostname such as myhomepc.homelinux.com or whatever you want. This will point to your current IP but if your IP is dynamic, it will change so we need to update this info in DynDNS automatically. For this, we'll create a script in your /etc/cron.hourly/ folder: There are 2 different versions for this script: bash and python, use whichever you want from below, but make sure the file name is dyndns without extension (no .py) because the scripts in cron.hourly won't run if they have an extension: The first thing you need to do is create an https://dyndns.com/ account and then go to My account > My hosts > add a dynamic dns and pick some hostname such as myhomepc.homelinux.com or whatever you want. This will point to your current IP but if your IP is dynamic, it will change so we need to update this info in DynDNS automatically. For this, we'll create a script in your /etc/cron.hourly/ folder: sudo gedit /etc/cron.hourly/dyndns There are 2 different versions for this script: bash and python, use whichever you want from below, but make sure the file name is dyndns without extension (no .py) because the scripts in cron.hourly won't run if they have an extension: 1. BASH: #!/bin/bash # Set the username and password for the dyndns account USERNAME= PASSWORD= # Set the system being used to either static or dynamic DNS SYSTEM=dyndns # Set the hostname for the record to change DYNHOST= # Set whether to wildcard the DNS entry, i.e. *.$DYNHOST WILDCARD=OFF ############################################ ## DO NOT EDIT ANYTHING BEYOND THIS POINT ## ############################################ if [ -z "$DYNDNS" ]; then DYNDNS="$DYNHOST" fi if [ -z "$DNSWILD"]; then DNSWILD="$WILDCARD" fi LOOKUP=`host $DYNHOST | awk '{print $4}'` MYIP=`curl -s http://www.ipchicken.com | awk '/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/ {print $1}'` # Do the work if [ "$LOOKUP" = "$MYIP" ]; then echo "No change in DNS entry." else echo `lynx -auth=${USERNAME}:${PASSWORD} -source "http://members.dyndns.org:8245/nic/update?system=${SYSTEM}&hostname=${DYNDNS}&myip=${MYIP}&wildcard=${DNSWILD}"` fi Next to "USERNAME=" and "PASSWORD=", fill in your DynDNS username and password and save the file. 2. Python: #!/usr/bin/env python import os import socket import urllib import urllib2 import re #Put your own username, password and dynhost name here. username='your_user_name' password='your_password' dynhost='yourdomain.whatever.com' system='dyndns' wildcard='OFF' ############################################ ## DO NOT EDIT ANYTHING BEYOND THIS POINT ## ############################################ print '\nDyndns.org updater is running!!!\n' #Find out what dynamic IP is currently set to. lookup=socket.gethostbyname(dynhost) print 'DynDNS is set to' , lookup #Find out what external IP really is. ipchicken = urllib2.urlopen('http://www.ipchicken.com') chicken = ipchicken.read(10000000) ipchicken.close() rawstr = r"""[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*""" #regex for an IP address myip_obj = re.search(rawstr, chicken) myip = myip_obj.group() print 'Your actual IP is' , myip #Compare those IPs if lookup == myip : print 'No change in DNS entry.' else: #change the DNS entry data = {} data['system'] = system data['hostname'] = dynhost data['wildcard'] = wildcard data['myip'] = myip url_values = urllib.urlencode(data) url = 'http://members.dyndns.org:8245/nic/update' full_url = url + '?' + url_values # create a password manager for loging into dyndns.org password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. password_mgr.add_password(None, url, username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # use the opener to fetch a URL opener.open(full_url) print "DNS updated." Don't forget to 'your_user_name', 'your_password' and 'yourdomain.whatever.com' with your info. Doesn't matter which script you choose from above, now you must make the script executable by running the following command: From now on you can login to your ssh server with ssh user@myhomepc.homelinux.net (or whatever hostname you choose when you set this up - in the beginning of the post). Even if your ISP changes your IP address while you are away, your IP will be updated to DyDNS hourly. Credits: celticmonkey user @ubuntuforums.org. Doesn't matter which script you choose from above, now you must make the script executable by running the following command: chmod a+x /etc/cron.hourly/dyndns From now on you can login to your ssh server with ssh user@myhomepc.homelinux.net (or whatever hostname you choose when you set this up - in the beginning of the post). Even if your ISP changes your IP address while you are away, your IP will be updated to DyDNS hourly. Credits: celticmonkey user @ubuntuforums.org.
tonyo Lancer un petit son en Python Salut, je voudrais modifier le desklet mailer (adesklet) pour qu'il joue un petit son lorsqu'un nouveau message est arrivé. J'ai vu dans le code du desklet qu'il y a un petit script "beep.sh" qui est lancé quand un message est arrivé (mais je ne suis pas sur... ) Donc peut-être, éventuellement il serait possible d'utiliser ce script ".sh" pour lancer un petit son ? Qu'en pensez-vous ? tonyo Hors ligne Anbreizh Re : Lancer un petit son en Python Normalement oui ! Avec un script bash tu peux facilement lance un son (la commande est ogg123 je crois ......) Il suffit que tu ouvre ce script et que tu modife le chemin d'acces au son ! "C'est le devoir de chaque homme de rendre au monde au moins autant qu'il en a reçu" Albert Einstein Pour votre webcam : http://projet.jbtheou.fr Mon site web (Mathématique, physique, science et service de publication ) http://jbtheou.fr Hors ligne tonyo Re : Lancer un petit son en Python Bonjour, j'ai un peu de temps pour me repencher sur le problème. Alors voila ce que j'ai dans mon fichier beep.sh : #!/bin/sh # play question.wav Lorsque je lance depuis une console via un ./beep.sh, le son est joué, et c'est marqué "playing question.wav". Malheureusement, lorsque je recois de nouveaux messages, rien ne se passe. Alors je me demande si le script est bien lancé par le desklet mailer... mais comment le vérifier ?? Voila le bout de code où est lancé le script : def alarm(self): """ Refresh the display as needed """ self.block() mail = self.mailer() self._display() if mail > self.mailer.last_size and mail>0: if self.config['program_on_new']: self._execute(join(self.basedir, self.config['program_on_new'])) self.unblock() et la fonction _execute() est définie ainsi : def _execute(self,command): spawnlp(P_NOWAIT, command.split()[0], *command.split()) Quelqu'un a une idée pour faire jouer ce son du problème qui se pose ? merci d'avance Hors ligne
This project is archived and is in readonly mode. psycopg2.connect fails when using spaces in password-keyword Reported by Martijn Bastiaan | January 2nd, 2012 @ 10:31 PM Hi all, Psycopg2 fails when trying to authenticate with spaces in a password. The following code illustrates the problem: >>> import psycopg2 >>> psycopg2.connect(database='amcat', host='localhost', user='martijn', port='5433', password='foo baar') Traceback (most recent call last): File "<stdin>", line 1, in <module> psycopg2.OperationalError: missing "=" after "test" in connection info string I've submitted a very simple patch, which resolves the problem, but introduces another problem: the object returned shows part of the password. >>> psycopg2.connect(**params) <connection object at 0x2449710; dsn: 'dbname=amcat host=localhost port=5433 user=martijn password=xxxxx baar', closed: 0> I'm unable to locate the relevant lines. If anyone could point me in the right direction, I'd be more than happy to fix the that part too. Kind regards, Martijn Create your profile Help contribute to this project by taking a few moments to create your personal profile. Create your profile » WARNING: the informations in this tracker are archived. Please submit new tickets or comments to the new tracker. Psycopg is the most used PostgreSQL adapter for the Python programming language. At the core it fully implements the Python DB API 2.0 specifications. Several extensions allow access to many of the features offered by PostgreSQL.
doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Ce que j'ai vu sur Internet, c'est l'annulaire, mais ça me semble étrange quand je pose mes doigts sur le clavier. Pour ma part, j'utilise surtout Alt Gr avec le @ et naturellement, c'est mon pouce qui se pose sur Alt gr et mon index sur @ (placé sous le 0). Mon responsable a la même idée que moi. Pour la touche Shift et la touche CTRL, j'utilise surtout l'annulaire (et parfois le majeur) en combinaison avec les lettres, mais je crois que l'auriculaire est préférable. Si ça vous semble cohérent, je ferai le changement sur mon fichier svg et les images du picasaweb. Hors ligne lavievit Re : Faire une animation sur la création de jeux vidéo libres Ce que vous proposez Doudoulolita me semble plus cohérent que ce que je vois et lis sur Internet. La position de l'auriculaire facilite les déplacements, plus que l'annulaire qui est moins souple. À ce jour, j'ai changé le clavier pour chaque touche dans Méli-mémo, de même pour Boite aux lettres, j'ai retravaillé des images dans le jeu de pairage et embellit les pages-titres. Je n'arrive pas encore à bâtir une nouvelle île. Je ne sais pas par où commencer. En attendant d'y voir clair je retravaille les jeux pour l'île 2. la vie commune-ô-terre Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres J'ai potassé un peu plus en détails le tutoriel de Renpy (traduit en français sur le site de Jnavigue) et vu qu'on pouvait insérer des jeux pygame dans les programmes réalisés avec Renpy, grâce à Renpygame. Avis aux connaisseurs ! Ce que je ne sais pas encore, c'est si Jnavigue utilise cette possibilité. Pour l'instant, je vais tester un peu plus les possibilités de Renpy avant de me lancer dans mon idée de jeu pour Jnavigue: - plan d'une maison puis d'une ville en fond - donner un endroit où se rendre par oral (son) ou par écrit. - L'utilisateur doit se rendre à cet endroit grâce aux flèches du pavé directionnel. C'est un peu comme les labyrinthes de Gcompris, mais pour quelqu'un qui apprend le français, il doit reconnaître le nom du lieu et éventuellement le trajet à suivre. Dernière modification par doudoulolita (Le 18/11/2011, à 21:44) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Par rapport à Gcompris, j'ai proposé à son créateur Bruno Coudoin une idée de jeu et il m'a demandé d'essayer de le réaliser. Cette idée vient des institutrices de maternelles qui viennent avec leur classe faire de l'informatique: un jeu des intrus. J'avais fait une version très simple pour Tuxpaint. Sur un décor, on doit positionner des animaux qui correspondent à l'environnement et effacer ceux qui ne collent pas à l'endroit (campagne, mer, montagne, ferme, savane, etc.). Sur Gcompris, un jeu correspond vaguement à ça, ça s'appelle babyshapes. C'est une peinture sur laquelle il y a des éléments en blanc (ou des formes en couleurs) et l'enfant doit recomposer l'image avec les morceaux placés sur le côté. Voilà mon premier essai basé sur babyshapes : intruders-activity.zip mais ça ne marche pas encore. On placera les animaux au bon emplacement, et ceux qui ne "collent" pas à l'ambiance iront dans un cadre rouge: Le décor est de moi et les animaux des tampons de Tuxpaint, tout simplement. Au départ du jeu, il n'y a que le background et éventuellement des points de placement (ronds rouge et noirs), les animaux sont à gauche dans un cartouche à part (non visible ici). Dernière modification par doudoulolita (Le 18/11/2011, à 22:00) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres J'ai réalisé un mini-jeu avec Renpy: maison.zip Les images proviennent de wikimedia commons ( http://www.alentours.com/propositions_u … images.txt ) J'ai réussi quelques manipulations d'images simples + leur placement exact. Ceci coupe l'image en deux et la place à droite de l'écran: image facade1 base = "facade.jpg" image facade1 droite = im.Crop("facade.jpg",512, 0, 512, 768) show facade1 droite at Position(xpos=.5, xanchor=0, yalign=0) Ceci réduit la taille de l'image et la positionne un peu vers la droite, en bas: image chambre base = "chambre.jpg" image chambre scale = im.Scale("chambre.jpg", 533, 400) show chambre scale at Position(xpos=600, xanchor=.5, ypos=1.0, yanchor=1.0) J'ai aussi utilisé une ou deux variables pour éviter de répéter certaines chaines de caractères et bien sûr les menus pour le choix des jeux. Pour l'utilisation de texte inséré par l'utilisateur, avec un contrôle simple (if ... else), j'ai un peu tatonné: #définit et initie la variable pour donner la couleur init: $ nomcouleur = "" $ couleur = DynamicCharacter("nomcouleur", color=(192, 64, 64, 255)) label chambre_couleur: # On demande à l'utilisateur de rentrer du texte $nomcouleur = renpy.input("Quelle est la couleur du mur ? \nEcris la réponse.") or "Blanc" couleur "Tu as écrit : \nLe mur est [nomcouleur]." #on vérifie la réponse if nomcouleur == "rouge" or nomcouleur == "ROUGE": "Bravo !" jump chambre_lampe else: "[faux]" jump chambre_couleur En particulier, cet exemple ne fonctionnait pas sans que je sache pourquoi: #pov "My name is %(povname)s." pov "Mon nom est %(povname)s." J'ai mis à la place la variable nomcouleur entre crochets. Le fait de ne pas avoir le code directement dans le tutoriel pour l'interaction utilisateur m'a un peu perturbé. Pas toujours facile de trouver ce qu'on cherche au sein des fichiers de demo contenus dans le repertoire game du tutoriel. Mais j'avance doucement mais surement et espère arriver à faire vraiment ce que je veux prochainement. Dernière modification par doudoulolita (Le 19/11/2011, à 21:21) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Retour sur pygame pour un essai très simple mais que je n'ai pas réussi à mettre en oeuvre. Je veux récupérer une donnée dans un fichier xml nommé coords.xml. J'ai fait au plus simple pour mon test: <?xml version="1.0" encoding="UTF-8"?> <image>"arriereplan.jpg"</image> Le but est de l'utiliser dans cette ligne de code de mon fichier pour ensuite pouvoir l'afficher: # charge les images arriereplan = pygame.image.load(image).convert() J'ai vu que dans USF, cette opération se faisait avec from xml.etree import ElementTree Mon idée était la suivante (en me basant sur docs.python.org - The ElementTree XML API): source = "coords.xml" image = xml.etree.ElementTree.parse(source, parser=None) print image Je reçois ceci dans la console: NameError: name 'xml' is not defined J'ai essayé de remplacer xml par différents noms, ça refuse les strings et les integers Je suppose que je dois faire une classe pour pouvoir l'utiliser mais tous les exemples que j'ai trouvés étaient beaucoup plus complexe que le mien et je ne comprenais pas le principe. J'ai trouvé une fonction simple dans usf > level.py mais elle fait appel à d'autres fichiers d'USF, pour CONFIG: CONFIG = Config() # en haut du fichier def get_xml(levelname): ''' return xml tree of the level ''' return ElementTree.ElementTree( None, os.path.join( CONFIG.sys_data_dir, 'levels', levelname, 'level.xml')) Si j'essaie ceci: source = "coords.xml" image = ElementTree.ElementTree(None, source) print image j'obtiens cela: <xml.etree.ElementTree.ElementTree instance at 0x8962e8c> Traceback (most recent call last): File "essai_avec_xml.py", line 24, in <module> arriereplan = pygame.image.load(image).convert() pygame.error: Can't seek in this data source Il y a du mieux car la fenêtre s'ouvre mais cela affiche un écran noir, bien sûr. Si je dois réaliser une classe, j'aimerais qu'elle soit très, très simple pour que je pige bien son utilisation. Dernière modification par doudoulolita (Le 20/11/2011, à 17:40) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres Hum, alors oui, le parsing de xml c'est un peu plus complexe que ce que t'as vu jusque là. Y'a plusieurs méthodes et plusieurs bibliotèques, dans USF j'utilise ElementTree, qui te renvois un objet dans lequel tu peux faire des recherches par tags, et lire les propriétés associées, il y a xpath, lxml et d'autres méthodes avec toutes leurs façons différentes de traiter le xml (et donc avantages et inconvénients). En gros, avec ElementTree, j'utilise get_xml juste pour m'aider, l'important, c'est que je récupère un objet que j'appelle "xml", c'est dans cet objet que je fais mes recherches d'éléments, et que je construit mon niveau. pour simplifier un peu # récupération de l'objet de type xml xml = return ElementTree.ElementTree(None, nom_du_fichier) # le xml est est arbre, il a donc une racine, qui est un élément unique, avec des enfants, on récupère les attributs de la racine attribs = xml.getroot().attrib # le nom du niveau est l'un de ces attributs, qui sont stoqués dans un dictionnaire self.name = attribs['name'] <?xml version="1.0" encoding="UTF-8"?> <map name="Big level" background="biglevel-background.png" foreground="biglevel-foreground.png" middle="biglevel-middle.png" margins="750,750,750,750" > ici map est le noeud racine, tous ses attributs sont entre "<map" et le premier signe ">", les enfants sont tout ce qui est entre ce ">" et le "</map>" correspondant. name est donc ici "Big Level" Un exemple simple pour comprendre comment je traite les enfants (:P) se trouve dans "load_entrypoints", à qui l'on passe le xml, c'est découpé dans un soucis de clareté, mais tous les "load_" pourrait bien etre remplacé par leur code, les uns à la suite des autres, c'était le cas au début, d'ailleurs. # initialisation des entrypoints en une liste vide self.entrypoints = [] # on demande à notre objet xml tous les enfants de type 'entry-point' et on boucle dessus. for point in xml.findall('entry-point'): # les enfants sont des noeuds, comme la racine, donc on demande leurs attributs de la meme façon. coords = point.attrib['coords'].split(' ') # on utilise les coordonées pour construire un point self.entrypoints.append([int(coords[0]), int(coords[1])]) en gros, entre attrib, et find_all, tu fais un peu tous les traitements de base. Dernière modification par tshirtman (Le 20/11/2011, à 17:26) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres De mon côté, j'ai regardé en détail les fichiers level.py et retravaillé mon fichier et ça marche !coords.xml est maintenant dans un dossier nommé essai et est composé ainsi: <?xml version="1.0" encoding="UTF-8"?> <map name="essai" background="arriereplan.jpg"> </map> Dans mon fichier principal (en .py), voici ce que j'ai fait: # nom du niveau niveau = "essai" # recherche du fichier xml def get_xml(niveau): ''' return xml tree of the level ''' return ElementTree.ElementTree( None, os.path.join( niveau, 'coords.xml')) # définition de l'objet xml xml = get_xml(niveau) # récupération des attributs du fichier xml attribs = xml.getroot().attrib # création d'un dictionnaire background = attribs['background'] print background #Plus loin: arriereplan = pygame.image.load(background).convert() # dans la boucle: screen.blit(arriereplan, (0, 0)) Si je faisais une classe, ce serait en fait pour avoir plusieurs niveaux différents et ne pas avoir à redéfinir la variable à chaque fois, c'est bien ça ? Je peux aussi utiliser l'interaction avec l'utilisateut pour qu'il me dise dans quel dossier je dois trouver coords.xml, sachant que le nom du dossier correspond à name dans le fichier xml. Dernière modification par doudoulolita (Le 20/11/2011, à 18:03) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres Une classe c'est plus un moyen de regrouper plusieurs données ensemble, et les méthodes permettant de les manipuler avec. L'exemple qu'on donne en général est celui d'une voiture, tu pourrais tout à fais considérer la vitesse de la voiture, sa direction, et ses coordonnées, comme des variables séparées, et des fonctions démarrer_voiture, tourner_voiture, etc pour la gérer, avec une classe, on regroupe tout ça dans un "lot" cohérent indépendant du reste, une voiture, avec une vitesse, une direction, des coordonées, et une méthode de démarrage, une méthode pour tourner, dans les programmes complexes, ça permet de segmenter la logique, et donc de plus facilement appréhender la complexité. Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Suite à une séance avec les maternelles où nous avons visité le site de l'expo Paul Klee à la Cité de la Musique (Paris), j'ai pensé que faire des niveaux pour USF inspirés de grands peintres serait sympa. Beaucoup sont dans le domaine public, donc ça ne devrait pas être trop compliqué d'avoir des images de bases. Sinon, on peut juste faire "à la manière de" ou reprendre la palette de couleurs, par exemple. Le logiciel Gcompris utilise des tableaux de Degas, Michel-Ange ou Renoir pour ses puzzles par exemple. Dans le genre peintre, on pourrait avoir des combats au pinceau où les persos changent progressivement de couleurs quand ils sont touchés, mais je crois que Disney a fait un jeu avec les couleurs (+ de vieux cartoons en N/B), déjà, non ? Dernière modification par doudoulolita (Le 26/11/2011, à 16:21) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Pour Jnavigue, il y a plein d'images de clavier. Les originaux sont en QWERTY et j'ai réalisé une version AZERTY. A l'heure actuelle, nous avons nommé suivant cet exemple: clavier_qwerty_e.png et clavier_azerty_e.png pour la lettre E Est-ce pratique ou faudrait-il plutôt mettre chacun dans un dossier qwerty et un dossier azerty en nommant les images de manière identique à l'intérieur des dossiers ? On aurait juste ainsi le même nom: clavier_e.png et on indiquerait le dossier dans le code suivant la version de l'utilisateur. Si on garde notre façon actuelle de nommer les images, est-ce qu'il y a une ruse pour simplifier le code (en ayant une partie du nom de l'image comme variable) au lieu de tout changer d'une version à l'autre ? Comment le faire ? rappel : Renpy définit les images avec image sylvie smile = "sylvie_smile.png"image sylvie surprised = "sylvie_surprised.png" et les affiche avec show sylvie smileshow sylvie surprised on peut introduire des variables et du code python sans souci. Exemple: label start: $ bl_game = False label hentai: $ bl_game = True m "Why it's a game..." if bl_game: "Well, apart from that boy's love game she insisted on making." Voir Quickstart pour plus de détail Dernière modification par doudoulolita (Le 29/11/2011, à 12:46) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres J'avais envie de faire une image de maison (ou au moins de chambre en 3D pour Jnavigue mais il me faudra baucoup d'éléments. J'ai trouvé un tabouret et des éléments à mettre sur une table sur blenderstuff.org. OpenClipart m'a aussi été conseillé par la créatrice de Jnavigue mais j'ai trouvé des fichiers svg et non des .blend. J'aimerais trouver encore d'autres modèles en rapport avec la vie quotidienne. Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Je travaille de nouveau sur mon jeu des intrus pour Gcompris: intruders-activity Je me suis basée sur une activité existante: babyshapes, elle-même basée sur le plugin shapegame. La démarche (pas réussie jusqu'au bout à l'heure actuelle) est la suivante: il faut d'abord récupérer la version de développement: git clone git://git.gnome.org/gcompris cd gcompris sh autogen.sh && make Ensuite, j'ai copié le dossier src>babyshapes-activity comme modèle. Après, j'ai suivi la doc Adding an activity J'ai réussi à ajouter mon dossier (retravaillé avec mes images et mes fichiers xml) mais il ne faut pas oublier de recompiler avec sh autogen.sh avant de faire make ./runit.sh intruders-activity La doc oublie de dire qu'il faut avoir gnome-common installé et ne précise pas quand on est dans le dossier gcompris ou dans le dossier src. Je n'ai pas encore réussi à lancer l'activité, le jeu commence à se lancer (il y a du mieux car au début rien ne venait) mais ne trouve pas le plugin, semble-t-il. La liste de diffusion de Gcompris est fort bien animée par Bruno Caudoin mais la doc des développeurs n'est pas super claire ni ultra-précise. Pour l'instant, je n'ai pas trouvé de topic de forum sur Ubuntu (ou ailleurs) pour plus d'aide sur Gcompris et l'ajout d'une activité. Les topics sont surtout sur les problèmes d'installation, dirait-on. Dernière modification par doudoulolita (Le 08/12/2011, à 13:44) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Les maternelles s'intéressent de près à USF et je souhaite en profiter pour faire une discussion sur les jeux de baston (réels et virtuels) qui leur plaisent tant. Un biais serait de faire créer un décor pour le jeu. J'ai fait un essai avec Tuxpaint, nommé tuxy. Il n'y a pas de fond transparent dans Tuxpaint, il faut passer par le filtre couleurs > couleur vers alpha de Gimp pour rendre le blanc transparent, c'est un peu ennuyeux pour tout faire en une seule séance. J'ai préparé quelques plateformes et fichiers xml à l'avance. Les plateformes peuvent être dessinées sous forme de carré vide à remplir avec des tampons personnalisés, les formes, des coups de pinceau... L'important serait qu'il n'y ait pas de blanc dans les éléments pour pouvoir utiliser le filtre de Gimp. On peut en tout cas faire faire le fond et l'insérer sous des plateformes déjà préparées, avec le code xml nécessaire. Il faut aussi faire le screenshot (que j'ai failli oublier !) en glissant les calques un par un dans Gimp, et renommer les fichiers. Dernière modification par doudoulolita (Le 03/12/2011, à 14:48) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Voici un autre essai avec la baguette magique et les tampons de Tuxpaint: tuxy2 Ici encore, les enfants créeraient juste le fond. On voit que si les enfants font les plateformes (middle.png) avec les tampons de Tuxpaint, il n'est pas très simple de rendre le fond transparent car certains tampons comportent du blanc ou n'ont pas des formes rectangulaires. Heureusement, les maternelles ne seront pas très exigeants sur la qualité des hardshapes... J'ai mis dans le dossier "source" le template qui permettrait aux instituteurs (ou à des enfants plus grands avec Gimp ou Inkscape) de créer d'autres plateformes pour ce niveau. Conseil : Pour ne pas avoir de problèmes de transparence, utiliser directement les tampons trouvés dans /usr/share/tuxpaint/stamps (sous Ubuntu) et les copier-coller dans un autre dossier pour les utiliser dans Gimp. Un redimensionnement précis est alors possible avec l'outil de mise à l'échelle de Gimp L'idéal serait de créer des tampons rectangulaires aux textures variées pouvant servir de plateformes, et d'ouvrir le template dans Tuxpaint pour bien placer les tampons. Des templates avec le contour des formes à tamponner très précisément pourraient être utiles (avec le point central permettant de savoir où cliquer). Dernière modification par doudoulolita (Le 03/12/2011, à 16:48) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres On peut maintenant repeindre sa chambre et changer la déco de la cuisine, à condition de bien écrire les mots... L'objectif sera de savoir écrire le nom des couleurs d'une part et de savoir recopier le nom des formes (destiné aux enfants ou adultes qui apprennent le français et l'informatique). Petit souci : Quand j'écris les réponses dans mon jeu, c'est très lent à s'afficher. Je ne sais pas d'où ça provient. Sinon, j'ai essayé l'utilisation de variables pour afficher les différentes couleurs de murs de la chambre mais ça ne fonctionne pas comme je le veux. Voici l'état actuel de cette partie du jeu (résumée) # definition des images image chambre rouge = "chambre/chambre_rouge.jpg" image chambre bleue = "chambre/chambre_bleue.jpg" image chambre jaune = "chambre/chambre_jaune.jpg" # l'utilisateur doit écrire le nom de la couleur $nomcouleur = renpy.input("De quelle couleur peins-tu le mur ? \nEcris la réponse.") or "Blanc" # suivant la réponse, on affiche l'une des images if nomcouleur == "rouge" or nomcouleur == "ROUGE": show chambre rouge elif nomcouleur == "jaune" or nomcouleur == "JAUNE": show chambre jaune elif nomcouleur == "bleu" or nomcouleur == "BLEU": show chambre bleue else: "Tu n'as pas cette couleur, recommence !" Ce que j'aimerais, c'est pouvoir écrire show chambre nomcouleur Mais ça n'a pas l'air de fonctionner. Ou peut-être puis-je créer une fonction + un tableau ou un dictionnaire ? Le but est de pouvoir ajouter d'autres couleurs par la suite, bien sûr. Pour l'instant, le choix est un peu réduit! Dernière modification par doudoulolita (Le 04/12/2011, à 02:37) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres couleurs = {'rouge': rouge, 'jaune': jaune, 'bleu': bleu} $nomcouleur = (renpy.input("De quelle couleur peins-tu le mur ? \nEcris la réponse.") or "Blanc").lower() if nomcouleur in couleurs: show chambre couleurs[nomcouleur] else: "Tu n'as pas cette couleur, recommence !" Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Je teste au boulot le jeu que j'ai fait chez moi. 2 soucis dans mon jeu, visibles en faisant un check script (lint): game/cuisine.rpy:53 Could not evaluate 'deco', in the who part of a say statement. game/script.rpy:37 Image peinture texte uses file 'peinture/texte_couleurs.png', which is not loadable. J'ai donc ajouté dans script.rpy: $ deco = DynamicCharacter("nomdeco", color=(192, 64, 64, 255)) et changé dans cuisine.rpy: scene bg cuisine show deco choix at Position(xalign=0, yalign=0) $nomdeco = renpy.input("Quelle décoration veux-tu ? \nRecopie la réponse en capitales.") or "Blanc" #on vérifie la réponse if nomdeco == "LES CARRÉS": show deco carres at Position(xalign=0, yalign=0) deco "Tu as choisi [nomdeco]." jump vrai elif nomdeco == "LES CARRES": deco "Tu as choisi [nomdeco] mais tu as oublié l'accent sur le E.\nRecommence !" jump cuisine_deco elif nomdeco == "LES CARRE" or nomdeco == "LES CARRÉ": deco "Tu as choisi [nomdeco] mais tu as oublié de les mettre au pluriel.\nRecommence !" jump cuisine_deco elif nomdeco == "les carrés": deco "Tu as choisi [nomdeco] mais tu as oublié de les mettre en capitales.\nRecommence !" jump cuisine_deco elif nomdeco == "LES LOSANGES": show deco losanges at Position(xalign=0, yalign=0) deco "Tu as choisi [nomdeco]." jump vrai elif nomdeco == "LES LOSANGE": deco "Tu as choisi [nomdeco] mais tu as oublié de les mettre au pluriel.\nRecommence !" jump cuisine_deco elif nomdeco == "les losanges": deco "Tu as choisi [nomdeco] mais tu as oublié de les mettre en capitales.\nRecommence !" jump cuisine_deco else: "[faux]" jump cuisine_deco Pour l'image texte_couleurs.png, je l'ai quelque part mais ai oublié de la mettre dans le bon dossier ! Il suffit d'enlever dans script.py: image peinture texte = "peinture/texte_couleurs.png" Ca ne sert pas à grand chose en fait. Dernière modification par doudoulolita (Le 05/12/2011, à 14:30) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Une fois tout ça corrigé, j'ai utilisé build distributions (dans le menu de renpy) sur mon jeu et voici le résultat actuel: maison-all.zip Ce n'est pas encore un chef d'oeuvre mais je crois qu'il y a des idées à développer. Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres couleurs = {'rouge': rouge, 'jaune': jaune, 'bleu': bleu} $nomcouleur = (renpy.input("De quelle couleur peins-tu le mur ? \nEcris la réponse.") or "Blanc").lower() if nomcouleur in couleurs: show chambre couleurs[nomcouleur] else: "Tu n'as pas cette couleur, recommence !" Dernière modification par doudoulolita (Le 05/12/2011, à 16:44) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Pour le jeu maison, j'ai réussi à utiliser la fonction renpy.image() python: for piece in ['chambre']: for couleur in ['blanche', 'rouge', 'bleue', 'jaune']: renpy.image((piece, couleur), "chambre/%s_%s.jpg" % (piece, couleur)) Je crois que je vais plus galérer pour renpy.show car l'exemple n'est pas aussi évident à adapter à mon jeu. Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Finalement, ce n'est pas très compliqué pour repeindre le mur avec python $nomcouleur = renpy.input("De quelle couleur peins-tu le mur ? \nEcris la réponse.") or "Blanc" python: couleurchambre = {'rouge': 'chambre rouge', 'jaune': 'chambre jaune', 'bleu': 'chambre bleue', 'bleue': 'chambre bleue'} if nomcouleur in couleurchambre: python: renpy.show(couleurchambre[nomcouleur]) J'ai fait de même pour la couleur des pots de peinture en simplifiant le nom de images. Dans script.rpy: python: for pot in ['pot']: for potcouleur in ['rouge', 'bleu', 'jaune']: renpy.image((pot, potcouleur), "peinture/%s_%s.png" % (pot, potcouleur)) dans chambre.rpy (dans label chambre_couleurs): python: couleurpot = {'rouge': 'pot rouge', 'jaune': 'pot jaune', 'bleu': 'pot bleu', 'bleue':'pot bleu'} # plus loin python: renpy.show(couleurpot[nomcouleur]) On ne peut pas indiquer la position de l'image avec at Position mais l'image se replace à la même position que pot couleurs, donc pas de souci. Télécharger maison-all.zip Dernière modification par doudoulolita (Le 08/12/2011, à 13:22) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres Finalement, ce n'est pas très compliqué pour repeindre le mur avec python $nomcouleur = renpy.input("De quelle couleur peins-tu le mur ? \nEcris la réponse.") or "Blanc" python: couleurchambre = {'rouge': 'chambre rouge', 'jaune': 'chambre jaune', 'bleu': 'chambre bleue', 'bleue': 'chambre bleue'} if nomcouleur in couleurchambre: python: renpy.show(couleurchambre[nomcouleur]) hum, du coup tu peux faire plus simple $nomcouleur = renpy.input("De quelle couleur peins-tu le mur ? \nEcris la réponse.") or "Blanc" python: couleurchambre = ['rouge', 'jaune', 'bleu', 'bleue'] if nomcouleur in couleurchambre: python: renpy.show('chambre ' + nomcouleur) et pareil pour le reste... Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Mon script ne marche pas, il ne veut pas tenir compte du clavier. Les fonctions de déplacement, elles, fonctionnent si on les teste une à une. Dernière modification par doudoulolita (Le 20/01/2012, à 00:55) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres En attendant la solution à mon problème précédent : ville.zip est le début d'un jeu avec Renpy qui aidera les gens qui souhaitent apprendre le français, sur le thème de la ville. Chaque lieu correspond à une des maisons de la carte ci-dessus. Chaque dossier contient une image avec 4 propositions (de mots ou groupes de mots), une autre image où les textes sont mis en valeur et une grande image contenant la réponse. J'ai aussi mis les images du jeu sur picasaweb. --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Chaque dossier aborde plus ou moins un problème de grammaire ou d'orthographe différent, comme le pluriel, le choix d'un pronom féminin ou masculin, etc... banque: pronom "le" ou "la", distinguer "en" et "an" - distributeur : faire correspondre une somme en toute lettres à des billets ou à des pièces de monnaie (en projet) boulangerie: ordre des lettres, distinguer "an" et "en", "j" et "g", pronom personnel "ma" ou "mon" école: pronom avec apostrophe + accent sur le "E" - éponge: pronom avec apostrophe, distinguer "on" et "an" mairie: distinguer 'ai", "é", "è", "ée" poste: espace entre pronom et nom, distinguer "s", "t", "r" supermarché: pluriel avec pronom idées supplémentaires: 2 à 4 niveaux : moins de monuments et de routes sur les niveaux bas. Mots différents pour chaque lieu ou objet. A cliquer, à recopier ou à écrire (réponse à la question: qu'est ce que c'est ?) chateau : pancartes avec dessin du chateau pour distinguer "o", "au", "eau", "on", "ou" mairie: fiche nom- prénom et finir la phrase: il (elle) s'appelle... Dernière modification par doudoulolita (Le 23/01/2012, à 23:27) Hors ligne
I'm trying to unstack a dataframe perform operations on it (over time only) and then stack it back together like this: import pandas as pd import numpy as np from itertools import * time = pd.date_range(pd.datetime(2007,1,1),pd.datetime(2007,1,2)) slot = map(lambda n:"s-"+str(n),reversed(range(2))) obj = map(lambda n:"o-"+str(n),reversed(range(2))) idx = pd.MultiIndex.from_tuples(list(product(slot, obj, time)), names=['Ananas','Bananas','time']) #list(.) needed to get a length, should this really be needed? data = np.random.rand(len(idx),4) df = pd.DataFrame(data=data,index=idx, columns=['a','b','c','d']) #why is idx.size==0? print df.to_string() print "=====" unstacked = df.unstack(level=[0,1]) print unstacked.to_string() print "=====" stacked = unstacked.stack(level=[2,1]) print stacked.to_string() The problem is that multiindex is getting reversed after the operation, is there any easy way to make this work? Perhaps I'm misusing the stack from the start?
I'm trying to multiply (add/divide/etc.) two dataframes that have different column labels. I'm sure this is possible, but what's the best way to do it? I've tried using rename to change the columns on one df first, but (1) I'd rather not do that and (2) my real data has a multiindex on the columns (where only one layer of the multiindex is differently labeled), and rename seems tricky for that case... So to try and generalize my question, how can I get df1 * df2 using map to define the columns to multiply together? df1 = pd.DataFrame([1,2,3], index=['1', '2', '3'], columns=['a', 'b', 'c']) df2 = pd.DataFrame([4,5,6], index=['1', '2', '3'], columns=['d', 'e', 'f']) map = {'a': 'e', 'b': 'd', 'c': 'f'} df1 * df2 = ?
Introdução web2py[web2py] é um Livre e open-source web framework escrito em Python[python] e programável em Python, para desenvolvimento ágil de aplicações web seguras baseadas em banco de dados. web2py é um framework auto contido, o que significa que ele contém todos os componentes que você precisa para desenvolver completamente aplicações web funcionais. web2py é projetado para orientar um desenvolvedor web a seguir as boas práticas da engenharia de software, tal como a utilização do padrão Model View Controller (MVC). web2py separa a representação dos dados (the model) da apresentação dos dados (the view) e também da lógica de aplicação e do fluxo de trabalho (the controller). web2py fornece bibliotecas para ajudar a criação, implementação, e teste do projeto, cada uma dessas três partes desenvolvidas separadamente, mas trabalhando em conjunto. web2py é construído para ser seguro. Isso significa que ele atende automaticamente muitas das questões que podem levar a vulnerabilidades de segurança, seguindo as práticas bem estabelecidas. Por exemplo, web2py valida todas as entradas (para prevenir injections), escapa todas as saídas (para previvir cross-site scripting), renomeia arquivos enviados (para prevenir ataques de atravessamento de diretórios). web2py cuida das principais questões de segurança, para que os desenvolvedores tenham menos chances de encontrar vulnerabilidades. web2py inclui uma camada de abstração de banco de dados (DAL) que escreve código SQL[sql-w] dinamicamente para que você, o desenvolvedor, não o faça. A DAL sabe como gerar código SQL de forma transparente para SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix], Ingres[ingresdb], e MongoDB[mongodb]. A DAL também pode gerar chamadas de função para o Google Datastore quando estiver rodando no Google App Engine (GAE)[gae]. Experimentalmente suportamos mais bancos de dados e os novos são constantemente adicionados. Por favor verifique no site web2py e na lista de discussão para descobrir adaptadores mais recentes. Uma vez que uma ou mais tabelas do banco de dados estão definidos, web2py gera automaticamente uma interface de administração web-based para acessar os bancos de dados e as tabelas. web2py diferente dos outros web frameworks in that é o único a adotar totalmente o paradigma Web 2.0, onde a web é o computador. De fato, web2py não exige instalação ou configuração; ele funciona em qualquer arquitetura que aceita Python (Unix/Linux, Windows, Windows CE, Mac OS X, e iOS), e tanto o desenvolvimento, quanto a produção, e manutenção da aplicação pode ser feita por uma interface web local ou remota. web2py é executado com CPython (a implementação em C) e PyPy (Python escrito em Python), nas versões 2.5, 2.6, e 2.7, embora "oficialmente" ele só suporta 2.5, para que possamos garantir a compatibilidade com versões anteriores para as aplicações. web2py fornece um sistema de ticketing para eventuais erros. Se um erro ocorrer, um ticket é emitido para o usuário, e o erro é registrado para o administrador. web2py é open source e licenciado sob a versão 3 da licença LGPL. Outra importante característica do web2py é que nós, os desenvolvedores, desejamos manter a compatibilidade com versões anteriores. Isto é feito desde a primeira versão do web2py em outubro de 2007. Novas funcionalidades foram adicionadas e bugs foram corrigidos, mas se um programa trabalhou com web2py 1.0, esse programa vai funcionar ainda melhor hoje. Aqui estão alguns exemplos de declarações web2py que ilustram o seu poder e simplicidade. O seguinte código: db.define_table('person', Field('name'), Field('image', 'upload')) cria uma tabela de banco de dados chamado "pessoa" com dois campos: "Nome", uma string, e "imagem", algo que precisa ser enviado (a imagem real). Se a tabela já existe, mas não corresponde a essa definição, é alterada de forma adequada. Dada a tabela definida acima, o seguinte código: form = SQLFORM(db.person).process() cria um formulário de inserção para esta tabela que permite aos usuários fazer upload de imagens. também valida um formulário submetido, renomeia a imagem carregada de uma forma segura, armazena a imagem em um arquivo, insere o registro correspondente no banco de dados, previne a dupla submissão, e eventualmente, modifica o próprio formulário, adicionando mensagens de erro se os dados enviados pelo usuário não passarem na validação. Este código incorpora um wiki totalmente funcional com as tags, pesquisa, tag cloud, permissões, anexos de mídia e suporte oEmbed: def index(): return auth.wiki() O código a seguir em vez disso: @auth.requires_permission('read','person') def f(): .... evita que os visitantes acessem a função f a menos que o visitante é um membro de um grupo cujos membros têm permissão para ler "read" os registros da tabela pessoa "person". Se o visitante não está logado, ele é direcionado para uma página de login (fornecido por padrão pelo web2py). web2py também suporta componentes, ou seja, ações que podem ser carregados em uma view e interagir com o visitante através de Ajax sem re-carregar a página inteira. Isto é feito através de um LOAD helper que permite um design muito modular de aplicações, que é discutida no capítulo 3, no contexto da wiki e, com algum detalhe, no último capítulo deste livro. Princípios Programação em Python normalmente segue esses princípios básicos: Não se repita - Don't repeat yourself (DRY). Deve haver apenas uma maneira de fazer as coisas. Explicito é melhor que implicito. web2py abrange totalmente os dois primeiros princípios, forçando o desenvolvedor a usar o software de boas práticas de engenharia que desestimulam a repetição de código. web2py orienta o desenvolvedor através de quase todas as tarefas comuns no desenvolvimento de aplicações web (criação e processamento de formulários, gerenciando sessões, cookies, erros, etc.) web2py difere de outros frameworks no que diz respeito ao terceiro princípio, que por vezes conflita com as outras duas. Em particular, web2py não importar aplicativos do usuário, mas executa-los em um contexto pré-definido. This context exposes the Python keywords, as well as the web2py keywords. Para alguns isso pode parecer mágica, mas não deveria. Simplesmente, na prática, alguns módulos já estão importados sem ter que fazer isso. web2py está tentando evitar a característica irritante de outros frameworks que forçam o desenvolvedor para importar os mesmos módulos no topo de cada modelo e controlador. web2py, através da importação de seus próprios módulos, economiza tempo e evita erros, seguindo, assim, o espírito de "não repetir-se" e " deve haver apenas uma forma de fazer as coisas". Se o desenvolvedor deseja usar outros módulos Python ou módulos de terceiros, os módulos devem ser importados explicitamente, como em qualquer outro programa Python. Web frameworks Em seu nível mais fundamental, uma aplicação web é composto de um conjunto de programas (ou funções) que são executadas quando o URL correspondente é visitado. A saída do programa é retornada para o visitante e transmitido pelo browser. O objetivo de frameworks web é permitir que desenvolvedores criem novos aplicativos de forma rápida, fácil e sem erros. Isso é feito por fornecimento de APIs e ferramentas que reduzem e simplificam a quantidade de codificação que é necessária. As duas abordagens clássicas para o desenvolvimento de aplicações web são: O primeiro modelo é o que foi seguido, por exemplo, pelos primeiros scripts CGI. O segundo modelo é seguido, por exemplo por, PHP php : citar (onde o código é em PHP, uma linguagem C-like), ASP (onde o código é em Visual Basic), e JSP (onde o código é em Java). Aqui é um exemplo de um programa para que, quando executado, recupera dados de um banco de dados e retorna uma página HTML que mostra os registros selecionados: <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> O problema com esta abordagem é que o código está incorporado em HTML, mas o mesmo código também precisa gerar HTML adicional e gerar instruções SQL para consultar o banco de dados, emaranhando várias camadas dea aplicação e tornando difícil de ler e manter. A situação é ainda pior para aplicações Ajax , e a complexidade cresce com o número de páginas (arquivos) que compõem a aplicação. A funcionalidade do exemplo acima pode ser expressa em web2py com duas linhas de código Python: def index(): return HTML(BODY(H1('Records'), db().select(db.contacts.ALL))) Neste exemplo simples, a estrutura da página HTML é representada programaticamente a HTML, CORPO e H1 objetos. O banco de dados db é consultado pelo comando select, finalmente, tudo é serializado em HTML. Note que db não é uma palavra, mas uma variável definida pelo usuário. Vamos usar esse nome consistentemente para se referir a uma conexão de banco de dados para evitar confusão. Frameworks web são geralmente classificados como um dos dois tipos: Um framework "glued" é construído pela montagem (colando) diversos componentes de terceiros. Um framework "full-stack" é construído através da criação de componentes projetados especificamente para serem totalmente integrados e trabalharem juntos. web2py é um framework full-stack. Quase todos os seus componentes são construídos a partir do zero e são projetados para trabalhar juntos, mas eles funcionam igualmente bem fora da estrutura completa web2py. Por exemplo, a camada de abstração de banco de dados (DAL) ou a linguagem de template podem ser usados independente do web2py framework,importando gluon.dal ou gluon.template em seus próprios aplicativos Python. gluon é o nome do módulo que contém o web2py bibliotecas do sistema. Algumas bibliotecas web2py, como a construção e processamento de formulários a partir de tabelas de banco de dados, tem dependências em outras partes do web2py. web2py também pode trabalhar com bibliotecas Python de terceiros, incluindo outras linguagens de template e Dals, mas eles não serão tão bem integrados como os componentes originais. Model-View-Controller web2py incentiva o desenvolvedor a representação de dados em separado (model), os dados apresentação (view) e o fluxo de trabalho do aplicativo (controller). Vamos considerar novamente o exemplo anterior e veja como construir uma aplicação web2py em torno dele. Aqui está um exemplo da interface de edição MVC web2py: O fluxo de trabalho típico de um request web2py é descrito no diagrama seguinte: No diagrama: O servidor pode ser o servidor web embutido no web2py ou um servidor de terceiros, como o Apache. O servidor lida com multi-threading. "main" é a principal aplicação WSGI. Ele executa todas as tarefas comuns e envolve aplicativos do usuário. Trata-se de cookies, sessões, transações, encaminhamento e roteamento de URL, e expedição reversa. Ela pode servir e transmitir arquivos estáticos se o servidor web já não está fazendo isso. Os componentes Models, Views e Controller compõe a aplicação do usuário. Múltiplas aplicações podem ser hospedadas na mesma instância de web2py. As setas a tracejado representam a comunicação com o(s) mecanismo(s) de banco de dados. As consultas de banco de dados podem ser escritos em SQL puro (desencorajado) ou usando o web2py camada de abstração de banco de dados (recomendado), de modo que o código do aplicativo web2py não é dependente do mecanismo banco de dados específico. O dispatcher mapeia a URL solicitada para uma chamada de função no controller. A saída da função pode ser uma string ou um dicionário de símbolos (uma tabela hash). Os dados do dicionário são renderizados por uma view. Se o visitante solicita uma página HTML (o padrão), o dicionário é renderizado em uma página HTML. Se o visitante solicita a mesma página em XML, web2py tenta encontrar uma visão que pode renderizar o dicionário em XML. O desenvolvedor pode criar visões para processar páginas em qualquer um dos protocolos já suportados (HTML, XML, JSON, RSS, CSV e RTF) ou em protocolos personalizados adicionais. Todas as chamadas são envolvidas em uma transação, e qualquer exceção não tratada faz com que a transação seja revertida. Se o pedido for bem sucedida, a transação é confirmada. web2py também lida com sessões e cookies de sessão automaticamente, e quando a transação for confirmada, a sessão também é armazenada, a menos que especificado o contrário. É possível registrar tarefas recorrentes (via cron) para ser executado em horários programados e / ou após a conclusão de determinadas ações. Desta forma é possível realizar tarefas longas e intensas em segundo plano sem reduzir a velocidade da navegação. Aqui esta um aplicativo MVC mínimo e completo, que consiste em três arquivos: "db.py" este é o model: db = DAL('sqlite://storage.sqlite') db.define_table('contact', Field('name'), Field('phone')) Ele se conecta ao banco de dados (Neste exemplo uma SQLite database armazenada no arquivo storage.sqlite) e define uma tabela chamada contact. Se a tablela não existe, web2py irá cria-la, transparentimente e em plano de fundo, gerar código SQL no dialeto SQL específico para o mecanismo de base de dados usado. O desenvolvedor pode o ver o código SQL gerado, mas não precisa alterar o código se o back-end de banco de dados, cujo padrão é SQLite, for substituído por MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres, e Google App Engine (SQL e NoSQL). Uma vez que a tabela é definida e criada, web2py também gera uma interface totalmente funcional baseada na Web de administração de banco de dados, chamada ** AppAdmin , para acessar o banco de dados e as tabelas. "default.py" este é o controller: def contacts(): grid=SQLFORM.grid(db.contact, user_signature=False) return locals() Em web2py, URLs são mapeadas para módulos Python e chamadas de função. Neste caso, o controller contem uma única função (ou "action") chamada contacts. Uma action pode retornar uma string (a página da web) ou um dicionário Python (um conjunto de pares key:value ) ou um conjunto de variáveis locais (como no exemplo). Se a função retornar um dicionário, ele é passado para a view com o mesmo nome do controller / função, que por sua vez processa a página. Nesse exemplo, a função contacts gera uma grid que permite select/search/create/update/delete na tabela db.contact e retorna esse grid para a view. "default/contacts.html" esta é a view:** {{extend 'layout.html'}} <h1>Manage My Contacts</h1> {{=grid}} Esta view é chamado automaticamente pelo web2py após a função de controller associada (ação) é executado. O objetivo dessa view é renderizar as variáveis ​​no dicionário retornado (no nosso caso grid) em HTML. O arquivo de view é escrito em HTML, mas ele incorpora código Python delimitado por {{ e }}. Isto é muito diferente do exemplo do código de PHP, porque o único código embutido no HTML é o código da "camada de apresentação". O arquivo "layout.html" referenciado no topo da view é fornecido pelo web2py e constitui o layout básico para todas as aplicações web2py. O arquivo de layout pode facilmente ser modificado ou substituído. Por que web2py? web2py é um dos muitos frameworks de desenvolvimento web, mas tem recursos interessantes e únicos. web2py foi originalmente desenvolvido como uma ferramenta de ensino, com as seguintes motivações primárias: Fácil para os usuários que estão aprendendo desenvolvimento web server-side sem comprometer funcionalidades. Por essa razão web2py não necessita de instalação ou configuração, não possui dependências (exceto pelo próprio código fonte , que requer Python 2.5 e seus módulos da biblioteca padrão), e expõe a maior parte de sua funcionalidade através de uma interface Web, incluindo um ambiente de desenvolvimento integrado com Debugger e interface de banco de dados. web2py tem se mantido estável desde o primeiro dia, pois segue um projeto top-down; i.e., ou seja, a sua API foi projetada antes de ser implementada. Mesmo depois de novas funcionalidades serem adicionadas, web2py nunca quebrou a compatibilidade, e não vai quebrar a compatibilidade quando uma funcionalidade adicional for adicionada no futuro. web2py proativamente aborda as questões de segurança mais importantes que afligem muitas aplicações web modernas,conforme determinado pelo OWASP[owasp]. web2py é leve. Suas bibliotecas centrais, incluindo a camada de abstração de banco de dados, a linguagem de template, e toda a quantidade de helpers tem apenas 1.4MB. O código-fonte inteiro, incluindo aplicações de exemplo e imagens equivale a 10,4 MB. web2py ocupa pouco espaço e é muito rápido. Ele usa o Rocket[rocket]Servidor web WSGI desenvolvido por Timothy Farrell. Ele é tão rápido quanto o Apache com mod_wsgi, e suporta SSL e IPv6. web2py utiliza sintaxe Python para models, controllers e views, mas não importa models e controllers (como todos os outros frameworks Python fazem) - em vez disso os executa. Isso significa que os aplicativos podem ser instalados, desinstalados, e modificado sem a necessidade de reiniciar o servidor web (mesmo em produção), e os diferentes aplicativos podem coexistir sem seus módulos interferindo uns com os outros. web2py usa a Database Abstraction Layer (DAL) ao em vez da Object Relational Mapper (ORM). Do ponto de vista conceitual, isso significa que as diferentes tabelas de banco de dados são mapeados em diferentes instâncias de uma classe Tablee não em diferentes classes, enquanto que os registros são mapeados em instâncias de uma classeRow, não em instâncias da classe tabela correspondente. De um ponto de vista prático, significa que a sintaxe SQL é mapeada quase em um-para-um na sintaxe DAL, e não há nenhuma programação metaclass complexa acontecendo sob o capô como nos ORMs populares, que gostaria de acrescentar latência. Aqui está uma imagem da interface principal do web2py admin: Segurança O Open Web Application Security Project[owasp] (OWASP) é uma comunidade mundial livre e de código aberto focado em melhorar a segurança de aplicações de software. OWASP listou os dez principais problemas de segurança que colocam aplicações web em risco. Essa lista é reproduzida aqui, junto com uma descrição de como cada questão é abordada por web2py: cross site scripting"Cross Site Scripting (XSS): falhas XSS ocorrem sempre que uma aplicação obtém os dados fornecidos pelo usuário e os envia para um navegador web sem primeiro validar ou codificar esse conteúdo. XSS permite que atacantes executar scripts no navegador da vítima, que pode sequestrar sessões de usuários, desfigurar sites, possivelmente introduzir worms, etc."web2py, por padrão, escapa todas as variáveis renderizadas na view, prevenindo XSS. injection flaws"Injection Flaws: Injection flaws, injeções de SQL particularmente, são comuns em aplicações web. Injections ocorre quando os dados fornecidos pelo usuário são enviados para um intérprete, como parte de um comando ou consulta. O atacante usa truques hostis para o intérprete executar comandos indesejados ou alterar dados."web2py inclui uma camada de abstração de banco de dados que torna a injeção de SQL impossível. Normalmente, as instruções SQL não são escritas pelo desenvolvedor. Em vez disso, SQL é gerado dinamicamente pelo DAL, garantindo que todos os dados inseridos estão devidamente escapados. malicious file execution"Malicious File Execution: Código vulnerável à inclusão de arquivos remotos (RFI) permite a atacantes incluir dados e código hostil, resultando em ataques devastadores, como comprometer servidores totalmente."web2py permite apenas funções expostas a serem executados, impedindo a execução de arquivos maliciosos. Funções importadas nunca são expostas, apenas ações estão expostas. web2py utiliza uma interface de administração baseada na Web que torna muito fácil acompanhar o que está exposto e o que não está. insecure object reference"Insecure Direct Object Reference: A referência direta à objeto ocorre quando um desenvolvedor expõe uma referência a um objeto de implementação interna, como um arquivo, diretório, registro de dados, ou chave, como um parâmetro de URL ou formulário. Os atacantes podem manipular estas referências para acessar outros objetos sem autorização."web2py não expõe quaisquer objetos internos; Além disso, web2py valida todas as URLs, evitando assim ataques de atravessamento de diretórios. web2py também fornece um mecanismo simples para criar formulários que validam automaticamente todos os valores de entrada. CSRF"Cross Site Request Forgery (CSRF): Um ataque CSRF força a iniciar sessão no navegador da vítima para enviar um pedido de pré-autenticação para uma aplicação web vulnerável, o que, em seguida, força o navegador da vítima a executar uma ação maliciosa em prol do atacante. CSRF pode ser tão poderoso quanto a aplicação Web que ele ataca."web2py evita CSRF, bem como acidental duplo envio de formulários através da atribuição de um sinal aleatório de uma só vez a cada formulário. Além disso web2py utiliza o UUID para o cookie de sessão. information leakageimproper error handling"Information Leakage e Improper Error Handling: Os aplicativos podem não intencionalmente vazar informações sobre sua configuração, funcionamento interno, ou violar a privacidade através de uma variedade de problemas de aplicação. Os atacantes se aproveitam dessa fraqueza para roubar dados sensíveis ou conduzir ataques mais graves."web2py inclui um sistema de bilhetagem. Nenhum erro pode resultar em exibição de código para os usuários. Todos os erros são registrados e um ticket, que permite o rastreamento de erro, é emitido para o usuário. Mas os erros e o código fonte só podem ser acessados pelo administrador. "Broken Authentication and Session Management: Credenciais da conta e tokens de sessão muitas vezes não são devidamente protegidos. Atacantes comprometem senhas, chaves ou tokens de autenticação para assumir a identidade de outros usuários." web2py fornece um mecanismo built-in para autenticação de administrador e gere sessões de forma independente para cada aplicação. A interface administrativa também obriga o uso de cookies de sessão seguro quando o cliente não é "localhost". Para aplicações, ele inclui uma poderosa API de controle de acesso. cryptographic store"Insecure Cryptographic Storage: Aplicações Web raramente utilizam funções criptográficas de forma adequada para proteger os dados e credenciais. Os invasores usam dados protegidos fracamente para realizar o roubo de identidade e outros crimes como fraude de cartão de crédito."web2py utiliza o MD5 ou o HMAC + algoritmos de hash SHA-512 para proteger as senhas armazenadas. Outros algoritmos também estão disponíveis. secure communications"Insecure Communications: Aplicações freqüentemente falham em criptografar tráfego de rede quando for necessário para proteger as comunicações sensíveis."web2py inclui o servidor Rocket WSGI que é SSL-enabled[ssl], mas também pode usar o Apache ou Lighttpd e mod_ssl para fornecer criptografia SSL de comunicações. access restriction"Failure to Restrict URL Access: Frequentemente uma aplicação só protege funcionalidade sensível ao impedir a exibição de links ou URLs para usuários não autorizados. Os atacantes podem usar esta fragilidade para acessar e realizar operações não autorizadas, acessando as URLs diretamente."web2py mapeia URL request para módulos Python e funções. web2py fornece um mecanismo para declarar quais as funções são públicas e quais exigem autenticação e autorização. A Role Based Access Control API incluída permite aos desenvolvedores restringir o acesso a qualquer função com base no login, membros do grupo ou o grupo de permissões baseadas. As permissões são muito granulares e podem ser combinadas com filtros de dados para permitir, por exemplo, acesso a tabelas específicos e / ou registos. web2py também permite URL assinado digitalmente e fornece API para assinar digitalmente os retornos de chamada do Ajax. web2py foi revisado para a segurança e você pode encontrar o resultado da análise em ref.[pythonsecurity]. In the box You can download web2py from the official web site: http://www.web2py.com web2py is composed of the following components: libraries: provide core functionality of web2py and are accessible programmatically. web server: the Rocket WSGI web server. the adminapplication: used to create, design, and manage other web2py applications.adminprovides a complete web-based Integrated Development Environment (IDE) for building web2py applications. It also includes other functionality, such as web-based testing and a web-based shell. the examplesapplication: contains documentation and interactive examples.examplesis a clone of the official web2py.com web site, and includes epydoc documentation. the welcomeapplication: the basic scaffolding template for any other application. By default it includes a pure CSS cascading menu and user authentication (discussed in Chapter 9). web2py is distributed in source code, and in binary form for Microsoft Windows and for Mac OS X. The source code distribution can be used in any platform where Python runs and includes the above-mentioned components. To run the source code, you need Python 2.5 pre-installed on the system. You also need one of the supported database engines installed. For testing and light-demand applications, you can use the SQLite database, included with Python 2.5. The binary versions of web2py (for Windows and Mac OS X) include a Python 2.5 interpreter and the SQLite database. Technically, these two are not components of web2py. Including them in the binary distributions enables you to run web2py out of the box. The following image depicts the overall web2py structure: About this book This book includes the following chapters, besides this introduction: Chapter 2 is a minimalist introduction to Python. It assumes knowledge of both procedural and object-oriented programming concepts such as loops, conditions, function calls and classes, and covers basic Python syntax. It also covers examples of Python modules that are used throughout the book. If you already know Python, you may skip Chapter 2. Chapter 3 shows how to start web2py, discusses the administrative interface, and guides the reader through various examples of increasing complexity: an application that returns a string, a counter application, an image blog, and a full blown wiki application that allows image uploads and comments, provides authentication, authorization, web services and an RSS feed. While reading this chapter, you may need to refer to Chapter 2 for general Python syntax and to the following chapters for a more detailed reference about the functions that are used. Chapter 4 covers more systematically the core structure and libraries: URL mapping, request, response, sessions, caching, cron, internationalization and general workflow. Chapter 5 is a reference for the template language used to build views. It shows how to embed Python code into HTML, and demonstrates the use of helpers (objects that can generate HTML). Chapter 6 covers the Database Abstraction Layer, or DAL. The syntax of the DAL is presented through a series of examples. Chapter 7 covers forms, form validation and form processing. FORM is the low level helper for form building. SQLFORM is the high level form builder. In Chapter 7 we also discuss legacy Create/Read/Update/Delete (CRUD) API. Chapter 8 covers communication with as sending emails and SMSes. Chapter 9 covers authentication, authorization and the extensible Role-Based Access Control mechanism available in web2py. Mail configuration and CAPTCHA are also discussed here, since they are used for authentication. In the third edition of the book we have added extensive coverage of integration with third-party authentication mechanisms such as OpenID, OAuth, Google, Facebook, LinkedIn, etc. Chapter 10 is about creating web services in web2py. We provide examples of integration with the Google Web Toolkit via Pyjamas, and with Adobe Flash via PyAMF. Chapter 11 is about web2py and jQuery recipes. web2py is designed mainly for server-side programming, but it includes jQuery, since we have found it to be the best open-source JavaScript library available for effects and Ajax. In this chapter, we discuss how to effectively use jQuery with web2py. Chapter 12 discusses web2py components and plugins as a way to build modular applications. We provide an example of a plugin that implements many commonly used functionality, such as charting, comments, tagging, and wiki. Chapter 13 is about production deployment of web2py applications. We mainly address three possible production scenarios: on a Linux web server or a set of servers (which we consider the main deployment alternative), running as a service on a Microsoft Windows environment, and deployment on the Google Applications Engine. In this chapter, we also discuss security and scalability issues. Chapter 14 contains a variety of other recipes to solve specific tasks, including upgrades, geocoding, pagination, the Twitter API, and more. This book only covers basic web2py functionalities and the API that ships with web2py. This book does not cover web2py appliances (i.e. ready made applications). You can download web2py appliances from the corresponding web site [appliances]. This book has been written using the markmin syntax and automatically converted to HTML, LaTeX and PDF. Support The main support channel is the usergroup[usergroup], with dozens of posts every day. Even if you're a newbie, don't hesitate to ask - we'll be pleased to help you. There is also a formal issue tracker system on http://code.google.com/p/web2py/issue . Last but not least, you can have professional support (see the web site for details). Contribute Any help is really appreciated. You can help other users on the user group, or by directly submitting patches on the program (at the GitHub site https://github.com/web2py/web2py). Even if you find a typo on this book, or have an improvement on it, the best way to help is by patching the book itself (which is under the source folder of the repository at https://github.com/mdipierro/web2py-book). Elements of style PEP8 [style] contains good style practices when programming with Python. You will find that web2py does not always follow these rules. This is not because of omissions or negligence; it is our belief that the users of web2py should follow these rules and we encourage it. We chose not to follow some of those rules when defining web2py helper objects in order to minimize the probability of name conflict with objects defined by the user. For example, the class that represents a <div> is called DIV, while according to the Python style reference it should have been called Div. We believe that, for this specific example that using an all-upper-case "DIV" is a more natural choice. Moreover, this approach leaves programmers free to create a class called "Div" if they choose to do so. Our syntax also maps naturally into the DOM notation of most browsers (including, for example, Firefox). According to the Python style guide, all-upper-case strings should be used for constants and not variables. Continuing with our example, even considering that DIV is a class, it is a special class that should never be modified by the user because doing so would break other web2py applications. Hence, we believe this qualifies the DIV class as something that should be treated as a constant, further justifying our choice of notation. In summary, the following conventions are followed: HTML helpers and validators are all upper case for the reasons discussed above (for example DIV,A,FORM,URL). The translator object Tis upper case despite the fact that it is an instance of a class and not a class itself. Logically the translator object performs an action similar to the HTML helpers, it affects rendering part of the presentation. Also,Tneeds to be easy to locate in the code and must have a short name. DAL classes follow the Python style guide (first letter capitalized), for example Table,Field,Query,Row,Rows, etc. In all other cases we believe we have followed, as much as possible, the Python Style Guide (PEP8). For example all instance objects are lower-case (request, response, session, cache), and all internal classes are capitalized. In all the examples of this book, web2py keywords are shown in bold, while strings and comments are shown in italic. License web2py is licensed under the LGPL version 3 License. The full text of the license if available in ref.[lgpl3]. In accordance with LGPL you may: redistribute web2py with your apps (including official web2py binary versions) release your applications which use official web2py libraries under any license you wish Yet you must: make clear in the documentation that your application uses web2py release any modification of the web2py libraries under the LGPLv3 license 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. Earlier versions Earlier versions of web2py, 1.0.*-1.90.*, were released under the GPL2 license plus a commercial exception which, for practical purposes, was very similar to the current LPGLv3. Third party software distributed with web2py web2py contains third party software under the gluon/contrib/ folder and various JavaScript and CSS files. These files are distributed with web2py under their original licenses, as stated in the files. Acknowledgments web2py was originally developed by and copyrighted by Massimo Di Pierro. The first version (1.0) was released in October, 2007. Since then it has been adopted by many users, some of whom have also contributed bug reports, testing, debugging, patches, and proofreading of this book. Some of the major developers and contributors are, in alphabetical order by first name: 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, José 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'Ávila, 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, 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. I am sure I forgot somebody, so I apologize. I particularly thank Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran and Patrick for their major contributions to web2py and 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 (and others) for proofreading various versions of this book. Their contribution was invaluable. If you find any errors in this book, they are exclusively my fault, probably introduced by a last-minute edit. I also thank Ryan Steffen of Wiley Custom Learning Solutions for help with publishing the first edition of this book. web2py contains code from the following authors, whom I would like to thank: Guido van Rossum for Python[python], Peter Hunt, Richard Gordon, Timothy Farrell for the Rocket[rocket] web server, Christopher Dolivet for EditArea[editarea], Bob Ippolito for simplejson[simplejson], Simon Cusack and Grant Edwards for pyRTF[pyrtf], Dalke Scientific Software for pyRSS2Gen[pyrss2gen], Mark Pilgrim for feedparser[feedparser], Trent Mick for markdown2[markdown2], Allan Saddi for fcgi.py, Evan Martin for the Python memcache module[memcache], John Resig for jQuery[jquery]. I thank Helmut Epp (provost of DePaul University), David Miller (Dean of the College of Computing and Digital Media of DePaul University), and Estia Eichten (Member of MetaCryption LLC), for their continuous trust and support. Finally, I wish to thank my wife, Claudia, and my son, Marco, for putting up with me during the many hours I have spent developing web2py, exchanging emails with users and collaborators, and writing this book. This book is dedicated to them. top
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
spyke Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr jerhum oki mais alors je ny arrive pas a les faire tourner justement est ce normale comme wolfenstein , quake4 etc..... Hors ligne foxylechou Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr il faut autoriser le fichier a être exécuter dans propriétés ofwgkta ------------------------------------------------------------------ Hors ligne andycam Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Bonjour, Quel est le(s) jeux (toute catégories confondues) qui est unique Linux et que l'on ne retrouve donc nul part ? Merci, Andycam Hors ligne gayelene Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr bonjour svp je veux installer le jeu MONOPOLY sur mon pc aidez moisvp comment faire? merci davance Hors ligne forficule Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr @andycam : un jeu que sous linux, ça colle pas avec ce qu'est linux, si tu as le code source (c'est le cas de beaucoup de jeux sous linux), tu peux le compiler pour d'autres plateformes (macosx, win32...). Honnêtement un jeu qui ne tournerait QUE sous linux, je ne vois pas... Hors ligne Calinou Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Ouais c'est bien mumble, mais Ya pas la 1.2.0... Hors ligne ArnaudK Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Bonjour, est-il possible de poster un lien vers un site de revente de jeux linux qui fait des promos ? Je sais que c'est mal vu car certains penseraient que c'est du SPAM Hors ligne ArnaudK Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Ne serait il pas bon d'ajouter les sites revendeurs de jeux Linux, qu'ils soient français ou internationaux ? ça se compte sur les doigts des deux mains, mais ça pourrait être intéressant. Hors ligne KazukyAkayashi Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Il y a LGP : http://www.linuxgamepublishing.com/ Sinon j'en parlerai, mais le mieux est de venir faire des propositions sur le forum jeuxlinux Mon Blog --> http://kazuky.homelinux.net/blog Hors ligne Crone123 Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Bonjour, Moi j'ai ce message qui s'affiche tout le temps: Traceback (most recent call last): File "djl_main.py", line 747, in timerEvent self.maj_liste() File "/home/valentin/djl/djl/diff.py", line 1125, in maj_liste self.etat(self.nom_jeu_depot()) File "djl_main.py", line 809, in etat self.verif_maj_jeu(nom_jeu) File "/home/valentin/djl/djl/diff.py", line 295, in verif_maj_jeu version = self.detail_jeux(no_description, type_info = 'version') File "/home/valentin/djl/djl/diff.py", line 72, in detail_jeux sortie = self.parse_detailjeux(no_jeu, 0) File "/home/valentin/djl/djl/depot.py", line 72, in parse_detailjeux return self.detailjeux['item'][val]['value'] AttributeError: 'Ui_Djl' object has no attribute 'detailjeux' Quelqu'un sait ce que c'est? Merci Hors ligne waston Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr salut a tous je suis nouveau sur ubuntu et sur le forum. j'ai un petit coup de gueule a pousser parce que la je me sent tout perdu et pas une personne pour me répondre clairement j' ai viré w7 de mon pc parce qu'il faisait planter ma machine. j'installe ubuntu 64 bits, super. mais voila que sa ce complique. je sais pas ouvrir un seul programme .exe. j'installe donc wine et wintricks. (il m'as fallu chercher pour trouver sa) ensuite je m'aperçois que fsx pas moyen de l'installer et football manager 2009 non plus ( j'ai était sur la page d'explication pour installer fm2009 et franchement sa marche pas) l'installe ne bouge plus, pourtant je tape tout ce qu'il demande avec E=enter et S et T etc et sa marche pas. j'ai toujours une page grise même après avoir installer direct3d comme demander dans l'explication, et je sais même pas quand l'instal sera finie, bref deux jeux, deux problème. je précise que j'ai ce pc pour moi jouer( le pc pour travailler reste au travail lol) si sous w7 je sais rien installer et maintenant sous ubuntu non plus. j'ai des jeux que je peux mettre a la poubelle et bref mon pc aussi. alors si quelqu'un a une solution miracle , merci de m'aider parce que franchement ras le bol. la seul excuse que ubuntu as par rapport a windows c'est que lui, il est gratuit. sinon c'est le même problème. les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. (je suis gamer mais pas informaticien, alors si vous savais m'aider expliquer moi sans mot trop technique s'il vous plait. merci) Hors ligne atichu Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr LEs fichier .EXE c'est des fichiers Windows pas linux/ubuntu... donc tu veux installer des roues de 2CV sur une porche. Tu comprend le bléme? en général les jeu ubuntu sont dans des dêpot ou sont des .deb qui installe le jeu. sinon voir la documention sur le forum /jeu ou le site Alors pour les gamers, faut se plaindre au fabriquand de jeu qui ne fond pas tout des version linux. mais si tu cherche il y en a quand même. certain gros gamers jour a WOW sous linux mais vu qu'il y a pas de version linux c'est pas tout les jours facile. Dernière modification par atichu (Le 31/03/2011, à 16:14) Je ne suis pas un geek ni un informaticien mais j'aime linux/ubuntu. acer aspire5741G (unity 12.04))+une vieillebousse(xfce 12.04) +teste de la version instable Hors ligne keld Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr la seul excuse que ubuntu as par rapport a windows c'est que lui, il est gratuit. sinon c'est le même problème. les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. (je suis gamer mais pas informaticien, alors si vous savais m'aider expliquer moi sans mot trop technique s'il vous plait. merci) Je te comprends tout a fait, moi aussi raz le cul, la dernière fois j'ai voulu mettre le dvd, fraichement payé, de Gran Turismo 5 sur ma Wii, bah tu sais quoi? Ça ne voulais pas marché!!! Y'en a marre de ces fabriquant de console qui ne s'occupe pas des gamer!!! L122-1 Powaaaa!!!!! Hors ligne waston Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr je pense que ubuntu est quand même très intéressent; vue que c'est asse facile de l'utiliser. maintenant je vais chercher de mon cote mais.... les jeux linux on les a ou? et franchement es qu'il en val le coup? je suis curieux . maintenant je vais essayer quand meme d'obtenir un windows xp pro 64 bits( w7 c'est vraiment de la M... ) pour pouvoir jouer a mes jeux favoris. en dual boot avec ubuntu je devrais être comblé. merci pour vos réponse. en effet je comprend mieux le problème vue la comparaison avec la deudeuche. Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Salut Waston,j'ai eu le meme probleme que toi au début mais maintenant ca va, la facons simple avec Wine c'est que quand tu veux installer un jeu tu va dans la CONFIGURATION de Wine et tu vas dans l'onglet (LECTEUR) situé en haut, une page apparait de tous tes lecteur tu clics sur la lettre de ton lecteur que tu as incerré ton jeu et tu fais (PARCOURIRE) situé un peu plus bas. La une fenetre s'ouvre avec tout tes fichier,tu choisi MEDIA tu double clic dessus,apres le nom de ton jeu apparait tu double clic dessus et tu fais OK.ensuite la fenetre se ferme, apres tu fais APPLIQUER. Tu ouvre WINE tu fais désinstaller un logiciel WINE, tu tappes sur installer tu clic sur la petite fleche verte,jusqua tant de voir ceci / tu vas voir la page est pleinne de fichiers tu trouve MEDIA tu double clic dessus le fichier de ton jeu apparait, tu double clic dessus et tu vas voir apparaitre les fichiers du jeu avec SETUP.EXE tu double clic dessus et l'installation commence. c'est de meme que je procede c'est une facon simple. Ca c'est bon pour les DVDROM. Ce qui est des jeux avec plusieurs CD ex: DIABLO 2 tu vas encore dans CONFIGURATION de Wine tu vas dans LECTEUR tu clic sur la lettre de ton LECTEUR,et tu inscis en bas dans la bar /media/cdrom0 et tu fais APPLIQUER. Tu ouvre Wine et tu fais comme je t'ai dit un peu plus haut tu clic sur la fleche verte et tu va chercher MEDIA tu double clic dessus apres le nom de ton jeux apparait tu double clic dessud et tu fais SETUP.EXE. Lorsequ'il te demande d'incerer le DISC 2 tu vas dans ton terminal (ca c'est important) tu tape sudo eject -a sinon ca na marchera pas entout cas pas pour moi,il faut que je fasse cela pour que ca fonctionne.Tu n'éjecte pas ton jeux manuellement. Si tu suit ce que je t'ai écris ca devrais fonctionner. Bonne chance. Dernière modification par goahead (Le 28/05/2011, à 07:44) Hors ligne Crone123 Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Ouais, mais Wine, ça reste léger, pour ne pas dire complètement nul... Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Pourquoi est-ce que tu dis ca? Hors ligne SlimGary Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. ! C'est pas les développeurs d'OS les fautifs, au contraire, ils mettent des outils de développement à disposition ! Non, les vrais fautifs sont clairement et simplement les éditeurs de jeux ... Et si tu trouves que les développeurs d'OS ne sont pas assez compétents, vas t'acheter une PS3 ou une XboX 360 ! Ouais, mais Wine, ça reste léger, pour ne pas dire complètement nul... Rien a dire ... ah si, scandaleux ! Hors ligne Nemr0D Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Merci ! C'est très interresent ! Hors ligne Crone123 Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Pourquoi est-ce que tu dis ca? C'est la vérité, 90% des programmes ne marchent pas, ou marchent mal, et ça crée des tonnes de raccourcis dans la liste de lancement de programmes (donc quand on choisis une application avec laquelle ouvrir un fichier, c'est mort.. [Wine affiche 90programmes supplémentaires dans la liste et c'est souvent 20fois le meme..]), bon, en plus l'affichage est pas Super Joli... (dans le programme, il pourrais y avoir un design Windows plus beau, ou le design de GNOME..) Bref, en tout cas, tous les jeux que j'ai testé sur Wine, qui sont pourtant certifiés, fonctionne bien sur Wine (depuis le site officiel), j'ai eu des désastres.... Pour être franc je ne l'utilise plus, si j'ai vraiment besoin d'un programme Windows, je lance Windows (env 1fois par mois..), mais sinon, je trouve toujours ce que je cherche en natif. (surtout pour développer..) J'utilise surtout mon PC le développement (donc j'ai tout ce qu'il faut en natif) et pour les jeux libres (même si je pense que les développeurs libres devraient faire plus souvent des .deb parce qu'un développeur php "amateur" français ne sait pas forcément compiler un programme C++ en lisant des instructions en anglais, surtout quand il viens d'avoir son brevet.. [Oui je suis encore étudiant...]) Donc, Linux reste Linux, pour des programmes Linux, et Windows reste Windows avec des programmes Windows, c'est sûrement la meilleure chose quand on a pas envie d'encombrer son PC avec des tonnes de trucs qui marchent a moitié, et dont on ne vas pas forcément se servir du coup. Et effectivement, si les développeurs pensaient un peu plus aux autres OS, ça serait mieux. (voir normal.), remarquez, il y a de plus en plus de jeux payants natifs dans la logithèque, peut être que la tendance va changer du coté des gros jeux (Call Of Duty, Crysis, Trackmania, ...) et peut être que l'on pourra les trouver en natif dans la Logithèque →Il faudrait faire une loi qui indique ceci: "Lorsque un développeur sort un programme payant (ou logiciel d'installation [je pense aux imprimantes, scanner par exemple]), il doit en fournir un version pour chaque OS (donc, une Windows, une Linux, et une Mac OS), si il ne veut pas la compiler pour X raison, il doit proposer les sources du logiciel de façon a ce que les utilisateurs (ou communautés) puissent les compiler pour leurs OS (et donc, en faire des .deb pour les dépôts)" Et ça, ça serait normal, pourquoi privilégier un OS instable payant, plutôt qu'un OS stable libre? Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Oui je suis daccord avec toi,mais si il venait a faire une loi du genre se qui est peu probable pour les raison de droit faudrait que Linux déboursse d'importante somme d'argent pour avoir c'est jeu natif. Comme Wine est une petite communauté il n'ont pas l'argent nécéssaiore pour faire se qu'ils aimerrait faire c'est pour ca que faire un don a ces programmes aide a la communauté de se développer. Hors ligne Rαiden Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Désolé de casser votre réflexion mais je ne suis pas d'accord pour ce genre de loi. Chacun fait ce qu'il veut, si les éditeurs n'ont envie de sortir leurs jeux et logiciels que pour Windows grand bien leur fasse mais hors de question d'obliger les gens à le faire. Sinon Je trouve que cela va à l'encontre des principes de liberté qui animent GNU/Linux à la base ce serait dommage, quand on force les gens à faire quelque chose on sait tous ce que ça donne des choses bâclées voir inutilisables. Concernant Wine en fait Wine existe en premier lieu à travers Crossover qui est une entreprise commerciale c'est vrai qu'ils n'ont pas énormément d'argent mais ils ont un statut d'entreprise qui peut au moins peut faire écho dans le milieu. Comme ils ont un pied dans le propriétaire ça serait cool qu'il prennent au moins la place laissez vacante par Cedega vis à vis de certains éditeurs. Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Je suis d'accord avec toi aussi,mais ne serrait-il pas le temps pour Linux de vouloir faire plaisir au Linuxiens d'avoir des jeux qu'ont pourraient jouer sans se casser la tete, a savoir si Wine va l'accepter je sais que le sujet c'est déjà parlé,mais la on est en 2011 et c'est le temps que Linux fasse le saut.Je sais que ca couterait des sous mais les jeux ont les achetent,donc un revenu pour Linux. Hors ligne Rαiden Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr En fait le problème (pour moi ça n'en est pas un mais bon) vient du fait que Linux est un noyau et seulement un Noyau il n'a qu'une fonction technique et pas franchement politique à part celle le concernant. Là ou le lobbying doit être fait c'est au niveau des distributions Ubuntu par exemple et comme on a 50 000 distributions ça n'aide pas à créer de grosses structures influentes qui peuvent rivaliser avec Microsoft et Apple. Du fait qu' il n'y ai pas de grosse structure la pression sur les éditeurs de jeux-vidéos est nulle c'est donc les développeurs qui choisissent en leur âme et conscience de développer pour GNU/Linux, moi je préfère honnêtement car c'est un acte en général altruiste et ça le reste. Quand un jeu sort sous GNU/Linux tu sais que c'est parce que le développeur à un attachement particulier à notre plateforme, qu'il a voulu faire plaisir à tous les utilisateurs et ça ça fait chaud au coeur. Parfois pour les développeurs indépendant c'est pour des raisons financières mais même si c'est le cas ce sont des gens qu'il faut encourager car ils sont l'avenir du secteur. Comme tu vois ce n'est pas à Linux de faire plaisir aux Linuxiens, Linux n'est qu'un noyau c'est aux éditeurs/développeurs de se bouger le cul car tous les outils existent pour développer correctement sous GNU/Linux c'est juste le choix de ne pas le faire pour des raisons financières en ce qui les concerne. Dernière modification par Rαίdeη (Le 23/07/2011, à 08:10) Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Merci de ton idée,je viens d'en apprendre beaucoup,se qui reste le mieux pour les jeux c'est un bon Xbox 360 ou un Playstation.Mais il reste que et j'espere, que Linux devienne plus qu'un simple Noyau.Il disent que Linux Mint est le 4eme systeme d'exploitation le plus utilisé au monde,il pourrait sen doute grossire la machine,mais c'est un peu comme si on voudrait changer la mentalité de LInux et je ne pense pas qu'il sont pret pour cela. Je me trompe peut-etre j'en suis sure que quelqu'un saura me le dire. Hors ligne
The setup... Trying to set up a clean Mac os X 10.6 install to develop python/django and I didn't remember running into this on 10.5. After installing MySQL from the installer on mysql-5.5.8-osx10.6-x86_64.dmg I ran $ sudo pip install MySQL-python and it seemed to go smoothly (output below) Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded Running setup.py egg_info for package MySQL-python warning: no files found matching 'MANIFEST' warning: no files found matching 'ChangeLog' warning: no files found matching 'GPL' Installing collected packages: MySQL-python Running setup.py install for MySQL-python building '_mysql' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/local/mysql/include -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/temp.macosx-10.6-universal-2.6/_mysql.o -Os -g -fno-common -fno-strict-aliasing -arch x86_64 In file included from _mysql.c:36: /usr/local/mysql/include/my_config.h:325:1: warning: "SIZEOF_SIZE_T" redefined In file included from /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:9, from pymemcompat.h:10, from _mysql.c:29: /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pymacconfig.h:33:1: warning: this is the location of the previous definition In file included from _mysql.c:36: /usr/local/mysql/include/my_config.h:419:1: warning: "HAVE_WCSCOLL" redefined In file included from /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:8, from pymemcompat.h:10, from _mysql.c:29: /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyconfig.h:803:1: warning: this is the location of the previous definition gcc-4.2 -Wl,-F. -bundle -undefined dynamic_lookup build/temp.macosx-10.6-universal-2.6/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lpthread -o build/lib.macosx-10.6-universal-2.6/_mysql.so -arch x86_64 warning: no files found matching 'MANIFEST' warning: no files found matching 'ChangeLog' warning: no files found matching 'GPL' Successfully installed MySQL-python Cleaning up... after this I tried: $ python -c "import MySQLdb" and it crapped out on me with: Traceback (most recent call last): File "<string>", line 1, in <module> File "/Library/Python/2.6/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/Library/Python/2.6/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.16.dylib Referenced from: /Library/Python/2.6/site-packages/_mysql.so Reason: image not found So on to my question... What did I do wrong?/What else do I need to do? Googling (and searching here) for this returns a lot of results getting this error message with Ruby not too many with Python tho.
Emails and SMS Setting up email Web2py provides the gluon.tools.Mail class to make it easy to send emails using web2py. One can define a mailer with from gluon.tools import Mail mail = Mail() mail.settings.server = 'smtp.example.com:25' mail.settings.sender = 'you@example.com' mail.settings.login = 'username:password' Note, if your application uses Auth (discussed in the next chapter), the auth object will include its own mailer in auth.settings.mailer, so you can use that instead as follows: mail = auth.settings.mailer mail.settings.server = 'smtp.example.com:25' mail.settings.sender = 'you@example.com' mail.settings.login = 'username:password' You need to replace the mail.settings with the proper parameters for your SMTP server. Set mail.settings.login = None if the SMTP server does not require authentication. If you don't want to use TLS, set mail.settings.tls = False For debugging purposes you can setand emails will not be sent but logged to the console instead.mail.settings.server = 'logging' Configuring email for Google App Engine For sending emails from Google App Engine account: mail.settings.server = 'gae' At the time of writing web2py does not support attachments and encrypted emails on Google App Engine. Notice cron and scheduler do not work on GAE. x509 and PGP Encryption It is possible to send x509 (SMIME) encrypted emails using the following settings: mail.settings.cipher_type = 'x509' mail.settings.sign = True mail.settings.sign_passphrase = 'your passphrase' mail.settings.encrypt = True mail.settings.x509_sign_keyfile = 'filename.key' mail.settings.x509_sign_certfile = 'filename.cert' mail.settings.x509_crypt_certfiles = 'filename.cert' It is possible to send PGP encrypted emails. First of all you need to install the python-pyme package. Then you can use GnuPG (GPG) to create the key-files for the sender (take the email-address from mail.settings.sender) and put the files pubring.gpg and secring.gpg in a directory (e.g. "/home/www-data/.gnupg"). Use the following settings: mail.settings.gpg_home = '/home/www-data/.gnupg/' mail.settings.cipher_type = 'gpg' mail.settings.sign = True mail.settings.sign_passphrase = 'your passphrase' mail.settings.encrypt = True Sending emails Once mail is defined, it can be used to send email via: mail.send(to=['somebody@example.com'], subject='hello', # If reply_to is omitted, then mail.settings.sender is used reply_to='us@example.com', message='hi there') Mail returns True if it succeeds in sending the email and False otherwise. A complete argument list for mail.send() is as follows: send(self, to, subject='None', message='None', attachments=[], cc=[], bcc=[], reply_to=[], sender=None, encoding='utf-8', raw=True, headers={}) Note, to, cc, and bcc each take a list of email addresses. sender defaults to None and in this case the sender will be set to mail.settings.sender. headers is dictionary of headers to refine the headers just before sending the email. For example: headers = {'Return-Path' : 'bounces@example.org'} Following are some additional examples demonstrating the use of mail.send(). Simple text email mail.send('you@example.com', 'Message subject', 'Plain text body of the message') HTML emails mail.send('you@example.com', 'Message subject', '<html>html body</html>') If the email body starts with <html> and ends with </html>, it will be sent as a HTML email. Combining text and HTML emails The email message can be a tuple (text, html): mail.send('you@example.com', 'Message subject', ('Plain text body', '<html>html body</html>')) cc and bcc emails mail.send('you@example.com', 'Message subject', 'Plain text body', cc=['other1@example.com', 'other2@example.com'], bcc=['other3@example.com', 'other4@example.com']) Attachments mail.send('you@example.com', 'Message subject', '<html><img src="cid:photo" /></html>', attachments = mail.Attachment('/path/to/photo.jpg', content_id='photo')) Multiple attachments mail.send('you@example.com', 'Message subject', 'Message body', attachments = [mail.Attachment('/path/to/fist.file'), mail.Attachment('/path/to/second.file')]) Sending SMS messages Sending SMS messages from a web2py application requires a third party service that can relay the messages to the receiver. Usually this is not a free service, but it differs from country to country. We have tried a few of these services with little success. Phone companies block emails originating from these services since they are eventually used as a source of spam. A better way is to use the phone companies themselves to relay the SMS. Each phone company has an email address uniquely associated with every cell-phone number, so SMS messages can be sent as emails to the phone number. web2py comes with a module to help in this process: from gluon.contrib.sms_utils import SMSCODES, sms_email email = sms_email('1 (111) 111-1111','T-Mobile USA (tmail)') mail.send(to=email, subject='test', message='test') SMSCODES is a dictionary that maps names of major phone companies to the email address postfix. The sms_email function takes a phone number (as a string) and the name of a phone company and returns the email address of the phone. Using the template system to generate messages It is possible to use the template system to generate emails. For example, consider the database table db.define_table('person', Field('name')) where you want to send to every person in the database the following message, stored in a view file "message.html": Dear {{=person.name}}, You have won the second prize, a set of steak knives. You can achieve this in the following way for person in db(db.person).select(): context = dict(person=person) message = response.render('message.html', context) mail.send(to=['who@example.com'], subject='None', message=message) Most of the work is done in the statement response.render('message.html', context) It renders the view "message.html" with the variables defined in the dictionary "context", and it returns a string with the rendered email text. The context is a dictionary that contains variables that will be visible to the template file. If the message starts with <html> and ends with </html>, the email will be an HTML email. Note, if you want to include a link back to your website in an HTML email, you can use the URL function. However, by default, the URL function generates a relative URL, which will not work from an email. To generate an absolute URL, you need to specify the scheme and host arguments to the URL function. For example: <a href="{{=URL(..., scheme=True, host=True)}}">Click here</a> or <a href="{{=URL(..., scheme='http', host='www.site.com')}}">Click here</a> The same mechanism that is used to generate email text can also be used to generate SMS messages or any other type of message based on a template. Sending messages using a background task The operation of sending an email message can take up to several seconds because of the need to log into and communicate with a potentially remote SMTP server. To keep the user from having to wait for the send operation to complete, it is sometimes desirable to queue the email to be sent at a later time via a background task. As described in Chapter 4, this can be done by setting up a homemade task queue or using the web2py scheduler. Here we provide an example using a homemade task queue. First, in a model file within our application, we set up a database model to store our email queue: db.define_table('queue', Field('status'), Field('email'), Field('subject'), Field('message')) From a controller, we can then enqueue messages to be sent by: db.queue.insert(status='pending', email='you@example.com', subject='test', message='test') Next, we need a background processing script that reads the queue and sends the emails: ## in file /app/private/mail_queue.py import time while True: rows = db(db.queue.status=='pending').select() for row in rows: if mail.send(to=row.email, subject=row.subject, message=row.message): row.update_record(status='sent') else: row.update_record(status='failed') db.commit() time.sleep(60) # check every minute Finally, as described in Chapter 4, we need to run the mail_queue.py script as if it were inside a controller in our app: python web2py.py -S app -M -R applications/app/private/mail_queue.py where -S app tells web2py to run "mail_queue.py" as "app", -M tells web2py to execute models. Here we assume that the mail object referenced in "mail_queue.py" is defined in a model file in our app and is therefore available in the "mail_queue.py" script because of the -M option. Also notice that it is important to commit any change as soon as possible in order not to lock the database to other concurrent processes. As noted in Chapter 4, this type of background process should not be executed via cron (except perhaps for cron @reboot) because you need to be sure that no more than one instance is running at the same time. Note, one drawback to sending email via a background process is that it makes it difficult to provide feedback to the user in case the email fails. If email is sent directly from the controller action, you can catch any errors and immediately return an error message to the user. With a background process, however, the email is sent asynchronously, after the controller action has already returned its response, so it becomes more complex to notify the user of a failure. Reading and managing email boxes (Experimental) The IMAP adapter is intended as an interface with email IMAP servers to perform simple queries in the web2py DAL query syntax, so email read, search and other related IMAP mail services (as those implemented by brands like Google(r), and Yahoo(r) can be managed from web2py applications. It creates its table and field names "statically", meaning that the developer should leave the table and field definitions to the DAL instance by calling the adapter .define_tables() method. The tables are defined with the IMAP server mailbox list information. Connection For a single mail account, this is the code recommended to start IMAP support at the app's model # Replace user, password, server and port in the connection string # Set port as 993 for SSL support imapdb = DAL("imap://user:password@server:port", pool_size=1) imapdb.define_tables() Note that <imapdb>.define_tables() returns a dictionary of strings mapping DAL tablenames to the server mailbox names with the structure {<tablename>: <server mailbox name>, ...}, so you can get the actual mailbox name in the IMAP server. If you want to set you own tablename/mailbox configuration and skip the automatic name configuration, you can pass a custom dictionary to the adapter in this way: imapdb.define_tables({"inbox": "MAILBOX", "trash", "SPAM"}) To handle the different native mailbox names for the user interface, the following attributes give access to the adapter auto mailbox mapped names (which native mailbox has what table name and vice versa): Attribute Type Format imapdb.mailboxes dict {<tablename>: <server native name>, ...} imapdb.<table>.mailbox string "server native name" The first can be useful to retrieve IMAP query sets by the native email service mailbox # mailbox is a string containing the actual mailbox name tablenames = dict([(v,k) for k,v in imapdb.mailboxes.items()]) myset = imapdb(imapdb[tablenames[mailbox]]) Fetching mail and updating flags Here's a list of IMAP commands you could use in the controller. For the examples, it's assumed that your IMAP service has a mailbox named INBOX, which is the case for Gmail(r) accounts. To count today's unseen messages smaller than 6000 octets from the inbox mailbox do q = imapdb.INBOX.seen == False q &= imapdb.INBOX.created == request.now.date() q &= imapdb.INBOX.size < 6000 unread = imapdb(q).count() You can fetch the previous query messages with rows = imapdb(q).select() Usual query operators are implemented, including belongs messages = imapdb(imapdb.INBOX.uid.belongs(<uid sequence>)).select() Note: It's strongly advised that you keep the query results below a given data size threshold to avoid jamming the server with large select commands. To perform faster email queries, it is recommended to pass a filtered set of fields: fields = ["INBOX.uid", "INBOX.sender", "INBOX.subject", "INBOX.created"] rows = imapdb(q).select(*fields) The adapter knows when to retrieve partial message payloads (fields like content, size and attachments require retrieving the complete message data) It is possible to filter query select results with limitby and sequences of mailbox fields # Replace the arguments with actual values myset.select(<fields sequence>, limitby=(<int>, <int>)) Say you want to have an app action show a mailbox message. First we retrieve the message (If your IMAP service supports it, fetch messages by uid field to avoid using old sequence references). mymessage = imapdb(imapdb.INBOX.uid == <uid>).select().first() Otherwise, you can use the message's id. mymessage = imapdb.INBOX[<id>] Note that using the message's id as reference is not recommended, because sequence numbers can change with mailbox maintenance operations as message deletions. If you still want to record references to messages (i.e. in another database's record field), the solution is to use the uid field as reference whenever supported, and retrieve each message with the recorded value. Finally, add something like the following to show the message content in a view {{=P(T("Message from"), " ", mymessage.sender)}} {{=P(T("Received on"), " ", mymessage.created)}} {{=H5(mymessage.subject)}} {{for text in mymessage.content:}} {{=DIV(text)}} {{=TR()}} {{pass}} As expected, we can take advantage of the SQLTABLE helper to build message lists in views {{=SQLTABLE(myset.select(), linkto=URL(...))}} And of course, it's possible to feed a form helper with the appropriate sequence id value {{=SQLFORM(imapdb.INBOX, <message id>, fields=[...])}} The current adapter supported fields available are the following: Field Type Description uid string answered boolean Flag created date content list:string A list of text or html parts to string cc string bcc string size integer the amount of octets of the message* deleted boolean Flag draft boolean Flag flagged boolean Flag sender string recent boolean Flag seen boolean Flag subject string mime string The mime header declaration string The complete RFC822 message** attachments list Each non text decoded part as dictionary encoding string The message's main detected charset *At the application side it is measured as the length of the RFC822 message string WARNING: As row id's are mapped to email sequence numbers, make sure your IMAP client web2py app does not delete messages during select or update actions, to prevent updating or deleting different messages. Standard CRUD database operations are not supported. There's no way of defining custom fields or tables and make inserts with different data types because updating mailboxes with IMAP services is usually reduced to posting flag updates to the server. Still, it's possible to access those flag commands through the DAL IMAP interface To mark last query messages as seen seen = imapdb(q).update(seen=True) Here we delete messages in the IMAP database that have mails from mr. Gumby deleted = 0 for tablename in imapdb.tables(): deleted += imapdb(imapdb[tablename].sender.contains("gumby")).delete() It is possible also to mark messages for deletion instead of erasing them directly with myset.update(deleted=True) top
How to exclude form fields if the user is not staff ? I tried this but didn't work , giving an error : global name 'user' is not defined class PostForm(ModelForm): class Meta: model = Photo exclude = ['author','featured','published'] def __init__(self, *args, **kwargs): published = kwargs.pop('published', None) super(PostForm, self).__init__(*args, **kwargs) if not user.is_staff: del self.fields['published'] view.py def addpost(request): if request.method == 'POST': form = PostForm(request.POST,request.FILES,user=request.user) if form.is_valid(): post = form.save(False) post.author = request.user form.save() return HttpResponseRedirect(reverse('insight.content.views.index', )) else: form = PostForm(user=request.user) ispost = True return render_to_response('form_add_place.html', {'form': form,'ispost':ispost},context_instance=RequestContext(request))
Introduction Background I'm writing a script to upload stuff including files using the multipart/form-data content type defined in RFC 2388. In the long run, I'm trying to provide a simple Python script to do uploads of binary packages for github, which involves sending form-like data to Amazon S3. Related This question has already asked about how to do this, but it is without an accepted answer so far, and the more useful of the two answers it currently has points to these recipes which in turn build the whole message manually. I am somewhat concerned about this approach, particularly with regard to charsets and binary content. There is also this question, with its currently highest-scoring answer suggesting the MultipartPostHandler module. But that is not much different from the recipes I mentioned, and therefore my concerns apply tho that as well. Concerns Binary content RFC 2388 Section 4.3 explicitely states that content is expected to be 7 bit unless declared otherwise, and therefore a Content-Transfer-Encoding header might be required. Does that mean I'd have to Base64-encode binary file content? Or would Content-Transfer-Encoding: 8bit be sufficient for arbitrary files? Or should that read Content-Transfer-Encoding: binary? Charset for header fields Header fields in general, and the filename header field in particular, are ASCII only by default. I'd like my method to be able to pass non-ASCII file names as well. I know that for my current application of uploading stuff for github, I probably won't need that as the file name is given in a separate field. But I'd like my code to be reusable, so I'd rather encode the file name parameter in a conforming way. RFC 2388 Section 4.4 advises the format introduced in RFC 2231, e.g. filename*=utf-8''t%C3%A4st.txt. My approach Using python libraries As multipart/form-data is essentially a MIME type, I thought that it should be possible to use the email package from the standard python libraries to compose my post. The rather complicated handling of non-ASCII header fields in particular is something I'd like to delegate. Work so far So I wrote the following code: #!/usr/bin/python3.2 import email.charset import email.generator import email.header import email.mime.application import email.mime.multipart import email.mime.text import io import sys class FormData(email.mime.multipart.MIMEMultipart): def __init__(self): email.mime.multipart.MIMEMultipart.__init__(self, 'form-data') def setText(self, name, value): part = email.mime.text.MIMEText(value, _charset='utf-8') part.add_header('Content-Disposition', 'form-data', name=name) self.attach(part) return part def setFile(self, name, value, filename, mimetype=None): part = email.mime.application.MIMEApplication(value) part.add_header('Content-Disposition', 'form-data', name=name, filename=filename) if mimetype is not None: part.set_type(mimetype) self.attach(part) return part def http_body(self): b = io.BytesIO() gen = email.generator.BytesGenerator(b, False, 0) gen.flatten(self, False, '\r\n') b.write(b'\r\n') b = b.getvalue() pos = b.find(b'\r\n\r\n') assert pos >= 0 return b[pos + 4:] fd = FormData() fd.setText('foo', 'bar') fd.setText('täst', 'Täst') fd.setFile('file', b'abcdef'*50, 'Täst.txt') sys.stdout.buffer.write(fd.http_body()) The result looks like this: --===============6469538197104697019== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: form-data; name="foo" YmFy --===============6469538197104697019== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: form-data; name*=utf-8''t%C3%A4st VMOkc3Q= --===============6469538197104697019== Content-Type: application/octet-stream MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: form-data; name="file"; filename*=utf-8''T%C3%A4st.txt YWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJj ZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVm YWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJj ZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVm YWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJjZGVmYWJj ZGVmYWJjZGVmYWJjZGVm --===============6469538197104697019==-- It does seem to handle headers reasonably well. Binary file content will get base64-encoded, which might be avoidable but which should work well enough. What worries me are the text fields in between. They are base64-encoded as well. I think that according to the standard, this should work well enough, but I'd rather have plain text in there, just in case some dumb framework has to deal with the data at an intermediate level and does not know about Base64 encoded data. Questions Can I use 8 bit data for my text fields and still conform to the specification? Can I get the email package to serialize my text fields as 8 bit data without extra encoding? If I have to stick to some 7 bit encoding, can I get the implementation to use quoted printable for those text parts where that encoding is shorter than base64? Can I avoid base64 encoding for binary file content as well? If I can avoid it, should I write the Content-Transfer-Encodingas8bitor asbinary? If I had to serialize the body myself, how could I use the(email.headerpackage on its own to just format header values?email.utils.encode_rfc2231does this.) Is there some implementation that already did all I'm trying to do? These questions are very closely related, and could be summarized as “how would you implement this”. In many cases, answering one question either answers or obsoletes another one. So I hope you agree that a single post for all of them is appropriate.
I am running through the book "OSGi and Apache Felix 3.0" and have hit a problem where a bundle I am deploying insists that it has a dependency on the wrong version of another bundle. For anyone who has worked through these examples before, I am just at the end of chapter 10 - implementing logging functionality in the Bookshelf Service Bundle. Basically the problem is as follows: I have a bundle called "Bookshelf Service" to which I have just added some sweet new logging functionality. This new functionality puts it at version 1.10.0 I have another bundle called "Bookshelf Service Gogo commands" which is a command-line interface to functionality in "Bookshelf Service". It is at version 1.9.0. What is puzzling is that when I deploy the "Bookshelf Service Gogo commands" bundle, it installs as follows: deploy -s "Bookshelf Service Gogo commands" Target resource(s): ------------------- Bookshelf Service Gogo commands (1.9.0) Required resource(s): --------------------- Bookshelf Service (1.7.0) Which of course is the wrong version of the 'Bookshelf Service' Bundle. I want to be using version 1.10.0. If I update, or force the framework to use version 1.10.0, then the functionality that "Bookshelf Service Gogo commands" offers ceases to be available. It is refusing to work with the newest version of 'Bookshelf Service'. According to the pom.xml file though, the dependency is indeed for the 1.10.0 version of 'Bookshelf Service'. The POM for "Bookshelf Service Gogo commands" is as follows: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.packtpub.felix</groupId> <artifactId>com.packtpub.felix.bookshelf-service-tui</artifactId> <version>1.9.0</version> <packaging>bundle</packaging> <name>Bookshelf Service Gogo commands</name> <description>The text user-interface</description> <dependencies> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.core</artifactId> <version>4.2.0</version> </dependency> <dependency> <groupId>org.apache.felix</groupId> <artifactId>org.apache.felix.gogo.runtime</artifactId> <version>0.8.0</version> </dependency> <dependency> <groupId>org.apache.felix</groupId> <artifactId>org.apache.felix.ipojo.annotations</artifactId> <version>1.6.4</version> </dependency> <dependency> <groupId>com.packtpub.felix</groupId> <artifactId>com.packtpub.felix.bookshelf-service</artifactId> <version>1.10.0</version> <type>bundle</type> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.1.0</version> <extensions>true</extensions> <configuration> <instructions> <Bundle-Category>sample</Bundle-Category> <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName> <Export-Package> com.packtpub.felix.bookshelf.service.tui </Export-Package> <!-- <Bundle-Activator> com.packtpub.felix.bookshelf.service.tui.activator.BookshelfTuiActivator </Bundle-Activator> <Private-Package> com.packtpub.felix.bookshelf.service.tui.activator </Private-Package> --> </instructions> <remoteOBR>repo-rel</remoteOBR> <prefixUrl>file:/home/awalker/sandbox_workspace/releases</prefixUrl> <ignoreLock>true</ignoreLock> </configuration> </plugin> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-ipojo-plugin</artifactId> <version>1.6.0</version> <executions> <execution> <goals> <goal>ipojo-bundle</goal> </goals> <configuration> <metadata>src/main/ipojo/meta.xml</metadata> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <inherited>true</inherited> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> <distributionManagement> <!-- releases repo --> <repository> <id>repo-rel</id> <url>file:/home/awalker/sandbox_workspace/releases</url> </repository> </distributionManagement> </project> So I don't understand why it only wants to work with 1.7.0. It is also worth mentioning that both of these bundles are taking advantage of iPOJO, so they do have meta.xml files. I don't think the problem is there however, because I have been comparing my code to the downloadable sample code for the book examples, and everything seems to match. Any ideas about what is going wrong, or where to look for the source of this problem? EDIT: As per request, the generated manifests. Bookshelf Service 1.7.0: Manifest-Version: 1.0 Export-Package: com.packtpub.felix.bookshelf.service.api;uses:="com.pa cktpub.felix.bookshelf.inventory.api",com.packtpub.felix.bookshelf.se rvice.impl;uses:="com.packtpub.felix.bookshelf.inventory.api,com.pack tpub.felix.bookshelf.service.api,org.osgi.framework" Built-By: awalker Tool: Bnd-0.0.357 Bundle-Category: sample Bundle-Name: Bookshelf Service Created-By: Apache Maven Bundle Plugin Build-Jdk: 1.6.0_24 Bundle-Version: 1.7.0 Bnd-LastModified: 1305055936964 Bundle-ManifestVersion: 2 Bundle-Activator: com.packtpub.felix.bookshelf.service.impl.activator. BookshelfServiceImplActivator Bundle-Description: This Bookshelf Service Bundle-SymbolicName: com.packtpub.felix.bookshelf-service Import-Package: com.packtpub.felix.bookshelf.inventory.api,com.packtpu b.felix.bookshelf.service.api,com.packtpub.felix.bookshelf.service.im pl,org.osgi.framework;version="1.5" Bookshelf Service version 1.10.0 Manifest-Version: 1.0 Export-Package: com.packtpub.felix.bookshelf.service.api;uses:="com.pa cktpub.felix.bookshelf.inventory.api",com.packtpub.felix.bookshelf.se rvice.impl;uses:="com.packtpub.felix.bookshelf.inventory.api,com.pack tpub.felix.bookshelf.service.api,com.packtpub.felix.bookshelf.log.api " iPOJO-Components: component { $immediate="true" $name="BookshelfServic eImpl" $classname="com.packtpub.felix.bookshelf.service.impl.Bookshel fServiceImpl" provides { }manipulation { field { $name="sessionId" $t ype="java.lang.String" }field { $name="inventory" $type="com.packtpub .felix.bookshelf.inventory.api.BookInventory" }field { $name="logger" $type="com.packtpub.felix.bookshelf.log.api.BookshelfLogHelper" }met hod { $name="$init" }method { $name="getLogger" $return="com.packtpub .felix.bookshelf.log.api.BookshelfLogHelper" }method { $name="lookupB ookInventory" $return="com.packtpub.felix.bookshelf.inventory.api.Boo kInventory" }method { $arguments="{java.lang.String,char[]}" $name="l ogin" $return="java.lang.String" }method { $arguments="{java.lang.Str ing}" $name="logout" }method { $arguments="{java.lang.String}" $name= "sessionIsValid" $return="boolean" }method { $arguments="{java.lang.S tring}" $name="checkSession" }method { $arguments="{java.lang.String, java.lang.String}" $name="getBook" $return="com.packtpub.felix.booksh elf.inventory.api.Book" }method { $arguments="{java.lang.String,java. lang.String}" $name="getBookForEdit" $return="com.packtpub.felix.book shelf.inventory.api.MutableBook" }method { $arguments="{java.lang.Str ing,java.lang.String,java.lang.String,java.lang.String,java.lang.Stri ng,int}" $name="addBook" }method { $arguments="{java.lang.String,java .lang.String,java.lang.String}" $name="modifyBookCategory" }method { $arguments="{java.lang.String,java.lang.String,int}" $name="modifyBoo kRating" }method { $arguments="{java.lang.String}" $name="getCategori es" $return="java.util.Set" }method { $arguments="{java.lang.String,j ava.lang.String}" $name="removeBook" }method { $arguments="{java.lang .String,java.lang.String}" $name="searchBooksByAuthor" $return="java. util.Set" }method { $arguments="{java.lang.String,java.lang.String}" $name="searchBooksByCategory" $return="java.util.Set" }method { $argu ments="{java.lang.String,java.lang.String}" $name="searchBooksByTitle " $return="java.util.Set" }method { $arguments="{java.lang.String,int ,int}" $name="searchBooksByRating" $return="java.util.Set" }interface { $name="com.packtpub.felix.bookshelf.service.api.BookshelfService" }}requires { $field="inventory" }requires { $field="logger" }}instanc e { $component="BookshelfServiceImpl" $name="bookshelf.service.impl" } Built-By: awalker Tool: Bnd-0.0.357 Bundle-Category: sample Bundle-Name: Bookshelf Service Created-By: Apache Maven Bundle Plugin & iPOJO 1.6.0 Build-Jdk: 1.6.0_24 Bundle-Version: 1.10.0 Bnd-LastModified: 1305656960793 Bundle-ManifestVersion: 2 Bundle-Description: This Bookshelf Service Import-Package: com.packtpub.felix.bookshelf.inventory.api, org.osgi.s ervice.log;version=1.3, com.packtpub.felix.bookshelf.service.impl, co m.packtpub.felix.bookshelf.service.api, org.apache.felix.ipojo.archit ecture;version= 1.6.0, com.packtpub.felix.bookshelf.log.api, org.apac he.felix.ipojo;version= 1.6.0, org.osgi.service.cm;version=1.2 Bundle-SymbolicName: com.packtpub.felix.bookshelf-service Bookshelf Service Gogo commands 1.9.0 Manifest-Version: 1.0 Export-Package: com.packtpub.felix.bookshelf.service.tui;uses:="com.pa cktpub.felix.bookshelf.inventory.api,com.packtpub.felix.bookshelf.ser vice.api,org.apache.felix.service.command" iPOJO-Components: instance { $component="BookshelfServiceProxy" $name= "bookshelf.service.tui" }component { $name="BookshelfServiceProxy" $c lassname="com.packtpub.felix.bookshelf.service.tui.BookshelfServicePr oxyImpl" $public="true" provides { property { $field="gogoScope" $nam e="osgi.command.scope" $value="book" }property { $field="gogoFunction s" $name="osgi.command.function" $value="[add,search]" }}manipulation { field { $name="bookshelf" $type="com.packtpub.felix.bookshelf.serv ice.api.BookshelfService" }field { $name="gogoScope" $type="java.lang .String" }field { $name="gogoFunctions" $type="java.lang.String[]" }m ethod { $name="$init" }method { $name="lookupService" $return="com.pa cktpub.felix.bookshelf.service.api.BookshelfService" }method { $argum ents="{java.lang.String,java.lang.String,java.lang.String,java.lang.S tring,java.lang.String,java.lang.String,int}" $name="add" $return="ja va.lang.String" }method { $arguments="{java.lang.String,java.lang.Str ing,java.lang.String,java.lang.String}" $name="search" $return="java. util.Set" }method { $arguments="{java.lang.String,java.lang.String,ja va.lang.String,int,int}" $name="search" $return="java.util.Set" }meth od { $arguments="{java.lang.String,com.packtpub.felix.bookshelf.servi ce.api.BookshelfService,java.util.Set}" $name="getBooks" $return="jav a.util.Set" }interface { $name="com.packtpub.felix.bookshelf.service. tui.BookshelfServiceProxy" }}requires { $field="bookshelf" }} Built-By: awalker Tool: Bnd-0.0.357 Bundle-Category: sample Bundle-Name: Bookshelf Service Gogo commands Created-By: Apache Maven Bundle Plugin & iPOJO 1.6.0 Build-Jdk: 1.6.0_24 Bundle-Version: 1.9.0 Bnd-LastModified: 1305650360964 Bundle-ManifestVersion: 2 Bundle-Description: The text user-interface Import-Package: com.packtpub.felix.bookshelf.inventory.api, org.osgi.s ervice.log;version=1.3, org.apache.felix.service.command;status=provi sional;version=0.8, com.packtpub.felix.bookshelf.service.api, org.apa che.felix.ipojo.architecture;version= 1.6.0, org.apache.felix.ipojo;v ersion= 1.6.0, org.osgi.service.cm;version=1.2, com.packtpub.felix.bo okshelf.service.tui Bundle-SymbolicName: com.packtpub.felix.bookshelf-service-tui
I'm running a python program compiled on windows which receives files as input but have problems when I'm passing file names. foo.py: def main(): args = sys.argv[1:] for i in args: print i But when I compile and call it from the command line \python foo.py *.html It directly gives me the result of *.html which I hope to see a list of matching strings. Can anyone hep plz:)
How to parse a custom string using optparse, instead of command line argument? I want to parse a string that I get from using raw_input().How can I use optparse for that? parser = optparse.OptionParser() # Set up your OptionParser inp = raw_input("Enter some crap: ") try: (options, args) = parser.parse_args(shlex.split(inp)) except: # Error handling. The optional argument to Be advised that Use the shlex module to split the input first. >>> import shlex >>> shlex.split(raw_input()) this is "a test" of shlex ['this', 'is', 'a test', 'of', 'shlex']
bowmore Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Bonjour à tous. J'essaye depuis quelques jour de faire fonctionner une imprimante HP Color LaserJet 4550N branchée en Ethernet sur un PC sous Lubuntu 12.04. N'ayant pas de port USB sur l'imprimante, ni de port série sur ma carte mère, je n'ai que cette option. J'ai branché directement un câble RJ45 (croisé) de l'imprimante, vers ma carte réseau, sans passer par un routeur ou autre équipement. J'ai suivi divers tutos, utilisé Cups, HPlib, le gestionnaire d'imprimante de Lubuntu, toujours en vain. Si je lance hp-probe -bnet dans un terminal, j'ai: warning: No devices found on the 'net' bus. If this isn't the result you are expecting,warning: check your network connections and make sure your internetwarning: firewall software is disabled. L'adresse IP m'est donné par la page d'autotest de l'imprimante. Si je ping cette adresse, j'ai: PING 87.141.1.14 (87.141.1.14) 56(84) bytes of data. 64 bytes from 87.141.1.14: icmp_req=1 ttl=64 time=0.036 ms 64 bytes from 87.141.1.14: icmp_req=2 ttl=64 time=0.031 ms 64 bytes from 87.141.1.14: icmp_req=3 ttl=64 time=0.032 ms --- 87.141.1.14 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1998ms rtt min/avg/max/mdev = 0.031/0.033/0.036/0.002 ms Bref, je patauge... Si quelqu'un à une idée, je suis preneur. Merci. Dernière modification par bowmore (Le 12/02/2013, à 14:19) "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne Brunod Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Pour hp j'ajoutais hplip-toolbox ou qq chose du genre, très pratique. 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 bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Oui, c'est le paquet hplip-gui qui se lance en terminal par hplip-toolbox => Doc hplip Mais, bon, ça ne m'a rien apporté de plus... Mon imprimante n'est toujours pas reconnue. "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne grigouille Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . man hp-setup ? Xubuntu 14.04 Hors ligne bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Avec hp-setup, j'ai toujours "No devices found", même en lançant une recherche manuelle avec l'adresse IP de l'imprimante. Je me demande s'il ne faudrait pas un routeur ou un switch entre mon PC et l'imprimante? "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne Brunod Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Normalement non, pas si chacun a une ip fixe. 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 Korak Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Bonjour, ni de port série sur ma carte mère Pour une imprimante, c'est plutôt un port parallèle. Si tu as un PC fixe, une carte port parallèle coûte une vingtaine d'Euros. J'ai branché directement un câble RJ45 (croisé) de l'imprimante, vers ma carte réseau[ Sinon, essaie avec un câble réseau droit. OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne Brunod Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . @korak : j'ai un doute pour le changement de câble car le ping passe. 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 Korak Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . @korak : j'ai un doute pour le changement de câble car le ping passe. D'accord avec toi. Mais ça ne coûte rien d'essayer (si tu as déjà un câble droit). OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Salut à Brunod et Korak! J'ai essayé plusieurs combinaisons, avec câble droit, croisé, avec un routeur, branché directement... Toujours pareil, "No devices found" J'ai récupérer la doc HP pour l'administration d'une imprimante en réseau, c'est gratiné... A priori, je dois créer un fichier /etc/bootptab qui est lu au démarrage de l'imprimante, et dans lequel toutes les infos utiles sont données, comme le nom de l'imprimante, son adresse MAC, son adresse IP, etc... Je vais creuser cette piste... @ Korak: oui, c'est un port parallèle, je me suis honteusement trompé... "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne grigouille Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Je ne sais pas cela va aider mais http://hplipopensource.com/hplip-web/mo … tml#note11 dit que Parallell I/O : No Xubuntu 14.04 Hors ligne bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Oui effectivement, le port parallèle n'est pas proposé. Sinon, j'ai installé la dernière version de hplip (3.12.11) mais sans résultats. Si je lance hp-setup, j'ai toujours: hp-setup HP Linux Imaging and Printing System (ver. 3.12.11) Printer/Fax Setup Utility ver. 9.0 Copyright (c) 2001-14 Hewlett-Packard Development Company, LP This software comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to distribute it under certain conditions. See COPYING file for more details. QGtkStyle was unable to detect the current GTK+ theme. Searching... (bus=net, timeout=5, ttl=4, search=(None) desc=0, method=mdns) error: No devices found on bus: net "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne grigouille Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Il faudrait plutôt utiliser : sudo hp-setup -iax et éventuellement hp-check -r mais je ne pense pas que cela règle ton problème. Xubuntu 14.04 Hors ligne Titouan Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . pourtant, sur le hplip 3.12.11, ton imprimante ressort dans les datas. sudo updatedb && grep 4550 $(locate models.dat) as-tu les groupes lp,lpadmin ? id bowmore Hors ligne bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Alors... sudo updatedb && grep 4550 $(locate models.dat) /usr/share/hplip/data/models/models.dat:model5=HP Officejet J4550 All-in-One Printer /usr/share/hplip/data/models/models.dat:model2=HP Photosmart C4550 All-in-One Printer /usr/share/hplip/data/models/models.dat:[hp_color_laserjet_4550] /usr/share/hplip/data/models/models.dat:model1=HP Color LaserJet 4550 Printer /usr/share/hplip/data/models/models.dat:model2=HP Color LaserJet 4550n Printer /usr/share/hplip/data/models/models.dat:model3=HP Color LaserJet 4550dn Printer /usr/share/hplip/data/models/models.dat:model4=HP Color LaserJet 4550hdn Printer /usr/share/hplip/data/models/models.dat:model5=HP Color LaserJet 4550n Plus Printer /usr/share/hplip/data/models/models.dat:model6=HP Color LaserJet 4550hdn Plus Printer et... id bowmore uid=1000(bowmore) gid=1000(bowmore) groupes=1000(bowmore),4(adm),6(disk),7(lp),24(cdrom),27(sudo),30(dip),46(plugdev),107(lpadmin),115(sambashare) Sinon, j'ai lancé: hp-check -r HP Linux Imaging and Printing System (ver. 3.12.11) Dependency/Version Check Utility ver. 15 Copyright (c) 2001-14 Hewlett-Packard Development Company, LP This software comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to distribute it under certain conditions. See COPYING file for more details. Note: hp-check can be run in three modes: 1. Compile-time check mode (-c or --compile): Use this mode before compiling the HPLIP supplied tarball (.tar.gz or .run) to determine if the proper dependencies are installed to successfully compile HPLIP. 2. Run-time check mode (-r or --run): Use this mode to determine if a distro supplied package (.deb, .rpm, etc) or an already built HPLIP supplied tarball has the proper dependencies installed to successfully run. 3. Both compile- and run-time check mode (-b or --both) (Default): This mode will check both of the above cases (both compile- and run-time dependencies). Check types: a. EXTERNALDEP - External Dependencies b. GENERALDEP - General Dependencies (required both at compile and run time) c. COMPILEDEP - Compile time Dependencies d. [All are run-time checks] PYEXT SCANCONF QUEUES PERMISSION Status Types: OK MISSING - Missing Dependency or Permission or Plug-in INCOMPAT - Incompatible dependency-version or Plugin-version Saving output in log file: /home/bowmore/hp-check.log Initializing. Please wait... --------------- | SYSTEM INFO | --------------- Kernel: 3.2.0-37-generic #58-Ubuntu SMP Thu Jan 24 15:28:10 UTC 2013 GNU/Linux Host: Alpha Proc: 3.2.0-37-generic #58-Ubuntu SMP Thu Jan 24 15:28:10 UTC 2013 GNU/Linux Distribution: ubuntu 12.04 ----------------------- | HPLIP CONFIGURATION | ----------------------- HPLIP-Version: HPLIP 3.12.11 HPLIP-Home: /usr/share/hplip HPLIP-Installation: Auto installation is supported for ubuntu distro 12.04 version Current contents of '/etc/hp/hplip.conf' file: # hplip.conf. Generated from hplip.conf.in by configure. [hplip] version=3.12.11 [dirs] home=/usr/share/hplip run=/var/run ppd=/usr/share/ppd/HP ppdbase=/usr/share/ppd doc=/usr/share/doc/hplip-3.12.11 icon=/usr/share/applications cupsbackend=/usr/lib/cups/backend cupsfilter=/usr/lib/cups/filter drv=/usr/share/cups/drv/hp # Following values are determined at configure time and cannot be changed. [configure] network-build=yes libusb01-build=no pp-build=no gui-build=yes scanner-build=yes fax-build=yes dbus-build=yes cups11-build=no doc-build=yes shadow-build=no hpijs-install=no foomatic-drv-install=no foomatic-ppd-install=no foomatic-rip-hplip-install=no hpcups-install=yes cups-drv-install=yes cups-ppd-install=no internal-tag=3.12.11 restricted-build=no ui-toolkit=qt4 qt3=no qt4=yes policy-kit=no hpijs-only-build=no lite-build=no udev-acl-rules=yes udev_sysfs_rules=no hpcups-only-build=no hpijs-only-build=no Current contents of '/var/lib/hp/hplip.state' file: # hplip.state - HPLIP runtime persistent variables. [plugin] installed=0 eula=0 Current contents of '~/.hplip/hplip.conf' file: [settings] systray_visible = 0 systray_messages = 0 [last_used] device_uri = printer_name = working_dir = . [commands] scan = /usr/bin/simple-scan %SANE_URI% [refresh] rate = 30 enable = false type = 1 [polling] enable = false interval = 5 device_list = [fax] voice_phone = email_address = [installation] date_time = 13/02/2013 16:08:42 version = 3.12.11 [upgrade] notify_upgrade = true last_upgraded_time = 1360760563 pending_upgrade_time = 0 latest_available_version = 3.12.11 <Package-name> <Package-Desc> <Required/Optional> <Min-Version> <Installed-Version> <Status> <Comment> -------------------------- | External Dependencies | -------------------------- gs Ghostscript REQUIRED 7.05 9.05 OK - network Network-wget OPTIONAL - 1.13.4 OK - dbus DBus REQUIRED - 1.4.18 OK - scanimage Shell-Scanning OPTIONAL 1.0 1.0.22 OK - policykit Admin-Policy-framework OPTIONAL - 0.104 OK - xsane SANE-GUI OPTIONAL 0.9 0.998 OK - cups CUPS REQUIRED 1.1 1.5.3 OK 'CUPS Scheduler is running' ------------------------- | General Dependencies | ------------------------- reportlab Python-PDF-Lib OPTIONAL 2.0 2.5 OK - libcrypto OpenSSL-Crypto-Lib REQUIRED - 1.0.1 OK - pil Python-Image-Lib OPTIONAL - 1.1.7 OK - pyqt4-dbus PyQt4-DBUS REQUIRED 4.0 4.9.1 OK - libjpeg JPEG-Lib REQUIRED - - OK - libpthread POSIX-Threads-Lib REQUIRED - 2.15 OK - python-dbus Python-DBUS REQUIRED 0.80.0 1.0.0 OK - python-devel Python-SDK REQUIRED 2.2 2.7.3 OK - pyqt4 Python-Qt4 REQUIRED 4.0 4.9.1 OK - cups-devel CUPS-SDK REQUIRED - 1.5.3 OK - sane-devel SANE-SDK REQUIRED - 1.0.22 OK - libusb USB-Lib REQUIRED - 1.0 OK - sane Scan-Lib REQUIRED - 1.0.22 OK - cups-image CUPS-Image-Lib REQUIRED - 1.5.3 OK - libnetsnmp-devel SNMP-Networking-SDK REQUIRED 5.0.9 5.4.3 OK - python-xml Python-XML-Lib REQUIRED - 2.0.1 OK - python-notify Desktop-notifications OPTIONAL - - OK - ---------------------- | Python Extentions | ---------------------- cupsext CUPS-Extension REQUIRED - 3.12.11 OK - pcardext PhotoCard-Extension REQUIRED - 3.12.11 OK - hpmudext IO-Extension REQUIRED - 3.12.11 OK - ----------------------- | Scan Configuration | ----------------------- hpaio HPLIP-SANE-Backend REQUIRED - 3.12.11 OK 'hpaio found in /etc/sane.d/dll.conf' scanext Scan-SANE-Extension REQUIRED - 3.12.11 OK - ------------------------------ | DISCOVERED SCANNER DEVICES | ------------------------------ No Scanner found. -------------------------- | DISCOVERED USB DEVICES | -------------------------- No devices found. --------------------------------- | INSTALLED CUPS PRINTER QUEUES | --------------------------------- WARNING ------- Type: Unknown Device URI: gnome-keyring:: couldn't connect to: /tmp/keyring-wU4hYc/pkcs11: Aucun fichier ou dossier de ce type LaserJet -------- Type: Unknown Device URI: socket://192.0.0.192:9100 PPD: /etc/cups/ppd/LaserJet.ppd PPD Description: HP Color LaserJet 4550 Foomatic/ljet4 Printer status: WARNING: gnome-keyring:: couldn't connect to: /tmp/keyring-wU4hYc/pkcs11: Aucun fichier oprinter The printer is busy.g LaserJet-23. enabled since mer. 13 févr. 2013 11:30:35 CET warning: Printer is not HPLIP installed. Printers must use the hp: or hpfax: CUPS backend for HP-Devices. -------------- | PERMISSION | -------------- error: groups user-groups Required - - MISSING lp ----------- | SUMMARY | ----------- Missing Required Dependencies ----------------------------- None Missing Optional Dependencies ----------------------------- None Total Errors: 1 Total Warnings: 1 Re-run 'hp-check --fix' command to prompt and fix the issues. Done. J'ai donc lancé comme demandé: hp-check --fix Et je dois rebooter pour avoir les changements validés... A tout de suite. "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Pas mieux... "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne Titouan Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . sudo hp-plugin si en automatique, cela ne marche pas, télécharge à l'adresse suivante http://www.openprinting.org/download/pr … P/plugins/ sudo sh hplip-*plugin.run http://localhost:631 Hors ligne Korak Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . Si tu as un PC fixe, une carte port parallèle coûte une vingtaine d'Euros. Si tu as un PC fixe, arrête de te casser la tête et achète une carte port parallèle. J'en ai acheté une pour le PC fixe de ma compagne. C'est une Manhattan Serial/Parallel combo PCI Card (deux ports série DB9 + un port parallèle DB25) Elle fonctionne directement sous Ubuntu 12.04 64 bits et ne coûte que 17,95 €. OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne bowmore Re : Problème avec une HP Color LaserJet 4550N branchée en Ethernet . oui, ça pourrait être une solution... "Bon bah, je vais essayer de ne pas claquer la porte en sortant" Buzz Aldrin, le 21 juillet 1969 sur la Mer de la Tranquillité Hors ligne
I'm trying to use Tastypie with ManyToMany relationships using intermediate models (through keyword) (https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships) I'm working with these models: class Point(models.Model): ... value = models.FloatField(_('Value'), null=True) rooms = models.ManyToManyField('rooms.Room', through='points.PointPosition') class Room(models.Model): title = models.CharField(max_length=64) class PointPosition(models.Model): point = models.ForeignKey('points.Point', verbose_name=_('Point')) room = models.ForeignKey('rooms.Room', verbose_name=_('Room')) x = models.IntegerField(_('Y')) y = models.IntegerField(_('X')) I've been able to fetch the many-to-many relationship, but not the extra fields. Here's my tastypie code: class PointResource(ModelResource): class Meta: queryset = Point.objects.select_related( depth=10 ).prefetch_related('rooms').all() resource_name = 'point' allowed_methods = ['get'] ... value = fields.FloatField() rooms = fields.ToManyField('rooms.api.RoomResource', 'rooms', full=True) class RoomResource(ModelResource): class Meta: queryset = Room.objects.all() resource_name = 'room' allowed_methods = ['get'] I've been trying to use a method to hydrate the room variable in my PointResource like this: def dehydrate_rooms(self, bundle): rooms = [] for room in bundle.obj.rooms.all(): position = PointPosition.objects.get( room_id = room.pk, point_id = bundle.obj.pk) rooms.append({'id': room.pk, 'title': room.title, 'x': position.x, 'y': position.y}) return rooms But the problem is that it creates as many query as I have points: it's a real performance killer when you have +8000 Points. I haven't been able to find any useful resources to gain performance. I was thinking of doing a custom query using the .extra() method available for QuerySet, but the JOIN keyword isn't available (the patch has been refused a couple months ago). And I'm not sure SELECT subqueries would do the trick.
pandageek MCedit pour minecraft bonjour a tous, je joue à minecraft version linux sous xubuntu et j'aimerai pouvoir utiliser le logiciel MCedit qui sert a éditer les cartes du jeu. or il ne fonctionne pas malgré mes tentatives : panda@panda-USB:~/Bureau/MCEdit-stable33-linux$ ./mcedit.sh RuntimeError: Bad magic number in .pyc file panda@panda-USB:~/Bureau/MCEdit-stable33-linux$ sh mcedit.sh python: can't open file 'mcedit.sh/MCEditData/mcedit.pyo': [Errno 20] Not a directory panda@panda-USB:~/Bureau/MCEdit-stable33-linux$ bash mcedit.sh python: can't open file 'mcedit.sh/MCEditData/mcedit.pyo': [Errno 20] Not a directory merci de m'aider! Hors ligne pandageek Re : MCedit pour minecraft personne? Hors ligne abelthorne Re : MCedit pour minecraft Les erreurs me font penser que le fichier est corrompu. Tu as essayé de le retélécharger ? En ligne pandageek Re : MCedit pour minecraft après re-téléchargement j’obtiens ceci. panda@panda-USB:~/Bureau/MCEdit-stable33-linux$ ./mcedit.sh Loading imports... Adding SafeOutputStream... Release: stable33 Loading OpenGL... Traceback (most recent call last): File "mcedit.py", line 102, in <module> File "/usr/lib/pymodules/python2.7/OpenGL/GL/__init__.py", line 2, in <module> from OpenGL.raw.GL import * File "/usr/lib/pymodules/python2.7/OpenGL/raw/GL/__init__.py", line 6, in <module> from OpenGL.raw.GL.constants import * File "/usr/lib/pymodules/python2.7/OpenGL/raw/GL/constants.py", line 7, in <module> from OpenGL import platform, arrays File "/usr/lib/pymodules/python2.7/OpenGL/platform/__init__.py", line 36, in <module> _load() File "/usr/lib/pymodules/python2.7/OpenGL/platform/__init__.py", line 27, in _load plugin_class = plugin.load() File "/usr/lib/pymodules/python2.7/OpenGL/plugins.py", line 14, in load return importByName( self.import_path ) File "/usr/lib/pymodules/python2.7/OpenGL/plugins.py", line 28, in importByName module = __import__( ".".join(moduleName), {}, {}, moduleName) File "/usr/lib/pymodules/python2.7/OpenGL/platform/glx.py", line 8, in <module> class GLXPlatform( baseplatform.BasePlatform ): File "/usr/lib/pymodules/python2.7/OpenGL/platform/glx.py", line 20, in GLXPlatform raise ImportError("Unable to load OpenGL library", *err.args) ImportError: ('Unable to load OpenGL library', "GL: Ne peut ouvrir le fichier d'objet partag\xc3\xa9: Aucun fichier ou dossier de ce type", 'GL', None) Startup failed. Please send a copy or screenshot of this error to codewarrior0@gmail.com Hors ligne pandageek Re : MCedit pour minecraft tout est déjà installé correctement. Hors ligne pandageek Re : MCedit pour minecraft up? Hors ligne pandageek Re : MCedit pour minecraft up Hors ligne pandageek Re : MCedit pour minecraft longtemps après, en cherchant une solution, je retrouve mon vieux topic... le message à changé : # python mcedit.py Running in development mode! Traceback (most recent call last): File "mcedit.py", line 13, in <module> import albow File "/home/panda/mcedit/albow/__init__.py", line 13, in <module> from albow.shell import Shell File "/home/panda/mcedit/albow/shell.py", line 5, in <module> from root import RootWidget File "/home/panda/mcedit/albow/root.py", line 13, in <module> from glbackground import * File "/home/panda/mcedit/glbackground.py", line 21, in <module> from albow.openglwidgets import GLOrtho File "/home/panda/mcedit/albow/openglwidgets.py", line 8, in <module> from OpenGL import GL, GLU File "/usr/lib/pymodules/python2.7/OpenGL/GL/__init__.py", line 2, in <module> from OpenGL.raw.GL import * File "/usr/lib/pymodules/python2.7/OpenGL/raw/GL/__init__.py", line 6, in <module> from OpenGL.raw.GL.constants import * File "/usr/lib/pymodules/python2.7/OpenGL/raw/GL/constants.py", line 7, in <module> from OpenGL import platform, arrays File "/usr/lib/pymodules/python2.7/OpenGL/platform/__init__.py", line 36, in <module> _load() File "/usr/lib/pymodules/python2.7/OpenGL/platform/__init__.py", line 27, in _load plugin_class = plugin.load() File "/usr/lib/pymodules/python2.7/OpenGL/plugins.py", line 14, in load return importByName( self.import_path ) File "/usr/lib/pymodules/python2.7/OpenGL/plugins.py", line 28, in importByName module = __import__( ".".join(moduleName), {}, {}, moduleName) File "/usr/lib/pymodules/python2.7/OpenGL/platform/glx.py", line 8, in <module> class GLXPlatform( baseplatform.BasePlatform ): File "/usr/lib/pymodules/python2.7/OpenGL/platform/glx.py", line 20, in GLXPlatform raise ImportError("Unable to load OpenGL library", *err.args) ImportError: ('Unable to load OpenGL library', 'GL: cannot open shared object file: No such file or directory', 'GL', None) petit up en fait Hors ligne
Topic: PostfixCourierIMAP MySQL Virt. hosts + optionals ClamAV & SpamAssassin Preamble I take no credit for the immense hardwork done by several people; this howto is built extensively upon their howtos which can (at the time of this writing) be found here: http://kirb.insanegenius.net/postfix.html http://www.ezunix.org/modules.php?op=mo … amp;page=1 http://ntecs.de/blog/Tech/Sysadm I thank them greatly for what they have done, and for making this possible. I am simply using their howtos to create a complete as possible NetBSD version. A *LOT* of this howto will be a direct copy of their work - I am NOT taking credit for those bits! Although this howto is predominantly aimed at NetBSD, only the location of files and the process used to start each of the daemons should be NetBSD specific - the rest should be generic in nature. Purpose The purpose behind this document is to create a mail server solution that includes postfix as the MTA, Courier-IMAP as the IMAP/POP server and MySQL for all potentially dynamic configuration. The goal is to have completely virtual users and domains. jimbob@domain1.com != jimbob@domain2.com. This means creating a separate namespace for each domain. Theory The first thought is how to create that separate namespace. Using Postfix virtual delivery agent, the problem is relatively trivialized. You just deliver mail to the appropriate maildir for the appropriate address. Postfix really doesn't care that you have multiple people named jimbob because it looks at the entire address. Separate namespace for Courier gets a little trickier. You could ask all of your users to login as user@domain.com or user.domain.com or even user.somenumber and this is the best solution we've come up with so far. The problem with user@domain.com logins is that drain bamaged MUA's may interpret that to mean one's complete address is "user@domain.com@domain.com". Needless to say, this is bad. Of course, the same faulty MUA's might cause problems with thinking "user.domain.com@domain.com" is the address... Installation I'm a *HUGE* fan of pkgsrc, so recommend its use where possible. We first need to setup our needed options which is done by adding them to /etc/mk.conf: # echo "PKG_OPTIONS.courier-authlib=mysql" >> /etc/mk.conf # echo "PKG_OPTIONS.postfix=mysql" >> /etc/mk.conf Now, to install the programs needed, simply: # cd /usr/pkgsrc/databases/mysql4-server # make install clean clean-depends # cd /usr/pkgsrc/security/courier-authlib # make install clean clean-depends # cd /usr/pkgsrc/mail/courier-imap # make install clean clean-depends # cd /usr/pkgsrc/mail/postfix # make install clean clean-depends this will install all that we need to complete this HowTo. Setup and Start MySQL You can start the MySQL server doing the following steps: # echo "mysqld=yes" >> /etc/rc.conf # cp /usr/pkg/share/examples/rc.d/mysqld /etc/rc.d # /etc/rc.d/mysqld start You now need to set the root password to secure your db, change new-password to suit your memory: /usr/pkg/bin/mysqladmin -u root -p password 'new-password' /usr/pkg/bin/mysqladmin -h `hostname` -u root -p password 'new-password' The Database Here is the quick description of the database: mysql> show tables; +------------------+ | Tables_in_maildb | +------------------+ | transport | | users | | virtual | +------------------+ 3 rows in set (0.00 sec) mysql> describe transport; +-----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+-------+ | domain | varchar(128) | | PRI | | | | transport | varchar(128) | | MUL | | | +-----------+--------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> describe virtual; +---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | address | varchar(255) | | PRI | | | | goto | varchar(255) | | | | | +---------+--------------+------+-----+---------+-------+ 2 rows in set (0.01 sec) mysql> describe users; +---------+----------------------+------+-----+----------------------------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+----------------------+------+-----+----------------------------+-------+ | id | varchar(128) | | PRI | | | | address | varchar(128) | | UNI | | | | crypt | varchar(128) | | | | | | clear | varchar(128) | | | | | | name | varchar(128) | | | | | | uid | smallint(5) unsigned | | | 0 | | | gid | smallint(5) unsigned | | | 0 | | | home | varchar(128) | | | /var/spool/postfix/virtual | | | domain | varchar(128) | | | | | | maildir | varchar(255) | | | | | | imapok | tinyint(3) unsigned | | | 1 | | | bool1 | tinyint(3) unsigned | | | 1 | | | bool2 | tinyint(3) unsigned | | | 1 | | +---------+----------------------+------+-----+----------------------------+-------+ 13 rows in set (0.01 sec) Database NotesTransport table: The transport table is your transport map. It tells postfix what transport agent to use for each domain. It is not absolutely necessary if you want all of your users to be in the database. We do , however, highly recommend using a transport map. Having at least one domain handled with the local delivery agent means, among other things, simplicity if you have to deal with mailing lists later and that any users added to the system as system users will automatically receive mail properly. Even if you have domains explicitly defined in the mydestinations config option for postfix, you should make sure that every domain has a corresponding entry in the transport map. Another nice feature of the transport map is that you do not have to define mydestinations explicitly, simply add $transport_maps to mydestinations and you have all your domains added cleanly and effectively without having to reload Postfix when you add a domain. domain = Any domain you host. Including those you want to deliver to using local: as the transport. transport = The transport method. All transport methods are legal, but usually either "local:" for local transport or "virtual:" for the virtual transport agent. Virtual table: The virtual table is your virtual map. It is similar to aliases, but different. An entry in virtual cannot point to an executable or a file. It is simply address to address mapping. However, this doesn't mean it has to be one to one. You can have a single virtual alias point to multiple addresses in a comma-delimited list. The important thing to remember is that you can have either sendmail-style or postfix-style virtual domains. Under sendmail-style, all local aliases and users exist in the virtual domain's namespace as well. In other words, a local user jimbob would be able to recieve jimbob@virtual1.com, jimbob@virtual2.com, and jimbob@localmachinedomain.com all at the same time. This can cause a problem when hosting many domains (or only a few if you have more than one user named JimBob.) Enter postfix-style virtuals. With a postfix-style virtual, the virtual domain doesn't share anything. You must define every alias and/or user within that domain. One caveat is that this means root and postmaster aliases must be defined for every postfix-style virtual. In order to implement a postfix-style virtual, you will need one line in your virtual map that has the domain name on the left, and some random text on the right. One handy way of doing this in a database virtual table is to have an entry where address is the domain name and goto is the name of the domain owner, or some other informative little piece of text. A nice convention is to use sendmail-style virtuals on all of your domains that are delivered with the local delivery agent and postfix-style on all of your domains delivered with the virtual agent. For a more thorough description of the virtual table and sendmail-style vs. postfix-style virtuals, please read "man 5 virtual". address = This is the virtual address address@domain.tld which will be forwarded to the address in goto. For Postfix-style virtuals, this will also be the domain name. goto = Where the virtual address above goes. This can be a comma-delimited list of addresses. It can include simply "user" entries for local users (root, postmaster, etc.), or, more commonly, complete user@domain.tld entries for users in virtual domains on your machine or for going out to other domains. Users table: The users table is the heart and soul of this whole thing. Transport and Virtual can easily be done as text files, but the users table makes this all worthwhile. While the other two tables are used only by Postfix, this table is shared between Postfix and Courier. That leads to interesting decisions in design. First of all, some will note the different id and address fields. In some cases, these fields may be identical. In that case, remove the address field, and replace address in all postfix config files with id. The reason there are two different fields is so you can use user.domain.tld, or user.somenumber or something along those lines rather than user@domain.tld as a username. If you plan on using user@domain.tld for logins and never changing it, don't waste space on an address field. Another important thing to remember is that the encrypted form of the password must be encrypted using the OS crypt(), not with MySQL's default encryption algorithm. This can be done by using crypt=encrypt('password') in your insert or update statement. You can increase the security of this by giving encrypt a second argument of a two-character salt. If you write a user management program to handle your data additions and updates, then creating it randomly will be useful. You can then use encrypt('password','salt') for the improved security. You also should note that you can have as many or as few (including none) of the fields beginning with "imapok" above. Those fields are not required, but can come in handy as mentioned in the table description. Also, remember that if you would like to use the maildir quota extension in courier-imap, you will need to add a quota field to hold that. Probably an unsigned int would be more than sufficient. Important I have recently found that spaces within the passwd (crypted / unencrypted) seem very hit and miss as to whether they work. I suggest NOT using spaces - so be warned. id = username. Either user.domain.tld or user@domain.tld address = email address. user@domain.com crypt = The crypt() form of the password. The easies way to accomplish this is to use encrypt('password') in your insert query clear = Clear text password. (for support purposes or Cram-MD5) You really only need one of the two password forms. If you choose that one to be clear, make sure ALL of your users can handle Cram-MD5 authentication name = Users real name or whatever string you feel belongs here. (not required unless you tell Courier it's there.) uid = virtual uid gid = virtual gid. (hint to make your life simpler: Make each domain have one and only one gid) home = You can set this to just about anything above your maildir directory. Easiest (but not very secure) is to set it to "/". If you are running postfix chroot, this needs to be somewhere inside of the jail. For instance, "/var/spool/postfix/". And, yes, the maildirs must all be subdirectories of this directory domain = user's domain name. This is far from necessary but comes in handy for support/programming purposes maildir = This is the users maildir. Use the full path. You don't have to, but use the full path. If this is a maildir, make sure that you include the trailing slash. (e.g. .../Maildir/ and NOT .../Maildir) Of course, if you want to use mbox (why, oh why?!) then you would need to exclude the slash imapok = This field would allow one to prevent users from accessing their mail by setting it to 0 if you use the appropriate Courier setting in authmysqlrc of "MYSQL_WHERE_CLAUSE= imapok" This could be useful for torturing your users, among other things bool1 = Same as above bool2 = ditto. (yes, Kirby is an aspiring BOFH, how'd you guess?) Create the Database To make your (our) life easier, a MySQL database creation script has been created. Simply copy the mysql script into a 'filename' and at the command line type: # mysql -u root -p < filenameEnter password:# issuing the password you created above (the new-password one). Here's the mysql script: #First Create the Database CREATE DATABASE maildb; use maildb; # # Table structure for table 'transport' # CREATE TABLE transport ( domain varchar(128) NOT NULL default '', transport varchar(128) NOT NULL default '', UNIQUE KEY domain (domain) ) TYPE=MyISAM; # # Table structure for table 'users' # CREATE TABLE users ( id varchar(128) NOT NULL default '', address varchar(128) NOT NULL default '', crypt varchar(128) NOT NULL default '', clear varchar(128) NOT NULL default '', name varchar(128) NOT NULL default '', uid smallint(5) unsigned NOT NULL default '1000', gid smallint(5) unsigned NOT NULL default '1000', home varchar(128) NOT NULL default '/var/spool/postfix/virtual', domain varchar(128) NOT NULL default '', maildir varchar(255) NOT NULL default '', imapok tinyint(3) unsigned NOT NULL default '1', bool1 tinyint(3) unsigned NOT NULL default '1', bool2 tinyint(3) unsigned NOT NULL default '1', PRIMARY KEY (id), UNIQUE KEY id (id), UNIQUE KEY address (address), KEY id_2 (id), KEY address_2 (address) ) TYPE=MyISAM; # # Table structure for table 'virtual' # CREATE TABLE virtual ( address varchar(255) NOT NULL default '', goto varchar(255) NOT NULL default '', UNIQUE KEY address (address) ) TYPE=MyISAM; Now we create our user and password to access the DB: # mysql -u root -p maildb Enter password: mysql> GRANT ALL ON maildb.* TO 'uname'@'localhost' IDENTIFIED BY 'passwd'; Query OK, 0 rows affected (0.01 sec) mysql>FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) mysql> \q Bye # Further Notes on the Database You might, after looking at the above, be wondering why on a few data type and indexing choices. Well, according to the mysql docs, varchar is faster in lookups and takes less space than char, so that's why it is used for all strings here. As for the size of integers, it was just logical choosing based on potential size of the values. In the case of the essentially boolean values, even the tinyint given to them is too much. These could easily be defined as "int(1) unsigned" if MySQL allows. You could also go with ENUM as a data type for these. See MySQL docs for more details. As for indexing and such, it's a good idea to have both id and address unique and indexed for faster lookups since almost every select performed on the users table will include either id or address in the where clause. On transport, it's a good idea to index the domain field. On virtual, you definitely want address indexed. Your virtual table will get very large, very quickly, when you consider that every virtual domain will have three minimum entries. As you can see, the general idea is to index any field that is likely to show up in a where clause in database query. One other thing on the database: If you run Postfix in a chroot jail, and you are using localhost as your mysql server, you might want to add a hardlink to the mysql socket somewhere inside the jail/sandbox you are running in. Of course, this will likely break when you restart the MySQL server. Instead, it would be better to just use TCP. You can even use TCP with everything on the same system. Consult the MySQL documentation for details. Configure Postfix run the following command to update main.cf and master.cf with the latest Postfix services and configuration directives: # /usr/pkg/sbin/postfix upgrade-configuration Configure postfix to start on boot # echo "postfix=YES" >> /etc/rc.conf # echo "sendmail=NO" >> /etc/rc.conf The existing /etc/rc.d/postfix can be forced to start /usr/pkg/sbin/postfix instead of /usr/sbin/postfix, by adding the following lines to /etc/rc.conf.d/postfix: required_files='/usr/pkg/etc/postfix/main.cf' start_cmd='/usr/pkg/sbin/postfix start' stop_cmd='/usr/pkg/sbin/postfix stop' reload_cmd='/usr/pkg/sbin/postfix reload' Before we can start changing system wide files we need to stop sendmail; find the process and kill it: # ps aux | grep sendmailroot 500 0.0 0.5 1012 1828 ?? Ss Wed08AM 0:03.61 sendmail: accepting connections # kill 500# /etc/mailer.conf needs to be updated with the correct information. Change it to the following: sendmail /usr/pkg/sbin/sendmail send-mail /usr/pkg/sbin/sendmail mailq /usr/pkg/sbin/sendmail newaliases /usr/pkg/sbin/sendmail If you don't want all users, including those locally defined to be in the database, you'll want to set up a transport map. We used a database-driven transport map as described above. We will assume transport to be either "virtual:" for virtual delivery or "local:" for local delivery. Other methods are available, but are beyond the scope of this howto. The files listed here will be in your postfix config directory, which will be /usr/pkg/etc/postfix in main.cf add the following lines transport_maps=mysql:/usr/pkg/etc/postfix/transport.cf mydestination = $mydomain, $myhostname, $transport_maps virtual_mailbox_maps=mysql:/usr/pkg/etc/postfix/mysql_virt.cf virtual_uid_maps=mysql:/usr/pkg/etc/postfix/uids.cf virtual_gid_maps=mysql:/usr/pkg/etc/postfix/gids.cf #You might want to change the following to something you'd prefer - BUT the 'home' field in the database MUST match virtual_mailbox_base=/var/spool/postfix/virtual virtual_maps=mysql:/usr/pkg/etc/postfix/virtual.cf # The following two lines are optional, and hopefully self explanitory virtual_mailbox_limit=102400000 # 100MB virtual_minimum_uid=100 in master.cf you need to uncomment or add these lines if they aren't already there. smtp inet n - n - - smtpdvirtual unix - n n - - virtual Now create the following files: transport.cf user=uname password=passwd dbname=maildb table=transport select_field=transport where_field=domain hosts=localhost mysql_virt.cf user=uname password=passwd dbname=maildb table=users select_field=maildir where_field=address hosts=localhost uids.cf user=uname password=passwd dbname=maildb table=users select_field=uid where_field=address hosts=localhost gids.cf user=uname password=passwd dbname=maildb table=users select_field=gid where_field=address hosts=localhost virtual.cf user=uname password=passwd dbname=maildb table=virtual select_field=goto where_field=address hosts=localhost Configure Courier-IMAP The file to edit in Courier-IMAP is "authmysqlrc". You'll want to define the following within it appropriately. I've noticed that the sample config file is well-commented on my installation. Hopefully the same is true for you. If you do not see a authmysqlrc.dist or some sample authmysqlrc, the below should give you a working configuration. There are a few other options, but we will not cover them here as they are unnecesary for our purposes. One of note is MYSQL_QUOTA_FIELD which allows you to use the courier quota extensions to maildir. The files below should be located in your courier-auth directory, /usr/pkg/etc/authlib: Settings in authmysqlrc MYSQL_SERVER localhost #your mysql server MYSQL_USERNAME uname MYSQL_PASSWORD passwd MYSQL_SOCKET /tmp/mysql.sock #necessary if you are on localhost MYSQL_DATABASE maildb MYSQL_USER_TABLE users MYSQL_CRYPT_PWFIELD crypt MYSQL_CLEAR_PWFIELD clear MYSQL_UID_FIELD uid MYSQL_GID_FIELD gid MYSQL_LOGIN_FIELD id MYSQL_HOME_FIELD home MYSQL_NAME_FIELD name MYSQL_MAILDIR_FIELD maildir MYSQL_WHERE_CLAUSE imapok=1 AND bool1=1 AND bool2=1 IMPORTANT NOTE: key values should be seperated with tabs NOT spaces!!! Settings in authdaemonrc #replace authpam with whatever your local auth is, authpwd, authsasl, whatever.authmodulelist="authmysql authpam"# If you only want users who are in the database to login, then only use authmysql aboveversion="authdaemond.mysql" Sample Database Entries Here is a sample of what should be in your database. It's one domain, "foo.com" with a single user "John Doe" who has the email adree "johndoe@foo.com". He also has two aliases, "root@foo.com" and anything not already assigned to a mailbox at "foo.com": mysql> INSERT INTO transport VALUES ('foo.com', 'virtual:'); Query OK, 1 row affected (0.00 sec) mysql> select * from transport; +----------+-----------+ | domain | transport | +----------+-----------+ | foo.com | virtual: | +----------+-----------+ 1 row in set (0.01 sec) mysql> INSERT INTO virtual VALUES ('@foo.com', 'johndoe@foo.com'); Query OK, 1 row affected (0.00 sec) mysql> select * from virtual; +--------------+-----------------+ | address | goto | +--------------+-----------------+ | root@foo.com | johndoe@foo.com | | @foo.com | johndoe@foo.com | +--------------+-----------------+ 2 rows in set (0.00 sec) mysql> INSERT INTO users VALUES ('johndoe', 'johndoe@foo.com', encrypt('abc'), 'abc', 'John Doe', '5000', '5000', '/', 'foo.com', 'foo.com/johndoe/', '1', '1', '1'); Query OK, 1 row affected (0.00 sec) mysql> select * from users; +---------+-----------------+---------------+-------+----------+------+------+... | id | address | crypt | clear | name | uid | gid | +---------+-----------------+---------------+-------+----------+------+------+... | johndoe | johndoe@foo.com | uduM6SQn95Xjo | abc | John Doe | 5000 | 5000 | +---------+-----------------+---------------+-------+----------+------+------+... ...+----------------------------+---------+------------------+--------+-------+-------+ | home | domain | maildir | imapok | bool1 | bool2 | ...+----------------------------+---------+------------------+--------+-------+-------+ | /var/spool/postfix/virtual | foo.com | foo.com/johndoe/ | 1 | 1 | 1 | ...+----------------------------+---------+------------------+--------+-------+-------+ 1 row in set (0.00 sec) Create the directories Based upon the user we just created, we need to create our directory structure: # cd /var/spool/postfix # mkdir virtual # chown postfix:postfix virtual # cd virtual # mkdir foo.com # chown postfix:postfix foo.com # chmod 0775 foo.com # cd foo.com # mkdir johndoe # chmod 0770 johndoe # chown 5000:5000 johndoe Starting the services Now that everything is in place, we'll setup and start the services. Courier-Imap Auth # cp /usr/pkg/share/examples/rc.d/authdaemond /etc/rc.d # echo "authdaemond=YES" >> /etc/rc.conf # /etc/rc.d/authdaemond start Starting authdaemond. # Courier-Imap # cp /usr/pkg/share/examples/rc.d/courierimap /etc/rc.d # echo "courierimap=YES" >> /etc/rc.conf # /etc/rc.d/courierimap start Starting courierimap. # cp /usr/pkg/share/examples/rc.d/courierimaps /etc/rc.d # echo "courierimaps=YES" >> /etc/rc.conf # /etc/rc.d/courierimaps start Starting courierimaps. # Postfix # /etc/rc.d/postfix start postfix/postfix-script: starting the Postfix mail system # What about POP3? If you'd rather have your email users use pop3 (so the email load isn't sitting on your server) CourierIMAP includes a pop3 daemon which you simply need to "turn on": # cp /usr/pkg/share/examples/rc.d/courierpop /etc/rc.d/ # echo "courierpop=YES" >> /etc/rc.conf # /etc/rc.d/courierpop start Starting courierpop. # OPTIONAL CLAMAV VIRUS CHECKING Facing the realities of this world, you may be hosting email that contains viri. So the following will update postfix to use ClamAV to scan for viri: # cd /usr/pkgsrc/mail/clamav # make install clean clean-depends # cd /usr/pkgsrc/mail/clamsmtp # make install clean clean-depends First thing to do is update the viri database. Edit /usr/pkg/etc/clamd.conf and /usr/pkg/etc/freshclam.conf, and comment the "Example" line in both, which looks as follows: # Comment or remove the line below.Example Now update the viri database with this command (you may also want to cron this command to keep your database updated): # /usr/pkg/bin/freshclam ClamAV update process started at Sat Apr 2 22:08:55 2005 Downloading main.cvd [*] main.cvd updated (version: 30, sigs: 31086, f-level: 4, builder: tkojm) Downloading daily.cvd [*] daily.cvd updated (version: 802, sigs: 1273, f-level: 4, builder: arnaud) Database updated (32359 signatures) from database.clamav.net (IP: 62.26.160.3) # Now start ClamAV: # cp /usr/pkg/share/examples/rc.d/freshclamd /etc/rc.d/freshclamd # echo "freshclamd=YES" >> /etc/rc.conf # /etc/rc.d/freshclamd start Starting freshclamd. # cp /usr/pkg/share/examples/rc.d/clamd /etc/rc.d/clamd # echo "clamd=YES" >> /etc/rc.conf # /etc/rc.d/clamd start Starting clamd. # Now configure and start ClamSMTP: Edit /usr/pkg/etc/clamsmtpd.conf and add the following line in the appropriate place: ClamAddress: /tmp/clamd and start the daemon: # cp /usr/pkg/share/examples/rc.d/clamsmtpd /etc/rc.d/clamsmtpd # echo "clamsmtpd=YES" >> /etc/rc.conf # /etc/rc.d/clamsmtpd start Starting clamsmtpd. # Configure postfix to use ClamAV In main.cf add these lines: content_filter = scan:localhost:10025 receive_override_options = no_address_mappings In master.cf add these: # AV scan filter (used by content_filter) scan unix - - n - 16 smtp -o smtp_send_xforward_command=yes # For injecting mail back into postfix from the filter localhost:10026 inet n - n - 16 smtpd -o content_filter= -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks -o smtpd_helo_restrictions= -o smtpd_client_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o mynetworks_style=host -o smtpd_authorized_xforward_hosts=127.0.0.0/8 Now have Postfix use the new ClamAV setup: # /usr/pkg/sbin/postfix stop postfix/postfix-script: stopping the Postfix mail system # /usr/pkg/sbin/postfix start postfix/postfix-script: starting the Postfix mail system # Emails that are scanned will contain an extra header as follows: X-Virus-Scanned: ClamAV using ClamSMTP OPTIONAL SPAMASSASSIN CHECKING SpamAssassin is a well known app designed to tag email as spam based upon a score rating. The configuration specifics of SpamAssassin are beyond the scope of this HowTo, however, full details can be found at: http://spamassassin.apache.org/doc.html NetBSD's default location for the configuration files is : /usr/pkg/etc/spamassassin We first install spamassassin: # cd /usr/pkgsrc/mail/spamassassin # make install clean clean-depends You can now edit the main spamassassin config file to suit your needs /usr/pkg/etc/spamassassin/local.cf, although the default is actually quite good. Ensure you have at least the following: rewrite_header Subject *****SPAM***** A useful online generator can be found here: http://www.yrex.com/spam/spamconfig.php You can then easily create your own rules within the file. For example, the following searches for the word "pharmacy" in the body of emails utilising Perl's standard matching methodology; and then gives it a score of 1.0 - the default is 5.0 before the email is classed as spam: body PHARMACY_WORD_SEARCH /pharmacy/i score PHARMACY_WORD_SEARCH 1.0 Now we can start the SpamAssassin daemon (spamd): # cp /usr/pkg/share/examples/rc.d/spamd /etc/rc.d/spamd # echo "spamd=YES" >> /etc/rc.conf # /etc/rc.d/spamd start Starting spamd. # Finally, we simply need to tell Postfix to use SpamAssassin on all incoming emails via smtp. Edit the master.cf file and change this line: smtp inet n - n - - smtpd to this: smtp inet n - n - - smtpd -o content_filter=spamassassin and then at the end of the file add this: #SpamAssassin spamassassin unix - n n - - pipe user=nobody argv=/usr/pkg/bin/spamc -f -e /usr/pkg/sbin/sendmail -oi -f ${sender} ${recipient} and restart postfix. External emails sent in to your box will now include details such as these in the header: X-Spam-Flag: YES X-Spam-Checker-Version: SpamAssassin 3.0.2 (2004-11-16) on www.foo.com Last edited by WIntellect (2005-07-01 23:57:13) -- Copyright BSDnexus
Issues ZF-2375: Zend_Db_Statement_Mysqli::_execute() causes too much memory to be allocated. Description Zend_Db_Statement_Mysqli::_execute() calls mysqli_stmt_bind_result() *before* calling mysqli_stmt_execute(), and it does not call mysqli_stmt_store_result() or mysqli_stmt_free_result(). Modify the following test case to set the library path and to use the correct database connection parameters. <?php set_include_path(implode(PATH_SEPARATOR, array( '/opt/software/ZendFramework/1.0.3/library' , get_include_path() ))); require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); try { $dbh = Zend_Db::factory('mysqli', array( 'host' => '127.0.0.1', 'username' => 'phpunit', 'password' => 'phpunit', 'dbname' => 'test' )); $dbh->getConnection(); } catch (Zend_Exception $e) { echo $e->getMessage(); exit; } $dbh->query("DROP TABLE IF EXISTS `zend_testcase`"); $dbh->query(" CREATE TABLE `zend_testcase` ( `column_a` tinytext , `column_b` text , `column_c` mediumtext ) "); $dbh->query("INSERT INTO `zend_testcase` VALUES('a', 'b', 'c')"); $mem = memory_get_usage(); $dbh->query("SELECT `column_a` FROM `zend_testcase`"); echo "Memory Used(TINYTEXT ): " . (memory_get_usage() - $mem) . "\n"; $mem = memory_get_usage(); $dbh->query("SELECT `column_b` FROM `zend_testcase`"); echo "Memory Used(TEXT ): " . (memory_get_usage() - $mem) . "\n"; $mem = memory_get_usage(); $dbh->query("SELECT `column_c` FROM `zend_testcase`"); echo "Memory Used(MEDIUMTEXT): " . (memory_get_usage() - $mem) . "\n"; $dbh->query('DROP TABLE IF EXISTS `zend_testcase`'); ?> The output shows that the memory used corresponds roughly to the maximum size of the data-type being selected, which is what can be expected when not using mysqli_stmt_store_result() based on the bug report linked above. Memory Used(TINYTEXT ): 1516 Memory Used(TEXT ): 65324 Memory Used(MEDIUMTEXT): 16711680 If the sequence of events in Zend_Db_Statement_Mysqli::_execute is updated, and a call to mysqli_stmt_store_result() is added, the memory usage drops significantly: Memory Used(TINYTEXT ): 1296 Memory Used(TEXT ): 20 Memory Used(MEDIUMTEXT): 0 If this approach is used, calls to mysqli_stmt_free_result will also have to be added in the appropriate places.
If you have a lot of those pair things, using frozenset() is NOT a good idea. Use tuples instead. >>> import sys >>> fs1 = frozenset([42, 666]) >>> fs2 = frozenset([666, 42]) >>> fs1 == fs2 True >>> t1 = tuple(sorted([42, 666])) >>> t2 = tuple(sorted([666, 42])) >>> t1 == t2 True >>> sys.getsizeof(fs1) 116 >>> sys.getsizeof(t1) 36 >>> Update Bonus: sorted tuples have a predictable iteration sequence: >>> for thing in fs1, fs2, t1, t2: print [x for x in thing] ... [42, 666] [666, 42] [42, 666] [42, 666] >>> Update 2 ... and their repr() is the same: >>> repr(fs1) 'frozenset([42, 666])' >>> repr(fs2) 'frozenset([666, 42])' # possible source of confusion >>> repr(t1) '(42, 666)' >>> repr(t2) '(42, 666)' >>>
I would like to use properties from an inheriting model's Meta class to configure a field defined in an abstract model higher up the inheritance tree: class NamedModel(models.Model): class Meta: abstract = True verbose_name = 'object' name = models.CharField("Name", max_length=200, db_index=True, help_text="A meaningful name for this %s." % Meta.verbose_name) # see what I'm trying to do here? ) ... class OwnedModel(NamedModel): class Meta(NamedModel.Meta): verbose_name = 'owned object' I would like the help text on the name field of OwnedModel forms to say 'A meaningful name for this owned object'. But it does not: the word 'owned' is missing, which would suggest that the verbose_name from the NamedModel.Meta is used when the model is set up, not OwnedModel.Meta. This isn't quite what I expect from an inheritance point of view: is there some way to get the field to be created whereby Meta.verbose_name refers to the value on the non-abstract model class, not the abstract one on which the field was defined? Or am I being daft? (This may seem like a trivial example, and it is: but it's just to illustrate the point of something more important and complex I am trying to do) Many thanks in advance.
evann83 Mode superutilisateur Bonjour Me voici avec un soucis que je n'arrive pas a résoudre: j'aimera utiliser la commande "javac" pour pouvoir compiler un fichier java sur mon bureau mais apparement il n'a pas envie puisque il me demande d'installer la JDK, logique je me suis dis après coups. Me voilà parti pour installier la JDK, passage en superutilisateur avec "sudo su" puis installation de la JDK avec : apt-get install openjdk-7-jdk Et la fail, petit message d'erreur : " E: impossible de récupérer quelques archives, peut être devrez-vous lancer la commande apt-get update ou essayer avec --fix-missing" Je lance " sudo apt-get update" encore un message d'erreur "W: le téléchargement de quelques fichiers d'index à échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place" J'avoue que je suis un peu dans le floue artistique. Cordialement. Hors ligne Korak Re : Mode superutilisateur Bonjour, Quelle est ta version d'Ubuntu? Plus: ouvre un terminal et donne le retour complet (de la commande en elle-même jusqu'au retour au prompt) de la commande: sudo apt-get update Edit: En partie grillé par f.x0. Dernière modification par Korak (Le 27/01/2013, à 17:39) OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne tiramiseb Re : Mode superutilisateur "W: le téléchargement de quelques fichiers d'index à échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place" De nombreux messages dans ce forum traitent de cette erreur, à vrai dire parfois plusieurs dans la même semaine... As-tu un peu creusé ? Hors ligne evann83 Re : Mode superutilisateur Bonjour alors tout d'abord je suis sur une machine virtuel avec la version ubuntu 12.10 voici le résultat en entier: Err http://fr.archive.ubuntu.com precise InRelease Err http://fr.archive.ubuntu.com precise-updates InRelease Err http://fr.archive.ubuntu.com precise-backports InRelease Err http://security.ubuntu.com precise-security InRelease Err http://security.ubuntu.com precise-security Release.gpg Ne parvient pas à résoudre « security.ubuntu.com » Err http://fr.archive.ubuntu.com precise Release.gpg Ne parvient pas à résoudre « fr.archive.ubuntu.com » Err http://fr.archive.ubuntu.com precise-updates Release.gpg Ne parvient pas à résoudre « fr.archive.ubuntu.com » Err http://fr.archive.ubuntu.com precise-backports Release.gpg Ne parvient pas à résoudre « fr.archive.ubuntu.com » Lecture des listes de paquets... Fait W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/precise/InRelease W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/precise-updates/InRelease W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/precise-backports/InRelease W: Impossible de récupérer http://security.ubuntu.com/ubuntu/dists/precise-security/InRelease W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/precise/Release.gpg Ne parvient pas à résoudre « fr.archive.ubuntu.com » W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/precise-updates/Release.gpg Ne parvient pas à résoudre « fr.archive.ubuntu.com » W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/precise-backports/Release.gpg Ne parvient pas à résoudre « fr.archive.ubuntu.com » W: Impossible de récupérer http://security.ubuntu.com/ubuntu/dists/precise-security/Release.gpg Ne parvient pas à résoudre « security.ubuntu.com » W: Le téléchargement de quelques fichiers d'index a échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place. evann@evann-VirtualBox:~$ Hors ligne tiramiseb Re : Mode superutilisateur Tu n'as pas de résolution DNS. Comment as-tu configuré le réseau dans VirtualBox ? As-tu mis un paramétrage particulier ? Hors ligne Korak Re : Mode superutilisateur je suis sur une machine virtuel avec la version ubuntu 12.10 Cette erreur, et les suivantes: Err http://fr.archive.ubuntu.com precise InRelease Concerne des dépôts pour Ubuntu 12.04 (Precise) et pas pour Ubuntu 12.10 (Quantal). D'où les problèmes. Supprime les dépôts concernant Precise. OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne tiramiseb Re : Mode superutilisateur [...] Concerne des dépôts pour Ubuntu12.04(Precise) et pas pour Ubuntu12.10(Quantal). D'où les problèmes. Vraiment ? Un conflit entre la version de l'OS et les dépôts utilisés expliquerait un problème de résolution DNS ? evann83: ta machine virtuelle n'est-elle pas en 12.04 plutôt qu'en 12.10 ? Mes questions ci-dessus restent valables : Comment as-tu configuré le réseau dans VirtualBox ? As-tu mis un paramétrage particulier dans VirtualBox ? Et j'ajoute : Peux-tu exécuter les commandes suivantes ? ifconfig cat /etc/resolv.conf Hors ligne Korak Re : Mode superutilisateur Un conflit entre la version de l'OS et les dépôts utilisés expliquerait un problème de résolution DNS ? Non, je ne parle pas de problème de DNS. Ça m'étonnerais aussi que ce soit lié aux dépôts. Je parle seulement de la version de l'O.S. annoncée et des dépôts à problèmes. OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne tiramiseb Re : Mode superutilisateur Quels dépôts à problèmes ? Comment vois-tu qu'il y a des dépôts à problèmes ? Hors ligne Korak Re : Mode superutilisateur Ce que j'appelle "dépôts à problèmes", c'est ceux qui ne correspondent pas à l'O.S. annoncé. Pour l'histoire du DNS, je te laisse faire. Je comprend bien ce que signifie "Ne parvient pas à résoudre..." mais je ne suis pas assez calé sur ce point. C'est pour cette raison que je n'en ai pas parlé. Pour préciser ma pensée, il y aurait deux problèmes: - Le DNS. - Les dépôts ne correspondant pas à l'O.S. annoncé (ou evann83 s'est trompé dans la version de l'O.S.). OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne tiramiseb Re : Mode superutilisateur - Les dépôts ne correspondant pas à l'O.S. annoncé (ou evann83 s'est trompé dans la version de l'O.S.). Oui je suis d'accord. On attend donc le retour d'evann83 hein... (demain vers 10h du matin s'il garde le même rythme qu'entre ses deux premiers messages ) Hors ligne Korak Re : Mode superutilisateur On attend donc le retour d'evann83 hein... Oui, bien sûr. C'est le mieux. En espérant avoir une certification quand à la version de l'O.S.: 12.04 ou 12.10? OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne tiramiseb Re : Mode superutilisateur Allez, j'vais faire l’extrémiste de la langue française : s/quand/quant/ Hors ligne Korak Re : Mode superutilisateur j'vais faire l’extrémiste de la langue française : s/quand/quant/ Emmerdeur (et là, je suis sûr de l'orthographe). OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne evann83 Re : Mode superutilisateur Désolé de mon retard alors j'ai eu récemmennt un problème de connexion avec ma carte wifi, je l'ai résolu grâce à ce forum : http://forum.ubuntu-fr.org/viewtopic.ph … #p12319021 Oui sûr c'est 12_10 eth1 Link encap:Ethernet HWaddr 08:00:27:24:37:45 inet adr:192.168.30.72 Bcast:192.168.30.255 Masque:255.255.255.0 adr inet6: fe80::a00:27ff:fe24:3745/64 Scope:Lien UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 Packets reçus:22067 erreurs:0 :0 overruns:0 frame:0 TX packets:9977 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 lg file transmission:1000 Octets reçus:3401036 (3.4 MB) Octets transmis:1801559 (1.8 MB) Interruption:10 Adresse de base:0xd020 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:254 erreurs:0 :0 overruns:0 frame:0 TX packets:254 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 lg file transmission:0 Octets reçus:21006 (21.0 KB) Octets transmis:21006 (21.0 KB) # Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8) # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN nameserver 127.0.0.1 search newton Hors ligne tiramiseb Re : Mode superutilisateur Peux-tu nous donner également les retours de : lsb_release -a grep -h domain-name-servers /var/lib/dhcp/dhclient*.lease | uniq cat /etc/apt/sources.list ls /etc/apt/sources.list.d cat /etc/apt/sources.list.d/* host google.com apt-get update PS : Dans le premier message tu as écrit : passage en superutilisateur avec "sudo su" puis installation de la JDK avec : apt-get install openjdk-7-jdk C'est à éviter. Dans ce cas fais plutôt "sudo apt-get install openjdk-7-jdk". (et si tu veux passer en root, plutôt que de faire "sudo su" tu peux faire "sudo -i" ou "sudo -s", c'est un chouïa plus propre) Dernière modification par tiramiseb (Le 30/01/2013, à 18:09) Hors ligne evann83 Re : Mode superutilisateur lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.04.1 LTS Release: 12.04 Codename: precise grep -h domain-name-servers /var/lib/dhcp/dhclient*.lease | uniq option domain-name-servers 192.168.30.1; option domain-name-servers 192.168.1.1; option domain-name-servers 10.136.127.253; cat /etc/apt/sources.list # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://fr.archive.ubuntu.com/ubuntu/ precise main restricted deb-src http://fr.archive.ubuntu.com/ubuntu/ precise main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://fr.archive.ubuntu.com/ubuntu/ precise universe deb-src http://fr.archive.ubuntu.com/ubuntu/ precise universe deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://fr.archive.ubuntu.com/ubuntu/ precise multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ precise multiverse deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu precise-security main restricted deb-src http://security.ubuntu.com/ubuntu precise-security main restricted deb http://security.ubuntu.com/ubuntu precise-security universe deb-src http://security.ubuntu.com/ubuntu precise-security universe deb http://security.ubuntu.com/ubuntu precise-security multiverse deb-src http://security.ubuntu.com/ubuntu precise-security multiverse ## Uncomment the following two lines to add software from Canonical's ## 'partner' repository. ## This software is not part of Ubuntu, but is offered by Canonical and the ## respective vendors as a service to Ubuntu users. # deb http://archive.canonical.com/ubuntu precise partner # deb-src http://archive.canonical.com/ubuntu precise partner ## Uncomment the following two lines to add software from Ubuntu's ## 'extras' repository. ## This software is not part of Ubuntu, but is offered by third-party ## developers who want to ship their latest software. # deb http://extras.ubuntu.com/ubuntu precise main # deb-src http://extras.ubuntu.com/ubuntu precise main ls /etc/apt/sources.list.d => rien cat /etc/apt/sources.list.d/* cat: /etc/apt/sources.list.d/*: Aucun fichier ou dossier de ce type host google.com google.com has address 173.194.34.0 google.com has address 173.194.34.1 google.com has address 173.194.34.2 google.com has address 173.194.34.3 google.com has address 173.194.34.4 google.com has address 173.194.34.5 google.com has address 173.194.34.6 google.com has address 173.194.34.7 google.com has address 173.194.34.8 google.com has address 173.194.34.9 google.com has address 173.194.34.14 Host google.com.home not found: 4(NOTIMP) google.com mail is handled by 40 alt3.aspmx.l.google.com. google.com mail is handled by 50 alt4.aspmx.l.google.com. google.com mail is handled by 10 aspmx.l.google.com. google.com mail is handled by 20 alt1.aspmx.l.google.com. google.com mail is handled by 30 alt2.aspmx.l.google.com. apt-get update E: Impossible d'ouvrir le fichier verrou /var/lib/apt/lists/lock - open (13: Permission non accordée) E: Impossible de verrouiller le répertoire /var/lib/apt/lists/ E: Impossible d'ouvrir le fichier verrou /var/lib/dpkg/lock - open (13: Permission non accordée) E: Impossible de verrouiller le répertoire d'administration (/var/lib/dpkg/). Avez-vous les privilèges du superutilisateur ? Quelle est la différence pour le mode super utilisateur ? Hors ligne tiramiseb Re : Mode superutilisateur Ton système est bien Ubuntu 12.04 et non Ubuntu 12.10 comme tu sembles le penser. Pour le mode super utilisateur, la différence est de l'ordre de la bonne pratique. Concrètement pour toi sur le moment ça ne change pas grand chose. Mais quand tu passes "en super utilisateur" tu as tous les droits, et si là tu fais une connerie (te tromper de terminal, exécuter une commande "destructive" en root alors que tu voulais l'exécuter ailleurs en utilisateur normal, par exemple) tu ne pourras t'en prendre qu'à toi-même... Alors il vaut mieux limiter les risques et n'utiliser sudo que lorsque c'est nécessaire. Désolé, pour la dernière commande ça aurait dû être : sudo apt-get update Peux-tu l'exécuter ? Hors ligne
Hello arm navigation gurus, I am running the latest and greatest Electric arm_navigation Debian packages on an Ubuntu 10.04 machine. Using the planning wizard is a breeze and I have defined one kinematic group for my robot's 6-dof right arm (see here for URDF). Next I tried things out in the planning visualizer and the IK engine has no trouble finding solutions for random movements of the right hand (no gripper). Turning to the real robot, I am using the dynamixel_motor stack to drive the arm and I have successfully tested the basic topics and services that control the servos. The joint states are published on the /joint_states topic at 20 Hz and moving the arm passively is reflected smoothly in RViz. I then wrote a simple move_arm test script in Python that mimics the C++ tutorial found here. I have included the script below. The target pose in the script was taken from the FK when the arm was passively moved in front of the robot and slight bent. I then moved the arm around into various joint positions and ran my test script manually to see if an IK solution could be found. In some cases, a solution is found and the arm moves over a smooth trajectory to place the hand correctly. However, there seems to be only a small bubble around the desired pose where IK solutions can be found. This is in contrast to the planning visualizer where solutions were not a problem. I'm guessing there is something missing from my test script related to initializing the environment scene but I'm not sure how to do that with Python. Any thoughts? --patrick Here now is my test script: #! /usr/bin/python import roslib roslib.load_manifest('pi_dynamixel_controller') import rospy import actionlib from actionlib_msgs.msg import * from pr2_controllers_msgs.msg import * from trajectory_msgs.msg import * from dynamixel_controllers.srv import TorqueEnable from arm_navigation_msgs.msg import * from control_msgs.msg import FollowJointTrajectoryAction def poseConstraintToPositionOrientationConstraints(pose_constraint): position_constraint = PositionConstraint() orientation_constraint = OrientationConstraint() position_constraint.header = pose_constraint.header position_constraint.link_name = pose_constraint.link_name position_constraint.position = pose_constraint.pose.position position_constraint.constraint_region_shape.type = 0 position_constraint.constraint_region_shape.dimensions.append(2*pose_constraint.absolute_position_tolerance.x) position_constraint.constraint_region_shape.dimensions.append(2*pose_constraint.absolute_position_tolerance.y) position_constraint.constraint_region_shape.dimensions.append(2*pose_constraint.absolute_position_tolerance.z) position_constraint.constraint_region_orientation.x = 0.0 position_constraint.constraint_region_orientation.y = 0.0 position_constraint.constraint_region_orientation.z = 0.0 position_constraint.constraint_region_orientation.w = 1.0 position_constraint.weight = 1.0 orientation_constraint.header = pose_constraint.header orientation_constraint.link_name = pose_constraint.link_name orientation_constraint.orientation = pose_constraint.pose.orientation orientation_constraint.type = pose_constraint.orientation_constraint_type orientation_constraint.absolute_roll_tolerance = pose_constraint.absolute_roll_tolerance orientation_constraint.absolute_pitch_tolerance = pose_constraint.absolute_pitch_tolerance orientation_constraint.absolute_yaw_tolerance = pose_constraint.absolute_yaw_tolerance orientation_constraint.weight = 1.0 return (position_constraint, orientation_constraint) def addGoalConstraintToMoveArmGoal(pose_constraint, move_arm_goal): position_constraint, orientation_constraint = poseConstraintToPositionOrientationConstraints(pose_constraint); move_arm_goal.motion_plan_request.goal_constraints.position_constraints.append(position_constraint) move_arm_goal.motion_plan_request.goal_constraints.orientation_constraints.append(orientation_constraint) rospy.init_node('place_hand', anonymous=True) side = rospy.get_param("~side", "right") move_arm = actionlib.SimpleActionClient("move_" + side + "_arm", MoveArmAction) dynamixel_namespace = '/dynamixel_controller' dynamixels = rospy.get_param(dynamixel_namespace + '/dynamixels', dict()) servo_torque_enable = list() for name in sorted(dynamixels): torque_enable_service = dynamixel_namespace + '/' + name + '_controller/torque_enable' rospy.wait_for_service(torque_enable_service) servo_torque_enable.append(rospy.ServiceProxy(torque_enable_service, TorqueEnable)) move_arm ...
To get your external ip, you could make a dns query to an opendns server with the special hostname "myip.opendns.com": from subprocess import check_output ip = check_output(["dig", "+short", "@resolver1.opendns.com", "myip.opendns.com"]).decode().strip() On Windows, you could try nslookup. There is no dns module in Python stdlib that would allow to specify custom dns server. You could use third party libraries e.g., Twisted to make the dns query: from twisted.internet import task # $ pip install twisted from twisted.names.client import Resolver from twisted.python.util import println def main(reactor): opendns_resolvers = [("208.67.222.222", 53), ("208.67.220.220", 53)] resolver = Resolver(servers=opendns_resolvers, reactor=reactor) # use magical hostname to get our public ip return resolver.getHostByName('myip.opendns.com').addCallback(println) task.react(main) Here's the same using dnspython library: import dns.resolver # $ pip install dnspython resolver = dns.resolver.Resolver(configure=False) resolver.nameservers = ["208.67.222.222", "208.67.220.220"] print(resolver.query('myip.opendns.com')[0])
Profiling shows this is the slowest segment of my code for a little word game I wrote: def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] "distance" is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from "word" by exactly 1 letter. I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated. Edit: Forgot to mention that wordlist is pre-filtered to only have words containing the same number of letters as "word" so it's guaranteed that "word1" and "word2" have the same number of chars. Results: Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation) I tested with 2 sets of inputs which I'll call A and B Optimization1: From for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference to for x,y in zip (word1, word2): if x != y: difference += 1 return difference Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B Optimization2: Added a separate method for differs by one in addition to the distance method (which I still needed elsewhere for the A* heuristics) def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B Optimization3: Big winner here was to use izip instead of zip Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone! Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82 Building on that and incorporating izip instead of range, I ended up with this: def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88 Even more results! Trying Sumudu's suggestion that I generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist, instead of the is_neighbor function I ended up with this: def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact ( w for w in oneoff if w in wordlist ) I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with: return set(oneoff) & set(wordlist) Bam! 3.74 -> 0.23 and 34.40 -> 2.25 This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation. The Great Debate: Ok, me and Unknown are having a big debate which you can read in the comments of his answer. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow this and this example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the 12dict word list using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries. from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "->"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) & set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) > 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score < g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this: def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) As for getting it to work as a C module I didn't get that far, but this is what I came up with: #include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &word1, &word2, &length)) return NULL; int i; int different = 0; for (i =0; i < length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } I profiled this using: python -m cProfile "Wordgame.py" And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.
Here's a list of non-LISP languages that allow for macros (including those mentioned in other answers) -- the links are to an explanations of the respective macro systems: Languages that have features that are kind of like macros, or which accomplish more or less the same thing in different ways (namely Smalltalk and Io)): F# Smalltalk Io (Also homoiconic) D We should note that being natural-language-like and allowing for clear, easily intelligible expression do not always go hand in hand (especially since the latter quality is heavily dependent upon how one trains their ways of thinking and reading). In your python example, 0 < a < 5 does not accord with natural English. In English, we would have to say 0 is less than a, which is less than five or maybe a is greater than 0 and less than five: i.e., we either need a relative clause that uses 'which' to indicate that a is still the subject of our second qualification, or, if we want to use a single main clause, we need to complicate the expression by using the two different predicates 'greater than' and 'less than'. 0 < a < 5 is especially readable because it gives a clear, uncluttered, concise expression of the relation-concept, not because it is accords with natural language. I'd like to present the Macro system in Prolog, just because I think the language is great for forming clear and illuminating articulations of problems, and I like it. I'll first show how we might write your example in idiomatic Prolog, then I'll show how we can write some rules to get Pythonish syntax for the same expression using the macro system. Here's a flushed out python line elaborating on your example: if 0 < a < 5 and b in list: print ("that is true!") else: print ("that is not true!") In Prolog, we might write the conditional thus[1]: ( 0 < A, A < 5, member(B, List) % If 0 < A and A < 5 and B is member of List -> write('that is true!') % then write ... ; write('that is not true!') % else write ... ) Prefix notation is common for Prolog predicates[2], but the way it gets used is mostly like the prefix notation in predicate logic. If you've learned the latter, Prolog is very clear, but maybe not if not. My understanding is that macro expansions are easy to implement in LISPs because they are homoiconic languages: i.e., in LISP, code is data (a language can, obviously, implement macros without being homoiconic, it's just not as straightforward). Prolog is also homoiconic. Prolog accomplishes macro expansions by preprosseing code and pattern matching all the terms of a program with the predicateterm_expansion/2, and it's derivative, goal_expansion/2. The following bit of code uses operator declarations, op/3 and goal_expansion/2 to get syntax like your Python example. :- op(200, yfx, user:(<.)). :- op(200, xfx, user:(in)). :- op(1000, xfx, user:(and)). goal_expansion(A and B, (A, B)). % Read: if term matches A and B, replace with (A,B) goal_expansion(L <. M <. H, (L < M, M < H)). % `.` added to avoid conflict with the builtin `<` goal_expansion(E in List, member(E, List)). example(A, B, List) :- 0 <. A <. 5 and B in List -> write('This is true'). In action: ?- example(4, b, [a,b,c,d,e]). This is true Footnotes 1: I don't know whether this pattern would ever be useful. I'd probably just write a predicate to take care of the condition: foo(A, B, List) :- % foo(A, B, List) is true if... between(0, 5, A), member(A, List). to be used thus: bar(Var) :- % Var is bar if... <some conditions>, % conditions are true and foo(A, B, List), % foo(A, B, List) is true and ... . % whatever else is true. 2: In Prolog, most of the work is done with predictes Prolog predicates are the (very) rough equivalent of functions in other languages (with the critical proviso that *they are not functions and do not evaluate to their return value). The definition of a function in Python, with the formdef (): corresponds to the definition of a predicate in Prolog, with the form() :- . Predicates are referred to withpredicate_name/arity`.
I have a table with alternate row background-color: tr:nth-child(even) {background: #FFF} tr:nth-child(odd) {background: #f4f4f4} The table is comprised of two types of cells, ".main" and ".sub". I would like the background-color to alternate every other ".main", while all ".sub" rows get the color of the previous ".main". It would be great if the solution were all CSS, but open to jquery if it's really the best way to go. Any ideas? <table> <tr id='1' class='main'><td></td></tr> <tr id='2' class='main'><td></td></tr> <tr id='3' class='main'><td></td></tr> <tr id='4' class='main'><td></td></tr> <tr id='5' class='main'><td></td></tr> <tr id='6' class='sub'><td></td></tr> <tr id='7' class='main'><td></td></tr> <tr id='8' class='main'><td></td></tr> <tr id='9' class='sub'><td></td></tr> <tr id='10' class='sub'><td></td></tr> <tr id='11' class='main'><td></td></tr> </table> rows 1,3,5,8 should be #f4f4f4 rows 2,4,7,11 should be #fffff and each .sub row should be the same color as the preceding .main row. (these tables are dynamically generated, so their placement will vary) EDIT: here is the jsfiddle of my failed first attempt with jquery http://jsfiddle.net/xjDZm/
If the set of characters were larger, using sets as below might be faster. As it is, this is a bit slower than a.py. dec = set('1234567890.') a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw' for i in xrange(1000000): ''.join(ch for ch in a if ch in dec) At least on my system, you can save a tiny bit of time (and memory if your string were long enough to matter) by using a generator expression instead of a list comprehension in a.py: a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw' for i in xrange(1000000): ''.join(c for c in a if c in '1234567890.') Oh, and here's the fastest way I've found by far on this test string (much faster than regex) if you are doing this many, many times and are willing to put up with the overhead of building a couple of character tables. chrs = ''.join(chr(i) for i in xrange(256)) deletable = ''.join(ch for ch in chrs if ch not in '1234567890.') a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw' for i in xrange(1000000): a.translate(chrs, deletable) On my system, that runs in ~1.0 seconds where the regex b.py runs in ~4.3 seconds.
The Software Center has a section of For Purchase programs —see screenshot below—, which is annonying me every time I want to install something. Is there any way to remove or hide these programs from the Software Center? Links to answers: The Software Center has a section of Is there any way to For 12.04 1. Ignore the purchasable apps Open a gksu gedit /usr/share/software-center/softwarecenter/db/update.py And press Enter. You'll be prompted for your password. doc = make_doc_from_parser(parser, cache) if not doc: LOG.debug("make_doc_from_parser() returned '%s', ignoring" % doc) return term_generator.set_document(doc) name = doc.get_data() Immediately after those lines, paste the following ( if doc.get_value(XapianValues.PRICE) not in (""): return Save the file ( 2. Remove the "For purchase" channel (optional) To also remove that "For purchase" item in the menu, open a terminal and type: gksu gedit /usr/share/software-center/softwarecenter/backend/channel_impl/aptchannels.py Locate these lines: if get_distro().PURCHASE_APP_URL: channels.append(for_purchase_channel) And disable them by putting a #if get_distro().PURCHASE_APP_URL: # channels.append(for_purchase_channel) Save and enjoy a software center without ads! Side notes: The. files. are. packaged. What does this mean, you ask? This means that, Undo the modifications If you want to restore the original state of the files, sudo apt-get install --reinstall software-center && exit Again, you will be prompted for your password, this time on the terminal. For 11.10 and earlier You can edit: and comment out (or delete) the following lines: for_purchase_channel = None #create a "magic" channel to display items available for purchase ` for_purchase_query = xapian.Query("AH" + AVAILABLE_FOR_PURCHASE_MAGIC_CHANNEL_NAME) for_purchase_channel = SoftwareChannel(self.icons, "For Purchase", None, None, channel_icon=None, # FIXME: need an icon channel_query=for_purchase_query, installed_only=installed_only) if partner_channel is not None: # channels.append(partner_channel) #channels.append(for_purchase_channel) Of course, you should have in mind that consequent updates to Check out this link for more details ;-) Note: for 12.04 the filename is I found a way to hide commercial results for 12.04: In /usr/share/software-center/softwarecenter/ui/gtk3/models/appstore2.py: After the lines: def set_from_matches(self, matches): """ set the content of the liststore based on a list of xapian.MSetItems """ LOG.debug("set_from_matches len(matches)='%s'" % len(matches)) Add the following line: matches[:] = [m for m in matches if (m.document.get_value(XapianValues.PRICE) in _FREE_AS_IN_BEER)] It should only change what is displayed, but I did not test it much yet, so use at your own risks. And enjoy an ad-free software center. For completeness, here is the solution that worked for me in 13.10: sudo aptitude install gksu gksu gedit /usr/share/software-center/softwarecenter/db/update.py Find this: def make_doc(self, cache): """Build a Xapian document from the desktop info.""" doc = xapian.Document() And add this (make sure you have the right indentation of TABS (python requires this): if self.has_option_desktop("X-AppInstall-Price"): if self.get_desktop("X-AppInstall-Price") > 0: return BTW this was my first python evar :-) For 12.10 and later Close the Software Center if it's open. gksu gedit /usr/share/software-center/softwarecenter/db/update.py And press Enter. You'll be prompted for your password. doc = self.make_doc(cache) if not doc: LOG.debug("%r.index_app_info: returned invalid doc %r, ignoring.", self.__class__.__name__, doc) return name = doc.get_data() Immediately after those lines, paste the following ( if doc.get_value(XapianValues.PRICE) not in (""): return Save the file ( gksu gedit /usr/share/software-center/softwarecenter/backend/channel_impl/aptchannels.py Press ENTER. An editor will appear again. Locate these lines: if get_distro().PURCHASE_APP_URL: channels.append(for_purchase_channel) And disable them by putting a #if get_distro().PURCHASE_APP_URL: # channels.append(for_purchase_channel) Save the file, close the editor but not the terminal. gksu echo; sudo update-software-center && exit Wait a bit, the terminal will automatically close when finished... Side notes: The. files. are. packaged. What does this mean, you ask? This means that, Undo the modifications If you want to restore the original state of the files, gksu echo; sudo apt-get install --reinstall software-center && exit Again, you will be prompted for your password. I tried this it it worked for me: only FREE gksu gedit /usr/share/software-center/softwarecenter/db/update.py Find this: def make_doc_from_parser(parser, cache): # XXX 2012-01-19 michaeln I'm just pulling this code out from # index_app_info_from_parser, but it'd be great to further # refactor it - it looks quite scary :-) doc = xapian.Document() # app name is the data Then add the following code: if parser.has_option_desktop("X-AppInstall-Price"): if parser.get_desktop("X-AppInstall-Price") > 0: return You can do this more simply by selecting View -> Canonical Maintained Software instead of All Software. This has the benefit of not being overwritten by software updates. This may hide some additional items but at least it gets rid of the annoying magazines and for sale software in my experience.
I have problem using Orthogonal Digitizing button from CAD Tools plugin menu. It moves the first point of the polygon by holding ctrl key pressed and pressing right mouse button till the last angle is squared. Is it possible to change setting to move the last vertex till the last angle is squared? Sergey, on QGIS 1.7.4-4 on Mac 10.7.3 with CAD Tools ver. 0.5.9, I am not seeing the first vertex being moved. In fact, I notice that the last vertex (one currently under the cursor?) is being moved, as per your request. On examining the relevant Python script... @ line #91, I notice the point-moving method as using the last vertex: def createFeature(self): layer = self.canvas.currentLayer() provider = layer.dataProvider() f = QgsFeature() if self.isPolygon == True: if self.mCtrl == True: # we will move the first point to close the polygon square... (square??) # NO: move the last point! # the last segment pn = self.rb.getPoint(0, self.rb.numberOfVertices()-2) pm = self.rb.getPoint(0, self.rb.numberOfVertices()-1) p1 = self.rb.getPoint(0, 0) p2 = self.rb.getPoint(0, 1) # but we need a line segment that is orthogonal to the last segment # der letzte Punkt ist der Aufpunkt # der Richtungsvektor ist der Vektor, der rechwinklig zum Differenzvektor pn-pm liegt (-> x/y vertauschen) d = ( (pn.x()-pm.x())**2 + (pn.y()-pm.y())**2 )**0.5 xp = p1.x() + (p1.y()-p2.y()) yp = p1.y() - (p1.x()-p2.x()) pp = QgsPoint(xp, yp) p0 = LineIntersection.intersectionPoint(pn, pm, p1, pp) self.rb.movePoint(self.rb.numberOfVertices()-1, p0, 0) Note "# NO: move the last point!" comment, and that last line contains: numberOfVertices()-1 <-- last point in QgsRubberBand being moved Maybe this is a newer version of CAD Tools than you are running? My version exhibits the behavior you are requesting. There does not seem to be an option -- short of editing the plugin's code -- to toggle which point gets moved. You may want to request this feature on the CAD Tools issue tracker at QGIS.org or the one at code.google.com. Not sure which is the appropriate, since there is not one listed at the plugin's QGIS repository page.
pontiac76 [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour, J'ai posté hier un message à propos de mon impossibilité d'aller sur internet sauf sur sur google avec mon installation toute neuve d'Ubuntu 12.04 LTS sur un second disque dur de mon pc fixe. Devant l'absence de réponse, j'ai relu les règles du forum et tenter d'en respecter la méthode, mais je n'ai pas encore trouvé de solutions, et je remercie la personne bienveillante qui pourra m'aider. J'ai donc réalisé cette installation avec une image iso vérifiée et en dernier recours, j'ai recommencé avec la version officielle achetée en ligne. Ma connexion ne fonctionne pas non plus avec le live-cd. J'ai parcouru le forum et la documentation, et après quelques manipulations, j'ai retrouvé une connexion....que j'ai à nouveau perdue au redémarrage, et je ne me souviens plus ce que j'ai dû faire par hasard qui a fonctionné. Mon pc fonctionne sur Intel pentium 4 et 1Go de ram, il fonctionne correctement avec windows xp pour aller sur le net. Quand j'affiche les informations de connexion dans le Network-manager, qui m'indique que ma liaison filaire est active, il y a toutes les adresses nécessaires de notées. En parcourant le forum, une personne a proposé quelques lignes de commandes pour faire un auto-diagnostic et je vous le soumets ci-dessous : jean-marc@jeanmarc-desktop:~$ sudo lshw -C network [sudo] password for jean-marc: *-network description: Ethernet interface produit: 190 Ethernet Adapter fabriquant: Silicon Integrated Systems [SiS] identifiant matériel: 4 information bus: pci@0000:00:04.0 nom logique: eth0 version: 00 numéro de série: 00:13:d3:c6:0f:e8 taille: 100Mbit/s capacité: 100Mbit/s bits: 32 bits horloge: 33MHz fonctionnalités: pm bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation configuration: autonegotiation=on broadcast=yes driver=sis190 driverversion=1.4 duplex=full ip=192.168.1.31 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s ressources: irq:19 mémoire:febfbc00-febfbc7f portE/S:cc00(taille=128) jean-marc@jeanmarc-desktop:~$ ifconfig eth0 Link encap:Ethernet HWaddr 00:13:d3:c6:0f:e8 inet adr:192.168.1.31 Bcast:192.168.1.255 Masque:255.255.255.0 adr inet6: fe80::213:d3ff:fec6:fe8/64 Scope:Lien UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 Packets reçus:330 erreurs:223 :4 overruns:0 frame:223 TX packets:426 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 lg file transmission:1000 Octets reçus:55441 (55.4 KB) Octets transmis:56392 (56.3 KB) Interruption:19 Adresse de base:0xdead 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:130 erreurs:0 :0 overruns:0 frame:0 TX packets:130 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 lg file transmission:0 Octets reçus:9798 (9.7 KB) Octets transmis:9798 (9.7 KB) jean-marc@jeanmarc-desktop:~$ cat /etc/network/interfaces auto lo iface lo inet loopback jean-marc@jeanmarc-desktop:~$ nm-tool NetworkManager Tool State: connected (global) - Device: eth0 [SFR_BOX] ------------------------------------------------------ Type: Wired Driver: sis190 State: connected Default: yes HW Address: 00:13:D3:C6:0F:E8 Capabilities: Carrier Detect: yes Speed: 100 Mb/s Wired Properties Carrier: on IPv4 Settings: Address: 192.168.1.31 Prefix: 24 (255.255.255.0) Gateway: 192.168.1.1 DNS: 192.168.1.1 J'ai bien remarqué que des erreurs existaient dans la transmission des paquets avec ifconfig, mais je ne sais les interprétées ni les corriger. Merci d'avance aux gentils magiciens du terminal. Dernière modification par pontiac76 (Le 14/08/2012, à 17:05) Hors ligne Korak Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour, Ouvre un terminal et donne le retour de la commande: ping www.google.be -c 5 Puis de la commande: ping www.allocine.fr -c 5 OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Merci beaucoup de te pencher sur mon problème, voilà ce que dit la console : jean-marc@jeanmarc-desktop:~$ ping google.be -c 5 PING google.be (173.194.34.56) 56(84) bytes of data. 64 bytes from par03s03-in-f24.1e100.net (173.194.34.56): icmp_req=1 ttl=56 time=1.76 ms 64 bytes from par03s03-in-f24.1e100.net (173.194.34.56): icmp_req=2 ttl=56 time=2.38 ms 64 bytes from par03s03-in-f24.1e100.net (173.194.34.56): icmp_req=3 ttl=56 time=2.32 ms 64 bytes from par03s03-in-f24.1e100.net (173.194.34.56): icmp_req=4 ttl=56 time=2.19 ms 64 bytes from par03s03-in-f24.1e100.net (173.194.34.56): icmp_req=5 ttl=56 time=2.34 ms --- google.be ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4006ms rtt min/avg/max/mdev = 1.767/2.201/2.384/0.234 ms jean-marc@jeanmarc-desktop:~$ ping www.allocine.fr -c 5 PING a1758.w7.akamai.net (77.67.11.106) 56(84) bytes of data. 64 bytes from hosted-by.illuminati.es (77.67.11.106): icmp_req=1 ttl=56 time=1.91 ms 64 bytes from hosted-by.illuminati.es (77.67.11.106): icmp_req=2 ttl=56 time=1.87 ms 64 bytes from hosted-by.illuminati.es (77.67.11.106): icmp_req=3 ttl=56 time=2.27 ms 64 bytes from hosted-by.illuminati.es (77.67.11.106): icmp_req=4 ttl=56 time=2.05 ms 64 bytes from hosted-by.illuminati.es (77.67.11.106): icmp_req=5 ttl=56 time=2.37 ms --- a1758.w7.akamai.net ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4006ms rtt min/avg/max/mdev = 1.870/2.098/2.376/0.198 ms jean-marc@jeanmarc-desktop:~$ En te remerciant Hors ligne Korak Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Ok, tu arrives a contacter les deux sites. Ouvre Firefox (ou autre navigateur) et entre l'adresse: Dis-nous si le site s'affiche correctement. Même chose avec l'adresse: OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Je me connecte avec Firefox, vu que sans connexion je n'ai pu installer d'autres navigateurs. La page du site www.google.be s'affiche, et même tous les liens affichés dans la barre du menu en haut. Si j'effectue une recherche dans la barre google, j'ai bien des réponses, mais ne peux me rendre ensuite sur aucun lien. La page du site www.allocine.fr ne s'affiche pas, et le symbole de l'onglet "Connexion" tourne en permanence...voilà voilà... Dernière modification par pontiac76 (Le 10/08/2012, à 14:00) Hors ligne Korak Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Tu n'aurais pas modifié les paramètres de ta box par hasard? Comme le pare-feu ou le contrôle parental? Utilises-tu un proxy? Dernière modification par Korak (Le 10/08/2012, à 14:02) OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne cracoucasse Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour Pontiac 76, j'ai malheureusement exactement le même problème que toi depuis plusieurs mois et je ne trouve aucune solution. On m'a également demandé si je n'avais pas touché au pare-feu ou au contrôle parental (ce qui n'est pas le cas) puis....plus de réponse. Je vais tenter cet après-midi d'installer un nouveau navigateur (opera) afin de voir si cela change quelque chose. Je suis plutôt sceptique puisqu'à ce problème s'ajoutent l'impossibilité d'effectuer les mises à jours et de faire fonctionner la logithèque. Je te tiens au courant... Hors ligne Korak Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 On m'a également demandé si je n'avais pas touché au pare-feu ou au contrôle parental (ce qui n'est pas le cas) puis....plus de réponse. C'est moi qui t'ai posé la question. Et je n'ai toujours pas de solution, d'où le fait que je n'ai plus répondu. OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Rebonjour, J'ai juste installé une ip fixe pour mon pc, comme je l'avais vu en conseil dans le forum. Ma box est une neufbox de chez SFR. Pourquoi le même pc avec la même carte réseau et l'ip fixe configurée ainsi fonctionne avec windows xp et pas avec ubuntu, alors que celui-ci reconnait la connexion active ? Je ne sais pas ce qu'est un proxy. Je vais rebooter complètement ma box en attendant et je vous tiens au courant. J'ai une clef usb installée avec eboost pour augmenter la mémoire de windows. Dans Ubuntu, je l'éjecte, est-ce que ça peut jouer ? Merci pour toute le peine donnée Jean-Marc Hors ligne Korak Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 J'ai juste installé une ip fixe pour mon pc, comme je l'avais vu en conseil dans le forum. L'IP fixe m'a déjà posé problème sous Ubuntu. Depuis, je n'utilise plus que le DHCP. Fais la même chose et tiens-nous au courant. OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT) PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM Je suis Parrain-Linux Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bon merci, Je vais remettre le DHCP sur la box après l'avoir remise à zéro. Comme je pars en week-end ce soir, je ne vais pas redonner les résultats avant la semaine prochaine. Bon week-end à toi Korak Hors ligne cracoucasse Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 pas de changement après avoir installé Opéra. En ce qui concerne ma connexion, qu'elle soit configurée en dhcp (automatique) ou en ip fixe, rien ne change, même après un hard reboot de la box ou l'utilisation d'autres dns... Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Effectivement cracoucasse, je n'y crois pas trop non plus...ça va devenir un vrai dilemme, mais il faut croire dans nos belles étoiles, beaucoup plus expérimentées que nous sous Linux, même si on gère pas mal de soucis sous windows. Moi, j'y crois, cela a fonctionné sauf que je ne me rappelle plus la manip magique ! Bon week-end à mes suiveurs(veuses)... Jean-Marc Hors ligne Francine34 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 J'ai le même problème. J'ai une freebox et sur mon compte free, j'ai désactivé l'option proxy WoL; Pour ma connexion internet j'ai coché "pas de proxy", mais ça n'y a rien fait. J'ai accès à mes mails et je peux explorer google maps autant que je veux, mais rien d'autre. Pas d'autre site, pas de mises à jour, pas de logithèque.. Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour, Après avoir réfléchi tout le week-end aux solutions possibles, j'ai choisi de remettre ma sfrbox en configuration usine, en débranchant tous les câbles ethernet, et faire un reset général. Redémarrage et contrôle connexion internet....tout fonctionne sous windows et sur ubuntu rien sauf google. J'ai déconnecté aussi l'option d'utiliser un serveur proxy dans firefox, et j'ai décoché aussi tous les filtrages proposé par ma box. Je n'ai aucun contrôle parental. Je n'avance pas et je ne comprends pas. Je me délectais déjà d'utiliser un nouveau système d'exploitation mais ça commence à me prendre la tête... Bon voilà, pour l'instant je n'ai que des états d'âme et suis à cours d'imagination pour résoudre mon problème, apparemment partagé. Je vais encore aller fouiller un peu partout sur le web et le forum ubuntu. Si je trouve quelque chose, je ne manquerais pas d'apporter ma contribution à tous mes "pairs". Salut à tous Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Me voilà enfin requinqué j'ai trouvé mon problème, enfin presque... J'ai trouvé cela sur le forum : quand internet est utilisé par XP, après un reboot sur ubuntu, plus d'accès à internet, alors que les connexions ont l'air actives. Je dois alors éteindre l'ordi, couper l'alimentation, attendre que les leds soient éteintes, et je redémarre sur ubuntu, et tout est dans l'ordre. Sans être vital, cet ennui mérite d'être solutionné, il n'est apparu que récemment, je n'ai pas remarqué quand exactement, pas de rapprochement avec une manoeuvre quelconque... Bref, je nage, ou plutôt je barbotte! J'ai fait la même manip : éteindre le pc, couper l'alimentaion, redémarrer sous ubuntu....et ça marche ! J'ai fait la mise à jour d'ubuntu. J'ai redémarré avec xp puis ensuite sous ubuntu, plus rien. Je refait la manip précédente, et tout refonctionne, miracle. Qu'est ce qui est retenu par le pc en mémoire qui empêche la reconnexion, et qu'il perd si on coupe complètement l'alimentation ??? Je n"ai pas trouvé l'origine de ce désagrément, mais le principal est de pouvoir faire les mises à jour ubuntu, surfer, enfin le rêve quoi ! Bon merci à tous qui, grâce à vos questions, vos recherches et vos réponses m'ont permis de remettre en route la machina Hors ligne ajourd83 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 bonjour sur le même pc acces à internet avec xp j ai plusieurs linux sur un second disque en 11.10 accès à internet dès que je monte en version 12.04 jamais d accès internet avec cette version message reseau déconnecté. je conserve bien sur l accès avec xp et mes linux en 11.10 si quelqu un à une idée merci d avance alain 63 ans en linux depuis 2000 Hors ligne Animaju Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour ceci m'avait aidé http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9649361 en particulier Bonjour, Installer le paquet linux-firmware-nonfree devrait suffire à résoudre le problème. pour cela tu dois te connecter en filaire en espérant que cela t'aide aussi cordialement Hors ligne cracoucasse Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Me voilà enfin requinqué j'ai trouvé mon problème, enfin presque... J'ai trouvé cela sur le forum : Sophrolo a écrit : quand internet est utilisé par XP, après un reboot sur ubuntu, plus d'accès à internet, alors que les connexions ont l'air actives. Je dois alors éteindre l'ordi, couper l'alimentation, attendre que les leds soient éteintes, et je redémarre sur ubuntu, et tout est dans l'ordre. Sans être vital, cet ennui mérite d'être solutionné, il n'est apparu que récemment, je n'ai pas remarqué quand exactement, pas de rapprochement avec une manoeuvre quelconque... Bref, je nage, ou plutôt je barbotte! J'ai fait la même manip : éteindre le pc, couper l'alimentaion, redémarrer sous ubuntu....et ça marche ! J'ai fait la mise à jour d'ubuntu. J'ai redémarré avec xp puis ensuite sous ubuntu, plus rien. Je refait la manip précédente, et tout refonctionne, miracle. Qu'est ce qui est retenu par le pc en mémoire qui empêche la reconnexion, et qu'il perd si on coupe complètement l'alimentation ??? Je n"ai pas trouvé l'origine de ce désagrément, mais le principal est de pouvoir faire les mises à jour ubuntu, surfer, enfin le rêve quoi ! Bon merci à tous qui, grâce à vos questions, vos recherches et vos réponses m'ont permis de remettre en route la machina Incroyable mais vrai, ça marche !!! Mille merci pontiac76 pour ce tuyau inexplicable...mais si efficace. Soulagé de ne plus avoir à perdre mon temps sous W7. Encore merci et bonne soirée Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Pas de quoi, mais je reste curieux de savoir d'où vient cette bizarrerie ! La carte réseau a t-elle une mémoire ? Peut-être qu'un ubuntien averti aura une explication et que cette donnée pourra être ajoutée dans la documentation.... En attendant, bon surf avec GNU/Linux Hors ligne LRDP Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Pour plus de sécurité: Alt F2 : fenêtre éditeur de configuration, lancer gconf-editor, cliquer sur apps, puis sur gnome-power-manager, puis sur general : regarder sur la fenêtre de droite si la ligne "network sleep" est cochée, sinon cochez la, cela incite Gnome a garder network actif après une extinction ou un reboot Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour, J'ai installé gconf-editor, mais je ne trouve pas "gnome-power-manager" dans le chemin proposé. Sinon, je pense que la solution semble proche. Merci Hors ligne kamware Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonsoir tout le monde, J'ai exactement le même problème! Connexion réseau ok Internet ko sauf google Ping ko Update et upgrade ko Quand je redémarre Ubuntu 12.04 en mode généric plus de problème du moins une fois sur 2 ou 3, des que je redémarre en mode PAE de nouveau le même problème. Je n'y comprend plus rien Avez-vous une solution à me communiquer svp? PS: J'ai effectuer toutes les manipulations ci-dessus mais rien ne foctionne Dernière modification par kamware (Le 23/08/2012, à 19:02) :-) Hors ligne wilson125 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour Je ne pense pas qu'on puisse vraiment ajouter [resolu] a ce souci ^^ En effet, je viens d'installer la derniere version d'ubuntu sur le pc fixe de mon padre en lui vantant monts et merveilles de cet intuitif systeme d'exploitation.. sauf que j'ai le meme souci que celui sus nommé, sans jamais aller sur windows au prealable (qui d'ailleurs n'est plus disponible, puisqu'ayant remplacer ce dernier par Ubuntu) Quelqu'un aurait il ce probleme sans passer par le dual boot ? Mieux encore, quelqu'un aurait il une piste de solution ? Merci Hors ligne pontiac76 Re : [résolu]Google Ok mais pas internet avec Ubuntu 12.04 Bonjour, J'ai ajouté [résolu] parce que la manipulation "magique" a fonctionné pour moi : éteindre et couper le courant de l'unité centrale et redémarrer avec ubuntu. Maintenant, c'est vrai que cela doit être un casse-tête pour les initiés, chacun y allant de son intuition mais sans vraiment trouver le bug. Chacun se décarcasse et cela est une démarche solidaire que je salue et je pense qu'un jour, une solution va être trouvée.. Bonne recherche et continuation Hors ligne
I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks. orig = csv.reader(open("googlel.csv", "rb"), delimiter = ';') goodrows = [] for feed in gotfeeds: for link,comments in feed.items(): for row in orig: print link if link in row[1]: row.append(comments) goodrows.append(row)
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open? You have a few options: Start the script from already open cmd window or at the end of script add something like this raw_input("press enter to exit ;)") you can combine the answers before: (for Notepad++ User) press F5 to run current script and type in command: in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :) To keep your window open in case of exception (yet, while printing the exception using http://stackoverflow.com/a/3702726/2436175) if __name__ == '__main__': try: ## your code, typically one function call except: import sys print sys.exc_info()[0] import traceback print traceback.format_exc() print "Press Enter to continue ..." raw_input() To keep the window open in any case: if __name__ == '__main__': try: ## your code, typically one function call except: import sys print sys.exc_info()[0] import traceback print traceback.format_exc() finally: print "Press Enter to continue ..." raw_input() To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs. raw_input() print('You have reached the end and the "raw_input()" function is keeping the window open') raw_input() print("You have reached the end and the "input()" function is keeping the window open") input() Hopefully this helps others who might be starting out and still haven't figured out how the computer thinks yet. It can take a while. :o) I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd windows immediately after the code terminated. Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.
I've just installed Ubuntu 12.04 and was about to manually install Rawstudio with the packages from SourceForge repo, but I've been stuck with dependency issues and I am short on apt command lines to sort this out. Here's the report I'v got : installArchives() failed: dpkg: dependency problems prevent configuration of libgphoto2-2: libgphoto2-2 depends on libjpeg62; however: Package libjpeg62 is not installed. libgphoto2-l10n (2.4.13-1ubuntu1) breaks libgphoto2-2 (<= 2.4.10.1-4) and is installed. Version of libgphoto2-2 to be configured is 2.4.10.1-0ubuntu3~maverick. dpkg: error processing libgphoto2-2 (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already dpkg: dependency problems prevent configuration of libgphoto2-2-dev: libgphoto2-2-dev depends on libgphoto2-2 (= 2.4.10.1-0ubuntu3~maverick); however: Package libgphoto2-2 is not configured yet. dpkg: error processing libgphoto2-2-dev (--configure): dependency problems - leaving unconfigured No apport report written because MaxReports is reached already Errors were encountered while processing: libgphoto2-2 libgphoto2-2-dev Error in function: SystemError: E:Sub-process /usr/bin/dpkg returned an error code (1) dpkg: dependency problems prevent configuration of libgphoto2-2: libgphoto2-2 depends on libjpeg62; however: Package libjpeg62 is not installed. libgphoto2-l10n (2.4.13-1ubuntu1) breaks libgphoto2-2 (<= 2.4.10.1-4) and is installed. Version of libgphoto2-2 to be configured is 2.4.10.1-0ubuntu3~maverick. dpkg: error processing libgphoto2-2 (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of libgphoto2-2-dev: libgphoto2-2-dev depends on libgphoto2-2 (= 2.4.10.1-0ubuntu3~maverick); however: Package libgphoto2-2 is not configured yet. dpkg: error processing libgphoto2-2-dev (--configure): dependency problems - leaving unconfigured I've tried "apt-get -f install" but without success. What is the mahick command line that will unblock the situation ? Thanks Seb
I have changed my source to local server. I'm using Ubuntu 12.10. When I type apt-cache search in terminal, it shows nothing. When I install lightread it shows Unable to locate package lightread. When I install lightread manually by python. It shows python '/home/peng/Downloads/quickly_trunk/setup.py' Traceback (most recent call last): File "/home/peng/Downloads/quickly_trunk/setup.py", line 93, in <module> data_files=[('share/icons/hicolor/128x128/apps', ['data/media/lightread.png'])] File "/usr/lib/python2.7/dist-packages/DistUtilsExtra/auto.py", line 71, in setup src_mark(src, 'setup.py') File "/usr/lib/python2.7/dist-packages/DistUtilsExtra/auto.py", line 527, in src_mark src.remove(path) KeyError: 'setup.py' How to solve the problem?
String Files String is a global object that may be used to construct String instances. String objects may be created by calling the constructor new String(). The String object wrapsJavaScript's string primitive data type with the methods described below. The global functionString() can also be called without new in front to create a primitive string. String literals inJavaScript are primitive strings. Because JavaScript automatically converts between string primitives and String objects, you can callany of the methods of the String object on a string primitive. JavaScript automatically converts thestring primitive to a temporary String object, calls the method, then discards the temporary Stringobject. For example, you can use the String.length property on a string primitive created from astring literal: s_obj = new String(s_prim = s_also_prim = "foo"); s_obj.length; // 3 s_prim.length; // 3 s_also_prim.length; // 3 'foo'.length; // 3 "foo".length; // 3 (A string literal is denoted with single or double quotation marks.) String objects can be converted to primitive strings with the valueOf method. String primitives and String objects give different results when evaluated as JavaScript. Primitives are treated as source code; String objects are treated as a character sequence object. For example: s1 = "2 + 2"; // creates a string primitive s2 = new String("2 + 2"); // creates a String object eval(s1); // returns the number 4 eval(s2); // returns the string "2 + 2" eval(s2.valueOf()); // returns the number 4 Character access There are two ways to access an individual character in a string. The first is the charAt method: return 'cat'.charAt(1); // returns "a" The other way is to treat the string as an array, where each index corresponds to an individual character: return 'cat'[1]; // returns "a" The second way (treating the string as an array) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature. In both cases, attempting to set an individual character won't work. Trying to set a characterthrough charAt results in an error, while trying to set a character via indexing does not throw anerror, but the string itself is unchanged. Comparing strings C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators: var a = "a"; var b = "b"; if (a < b) // true print(a + " is less than " + b); else if (a > b) print(a + " is greater than " + b); else print(a + " and " + b + " are equal."); A similar result can be achieved using the localeCompare method inherited by String instances. Available since: 2.0.0 Properties Reflects the length of the string. This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bitcode unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it'spossible for the value returned by length to not match the actual number of characters in the string. For an empty string, length is 0. var x = "Netscape"; var empty = ""; console.log("Netspace is " + x.length + " code units long"); console.log("The empty string is has a length of " + empty.length); // should be 0 Available since: 2.0.0 Methods Returns the character at the specified index. Characters in a string are indexed from left to right. The index of the first character is 0, andthe index of the last character in a string called stringName is stringName.length - 1. If theindex you supply is out of range, JavaScript returns an empty string. The following example displays characters at different locations in the string "Brave new world": var anyString="Brave new world"; document.writeln("The character at index 0 is '" + anyString.charAt(0) + "'"); document.writeln("The character at index 1 is '" + anyString.charAt(1) + "'"); document.writeln("The character at index 2 is '" + anyString.charAt(2) + "'"); document.writeln("The character at index 3 is '" + anyString.charAt(3) + "'"); document.writeln("The character at index 4 is '" + anyString.charAt(4) + "'"); document.writeln("The character at index 999 is '" + anyString.charAt(999) + "'"); These lines display the following: The character at index 0 is 'B'The character at index 1 is 'r'The character at index 2 is 'a'The character at index 3 is 'v'The character at index 4 is 'e'The character at index 999 is '' The following provides a means of ensuring that going through a string loop always provides a whole character, even if the string contains characters that are not in the Basic Multi-lingual Plane. var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly for (var i=0, chr; i < str.length; i++) { if ((chr = getWholeChar(str, i)) === false) {continue;} // Adapt this line at the top of each loop, passing in the whole string and the current iteration and returning a variable to represent the individual character alert(chr); } function getWholeChar (str, i) { var code = str.charCodeAt(i); if (isNaN(code)) { return ''; // Position not found } if (code < 0xD800 || code > 0xDFFF) { return str.charAt(i); } if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters) if (str.length <= (i+1)) { throw 'High surrogate without following low surrogate'; } var next = str.charCodeAt(i+1); if (0xDC00 > next || next > 0xDFFF) { throw 'High surrogate without following low surrogate'; } return str.charAt(i)+str.charAt(i+1); } // Low surrogate (0xDC00 <= code && code <= 0xDFFF) if (i === 0) { throw 'Low surrogate without preceding high surrogate'; } var prev = str.charCodeAt(i-1); if (0xD800 > prev || prev > 0xDBFF) { // (could change last hex to 0xDB7F to treat high private surrogates as single characters) throw 'Low surrogate without preceding high surrogate'; } return false; // We can pass over low surrogates now as the second component in a pair which we have already processed } While the second example may be more frequently useful for those wishing to support non-BMPcharacters (since the above does not require the caller to know where any non-BMP character mightappear), in the event that one does wish, in choosing a character by index, to treat the surrogatepairs within a string as the single characters they represent, one can use the following: function fixedCharAt (str, idx) { var ret = ''; str += ''; var end = str.length; var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; while ((surrogatePairs.exec(str)) != null) { var li = surrogatePairs.lastIndex; if (li - 2 < idx) { idx++; } else { break; } } if (idx >= end || idx < 0) { return ''; } ret += str.charAt(idx); if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx+1))) { ret += str.charAt(idx+1); // Go one further, since one of the "characters" is part of a surrogate pair } return ret; } Available since: 2.0.0 Parameters index : Number An integer between 0 and 1 less than the length of the string. Returns String Individual character from string. Returns a number indicating the Unicode value of the character at the given index. Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct match of the ASCII character encoding. Note that charCodeAt will always return a value that is less than 65,536. This is because thehigher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters whichare used to comprise the real character. Because of this, in order to examine or reproduce the fullcharacter for individual characters of value 65,536 and above, for such characters, it is necessaryto retrieve not only charCodeAt(i), but also charCodeAt(i+1) (as if examining/reproducing astring with two letters). See example 2 and 3 below. charCodeAt returns NaN if the given index is not greater than 0 or is greater than the length ofthe string. Backward Compatibility with JavaScript 1.2 The charCodeAt method returns a number indicating the ISO-Latin-1 codeset value of the characterat the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a directmatch of the ASCII character set. Example 1: Using charCodeAt The following example returns 65, the Unicode value for A. "ABC".charCodeAt(0) // returns 65 Example 2: Fixing charCodeAt to handle non-Basic-Multilingual-Plane characters if their presenceearlier in the string is unknown This version might be used in for loops and the like when it is unknown whether non-BMP characters exist before the specified index position. function fixedCharCodeAt (str, idx) { // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536 // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // 65536 idx = idx || 0; var code = str.charCodeAt(idx); var hi, low; if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters) hi = code; low = str.charCodeAt(idx+1); if (isNaN(low)) { throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()'; } return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate // We return false to allow loops to skip this iteration since should have already handled high surrogate above in the previous iteration return false; } return code; } Example 3: Fixing charCodeAt to handle non-Basic-Multilingual-Plane characters if their presenceearlier in the string is known function knownCharCodeAt (str, idx) { str += ''; var code, end = str.length; var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; while ((surrogatePairs.exec(str)) != null) { var li = surrogatePairs.lastIndex; if (li - 2 < idx) { idx++; } else { break; } } if (idx >= end || idx < 0) { return NaN; } code = str.charCodeAt(idx); var hi, low; if (0xD800 <= code && code <= 0xDBFF) { hi = code; low = str.charCodeAt(idx+1); // Go one further, since one of the "characters" is part of a surrogate pair return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return code; } Available since: 2.0.0 Parameters index : Number An integer greater than 0 and less than the length of the string; if it is not a number, it defaults to 0. Returns Number Value between 0 and 65535. Combines combines the text from one or more strings and returns a new string. Changes to the text in one string do not affect the other string. The following example combines strings into a new string. var hello = "Hello, "; console.log(hello.concat("Kevin", " have a nice day.")); // Hello, Kevin have a nice day. Available since: 2.0.0 Parameters strings : String... The strings to concatenate. Returns String Result of both strings. Returns a string created by using the specified sequence of Unicode values. This method returns a string and not a String object. Because fromCharCode is a static method of String, you always use it as String.fromCharCode(),rather than as a method of a String object you created. Although most common Unicode values can be represented in a fixed width system/with one number (asexpected early on during JavaScript standardization) and fromCharCode() can be used to return asingle character for the most common values (i.e., UCS-2 values which are the subset of UTF-16 withthe most common characters), in order to deal with ALL legal Unicode values, fromCharCode() aloneis inadequate. Since the higher code point characters use two (lower value) "surrogate" numbers toform a single character, fromCharCode() can be used to return such a pair and thus adequatelyrepresent these higher valued characters. Be aware, therefore, that the following utility function to grab the accurate character even for higher value code points, may be returning a value which is rendered as a single character, but which has a string count of two (though usually the count will be one). // String.fromCharCode() alone cannot get the character at such a high code point // The following, on the other hand, can return a 4-byte character as well as the // usual 2-byte ones (i.e., it can return a single character which actually has // a string length of 2 instead of 1!) alert(fixedFromCharCode(0x2F804)); // or 194564 in decimal function fixedFromCharCode (codePt) { if (codePt > 0xFFFF) { codePt -= 0x10000; return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF)); } else { return String.fromCharCode(codePt); } } The following example returns the string "ABC". String.fromCharCode(65,66,67) Available since: 2.0.0 Parameters numbers : Number... A sequence of numbers that are Unicode values. Returns String String containing characters from encoding. Returns the index within the calling String object of the first occurrence of the specified value,or -1 if not found. Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last characterof a string called stringName is stringName.length - 1. "Blue Whale".indexOf("Blue") // returns 0 "Blue Whale".indexOf("Blute") // returns -1 "Blue Whale".indexOf("Whale",0) // returns 5 "Blue Whale".indexOf("Whale",5) // returns 5 "Blue Whale".indexOf("",9) // returns 9 "Blue Whale".indexOf("",10) // returns 10 "Blue Whale".indexOf("",11) // returns 10 The indexOf method is case sensitive. For example, the following expression returns -1: "Blue Whale".indexOf("blue") Note that '0' doesn't evaluate to true and '-1' doesn't evaluate to false. Therefore, when checking if a specific string exists within another string the correct way to check would be: "Blue Whale".indexOf("Blue") != -1 // true "Blue Whale".indexOf("Bloe") != -1 // false The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world". var anyString="Brave new world" document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) // Displays 8 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) // Displays 10 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) // Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new")) // Displays 6 The following example defines two string variables. The variables contain the same string except that the second string containsuppercase letters. The first writeln method displays 19. But because the indexOf method is case sensitive, the string"cheddar" is not found in myCapString, so the second writeln method displays -1. myString="brie, pepper jack, cheddar" myCapString="Brie, Pepper Jack, Cheddar" document.writeln('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar")) document.writeln('<P>myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar")) The following example sets count to the number of occurrences of the letter x in the string str: count = 0; pos = str.indexOf("x"); while ( pos != -1 ) { count++; pos = str.indexOf("x",pos+1); } Available since: 2.0.0 Parameters searchValue : String A string representing the value to search for. fromIndex : Number The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0. Returns Number Position of specified value or -1 if not found. Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. The calling string is searched backward, starting at fromIndex. Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last characteris stringName.length - 1. "canal".lastIndexOf("a") // returns 3 "canal".lastIndexOf("a",2) // returns 1 "canal".lastIndexOf("a",0) // returns -1 "canal".lastIndexOf("x") // returns -1 The lastIndexOf method is case sensitive. For example, the following expression returns -1: "Blue Whale, Killer Whale".lastIndexOf("blue") The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world". var anyString="Brave new world" // Displays 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) // Displays 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) // Displays 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) // Displays 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new")) Available since: 2.0.0 Parameters searchValue : String A string representing the value to search for. fromIndex : Number The location within the calling string to start the search from, indexed from left to right. It can be any integer between 0 and the length of the string. The default value is the length of the string. Returns Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Returns a number indicating whether a reference string comes before or after or is the same as thegiven string in sort order. Returns -1 if the string occurs earlier in a sort than compareString,returns 1 if the string occurs afterwards in such a sort, and returns 0 if they occur at the samelevel. The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: alert('a'.localeCompare('b')); // -1 alert('b'.localeCompare('a')); // 1 alert('b'.localeCompare('b')); // 0 Available since: 2.0.0 Parameters compareString : String The string against which the referring string is comparing. Returns Number Returns -1 if the string occurs earlier in a sort than compareString, returns 1 if the string occurs afterwards in such a sort, and returns 0 if they occur at the same level. Used to match a regular expression against a string. If the regular expression does not include the g flag, returns the same result as regexp.exec(string). If the regular expression includes the g flag, the method returns an Array containing all matches. If there were no matches,the method returns null. The returned Array has an extra input property, which contains the regexp that generated it as a result. In addition,it has an index property, which represents the zero-based index of the match in the string. In the following example, match is used to find "Chapter" followed by 1 or more numeric characters followed by a decimal pointand numeric character 0 or more times. The regular expression includes the i flag so that case will be ignored. str = "For more information, see Chapter 3.4.5.1"; re = /(chapter \d+(\.\d)*)/i; found = str.match(re); document.write(found); This returns the array containing Chapter 3.4.5.1,Chapter 3.4.5.1,.1 "Chapter 3.4.5.1" is the first match and the first value remembered from (Chapter \d+(\.\d)*). ".1" is the second value remembered from (\.\d). The following example demonstrates the use of the global and ignore case flags with match. All letters A through E and athrough e are returned, each its own element in the array var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var regexp = /[A-E]/gi; var matches_array = str.match(regexp); document.write(matches_array); matches_array now equals ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']. Available since: 2.0.0 Parameters regexp : RegExp A RegExp object. If a non-RegExp object objis passed, it is implicitly converted to a RegExp by usingnew RegExp(obj). Returns Array Contains results of the match (if any). Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. This method does not change the String object it is called on. It simply returns a new string. To perform a global search and replace, either include the g flag in the regular expression or ifthe first parameter is a string, include g in the flags parameter. The replacement string can include the following special replacement patterns: Pattern Inserts $$ Inserts a $. $& Inserts the matched substring. `$`` Inserts the portion of the string that precedes the matched substring. $' Inserts the portion of the string that follows the matched substring. $n or $nn Where n or nn are decimal digits, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object. You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. The arguments to the function are as follows: Possible Name Supplied Value str The matched substring. (Corresponds to $& above.) p1, p2, ... The _n_th parenthesized submatch string, provided the first argument to replace was a RegExp object. (Correspond to , , etc. above.) offset The offset of the matched substring within the total string being examined. (For example, if the total string was "abcd", and the matched substring was "bc", then this argument will be 1.) s The total string being examined. (The exact number of arguments will depend on whether the first argument was a RegExp object and, if so, how many parenthesizedsubmatches it specifies.) The following example will set newString to "XXzzzz - XX , zzzz": function replacer(str, p1, p2, offset, s) { return str + " - " + p1 + " , " + p2; } var newString = "XXzzzz".replace(/(X*)(z*)/, replacer); In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges'. var re = /apples/gi; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); print(newstr); In this version, a string is used as the first parameter and the global and ignore case flags are specified in the flags parameter. var str = "Apples are round, and apples are juicy."; var newstr = str.replace("apples", "oranges", "gi"); print(newstr); Both of these examples print "oranges are round, and oranges are juicy." In the following example, the regular expression is defined in replace and includes the ignore case flag. var str = "Twas the night before Xmas..."; var newstr = str.replace(/xmas/i, "Christmas"); print(newstr); This prints "Twas the night before Christmas..." The following script switches the words in the string. For the replacement text, the script uses the and replacement patterns. var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, ", "); print(newstr); This prints "Smith, John". In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement. The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning. function styleHyphenFormat(propertyName) { function upperToHyphenLower(match) { return '-' + match.toLowerCase(); } return propertyName.replace(/[A-Z]/, upperToHyphenLower); } Given styleHyphenFormat('borderTop'), this returns 'border-top'. Because we want to further transform the result of the match before the final substitution is made, we must use a function.This forces the evaluation of the match prior to the toLowerCase() method. If we had tried to do this using the match without a function, the toLowerCase() would have no effect. var newString = propertyName.replace(/[A-Z]/, '-' + '$&'.toLowerCase()); // won't work This is because '$&'.toLowerCase() would be evaluated first as a string literal (resulting in the same '$&') before using thecharacters as a pattern. The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C. The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to thefunction through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in astring to the f2c function. f2c then returns the Celsius number. This function approximates Perl's s///e flag. function f2c(x) { function convert(str, p1, offset, s) { return ((p1-32) * 5/9) + "C"; } var s = String(x); var test = /(\d+(?:\.\d*)?)F\b/g; return s.replace(test, convert); } Available since: 2.0.0 Parameters pattern : String/RegExp Either a string or regular expression pattern to search for. replacement : String/Function Either string or function: The String to replace the patternwith. Number of special replacement patterns are supported; see the "Specifying a string as a parameter" section above. A function to be invoked to create the replacement. The arguments supplied to this function are described in the "Specifying a function as a parameter" section above. The String to replace the Returns String String of matched replaced items. Executes the search for a match between a regular expression and a specified string. If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1. When you want to know whether a pattern is found in a string use search (similar to the regularexpression test method); for more information (but slower execution) use match (similar to theregular expression exec method). The following example prints a message which depends on the success of the test. function testinput(re, str){ if (str.search(re) != -1) midstring = " contains "; else midstring = " does not contain "; document.write (str + midstring + re); } Available since: 2.0.0 Parameters regexp : RegExp A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). Returns Number If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1. Extracts a section of a string and returns a new string. slice extracts the text from one string and returns a new string. Changes to the text in onestring do not affect the other string. slice extracts up to but not including endSlice. string.slice(1,4) extracts the secondcharacter through the fourth character (characters indexed 1, 2, and 3). As a negative index, endSlice indicates an offset from the end of the string. string.slice(2,-1)extracts the third character through the second to last character in the string. The following example uses slice to create a new string. // assumes a print function is defined var str1 = "The morning is upon us."; var str2 = str1.slice(4, -2); print(str2); This writes: morning is upon u Available since: 2.0.0 Parameters beginSlice : Number The zero-based index at which to begin extraction. endSlice : Number The zero-based index at which to end extraction. If omitted, sliceextracts to the end of the string. Returns String All characters from specified start up to (but excluding) end. Splits a String object into an array of strings by separating the string into substrings. The split method returns the new array. When found, separator is removed from the string and the substrings are returned in an array. Ifseparator is omitted, the array contains one element consisting of the entire string. If separator is a regular expression that contains capturing parentheses, then each time separatoris matched the results (including any undefined results) of the capturing parentheses are splicedinto the output array. However, not all browsers support this capability. Note: When the string is empty, split returns an array containing one empty string, rather than anempty array. The following example defines a function that splits a string into an array of strings using the specified separator. After splitting the string, the function displays messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements. function splitString(stringToSplit,separator) { var arrayOfStrings = stringToSplit.split(separator); print('The original string is: "' + stringToSplit + '"'); print('The separator is: "' + separator + '"'); print("The array has " + arrayOfStrings.length + " elements: "); for (var i=0; i < arrayOfStrings.length; i++) print(arrayOfStrings[i] + " / "); } var tempestString = "Oh brave new world that has such people in it."; var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"; var space = " "; var comma = ","; splitString(tempestString, space); splitString(tempestString); splitString(monthString, comma); This example produces the following output: The original string is: "Oh brave new world that has such people in it."The separator is: " "The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /The original string is: "Oh brave new world that has such people in it."The separator is: "undefined"The array has 1 elements: Oh brave new world that has such people in it. / The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" The separator is: "," The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec / In the following example, split looks for 0 or more spaces followed by a semicolon followed by 0or more spaces and, when found, removes the spaces from the string. nameList is the array returnedas a result of split. var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand "; print(names); var re = /\s*;\s*\/; var nameList = names.split(re); print(nameList); This prints two lines; the first line prints the original string, and the second line prints the resulting array. Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand Harry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand In the following example, split looks for 0 or more spaces in a string and returns the first 3 splits that it finds. var myString = "Hello World. How are you doing?"; var splits = myString.split(" ", 3); print(splits); This script displays the following: Hello,World.,How If separator contains capturing parentheses, matched results are returned in the array. var myString = "Hello 1 word. Sentence number 2."; var splits = myString.split(/(\d)/); print(splits); This script displays the following: Hello ,1, word. Sentence number ,2, . Available since: 2.0.0 Parameters seperator : String Specifies the character to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. limit : Number Integer specifying a limit on the number of splits to be found. The split method still splits on every match of separator, but it truncates the returned array to at most limit elements. Returns Array Substrings are returned in an array. Returns the characters in a string beginning at the specified location through the specified number of characters. start is a character index. The index of the first character is 0, and the index of the lastcharacter is 1 less than the length of the string. substr begins extracting characters at startand collects length characters (unless it reaches the end of the string first, in which case it willreturn fewer). If start is positive and is greater than or equal to the length of the string, substr returns anempty string. If start is negative, substr uses it as a character index from the end of the string. If startis negative and abs(start) is larger than the length of the string, substr uses 0 as the startindex. Note: the described handling of negative values of the start argument is not supported byMicrosoft JScript. If length is 0 or negative, substr returns an empty string. If length is omitted, substrextracts characters to the end of the string. Consider the following script: // assumes a print function is defined var str = "abcdefghij"; print("(1,2): " + str.substr(1,2)); print("(-3,2): " + str.substr(-3,2)); print("(-3): " + str.substr(-3)); print("(1): " + str.substr(1)); print("(-20, 2): " + str.substr(-20,2)); print("(20, 2): " + str.substr(20,2)); This script displays: (1,2): bc (-3,2): hi (-3): hij (1): bcdefghij (-20, 2): ab (20, 2): Available since: 2.0.0 Parameters start : Number Location at which to begin extracting characters. length : Number The number of characters to extract. Returns String Modified string. Returns the characters in a string between two indexes into the string. substring extracts characters from indexA up to but not including indexB. In particular:* If indexA equals indexB, substring returns an empty string.* If indexB is omitted, substring extracts characters to the end of the string.* If either argument is less than 0 or is NaN, it is treated as if it were 0.* If either argument is greater than stringName.length, it is treated as if it werestringName.length. If indexA is larger than indexB, then the effect of substring is as if the two arguments wereswapped; for example, str.substring(1, 0) == str.substring(0, 1). The following example uses substring to display characters from the string "Sencha": // assumes a print function is defined var anyString = "Sencha"; // Displays "Sen" print(anyString.substring(0,3)); print(anyString.substring(3,0)); // Displays "cha" print(anyString.substring(3,6)); print(anyString.substring(6,3)); // Displays "Sencha" print(anyString.substring(0,6)); print(anyString.substring(0,10)); The following example replaces a substring within a string. It will replace both individualcharacters and substrings. The function call at the end of the example changes the string "BraveNew World" into "Brave New Web". function replaceString(oldS, newS, fullS) { // Replaces oldS with newS in the string fullS for (var i = 0; i < fullS.length; i++) { if (fullS.substring(i, i + oldS.length) == oldS) { fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length); } } return fullS; } replaceString("World", "Web", "Brave New World"); Available since: 2.0.0 Parameters indexA : Number An integer between 0 and one less than the length of the string. indexB : Number (optional) An integer between 0 and the length of the string. Returns String Returns the characters in a string between two indexes into the string. The characters within a string are converted to lower case while respecting the current locale. Formost languages, this will return the same as toLowerCase. The toLocaleLowerCase method returns the value of the string converted to lower case according toany locale-specific case mappings. toLocaleLowerCase does not affect the value of the stringitself. In most cases, this will produce the same result as toLowerCase(), but for some locales,such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there maybe a different result. The following example displays the string "sencha": var upperText="SENCHA"; document.write(upperText.toLocaleLowerCase()); Available since: 2.0.0 Returns String Returns value of the string in lowercase. The characters within a string are converted to upper case while respecting the current locale. Formost languages, this will return the same as toUpperCase. The toLocaleUpperCase method returns the value of the string converted to upper case according toany locale-specific case mappings. toLocaleUpperCase does not affect the value of the stringitself. In most cases, this will produce the same result as toUpperCase(), but for some locales,such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there maybe a different result. The following example displays the string "SENCHA": var lowerText="sencha"; document.write(lowerText.toLocaleUpperCase()); Available since: 2.0.0 Returns String Returns value of the string in uppercase. Returns the calling string value converted to lower case. The toLowerCase method returns the value of the string converted to lowercase. toLowerCase doesnot affect the value of the string itself. The following example displays the lowercase string "sencha": var upperText="SENCHA"; document.write(upperText.toLowerCase()); Available since: 2.0.0 Returns String Returns value of the string in lowercase. Returns a string representing the specified object. Overrides the Object.toString method. The String object overrides the toString method of the Object object; it does not inheritObject.toString. For String objects, the toString method returns a string representation ofthe object. The following example displays the string value of a String object: x = new String("Hello world"); alert(x.toString()) // Displays "Hello world" Available since: 2.0.0 Returns String A string representation of the object. Returns the calling string value converted to uppercase. The toUpperCase method returns the value of the string converted to uppercase. toUpperCase doesnot affect the value of the string itself. The following example displays the string "SENCHA": var lowerText="sencha"; document.write(lowerText.toUpperCase()); Available since: 2.0.0 Returns String Returns value of the string in uppercase. Removes whitespace from both ends of the string. Does not affect the value of the string itself. The following example displays the lowercase string "foo": var orig = " foo "; alert(orig.trim()); NOTE: This method is part of the ECMAScript 5 standard. Available since: 2.0.0 Returns String A string stripped of whitespace on both ends. Returns the primitive value of the specified object. Overrides the Object.valueOf method. The valueOf method of String returns the primitive value of a String object as a string datatype. This value is equivalent to String.toString. This method is usually called internally by JavaScript and not explicitly in code. x = new String("Hello world"); alert(x.valueOf()) // Displays "Hello world" Available since: 2.0.0 Returns String Returns value of string.
Generating Graphics With Piddle by Michal Wallace 05/31/2001 You probably know by now that Python's flexible data structures make working with complex data a breeze. Did you know Python also makes it a snap to visualize your data in vibrant color? Thanks to the slew of graphics modules people have built, Python is a handy language for creating graphics on the fly. This article looks at two of those modules and shows how to use them to generate graphics from a Python data structure. The example we'll use is a simple Gantt chart. Gantt charts, a type of timeline often used in project planning, clearly show how resources are allocated to different tasks over time. A Gantt chart makes it easy to see who's supposed to be doing what, and when they're supposed to be finished. It also shows who's overbooked and who's free to pick up the slack. I use Gantt charts to help organize my projects so I don't try to take on too much. In this case, the resources I am tracking are really just chunks of my time and energy. If I see less than three boxes in a column, I know I've got some free time coming up. If I see more than that, I try to reschedule things. Here's a recent example: This chart, reduced in size to fit this page, was generated with just under 100 lines of Python code, using two imaging modules: piddle and PIL. Piddle stands for Plug In Drawing, Does Little Else. It provides a simple interface for drawing 2D lines, arcs, shapes, and text. It allows you to write your drawings to a variety of file types and to interactive displays generated by Tk or wxWindows. You can fetch Piddle from SourceForge. You'll notice two packages there: piddle and sping. At the moment, sping (Simple Platform Independent Graphics) is the development branch of piddle, rebundled as a python package and renamed to be a little less offputting. But we'll use piddle for this example. We'll also need the Python Imaging Library (PIL), which we'll use to save our chart as a JPEG. The PIL homepage offers the complete source as well as precompiled binaries for Windows. Why two modules? PIL by itself is excellent for general image manipulation. It takes care of the low level details of reading and writing file formats, scaling and rotating images, and dealing with individual pixels. While PIL provides some drawing capabilities, piddle operates at a higher level. It offers more choices for storing and displaying images, and it provides the support I mentioned for interactive drawings (though we won't get into that here). Getting Started To install piddle, add the unzipped piddle directory to your Python path. To install PIL on windows, unzip the precompiled binaries to your Python directory. Installing PIL on Unix is a bit trickier; you'll have to follow the installation instructions to compile it yourself. We'll test the installation by generating a simple, empty graphic. The first step is to define a Canvas object. A piddle Canvas is a rectangular drawing area similar to a painter's canvas, but composed of pixels. There is a different Canvas class for each piddle backend. Since we're working with PIL, we'll use piddlePIL.PILCanvas. Because we might want to change to another backend later, we'll use python 2.0's import as syntax to hide the module name: import piddlePIL as pid c = pid.PILCanvas(size=(250,250)) # .. code to draw graphics goes here .. c.save("gantt", format="jpeg") If everything is installed correctly, running this code will save a completely blank 250x250 JPEG called gantt.jpeg to the current directory. Note that at the time of this writing, neither piddle nor PIL has been updated for python 2.1. If you're using the latest interpreter you may get some warning messages, however, the code should still run. Drawing the Background Now that we've got the basics working, let's draw the simple outline of our chart. A Gantt chart is essentially a set of rows and columns with some colored rectangles drawn on it, so we'll use the drawRect and drawLine methods from PILCanvas to do most of our work. Before we start drawing, let's define a few variables to control how we draw: things like column titles, cell sizes, and even the size of the image itself. This will make the code a little easier to read, and also make it easier for us to tweak our image later. Replace the canvas definition with the following: titles = ["apr","may","jun","jul","aug","sep"] cols = len(titles) # number of data columns rows = 6 # number of data rows cellW = 80 # cell width cellH = 20 # cell height lftColW = 100 # width of left column (task names) topRowH = 25 # height top row (month names) # calculate image size and define the canvas: imgW = lftColW + (cellW * cols) imgH = topRowH + (cellH * rows) c = pid.PILCanvas(size=(imgW,imgH)) For the chart's background, we'll draw some shaded boxes on the top and left and use a couple for loops to draw the lines. In the code below, notice how passing three arguments to Python's range function lets us define our grid wholly in terms of the variables we created. The arguments tell Python where to start, where to end, and how long to make each step in between. To avoid clutter, we'll multiply cellH by two in the second loop, skipping every other horizontal line. ## color in the headers: c.drawRect(0,0,imgW,topRowH, fillColor=pid.gainsboro) c.drawRect(0,0,lftColW,imgH, fillColor=pid.gainsboro) # and the area where toprow and lftcol overlap: c.drawRect(0,0,lftColW,topRowH, fillColor=pid.silver) ## draw the grid: for x in range(lftColW, imgW, cellW): c.drawLine(x, 0, x, imgH) for y in range(topRowH, imgH, cellH * 2): c.drawLine(0, y, imgW, y) ## draw outer border c.drawRect(0, 0, imgW-1, imgH-1) To fill in the labels, we'll call the drawString method, passing it a string, some x and y coordinates, and a Font object. We need some math to center the labels. The formula for centering requires taking the width of the string in pixels and subtracting half from the point around which we're centering. Piddle provides the stringhWidth method for just this task: ## column titles, centered horizontally and vertically: for i in range(cols): c.drawString(titles[i], lftColW + (cellW * i) + (cellW - c.stringWidth(titles[i]))/2, # left (topRowH + 12)/2, # top pid.Font(face="sansserif",size=12,bold=1)) Pages:
I'm using the Facebook SDK on Android to post an update to the user's feed. I was able to get it to work when I did not have the Facebook client installed. Now, even after removing the Facebook app, when I try to authorize or open the feed dialog the activity is abrupty killed. I don't get any message telling me that the app has crashed or anything. It's just destroyed. The only message is Mono telling me that the thread 0x0 has been prematurely finalized, which is odd. Also, there's this odd "Not supported in this case." message from webcore. I'm using the NativeActivity class. I don't use it directly but I extend it in my activity. Here's the logcat from around where things go wrong: I/PixelWorldEngine( 6796): Authorizing for Facebook... D/Database( 6796): dbopen(): path = /data/data/com.ri.BubblingUpLite/databases/webview.db, flag = 6, cannot stat file, error message: No such file or directory D/Database( 6796): dbopen(): path = /data/data/com.ri.BubblingUpLite/databases/webview.db, mode: delete, disk free size: 35 M, handle: 0x801450 D/Database( 6796): dbopen(): path = /data/data/com.ri.BubblingUpLite/databases/webviewCache.db, flag = 6, cannot stat file, error message: No such file or directory D/Database( 6796): dbopen(): path = /data/data/com.ri.BubblingUpLite/databases/webviewCache.db, mode: delete, disk free size: 35 M, handle: 0x7ff128 D/skia ( 6796): htcFlashPlugin::htcFlashPlugin W/webcore ( 6796): Not supported in this case. I/PixelWorld-glue( 6796): WindowFocusChanged: 0x333288 -- 0 D/SensorService( 120): disable: connection.get() = 0x9f5c20 D/SensorService( 120): disable: get sensor name = BMA150 3-axis Accelerometer D/SensorService( 120): SensorDevice::activate: handle = 0x0, enabled = 0x0 D/Sensors ( 120): Enable akm: en = 0 D/SensorService( 120): noteStopSensor: uid = 0x274d, handle = 0x0 D/SensorService( 120): pid=6796, uid=10061 D/SensorService( 120): Active sensors: D/SensorService( 120): CM3602 Light sensor (handle=0x00000004, connections=1) W/webcore ( 6796): Not supported in this case. W/mono ( 6796): Thread 0x0 may have been prematurely finalized D/SensorGUI( 120): ~SensorChannel: mSendFd = 255, mReceiveFd = -1 D/AudioPolicyService( 72): stopOutput() tid 2223 D/AudioPolicyService( 72): releaseOutput() tid 2223 D/AudioPolicyService( 72): releaseOutput() tid 2223 I/ActivityManager( 120): Process com.ri.BubblingUpLite (pid 6796) has died. I/WindowManager( 120): WIN DEATH: Window{407e9548 com.ri.BubblingUpLite/com.ri.PixelWorldEngine.GameActivity paused=false}
If I have an enumerate object x, why does doing the following: dict(x) clear all the items in the enumerate sequence? If you want to create a real sequence from a iterator you can call stuff = range(5,0,-1) it = enumerate(stuff) print dict(it), dict(it) # first consumes all items, so there are none left for the 2nd call seq = list(enumerate(stuff)) # creates a list of all the items print dict(seq), dict(seq) # you can use it as often as you want
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
If you are a shell addicted person and like Python, then the IPythonwas made just for you. The IPythonprovides a very usefull feature (that may look a bit strange at first) of mixing Python and Shell commandsin a easy and intuitive way. I don’t pretend to say why you should use IPython instead of your current shellbut I believe that if you know Python, you should prefer to write Python code instead of Bash code. I’ll assume that you already have the IPython installed, but if you don’t take a look atIPython’s documentation to see how to install it. I’m running Debian, sothis setup is focused on it. It should work for the most of the others linux distros but if you are runninga different system, I’m sorry but you may have to adapt some commands and/or paths. :) Configuring the IPython’s prompt The first time you run IPython, it displays a warning about the creation of your personal configuration directory.One of the most important parts of this warning is about the new configuration file: ~/.ipython/ipy_user_conf.py.So let’s configure this file and the IPython’s prompt to make it looks exactly like the Debian’s prompt. Edit yourconfiguration file and change the following settings as below: ... import ipy_profile_sh ... o.prompt_in1 = r'\C_Normal\u@\H:\Y2$ ' o.prompt_in2 = r'\C_Normal... ' ... The first option, import ipy_profile_sh, avoid you to have to escape all the Bash commands. The second andthird options, o.prompt_in1 and o.prompt_in2, change the IPython’s prompt. And now start the IPython as follow: afurlan@wetzel:~$ ipython -nosep -nobanner -noconfirm_exit afurlan@wetzel:~$ afurlan@wetzel:~$ afurlan@wetzel:~$ print 'hello python!' hello python! afurlan@wetzel:~$ echo 'hello bash!' hello bash! Great, now you’re able to run Python commands in your iPython shell: afurlan@wetzel:~$ for line in file('domains.txt'): ... print line ... ... arthurfurlan.org configr.com And a mixed of Python and Bash commands: afurlan@wetzel:~$ for line in file('domains.txt'): ... echo "$line" ... ... arthurfurlan.org configr.com afurlan@wetzel:~$ for line in file('domains.txt'): ... echo "$line.strip()" ... ... arthurfurlan.org configr.com Setting the IPython as your default shell Actually I don’t like to set the IPython as my default shell… I use to run screen so I prefer to configure it to open five IPython sessions by default, but if you really like to set it as your default shell, you can add the following line at the end of your ~/.bashrc file: ... exec ipython -nosep -nobanner -noconfirm_exit If you’re a screen user like me, you can add the following lines at your ~/.screenrc: ... ## open 5 ipython sessions by default screen -t p 1 ipython -nosep -nobanner -noconfirm_exit screen -t p 2 ipython -nosep -nobanner -noconfirm_exit screen -t p 3 ipython -nosep -nobanner -noconfirm_exit screen -t p 4 ipython -nosep -nobanner -noconfirm_exit screen -t p 5 ipython -nosep -nobanner -noconfirm_exit ... Or, if you like, you can also get my current .screenrc file.
I use SQLAlchemy for all python database access. I highly recommend SQLAlchemy. SA uses pyodbc under the hood when connecting to SQL server databases. It uses other DBAPI libraries to connect to other database, for instance cx_Oracle. A simplistic example, using SQLAlchemy like you would normally use a DBAPI module: import sqlalchemy engine = sqlalchemy.create_engine('sqlite:///database.db') for r in engine.execute('SELECT * FROM T'): print(r.OneColumn, r.OtherColumn) But the real value of SQLAlchemy lies in its ORM and SQL expression language. Have a look, it is well worth the effort to learn to use.
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
Началось все с обычной задачи по работе. Открываю консоль, запускаю dev сервер с веб проектом и получаю вот такое: Traceback (most recent call last): File "./manage.py", line 89, in script.run() File "/Users/riffm/proj/third-party/werkzeug/script.py", line 168, in run return func(**arguments) File "/Users/riffm/proj/third-party/werkzeug/script.py", line 298, in action static_files=static_files) File "/Users/riffm/proj/third-party/werkzeug/serving.py", line 390, in run_simple run_with_reloader(inner, extra_files, reloader_interval) File "/Users/riffm/proj/third-party/werkzeug/serving.py", line 319, in run_with_reloader reloader_loop(extra_files, interval) File "/Users/riffm/proj/third-party/werkzeug/serving.py", line 284, in reloader_loop for filename in chain(iter_module_files(), extra_files or ()): File "/Users/riffm/proj/third-party/werkzeug/serving.py", line 271, in iter_module_files filename = getattr(module, '__file__', None) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/py/_apipkg.py", line 159, in __getattribute__ return getattr(getmod(), name) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/py/_apipkg.py", line 144, in getmod x = importobj(modpath, None) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/py/_apipkg.py", line 37, in importobj module = __import__(modpath, None, None, ['__doc__']) ImportError: No module named pytest Сторонние библиотеки в проекте храняться в папке third-party, которая добавляется в sys.path в едином месте — manage.py. Ну, может кто доставил зависимость и не углядел, подумал я. И начал grep’ать проект на предмет использования pytest. Никаких результатов. Т.е. модуль или пакет pytest никто не импортирует явно (!). В трейсбеке видно, что в этом безобразии учавствет некий пакет py. Перед тем как посмотреть в его исходник, я запустил shell с приложением и провел мелкое расследование. proj riffm$ ./manage.py shell Python shell >>> import sys >>> filter(lambda k: k.startswith('py'), sys.modules.keys()) ['py.builtin', 'pytils.utils', 'py.sys', 'py.os', 'pytils.translit', 'py.error', 'pytils.sys',  'pytils', 'py.iniconfig', 'py.test.collect', 'pytils.numeral', 'pytils.warnings', 'py.xml', 'py.types', 'pytils.os', 'py.process', 'py.apipkg', 'pytils.re', 'pytils.third', 'pytils.third.re', 'pyexpat.errors', 'pyexpat.model', 'py.io', 'py', 'pyexpat', 'py.code', 'py.path', 'py._apipkg', 'pytils.err', 'pytils.third.types', 'py.py', 'pytils.pytils', 'pytils.typo', 'pytils.third.inspect', 'py.log', 'py.test', 'pytils.decimal', 'pytils.dt', 'pytils.datetime', 'py.test.cmdline', 'pytils.third.aspn426123'] Нашелся некий py.test и еще куча модулей и пакетов из, непойми откуда взявшегося, py пакета. Но pytest нигде нет. При попытке запустить только интерпретатор таких вещей не обнаруживаю. Значит, кто-то все-таки импортирует py или что-то из py. grep показал, что это делает werkzeug. Он импортирует greenlet’ы (wtf?) и перехватывает все исключения (там есть комментарий который многое объясняет). Но как мы знаем, питон импортирует последовательно проходя все пакеты, значит мой путь лежал к py/__init__.py. Тут даже бывалый и видавший виды питон разработчик ахнет и стечет с кресла под стол. В py/__init__.py в наглую патчится sys.modules. Для этого у автора есть специальный API (!), вызовы которого видны в трейсбеке. Без комментариев. Скажу только, что там и нашелся pytest. Потом выяснилось откуда взялся py в моем питоне, он идет зависимостью для пакета tox, что не удивительно, ведь автор один =) А, сам tox используется для организации тестирования webob, которым я, за пару дней до этого, занимался. Выводы: P.S. В werkzeug 0.7 из py, вроде, ничего не импортируется. И кстати, в py есть такой тикет со статусом wontfix =) подумала я тут, кому жарче? комбайнеру на кубанских полях в солнцепек. или водителю автобуса в московских пробках. или пожарному в горящих лесах якутии …. и как-то мне стало прохладнее … с вентилятором под боком и душем в пяти метрах и в любой момент … быть благодарным это правильнее. каждодневного нытья … Истина. Спасибо, Красное море! Без ссылочной целостности любой веб проект не представляет интереса. Раньше ссылки вбивались в код как есть. Потом в обиход вошел термин url reverse. Подход простой: функция (например url_for) принимала строку — имя url и параметры, требуемые для корректного построения адреса, на выходе получается строка url. Таким образом, в проекте можно переименовывать адреса ресурсов не теряя ссылочную целостность. Такой подход применяется в werkzeug, django, pyramid (+1), rails (2.3 paths and urls, 3.6 naming routes) и др. Для примера возьмем следующее приложение написанное при помощи библиотеки insanities. from insanities import web import views ns = web.namespace app = web.cases( web.match('/', 'index') | views.index, web.prefix('/docs') | ns('docs') | web.cases( web.match('') | views.docs, web.match('/new', 'new') | views.new_doc, web.prefix('/<int:doc_id>') | ns('item') | view.get_doc | web.cases( web.match('') | views.show_doc, web.match('/update', 'update') | views.update_doc, web.match('/delete', 'delete') | views.delete_doc, ) ) ) url_for = web.Reverse.from_handler(app) url_for('index') # '/' url_for('docs') # '/docs' url_for('docs.new') # '/docs/new' url_for('docs.item', doc_id=1) # '/docs/1' url_for('docs.item.update', doc_id=1) # '/docs/1/update' url_for('docs.item.delete', doc_id=1) # '/docs/1/delete' Тут все просто. url строится по названию адреса (второй атрибут web.match) с учетом web.namespace. Но что, если надо реализовать ресурс “события”? А еще опубликовать этот ресурс в нескольких местах? Прикинем следующую функцию-фабрику. (Пример не очень хорош) from insanities import web import views ns = web.namespace def event_factory(): return web.cases( web.match('') | views.events, web.match('/new', 'new') | views.new_event, web.prefix('/<int:event_id>') | ns('item') | views.get_event | web.cases( web.match('') | views.show_event, web.match('/update', 'update') | views.update_event, web.match('/delete', 'delete') | views.delete_event, ) ) И пристроим ее в двух разных местах нашего приложения ... app = web.cases( web.match('/', 'index') | views.index, web.prefix('/docs') | ns('docs') | web.cases( web.match('') | views.docs, web.match('/new', 'new') | views.new_doc, web.prefix('/<int:doc_id>') | ns('item') | view.get_doc | web.cases( web.match('') | views.show_doc, web.match('/update', 'update') | views.update_doc, web.match('/delete', 'delete') | views.delete_doc, web.prefix('/events') | ns('events') | event_factory(), ) ), web.prefix('/events') | ns('events') | event_factory(), ) С учетом всего написаного url_for будет работать так ... url_for = web.Reverse.from_handler(app) url_for('docs.item.events', doc_id=1) # '/docs/1/events' url_for('docs.item.events.item', doc_id=1, event_id=1) # '/docs/1/events/1' url_for('docs.item.events.item.update', doc_id=1, event_id=1) # '/docs/1/events/1/update' url_for('events') # '/events' url_for('events.item', event_id=1) # '/events/1' url_for('events.item.update', event_id=1) # '/events/1/update' Проблема заключается в следующем: наверняка, в views.show_event надо будет дать ссылку на обновление или удаление данного элемента. На момент вызова учитывается текущий namespace и можно делать url относительно его. Напиример если мы попали в views.show_event с namespace равеным ‘events’. url_for('.') # '/events' url_for('.item', event_id=1) # '/events/1' url_for('.item.update', event_id=1) # '/events/1/update' Но в случае с ‘docs.item.events’ такой трюк не пройдет, т.к. для построения url нужен так же и doc_id (по правде говоря, он попадает во views.show_event). Как удобнее решать такие ситуации — не знаю. Можно использовать предопределенный url reverse объект. url_for.events() # '/events' url_for.events.item(event_id=1) # '/events/1' url_for.events.item.update(event_id=1) # '/events/1/update' url_for.docs.item.events(doc_id=1) # '/docs/1/events' predefined = url_for.docs.item(doc_id=1) predefined.events() # '/docs/1/events' predefined.events.item(event_id=1) # '/docs/1/events/1' predefined.events.item.update(event_id=1) # '/docs/1/events/1/update' Т.е. url_for атрибуты которого возвращают новый объект url_for частично заполненный. Синтаксис приведенный выше — неоднозначен. Жду предложений по этому поводу. у нас есть новая кухня … и нет денег и сил :) хочется весны и почему-то арбузов … с черешней. git checkout -b 2011
Ok, I think you a bit confused. You can use gettext and po/mo files from within appengine, since gettext is exported from Google's django.util implementation (a discussion of this can be found in the google-appengine google group) : from django.utils.translation import gettext as _ I am not familiar with AppEngine CSV's i18n format, but there is a very easy way to extract internationalized strings from tornado's code and templates using xgettext, just basically force python from the command line. As an example: xgettext -L Python -o myproject.pot *.html That command will get all i18n'ed strings from *.html in your current directory and will place them on myproject.pot. You can initialize that file and translate into let's say ./it_IT/myproject.po using any commercial or opensource tool (I would recommend poedit or pootle) and once you have translated all strings you can convert the file into CVS using Translate Toolkit's po2csv, which is also written in python: po2csv -i it_IT/myproject.po -o it_IT/myproject.csv The format is location:codeLine,source,target which is pretty simple end easy to convert to whichever other format you need (I am not familiar with appengine's i18n CSV format), you can call po2csv with no -o argument and pipe the output out from STDOUT. I don't know if that solves your question, but basically I think you should adopt a code->pot/po->csv workflow since there are many tools that expect po/pot/mo and will allow you to handle your translations or work with translation memories/spellcheckers, etc.... try and let me know if you need any more help with that.
When would you use a Python mixin? That's not a rhetorical question. I'd like to know in which scenarios a mixin in python really is the best option. I can't seem to think of any, but maybe I'm not thinking outside the box enough. The basic idea of a mixin is to create a small re-usable class that can "plug-in" to other largerclasses. From the wikipedia definition, a mixin is a way to compose classes together withoutusing inheritance. The problem is unlike ruby, python mixins are a purely conceptual construct.Python mixins are inheritance (the only difference is that the class name usually contains 'Mixin'). It is up to the developer to remember this, and to manually avoid all of the commonpitfalls of multiple inheritance. This kind of defeats the whole purpose of the mixin in the firstplace. What's more is that most people use python mixins improperly. Consider the following example: from book import Book from index import IndexMixin class TextBook(Book, IndexMixin): def __init__(self, name, contents, edition='1st'): Book.__init__(self, name, contents) self.edition = edition t = TextBook('Learn Python the Hard Way') t.search('python') >>> 0 results found Here we correctly use inheritance to denote Book as a base class, a textbook is a book. We use anIndexMixin because textbooks aren't indices, they have an index. We then instantiate it and searchthe book for the string 'python'. Wait a minute, how can a textbook about python not contain theword python? In python, the multiple inheritance chain is read right to left, this means thatIndexMixin is technically the base class here. It just so happens that IndexMixin also has a functioncalled search which overrides the one defined in Book. It turns out there's another way to compose classes together without using inheritance. Just usethe class (or module) directly: from book import Book from index import Index class TextBook(Book): def __init__(self, name, contents, edition='1st'): Book.__init__(self, name, contents) self.edition = edition self.index = Index() t = TextBook('Learn Python the Hard Way') t.search('python') >>> Many results found t.index.search('python') >>> 0 results found If the relationship between objects A and B is "A is a B", then B is a base class, not a mixin. If the relationship is "A has a B", then why not use composition? What benefit does a mixin give you?
languages wernaeh at April 26th, 2010 19:00 — #1 Hello everyone Recently, I've been having quite some performance problem with using a large (\~\~500 MB) std::vector\, which is repeatedly getting resized, cleared, and dropped in a tight loop. Weirdly, the problem comes from the STL that accompanies Visual Studio 2008. In particular, using std::vector::resize() is slow, since it uses a "normal" inner loop for default-constructing (zero-initializing) the new vector entries. On my machine, resizing() the vector takes around 8 seconds, while allocating the memory with std::vector::reserve() or copying an entire new dataset into the vector with one of the optimized RTL functions takes an order of magnitude less time. After some digging in the STL, I noticed that there is an optimized _fill_n method that uses memset for unsigned-char type elements. Yet this method does not get called by the compiler on template resolution, but instead, the vector is resized with the loop-based, default version of _fill_n, i.e. this // TEMPLATE FUNCTION fill_n template<class _OutIt, class _Diff, class _Ty> inline void __CLRCALL_OR_CDECL _Fill_n(_OutIt _First, _Diff _Count, const _Ty& _Val, _Range_checked_iterator_tag) { // copy _Val _Count times through [_First, ...) for (; 0 < _Count; --_Count, ++_First) *_First = _Val; } with: _OutIt == unsigned char* _Diff == unsigned int _Ty = unsigned char is preferred over the non-template inline void __CLRCALL_OR_CDECL _Fill_n (unsigned char *_First, size_t _Count, int _Val, _Range_checked_iterator_tag) { // copy unsigned char _Val _Count times through [_First, ...) ::memset(_First, _Val, _Count); } a few lines further down. The reason, I think, is that the compiler decides to prefer a template over implicitly casting any parameters (also makes sense when considering classes with custom casts), but then again, the optimized methods won't probably ever be used (target pointer type != value type...) For other methods, such as vector copying, the correct, optimized version using memcpy is used for certain scalar types. Is this explanation correct ? Is this a compiler bug or a problem in the STL ? Any ideas on how to fix the misbehaviour ? (Apart from designing a better algorithm, or using a custom, malloc-ed container...) Thank you for your time, Cheers, jarkkol at April 27th, 2010 03:03 — #2 Yeah, the templated version is better match due to implicit cast so looks like a bug in the STL implementation (should be "unsigned char _Val"). You could just implement the proper version of the function yourself which should be called by std::vector, afaik. wernaeh at April 27th, 2010 05:23 — #3 Okay, works like a charm My vector resize() time is down to less than half a second now. I just hope this modification does not have any side effects... Well, I guess I'll notice soon enough :o) Thank you, Cheers, jarkkol at April 27th, 2010 05:36 — #4 You may have some ODR issues if the std::vector is instantiated for unsigned char somewhere where the function isn't defined, but meh d: kvakvs at April 27th, 2010 05:47 — #5 Seems vector does not do you good. See if you can use different container than std::vector. You might benefit from making a a new class simulating behavior of std::vector, which would store data in chunks and resize only chunk that needs it. Also if you randomly add items in the middle of vector, those chunks may as well grow and interchange data trying to rebalance their sizes. wernaeh at April 27th, 2010 09:37 — #6 You may have some ODR issues if the std::vector is instantiated for unsigned char somewhere where the function isn't defined, but meh d: That's why I placed the replacement function directly into \ Seems vector does not do you good. See if you can use different container than std::vector. You might benefit from making a a new class simulating behavior of std::vector, which would store data in chunks and resize only chunk that needs it. Also if you randomly add items in the middle of vector, those chunks may as well grow and interchange data trying to rebalance their sizes. Basically, I'm using the std::vector less because its usefulness, but more because its standard and everyone knows how it works. In particular, I could without much effort also simply change to a unsigned char*, use malloc, and add a ScopeGuard for exception safety. std::vector just reads much nicer, and if correctly implemented, isn't all that much slower than a specialized container. Thank you for the input, though Cheers,
Edit: Let me try to reword and improve my question. The old version is attached at the bottom. What I am looking for is a way to express and use free functions in a type-generic way. Examples: abs(x) # maps to x.__abs__() next(x) # maps to x.__next__() at least in Python 3 -x # maps to x.__neg__() In these cases the functions have been designed in a way that allows users with user-defined types to customize their behaviour by delegating the work to a non-static method call. This is nice. It allows us to write functions that don't really care about the exact parameter types as long as they "feel" like objects that model a certain concept. Counter examples: Functions that can't be easily used generically: math.exp # only for reals cmath.exp # takes complex numbers Suppose, I want to write a generic function that applies exp on a list of number-like objects. What exp function should I use? How do I select the correct one? def listexp(lst): return [math.exp(x) for x in lst] Obviously, this won't work for lists of complex numbers even though there is an exp for complex numbers (in cmath). And it also won't work for any user-defined number-like type which might offer its own special exp function. So, what I'm looking for is a way to deal with this on both sides -- ideally without special casing a lot of things. As a writer of some generic function that does not care about the exact types of parameters I want to use the correct mathematical functions that is specific to the types involved without having to deal with this explicitly. As a writer of a user-defined type, I would like to expose special mathematical functions that have been augmented to deal with additional data stored in those objects (similar to the imaginary part of complex numbers). What is the preferred pattern/protocol/idiom for doing that? I did not yet test numpy. But I downloaded its source code. As far as I know, it offers a sin function for arrays. Unfortunately, I haven't found its implementation yet in the source code. But it would be interesting to see how they managed to pick the right sin function for the right type of numbers the array currently stores. In C++ I would have relied on function overloading and ADL (argument-dependent lookup). With C++ being statically typed, it should come as no surprise that this (name lookup, overload resolution) is handled completely at compile-time. I suppose, I could emulate this at runtime with Python and the reflective tools Python has to offer. But I also know that trying to import a coding style into another language might be a bad idea and not very idiomatic in the new language. So, if you have a different idea for an approach, I'm all ears. I guess, somewhere at some point I need to manually do some type-dependent dispatching in an extensible way. Maybe write a module "tgmath" (type generic math) that comes with support for real and complex support as well as allows others to register their types and special case functions... Opinions? What do the Python masters say about this? TIA Edit: Apparently, I'm not the only one who is interested in generic functions and type-dependent overloading. There is PEP 3124 but it is in draft state since 4 years ago. Old version of the question: I have a strong background in Java and C++ and just recently started learning Python. What I'm wondering about is: How do we extend mathematical functions (at least their names) so they work on other user-defined types? Do these kinds of functions offer any kind of extension point/hook I can leverage (similar to the iterator protocol where next(obj) actually delegates to obj.__next__, etc) ? In C++ I would have simply overloaded the function with the new parameter type and have the compiler figure out which of the functions was meant using the argument expressions' static types. But since Python is a very dynamic language there is no such thing as overloading. What is the preferred Python way of doing this? Also, when I write custom functions, I would like to avoid long chains of if isinstance(arg,someClass): suchandsuch elif ... What are the patterns I could use to make the code look prettier and more Pythonish? I guess, I'm basically trying to deal with the lack of function overloading in Python. At least in C++ overloading and argument-dependent lookup is an important part of good C++ style. Is it possible to make x = udt(something) # object of user-defined type that represents a number y = sin(x) # how do I make this invoke custom type-specific code for sin? t = abs(x) # works because abs delegates to __abs__() which I defined. work? I know I could make sin a non-static method of the class. But then I lose genericity because for every other kind of number-like object it's sin(x) and not x.sin(). Adding a __float__ method is not acceptable since I keep additional information in the object such as derivatives for "automatic differentiation". TIA Edit: If you're curious about what the code looks like, check this out. In an ideal world I would be able to use sin/cos/sqrt in a type-generic way. I consider these functions part of the objects interface even if they are "free functions". In __somefunction I did not qualify the functions with math. nor __main__.. It just works because I manually fall back on math.sin (etc) in my custom functions via the decorator. But I consider this to be an ugly hack.
I started with the answer by @mgilson and reworked it a bit. I wanted to test the "decision bit" and lookup table techniques as discussed in my answer to the original question: http://stackoverflow.com/a/17782979/166949 I made a few changes to the original. Some were just style things that reflect my personal preference. However, I discovered bugs in the original, and I think it's important to measure the correct code. I made the Python code now take arguments from the command line, and wrote a shell script that runs the Python script using Python 2.x, Python 3.x, and PyPy. The exact versions were: Python 2.7.6, Python 3.4.0, and PyPy 2.7.3 I ran the tests on Linux Mint 17, 64-bit version. The CPU is an AMD Phenom 9850 running at 2.5 GHz with 16 GB of RAM. The Linux kernel version, per uname -r, is: 3.13.0-24-generic The reason I made the code take arguments from the command line is that 327 is a pretty short list. I figured that the sum() and generator expressions would do better when the list was much longer, so I made list size and number of trials be passed from the command line. The results shows which Python, and the list length and number of trials. Conclusion: to my surprise, even with a long list, Python was fastest using sum() with a list comprehension! There is some overhead to running a generator that seems to be slower than the overhead of building a list and then tearing it down. However, if the list got truly large, I expected the generator would begin to out-perform the list comprehension. With a list of a million random values, the listcomp was still faster, but when I went to 16 million random values, the genexp became faster. And the speed penalty of the generator expression is not large for shorter lists. So I still favor the generator expression as the go-to way to solve this problem in Python. Interestingly, PyPy was fastest with the table lookup. This makes sense: that was the fastest way I found in C, and PyPy is generating native code from the JIT. For CPython, with its virtual machine, it is faster to invoke a single operation than several operations; the overhead of the Python VM can outweigh a more expensive fundamental operation. Thus integer division is faster than bit masking plus bit shifting, because the division is a single operation. But in PyPy, the bit masking+shifting is much faster than the division. Also, in CPython, using sum() lets your code run in the C internals so it can be very fast; but in PyPy, sum() is slower than just writing a straighforward loop that the JIT can turn into a wicked fast native loop. My guess is that the generator machinery is hard for PyPy to grok and optimize away into native code. The shell script: for P in python python3 pypy; do echo "$P ($1, $2)" $P test_branches.py $1 $2 echo done The Python code: import random import sys import timeit try: RANGE = xrange except NameError: RANGE = range if len(sys.argv) != 3: print("Usage: python test_branches.py <length_of_array> <number_of_trials>") sys.exit(1) TEST_DATA_LEN = int(sys.argv[1]) NUM_REPEATS = int(sys.argv[2]) _test_data = [random.randint(0,255) for _ in RANGE(TEST_DATA_LEN)] def test0(data): """original way""" total = 0 for i in RANGE(TEST_DATA_LEN): if data[i] >= 128: total += data[i] return total def test1(data): """better loop""" total = 0 for n in data: if n >= 128: total += n return total def test2(data): """sum + generator""" return sum(n for n in data if n >= 128) def test3(data): """sum + listcomp""" return sum([n for n in data if n >= 128]) def test4(data): """decision bit -- bit mask and shift""" lst = [0, 0] for n in data: lst[(n & 0x80) >> 7] += n return lst[1] def test5(data): """decision bit -- division""" lst = [0, 0] for n in data: lst[n // 128] += n return lst[1] _lut = [0 if n < 128 else n for n in RANGE(256)] def test6(data): """lookup table""" total = 0 for n in data: total += _lut[n] return total def test7(data): """lookup table with sum()""" return sum(_lut[n] for n in data) test_functions = [v for k,v in globals().items() if k.startswith("test")] test_functions.sort(key=lambda x: x.__name__) correct = test0(_test_data) for fn in test_functions: name = fn.__name__ doc = fn.__doc__ if fn(_test_data) != correct: print("{}() not correct!!!".format(name)) s_call = "{}(_test_data)".format(name) s_import = "from __main__ import {},_test_data".format(name) t = timeit.timeit(s_call,s_import,number=NUM_REPEATS) print("{:7.03f}: {}".format(t, doc)) The results: python (327, 100000) 3.170: original way 2.211: better loop 2.378: sum + generator 2.188: sum + listcomp 5.321: decision bit -- bit mask and shift 4.977: decision bit -- division 2.937: lookup table 3.464: lookup table with sum() python3 (327, 100000) 5.786: original way 3.444: better loop 3.286: sum + generator 2.968: sum + listcomp 8.858: decision bit -- bit mask and shift 7.056: decision bit -- division 4.640: lookup table 4.783: lookup table with sum() pypy (327, 100000) 0.296: original way 0.312: better loop 1.932: sum + generator 1.011: sum + listcomp 0.172: decision bit -- bit mask and shift 0.613: decision bit -- division 0.140: lookup table 1.977: lookup table with sum() python (65536, 1000) 6.528: original way 4.661: better loop 4.974: sum + generator 4.150: sum + listcomp 10.971: decision bit -- bit mask and shift 10.218: decision bit -- division 6.052: lookup table 7.070: lookup table with sum() python3 (65536, 1000) 12.999: original way 7.618: better loop 6.826: sum + generator 5.587: sum + listcomp 19.326: decision bit -- bit mask and shift 14.917: decision bit -- division 9.779: lookup table 9.575: lookup table with sum() pypy (65536, 1000) 0.681: original way 0.884: better loop 2.640: sum + generator 2.642: sum + listcomp 0.316: decision bit -- bit mask and shift 1.573: decision bit -- division 0.280: lookup table 1.561: lookup table with sum() python (1048576, 100) 10.371: original way 7.065: better loop 7.910: sum + generator 6.579: sum + listcomp 17.583: decision bit -- bit mask and shift 15.426: decision bit -- division 9.285: lookup table 10.850: lookup table with sum() python3 (1048576, 100) 20.435: original way 11.221: better loop 10.162: sum + generator 8.981: sum + listcomp 29.108: decision bit -- bit mask and shift 23.626: decision bit -- division 14.706: lookup table 14.173: lookup table with sum() pypy (1048576, 100) 0.985: original way 0.926: better loop 5.462: sum + generator 6.623: sum + listcomp 0.527: decision bit -- bit mask and shift 2.334: decision bit -- division 0.481: lookup table 5.800: lookup table with sum() python (16777216, 10) 15.704: original way 11.331: better loop 11.995: sum + generator 13.787: sum + listcomp 28.527: decision bit -- bit mask and shift 25.204: decision bit -- division 15.349: lookup table 17.607: lookup table with sum() python3 (16777216, 10) 32.822: original way 18.530: better loop 16.339: sum + generator 14.999: sum + listcomp 47.755: decision bit -- bit mask and shift 38.930: decision bit -- division 23.704: lookup table 22.693: lookup table with sum() pypy (16777216, 10) 1.559: original way 2.234: better loop 6.586: sum + generator 10.931: sum + listcomp 0.817: decision bit -- bit mask and shift 3.714: decision bit -- division 0.752: lookup table 3.837: lookup table with sum()
#1251 Le 05/02/2012, à 19:35 chaoswizard Re : TVDownloader: télécharger les médias du net ! Voilà, la version 0.5 est arrivée dans le PPA ! Ubuntu ==> Debian ==> Archlinux Hors ligne #1252 Le 05/02/2012, à 20:08 ynad Re : TVDownloader: télécharger les médias du net ! @Greg_lattice comme f.x0 avec la même ligne de commande tout fonctionne sans blème... Hors ligne #1253 Le 06/02/2012, à 19:45 grandtoubab Re : TVDownloader: télécharger les médias du net ! bonsoir Un message d'erreur final alors que le téléchargement est "apparement" complet @ubuntu-desktop:~/Vidéos$ pluzzdl http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments [CRITICAL] PluzzDL.py Impossible de charger la vidéo @ubuntu-desktop:~/Vidéos$ ls -alrt faites* -rw-r--r-- 1 abc root 265409490 2012-02-06 18:03 faites-entrer-l-accuse.flv @ubuntu-desktop:~/Vidéos$ Malheureusement fichier incomplet, smplayer affiche une durée de 1h10mn 50 s mais la lecture s'arrête à 29 mn 11 s jusqu'à là tout va bien @ubuntu-desktop:~/Vidéos$ pluzzdl -f -b http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments [INFO ] PluzzDL.py Avancement : 1 % [INFO ] PluzzDL.py Avancement : 2 % [INFO ] PluzzDL.py Avancement : 3 % [INFO ] PluzzDL.py Avancement : 4 % [INFO ] PluzzDL.py Avancement : 5 % [INFO ] PluzzDL.py Avancement : 6 % [INFO ] PluzzDL.py Avancement : 7 % [INFO ] PluzzDL.py Avancement : 8 % [INFO ] PluzzDL.py Avancement : 9 % [INFO ] PluzzDL.py Avancement : 10 % [INFO ] PluzzDL.py Avancement : 11 % [INFO ] PluzzDL.py Avancement : 12 % [INFO ] PluzzDL.py Avancement : 13 % [INFO ] PluzzDL.py Avancement : 14 % [INFO ] PluzzDL.py Avancement : 15 % [INFO ] PluzzDL.py Avancement : 16 % [INFO ] PluzzDL.py Avancement : 17 % [INFO ] PluzzDL.py Avancement : 18 % [INFO ] PluzzDL.py Avancement : 19 % [INFO ] PluzzDL.py Avancement : 20 % [INFO ] PluzzDL.py Avancement : 21 % [INFO ] PluzzDL.py Avancement : 22 % [INFO ] PluzzDL.py Avancement : 23 % [INFO ] PluzzDL.py Avancement : 24 % [INFO ] PluzzDL.py Avancement : 25 % [INFO ] PluzzDL.py Avancement : 26 % [INFO ] PluzzDL.py Avancement : 27 % [INFO ] PluzzDL.py Avancement : 28 % [INFO ] PluzzDL.py Avancement : 29 % [INFO ] PluzzDL.py Avancement : 30 % [INFO ] PluzzDL.py Avancement : 31 % ça se gâte [INFO ] PluzzDL.py Avancement : 32 %[CRITICAL] PluzzDL.py Impossible de charger la vidéo Dernière modification par grandtoubab (Le 06/02/2012, à 20:25) 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 #1254 Le 06/02/2012, à 23:13 k3c Re : TVDownloader: télécharger les médias du net ! Bizarre, pour moi le même téléchargement est OK. Hors ligne #1255 Le 07/02/2012, à 16:30 bibichouchou Re : TVDownloader: télécharger les médias du net ! Bonjour à tous, 1/ j'arrive un peu tard mais voici mon grain de sel pour obtenir la progression. La taille finale du fichier est indiquée dans l'en-tête du fichier flv. On peut y accéder avec flvtool2 comme ceci: flvtool2 -P video_name.flv|grep filesize|grep -oE [0-9]\{1,\} On peut donc comparer la taille actuelle à la taille attendue pour obtenir la progression. Ce n'est pas complétement précis. D'après ce que j'ai remarqué, on peut s'attendre à des décalages de l'ordre de 1 ou 2%. J'imagine que faire appel à un programme tiers n'est pas très pythonique (corrigez-moi, je débute en python) mais je pense que l'on peut écrire un lecteur python des méta-données du flv. 2/ Ensuite, je voudrais savoir s'il est possible de rajouter une option "reprendre", dans le cas d'une connexion défaillante, histoire de ne pas télécharger encore et encore les mêmes fragments. Je ne pense pas que le programme le fasse actuellement et je ne sais pas si on peut le mettre en oeuvre facilement. Initialement, je m'étais écrit un code bash pour récupérer les émissions de pluzz, qui sauvegardait les fragments séparément et concaténait le tout à la fin, approche qui permet de savoir quel est le dernier fragment téléchargé. Le programme de chaoswizard concatène au fur et à mesure les fragments. 3/ est-ce que quelqu'un s'est penché sur le site de rattrapage de bfmtv et a pondu un joli programme ? je m'y suis cassé les dents. Bonne journée à tous ! Dernière modification par bibichouchou (Le 07/02/2012, à 16:50) Hors ligne #1256 Le 07/02/2012, à 16:32 Greg_lattice Re : TVDownloader: télécharger les médias du net ! @Greg_lattice comme f.x0 avec la même ligne de commande tout fonctionne sans blème... Merci je sais pourquoi ça ne fonctionne pas... C'est parce que je suis à l'étranger. Avant on pouvait accéder aux émissions de pluzz, mais apparement depuis 2semaines peu à peu on interdit aux expatriés l'accès à pluzz! Merci quand même!! Hors ligne #1257 Le 07/02/2012, à 18:28 grandtoubab Re : TVDownloader: télécharger les médias du net ! Bizarre, pour moi le même téléchargement est OK. Pire encore @ubuntu-desktop:~/Vidéos$ pluzzdl http://www.pluzz.fr/faites-entrer-l-accuse.html Traceback (most recent call last): File "/usr/share/pluzzdl/main.py", line 74, in <module> PluzzDL( args[ 0 ], options.fragments, options.proxy, options.progressbar ) File "/usr/share/pluzzdl/PluzzDL.py", line 70, in __init__ self.manifest = self.navigateur.getFichier( self.manifestURLToken ) File "/usr/share/pluzzdl/Navigateur.py", line 48, in getFichier page = self.urlOpener.open( requete, timeout = self.timeOut ) File "/usr/lib/python2.7/urllib2.py", line 400, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 513, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 438, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found @ubuntu-desktop:~/Vidéos$ python --version Python 2.7.2+ @ubuntu-desktop:~/Vidéos$ Dernière modification par grandtoubab (Le 07/02/2012, à 18:35) 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 #1258 Le 07/02/2012, à 18:42 k3c Re : TVDownloader: télécharger les médias du net ! J'ai la version 0.5 de pluzzdl, est-ce ton cas ? Hors ligne #1259 Le 07/02/2012, à 18:49 grandtoubab Re : TVDownloader: télécharger les médias du net ! J'ai la version 0.5 de pluzzdl, est-ce ton cas ? Clic sur l'image que j'ai posté et tu verras que oui. Mais je relance avec l'option -f et ca commence à télécharger (http://code.google.com/p/tvdownloader/wiki/pluzzdl) @ubuntu-desktop:~/Vidéos$ pluzzdl -f http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments 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 #1260 Le 07/02/2012, à 18:53 k3c Re : TVDownloader: télécharger les médias du net ! @ bibichouchou Pour 3) Récupérer les replay de BFM TV est faisable, vu que Captvty le fait. http://rectv.free.fr/viewforum.php?f=17 Je crois surtout que personne ne s'est penché dessus pour l'instant Hors ligne #1261 Le 07/02/2012, à 18:57 bibichouchou Re : TVDownloader: télécharger les médias du net ! @ k3c et oui j'avais bien vu, c'est pourquoi j'ai bon espoir pour un script pour linux. mais j'ai regardé et pour le coup, c'est hors de mes compétences... je lance une bouteille à la mer ! Hors ligne #1262 Le 07/02/2012, à 19:10 grandtoubab Re : TVDownloader: télécharger les médias du net ! k3c a écrit : J'ai la version 0.5 de pluzzdl, est-ce ton cas ? Clic sur l'image que j'ai posté et tu verras que oui. Mais je relance avec l'option -f et ca commence à télécharger (http://code.google.com/p/tvdownloader/wiki/pluzzdl)<metadata lang=CSV prob=0.07 /> @ubuntu-desktop:~/Vidéos$ pluzzdl -f http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments Et là le fichier est complet @ubuntu-desktop:~/Vidéos$ pluzzdl -f http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments [INFO ] PluzzDL.py Fin du téléchargement @ubuntu-desktop:~/Vidéos$ c'est quand même cool de regarder du flash sans entendre le PC ronfler à mort 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 #1263 Le 07/02/2012, à 20:19 k3c Re : TVDownloader: télécharger les médias du net ! @ bibichouchou Un des programmes de récupération de replays sous Windows (TVRR) s'arrête http://rectv.free.fr/viewtopic.php?f=6&t=358 C'est dommage qu'il ne passe pas en open source, et que tout ce code disparaisse... Hors ligne #1264 Le 08/02/2012, à 11:43 k3c Re : TVDownloader: télécharger les médias du net ! Concernant TV5mondeplus, en fait il y a 2 cas - les urls de TV5mondeplus "de base", qui se terminent par -6chiffres. Le fichier .mp4 est dans une balise appleStreamingUrl - les urls de TV5monde Afrique, Asie, Amérique du Sud..., qui se terminent par 5 chiffres. Le fichier .mp4 est dans une balise vidéoUrl d'un fichier .smil J'ai donc fait une nouvelle version de mon script, qui récupère aussi ce deuxième cas de figure. #!/usr/bin/env python # -*- coding:utf-8 -*- # version 0.3 par k3c from lxml import etree from lxml import objectify import subprocess, optparse, re from urllib2 import URLError, Request, urlopen import socket timeout = 10 # timeout en secondes socket.setdefaulttimeout(timeout) usage = "usage: python tv5 [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() # Vérification du nombre d'arguments if( len( args ) != 1 or args[ 0 ] == "" ): parser.print_help() parser.exit( 1 ) if args[0][-4:] == "?t=1": xargs[0] = args[0][:-4] id = re.findall('[0-9]{5}[0-9]?$',args[0]) #conversion string numérique id = ''.join(id) # les infos sur la vidéo sont accessibles là the_url = "".join('http://www.tv5mondeplus.com/video-xml/get/') + str(id) try: file = urlopen(the_url) except URLError, e: print e.code data = file.read() file.close() root = objectify.fromstring(data) for element in root.iter(): if element.tag == "permalink": titre = element.text tit = titre.split('/')[-1] # on enlève les 7 derniers caractères qui sont - et 6 chiffres pour le nom du fichier et on ajoute tv5_ au début tit = tit[:-6] tit = "tv5_"+tit+".wmv" # 2 cas, la video est sur la balise appleStreamingUrl, ou dans le .smil à # la vidéo est sur appleStreamingUrl if element.tag == "appleStreamingUrl": video = element.text # la vidéo est sur videoUrl, dans un .smil, que l'on va ouvrir # http://fr.wikipedia.org/wiki/Synchronized_Multimedia_Integration_Language if element.tag == "videoUrl": video = element.text try: # exemple de fichier .smil # <?xml version="1.0"?> # <!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd"> # <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> # <head> # <meta name="title" content="COURTS SEJOURS" /> # <meta name="httpBase" content="http://vodhdflash.tv5monde.com/" /> # <meta name="rtmpAuthBase" content="" /> # </head> # <body> # <switch id="tv5_catchup"> # <video src="tv5mondeplus/hq/3137682.mp4" system-bitrate="500000"/> # <video src="tv5mondeplus/bq/3137682.mp4" system-bitrate="300000"/> # </switch> # </body> # </smil> # on enleve la première ligne blanche, sinon le parsing xml se plante video = urlopen(video) video.readline() video = video.read() root = objectify.fromstring(video) # le début de l'emplacement de la vidéo est à httpBase, c'est normalement # http://vodhdflash.tv5monde.com/ for x in root.head.getchildren(): if x.get('name') == 'httpBase': content = x.get('content') #la suite de l'emplacement de la video est à video src, # et on prend la ligne avec le bit-rate le plus élevé # exemple de suite de l'emplacement, à concaténer # tv5mondeplus/hq/3137682.mp4 itc = root.body.switch.getchildren() url = itc.pop() for x in itc: if x.get('system-bitrate') > url.get('system-bitrate'): url = x url = url.get('src') except IOError, e: if hasattr(e, 'reason'): print 'Nous avons échoué à joindre le serveur.' print 'Raison: ', e.reason elif hasattr(e, 'code'): print 'Le serveur n\'a pu satisfaire la demande.' print 'Code d\' erreur : ', e.code args = ['/usr/bin/msdl', content + url , '-o', tit] app = subprocess.Popen(args=args, stdout=open('somefile', 'w')) Dernière modification par k3c (Le 08/02/2012, à 11:47) Hors ligne #1265 Le 08/02/2012, à 15:36 Babar21 Re : TVDownloader: télécharger les médias du net ! Merci pour le script TV5, k3C ! Hors ligne #1266 Le 08/02/2012, à 15:37 Zoulou.4556 Re : TVDownloader: télécharger les médias du net ! Bonjour, je fais un retour de l'utilisation de tvdownloader avec les erreurs suivante : Arte certaines émissions seulement FR Inter et Radio France rien du tout Pluzz rien du tout W9 Replay rien du tout pour le reste c'est ok voilà se que ça donne en console: zoulou@zoulou-Linux:~$ tvdownloader Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 842, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 719, in format return fmt.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 464, in format record.message = record.getMessage() File "/usr/lib/python2.7/logging/__init__.py", line 328, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting Logged from file APIPrive.py, line 253 Traceback (most recent call last): File "/usr/share/tvdownloader/APIPrive.py", line 251, in pluginRafraichir self.listePluginActif[nomPlugin].rafraichir() File "plugins/W9Replay.py", line 51, in rafraichir page = urllib.urlopen( self.urlFichierXML ) File "/usr/lib/python2.7/urllib.py", line 84, in urlopen return opener.open(url) File "/usr/lib/python2.7/urllib.py", line 205, in open return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py", line 342, in open_http h.endheaders(data) File "/usr/lib/python2.7/httplib.py", line 951, in endheaders self._send_output(message_body) File "/usr/lib/python2.7/httplib.py", line 811, in _send_output self.send(msg) File "/usr/lib/python2.7/httplib.py", line 773, in send self.connect() File "/usr/lib/python2.7/httplib.py", line 754, in connect self.timeout, self.source_address) File "/usr/lib/python2.7/socket.py", line 553, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno -2] Nom ou service inconnu ERROR Navigateur : timed out ERROR Navigateur : timed out ERROR Navigateur : timed out utilisation de tvdownloader sur ubuntu 11.04 64bits. bon courage pour la suite, merci pour vos développements et votre partage. Dernière modification par Zoulou.4556 (Le 08/02/2012, à 15:44) Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits Hors ligne #1267 Le 08/02/2012, à 16:02 k3c Re : TVDownloader: télécharger les médias du net ! @ Zoulou Pour récupérer les émissions de Pluzz, cela marche très bien, mais il faut utiliser PluzzDL 0.5, en attendant que cela soit à nouveau intégré dans TVDownloader. http://code.google.com/p/tvdownloader/wiki/pluzzdl Puis tu tapes, pour récupérer un Samantha par exemple $ pluzzdl -f http://www.pluzz.fr/samantha-oups-2012-02-07-20h15.html Je télécharge Missing sur W9replay, donc il y a au moins un replay qui fonctionne correctement sur cette chaîne. Est-ce que tu as essayé ce replay-là ? Pour Arte, je télécharge [HD] Son Jarocho de Veracruz, avec Son de Madera au Quai Branly mais effectivement il y a des choses qui ne fonctionnent pas. Je n'utilise jamais les radios, mais je vais regarder. Hors ligne #1268 Le 08/02/2012, à 16:05 Babar21 Re : TVDownloader: télécharger les médias du net ! Pour ce qui ne marche plus (pour l'instant) sur Arte dans TVDownloader, il y a Arte+7 recorder, qui ne fait que ça mais qui le fait bien. Hors ligne #1269 Le 08/02/2012, à 16:18 Zoulou.4556 Re : TVDownloader: télécharger les médias du net ! @k3c, je viens d'essayer avec PluzzDL ça fonctionne sans problème merci pour l'info. @Babar21, je l'utilise effectivement pour Arte, c'était surtout pour un retour que je l ai signalé. merci pour vos réponses. Dernière modification par Zoulou.4556 (Le 08/02/2012, à 16:19) Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits Hors ligne #1270 Le 08/02/2012, à 19:23 grandtoubab Re : TVDownloader: télécharger les médias du net ! Concernant TV5mondeplus, en fait il y a 2 cas Bord!!! j'ai pas de pot moi @ubuntu-desktop:~/Linux$ python k3c.py http://www.tv5mondeplusafrique.com/#serie_cinema_histoires_droles_et_droles_de_gens 404 Traceback (most recent call last): File "k3c.py", line 32, in <module> data = file.read() TypeError: descriptor 'read' of 'file' object needs an argument Par contre la Rama, je la récupère @ubuntu-desktop:~/Linux$ python k3c.py http://www.tv5mondeplus.com/video/08-02-2012/rama-yade-213995 download [ tv5_rama-yade-.wmv ] @ubuntu-desktop:~/Linux$ Host: [ 195.12.231.32:80 ] connected! DL: 3143308/2147483647 B -- 0% 87.6K/s ETA 06:09:5 DL: 39109792/39109792 B -- 100% 84.0K/s Complete finished!! FINISHED --00:07:46-- Donc y a un troisieme cas celui sans numéro à la fin Dernière modification par grandtoubab (Le 08/02/2012, à 19:50) 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 #1271 Le 08/02/2012, à 20:19 k3c Re : TVDownloader: télécharger les médias du net ! @ Grandtoubab Chic, un cas non géré ! Je regarde... Edit : en fait, sur tv5mondeplus.com, quand on clique sur mappemonde, - on a un certain nombre de reportages visibles sur la carte - on peut aussi sélectionner Afrique, Amérique du Sud, Australie... C'est ces cas que mon script est censé gérer, vu que je n'ai vu que des adresses html se terminant par - et 5 chiffres Dernière modification par k3c (Le 09/02/2012, à 11:18) Hors ligne #1272 Le 12/02/2012, à 16:25 coucou123 Re : TVDownloader: télécharger les médias du net ! Salut, je me permet un petit retour: Quand je télécharge certaines émissions sur M6replay, la barre de téléchargement reviens sans cesse à 0% (à peine passé le cap des 10%). De plsu lorsque le téléchargement est terminé, il s'avère que le fichier est incomplet. Mais sinon, c'est une excellent initiative ce logiciel, d'autant plus que je n'arrive plus à voir quoi que ce soit sur M6Replay ! Precise Pangolin 64bits Lucid Lynx 64bits Hors ligne #1273 Le 13/02/2012, à 09:00 k3c Re : TVDownloader: télécharger les médias du net ! @coucou123 Ca se produit avec quelles émissions sur M6 ? Hier j'ai téléchargé sans problème une série, puis un Turbo. Hors ligne #1274 Le 13/02/2012, à 15:32 coucou123 Re : TVDownloader: télécharger les médias du net ! oups, désolé, en fait il se trouve que l'émission était bien en entier, mais que c'était la barre de défilement de VLC qui n'allait pas jusqu'à la fin. Le fichier est peut-être légèrement corrompu, je ne sais pas... Par contre il est vrai que la barre de progression de téléchargement de TVDownloader bugue un peu. L'émission en question c'était Top Chef (qui dure 2h30), et la barre de progression de téléchargement revenait à zéro dès qu'elle dépassait 9%, ce qui fait qu'il était impossible de savoir quand le téléchargement allait se terminer. Mais sinon, ce logiciel est vraiment chouette. Il faudrait juste que l'on puisse ajouter soi-même des sites, ou alors que le choix s'agrandisse au fil du temps. Peut-être aussi qu'un outil pour signaler les plugins qui ne fonctionnent plus, ce serait pas mal. Merci pour ton boulot, c'est du bon boulot ! Precise Pangolin 64bits Lucid Lynx 64bits Hors ligne #1275 Le 13/02/2012, à 18:53 grandtoubab Re : TVDownloader: télécharger les médias du net ! @ Grandtoubab Chic, un cas non géré ! Je regarde... Edit : en fait, sur tv5mondeplus.com, quand on clique sur mappemonde, - on a un certain nombre de reportages visibles sur la carte - on peut aussi sélectionner Afrique, Amérique du Sud, Australie... C'est ces cas que mon script est censé gérer, vu que je n'ai vu que des adresses html se terminant par - et 5 chiffres Et donc pour le reste c'est foutu? 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
The other night I put (what I think are) the finishing touches of an Undo/Redo stack for Photobomb. This is the second time I've written an Undo/Redo stack, the first time being for the TextEditor Quidget. Neither time was I able to find much guidance for how to approach the problem. I handled it slightly differently each time. I thought I'd write up a blog post about how I approached Undo/Redo for Photobomb, in case it helps someone else out. Generally, the way I conceived the problem was to keep a list of actions that needed to be undone. When an action is undone, then that action needs to be added to a list of actions that can be redone. But what does it mean to store an action in code? I thought of 2 approaches: Keep a list of actions as functions along arguments to pass to those functions. Keep a list of "backups" for every change made to an object, and on redo swap out the backup for the actual object. List of Actions Approach I took the first approach back when I wrote TextEditor. It was easy to do because the only actions supported by Undo and Redo was that something could be added to the TextBuffer, or something could have been removed. So I very literally stored a list of functions and elements. So on a change, such as when text has been inserted, I store point at which the text was inserted, along with the inserted text: cmd = {"action":"delete","offset":iter.get_offset(),"text":text} self._add_undo(cmd) The _add_undo function merely ensures that the list does not grow beyond a defined maximum, and adds it to the undo list: def _add_undo(self, cmd): if self.undo_max is not None and len(self.undos) >= self.undo_max: del(self.undos[0]) self.undos.append(cmd) The heart of the __add_undo command was to extract the command to undo, and pass it along to _do_action(), and then add the return value of undo to redo stack. undo = self.undos[-1] redo = self._do_action(undo) self.redos.append(redo) del(self.undos[-1]) do_action, in turn read the type of action, did the specified action, and returned the opposite action so it could be used for redo. if action["action"] == "delete": self.get_buffer().delete(start_iter, end_iter) action["action"] = "insert" elif action["action"] == "insert": self.get_buffer().insert(start_iter, action["text"]) action["action"] = "delete" return action So by keeping a mapping of actions and their opposites, and by using a dictionary to store the information needed to undo or redo the action, this system worked well for simple case of simple text editor. List of Backup Approach Not surprisingly, when I approach this problem in Photobomb, I followed the same basic solution path. For example, I set up a list to store undo actions in. I then started storing a code for actions like I used for delete and insert in the text editor. However, I quickly ran into some problems. Photobomb is more complex then TextEditor, and GooCanvas is more complex than TextView/TextBuffer. For example, storing all the info needed for undoing and redoing a clipping path on an object required some more complex code than seemed right for the problem. So, I switched to the second approach. Here, I store a list of undos, but what I store in the list is objects. A "new" object, as in the object after the change, and the "old" object. Kind of like the backup. To store an undo in this system, I make a back up of the object, change it, and then add the undo: saved_item = self.back_up_item() self.selected_item.move(delta_x,delta_y) self.add_undo(self.selected_item, saved_item) Making the backup entailed duplicating the entailed not just making a copy, but removing the copy from the goocanvas, and storing the z-order. GooCanvas doesn't track z-order for you, so I had to track it myself. Every object on the GooCanvas suface derives from a subclass of the custom PhotobombItem and one of the built in GooCanvas types, such as goocanvas.Image). PhotobombItems have a duplicate function witch return a copy, and a remove function. So getting a copy was easy. def back_up_item(self, item=None): if item is None: item = self.selected_item copy = item.duplicate(True, False) copy.remove() index = self.z_order.index(item) self.z_order.insert(index+1,copy) return copy I quickly found that it is insufficient to simply store a pair of old and new objects for each undo. This is because an object can be modified twice in a row. And if you store the object itself, rather than a copy of the object, the undo stack will reference the object in whatever is it's current state, so undo can appear to weirdly go backward. For example if I make an item, call it O1 bigger, I'll store a copy of O1, call the copy O1.1, and O1 as the old and new items, respectively. Then if I make it bigger again, I store another copy of O1, call it O1.2, and O1 *again*. So undoing will go O1 is replaced by O1.2, which looks right, but then undo again and O1 will be replaced by O1.1. But oops, O1 was already replaced, so O1.1 appears, but O1.2 was never replaced. To guard against this, I looked backward through the undo stack to see where in the current undo stack the object appears last, and I take the current backup of the "old_item" and make that the "new_item" for the previous undo. So, for then making something bigger would store O1.1 and O1 again, but then making it bigger again, it would replace O1 with O1.2 as the "new_item" and then store O1.2 and O1 as the new_item at the top of the undo stack. So undo would replace O1 with O1.2, and then O1.2 with O1.1, and everything seems to work. That was a pretty long winded explanation for not that much code. Basically, I loop back through the undo stack and update the last occurrence of the object being added with the copy before going ahead and adding the objects to the stack. def add_undo(self, new_item, old_item): #ensure proper undos for multiple edits of the same object if len(self.undos) > 0: for item in self.undos[::-1]: if item["new_item"] is new_item: item["new_item"] = old_item break self.undos.append({"new_item":new_item, "old_item":old_item}) self.redos = [] Note that I also reset the redo stack whenever the undo stack is modified. So what does undo and redo do? They function in a very similar manner to the undo/redo functions in the text editor. First, they get they item from the top of the stack and stick it on the other stack. So for undo: undo = self.undos[-1] self.redos.append(undo) del(self.undos[-1]) Then they remove the new item, and restore the backup (assuming they both exist). If there is no backup, that means the item was just created, so removing the item is sufficient. Conversely, if there is no new item, then it means the item was deleted, so adding it back to the canvas is sufficient. Finally, the function has to position the new item in the z-order and then select the new item. if undo["new_item"] is not None: undo["new_item"].remove() if undo["old_item"] is not None: undo["old_item"].set_property("parent",self.__root) next_item = self._find_item_above(undo["old_item"]) if next_item is not None: #position in z-order undo["old_item"].lower(next_item) self.selected_item = undo["old_item"] self.__reset_selection() Redo does essentially the same thing, only removes old_items and restores new_items. There was about 100% code duplication between the undo and redo functions. However, I decided to keep the duplicate code in place because I was worried that if I have to go back and fix bugs in a year or so, I'd need the code to be crystal clear about what it did. I can always refactor into a common function later, but for now, I felt that the duplicated code was just easier to read and understand. Now, calling these functions is easy in cases where a menu item was used to change on object, as there was one and only one change to store in the undo stack. But sometimes it's not so easy. For example, Photobomb has what I call "Press and Hold Buttons". To make an item bigger, for example, you can use the Bigger menu item, or you can hold down the Bigger button until the selected object is the size that you want and release the button. The button emits a signal called "tick" every 100 milliseconds, which is bound to an action, in the case, the "self.bigger" function. This causes the item to get bigger many many times (about 10 times per second, in fact) but the user is going to think of it as one action to be undone. In order to handle this case, I created two signal handlers, one for the press event and one for the released signal of a button. All the Press and Hold buttons use these handlers. The press signal handler creates an immediate copy of the item, and then connects the tick and the released signals. Occasionally, the released handler gets called twice, which causes some confusion, so I track the tick signal to make sure that the released signal is only handled once. def pah_button_pressed(self, button, action): old_item = self.back_up_item() tick_signal_id = button.connect("tick",action) button.connect("released",self.pah_button_released, (tick_signal_id, old_item)) Then in the released signal, I add the new item and the old_item to the undo stack, assuming it hasn't been already. def pah_button_released(self, button, args): tick_signal_id, old_item = args #work around released signals being called multiple times if tick_signal_id in self.__disconnected_tick_signals: return self.__disconnected_tick_signals.append(tick_signal_id) button.disconnect(tick_signal_id) if self.selected_item is not None: self.add_undo(self.selected_item, old_item) Now only 1 undo is added when a Press and Hold Button is used. Another challenge to overcome in this system was handling the user changing selection by clicking on an item versus when the user clicked and dragged an item. The latter should be added to the undo stack, but not the former. Fortunately, this can be handled with a similar pattern. The mouse_down signal handler creates a copy of the item, and passes it to the mouse_up signal handler. old_item = self.back_up_item(clicked_item) self.__mouse_up_handler = self.__goo_canvas.connect("button_release_event",self.drag_stop, old_item) Then the drag_stop function checks if the item was actually moved before adding to the undo stack. If the item hasn't been moved, then the selection has simply changed. Finishing Touch One last finishing touch is to ensure that the undo and redo menu items are only sensitive if there is anything in the undo and/or redo stacks. Photobomb handles this by connecting to the activate signal of the edit menu, and then checking if there is anything in the undo and redo lists, and setting the sensitivity accordingly. def edit_menu_reveal(self, widget, data=None): active_undos = len(self.undos) > 0 active_redos = len(self.redos) > 0 self.builder.get_object("menuitem_undo").set_sensitive(active_undos) self.builder.get_object("menuitem_redo").set_sensitive(active_redos) There is a lot of ineractivity in photobomb, and this creates a bit of complexity in handling undo/redo. You can see all the code in context in the photobomb trunk . Read more
gtk Functions — miscellaneous functions gtk.AboutDialog Functions def gtk.about_dialog_set_email_hook(func, data) def gtk.about_dialog_set_url_hook(func, data) gtk.AccelGroup Functions def gtk.accelerator_valid(keyval, modifiers) def gtk.accelerator_parse(accelerator) def gtk.accelerator_name(accelerator_key, accelerator_mods) def gtk.accelerator_set_default_mod_mask(default_mod_mask) def gtk.accelerator_get_default_mod_mask() def gtk.accelerator_get_label(accelerator_key, accelerator_mods) def gtk.accel_groups_from_object(object) gtk.AccelMap Functions def gtk.accel_map_add_entry(accel_path, accel_key, accel_mods) def gtk.accel_map_lookup_entry(accel_path) def gtk.accel_map_change_entry(accel_path, accel_key, accel_mods, replace) def gtk.accel_map_foreach(foreach_func, data=None) def gtk.accel_map_foreach_unfiltered(foreach_func, data=None) def gtk.accel_map_get() def gtk.accel_map_load(file_name) def gtk.accel_map_save(file_name) def gtk.accel_map_load_fd(fd) def gtk.accel_map_save_fd(fd) def gtk.accel_map_lock_path(accel_path) def gtk.accel_map_unlock_path(accel_path) def gtk.accel_map_add_filter(filter_pattern) gtk.CellView Functions def gtk.cell_view_new_with_text(text) def gtk.cell_view_new_with_markup(markup) def gtk.cell_view_new_with_pixbuf(pixbuf) gtk.Clipboard Functions def gtk.clipboard_get() gtk.ColorSelection Functions def gtk.color_selection_palette_from_string(str) def gtk.color_selection_palette_to_string(colors) gtk.ComboBox Functions def gtk.combo_box_new_text() gtk.ComboBoxEntry Functions def gtk.combo_box_entry_new_text() gtk.ComboBoxText Functions def gtk.combo_box_text_new_with_entry() gtk.Container Functions def gtk.container_class_install_child_property(klass, property_id, pspec) def gtk.container_class_list_child_properties(klass) gtk.Dialog Functions def gtk.alternative_dialog_button_order(screen=None) gtk.Expander Functions def gtk.expander_new_with_mnemonic(label) gtk.IconFactory Functions def gtk.icon_factory_lookup_default(stock_id) gtk.IconSource Functions def gtk.icon_size_lookup(icon_size) def gtk.icon_size_lookup_for_settings(settings, icon_size) def gtk.icon_size_register(name, width, height) def gtk.icon_size_register_alias(alias, target) def gtk.icon_size_from_name(name) def gtk.icon_size_get_name(size) gtk.IconTheme Functions def gtk.icon_theme_get_default() def gtk.icon_theme_get_for_screen(screen) def gtk.icon_theme_add_builtin_icon(icon_name, size, pixbuf) gtk.Image Functions def gtk.image_new_from_stock(stock_id, size) def gtk.image_new_from_icon_set(icon_set, size) def gtk.image_new_from_animation(animation) def gtk.image_new_from_icon_name(icon_name, size) gtk.ItemFactory Functions def gtk.item_factory_from_widget(widget) def gtk.item_factory_path_from_widget(widget) gtk.LinkButton Functions def gtk.link_button_set_uri_hook(func, data=None) gtk.Object Functions def gtk.bindings_activate(object, keyval, modifiers) def gtk.bindings_activate_event(object, event) def gtk.binding_entry_add_signal(object, keyval, modifiers, signal_name, ...) def gtk.binding_entry_remove(class_type, keyval, modifiers) gtk.PaperSize Functions def gtk.paper_size_new_from_ppd(ppd_name, ppd_display_name, width, height) def gtk.paper_size_new_cutom(name, display_name, width, height, unit) def gtk.paper_size_get_default() gtk.Plug Functions def gtk.plug_new_for_display(display, socket_id) gtk.RcStyle Functions def gtk.rc_add_default_file(filename) def gtk.rc_set_default_files(filenames) def gtk.rc_get_default_files() def gtk.rc_get_style_by_paths(settings, widget_path, class_path, type) def gtk.rc_reparse_all_for_settings(settings, force_load) def gtk.rc_reset_styles(settings) def gtk.rc_parse(filename) def gtk.rc_parse_string(rc_string) def gtk.rc_reparse_all() def gtk.rc_find_module_in_path(module_file) def gtk.rc_get_theme_dir() def gtk.rc_get_module_dir() def gtk.rc_get_im_module_path() def gtk.rc_get_im_module_file() gtk.RecentManager Functions def gtk.recent_manager_get_default() def gtk.recent_manager_get_for_screen(screen) gtk.SelectionData Functions def gtk.selection_owner_set_for_display(display, widget, selection, time=0) def gtk.target_list_add_image_targets(list=None, info=0, writable=False) def gtk.target_list_add_text_targets(list=None, info=0) def gtk.target_list_add_uri_targets(list=None, info=0) gtk.Settings Functions def gtk.settings_get_default() def gtk.settings_get_for_screen(screen) gtk.StatusIcon Functions def gtk.status_icon_new_from_pixbuf(pixbuf) def gtk.status_icon_new_from_file(filename) def gtk.status_icon_new_from_stock(stock_id) def gtk.status_icon_new_from_icon_name(icon_name) def gtk.status_icon_position_menu(menu, statusicon) gtk.Tooltips Functions def gtk.tooltips_data_get(widget) gtk.TreeModel Functions def gtk.tree_row_reference_inserted(proxy, path) def gtk.tree_row_reference_deleted(proxy, path) gtk.Widget Functions def gtk.widget_push_colormap(cmap) def gtk.widget_push_composite_child() def gtk.widget_pop_composite_child() def gtk.widget_pop_colormap() def gtk.widget_get_default_style() def gtk.widget_set_default_colormap(colormap) def gtk.widget_get_default_colormap() def gtk.widget_get_default_visual() def gtk.widget_set_default_direction(dir) def gtk.widget_get_default_direction() def gtk.widget_class_list_style_properties(widget) def gtk.widget_class_install_style_property(widget, pspec) gtk.Window Functions def gtk.window_set_default_icon(icon) def gtk.window_set_default_icon_from_file(filename) def gtk.window_set_default_icon_list(...) def gtk.window_get_default_icon_list() def gtk.window_set_auto_startup_notification(setting) def gtk.window_list_toplevels() def gtk.window_set_default_icon_name(name) def gtk.stock_add(items) def gtk.stock_lookup(stock_id) def gtk.stock_list_ids() def gtk.check_version(required_major, required_minor, required_micro) def gtk.draw_insertion_cursor(widget, drawable, area, location, is_primary, direction, draw_arrow) def gtk.get_default_language() def gtk.events_pending() def gtk.main_do_event(event) def gtk.main() def gtk.main_level() def gtk.main_quit() def gtk.main_iteration(block) def gtk.main_iteration_do(block) def gtk.grab_get_current() def gtk.quit_add(level, func, ...) def gtk.quit_remove(quit_handler_id) def gtk.get_current_event() def gtk.get_current_event_state() def gtk.get_current_event_time() def gtk.init_check() def gtk.remove_log_handlers() def gtk.add_log_handlers() def gtk.set_interactive(interactive) def gtk.show_uri(screen, uri, timestamp) All PyGTK functions for the gtk module arelisted above categorized by class. Those functions associated with a classhave their descriptions included with the class reference. Those functionsthat are not associated with a specific class are described below. def gtk.check_version(required_major, required_minor, required_micro) the required major version number the required minor version number the required micro version number None if the underlyingGTK+ library is compatible or a string describing themismatch The gtk.check_version() function checks theunderlying GTK+ library version against the versionspecified by required_major, required_minorrequired_microNone; otherwise it returns a stringdescribing the mismatch. def gtk.draw_insertion_cursor(widget, drawable, area, location, is_primary, direction, draw_arrow) a gtk.Widget a gtk.gdk.Drawable the rectangle to which the output is clipped, orNone if the output should not be clipped the location to draw the cursor ( is ignored)location.width if True the cursor should be the primary cursor color. the direction of the cursor; either gtk.TEXT_DIR_LTR or gtk.TEXT_DIR_RTL if True draw a directional arrow on the cursor. Should be False unless the cursor is split. This function is available in PyGTK 2.4 and above. The gtk.draw_insertion_cursor() functiondraws a text caret on the gtk.gdk.Drawablespecified by drawable at the position specified by locationareaNone if the output should not beclipped. If is_primaryTrue thecursor should be the primary cursor color. direction def gtk.get_default_language() a pango.Languageobject for the default language The gtk.get_default_language() functionreturns a pango.Languagedescribing the default language. def gtk.events_pending() True if any events arepending The gtk.events_pending() function returnsTrue if any events are pending. This can be used toupdate the user interface and invoke timeouts etc. while doing some timeintensive computation. def gtk.main_do_event() a gtk.gdk.Event toprocess The gtk.main_do_event() function processesa single gtk.gdk.Event. Thisfunction is public only to allow filtering of events betweenGDK and GTK+. You will not usuallyneed to call this function directly. While you should not call this functiondirectly, you might want to know how exactly events are handled. So here iswhat this function does with the event: GDK) both events are thrown away. This is to avoid abacklog of (de-)highlighting widgets crossed by the pointer.INCR transaction. In that case it is passed togtk_selection_incr_event().gtk.get_current_event(). The event is sent to a widget. If a grab is active all events for widgets that are not in the contained in the grab widget are sent to the latter with a few exceptions: Another point of interest might be that all key eventsare first passed through the key snooper functions if there are any. Readthe description of gtk_key_snooper_install() if youneed this feature. def gtk.main() The gtk.main() function runs the main loopuntil the gtk.main_quit() function is called. You can nest calls to gtk.main().In that case the call to the gtk.main_quit() function will make the innermost invocation of the main loop return. def gtk.main_level() the nesting level of the current invocation of the main loop The gtk.main_level() function returns thecurrent nesting level of the main loop. The nesting level is increased bycalling the gtk.main() functionand reduced by calling the gtk.main_quit() function. def gtk.main_quit() The gtk.main_quit() function terminates thecurrent main loop level started by the most recent call to the gtk.main()function. The nesting level of the main loop is reduced by calling thisfunction. def gtk.main_iteration(block=True) if True block if no eventsare pending True if the gtk.main_quit() function has been called for the innermost main loop. The gtk.main_iteration() function runs asingle iteration of the mainloop. If no events are waiting to be processedPyGTK will block until the next event is noticed if block is True. This function isidentical to the gtk.main_iteration_do() function. def gtk.main_iteration_do(block=True) if True block if no eventsare pending True if the gtk.main_quit() function has been called for the innermost main loop. The gtk.main_iteration_do() function runs asingle iteration of the main loop. If block is True block until an event occurs. This function isidentical to the gtk.main_iteration() function. def gtk.grab_get_current() the gtk.Widget that hasthe grab currently or None if no grab isactive The gtk.grab_get_current() function returnsthe gtk.Widgetthat has the grab or None if no grab is active. def gtk.quit_add(level, func, ...) the level at which termination shall be called. You can pass 0 here to havefunc run at the termination of the current mainloop.func the function to call - it should return 0 to be removed from the list of quit handlers optional parameter(s) to be passed tofunc a handle for this quit handler (you need thisfor the gtk.quit_remove() function). The gtk.quit_add() function registers afunction specified by func to be called when thespecified main loop levelfuncgtk.quit_remove() function. def gtk.quit_remove(quit_handler_id) the ID of a quit handler The gtk.quit_remove() function removes thequit handler specified by quit_handler_id from thelist of quit handlers. def gtk.get_current_event() a copy of the current event orNone This function is available in PyGTK 2.6 and above. The gtk.get_current_event() functionreturns a copy of the event currently being processed by GTK+. For example,if you get a "clicked" signal from gtk.Button, thecurrent event will be the GdkEventButton that triggered the "clicked"signal. If there is no current event, the function returnsNone. def gtk.get_current_event_state() the state of the current event if any orNone if there is no current event orstate This function is available in PyGTK 2.6 and above. The gtk.get_current_event_state() functionreturns the state of the current event or None if thereis no current event or state. def gtk.get_current_event_time() the timestamp of the current event or 0L The gtk.get_current_event_time() functionreturns the timestamp from the current event or 0L if there is no currentevent. def gtk.init_check() True if GTK has been successfully initialized The gtk.init_check() function tries to initialize GTK and returns True if successful. def gtk.remove_log_handlers() This function is available in PyGTK 2.10 and above. The gtk.remove_log_handlers() function removes the default PyGTK log handlers, def gtk.add_log_handlers() This function is available in PyGTK 2.10 and above. The gtk.add_log_handlers() function installs the default PyGTK log handlers, def gtk.set_interactive(interactive) If True interactive usage is enabled This function is available in PyGTK 2.16 and above. The gtk.set_interactive() function can be used toenable or disable interactive usage of PyGTK. By default, interactive usage is switchedon when importing gtk. You can then use PyGTK from the Python command prompt and see theresults immediately without having to call gtk.main(). def show_uri(screen, uri, timestamp) A gtk.gdk.Screen to show the uri on or None for the default screen. the uri to show. a timestamp to prevent focus stealing. This function is available in PyGTK 2.14 and above. The show_uri() function is a convenience function for launching the default application to show the uri. The uri must be of a form understood by GIO. Typical examples are: file:///home/gnome/pict.jpg http://www.gnome.org mailto:me@gnome.org Ideally the timestamp is taken from the event triggering the gtk.show_uri() call. If timestamp is not known you can take gtk.gdk.CURRENT_TIME. This function can be used as a replacement for gnome_vfs_url_show() and gnome_url_show().
What is an algorithm to get the nth element of a rectangular tiled spiral? Here's a short and sweet answer using just simple math in pseudocode. No conditionals and no iteration. Given intRoot=int(sqrt(tileNum)); x=(round(intRoot/2)*(-1^(intRoot+1)))+((-1^(intRoot+1))*(((intRoot*(intRoot+1))-tileNum)-abs((intRoot*(intRoot+1))-tileNum))/2); y=(round(intRoot/2)*(-1^intRoot))+((-1^(intRoot+1))*(((intRoot*(intRoot+1))-tileNum)+abs((intRoot*(intRoot+1))-tileNum))/2); Here's a fiddle to see it in action. Similar questions exist already... See my non-looping version. You may need to swap and/or negate X/Y coordinates and change the There's also more canonical looping versions. Here's my solution in javascript using inverse sum of 8 and edge numbering Complexity : O(1) no iteration loop function spiral(n) { // given n an index in the squared spiral // p the sum of point in inner square // a the position on the current square // n = p + a var r = Math.floor((Math.sqrt(n + 1) - 1) / 2) + 1; // compute radius : inverse arithmetic sum of 8+16+24+...= var p = (8 * r * (r - 1)) / 2; // compute total point on radius -1 : arithmetic sum of 8+16+24+... en = r * 2; // points by edge var a = (1 + n - p) % (r * 8); // compute de position and shift it so the first is (-r,-r) but (-r+1,-r) // so square can connect var pos = [0, 0]; switch (Math.floor(a / (r * 2))) { // find the face : 0 top, 1 right, 2, bottom, 3 left case 0: { pos[0] = a - r; pos[1] = -r; } break; case 1: { pos[0] = r; pos[1] = (a % en) - r; } break; case 2: { pos[0] = r - (a %en); pos[1] = r; } break; case 3: { pos[0] = -r; pos[1] = r - (a % en); } break; } console.log("n : ", n, " r : ", r, " p : ", p, " a : ", a, " --> ", pos); return pos; } Demo : Fiddle First, find out which ring your desired element is in (hint: until you get to the outer ring, your spiral is made up of nested squares), then which side (of the 4) it is on, then you're just left with its position on that side. As nobody answered, there is a solution: def square_spiral(total_steps): position = (0,0) direction = (1,0) turn_steps = [floor(((x+2)**2)/4) for x in range(n+2)] for step in range(total_steps): if (step in turn_steps): direction = (-direction[1],direction[0]) position = tuple(a+b for a,b in zip(position,direction)) return position This simulates a walk through the desired path. You start at position (0,0), walk 1 step to the right, 1 step down, 3 steps left, 3 steps up, and so on, following the spiral. To code this, notice that we are changing our direction on steps of numbers 1, 2, 4, 6, 9, 12, 16, 20 and so on. https://oeis.org/ reveals this is the quarter-square integer sequence. So all we need is a loop where each iteration simulates a step, adding the direction to the position and turning it 90º when the step count is part of the sequence.
Not TeX-related, but since you inquired about a Python script... #!/usr/bin/env python # Generates QR code from given text using Google charts API. import urllib2 import sys # change those to your heart's content. See http://code.google.com/apis/chart/docs/gallery/qr_codes.html for more info ENCODING='utf-8' IMAGE_WIDTH=200 IMAGE_HEIGHT=200 def make_magic_url(text): # spaces in the text should be replaced with "+". probably other control symbols need to be handled in special way. return 'http://chart.apis.google.com/chart?chs=%dx%d&cht=qr&choe=%s&chl=%s' %(IMAGE_WIDTH, IMAGE_HEIGHT, ENCODING, text.replace(" ", "+")) def makeQR(text, dest): print make_magic_url(text) myfig=urllib2.urlopen(make_magic_url(text)) output=open(dest, 'wb') output.write(myfig.read()) output.close() text=sys.argv[1] dest=sys.argv[2] makeQR(text, dest) Save this as fetchqr.py, or some such. Usage is simple: python fetchqr.py 'http://tex.stackexchange.com/questions/1429/latex-package-to-generate-qr-codes' '/tmp/myfig.png' And you'd get something like: This works on Python 2.6 under Windows, but I imagine it shouldn't be a a problem with older Python versions. Not sure about Python 3.x though. If you're using something like a Makefile to run your project, then you should be able to generate those on the fly as needed -- maybe create a file with stuff to QR-code, then run all the entries through the grinder in one go. The code is free for the taking.
Linux has come a long way in the last 10 years. At that time, if you were looking through the main audio and music applications on other operating systems, you would have struggled to find comparable, fully developed, apps on Linux. Nowadays, while no one would say the job was done, they could point to an assortment of high-quality applications that are getting real jobs done. Having said that, there's still work to do on existing apps and the whole future ahead for those who want to try to get the future started now; which is to say that there is no fundamental law stating that there shall only be sequencers, loopers, and whatever. Whether designing the future or just having a play with sounds, Linux is a nice place to get started for practical as well as possible idealogical reasons. The practical reasons have to do with the variety of APIs available to let you get into Linux audio programming in a way that suits your ambitions and skills. Once you've acquired some skills, you could join an existing development team for an app you like, or head off into the wilderness hacking your own trail. One side issue here is the business model. This is of interest to anyone hoping that what might start as an enjoyable hobby could have the possibility of being a job as well. First of all, there really aren't that many jobs in this field, and there still aren't that many if you include all the commercial audio software houses. They are there though. Academia is a similarly small area, but another possibility. One thing is for sure, project donations will not pay the rent. Consulting work gained as a result of your project work might do so, though. And if you come up with the next Big Thing, well, that's a different story. Before we head into some specifics, and if you're unfamiliar with this general area, there are a couple of podcast chats with Fernando Lopez-Lescano of CCRMA at Stanford and another with Paul Davis of the Ardour project that cover a wide range of topics under this heading. The podcasts are available at Technical University Berlin and Mstation.org. Now, let's have a look at what we're trying to do and the main options available for doing it. The three main things to do are capturing (recording) audio, replaying it, and altering it. All of this comes under the heading of Digital Signal Processing (DSP). We'll be looking at the first two options: capturing and replaying. What we want to do is talk to the sound card in the computer, tell it what to do, what sort of arrangement the data should have (bearing in mind the card's capabilities), and then store it somewhere. This could be broadly shown as the following (from the Paul Davis tutorial on ALSA programming): open_the_device(); set_the_parameters_of_the_device(); while (!done) { /* one or both of these */ receive_audio_data_from_the_device(); deliver_audio_data_to_the_device(); } close the device A look at the ALSA sound card matrix is a good starting point for learning about cards, but in what comes below, you frequently don't need to be that far into the machine (depending on what you want to accomplish). Now, let's have a look at the ways we might get something happening. Open Sound System (OSS), from 4Front Technologies, was the only supplier of sound card drivers for Linux until 1997 or '98. In those days, there was a free driver set and a commercial set, which offered a lot more. Now, OSS drivers are available for free for non-commercial use. The drivers are also open source since June 2007. ALSA (Advanced Linux Sound Architecture) now provides the kernel drivers, and OSS use is deprecated, but there may be circumstances where OSS is useful, including doing work on an existing OSS application. Hannu Savolainen, the man behind OSS who was originally responsible for Linux sound support, writes a blog that provides a fascinating backlog to all of this. He maintains that lots of developers continue to use OSS because they don't like the ALSA API and don't need its added features (and complication). However, there are easier ways into ALSA, which we'll get to in the next section. If you've ever seen a jokey reference to cat somefile > /dev/dsp then you've seen an OSS interface and, by the way, the results of doing just that with, say, a text file can be extremely ugly. The OSS API consists of Posix/Unix system calls: open(), close(), read(), write(), ioctl(), select(), poll(), and mmap(). The following is a simple audio playback program from the OSS documentation that plays a continuous 1 kHz sine wave. The well-documented code, first of all, gives an example of synthesis and then goes on to set parameters, open and set the audio device, and finally to write the data to the device. #include #include #include #include #include int fd_out; int sample_rate = 48000; static void write_sinewave (void) { /* This routine is a typical example of application routine that produces audio signal using synthesis. This is actually a very basic "wave table" algorithm (btw). It uses precomputed sine function values for a complete cycle of a sine function. This is much faster than calling the sin() function once for each sample. In other applications this routine can simply be replaced by whatever the application needs to do. */ static unsigned int phase = 0; /* Phase of the sine wave */ unsigned int p; int i; short buf[1024]; /* 1024 samples/write is a safe choice */ int outsz = sizeof (buf) / 2; static int sinebuf[48] = { 0, 4276, 8480, 12539, 16383, 19947, 23169, 25995, 28377, 30272, 31650, 32486, 32767, 32486, 31650, 30272, 28377, 25995, 23169, 19947, 16383, 12539, 8480, 4276, 0, -4276, -8480, -12539, -16383, -19947, -23169, -25995, -28377, -30272, -31650, -32486, -32767, -32486, -31650, -30272, -28377, -25995, -23169, -19947, -16383, -12539, -8480, -4276 }; for (i = 0; i < outsz; i++) { /* The sinebuf[] table was computed for 48000 Hz. We will use simple sample rate compensation. We must prevent the phase variable from growing too large because that would cause cause arihmetic overflows after certain time. This kind of error posibilities must be identified when writing audio programs that could be running for hours or even months or years without interruption. When computing (say) 192000 samples each second the 32 bit integer range may get overflown very quickly. The number of samples played at 192 kHz will cause an overflow after about 6 hours. */ p = (phase * sample_rate) / 48000; phase = (phase + 1) % 4800; buf[i] = sinebuf[p % 48]; } /* Proper error checking must be done when using write. It's also important to report the error code returned by the system. */ if (write (fd_out, buf, sizeof (buf)) != sizeof (buf)) { perror ("Audio write"); exit (-1); } } /* The open_audio_device opens the audio device and initializes it for the required mode. */ static int open_audio_device (char *name, int mode) { int tmp, fd; if ((fd = open (name, mode, 0)) == -1) { perror (name); exit (-1); } /* Setup the device. Note that it's important to set the sample format, number of channels and sample rate exactly in this order. Some devices depend on the order. */ /* Set the sample format */ tmp = AFMT_S16_NE; /* Native 16 bits */ if (ioctl (fd, SNDCTL_DSP_SETFMT, &tmp) == -1) { perror ("SNDCTL_DSP_SETFMT"); exit (-1); } if (tmp != AFMT_S16_NE) { fprintf (stderr, "The device doesn't support the 16 bit sample format.\n"); exit (-1); } /* Set the number of channels */ tmp = 1; if (ioctl (fd, SNDCTL_DSP_CHANNELS, &tmp) == -1) { perror ("SNDCTL_DSP_CHANNELS"); exit (-1); } if (tmp != 1) { fprintf (stderr, "The device doesn't support mono mode.\n"); exit (-1); } /* Set the sample rate */ sample_rate = 48000; if (ioctl (fd, SNDCTL_DSP_SPEED, &sample_rate) == -1) { perror ("SNDCTL_DSP_SPEED"); exit (-1); } /* No need for error checking because we will automatically adjust the signal based on the actual sample rate. However most application must check the value of sample_rate and compare it to the requested rate. Small differences between the rates (10% or less) are normal and the applications should usually tolerate them. However larger differences may cause annoying pitch problems (Mickey Mouse). */ return fd; } int main (int argc, char *argv[]) { /* Use /dev/dsp as the default device because the system administrator may select the device using the ossctl program or some other methods */ char *name_out = "/dev/dsp"; /* It's recommended to provide some method for selecting some other device than the default. We use command line argument but in some cases an environment variable or some configuration file setting may be better. */ if (argc > 1) name_out = argv[1]; /* It's mandatory to use O_WRONLY in programs that do only playback. Other modes may cause increased resource (memory) usage in the driver. It may also prevent other applications from using the same device for recording at the same time. */ fd_out = open_audio_device (name_out, O_WRONLY); while (1) write_sinewave (); exit (0); } Copyright (C) 4Front Technologies, 2002-2004. Released under GPLv2/CDDL. ALSA was started to fill a perceived gap for free, open source sound drivers. In 1998, for example, the OSS free drivers would not allow you to use full duplex on your sound card (being able to monitor a prerecorded track as well as what you're recording). Also, the OSS drivers at the time would not address the more sophisticated parts of the higher-end cards like the RME Hammerfall which were becoming available. A thought at the time was that OSS was fine for users who just wanted to play CDs or MP3s, and ALSA was what you needed if you were going to do serious studio work. The ALSA API could thus be said to be lower-level than OSS although in both APIs there are both generic and specific ways to talk to hardware; and the specific way (mmap in OSS, hw in ALSA) is more verbose and requires detailed knowledge of the card--which makes sense if you're trying, for example, to use specific features of a high-end audio card (to see if a specific card is supported see the sound card matrix mentioned earlier). Bear in mind also that these APIs enable the machine to talk to the sound card via the drivers; the generic way of talking to them isn't magic, it's just addressing information already contained in the drivers. Below is an example of a minimal, interrupt-driven program from the Paul Davis Tutorial on the ALSA API.'This program opens an audio interface for playback, configures it for stereo, 16 bit, 44. 1kHz, interleaved conventional read/write access. It then waits till the interface is ready for playback data, and delivers random data to it at that time. This design allows your program to be easily ported to systems that rely on a callback-driven mechanism, such as JACK, LADSPA, CoreAudio, VST, and many others. #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <poll.h> #include &ltalsa/asoundlib.h> snd_pcm_t *playback_handle; short buf[4096]; int playback_callback (snd_pcm_sframes_t nframes) { int err; printf ("playback callback called with %u frames\n", nframes); /* ... fill buf with data ... */ if ((err = snd_pcm_writei (playback_handle, buf, nframes)) < 0) { fprintf (stderr, "write failed (%s)\n", snd_strerror (err)); } return err; } main (int argc, char *argv[]) { snd_pcm_hw_params_t *hw_params; snd_pcm_sw_params_t *sw_params; snd_pcm_sframes_t frames_to_deliver; int nfds; int err; struct pollfd *pfds; if ((err = snd_pcm_open (&playback_handle, argv[1], SND_PCM_STREAM_PLAYBACK, 0)) < 0) { fprintf (stderr, "cannot open audio device %s (%s)\n", argv[1], snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params_malloc (&hw_params)) < 0) { fprintf (stderr, "cannot allocate hardware parameter structure (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params_any (playback_handle, hw_params)) < 0) { fprintf (stderr, "cannot initialize hardware parameter structure (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params_set_access (playback_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { fprintf (stderr, "cannot set access type (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params_set_format (playback_handle, hw_params, SND_PCM_FORMAT_S16_LE)) < 0) { fprintf (stderr, "cannot set sample format (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params_set_rate_near (playback_handle, hw_params, 44100, 0)) < 0) { fprintf (stderr, "cannot set sample rate (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params_set_channels (playback_handle, hw_params, 2)) < 0) { fprintf (stderr, "cannot set channel count (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_hw_params (playback_handle, hw_params)) < 0) { fprintf (stderr, "cannot set parameters (%s)\n", snd_strerror (err)); exit (1); } snd_pcm_hw_params_free (hw_params); /* tell ALSA to wake us up whenever 4096 or more frames of playback data can be delivered. Also, tell ALSA that we'll start the device ourselves. */ if ((err = snd_pcm_sw_params_malloc (&sw_params)) < 0) { fprintf (stderr, "cannot allocate software parameters structure (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_sw_params_current (playback_handle, sw_params)) < 0) { fprintf (stderr, "cannot initialize software parameters structure (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_sw_params_set_avail_min (playback_handle, sw_params, 4096)) < 0) { fprintf (stderr, "cannot set minimum available count (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_sw_params_set_start_threshold (playback_handle, sw_params, 0U)) < 0) { fprintf (stderr, "cannot set start mode (%s)\n", snd_strerror (err)); exit (1); } if ((err = snd_pcm_sw_params (playback_handle, sw_params)) < 0) { fprintf (stderr, "cannot set software parameters (%s)\n", snd_strerror (err)); exit (1); } /* the interface will interrupt the kernel every 4096 frames, and ALSA will wake up this program very soon after that. */ if ((err = snd_pcm_prepare (playback_handle)) < 0) { fprintf (stderr, "cannot prepare audio interface for use (%s)\n", snd_strerror (err)); exit (1); } while (1) { /* wait till the interface is ready for data, or 1 second has elapsed. */ if ((err = snd_pcm_wait (playback_handle, 1000)) < 0) { fprintf (stderr, "poll failed (%s)\n", strerror (errno)); break; } /* find out how much space is available for playback data */ if ((frames_to_deliver = snd_pcm_avail_update (playback_handle)) < 0) { if (frames_to_deliver == -EPIPE) { fprintf (stderr, "an xrun occured\n"); break; } else { fprintf (stderr, "unknown ALSA avail update return value (%d)\n", frames_to_deliver); break; } } frames_to_deliver = frames_to_deliver > 4096 ? 4096 : frames_to_deliver; /* deliver the data */ if (playback_callback (frames_to_deliver) != frames_to_deliver) { fprintf (stderr, "playback callback failed\n"); break; } } snd_pcm_close (playback_handle); exit (0); } In the example after this one, Paul goes on to talk about full-duplex, or combining both capture and playback to achieve what we talked about a little earlier. Achieving this by combining ordinary capture and playback is, in his opinion, deeply flawed, and interupts are the way to go with this. However, doing it this way is complex and he recommends JACK. If you listened to the podcast chat with Paul Davis, you'll have caught me saying something like: What do you think is the best way into Linux Audio programming, ALSA? And him saying that, actually, JACK would usually be the best way to go, for the reason that there's a higher level of abstraction, so dealing with the sound card stuff is easier and requires less code. JACK Audio Connection Kit was put together by Paul Davis and others from the Linux Audio Dev mailing list. The primary ideas of the thing are to allow audio apps on POSIX-compliant operating systems (e.g., Linux, BSD, Mac OS X) to interchange data while running, and also to provide a higher level of abstraction so that developers can concentrate more on the core functionality of their programs. An added advantage is that porting from Linux to Mac OS X is trivial if you're using X11 or it's a command line app. Here is a simple client that shows the basic features of JACK. The typical steps as listed on the JACK site are: jack_client_open() to connect to the JACK server.jack.h, which is the only call made in the following example (from this LXR project page on SourceForge). Needless to say, a thorough study of this in conjunction with existing code (code reuse!) is a good place to start. /** @file simple_client.c * * @brief This is very simple client that demonstrates the basic * features of JACK as they would be used by many applications. */ #include #include #include #include #include #include jack_port_t *input_port; jack_port_t *output_port; /** * The process callback for this JACK application. * It is called by JACK at the appropriate times. */ int process (jack_nframes_t nframes, void *arg) { jack_default_audio_sample_t *out = (jack_default_audio_sample_t *) jack_port_get_buffer (output_port, nframes); jack_default_audio_sample_t *in = (jack_default_audio_sample_t *) jack_port_get_buffer (input_port, nframes); memcpy (out, in, sizeof (jack_default_audio_sample_t) * nframes); return 0; } /** * This is the shutdown callback for this JACK application. * It is called by JACK if the server ever shuts down or * decides to disconnect the client. */ void jack_shutdown (void *arg) { exit (1); } int main (int argc, char *argv[]) { jack_client_t *client; const char **ports; if (argc < 2) { fprintf (stderr, "usage: jack_simple_client \n"); return 1; } /* try to become a client of the JACK server */ if ((client = jack_client_new (argv[1])) == 0) { fprintf (stderr, "jack server not running?\n"); return 1; } /* tell the JACK server to call `process()' whenever there is work to be done. */ jack_set_process_callback (client, process, 0); /* tell the JACK server to call `jack_shutdown()' if it ever shuts down, either entirely, or if it just decides to stop calling us. */ jack_on_shutdown (client, jack_shutdown, 0); /* display the current sample rate. */ printf ("engine sample rate: %" PRIu32 "\n", jack_get_sample_rate (client)); /* create two ports */ input_port = jack_port_register (client, "input", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); output_port = jack_port_register (client, "output", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); /* tell the JACK server that we are ready to roll */ if (jack_activate (client)) { fprintf (stderr, "cannot activate client"); return 1; } /* connect the ports. Note: you can't do this before the client is activated, because we can't allow connections to be made to clients that aren't running. */ if ((ports = jack_get_ports (client, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == NULL) { fprintf(stderr, "Cannot find any physical capture ports\n"); exit(1); } if (jack_connect (client, ports[0], jack_port_name (input_port))) { fprintf (stderr, "cannot connect input ports\n"); } free (ports); if ((ports = jack_get_ports (client, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == NULL) { fprintf(stderr, "Cannot find any physical playback ports\n"); exit(1); } if (jack_connect (client, jack_port_name (output_port), ports[0])) { fprintf (stderr, "cannot connect output ports\n"); } free (ports); /* Since this is just a toy, run for a few seconds, then finish */ sleep (10); jack_client_close (client); exit (0); } Even higher level than JACK is the idea of using the Python bindings for Gstreamer, or the PyAudio bindings for PortAudio, a cross-platform audio library. Here is an example from the PyAudio docs. We import the audio libraries first and then sys which enables us to read and write files. Then we do what we've done in every example, which is to set the format of the audio and the audio device. We open a stream, grab the stuff, and then save it. """ Record a few seconds of audio and save to a WAVE file. """ import pyaudio import wave import sys chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 5 WAVE_OUTPUT_FILENAME = "output.wav" p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) print "* recording" all = [] for i in range(0, RATE / chunk * RECORD_SECONDS): data = stream.read(chunk) all.append(data) print "* done recording" stream.close() p.terminate() # write data to WAVE file data = ''.join(all) wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(data) wf.close() Note how minimal this code is. There is no GUI, of course, so that helps as well. A good introduction to Gstreamer is Jono Bacon's article that describes the workings of Gstreamer and the PyGst bindings. Gstreamer offers quite a lot of creative possibilities and, unlike ESD, offers the possibility of having more than one audio stream playing at one time, amongst many other features. Below is an example of code from the PyGst docs of a simple audio player. We grab the sys, windowing, and pygst stuff, set up the window and the player, and away we go. Note that some implementations, particularly for small devices, are missing crucial bits. For example, I was interested to do a command line version for a Nokia 770 to play loops and wasn't able to. #!/usr/bin/env python import sys, os, os.path import pygtk, gtk, gobject import pygst pygst.require("0.10") import gst class GTK_Main: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("Audio-Player") window.set_default_size(400, 300) window.connect("destroy", gtk.main_quit, "WM destroy") vbox = gtk.VBox() window.add(vbox) self.entry = gtk.Entry() vbox.pack_start(self.entry, False, True) self.button = gtk.Button("Start") self.button.connect("clicked", self.start_stop) vbox.add(self.button) window.show_all() self.player = gst.element_factory_make("playbin", "player") fakesink = gst.element_factory_make('fakesink', "my-fakesink") self.player.set_property("video-sink", fakesink) bus = self.player.get_bus() bus.add_signal_watch() bus.connect('message', self.on_message) def start_stop(self, w): if self.button.get_label() == "Start": filepath = self.entry.get_text() if os.path.exists(filepath): self.button.set_label("Stop") self.player.set_property('uri', "file://" + filepath) self.player.set_state(gst.STATE_PLAYING) else: self.player.set_state(gst.STATE_NULL) self.button.set_label("Start") def on_message(self, bus, message): t = message.type if t == gst.MESSAGE_EOS: self.player.set_state(gst.STATE_NULL) self.button.set_label("Start") elif t == gst.MESSAGE_ERROR: self.player.set_state(gst.STATE_NULL) self.button.set_label("Start") gtk.gdk.threads_init() GTK_Main() gtk.main() Here we actually have a GUI, but you can see the amount of code needed is still relatively small compared to what would be required with some lower-level language. Which way you might go to get into Linux Audio depends on what you'd like to achieve. If you're planning to just have some fun while learning something, then wherever you start will be OK. If the fun leads to ideas, then you'll soon figure out whether you need to be deeper into the machine or whether you just need to be sketching on the surface. Just bear in mind that the higher the level you're on, the more you're bound by what other people think about how things should be. This is mostly good in terms of ease and implementation time, but could be bad in terms of constricted horizons. A good mailing list to join if you get serious is the Linux Audio Dev list, which describes itself like this: "The Linux Audio Developers (LAD) list is dedicated to sound architecture and application development for the Linux Operating System. With its proven stability and scalability, it is a perfect foundation for the handling and processing of large amounts of audio data. Our goal is to encourage widespread code re-use and cooperation, and to provide a common forum for all audio related software projects and an exchange point for a number of other special-interest mailing lists." The archives of this list can also be useful for answering questions, as can using the likes of krugle.com or Google's Codesearch. At this point, you might say to yourself, well, actually, what I really want to do is make noises or non-standard kinds of music. In that case you could have a look at Csound or Pure Data. You could also look into the synthesis and DSP side of programming, which is something we haven't looked at in this article. John Littler is chief gopher for Mstation.org. Return to LinuxDevCenter.com. Copyright © 2009 O'Reilly Media, Inc.
Please help (I know that it's a silly question): I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once? Convert to a set then back again: list(set(d)) If order matters, you can pass the values through a dict that remembers the original indices. This approach, while expressible as a single expression, is considerably more complicated: [x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())] Of course, you don't have to use comprehensions. For this problem, a fairly simple solution is available: a = [] for x in d: if x not in a: a.append(x) Note that both the order-preserving solutions assume that you want to keep the first occurrence of each duplicated element. To d = [x for x in d if d.count(x) == 1] For the example provided above, d will bind to an empty list. Others have posted good solutions to Lets say you got a list named I bet there are far more efficient ways though. If you shouldn't have done that already, make sure to read the python docs on itertools, especially product(), permutations() and combinations(). If order matters check out the If order doesn't matter, convert to a set.
Recently I asked for some help on how to download a file without blocking the GUI. Thanks to everyone who contributed their expertise in the post comments: I now have my program working great. I wanted to now share my conclusions so that others can benefit from them too. To do this I am going to first explain how this works, and secondly I have created a Python Snippet and added it to the Python Snippets library so there is a great working example you folks can play with. You can use Acire to load the snippet and play with it. This is the first gio snippet, and I hope there will be many more. The goal I set out with was to download a file without freezing the GUI. This was somewhat inspired from a recent Shot Of Jaq shot that we did on async programming, and I used this app as a good example to play with. Typically I had downloaded files the manual way and this had blocked my GUI hard, but I was aware that this is exactly what gio, part of the GNOME platform is here to solve. The way async basically works is that you kick off an operation and then you wait for confirmation of the result before you proceed. It is the opposite of procedural programming: you don’t kick off an operation and in the next line process it. When you do things the async way, you start an operation and then tell it what callback should be called when it is complete. It feels very event-driven: kind of how you connect a handler to a signal in a widget so that when that signal is generated, the handler is called. When I started playing with this the docs insinuated that read_async() and read_finish() were what I needed to use. I started off with code that looked a little like this: def download_latest_shot(self): audiourl = "http://....the url to the Ogg file...." self.shot_stream = gio.File(audiourl) self.shot_stream.read_async(self.download_latest_shot_complete) It then calls this callback: def download_latest_shot_complete(self, gdaemonfile, result): f = self.shot_stream.read_finish(result).read() outputfile = open("/home/jono/Desktop/shot.ogg","w") outputfile.writelines(f) After some helpful notes from the GNOME community, it turned out that what I really needed to use was load_contents_async() to download the full content of the file (read_async() merely kicks off a read operation) and load_contents_finish() as the callback that is called when it is complete. This worked great for me. As such, here is the snippet which I have added to the Python Snippets library which downloads the Ubuntu HTML index page, shows it in a GUI without blocking it and writes it to the disk: #!/usr/bin/env python # # [SNIPPET_NAME: Download a file asynchronously] # [SNIPPET_CATEGORIES: GIO] # [SNIPPET_DESCRIPTION: Download a file async (useful for not blocking the GUI)] # [SNIPPET_AUTHOR: Jono Bacon <jono@ubuntu.com>] # [SNIPPET_LICENSE: GPL] import gio, gtk, os # Downloading a file in an async way is a great way of not blocking a GUI. This snippet will show a simple GUI and # download the main HTML file from ubuntu.com without blocking the GUI. You will see the dialog appear with no content # and when the content has downloaded, the GUI will be refreshed. This snippet also writes the content to the home # directory as pythonsnippetexample-ubuntuwebsite.html. # To download in an async way you kick off the download and when it is complete, another callback is called to process # it (namely, display it in the window and write it to the disk). This separation means you can download large files and # not block the GUI if needed. class Example(object): def download_file(self, data, url): """Download the file using gio""" # create a gio stream and download the URL passed to the method self.stream = gio.File(url) # there are two methods of downloading content: load_contents_async and read_async. Here we use load_contents_async as it # downloads the full contents of the file, which is what we want. We pass it a method to be called when the download has # complete: in this case, self.download_file_complete self.stream.load_contents_async(self.download_file_complete) def download_file_complete(self, gdaemonfile, result): """Method called after the file has downloaded""" # the result from the download is actually a tuple with three elements. The first element is the actual content # so let's grab that content = self.stream.load_contents_finish(result)[0] # update the label with the content label.set_text(content) # let's now save the content to the user's home directory outputfile = open(os.path.expanduser('~') + "/pythonsnippetexample-ubuntuwebsite.html","w") outputfile.write(content) ex = Example() dial = gtk.Dialog() label = gtk.Label() dial.action_area.pack_start(label) label.show_all() label.connect('realize', ex.download_file, "http://www.ubuntu.com") dial.run() I am still pretty new to this, and I am sure there is plenty that can be improved in the snippet, so feel free submit a merge request if you would like to improve it. Hope this helps!
I use Tastypie for Django's API. but it returns error. my code is bellow. $.ajax({ type : "POST", url : "http://192.168.1.130:8000/api/user/author/", data : '{"first_name": "111","second_name": "222"}', success: function(){ alert('Submit Success') }, dataType : 'json', contentType : 'application/json', processData: false }); my api.py like this: class AuthorResource(ModelResource): class Meta: queryset = Author.objects.all() resource_name ='author' fields = ['first_name','last_name'] filtering = { 'first_name': ALL, } authentication = Authentication() authorization = Authorization() it returns 200 and post nothing.How can I reslove it?
Is the memory consumed by a process spawned by a multiprocessing.Process going to be released once the process is joined? The scenario I have in mind is roughly like this: from multiprocessing import Process from multiprocessing import Queue import time import os def main(): tasks = Queue() for task in [1, 18, 1, 2, 5, 2]: tasks.put(task) num_proc = 3 # this many workers @ each point in time procs = [] for j in range(num_proc): p = Process(target = run_q, args = (tasks,)) procs.append(p) p.start() # joines a worker once he's done while procs: for p in procs: if not p.is_alive(): p.join() # what happens to the memory allocated by run()? procs.remove(p) print p, len(procs) time.sleep(1) def run_q(task_q): while not task_q.empty(): # while's stuff to do, keep working task = task_q.get() run(task) def run(x): # do real work, allocates memory print x, os.getpid() time.sleep(3*x) if __name__ == "__main__": main() In real code, the length of tasks is much larger then the number of CPU cores, each task is lightweight, different tasks take vastly different amount of CPU time (minutes to days) and vastly different amount of memory (from peanuts to a couple of GBs). All this memory is local to a run, and there's no need to share it --- so the question is if it's released once a run returns, and/or once a process is joined.
Is it possible to chain metaclasses? I have class Model which uses __metaclass__=ModelBase to process its namespace dict. I'm going to inherit from it and "bind" another metaclass so it won't shade the original one. First approach is to subclass class MyModelBase(ModelBase): MyModel(Model): __metaclass__ = MyModelBase # inherits from `ModelBase` But is it possible just to chain them like mixins, without explicit subclassing? Something like class MyModel(Model): __metaclass__ = (MyMixin, super(Model).__metaclass__) ... or even better: create a MixIn that will use __metaclass__ from the direct parent of the class that uses it: class MyModel(Model): __metaclass__ = MyMetaMixin, # Automagically uses `Model.__metaclass__` The reason: For more flexibility in extending existing apps, I want to create a global mechanism for hooking into the process of Model, Form, ... definitions in Django so it can be changed at runtime. A common mechanism would be much better than implementing multiple metaclasses with callback mixins. With your help I finally managed to come up to a solution: metaclass MetaProxy. The idea is: create a metaclass that invokes a callback to modify the namespace of the class being created, then, with the help of __new__, mutate into a metaclass of one of the parents #!/usr/bin/env python #-*- coding: utf-8 -*- # Magical metaclass class MetaProxy(type): """ Decorate the class being created & preserve __metaclass__ of the parent It executes two callbacks: before & after creation of a class, that allows you to decorate them. Between two callbacks, it tries to locate any `__metaclass__` in the parents (sorted in MRO). If found — with the help of `__new__` method it mutates to the found base metaclass. If not found — it just instantiates the given class. """ @classmethod def pre_new(cls, name, bases, attrs): """ Decorate a class before creation """ return (name, bases, attrs) @classmethod def post_new(cls, newclass): """ Decorate a class after creation """ return newclass @classmethod def _mrobases(cls, bases): """ Expand tuple of base-classes ``bases`` in MRO """ mrobases = [] for base in bases: if base is not None: # We don't like `None` :) mrobases.extend(base.mro()) return mrobases @classmethod def _find_parent_metaclass(cls, mrobases): """ Find any __metaclass__ callable in ``mrobases`` """ for base in mrobases: if hasattr(base, '__metaclass__'): metacls = base.__metaclass__ if metacls and not issubclass(metacls, cls): # don't call self again return metacls#(name, bases, attrs) # Not found: use `type` return lambda name,bases,attrs: type.__new__(type, name, bases, attrs) def __new__(cls, name, bases, attrs): mrobases = cls._mrobases(bases) name, bases, attrs = cls.pre_new(name, bases, attrs) # Decorate, pre-creation newclass = cls._find_parent_metaclass(mrobases)(name, bases, attrs) return cls.post_new(newclass) # Decorate, post-creation # Testing if __name__ == '__main__': # Original classes. We won't touch them class ModelMeta(type): def __new__(cls, name, bases, attrs): attrs['parentmeta'] = name return super(ModelMeta, cls).__new__(cls, name, bases, attrs) class Model(object): __metaclass__ = ModelMeta # Try to subclass me but don't forget about `ModelMeta` # Decorator metaclass class MyMeta(MetaProxy): """ Decorate a class Being a subclass of `MetaProxyDecorator`, it will call base metaclasses after decorating """ @classmethod def pre_new(cls, name, bases, attrs): """ Set `washere` to classname """ attrs['washere'] = name return super(MyMeta, cls).pre_new(name, bases, attrs) @classmethod def post_new(cls, newclass): """ Append '!' to `.washere` """ newclass.washere += '!' return super(MyMeta, cls).post_new(newclass) # Here goes the inheritance... class MyModel(Model): __metaclass__ = MyMeta a=1 class MyNewModel(MyModel): __metaclass__ = MyMeta # Still have to declare it: __metaclass__ do not inherit a=2 class MyNewNewModel(MyNewModel): # Will use the original ModelMeta a=3 class A(object): __metaclass__ = MyMeta # No __metaclass__ in parents: just instantiate a=4 class B(A): pass # MyMeta is not called until specified explicitly # Make sure we did everything right assert MyModel.a == 1 assert MyNewModel.a == 2 assert MyNewNewModel.a == 3 assert A.a == 4 # Make sure callback() worked assert hasattr(MyModel, 'washere') assert hasattr(MyNewModel, 'washere') assert hasattr(MyNewNewModel, 'washere') # inherited assert hasattr(A, 'washere') assert MyModel.washere == 'MyModel!' assert MyNewModel.washere == 'MyNewModel!' assert MyNewNewModel.washere == 'MyNewModel!' # inherited, so unchanged assert A.washere == 'A!'
Certainly, there must be some way to somewhat create a list of words suggested to be included in an index. I suggest you look at the script make-index.py (and related files) in the scripts folder of the download page at the Stacks Project (http://www.math.columbia.edu/algebraic_geometry/stacks-git/). The index it generates isn't really ideal, but at least their strategy will give you some idea how to get started. They seem to take the approach that (in a gigantic math textbook) the things which most deserve to be in the index are the italicized word(s) or phrase(s) in each definition environment. In my experience using math books, the most common reason I look something up in the index is to learn its definition, so this seems appropriate, although maybe not for books in other subjects. However you might be able to use the Stacks Project script as a guide to automate the creation of an index which suits your own needs, even if they are very different. As others have mentioned, trying to automate this task would be close to impossible. But if you want to get some very rough hints of words for yourself, this is something I would try (note, requires some scripting): Use In addition to what Juan A. Navarro suggested, I'd say that words which occur in chapter and section titles are likely candidates for indexing. Other things to check could include words which are capitalized when not at the beginning of a sentence and words set in emphatic type. I just wrote a quick python script to extract the most common words in some tex files. It uses detex to strip tex commands from the files, strips characters like ".", ",", ";", "?", "!" from the end of words, ignores words that contain # or =, ignores case and the 100 most common english words (copied from http://www.duboislc.org/EducationWatch/First100Words.html) #!/usr/bin/python import subprocess, glob, operator # Tweak output here: charsToStripFromEnd = ".,;?!" nonWordChars = "=#" minOccurrence = 30 skipWords = 'the of and a to in is you that it he was for on are as with his they I at be this have from or one had by word but not what all were we when your can said there use an each which she do how their if will up other about out many then them these so some her would make like him into time has look two more write go see number no way could people my than first water been call who oil its now find long down day did get come made may part e.g i.e'.split() output = subprocess.check_output( ['detex'] + glob.glob('*.tex') ) wordList = output.split() words = {} for w in wordList: w = w.rstrip(charsToStripFromEnd).lower() if len(w) <= 2: continue isARealWord = True for c in nonWordChars: if c in w: isARealWord = True if not isARealWord: continue if w in skipWords: continue if not w in words: words[w] = 1 else: words[w] += 1 sorted = sorted(words.iteritems(), key=operator.itemgetter(1)) sorted.reverse() for item in sorted: print item[0], item[1] if item[1] < minOccurrence: break As a rough hack I sometimes use the following lines to get all my definitions in bold+italic, and put them in the index. \newcommand{\eb}[1]{{\itshape\bfseries#1}{\index{#1}}} \renewcommand{\emph}{\eb} You could use the glossaries package to suggest terms and acronyms for inclusion in an automatically generated glossary. It won't pick out words for inclusion on its own though, that might require a rather advanced level of natural language processing to accomplish. An alternative would be to use detex and pipe that into a frequency-analyzing script: This will show a list of the word distribution (case-sensitive), with the most frequent words first: This will output words that are not in the English dictionary: detex input.tex | tr -d '[:punct:]' | tr -d '[:digit:]' | tr ' ' '\n' | sort -u | while read i; do if [ -z "`grep -i "$i" /usr/share/dict/words`" ]; then echo "$i"; fi; done It's pretty slow; there's got to be a faster way, though.
Hello I have the following Model: class Participation(models.Model): workflow_activity = models.ForeignKey('WorkflowActivity') user = models.ForeignKey(User) role = models.ForeignKey(Role) current = models.BooleanField() This is the many-to-many 'through' table.I want to filter instances of workflow_activity that have either one of these conditions: No users assigned, ie, no entries for that workflow_activity in the Participation table No current active users, ie, where all the rows for workflow_activity in the Participation table have current==False Help with building the query would be much appreciated! EDIT: Hey everyone, thanks for the responses. I guess im probably approaching this thing wrong. My requirement is that im building a sort of ticketing system that has an auto assign function which assigns users to the tickets based on some selection logic. Im running the assign function as a periodic task (using celery), but for that i need to select tickets that are currently unassigned for the current state of the ticket. The current boolean is used to mark if that particular user is assigned to the current state of the ticket. Any ideas/thoughts on implementing this? Edit2 Heres one i thought of: class WorkflowActivity(models.Model): ... ... assigned_to = models.ManytoManyField('Participation') # older table without the current field current = models.ManytoManyField('Current') class Current(models.Model): participant = models.ForeignKey('Participation') Cringe-worthy I know, but its what i could come up with, any other options?
I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine: import multiprocessing def f(x): return x*x def go(): pool = multiprocessing.Pool(processes=4) #result = pool.apply_async(self.f, [10]) #print result.get(timeout=1) print pool.map(f, range(10)) if __name__== '__main__' : go() However, when I use it in a more object-oriented approach, it doesn't work. The error message it gives is: PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup__builtin__.instancemethod failed This occurs when the following is my main program: import someClass if __name__== '__main__' : # lfq = lastFmQueries.lastFmQueries() # x = lfq.getUsersTopTracks("acet", "overall") sc = someClass.someClass() sc.go() and the following is my someClass class: import multiprocessing class someClass(object): def __init__(self): pass def f(self, x): return x*x def go(self): pool = multiprocessing.Pool(processes=4) #result = pool.apply_async(self.f, [10]) #print result.get(timeout=1) print pool.map(self.f, range(10)) Anyone know what the problem could be, or an easy way around it?
I really miss something basic about python's logging module. In the following code, I create a logger object (log) and add to it two handlers. One with 'INFO' level and one with 'WARNING' level. Both of them are supposed to print to stdout. I expect that calling to log.info(msg)will result in one copy of msg in my stdout and calling to log.warn(msg) sould result in two copies of msg printed to my stdout. Here is the code: import logging import sys logging.basicConfig() log = logging.getLogger('myLogger') log.handlers = [] h1 = logging.StreamHandler(sys.stdout) h1.level = logging.INFO h1.formatter = logging.Formatter('H1 H1 %(message)s ') h2 = logging.StreamHandler(sys.stdout) h2.level = logging.WARNING h2.formatter = logging.Formatter('H2 H2 %(message)s') log.addHandler(h1) log.addHandler(h2) print 'log.level == %s'%logging.getLevelName(log.level) print 'log.info' log.info('this is some info') print 'done' print 'log.warn' log.warn('this is a warning') print 'done' The output is really very strange to me. The .info call results in no visual effect.However, calling to warn results in two copies of msg printed to stdout (which is OK), but also one copy printed to stderr (why?). This is the output of the above code. Note the formatting of the last line in this output. This line is printed to stderr. log.level == NOTSETlog.infodonelog.warnH1 H1 this is a warning H2 H2 this is a warningdoneWARNING:myLogger:this is a warning So my questions are: why does my call to inforesult in no output, despite the fact thath1's level is set to INFO? why does my call to warnresults in additional output to stderr?
I have recently started to learn Python and MySQL for web purposes and I have run into a following problem : I want to pull out from a mysql database one record that contains any text that I enter in param section, howerver I am running into following problem when making a query: traceback (most recent call last): File "/Users/Strielok/Desktop/test.py", line 13, in <module> c.execute("SELECT * FROM data WHERE params LIKE ('%s%') LIMIT 1" % (param)) TypeError: not enough arguments for format string Here is my code: import MySQLdb db = MySQLdb.connect (host = "localhost", user = "root", passwd = "root", db = "test") param = "Test" par = param c = db.cursor() c.execute("SELECT * FROM data WHERE params LIKE ('%s%') LIMIT 1" % (param)) data = c.fetchall() print data c.close() Thanks in advance.
no_spleen Re : Petit guide pour aider au choix d'un langage Le fichier de maillage est trops gros à poster ! Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage un code permettant de générer un fichier de ce type alors? je vais regarder ton code voir si je voit quelque chose de choquant pour les perfs, et éventuellement passer par CProfile pour voir les bottleneck… Malheureusement, cela n'a pas l'air ce changer quoi que soit chez moi. bizarre 3) Je vais installer python 3 pour voir ! python3 est plus lent que python2.6, pypy est plus intéressant de ce coté là par contre. http://speed.pypy.org/ Dernière modification par tshirtman (Le 26/03/2010, à 18:11) Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Bon, les résultats ne m'étonnent pas, c'est effectivement ce sur quoi j'étais resté. Ce n'est pas surprenant : Python n'a pas du tout été créé dans un objectif de calculs intensifs. Cela dit, tous les langages qui ont vraiment fonctionné étaient des langages qui avaient un objectif en vue et qui se sont attachés à l'atteindre plutôt qu'à vouloir être le langage parfait pour tout. Je n'oublie pas le code C++, ça va venir vite. À 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 Le but auquel le python s'attache est la clareté, et le dynamisme, l'universialisme de son offre découle plus de sa popularité que d'un but réel de sa conception. Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Le but auquel le python s'attache est la clareté, et le dynamisme, l'universialisme de son offre découle plus de sa popularité que d'un but réel de sa conception. À mon sens, le but de Python, c'est de créer efficacement et proprement des automates et de gérer efficacement les entrées-sorties, ainsi que tout ce qui est traitement de fichiers et ce qui s'y rattache (de manière très générale). Par extension, son domaine porte aussi sur les interfaces graphiques. Tout cela fait qu'il se combine très bien avec des langages tels que C++ pour réaliser des applications ambitieuses. Dans sa conception, le parti a été pris de lui faire supporter un grand nombre de paradigmes -- impératif, fonctionnel, objet, modulaire et d'autres. Par réaction à Perl, qui est parfois ésotérique, l'accent a été mis sur la clarté et pour cela il y a eu une forte inspiration de Haskell. De part sa conception, il s'agit d'un langage interprété (même s'il existe des compilateurs just in time), ce qui le rend impropre à l'informatique haute performance, mais il faut d'abord se souvenir que la majorité des applications ne sont pas des applications à hautes performances, d'une part. D'autre part le fait que le langage soit interprété donne une grande souplesse, notamment cela permet à Python d'autoriser la méta-programmation dynamique, c'est-à-dire l'écriture de programmes qui changent au court de leur exécution, par opposition à la méta-programmation de C++, qui est statique (le programme ne change que pendant la phase de compilation). Par contre, je ne conseillerais pas Python pour l'embarqué, à mon sens ADA est plus approprié. De toute façon, je ne donnerais pas le qualificatif d'universel à Python, mais des langages à vocation universelle, il y en a eu beaucoup et à chaque fois il s'agissait d'usines à gaz inutilisables en pratique. C'est donc plutôt une bonne chose que Python ne soit pas universel. À bientôt. Le Farfadet Spatial, qui devrait réaliser le code C++ ce week-end. Dernière modification par Le Farfadet Spatial (Le 26/03/2010, à 23:36) 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 par opposition à la méta-programmation de C++, qui est statique (le programme ne change que pendant la phase de compilation). d'ou la quasi non usabilité des templates… mais oui, pour le haute performance, le dynamisme est un frein sérieux, le just in time permet de rattraper une partie de la perte, mais il est évident que par construction, ça ne peut pas être aussi performant… Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! par opposition à la méta-programmation de C++, qui est statique (le programme ne change que pendant la phase de compilation). d'ou la quasi non usabilité des templates… Les modèles sont parfaitement utilisables. D'abord, tu n'es pas obligé de faire de la méta-programmation pour utiliser les modèles. Ensuite, Boost, par exemple, montre bien que la méta-programmation est parfaitement exploitable, certes au prix d'une lisibilité un peu délicate. Tu as parfaitement le droit de détester C++, mais ton affirmation est objectivement fausse. À 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 Pour obtenir le maillage, il faut installer le logiciel gmsh (il est dans les dépots). Voici un fichier a nommer lit.geo et ensuite en ligne de commande gmsh lit.geo -3 ce qui va générer le maillage lit.msh Point(1) = {0, 0, 0, 0.1}; Point(2) = {0.009299999999999999, 0, 0, 0.1}; Point(3) = {0.0373, 0, 0, 0.1}; Point(4) = {0.056, 0, 0, 0.01}; Line(5) = {1,2}; Line(6) = {2,3}; Line(7) = {3,4}; Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{5, 6, 7}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{8, 11, 15}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{19, 22, 26}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{37, 33, 30}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{41, 45, 49}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{52, 56, 60}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{71, 67, 63}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{74}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{77}; } Extrude {{0, 0, 1}, {0, 0, 0}, Pi/4} { Line{81}; } Physical Surface(96) = {40}; Physical Surface(97) = {29}; Physical Surface(98) = {18}; Physical Surface(99) = {95}; Physical Surface(100) = {84}; Physical Surface(101) = {66}; Physical Surface(102) = {55}; Physical Surface(103) = {44}; Physical Surface(104) = {48}; Physical Surface(105) = {36}; Physical Surface(106) = {25}; Physical Surface(107) = {14}; Physical Surface(108) = {91}; Physical Surface(109) = {80}; Physical Surface(110) = {70}; Physical Surface(111) = {59}; Physical Surface(112) = {51, 32, 21, 10, 87, 76, 73, 62}; Extrude {0, 0, 0.4} { Surface{55, 44, 40, 29, 18, 95, 84, 66, 59, 48, 36, 25, 14, 91, 80, 70, 62, 51, 32, 21, 10, 87, 76, 73}; } Physical Surface(601) = {125,213, 279, 257, 235, 213, 191, 169, 147}; Physical Surface(602) = {134, 156, 178, 200, 288, 266, 244, 222, 310, 332, 354, 376, 398, 420, 442, 481, 498, 515, 532, 549, 566, 583, 600, 464}; Physical Volume(603) = {7, 6, 14, 15, 8, 1, 2, 3, 4, 5, 13, 12, 11, 10, 9, 16, 17, 24, 23, 22, 21, 20, 19, 18}; Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage je vient de me dire qu'il faudrait peut être que je fasse un retour là dessus. J'ai généré le fichier mesh, mais si je ne m'abuse il manque le fichier linear_system.py pour tester… Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Flûte : je me suis laissé avoir par le « je le ferais plus tard ». Bon, il faut que je m'occupe de la version C++. À 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, je le poste dans la journée ! Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Voici le fichier linear_system. C'est une classe gérant les systèmes linéaires, basée sur le module pysparse. Comme tu as cité Cprofile, je me suis renseigné et j'ai un peu testé. Pour expliquer les résultats il faut que j'explique un peu ce qui se passe dans le code. Les degrés de liberté (les inconnues) sont définis dans la classe dofkey. Ce sont en fait un couple entre un noeud (de la classe node) et un string désignant le nom de l'inconnue. La classe dof_manager gère ces degrés de libertés, en créant deux dictionnaires. Un dictionnaire self._fixed qui est la liste des degrés de libertés fixés (par exemple, on sait que sur une paroi la vitesse est nulle), et le dictionnaire self._numbering qui est la liste des ddl que l'on va réellement calculer. Quand on va faire une opération, le dof_manager va vérifier si l'on parle d'un ddl fixé ou non, et réaliser l'action adéquate, ce qui se traduit par exemple par ce bout de code def numberVertex(self,node,name): dof = dofkey(node,name) try: a = self._fixed[dof] except KeyError: self._numbering[dof]=(len(self._numbering)) qui est la fonction ajoutant un ddl à la liste des ddl à calculer. Avant de l'ajouter, on vérifie si ce n'est pas un ddl fixé, car dans ce cas on ne le rajoute pas. Et voila ou je voulais en venir. En faisant un cProfile, j'ai remarqué que la plus grosse partie du temps perdu l'est dans les comparaisons entre degrés de libertés (fonction __eq__ de la classe dofkey), c'est à dire à mon avis à chaque fois qu'il faut chercher un ddl dans les dictionnaires (puisque à mon avis, quand in cherche un élément dans un dictionnaire, il fait une boucle sur les clés et appelle la fonction __eq__ non ?) from pysparse import spmatrix,superlu,itsolvers from numpy import * import psyco psyco.full() class linear_system : """ Linear system class based on pysparse """ def __init__(self,n): self._a = spmatrix.ll_mat(n,n) self._xold = array(zeros(n)) self._xnew = array(zeros(n)) self._b = array(zeros(n)) def addToMatrix(self,r,c,val): self._a[r,c] += val def getFromMatrix(self,r,c): val = self._a[r,c] return val def fixInMatrix(self,r,c,val): self._a[r,c] = val def zeroMatrix(self): self._a[:,:] = 0.0 def addToSolution(self,r,val): self._xnew[r] += val def getFromNewSolution(self,r): val = self._xnew[r] return val def getFromOldSolution(self,r): val = self._xold[r] return val def fixInSolution(self,r,val): self._xnew[r] = val def zeroSolution(self): seld._xnew[:] = 0.0 def addToRHS(self,r,val): self._b[r] += val def getFromRHS(self,r): val = self._b[r] return val def fixInRHS(self,r,val): self._b[r] = val def zeroRHS(self): self._b[:] = 0.0 def solve(self): #LU = superlu.factorize(self._a.to_csr()) #LU.solve(self._b,self._xnew) itsolvers.pcg(self._a.to_sss(),self._b,self._xnew,1e-12,2000) def getOldSolution(self): return self._xold def getNewSolution(self): return self._xnew def swichSolution(self): self._xold = self._xnew Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! J'ai en ce moment de gros problèmes matériels. En conséquence, je n'ai pas pu avancer sur le code et je risque de ne pas pouvoir le faire avant quelques temps. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne Foromus Re : Petit guide pour aider au choix d'un langage Bonjour, J'ai lu avec intérêt et attention tous les commentaires depuis la création de cette discussion. Je me considère comme "débutant", même si j'ai pas mal programmé en VB et que, tout récemment, je viens de découvrir Gambas (qui n'est pas la même chose, même si il y a des éléments communs ou ressemblants). En effet, j'ai quitté Win il y a deux ans ou presque, et je suis maintenant sous Ubuntu. En tant que néophyte, je suis réellement décontenancé par ce que j'ai lu. Bon, le mieux, dites-vous, c'est d'oublier Basic, et ce qui y ressemble : Fort bien. Il est probable que pour des programmes d'importance, et éventuellement professionnels, le basic ne tienne peut-être pas le haut du pavé. A un moment, j'avais abordé Python, vu l'éloge qui en était fait. Compte-tenu de l'éloge encore une fois mentionné ici, je me suis dit que je devrais regarder sérieusement la chose, car, malheureusement, j'ai absolument tout oublié du peu que j'avais appris sur le sujet. J'ai téléchargé le pdf recommandé (A Byte of Python - version française du 12-01-2010), et je l'ai lu. Soucieux de trouver un éditeur à la hauteur, j'ai installé ce que j'ai trouvé dans la bibliothèque Ubuntu, à savoir "EricPython". Bien, j'ai lu le bouquin, j'ai essayé (timidement) de faire quelque chose dans mon éditeur, rien ne s'est passé... Enfin, et d'après ce que j'ai cru comprendre, ça marche essentiellement en console. Bien entendu, il est possible de mettre du graphisme, mais cela fait l'objet d'un autre bouquin il me semble. A ma grande honte, je dois avouer que le fait de mettre un bouton sur une page, et de remplir la procédure y afférente me plaisait bien aussi. Et surtout, je trouvais ça pratique. Là, si je veux écrire "Hello Word" au milieu de la page en cliquant sur un bouton, je ne vois pas, pour l'heure, comment je pourrais faire. La console, c'est bien. Par exemple, quand je veux lire un fichier codé, je vais dans la console, je tape ccrypt-d et j'ajoute le chemin du fichier concerné, je rentre le mot de passe, et je peux ouvrir le fichier. Une fois consulté, je refais l'opération, et mon fichier est à nouveau codé. Sous Win, je faisais un clic droit sur mon fichier, le menu contextuel me proposais "déchiffrer", un clil, le mot de passe, et je pouvais ouvrir mon fichier. Le simple fait de le refermer le codait. Je suis désolé, mais je trouvais ça plus pratique, beaucoup plus rapide et moins fastidieux. J'en déduis donc, à la lecture de toutes ces informations, que le sujet est proposé à des gens qui se destinent vraiment à la programmation, et qui ont des choses conséquentes à faire. Dans ce cas de figure, on pourrait supposer qu'ils ont déjà un minimum de connaissances en informatique, et par conséquent, ils sont probablement en mesure de faire un choix qui leur convient. Voilà, c'était l'avis d'un "candide" ! Je reste très content d'avoir lu tout ça, j'ai acquis une bonne culture générale sur le sujet. Je souhaite une bonne réussite à tous les aspirants programmeurs ! Assemblé perso - AMD Athlon LE 1640 _ Ram 2 G - Xubuntu 12.04(Precise) _ Xfce 4.8 Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Voilà, c'était l'avis d'un "candide" ! Un tel avis est important, vu que c'est la première cible. Donc, merci d'avoir posté ton avis. Cela dit, les manipulations graphiques que tu as données m'apparaissent bien fastidieuses, je trouve que ça prend trop de temps. En général (on peut trouver des cas particuliers), le programmeur qui a de la bouteille sous un système Unix, mais également quelqu'un d'habitué à donner des cours de programmation est très réticent à commencer par la partie graphique, parce que cela détourne de l'essentiel et pousse à se focaliser sur des détails. Toutefois, lorsque l'on veut créer une interface graphique, il est en effet préférable d'avoir recours à un outil de construction d'interface graphique, par exemple Glade pour Gtk+. Cela dit, mon avis est que la construction d'interface graphique ne devrait pas être la première chose à présenter à un débutant en programmation, quel que soit ce qu'il entend réaliser par la suite. Cela dit, à te lire, j'ai l'impression que ce n'est pas tant le choix du langage qui te pose problème, que la façon dont son enseignement est dispensé. Bon, puisque je t'ai sous la main : dans ton cas, que veux-tu faire en programmation ? À 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 il existe de nombreuses bibliothèques de widgets disponibles en python (les widgets c'est les fenetres, les boutons, les cadres, les onglets, tout ce qui fait une interface gaphique moderne), on cite en général GTK, QT, WXwidgets, et en python, TK (qui viellit, mais est facile à aborder), cependant, il est en effet plus pratique d'utiliser un logiciel pour créer son interface (glade est très bien) et lui relier les fonctions. Enfin si tu veux quelque chose de bien intégré pour créer des applications python/gnome sans te prendre la tête, quickly (présent dans les dépots) pourrait te plaire. Tu sera lancé assez facilement normalement. (glade est intégré à l'ensemble). Mais bon après faire des applications modernes ça demande quand même un minimum d'apprentissage sur ce qui se fait. Enfin VB et Gambas sont certes des environnements simples pour créer des petites applications (jetables, souvent), mais ne sont pas, en effet efficace pour faire des projets plus solides. Hors ligne Foromus Re : Petit guide pour aider au choix d'un langage Bonjour, Merci d'avoir pris mon avis en considération, même s'il ne présente pas grand intérêt.""""dans ton cas, que veux-tu faire en programmation ?"""" Rien de spécial ! Désolé de vous décevoir... Programmer me plaît bien : ça entretient un peu l'esprit, ça fait fonctionner le cerveau. Mais encore faut-il avoir un but... Sans raconter ma vie, je dirais que j'ai commencé avec le ZX81 : 1K° de mémoire (oui, un seul petit kilo !), mais avec une extension de 16k°, quel pied, et une télé comme écran et un petit magnéto à K7 pour le stockage de masse... Ensuite, je suis passé sous un Apple : 48K° de mémoire, mais avec une carte de 16 K° supplémentaires, j'ai pu commencer à utiliser mon premier tableur, et un traitement de texte ! Tout ça pour dire que le ZX fonctionnait avec son basic propre, et l'Apple aussi avec quelque chose qui devait s'appeler EditBasic ou quelque chose du genre. Vous conviendrez donc que si je voulais écrire Bonjour le Monde au milieu de l'écran, il fallait que je me débrouille tout seul. J'ai tout appris tout seul, par des livres et par le vécu, je n'ai jamais eu de profs, c'est peut-être une raison qui fait que je suis assez peu réceptifs aux conseils des autres, et c'est probablement pour ça aussi que je me fais régulièrement rabrouer dans les forums, à tel point que j'ai abandonné le site de Gambas tellement je me suis fait laminer. J'ai à peu près vécu la même chose ici quand je suis passé sous Ubuntu, ma façon de comprendre et d'apprendre ne convenant pas à ceux qui "ont le savoir". Bref, j'ai été assez rudement traité, mais j'ai fini par arriver à me servir un peu d'Ubuntu (mais il est évident que je ne dois l'utiliser qu'à 5 ou 10 %..). Cette parenthèse étant fermée, je ne reste pas sectaire puisque l'auteur de cette discussion cherche à savoir, ce qui est tout à fait à son honneur. J'ai fait des choses en Visual Basic, et si ce n'est pas le langage le plus performant, je suis quand même arrivé à faire un logiciel avec des milliers de lignes de code et j'ai utilisé la plupart des fonctions proposées. Au passage, j'ai sincèrement admiré la simplicité de Python pour le peu que j'en ai vu. Pour donner un exemple précis, en VB, j'ai aussi fait un programme d'apprentissage du clavier français. A chacun son truc, moi, quand je vois des gens frapper le clavier en regardant où ils posent leurs deux index, francehment, ça m'énerve ! Moi quand je tape, je regarde ce qui s'inscrit sur l'écran, à la rigueur, je regarde ce que je veux recopier, je trouve ça plus rationnel que de regarder mes index ou mes huit autres doigts... Donc, dans un premier temps, j'aurais aimé retranscrire dans un langage autre que VB ce programme, de manière à ce qu'il tourne sous Linux. Opération totalement gratuite, vous l'aurez compris, puisque l'usage personnel de ce logiciel n'est plus vraiment nécessaire, encore que, comme dans toute discipline, il faut toujours s'entraîner. Mon programme comporte 20 leçons, il analyse les erreurs, les comptabilise, donne un coefficient de réussite (100 - vitesse de frappe / erreurs) (je ne me souviens plus exactement de la formule que j'avais établie à l'époque) , on peut enregistrer ses scores, l'enregistrement n'est proposé que quand le score obtenu est meilleur que ce qui est déjà enregistré. Naturellement, tous les utilisateurs peuvent avoir leur propre dossier, ça tombe sous le sens. On peut tout paramétrer au niveau de la présentation, on peut activer ou non des infobulles sur les touches du clavier représenté, et le texte de l'exercie est affiché dans une fenêtre qui change de couleur juste après la frappe, le modèle à travailler étant dans une fenêtre juste au-dessus. Alors, je veux bien que le graphisme ne soit pas du premier intérêt, mais je ne vois pas comment je pourrai réécrire ce programme en Python, tout au moins, avec le peu que j'en ai vu jusqu'alors. Je voudrais aussi répondre au fait que la programmation doit commencer avec les bases et ne pas s'embarrasser du graphisme qui écarterait des bases et détourerait l'attention, cela pouvant conduire à une éventuelle dissémination de l'esprit. Fort bien, dont acte. Cela dit, quand j'ai étudié le VB avec un livre - j'ai eu la chance de tomber sur un bon, ce qui reste exceptionnel, j'ai appris certes le graphisme, j'ai aussi appris ce qu'était une procédure, une fonction, une variable - fut-elle locale ou globale, j'a aussi appris toutes les commandes, les instructions, boucles, tableaux, débranchements, fichiers et je n'ai pas un seul instant senti que le graphisme gênant d'une manière ou d'une autre. Maintenant, on peut aussi considérer que toutes les bases auxquelles vous faites allusions, je les ai déjà un peu tutoyées dans mon utilisation précédente de mon Apple, je me souviens qu'à l'époque, je m'étais construit un logiciel professionnel - j'étais artisan à l'époque, et qui gérait mes factures (clients et fournisseurs), la gestion de mes pièces détachées, imprimait mes factures et faisait même mes lettres de rappel ! Et tout ça, sans graphisme, naturellement ! Ceci m'amène à réitérer mon avis à propos des aspirants programmeurs, et je crois sincèrement que ceux qui envisagent de se mettre à la programmation ont déjà une expérience réelle et suffisante de l'informatique pour pouvoir déjà avoir une idée de leurs choix possibles. Mais je me répète encore, une discussion comme celle-ci est très utile car elle donne une bonne vue d'ensemble sur les différents langages, j'avoue pour ma part que des choses comme Perl ou C++, pour moi, c'est de l'hébreu, et si j'avais un programme important à faire, je crois que je trouverais matière à creuser. Bien, mais comme j'approche des mes 70 ans, je n'ai plus vraiment de grandes réalisations à faire ! Mais je vais continuer à lire ce fil avec intérêt ! Assemblé perso - AMD Athlon LE 1640 _ Ram 2 G - Xubuntu 12.04(Precise) _ Xfce 4.8 Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Bon, Foromus, tu reconnaîtras aisément, je pense, que tu restes un cas assez atypique. Oui, les premiers micro-ordinateurs, depuis l'Altair, ont été livrés avec Basic. Cela dit, avec le recul, il faut reconnaitre que ce langage pousse à utiliser des pratiques de programmation rendant les programmes difficiles à déboguer et à maintenir, en plus de problèmes de performances. Raison pour laquelle nombreux sont ceux, dont je fais partie, qui, s'ils reconnaissent l'intérêt qu'a eu Basic, le déconseille maintenant au vu de l'offre disponible. Concernant le choix d'un langage, oui, je pense que quelqu'un qui se lance aura tendance à avoir une certaine expérience de l'informatique. Toutefois, le présent fil de discussion est né de la démultiplication sur le forum des messages demandant quel langage choisir et d'une demande des intervenants du forum. Au sujet des interfaces graphiques, le problème c'est que, très (trop) souvent, on voit des débutants se lancer dans la réalisation d'une interface avant, d'une part, de vraiment avoir déterminé ce qu'ils voulaient coder, d'autre part avant même de savoir programmer. Le résultat est la création d'une interface qui ne fonctionne pas, ne sert à rien et un découragement du dit débutant. Commencer par des petits programmes en mode console est plus simple, plus rapide, permet de voir facilement le résultat et évite de s'atteler tout de go à des problèmes qui demandent de la minutie. Cela dit, dans ton cas, je pense en effet que tu aurais intérêt à te pencher sur Python, ainsi que Gtk+ et Glade. Tout cela te permettrait de réaliser une nouvelle version de ton programme à la fois maintenable et efficace, ceci assez facilement (même si la logique est différente de celle de Basic). En revanche, cela nécessitera de remettre en question ce que tu penses savoir de la programmation. À 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 @Foromus: je cerne un peu mieux ton expérience, tu as programmé au quotidien, en autodidacte, depuis très longtemps, avec des outils qui ne sont pas les meilleurs, mais sont assez facile a appréhender pour s'y mettre en autodidacte (je suis passé par là aussi), alors certes, se passer du basic quand on a connus que ça est assez difficile, car en effet il rends très simple à faire les choses simples, mais compliqué les choses complexes. Beaucoup de langages font le choix inverse, considérant que ce n'est pas grave de complexifier l'apprentissage de la base, si c'est pour fournir des outils bien plus puissant, et donc permettre de réaliser plus simplement des choses très complexes. Python est (à mon sens) l'un des rares langages à permettre plusieurs niveaux de complexités, tout en gardant une simplicité de réalisation assez simple. Ce n'est pas le langage parfait (qui n'existe pas) mais il est bon. Si l'anglais n'est pas un problème pour toi (je suppose vu que tu programme depuis longtemps) je te conseil de regarder du coté de quickly pour te lancer, ils expliquent comment commencer facilement un projet en gtk/glade/python, après un temps d'adaptation tu devrais t'en sortir je pense . Hors ligne Foromus Re : Petit guide pour aider au choix d'un langage Bonjour, Voilà, je ne voudrais pas abuser de mon temps d'antenne, mais vu que la conversation se tarit un petit peu, j'en profite pour rajouter un petit grain de sel... D'abord, accordez-moi cette justice que je ne suis pas borné au basic. Aurais-je laissé penser cela ? Partir de l'apprentissage complexe pour arriver à faire facilement des choses complexes me semble une excellente démarche. Prenons par exemple, l'apprentissage de la musique : une école préconise de faire faire 4 ans de solfège à l'apprenant, avant de lui laisser toucher un instrument. Une autre école préconise de d'abord donner un instrument, et parallèlement, l'apprenant devra acquérir les notions indispensables. Comme on peut s'en douter la première méthode produit un nombre considérable de déchets, apprendre le solfège peut parfois manquer d'intérêt, d'autant que cela concerne des règles rigides, pures et dures et incontournables. C'est peut-être pour ça que je fais le lien avec la programmation. Concernant la seconde méthode, les déchets sont carrément ahurissants, il n'y a pratiquement aucune réussite, et pire, l'apprenant peut éprouver un dégoût profond qui le fera renoncer à jamais, ce qui n'est pas le cas de la première méthode : le jour où l'apprenant aura compris la nécessité du solfège avant l'instrument. Remarquez, on s'en serait douté : serait-ce raisonnable de confier un livre de philo à un illettré en lui proposant d'apprendre à lire en même temps qu'il apprendrait la logique formelle ? Pour revenir à Python, dont on me vante ici les grands mérites - ce dont je ne doute pas, je m'y mettrai peut-être un jour... Je viens de relire quelques passages du livre recommandé et déjà mentionné. Première déclaration : Python est simple... Ah bon ?.... Voyons voir.... Prenons une variable : pas besoin de la déclarer, la déclaration se fait au moment de l'emploi (si j'ai bien compris, ce qui n'est pas sûr....). Ensuite, pour une numérique, il y a 3 types : entier, flottant, imaginaire. Fort bien, je ne me souviens pas que la troisième catégorie fut présente dans les basics, mais je ne l'ai pas forcément vue. C'est vrai que ça change entre la byte, le integer, le float, le long, le super long et je ne sais plus quoi...Donc, Python serait plus simple. Pas forcément pour moi.... Quand je programme, il m'arrive encore de déclarer des numériques en Byte. Il y a probablement là un vieux réflexe d'une époque où l'on avait à cœur d'utiliser au mieux la ressource, le gaspillage n'était pas de mise, pas à la mode. Il en est tout autrement maintenant, la mémoire ne coûte plus rien, le µ pédale à 3 ou 4 GHz, que demande le peuple ? Et tout le reste est à l'avenant : on prend 5 douches par jour, on met à la poubelle, etc, je ne veux pas déborder, sachant que chaos qui nous attend fera tomber de haut une génération déboussolée par l'excès... Pour revenir aux déclarations : il est clair que lorsqu'on commence à avoir un programme d'importance - même au stade de projet, il est totalement absurde de foncer dans le code avant d'avoir établi au moins les grandes lignes : avant de coder, il faut au minimum avoir rédigé sa trame ! (Et c'est peut-être là la mise en garde mentionnée plus haut). Il faut aussi, et c'est un minimum, prévoir ses variables. Le mieux est encore de les écrire, ne serait-ce pour pouvoir retrouver à quoi elles correspondent plus tard, de même que pour les définir, ce qui peut éviter pas mal d'erreurs d'incompatibilité. Les écrire d'abord (sur un papier ou sur un fichier texte - la première solution étant de loin la meilleure) est certainement la chose à faire bien avant le codage. Que l'on fasse du code pour "essayer" tel ou tel commande ou contrôle me parait logique, foncer tête baissée me le semble beaucoup moins... Bon, je reviens à Python. Qui utilise les nombres imaginaires dans son quotidien, même si il est programmeur ? Je conçois que peut-être, un scientifique ou quelqu'un qui veut faire des polices vectorielles ou du dessin du même type soit adhérent, pour le reste du commun des programmeurs, ce n'est pas l'outil qu'il doit obligatoirement tenir sous une patte de sa souris. Par ce que, là aussi, il faut se demander ce qu'on va faire avec la programmation que l'on souhaite apprendre. J'ai comme l'impression que l'on fait rarement un apprentissage comme ça, gratuitement, en général, c'est pour donner suite à un souhait ou un besoin, fut-il d'ailleurs simplement ludique ! Je voulais aussi parler d'une autre chose vue dans Python, et qui se réclame de la simplicité : la boucle IF. Au premier abord, j'ai été séduit : c'est vrai, tout simple, même pas de End pour terminer, pas de Then mais deux-points, à première vue, c'est simple. Et le Else ? Une gentillesse... En fait, je vois les choses autrement. D'abord, le Else. Je ne l'utilise pratiquement jamais ! Que signifie Else ? Tout le reste et n'importe quoi ! Imaginons un impondérable qui se glisse dans votre construction, et il se peut fort bien qu'il soit exécuté par un Else ! En général, je mets une boucle avec la condition, et une seconde boucle avec la non-condition. En fait, ça me prend une ligne de plus, mais c'est clair, net, précis, sans équivoque, il n'y a que ce qui est écrit qui peut arriver, et pas autre chose. Toujours en rapport avec la boucle IF pythonesque, j'ai noté avec un bond sur mon fauteuil que l'identation était très importante. Et l'auteur de souligner à propos du code : ça va générer une erreur car il y a un espace au début... Chacun ses habitudes, moi, je suis très pointilleux sur l'identation, c'est la condition sine qua non pour s'y retrouver dans son code, surtout si on doit le relire six mois ou un an après. Quand je programme une boucle IF, j'écris ma première ligne, la condition donc, et immédiatement après, je tape mon End par retour chariot, ce qui fait qu'il est obligatoirement à la même identation. J'ajoute des espaces entre les deux lignes, et si j'ai des IF imbriqués, je fais exactement la même chose, sauf bien sur dans le cas de la décision unique où le End n'est pas nécessaire. Il m'est même arrivé avec des procédures un peu alambiquées il est vrai, de numéroter les IF et END en commentaires pour être certain de m'y retrouver. Tout ça pour dire que ce n'est pas forcement, suivant ma logique, que parce qu'il y a moins de lignes que c'est plus simple. Il en va de même pour certaines formules mathématiques que l'on peut toujours enchaîner, certes, mais dont on n'arrive plus à savoir exactement la préséances des opérateurs. Pour peu que l'on veuille une assurance sécurité, il faudra ajouter un nombre significatif de parenthèses qui compliqueront d'autant le code, alors que parfois, l'ajout d'une au deux variables locales simplifie considérablement la lisibilité. Cela dit, mon propos n'est pas d'essayer de démontrer quoi que ce soit, encore moins de faire le procès de Python. C'est un langage que je vais peut-être essayer d'approcher, cela dit, ou plutôt redit, il faut qu'un intérêt apparaisse, il faut un projet qui motive cet apprentissage, on ne fait rien sans motivation ! D'après ce que j'ai lu de Python, la simplicité promise ne me semble pas du tout au rendez-vous, j'ai vraiment le sentiment que c'est quelque chose de compliqué, pas forcément inaccessible, mais assurément compliqué, et en lisant le livre sus-mentionné, il y a plein de trucs auxquels je n'ai rien compris, et si je voulais réécrire mon programme d'apprentissage de clavier par exemple, je ne vois même pas par quel bout je pourrais commencer ! Tout cela m'amène à une considération déjà effleurée plus haut. Je crois l'avoir dit, je suis resté vraiment surpris de trouver cette discussions sur ce site. Quand j'ai décidé de migrer sous Linux, j'ai tâté un peu hasard, et je ne me souviens pas du tout des raisons de mon choix ! Ce que j'ai retenu, c'est que Ubuntu est une distribution facile et sûre, deux raisons de retenir mon attention, il est quand même certain que vu mon âge, les grosses difficultés me posent plus de problèmes qu'il y a trente ou quarante ans ! Bref, ce n'est pas si facile de migrer, même sous une distribution simple. Je le répète, ici, sur ce site, je me suis fait virer et pratiquement insulter. Je veux bien que quand on débarque, on pose des questions stupides, idiotes, je sais bien que parfois, on oublie de consulter une aide disponible en ligne, tout simplement parce qu'on est coincé, ou que l'on ne se rappelle plus où se trouve cette aide potentielle. Je sais également que beaucoup de gens donnent de leur temps précieux et de leur patience pour aider les débutants, et qu'ils sont peu nombreux face à la demande, aussi, ils sont parfois excédés par des questions répétitives. A cela je fais remarquer que si ils ont raison dans l'immédiat, ils n'ont pas forcément raison dans le temps. Certes, au début, on patauge, on pose plein de questions, et au fur et à mesure que l'on découvre, on apprend, non seulement à utiliser le produit, mais aussi à trouver seul des éventuelles solutions. En rabrouant les gens, comme je l'ai vu faire pas mal de fois, la discussion se terminait par : "Et merde, j'en ai marre, je retourne sous Windows"... Etait-ce bien le but de la manœuvre ?... Mais le pire, c'est que j'ai retrouvé un comportement quasi similaire sur le site de Gambas ! Alors, je veux bien admettre que je suis un peu bouché à l'émeri et que j'ai un caractère de vache, il n'en reste pas moins vrai que si j'ai un peu avancé, il a fallu montrer une réelle persévérance. Je me souviens d'un proche qui m'a dit un jour : "Si tu vas sous Linux, tu vas avoir les trois quarts de tes programmes qui ne vont plus marcher. Et puis, sous Linux, il faut déjà être un peu informaticien". Je veux bien que cette conversation date de un ou deux ans, néanmoins, tous mes programmes fonctionnent sous Linux, et même mieux pour certains, et je ne suis toujours pas informaticien ! Pourquoi tout ce baratin me direz-vous ? Et bien justement, c'est en rapport avec ce que j'ai dit plus haut, et qui concerne mon étonnement d'avoir trouvé cette discussion sur ce site. Si Ubuntu est simple et facile - ce serait aux dires de certains la distribution la plus facile, pourquoi des aspirants à la programmation chercheraient ici les bases ou les conseils sur le choix d'un langage, surtout lorsqu'il est dit dans le fil que l'apprentissage le plus sérieux sera d'évidence le plus rigoureux ? Je remarque quand même qu'il n'y a pas foule dans les commentaires, non ? Bien entendu, il y a probablement beaucoup de gens qui lisent sans intervenir, je voudrais quand même remarquer que, lorsqu'on est intéressé, on se manifeste en général ! Bien en conclusion, je crains d'avoir été un peu long, je vais me relire quand même... Pour l'instant, me mettre à Python est une hypothèse, il me reste à trouver les moyens de m'y mettre, c'est à dire, de trouver de la documentation, une aide sérieuse et sur laquelle je puisse compter, et surtout, une perspective très claire du chemin à parcourir : sans carte, sans GPS et sans idée du but à atteindre, il est hors de question d'entreprendre le chemin... Tant que je n'aurai pas une idée claire du chemin où je dois poser mon premier pas phytonneux, je crains de rester béatement dans le confort de mon fauteuil... Merci à tous pour vos interventions ! Je souhaite sincèrement que cette discussion éveille des vocations ! Assemblé perso - AMD Athlon LE 1640 _ Ram 2 G - Xubuntu 12.04(Precise) _ Xfce 4.8 Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Foromus, sans vouloir polémiquer, tu devrais aérer et structurer un peu plus tes interventions, ce serait plus facile à lire. Quelques remarques : tout d'abord, il n'y a pas que Python. Ensuite, tu parles beaucoup de tes habitudes, encore une fois il est certain qu'en changeant de langage, il faut changer d'habitude. Cela dit, oui, il est préférable d'avoir une motivation particulière lorsque l'on veut se lancer dans la programmation, d'ailleurs cela me semblait être indiqué dans le message de départ. Concernant le type des variables, il faut tout de même garder en tête plusieurs choses. Tout d'abord, jusqu'aux années quatre-vingt-dix, à peu près, sur les ordinateurs de bureau, on gérait la pénurie. Aujourd'hui, on gère l'abondance : la pénurie ne se gère pas du tout comme l'abondance. De plus, faire des économies de bouts de chandelles n'est pas la marque d'un fin gestionnaire. Il ne faut pas oublier que le bogue de l'an 2000, c'était d'abord une affaire de variables trop justes pour pouvoir supporter le changement de millénaire : il ne faut pas oublier qu'un programme va évoluer. Par exemple, coder un entier sur un seul octet signifie qu'il sera compris entre -128 et 127, ce qui est très juste. D'autant qu'un système 8 bits gérera mieux les variables 8 bits, un système 16 bits les variables 16 bits et ainsi de suite -- notamment en ce qui concerne les caches, dans lesquels on peut facilement perdre de la place à vouloir à tout prix créer des variables extrêmement justes, c'est le problème d'alignement des variables. En clair, une bonne gestion de la mémoire, ce n'est pas réduire à tout prix la taille des variables, au risque de rendre le programme incapable d'évoluer (voir incapable de traiter les cas que l'on veut traiter), au mépris des performances, parfois en entrainant une perte de mémoire. Une bonne gestion de la mémoire, c'est de prendre du recul et de faire attention à ses structures de données, c'est-à-dire analyser son problème en amont. Sinon, depuis que je suis inscrit à ce forum, j'ai vu de l'ordre d'une fois par mois apparaître un message demandant quel langage choisir pour débuter la programmation. Si ce fil de discussion a été créé, c'est à la demande des utilisateurs et aussi parce que ceux qui répondaient en avait assez de répéter sans arrêt la même chose. D'ailleurs, il a atteint pour l'heure cinq pages, ce qui le place au-dessus de la moyenne des fils de discussion. Après, si tu le trouves inutile, le mieux, c'est encore que tu ne le consultes pas. À bientôt. Le Farfadet Spatial Dernière modification par Le Farfadet Spatial (Le 30/04/2010, à 08:05) L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne ffw137 Re : Petit guide pour aider au choix d'un langage Bonjour à tous, je trouve ce sujet très intéressant et notamment ce que Foromus et le Farfadet Spatial échange. J'adore programmer à titre personnel depuis une trentaine d'année et je suis très très loin d'être un expert, je suis passé également par le TRS-80, ZX-80 et toute la série avec l'upgrade chaque année. Maintenant au niveau des langages, je pense que l'on est tous un peu sectaire et on a tendance à défendre celui que l'on utilise le plus. J'ai programmé en ZXBasic, QBasic, Turbo Basic et VB et j'ai aimé fortement ces langages sauf quand il fallait avoir de la vitesse et l'accès rapide au hardware, donc je me suis marié avec mon second meilleur ami: l'assembleur qui lui n'est pas sympa et à rarement de beau IDE graphique pour créer sa fenêtre avec le bouton qui affiche bonjour mais quand on sait le faire, le programme ne pèse rien et va à la vitesse d'une bombe. Ensuite j'ai découvert Turbo Pascal, Turbo C et Turbo Prolog très complémentaires, j'ai programmé assez bien mais mon cœur à virer vers Blaise et c'est naturellement que j'ai opté pour Delphi (Lazarus est très bon sous linux). Maintenant j'en ai un peu marre de passer des heures à convertir une bibliothèque du C/C++ (qui représente une énorme parie des codes sources ) vers le pascal, je me suis replonger dans le C/C++. Donc je pense qu'il faut savoir gouter à tout, maintenant je suis pour l'apprentissage pas à pas en mode console pour apprendre les bases et les dissocier de l'interface graphique mais celle-ci doit rapidement être vue pour apprendre les bases d'un bon dialogue utilisateur/programme. Combien de programmeurs talentueux font des interfaces de m... car ils n'ont aucune idée de l'ergonomie "normale", pas la leur car ils vont trouver ultra important une fonction sur laquelle ils auront passer des heures et occulter une autre qui sera pourtant fortement demandée mais peu maniable et provoquera l'abandon de leur programme. Pour l'éditeur on prend ce qu'on aime et pas nécessairement avec Emacs/Vim sans pluggin dirait certains selon qui le fait de taper du code avec une aide quelconque est une hérésie et empêche d'apprendre toutes les arcanes d'un langage, je leur rétorquerai, que j'ai passé mon temps à programmer des ordinateurs 24 bits (oui 24 bits!) en porte NAND (plusieurs milliers en composant non discret) en entrant des séquences octales avec pression d'un bouton dans chaque adresse pendant des heures donc ils peuvent aller se recoucher, de plus la complétion automatique m'a souvent fait découvrir des choses que je ne connaissais pas avant et m'a enfin fait lire la documentation un peu plus complètement. Maintenant, je suis un programmeur "bord.elle...hic", je n'utilise pas UML, j'ai ouvert un livre, j'ai commencé à lire et je n'y ai vu aucun exemple pratique appliqué à des cas réels, juste du code exemple sans aucun contexte et qui ne permet pas de réellement l'utiliser mais je persévèrerai et j'y arriverai un jour. Par contre, j'adore toujours l'assembleur et ma passion est la rétro-ingénierie des firmwares de décodeurs satellites par pour le piratage mais pour savoir comment cela fonctionne et là, malheureusement, j'ai pu voir les dégâts engendrés par la programmation objet mal utilisée, des tonnes de tables de saut indirects pointant sur des autres tables qui pointaient sur du code qui appelaient également des méthodes indirectes via des pointeurs de pointeurs tout cela rend vraiment triste quand on voit de précieuses ressources mémoires (en général 2 Mo de flash et 8 Mo de RAM à partager avec la vidéo, l'audio et le système) ainsi dilapidées. La programmation objet est géniale pour développer, maintenir mais on doit ensuite replonger dans le code assembleur pour l'optimiser et bien utiliser les options des compilateurs sinon on a un programme lent! J'ai vu du code tourner deux fois moins vite sans problème à cause de cela mais tout est une question d'équilibre. Donc pour moi, il faut connaître un peu de tous les langages, donc en tester un grand nombre, développer des interfaces graphiques convenables également et une ligne de commande utilisable aussi mais surtout optimiser ses programmes. Je suis venu à Ubuntu dans cet esprit et quand j'aurai du temps libre réaliser un programme permettant le désassemblage des firmwares satellites un peu comme IDA PRO, j'en ai fait une partie avant sous delphi/win (la partie transformant l'assembleur MIPS en code C) mais maintenant je suis entrain de voir Ajunta et GTK+ et j'espère aider cette communauté et partager mes expériences. Désolé pour la longueur. Dernière modification par ffw137 (Le 12/05/2010, à 15:47) Acer 5610-Epson DX3850-Samsung ML-1640-Lucid Samsung NC-10-Lucid-Ecran 17" "Un philosophe c'est quelqu'un qui est prêt à faire mourir les autres pour ses idées avant d'en changer quand vient son tour" (perso enfin je pense) Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Tout d'abord, merci pour ton intervention Ffw137. Quelques remarques : l'assembleur qui lui n'est pas sympa et à rarement de beau IDE graphique pour créer sa fenêtre avec le bouton qui affiche bonjour mais quand on sait le faire, le programme ne pèse rien et va à la vitesse d'une bombe. Ce n'est plus tout à fait vrai : depuis les années 80, les choses ont bien changé. Désormais, les processeurs sont superscalaires et multi-cœurs, ce qui implique des architectures intrinsèquement parallèles et une forte utilisation du principe de pipeline. En conséquence, les optimisations adaptées à de telles architectures sont difficilement réalisables par un être humain. De plus, un code en assembleur est par essence non-portable. De nos jours, une utilisation raisonnée de l'assembleur est d'y avoir recours pour l'accès fin au matériel et pour certaines applications embarquées. Combien de programmeurs talentueux font des interfaces de m... car ils n'ont aucune idée de l'ergonomie "normale", pas la leur car ils vont trouver ultra important une fonction sur laquelle ils auront passer des heures et occulter une autre qui sera pourtant fortement demandée mais peu maniable et provoquera l'abandon de leur programme. Il est généralement préférable de détacher l'interface graphique du programme, car il s'agit de deux choses différentes. Le code est l'affaire du programmeur, l'interface de l'ergonomiste. Les bibliothèques tels que Qt ou Gtk+ permettent de faciliter une telle distinction. Pour l'éditeur on prend ce qu'on aime et pas nécessairement avec Emacs/Vim sans pluggin dirait certains selon qui le fait de taper du code avec une aide quelconque est une hérésie et empêche d'apprendre toutes les arcanes d'un langage, je leur rétorquerai, que j'ai passé mon temps à programmer des ordinateurs 24 bits (oui 24 bits!) en porte NAND (plusieurs milliers en composant non discret) en entrant des séquences octales avec pression d'un bouton dans chaque adresse pendant des heures donc ils peuvent aller se recoucher, de plus la complétion automatique m'a souvent fait découvrir des choses que je ne connaissais pas avant et m'a enfin fait lire la documentation un peu plus complètement. En réalité, tant Emacs que Vim fournissent de nombreuses aides aux programmeurs, notamment ils possèdent tous les deux la complétion automatique. Ce sont loin d'être de simples éditeurs de textes, ce sont des environnements de travail très complets. Pour ma part, après avoir testé en profondeur de nombreux environnements de développements intégrés, je suis revenu à Emacs, non pas parce que c'est une hérésie d'avoir de l'aide au développement, mais justement parce que les outils offerts par Emacs me permettent d'être plus productif avec Emacs qu'avec aucun des environnements de développements intégrés aujourd'hui disponibles. j'ai pu voir les dégâts engendrés par la programmation objet mal utilisée, des tonnes de tables de saut indirects pointant sur des autres tables qui pointaient sur du code qui appelaient également des méthodes indirectes via des pointeurs de pointeurs tout cela rend vraiment triste quand on voit de précieuses ressources mémoires (en général 2 Mo de flash et 8 Mo de RAM à partager avec la vidéo, l'audio et le système) ainsi dilapidées. Il ne faut pas oublier l'importance du compilateur dans ce processus et aussi des options de compilations, de quand remontent tes expériences et avec quels compilateurs ? Cela dit, oui, il est bon de programmer en réfléchissant aux conséquences que cela à sur l'utilisation des ressources. on doit ensuite replonger dans le code assembleur pour l'optimiser et bien utiliser les options des compilateurs sinon on a un programme lent! C'est très vite dit. Les optimisations, il faut savoir où et comment les faire : la mise au point d'algorithmes et de structures de données performantes permet aisément de gagner un facteur 1000 -- de plus, c'est portable et maintenable --, l'utilisation intelligente du compilateur un facteur 100. Les petites optimisations de sioux permettent au mieux de faire gagner un facteur 10, peuvent rendre le code incorrect et sont difficiles à maintenir. Il peut arriver d'en avoir besoin, mais c'est loin d'être un passage obligé, c'est même plutôt quelque chose de dangereux. À bientôt. Le Farfadet Spatial Dernière modification par Le Farfadet Spatial (Le 12/05/2010, à 18:35) L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne ffw137 Re : Petit guide pour aider au choix d'un langage Merci pour cette réponse! Pour Emacs, comme je l'ai précisé cela est sans les pluggins mais bien un Emacs tout nu mais je l'apprend aussi en parallèle avec anjuta ainsi que vim, maintenant pour un premier venu qui a programmé sous windows, il est un fait qu'il faut qu'il s'habitue à l'ergonomie de Emacs ou Vim. Existe-t-il un bon site qui répertorie les pluggins de Emacs et leurs fonctions. Maintenant pour mes expériences de programmation, tu as surement vu que j'aime les systèmes embarqués des décodeurs qui sont en général des mono core avec beaucoup de hardware spécialisés autour comme les SC2000 / SC2005, maintenant pour l'optimisation, il est un fait que je me concentre sur une seule plateforme et ce n'est pas maintenable avec plusieurs. Pour les dernières compilations: j'ai eu affaire au couple diab/psos, gcc/système proprio de ALi donc des systèmes destinés à de l'embarqué donc je ne peux juger avec les avancées actuelles. Maintenant, je suis d'accord pour une bonne organisation des données et une bonne analyse en amont mais parfois je vois de l'utilisation de l'objet pour tout et n'importe quoi, la moindre variable devient un objet avec une tonne de méthodes sous le couvert de la facilité de maintenance et la réutilisation mais bon cela est juste mon impression. Maintenant, quand je vois la tonne de fichier généré par anjuta, c'est vrai que ça fait peur également! Allez je vais me mettre plus à Emacs alors! Pour les interfaces, j'utilise quand même glade en couple avec Emacs ou bien je dois utiliser autre chose? PS: Existe-t-il un pluggin emacs pour afficher l'arborescence des fichiers d'un projet si oui je suis satisfait. Merci pour ce post! Acer 5610-Epson DX3850-Samsung ML-1640-Lucid Samsung NC-10-Lucid-Ecran 17" "Un philosophe c'est quelqu'un qui est prêt à faire mourir les autres pour ses idées avant d'en changer quand vient son tour" (perso enfin je pense) Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Existe-t-il un bon site qui répertorie les pluggins de Emacs et leurs fonctions. Un excellent livre pour découvrir Emacs : Introduction à GNU Emacs Debra CAMERON, Bill ROSENBLATT et Eric S. Raymond O'Reilly Dans la documentation, il y a une section dédiée à Emacs avec des liens intéressants : Tout cela devrait te donner de bons points de départs. PS: Existe-t-il un pluggin emacs pour afficher l'arborescence des fichiers d'un projet si oui je suis satisfait. Oui, il est possible de naviguer dans l'arborescence d'un projet par l'intermédiaire de Emacs. Tu devrais trouver ce qu'il te faut avec les éléments que je t'ai donnés. pour un premier venu qui a programmé sous windows, il est un fait qu'il faut qu'il s'habitue à l'ergonomie de Emacs ou Vim. Oui, c'est certain : il faut changer ses habitudes, ce qui demande toujours du temps. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne
The only reason the interpreter would have returned between lines 14 and 18 is that it hit an exception. Because the debugger has a couple of nifty postmortem functions, I modified my script to use one, fired it up to see where it stopped, and started debugging from there. Here is the modified source file; pay special attention to the try/except block in the get_number_dict() method: #!/usr/bin/env python import pdb import string import sys class ConvertToDict: def __init__(self): self.tmp_dict = {} self.return_dict = {} def walk_string(self, some_string): '''walk given text string and return a dictionary. Maintain state in instance attributes in case we hit an exception''' l = string.split(some_string) for i in range(len(l)): key = str(i) self.tmp_dict[key] = int(l[i]) return_dict = self.tmp_dict self.return_dict = self.tmp_dict self.reset() return return_dict def reset(self): '''clean up''' self.tmp_dict = {} self.return_dict = {} def get_number_dict(self, some_string): '''do super duper exception handling here''' try: return self.walk_string(some_string) except: #modified exception handler - drop us into a debugger tb = sys.exc_info()[2] pdb.post_mortem(tb) #if we hit an exception, we can rely on tmp_dict being a backup to the point of the exception return self.tmp_dict def main(): ctd = ConvertToDict() for line in file(sys.argv[1]): line = line.strip() print "*" * 40 print "line>>", line print ctd.get_number_dict(line) print "*" * 40 if __name__ == "__main__": main() I chose to kick off the postmortem debugger in the except clause of the get_number_dict() method, because get_number_dict() is the closest exception handler to where the exception must be occurring in the walk_string() method. Here is the result of a run with a list immediately after it for context: jmjones@bean:~/debugger $ python example_debugger_pm.py example_debugger.data **************************************** line>> 1 2 3 4 5 6 7 8 9 10 {'1': 2, '0': 1, '3': 4, '2': 3, '5': 6, '4': 5, '7': 8, '6': 7, '9': \ 10, '8': 9} **************************************** **************************************** line>> 1 2 3 4 5 6 7 8 9 10 > /home/jmjones/debugger/example_debugger_pm.py(17)walk_string() -> self.tmp_dict[key] = int(l[i]) (Pdb) list 12 '''walk given text string and return a dictionary. 13 Maintain state in instance attributes in case we hit an exception''' 14 l = string.split(some_string) 15 for i in range(len(l)): 16 key = str(i) 17 -> self.tmp_dict[key] = int(l[i]) 18 return_dict = self.tmp_dict 19 self.return_dict = self.tmp_dict 20 self.reset() 21 return return_dict 22 def reset(self): This confirmed some of my earlier suspicions. It was hitting an exception in the for loop. Now my goal was to figure out what exception it hit and why: (Pdb) for e in sys.exc_info(): print "EXCEPTION>>>", e EXCEPTION>>> exceptions.AttributeError EXCEPTION>>> Pdb instance has no attribute 'do_for' EXCEPTION>>> <traceback object at 0x402ef784> What? My code was not even calling a do_for() method or trying to access any do_for attribute. This is a little gotcha that hounded me for a bit as I was trying to print the last exception from within this example code. You should be able to tell what is going on with a little insight from the traceback module: (Pdb) import traceback (Pdb) traceback.print_stack() File "example_debugger_pm.py", line 48, in ? main() File "example_debugger_pm.py", line 44, in main print ctd.get_number_dict(line) File "example_debugger_pm.py", line 33, in get_number_dict pdb.post_mortem(tb) File "/usr/local/python24/lib/python2.4/pdb.py", line 1009, in post_mortem p.interaction(t.tb_frame, t) File "/usr/local/python24/lib/python2.4/pdb.py", line 158, in interaction self.cmdloop() File "/usr/local/python24/lib/python2.4/cmd.py", line 142, in cmdloop stop = self.onecmd(line) File "/usr/local/python24/lib/python2.4/cmd.py", line 218, in onecmd return self.default(line) File "/usr/local/python24/lib/python2.4/pdb.py", line 167, in default exec code in globals, locals File "<stdin>", line 1, in ? Basically, the Python interpreter keeps track of any exceptions that running code raises; it saves the last traceback when running code hits an exception. The debugger is just another piece of code that the interpreter runs. When a user feeds the debugger commands, those commands may raise exceptions within the debugger itself. In this case, I gave the debugger a for statement. It first tried to execute a debugger for command by calling the do_for() method. That raised the exception above. Such debugger exceptions can potentially pollute the interpreter with unexpected exceptions and tracebacks that we users don't really want to see when trying to debug our own code. Maybe there is a better way of writing a debugger than combining the debugger code and the debugged code in the same interpreter as shown here, but the Python team has produced a pretty tricky, complex piece of code that otherwise works really well.
UPDATE: Thanks so much for all the feedback! I’m going to look at using flock as well, and I’ll write that up soon. Imagine you have a script that archives a bunch of data by copying it to another box. You use cron to schedule that script to run every hour, because normally, the script finishes in about thirty (30) minutes or so. But every so often, maybe when your application gets really popular, the cron job takes more than an hour. Maybe it takes three hours this one time. And during that time, cron starts up two more copies of your script. That can cause all sorts of havoc, where two or more scripts each try to modify the same file, for example. In this scenario, you need a way to prevent those second and third (and maybe fourth and fifth, etc) scripts from starting as long as one is already going. It would be very helpful when the script started, it first checked if another process was already running. If one is already running, then this new script should just immediately exit. But if no other script is running, then this script should get to work. Here’s a simple method for doing that: 1. When the script starts, the first thing it does it look for a file in /tmp named something like /tmp/myscript.pid. 2. If that file exists, then the script reads that file. The file holds a process ID (pid). The script now checks if that any process with that pid is running. 3. If there is not a process running with this pid, then probably what happened was the old script crashed without cleaning up this pid file. So, this script should get to work. But if there is a process running with that pid, then there is already a running instance of this script, and so this script should just immediately exit. There’s a tiny risk with this approach that I’ll discuss at the end of this post. 4. Depending on what happened in step 3, the script should exit at this point, or it should get to work. Before the script gets to the real work though, it should write its own process ID into /tmp/myscript.pid. That’s the pseudocode, now here’s two python functions to help make it happen: import os def pid_is_running(pid):     """     Return pid if pid is still going.     >>> import os     >>> mypid = os.getpid()     >>> mypid == pid_is_running(mypid)     True     >>> pid_is_running(1000000) is None     True     """     try:         os.kill(pid, 0)     except OSError:         return     else:         return pid def write_pidfile_or_die(path_to_pidfile):     if os.path.exists(path_to_pidfile):         pid = int(open(path_to_pidfile).read())         if pid_is_running(pid):             print("Sorry, found a pidfile!  Process {0} is still running.".format(pid))             raise SystemExit         else:             os.remove(path_to_pidfile)     open(path_to_pidfile, 'w').write(str(os.getpid()))     return path_to_pidfile And here’s a trivial script that does nothing but check for a pidfile and then sleep for a few seconds: if __name__ == '__main__':     write_pidfile_or_die('/tmp/pidfun.pid')     time.sleep(5) # placeholder for the real work     print('process {0} finished work!'.format(os.getpid())) Try running this in two different terminals, and you’ll see that the second process immediately exits as long as the first process is still running. In the worst case, this isn’t perfect Imagine that the first process started up and the operating system gave it process ID 99. Then imagine that the process crashed without cleaning up its pidfile. Now imagine that some completely different process started up, and the operating system happens to recycle that process ID 99 again and give that to the new process. Now, when our cron job comes around, and starts up a new version of our script, then our script will read the pid file and check for a running process with process ID 99. And in this scenario, the script will be misled and will shut down. So, what to do? Well, first of all, understand this is an extremely unlikely scenario. But if you want to prevent this from happening, I suggest you make two tweaks: 1. Do your absolute best to clean up that pidfile. For example, use python’s sys.excepthook or atexit functions to make sure that the pid file is gone. 2. Write more than just the process ID into the pid file. For example, you can use ps and then write the process name to the pid file. Then change how you check if the process exists. In addition to checking for a running process with the same pid, check for the same pid and the same data returned from ps for that process. Check back soon and I’ll likely whip up some kind of some simple library that offers a context manager that does it to the extreme case described above.
PhoneGap + Zepto + Bootstrap function setupFixedFix() { if (isFixedBroken()) { $('.container-fluid').css({'position': 'static'}); $('.actionsbar, .navbar').css({'position': 'absolute'}); fixFixed(); $(window).bind('scroll', fixFixed); $('.mobile-page').bind('touchend', fixFixed); } } function isFixedBroken(){ // Feature detection didnt seem to work so we check the user agent instead return (ED.util.isIOS() && navigator.userAgent.match(/[5-9]_[0-9]/) === null); } function fixFixed() { if (isFixedBroken()) { $('.actionsbar').css({'top': (window.pageYOffset) + 'px'}); $('.navbar').css({'top': (window.pageYOffset + window.innerHeight - 30) + 'px'}); } } ED.util.addTouchOrClickHandler($('.mobile-log-a'), openPageLink); ED.util.addClickHandler($('.mobile-footer-a'), openPageLink); ED.util.addClickHandler($('.mobile-stream-a'), openStreamLink); function addTouchOrClickHandler(dom, callback, logThis) { if (useTouchEvents()) { dom.each(function() { $(this).unbind('tap', callback); $(this).bind('tap', callback); $(this).bind('touchstart', function(e) { e.preventDefault(); var item = e.currentTarget; if (ISTOUCHING) return; item.moved = false; ISTOUCHING = true; item.startX = e.touches[0].pageX; item.startY = e.touches[0].pageY; $(item).addClass('active'); }); $(this).bind('touchmove', function(e) { var item = e.currentTarget; if (Math.abs(e.touches[0].pageX - item.startX) > 10 || Math.abs(e.touches[0].pageY - item.startY) > 10) { item.moved = true; $(item).removeClass('active'); } }); $(this).bind('touchend', function(e) { var item = e.currentTarget; ISTOUCHING = false; if(!item.moved) { $(item).trigger('tap'); } setTimeout(function() { $(item).removeClass('active'); }, 300); delete item.moved; }); }); } else { dom.unbind('click', callback).bind('click', callback); } } def click_button(self, selector): if self.driver.name == 'iPhone': self.driver.execute_script('$("%s").trigger("tap")' % (selector)) else: try: self.get_el(selector).click() function show() { ED.util.resetScroll(); ED.util.makeAutoResize($(DOM.notesInput)); ED.util.putCursorAtEnd($(DOM.notesInput)); } function resetScroll(top) { top = top || 0; $(document).scrollTop(top); window.setTimeout(function() { $(document).scrollTop(top); }, 10); } ☞ Device Bugs: #1 <input type="number" step="0.01"> function hideKeyboard() { $('input, textarea').blur(); if (ED.util.isIOS()) { document.activeElement.blur(); } if (ED.util.isAndroid()) { var field = $('<input type="text">'); $('#mobile-logs-page').append(field); setTimeout(function() { field.focus(); setTimeout(function() { field.hide(); }, 50); }, 50); } } /** * This is a hack to make text input focus work in Android/PG * where calling el.focus() doesn't actually have the * blinking cursor effect = scumbag. * @param {Zepto} $el A zepto element. */ ws.focus = function($el) { var el = $el.get(0); el.focus(); el.setSelectionRange && el.setSelectionRange(0, 0); }; Courtesy @elsigh canvasContext.drawImage(img, x, y, width, height); var dataUrl = canvas.toDataURL('image/png'); if (dataUrl.indexOf('data:image/png') == -1) { onFail('Got back an invalid data URL'); } else { onSuccess(dataUrl.replace('data:image/png;base64,', '')); } var cachedSupportsDataURL; function supportsDataURL() { if (cachedSupportsDataURL === undefined) { var c = document.createElement('canvas'); var dataUrl = c.toDataURL('image/png'); cachedSupportsDataURL = (dataUrl.indexOf('data:image/png') === 0); } return cachedSupportsDataURL; } var MSG_LOG_OFFLINE = 'We can\'t connect to the network now, so your log may be out of date.'; runIfOnline(function() { fetchNewData(); }, MSG_LOG_OFFLINE); } function runIfOnline(onlineFunc, message, offlineFunc) { message = message || 'Sorry, we can\'t connect to the network right now.'; if (isOnline()) { try { onlineFunc(); } catch(e) { logError(e); } } else { alert(message); if (offlineFunc) { try { offlineFunc(); } catch(ee) { logError(ee); } } } } function isOnline() { // Presume online unless PhoneGap or HTML5 tell us otherwise. if (navigator.network && navigator.network.connection.type == Connection.NONE && 0) { ED.util.log('Found Connection.NONE'); return false; } if (navigator.onLine === false) { ED.util.log('Found navigator.onLine is false'); return false; } return true; } var timedEvents = []; function timeEvent(name) { timedEvents.push({'name': name || 'unnamed', time: Date.now()}); } function showTimedEvents() { var timeText = ''; var timeHtml = '<table>'; for (var i = 0; i < timedEvents.length; i++) { var timedEvent = timedEvents[i]; timeText += timedEvent.name + ': ' + timedEvent.time; var diff = ''; if (i > 0) { diff = (timedEvent.time - timedEvents[i-1].time); timeText += ' (' + diff + 'ms elapsed)'; } timeHtml += '<tr><td>' + timedEvent.name + '<td>' + timedEvent.time + '<td>' + diff; timeText += '\n'; } console.log(timeText); document.body.innerHTML += timeHtml; } <html> <head> <script> // Timer functions </script> <script>timeEvent('Before CSS');</script> <link rel="stylesheet" href="css/all-phonegap-min.css?v=10201550"/> <script>timeEvent('After CSS');</script> </head> <body> <div>HTML here (more than this)</div> <script>timeEvent('After HTML');</script> <script src="js/libs/jquery-1.6.2.min.js"></script> <script>timeEvent('After jQuery script tag');</script> <script src="js/all-phonegap-min.js?v=10201550"></script> <script>timeEvent('After other script tag');</script> <script> $(document).ready(function() { timeEvent('After document ready'); myCustomMobileFunction(); timeEvent('After ready JS called'); showTimedEvents(); }); </script> </body> </html> jQuery -> Zepto Shaved: 22% onload -> deviceready Shaved: 67% document.addEventListener("DOMContentLoaded", function() { ED.mobile.setupMobile(); }); document.addEventListener('deviceready', function() { ED.mobile.setupPhonegap(); }, false); function setupMobile() { // Sets up the page CSS // Binds events to DOM } function setupPhonegap() { // Shows splash page // Fetches data // Binds PhoneGap events } ☞ Get to deviceready faster on Android ☞ Working Around Android Webkit .android { .modal { @include box-shadow(none); @include background-clip(border-box); @include border-radius(0px); border: 1px solid black; } } $(window).on('scroll', $.throttle(500, loadVisibleImages)); $textAreas.autoResizer({resizeOnChange: !isAndroid()}); window.setTimeout(function() { ED.shared.setupStream(); ED.shared.setupStreamTimer(); }, 2000); window.setTimeout(function() { ED.shared.maybeFetchStream(); }, 100); window.setTimeout(function() { fetchNewData(); }, 1000); ☞ Zakas: Responsive Interfaces
I am new to python and coding in general. I am trying to read from a text file which has path names on each line. I would like to read the text file line by line and split the line strings into drive, path and file name. Here is my code thus far: import os,sys, arcpy ## Open the file with read only permit f = open('C:/Users/visc/scratch/scratch_child/test.txt') for line in f: (drive,path,file) = os.path.split(line) print line.strip() #arcpy.AddMessage (line.strip()) print('Drive is %s Path is %s and file is %s' % (drive, path, file)) I get the following error: File "C:/Users/visc/scratch/simple.py", line 14, in <module> (drive,path,file) = os.path.split(line) ValueError: need more than 2 values to unpack I do not receive this error when I only want the path and file name.
If you visit DuckDuck Go API Page, you will find some notes about using the API. The first notes says clearly that: As this is a Zero-click Info API, most deep queries (non topic names) will be blank. An here's the list of those fields: Abstract: "" AbstractText: "" AbstractSource: "" AbstractURL: "" Image: "" Heading: "" Answer: "" Redirect: "" AnswerType: "" Definition: "" DefinitionSource: "" DefinitionURL: "" RelatedTopics: [ ] Results: [ ] Type: "" So it might be a pity, but their API just truncates a bunch of results and does not give them to you; possibly to work faster, and seems like nothing can be done except using DuckDuckGo.com. So, obviously, in that case API is not the way to go. As for me, I see only one way out left: retrieving raw html from duckduckgo.com and parsing it using, e.g. html5lib (it worth to mention that their html is well-structured). It also worth to mention that parsing html pages is not the most reliable way to scrap data, because html structure can change, while API usually stays stable until changes are publicly announced. Here's and example of how can be such parsing achieved with BeautifulSoup: from BeautifulSoup import BeautifulSoup import urllib import re site = urllib.urlopen('http://duckduckgo.com/?q=example') data = site.read() parsed = BeautifulSoup(data) topics = parsed.findAll('div', {'id': 'zero_click_topics'})[0] results = topics.findAll('div', {'class': re.compile('results_*')}) print results[0].text This script prints: u'Eixample, an inner suburb of Barcelona with distinctive architecture' The problem of direct querying on the main page is that it uses JavaScript to produce required results (not related topics), so you can use HTML version to get results only. HTML version has different link: Let's see what we can get: site = urllib.urlopen('http://duckduckgo.com/html/?q=example') data = site.read() parsed = BeautifulSoup(data) first_link = parsed.findAll('div', {'class': re.compile('links_main*')})[0].a['href'] The result stored in first_link variable is a link to the first result (not a related search) that search engine outputs: http://www.iana.org/domains/example To get all the links you can iterate over found tags (other data except links can be received similar way) for i in parsed.findAll('div', {'class': re.compile('links_main*')}): print i.a['href'] http://www.iana.org/domains/example https://twitter.com/example https://www.facebook.com/leadingbyexample http://www.trythisforexample.com/ http://www.myspace.com/leadingbyexample?_escaped_fragment_= https://www.youtube.com/watch?v=CLXt3yh2g0s https://en.wikipedia.org/wiki/Example_(musician) http://www.merriam-webster.com/dictionary/example ... Note that HTML-only version contains only results, and for related search you must use JavaScript version. (vithout html part in url).
I am trying to install wine on a 64-bit Natty. It was installed, but one of my regular update & dist-upgrades removed it (didn't pay enough attention to which packages would be removed). Now when I'm trying to install it, I get the following error: The following packages have unmet dependencies: wine : Depends: wine1.3 but it is not going to be installed Depends: ia32-libs (>= 1.6) but it is not going to be installed E: Broken packages I found this question on askubuntu, but the accepted answer (change the mirror to the main one) didn't work for me. I also tried to disable all sources that aren't enabled after a clean install, do an update an install wine, didn't work. Here's my /etc/apt/sources.list (sans comments for brewity): deb http://us.archive.ubuntu.com/ubuntu/ natty main restricted multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ natty main universe restricted multiverse deb http://us.archive.ubuntu.com/ubuntu/ natty-updates main restricted multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ natty-updates main universe restricted multiverse deb http://us.archive.ubuntu.com/ubuntu/ natty universe deb http://us.archive.ubuntu.com/ubuntu/ natty-updates universe deb http://archive.canonical.com/ubuntu natty partner deb-src http://archive.canonical.com/ubuntu natty partner deb http://us.archive.ubuntu.com/ubuntu/ natty-security main restricted multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ natty-security main universe restricted multiverse deb http://us.archive.ubuntu.com/ubuntu/ natty-security universe deb http://linux.dropbox.com/ubuntu natty main deb-src http://linux.dropbox.com/ubuntu natty main deb http://ppa.launchpad.net/libv4l/ppa/ubuntu natty main deb-src http://ppa.launchpad.net/libv4l/ppa/ubuntu natty main deb http://apt.mucommander.com stable main non-free contrib deb http://extras.ubuntu.com/ubuntu natty main deb http://archive.canonical.com/ natty partner deb-src http://archive.canonical.com/ natty partner And here's the contents of the files in /etc/apt/sources.list.d/: deb http://ppa.launchpad.net/gm-notify-maintainers/ppa/ubuntu natty main deb http://ppa.launchpad.net/gm-notify-maintainers/ppa/ubuntu natty main deb http://ppa.launchpad.net/mozillateam/firefox-next/ubuntu natty main deb-src http://ppa.launchpad.net/mozillateam/firefox-next/ubuntu natty main deb http://deb.opera.com/opera/ stable non-free deb http://ppa.launchpad.net/resmo/git-ftp/ubuntu natty main deb-src http://ppa.launchpad.net/resmo/git-ftp/ubuntu natty main deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu natty main deb http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu natty main deb-src http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu natty main
How would you divide a number by 3 without using *, /, +, -, %, operators? The number may be signed or unsigned. There is a simple function I found here. But it's using the // replaces the + operator int add(int x, int y) { while(x) { int t = (x & y) <<1; y ^= x; x = t; } return y; } int divideby3 (int num) { int sum = 0; while (num > 3) { sum = add(num >> 2, sum); num = add(num >> 2, num & 3); } if (num == 3) sum = add(sum, 1); return sum; } As Jim commented this works because: Write the program in Pascal and use the Since the question is tagged c, you can probably write a function in Pascal and call it from your C program; the method for doing so is system-specific. But here's an example that works on my Ubuntu system with the Free Pascal unit Divide_By_3; interface function div_by_3(n: integer): integer; cdecl; export; implementation function div_by_3(n: integer): integer; cdecl; begin div_by_3 := n div 3; end; end. #include <stdio.h> #include <stdlib.h> extern int div_by_3(int n); int main(void) { int n; fputs("Enter a number: ", stdout); fflush(stdout); scanf("%d", &n); printf("%d / 3 = %d\n", n, div_by_3(n)); return 0; } $ ./main Enter a number: 100 100 / 3 = 33 This is not as tricky as it sounds, because you said "without using the [..] unsigned div_by(unsigned const x, unsigned const by) { unsigned floor = 0; for (unsigned cmp = 0, r = 0; cmp <= x;) { for (unsigned i = 0; i < by; i++) cmp++; // that's not the + operator! floor = r; r++; // neither is this. } return floor; } then just say // Note: itoa is non-standard but actual implementations // don't seem to handle negative when base != 10. int div3(int i) { char str[42]; sprintf(str, "%d", INT_MIN); // Put minus sign at str[0] if (i>0) // Remove sign if positive str[0] = ' '; itoa(abs(i), &str[1], 3); // Put ternary absolute value starting at str[1] str[strlen(&str[1])] = '\0'; // Drop last digit return strtol(str, NULL, 3); // Read back result } To divide a 32-bit number by 3 one can multiply it by Now all that's left to do is to implement multiplication using bit operations and shifts... log(pow(exp(number),0.33333333333333333333)) /* :-) */ Idiotic conditions call for an idiotic solution: #include <stdio.h> #include <stdlib.h> int main() { FILE * fp=fopen("temp.dat","w+b"); int number=12346; int divisor=3; char * buf = calloc(number,1); fwrite(buf,number,1,fp); rewind(fp); int result=fread(buf,divisor,number,fp); printf("%d / %d = %d", number, divisor, result); free(buf); fclose(fp); return 0; } If also the decimal part is needed, just declare If you write 30 bytes then read back the file in units of 3, you get 10 "units". 30 / 3 = 10 #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int num = 1234567; int den = 3; div_t r = div(num,den); // div() is a standard C function. printf("%d\n", r.quot); return 0; } Use inline assembler: (also works for negative numbers) #include <stdio.h> int main() { int dividend = -42, divisor = 3, quotient, remainder; __asm__ ( "movl %2, %%edx;" "sarl $31, %%edx;" "movl %2, %%eax;" "movl %3, %%ebx;" "idivl %%ebx;" : "=a" (quotient), "=d" (remainder) : "g" (dividend), "g" (divisor) : "ebx" ); printf("%i / %i = %i, remainder: %i\n", dividend, divisor, quotient, remainder); } int divideByThree(int num) { return (fma(num, 1431655766, 0) >> 32); } Where fma is a standard library function defined in Here's my solution: public static int div_by_3(long a) { a <<= 30; for(int i = 2; i <= 32 ; i <<= 1) { a = add(a, a >> i); } return (int) (a >> 32); } public static long add(long a, long b) { long carry = (a & b) << 1; long sum = (a ^ b); return carry == 0 ? sum : add(carry, sum); } First, note that 1/3 = 1/4 + 1/16 + 1/64 + ... Now, the rest is simple! a/3 = a * 1/3 a/3 = a * (1/4 + 1/16 + 1/64 + ...) a/3 = a/4 + a/16 + 1/64 + ... a/3 = a >> 2 + a >> 4 + a >> 6 + ... Now all we have to do is add together these bit shifted values of a! Oops! We can't add though, so instead, we'll have to write an add function using bit-wise operators! If you're familiar with bit-wise operators, my solution should look fairly simple... but just in-case you aren't, I'll walk through an example at the end. Another thing to note is that first I shift left by 30! This is to make sure that the fractions don't get rounded off. 11 + 6 1011 + 0110 sum = 1011 ^ 0110 = 1101 carry = (1011 & 0110) << 1 = 0010 << 1 = 0100 Now you recurse! 1101 + 0100 sum = 1101 ^ 0100 = 1001 carry = (1101 & 0100) << 1 = 0100 << 1 = 1000 Again! 1001 + 1000 sum = 1001 ^ 1000 = 0001 carry = (1001 & 1000) << 1 = 1000 << 1 = 10000 One last time! 0001 + 10000 sum = 0001 ^ 10000 = 10001 = 17 carry = (0001 & 10000) << 1 = 0 Done! It's simply carry addition that you learned as a child! This implementation a / 3 = a/4 + a/4^2 + a/4^3 + ... + a/4^i + ... = f(a, i) + a * 1/3 * 1/4^i f(a, i) = a/4 + a/4^2 + ... + a/4^i Suppose the reslut of Yet another solution. This should handle all ints (including negative ints) except the min value of an int, which would need to be handled as a hard coded exception. This basically does division by subtraction but only using bit operators (shifts, xor, & and complement). For faster speed, it subtracts 3 * (decreasing powers of 2). In c#, it executes around 444 of these DivideBy3 calls per millisecond (2.2 seconds for 1,000,000 divides), so not horrendously slow, but no where near as fast as a simple x/3. By comparison, Coodey's nice solution is about 5 times faster than this one. public static int DivideBy3(int a) { bool negative = a < 0; if (negative) a = Negate(a); int result; int sub = 3 << 29; int threes = 1 << 29; result = 0; while (threes > 0) { if (a >= sub) { a = Add(a, Negate(sub)); result = Add(result, threes); } sub >>= 1; threes >>= 1; } if (negative) result = Negate(result); return result; } public static int Negate(int a) { return Add(~a, 1); } public static int Add(int a, int b) { int x = 0; x = a ^ b; while ((a & b) != 0) { b = (a & b) << 1; a = x; x = a ^ b; } return x; } This is c# because that's what I had handy, but differences from c should be minor. It is easily possible on the Setun computer. To divide an integer by 3, shift right by 1 place. I'm not sure whether it's strictly possible to implement a conforming C compiler on such a platform though. We might have to stretch the rules a bit, like interpreting "at least 8 bits" as "capable of holding at least integers from -128 to +127". First that I've come up with. irb(main):101:0> div3 = -> n { s = '%0' + n.to_s + 's'; (s % '').gsub(' ', ' ').size } => #<Proc:0x0000000205ae90@(irb):101 (lambda)> irb(main):102:0> div3[12] => 4 irb(main):103:0> div3[666] => 222 This one is the classical division algorithm in base 2: #include <stdio.h> #include <stdint.h> int main() { uint32_t mod3[6] = { 0,1,2,0,1,2 }; uint32_t x = 1234567; // number to divide, and remainder at the end uint32_t y = 0; // result int bit = 31; // current bit printf("X=%u X/3=%u\n",x,x/3); // the '/3' is for testing while (bit>0) { printf("BIT=%d X=%u Y=%u\n",bit,x,y); // decrement bit int h = 1; while (1) { bit ^= h; if ( bit&h ) h <<= 1; else break; } uint32_t r = x>>bit; // current remainder in 0..5 x ^= r<<bit; // remove R bits from X if (r >= 3) y |= 1<<bit; // new output bit x |= mod3[r]<<bit; // new remainder inserted in X } printf("Y=%u\n",y); } Use cblas, included as part of OS X's Accelerate framework. [02:31:59] [william@relativity ~]$ cat div3.c #import <stdio.h> #import <Accelerate/Accelerate.h> int main() { float multiplicand = 123456.0; float multiplier = 0.333333; printf("%f * %f == ", multiplicand, multiplier); cblas_sscal(1, multiplier, &multiplicand, 1); printf("%f\n", multiplicand); } [02:32:07] [william@relativity ~]$ clang div3.c -framework Accelerate -o div3 && ./div3 123456.000000 * 0.333333 == 41151.957031 Didn't cross-check if this answer is already published. If the program need to be extended to floating numbers, the numbers can be multiplied by 10*number of precision needed and then the following code can be again applied. #include <stdio.h> int main() { int aNumber = 500; int gResult = 0; int aLoop = 0; int i = 0; for(i = 0; i < aNumber; i++) { if(aLoop == 3) { gResult++; aLoop = 0; } aLoop++; } printf("Reulst of %d / 3 = %d", aNumber, gResult); return 0; } This should work for any divisor, not only three. Currently only for unsigned, but extending it to signed should not be that difficult. #include <stdio.h> unsigned sub(unsigned two, unsigned one); unsigned bitdiv(unsigned top, unsigned bot); unsigned sub(unsigned two, unsigned one) { unsigned bor; bor = one; do { one = ~two & bor; two ^= bor; bor = one<<1; } while (one); return two; } unsigned bitdiv(unsigned top, unsigned bot) { unsigned result, shift; if (!bot || top < bot) return 0; for(shift=1;top >= (bot<<=1); shift++) {;} bot >>= 1; for (result=0; shift--; bot >>= 1 ) { result <<=1; if (top >= bot) { top = sub(top,bot); result |= 1; } } return result; } int main(void) { unsigned arg,val; for (arg=2; arg < 40; arg++) { val = bitdiv(arg,3); printf("Arg=%u Val=%u\n", arg, val); } return 0; } #!/bin/ruby def div_by_3(i) i.div 3 # always return int http://www.ruby-doc.org/core-1.9.3/Numeric.html#method-i-div end Solution using fma() library function, works for any positive number: #include <stdio.h> #include <math.h> int main() { int number = 8;//Any +ve no. int temp = 3, result = 0; while(temp <= number){ temp = fma(temp, 1, 3); //fma(a, b, c) is a library function and returns (a*b) + c. result = fma(result, 1, 1); } printf("\n\n%d divided by 3 = %d\n", number, result); } Here it is in Python with, basically, string comparisons and a state machine. def divide_by_3(input): to_do = {} enque_index = 0 zero_to_9 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) leave_over = 0 for left_over in (0, 1, 2): for digit in zero_to_9: # left_over, digit => enque, leave_over to_do[(left_over, digit)] = (zero_to_9[enque_index], leave_over) if leave_over == 0: leave_over = 1 elif leave_over == 1: leave_over = 2 elif leave_over == 2 and enque_index != 9: leave_over = 0 enque_index = (1, 2, 3, 4, 5, 6, 7, 8, 9)[enque_index] answer_q = [] left_over = 0 digits = list(str(input)) if digits[0] == "-": answer_q.append("-") digits = digits[1:] for digit in digits: enque, left_over = to_do[(left_over, int(digit))] if enque or len(answer_q): answer_q.append(enque) answer = 0 if len(answer_q): answer = int("".join([str(a) for a in answer_q])) return answer <?php $a = 12345; $b = bcdiv($a, 3); ?> > SELECT 12345 DIV 3; a:= 12345; b:= a div 3; Since it's from Oracle, how about a lookup table of pre calculated answers. :-D int div3(int x) { int reminder = abs(x); int result = 0; while(reminder >= 3) { result++; reminder--; reminder--; reminder--; } return result; } Using counters is a basic solution: int DivBy3(int num) { int result = 0; int counter = 0; while (1) { if (num == counter) //Modulus 0 return result; counter = abs(~counter); //++counter if (num == counter) //Modulus 1 return result; counter = abs(~counter); //++counter if (num == counter) //Modulus 2 return result; counter = abs(~counter); //++counter result = abs(~result); //++result } } It is also easy to perform a modulus function, check the comments. Using a Linux shell script: #include <stdio.h> int main() { int number = 30; char command[25]; snprintf(command, 25, "echo $((%d %c 3)) ", number, 47); system( command ); return 0; } The following script generates a C program that solves the problem without using the operators #!/usr/bin/env python3 print('''#include <stdint.h> #include <stdio.h> const int32_t div_by_3(const int32_t input) { ''') for i in range(-2**31, 2**31): print(' if(input == %d) return %d;' % (i, i / 3)) print(r''' return 42; // impossible } int main() { const int32_t number = 8; printf("%d / 3 = %d\n", number, div_by_3(number)); } ''') It's really quite easy. if (number == 0) return 0; if (number == 1) return 0; if (number == 2) return 0; if (number == 3) return 1; if (number == 4) return 1; if (number == 5) return 1; if (number == 6) return 2; (I have of course omitted some of the program for the sake of brevity.) If the programmer gets tired of typing this all out, I'm sure that he or she could write a separate program to generate it for him. I happen to be aware of a certain operator, Would it be cheating to use the For example, in Javacript, you can do function div3 (n) { var div = String.fromCharCode(47); return eval([n, div, 3].join("")); } Good 'ol $ num=1337; printf "scale=5;${num}\x2F3;\n" | bc 445.66666 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?
The code below works (it will eventually pull records from a database via SQL), but I am having trouble understanding why the assert statement in the code below works. def build_row(table, cols): """Build a class that creates instances of specific rows""" class DataRow: """Generic data row class, specialized by surrounding function""" def __init__(self, data): """Uses data and column names to inject attributes""" assert len(data)==len(self.cols) for colname, dat in zip(self.cols, data): setattr(self, colname, dat) def __repr__(self): return "{0}_record({1})".format(self.table, ", ".join(["{0!r}".format(getattr(self, c)) for c in self.cols])) DataRow.table = table DataRow.cols = cols.split() return DataRow When is the length of 'data' determined and how is it guaranteed to be the same length as 'self.cols'? Will someone please explain this behavior?
what i'm trying to do is to read each line of the file then put it into other function called handleLine which then creates output, numericgrade calculates the overall percentage and then lettergrade assigns a grade. for example in file i have "name, last name", classid, exam, final and i want it to output full name, score , grade def main(): fin=open("scores.csv", "r") fout=open("grades.csv", "w") fout.write('"Name", "Score", "Grade"\n') line=fin.readlines()[1:] for line in line: line=line.split(",") handleLine(line) fout.write('"' + lname + "," + fname + '" ,' + score +", " + grade+ ' ", ') def numericGrade(midterm, final): score=0.4*float(midterm) + (0.6 * float(final)) def letterGrade(score): grade = None if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >=70: grade ="C" elif score >= 60: grade = "D" else: grade = "F" def handleLine(line): fout=open("grades.csv", "w") fname= line[1][1 : -1] lname= line[0][1 : ] midterm= line[2] final = line[3] numericGrade(midterm, final) score = numericGrade(midterm,final) grade = letterGrade(score) return lname, fname, score, grade if __name__=="__main__": main() I'm having trouble putting one function to another, now it says that lname is not defined in line 14. Im really lost now. EDIT: I have fixed the lname, fname, score, grade= handleLine(line) but i have an error now in line 14 TypeError: cannot concatenate 'str' and 'NoneType' objects
I parse a .txt like this: def parse_file(src): for line in src.readlines(): if re.search('SecId', line): continue else: cols = line.split(',') Time = cols[4] output_file.write('{}\n'.format( Time)) I think cols are lists that I could use index. Although it succeeds in printing out correct result as I want, there exists an out of range error: File "./tdseq.py", line 37, in parse_file Time = cols[4] IndexError: list index out of range make: *[all] Error 1 Data I use: I10.FE,--,xx,xxxx,13450,tt,tt,tt,33,22,22:33:44