text
stringlengths
256
65.5k
Mathieu11 [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Edit admin : le sommaire renvoyant vers les différents scripts se trouve désormais sur cette page de la documentation. Les nouveaux scripts peuvent donc être discutés ici, puis inclus dans le sommaire J'ouvre ce sujet pour proposer a chacun de poster les scripts qu'il trouve utiles/pratiques ou de soumettre l'idee d'un script qui lui semblerait pratique. S'il était épinglé peut etre que ca permettrait un bon échange entre tout le monde et éviterai a certains de "ré-inventer la roue"... Pour faciliter la lecture je vais faire un sommaire avec lien vers chaque script. De meme je pense que pour faciliter cette lecture et la creation du sommaire chacun d'entre nous ne devrait placer qu'UN seul script par post (si ceux qui ont deja poste peuvent modifier je serais reconnaissant) et le poster sous une forme qui ressemble a ceci : http://doc.ubuntu-fr.org/scripts_utiles NB : Vous devez rendre ces scripts executables avant leur utilisation : Placez vous dans le dossier ou se situe le script, ouvrez un terminal et tapez chmod +x $nom_du_script (en remplacant $nom_du_script par le nom du script en question :P :D) Dernière modification par xabilon (Le 03/11/2008, à 15:05) Vostro 1400 Hors ligne messi89 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) merci mon frere pour le partage l'amour est comme les cookies..sa durée de vie doit être courte pour des raisons de sécurité Hors ligne Mathieu11 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) De nada. Si jamais ca interesse du monde. Vostro 1400 Hors ligne jadoman Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) C'est une bonne idée, merci c'est bien cool. à+:cool: Processor Intel dual-core E7400 2.80ghz. Memory 8 go crucial ddr2 dual-chanel Moniteur 23 pouces ASUS VH236 Résolution 1920*1080 pixels linuxmint katya 64; ubuntu ultimate 3.4; sabayon; kubuntu 12.04 nvidia gtx 560 gigabyte Hors ligne Krevan Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) 4/ ENCODAGE VERS PSP Voilà le script que j'ai écrit pour encoder rapidement, en ligne de commande, des fichiers pour ma PSP. Il fonctionne grâce à FFMPEG, celui-ci est donc indispensable. Téléchargez le script [en cliquant ici] ou bien ouvrez créez un nouveau fichier et copiez-le à l'intérieur. #!/bin/sh # Version 0.3-1 # Script sous licence GNU GPL sortant = entrant"-psp" echo " __ __"; echo " / / / FFMPEG"; echo " / / / /| Script Encodeur Express pour PSP"; echo "| / / / | Version 0.2-3"; echo "|/ / / /"; echo " /_/ /__ "; # Prompt demandant le format sortant désiré (mp4 ou avi). echo ; echo "Choix du format vidéo sortant" echo "1. MP4"; echo "2. AVI"; echo "Merci d'entrer le numéro correspondant"; echo -n "> " read format && # Prompt demandant le chemin des fichiers entrant et sortant. echo ; echo "Choix de la vidéo à encoder"; echo -n "> "; read entrant && # Simulation « inutile » (mais classe) de chargement. echo ; echo -n "Lancement du script"; sleep 1; echo -n .; sleep 1; echo -n .; sleep 1; echo .; sleep 1; # Condition vérifiant le format désiré et encode la vidéo en conséquence. if [ "$format" = "1" ]; then { ffmpeg -i $entrant -f psp -r 29.97 -b 768k -ar 24000 -ab 64k -s 480x272 output-psp.mp4; } elif [ "$format" = "2" ]; then { ffmpeg -i $entrant -vcodec xvid -acodec mp3 -b 1000kb -s 480x272 output-psp.avi; } else { echo "«$format» n'est pas une valeur correcte, vérifiez que vous avez bien tapé le chiffre correspondant au format désiré et relancez le programme."; exit 0; } fi # Suppression des sources. echo; echo; echo -n "Voulez-vous supprimer le fichier source «$entrant» (O/N) ? " read supprimer_sources && if [ "$supprimer_sources" = "O" ] || [ "supprimer_sources" = "o" ]; then { echo -n "Suppression en cours... "; rm $entrant; echo "OK"; } else { echo "Le fichier source ne sera pas supprimé."; } fi # Fin. echo ; echo "Le script s'est correctement terminé. Il est tout de même conseillé de vérifier la vidéo."; sleep 3; exit 0; Si vous avez des doutes quand à l'installation du script voici la marche à suivre, $ signalant une nouvelle entrée (vous ne devez pas l'écrire). # Vérifiez que vos dépots Medibuntu soient activés. $ sudo apt-get install ffmpeg # Téléchargez et installez : $ wget http://sh-theque.eg2.fr/scripts/seep.tar.gz $ tar -zxvf seep.tar.gz $ mv seep .seep $ sudo chmod +x .seep # Executez le tout ! $ ./.seep N'hésitez pas à me signaler vos problèmes. Dernière modification par Krevan (Le 30/03/2008, à 20:43) « Ce n'est pas une miette de pain, c'est la moisson du monde entier qu'il faut à la race humaine, sans exploiteur et sans exploité. » Louise Michel Hors ligne Shrat Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Cdanslair vers lecteur mp3 chinois (.amv) Il y a surement moyen de coder ca plus proprement, j'ai un peu honte. M'enfin... à toutes fins utiles, je poste. #!/bin/bash #Tous les chemins de ce script sont absolus. Ce script ne fonctionne que dans un environnement bien précis. annee=`date "+%Y"` mois=`date "+%m"` jour=`date "+%d"` joursemaine=`date "+%u"` heure=`date "+%H"` we=0 negatif=0 #On se débarasse du problème du week end if [ $joursemaine == 6 ]; then ((jour = jour-1)) we=1 fi if [ $joursemaine == 7 ]; then ((jour = jour-2)) we=1 fi #S'il est moins de 20h, il faut prendre la vidéo du jour d'avant if [[ $we == 0 && $heure < 20 ]]; then if [ $joursemaine == 1 ]; then ((jour = jour-3)) else ((jour = jour-1)) fi fi #Maintenant, on a le bon jour, prenant en compte l'heure et le week end. Problème : les bornes des mois. if [ $jour == -2 ]; then negatif=1 #Mois précédent de 31 jours if [ $mois == 01 ] || [ $mois == 02 ] || [ $mois == 04 ] || [ $mois == 06 ] || [ $mois == 08 ] || [ $mois == 09 ] || [ $mois == 11 ]; then jour=29 fi #Mois précédent de 30 jours if [ $mois == 05 ] || [ $mois == 07 ] || [ $mois == 10 ] || [ $mois == 12 ]; then jour=28 fi #Le mois précédant mars est février, et c'est lourd... if [ $mois == 03 ]; then #On vérifie si l'année est bissextile if [ $((annee%4)) == 0 ]; then jour=27 else jour=26 fi fi fi if [ $jour == -1 ]; then negatif=1 #Mois précédent de 31 jours if [ $mois == 01 ] || [ $mois == 02 ] || [ $mois == 04 ] || [ $mois == 06 ] || [ $mois == 08 ] || [ $mois == 09 ] || [ $mois == 11 ]; then jour=30 fi #Mois précédent de 30 jours if [ $mois == 05 ] || [ $mois == 07 ] || [ $mois == 10 ] || [ $mois == 12 ]; then jour=29 fi #Le mois précédant mars est février, et c'est lourd... if [ $mois == 03 ]; then #On vérifie si l'année est bissextile if [ $((annee%4)) == 0 ]; then jour=28 else jour=27 fi fi fi if [ $jour == 0 ]; then negatif=1 #Mois précédent de 31 jours if [ $mois == 01 ] || [ $mois == 02 ] || [ $mois == 04 ] || [ $mois == 06 ] || [ $mois == 08 ] || [ $mois == 09 ] || [ $mois == 11 ]; then jour=31 fi #Mois précédent de 30 jours if [ $mois == 05 ] || [ $mois == 07 ] || [ $mois == 10 ] || [ $mois == 12 ]; then jour=30 fi #Le mois précédant mars est février, et c'est lourd... if [ $mois == 03 ]; then #On vérifie si l'année est bissextile if [ $((annee%4)) == 0 ]; then jour=29 else jour=28 fi fi fi if [ $negatif == 1 ]; then if [ $mois == 01 ]; then mois=12 else ((mois = mois-1)) fi fi mencoder mms://a533.v55778.c5577.e.vm.akamaistream.net/7/533/5577/42c40fe4/lacinq.download.akamai.com/5577/internet/cdanslair/cdanslair_$annee$mois$jour.wmv -ofps 25 -fps 25 -ovc copy -oac pcm -o /home/michael/Media/Podcasts/$annee$mois$jour.avi cd /home/michael/Applis/amv-codec-tools/AMVmuxer/ffmpeg && ./ffmpeg -i /home/michael/Media/Podcasts/$annee$mois$jour.avi -f amv -r 16 -s 160x120 -ac 1 -ar 22050 -y /home/michael/Media/Podcasts/$annee$mois$jour.amv echo "Fichiers vidéo généré! Youpi!!" Hors ligne DocPlenitude Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Voilà un script pour compter le nombre d'image que j'ai dans Webilder, il suffit de le mettre dans le dossier ~/.webilder/ mais on peut s'en servir dans un autre dossier pour compter le nombre d'image dans le dossier et ces sous dossiers. #!/bin/bash nb_images_jpg=`find . -iname *.jpg -print | grep -v "thumbnail" | wc -l` nb_images_gif=`find . -iname *.gif -print | grep -v "thumbnail" | wc -l` nb_images_png=`find . -iname *.png -print | grep -v "thumbnail" | wc -l` nb_images=`expr $nb_images_jpg + $nb_images_gif + $nb_images_png` zenity --info --title="Nombre d'images dans le dossier" --text="Il y a $nb_images images dans le dossier." Il compte le nombre d'image gif, jpg et png en ne comptant pas les miniatures et fais le total puis vous l'affiche. ------------ Pour avoir une download-bar quand on télécharge en ligne de commande avec wget (bon celui là je l'ai fait à partir de morçals chipés sur le web). #!/bin/bash sed -u 's/\([ 0-9]\+K\)[ \.]*\([0-9]\+%\) \(.*\)/\2\n#Transfert : \1 (\2) à \3/' </dev/stdin | zenity --progress --text="Progression" --percentage=0 Pour l'utiliser (dans l'exemple j'ai mis le script dans wget-download-bar et je l'ai mis dans mon dossier ~/bin/) : wget ftp://machin.bidule 2>&1 | ~/bin/wget-download-bar Dernière modification par DocPlenitude (Le 31/03/2008, à 00:21) Hors ligne soupaloignon Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Sympa ce post, bien vu ==> Libérez les huitres du bassin d'Arcachon <== Hors ligne Oreste visari Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Shrat, comment faire pour que ton script télécharge les vidéos et les mettes dans le dossier /home/user/Vidéos/cDansLair ? Car j'ai essayer en remplaçant le chemin du lecteur par celui du dossier mais ça n'as rien donné, la console s'ouvre et ce ferme lorsque je lance le script. Quoi qu'il en soit merci pour vos scripts! Elementary OS Luna - Acer Aspire S3 Hors ligne Shrat Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Je te fais ça Oreste. Pour l'instant j'ai du boulot mais je poste dans la semaine. Hors ligne Ras&#039; Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) très sympa le todo list, enfin je sais pas si je m'en servirais comme ça mais un marque page discret à afficher en conky c'est une bonne idée ! je poste les miens ce soir j'ai pas le temps là ^^ Mettre le nom en rouge et le but en gras est une bonne idée aussi pour améliorer la lecture EDIT : Bon du coup je poste ça maintenant ROTATION D'IMAGEQuand on prend des photos verticales, il peut y avoir des problèmes avec les données EXIF.Ainsi la photo s'affiche dans le bon sens avec le visionneur d'image, mais s'affichera à l'horizontale avec d'autres applications (envoi sur blogspot par exemple). Le script permet de remettre toutes les photos d'un dossier dans le sens correct. Je l'ai mis en nautilus script pour faire ça d'un clique droit au moment de l'import des photos Dépendances : On à besoin de la commande exifautotran dispo dans le paquet libjpeg-progs #!/bin/bash # # Rotation des images verticales d'un dossier dans leur sens original # find $1 -type f -exec exifautotran '{}' \; zenity --info --title "fin du script" --text "les images ont correctement été modifiées" ENVOI D'UNE IMAGE SUR PIX.NOFRAGUn nautilus script pour envoyer une image sur pix.nofrag d'un click droit et récupérer le lien vers l'image dans le presse papier Merci à pmd pour ce script, pour le support voir ici : http://forum.ubuntu-fr.org/viewtopic.php?id=183632 #!/bin/bash # Nom : pix.sh # But : Envoyer facilement des images sur pix.nofrag. # By pmd # Configuration FICHIER=$1 MIMETYPE=$(file -bi "$1") URL=pix.nofrag.com MAX_TAILLE_FICHIER=2000000 #2Mo (fixé par pix.nofrag) # Verifier le fichier avant envoi TAILLE_FICHIER=$(stat -c%s "$FICHIER") if [ $TAILLE_FICHIER -gt $MAX_TAILLE_FICHIER ]; then { echo "Erreur, le fichier $FICHIER est trop lourd ($TAILLE_FICHIER octets pour une limite de $MAX_TAILLE_FICHIER maximum)." zenity --warning --text="Erreur, le fichier $FICHIER est trop lourd ($TAILLE_FICHIER octets pour une limite de $MAX_TAILLE_FICHIER maximum)." exit 1 } fi # Envoyer le fichier, et enregistrer la page résultat TEMPFILE=$(tempfile) curl $URL -F monimage=@"$FICHIER" -F submit=Upload -H "Expect:" -o $TEMPFILE --progress-bar | zenity --progress --pulsate --auto-close --text="Envoi de <i>$1</i> vers $URL ..." # Analyser la page pour extraire les donnees VIEWPAGE=$(grep -oEm 1 '\[url\=([^]]*)' $TEMPFILE | sed 's/\[url\=//') IMAGE_BIG=$(grep -oEm 1 '\[img\]([^[]*)' $TEMPFILE | sed 's/\[img\]//') NB_IMG=$(grep -c '\[img\]' $TEMPFILE) if [ "$NB_IMG" -eq "1" ]; then # Si ya pas besoin de miniature { IMAGE_MINI=$IMAGE_BIG } elif [ "$NB_IMG" -ge "2" ] || [ "$NB_IMG" -le "3" ]; then # Si ya besoin de miniature { IMAGE_MINI=$(echo $VIEWPAGE | sed 's/\.html//')"t.jpg" } else { echo "La disposition de présentation du code à changé dans pix.nofrag." zenity --warning --text="La disposition de présentation du code à changé dans pix.nofrag." exit 2 } fi rm $TEMPFILE # Resultat de l'upload : le code a placer dans un forum BBCODE="[url=$VIEWPAGE][img]$IMAGE_MINI[/img][/url]" ZCODE="&lt;lien url=\"$VIEWPAGE\"&gt;&lt;image&gt;$IMAGE_MINI&lt;/image&gt;&lt;/lien&gt;" # ="<lien url="$VIEWPAGE"><image>$IMAGE_MINI</image></lien>" # On affiche echo "Lien : $VIEWPAGE" zenity --info --text=" <b>Fichier :</b> $1 <b>Type :</b> $MIMETYPE <b>Lien :</b>\n<i><small>$VIEWPAGE</small></i> <b>Image :</b>\n<i><small>$IMAGE_BIG</small></i> <b>Miniature :</b>\n<i><small>$IMAGE_MINI</small></i> <b>BBCode :</b>\n<i><small>$BBCODE</small></i> <b>ZCode :</b>\n<i><small>$ZCODE</small></i>" # On met le lien direct dans le presse papier echo [url=$IMAGE_BIG][img]$IMAGE_MINI[/img][/url]|xclip TELECHARGER LES QUOTIDIENNES DE CANALComme son nom l'indique, ce script permet de télécharger les quotidiennes (et presques quotidiennes) de canal, c'est à dire :les guignolsle zappingle petit journal actu et peoplele sav des émissionsla boite à questionla météo de louisela chronique de chris esquerreetc... Je vous renvoi à ce lien vu que le script peut être souvent modifié : http://forum.ubuntu-fr.org/viewtopic.php?id=200149 Dernière modification par Raskal (Le 08/04/2008, à 10:24) En ligne Mathieu11 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Merci a tous ceux qui participent Je vais tester ton script Canal+ Raskal ca a l'air super sympa. Dernière modification par Mathieu11 (Le 31/03/2008, à 19:48) Vostro 1400 Hors ligne Zak Blayde Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Génial, le coup de pixnofrag, je teste ce soir ! Hors ligne Hors ligne Mathieu11 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Le script pour les envois vers pixnofrag ne fonctionne pas chez moi, je ne recois pas d'url pour l'image dans la boite de dialogue zenity qui s'affiche et je n'ai rien dans le presse-papiers... Quelqu'un sait pourquoi ? Edit : Il me manquait le paquet curl... dsl... ca marche now. Je propose de rajouter les noms des paquets necessaires pour chaque script si possible. Dernière modification par Mathieu11 (Le 03/04/2008, à 15:54) Vostro 1400 Hors ligne djezair31 Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Hello tous, j'ai du installer dernierement dotclear sur plusieurs machine ubuntu gutsy. Du coup, je poste le script d'installation. Attention, vous devez editer le script et modifier la ligne : ROOTMYSQLPASSWD="dotclear" Dans le cas contraire, le script modifie le mot de passe root de MySQL Une fois le script executer rendez-vous à l'url http://localhost/dotclear/admin/install/ Et voilou ça tourne #!/bin/bash if ! id | grep -q "uid=0" then echo "You must be root to run this script (try sudo)" exit 1 fi # Si vous avez deja un mot de passe root pour MySQL # Veuillez le renseigner ici. ROOTMYSQLPASSWD="dotclear" DC_DBUSER="dotclear" DBPASSWORD="dotclear" DC_DBNAME="dotclear" reponse=no DOTCLEARVERSION="dotclear-2.0-beta7.tar.gz" DOTCLEARTGZ="http://download.dotclear.net/latest/${DOTCLEARVERSION}" WWWDIR="/var/www" WWWAPPDIR="/var/www/dotclear" shellout(){ echo echo -n `date` echo -e "\033[1m $1\033[0m" echo "Existing with ERROR" echo exit 1; }; title(){ echo echo -e "\033[1m $1\033[0m" echo } echo echo "ATTENTION !!!" echo echo "Le mot de passe de l'utilisateur root mysql va etre modifier." echo "Le nouveau mot de passe sera : $ROOTMYSQLPASSWD" echo echo "Si MySQL possede deja un mot de passe root et que vous le connaissez" echo "vous devez renseigner la variable ROOTMYSQLPASSWD en premiere ligne de ce script" echo echo -n "Voulez vous continuez (yes or no) : " read reponse echo echo if [ ! $reponse = "yes" ] then echo "Existing"; exit 1; fi [ "${reponse}" = "" ] && exit title "Verification des dépendances" apt-get install mysql-server mysql-client apache2 apache2-mpm-prefork apache2-utils apache2.2-common libapache2-mod-auth-mysql libapache2-mod-fcgid libapache2-mod-php5 php5 php5-cgi php5-cli php5-common php5-gd php5-mcrypt php5-mysql phpmyadmin libpcre3-dev || shellout "Erreur d'installation des paquets. Verifier vos dépots" apt-get install sysv-rc-conf update-rc.d apache2 defaults 90 update-rc.d mysql defaults 90 title "Configuration du serveur MySQL" /etc/init.d/mysql stop mysqld_safe --skip-grant-tables --skip-networking & sleep 5 mysql mysql -e "update user set password=password(\"${ROOTMYSQLPASSWD}\") where user=\"root\" and host=\"localhost\";" || shellout "Erreur 1 MySQL" mysqladmin shutdown || shellout "Erreur 2 Impossible d'arreter MySQL" /etc/init.d/mysql start || shellout "Erreur 3 Impossible de démarrer MySQL" #mysql -u root -e "DROP DATABASE ${DC_DBNAME}" --password="$ROOTMYSQLPASSWD" mysql -u root -e "CREATE DATABASE ${DC_DBNAME}" --password="$ROOTMYSQLPASSWD" #mysql -u root -e "CREATE USER ${DC_DBUSER}" --password="$ROOTMYSQLPASSWD" || shellout "Echec Creation du user ${DC_DBUSER}" mysql -u root mysql -e "GRANT ALL PRIVILEGES ON ${DC_DBNAME}.* TO '${DC_DBUSER}'@'localhost' IDENTIFIED BY '${DBPASSWORD}'; FLUSH PRIVILEGES;" --password="$ROOTMYSQLPASSWD" title "Telechargement de DotCLEAR : $DOTCLEARTGZ" rm -f /tmp/$DOTCLEARVERSION wget $DOTCLEARTGZ -P /tmp/ || shellout "Echec de telechargement du fichier $DOTCLEARTGZ" title "Decompression du fichier /tmp/$DOTCLEARVERSION" tar zxvf /tmp/$DOTCLEARVERSION -C ${WWWDIR} | \ awk '{l++; if (l%1==0) {printf "."; fflush()}}' echo chown -R www-data:www-data ${WWWDIR}/dotclear/ chmod -R 0775 ${WWWDIR}/dotclear/ title "Configuration de DotCLEAR" cp ${WWWDIR}/dotclear/inc/config.php.in ${WWWDIR}/dotclear/inc/config.php.in.orig sed -i "s/define('DC_DBPASSWORD','');/define('DC_DBPASSWORD','$DBPASSWORD');/g" ${WWWDIR}/dotclear/inc/config.php.in sed -i "s/define('DC_DBNAME','');/define('DC_DBNAME','$DC_DBNAME');/g" ${WWWDIR}/dotclear/inc/config.php.in sed -i "s/define('DC_DBUSER','');/define('DC_DBUSER','$DC_DBUSER');/g" ${WWWDIR}/dotclear/inc/config.php.in sed -i "s/define('DC_MASTER_KEY','');/define('DC_MASTER_KEY','le train sifflera trois fois');/g" ${WWWDIR}/dotclear/inc/config.php.in sed -i "s/define('DC_DBDRIVER','');/define('DC_DBDRIVER','mysql');/g" ${WWWDIR}/dotclear/inc/config.php.in sed -i "s/define('DC_ADMIN_URL','');/define('DC_ADMIN_URL','\/dotclear\/config');/g" ${WWWDIR}/dotclear/inc/config.php.in title "Patch DotCLEAR" # Correction de BUG Voir http://dev.dotclear.net/2.0/changeset/1543 cat > ${WWWDIR}/dotclear/admin/install/patch.diff <<EOF Index: /trunk/admin/install/check.php =================================================================== --- /trunk/admin/install/check.php (revision 1145) +++ /trunk/admin/install/check.php (revision 1543) @@ -49,5 +49,6 @@ } - if (!@preg_match("/\xf8\xa1\xa1\xa1\xa1/u", "\xf8\xa1\xa1\xa1\xa1")) { + \$pcre_str = base64_decode('w6nDqMOgw6o='); + if (!@preg_match('/'.\$pcre_str.'/u', \$pcre_str)) { \$err[] = __('PCRE engine does not support UTF-8 strings.'); } EOF cd ${WWWDIR}/dotclear/admin/install/ && patch check.php < patch.diff cd /tmp mv ${WWWDIR}/dotclear/inc/config.php.in ${WWWDIR}/dotclear/inc/config.php title "Firefox to http://localhost/dotclear/admin/install/ and enjoy dotclear :-)" Hors ligne Ras&#039; Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) @Raskal, tu auras sûrement remarqué que les gens aiment bien être cité pour un travail fourni. Désolé, j'ai eu la flemme de rechercher le topic qui en parlait :$ Met un commentaire dans le script Désolé... je voulais vraiment pas faire passer ça pour une oeuvre à moi :$ EDIT : ah ben il y est sur le script du topic O_o J'ai du prendre une vieille version ou il ne devrait pas y être ou je sais pas mais y'avais aucune intention douteuse... Dernière modification par Raskal (Le 03/04/2008, à 19:54) En ligne kouskous Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Script nautilus qui copie vos fichiers dans le dossier des scripts nautilus et leur donne les droits nécessaires afin d'être exécutés (fait pour Ubuntu-noobie) #!/bin/sh # # GPL v.3 # Copie vos fichiers/dossiers à l'emplacement des scripts nautilus et leur donne les droits nécessaires # Si aucun fichier selectionné if [ $# -eq 0 ]; then zenity --error --title="Erreur" --text="Vous devez selectionner un fichier !" exit fi for File in "$@" do # Si c'est un dossier if [ -d "$File" ]; then if zenity --question --title="Confirmation" --text="Désirez-vous copier ce dossier : '$File' ?"; then cp $@/ $HOME/.gnome2/nautilus-scripts/ -R && chown $LOGNAME $HOME/.gnome2/nautilus-scripts/$@/ -R && chmod 755 $HOME/.gnome2/nautilus-scripts/$@/ -R fi #Si c'est un fichier else cp $@ $HOME/.gnome2/nautilus-scripts/ && chown $LOGNAME $HOME/.gnome2/nautilus-scripts/$@ && chmod 755 $HOME/.gnome2/nautilus-scripts/$@ fi done Dernière modification par Kous-Kous! (Le 04/04/2008, à 14:40) #!/usr/bin/killall « « J'aime kouskous » — kouskous. » — kouskous. Hors ligne Ubuntu-Noobie Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) ici: http://www.gnomefiles.org/app.php?soft_id=1159 un script pour convertir mp3, wma, ogg, wav... télécharger un .bz2 récupérer le script audio-convert. Il est nécessaire d'avoir mplayer "Quand on voit ce qu'on voit, qu'on entend ce qu'on entend... on a raison de penser ce qu'on pense" [coluche] Hors ligne Lonewolf Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) @Raskal Salut, J'ai un problème avec ton pix.nofrag. Voilà ce que me renvoie la fenêtre zenity : Fichier : IMG_1488.JPG Type : ERROR: cannot open `IMG_1488.JPG' (No such file or directory) Lien : Image : Miniature : t.jpg BBCode : [url=][img]t.jpg[/img][/url] ZCode : <lien url=""><image>t.jpg</image></lien> NB : curl était déjà installé (cf post de Mathieu11). Hors ligne Ras&#039; Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) il n'est pas de moi, il faut voir avec pmd, désolé j'avais oublié de le citer, j'ai corrigé mon post, j'y ai rajouté le lien : http://forum.ubuntu-fr.org/viewtopic.php?id=183632 En ligne pmd Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) il n'est pas de moi, il faut voir avec pmd, désolé j'avais oublié de le citer, j'ai corrigé mon post, j'y ai rajouté le lien : http://forum.ubuntu-fr.org/viewtopic.php?id=183632 Ra merde, il renvoi l'ascenseur Lonewolf : Passe là : http://forum.ubuntu-fr.org/viewtopic.php?id=183632 Et essai en passant par la console Apparemment, l'url du fichier donné en argument n'est pas bonne Hors ligne Mukri Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Prend celui la en python il est 2 fois plus rapide que le script bash #!/usr/bin/env python import urllib, httplib, mimetypes, sys, re def post_multipart(host, port, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host, port) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '---------------------------13049614110900' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' params = [('MAX_FILE_SIZE', '3145728'), ('refer', 'http://reg.imageshack.us/v_images.php')] files = [('fileupload', sys.argv[1], open(sys.argv[1], 'rb').read())] open(sys.argv[1]).read() text1 = post_multipart('imageshack.us', 80, '/index.php', params, files) keyword = re.compile(r"(image to friends)+") lines = str(text1).split('\n') for line in lines: if keyword.search (line): foo = line.split('"') print foo[1] USage: ./imageshack.py image.jpg Hors ligne Ras&#039; Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...) Comme tu n'es pas le premier à qui ça arrive, http://forum.ubuntu-fr.org/viewtopic.php?id=78396 Celà dit le script ne fonctionnait pas chez moi... En ligne
If there are too few values that ​​fit on one line, I would choose to separate them by commas as exemplified by other fellows, otherwise per RFC822 standard you can split values by lines started by tabs: settings.conf: [syndication] name = Test Name title = Test Title categories = Category 1 Category 2 Category 3 settings.py: #!/usr/bin/python import ConfigParser config = ConfigParser.ConfigParser() # Reading config.readfp(open('settings.conf')) categories = config.get('syndication', 'categories').strip().split('\n') # Appending categories.append('Category 4') # Changing config.set('syndication', 'categories', '\n' + '\n'.join(categories)) # Storing config.write(open('settings.conf', 'w')) Your new settings.conf: [syndication] name = Test Name title = Test Title categories = Category 1 Category 2 Category 3 Category 4 Note: You can put a value in the first line after the : or =, but being a list of values, I think starting from the second line is more "readable" when you've to manually edit the file.
I am trying to write a program using the Mathematica function IsotopeData, but am finding the code troublesome. Due to my (relative) familiarity with Python, I am puzzled as to how Mathematica works, as they are very different.$\require{mhchem}$ What I am trying to do, is to find the elements in a decay chain which end with either $\ce{^{191}_{77}Ir}$ or $\ce{^{193}_{77}Ir}$. In Python syntax, what I'm trying to do would look a bit like this: #A would be the Atomic Mass and Z the Atomic Number #DaughterNuclide(Z,A) would return the Daughter Nuclides of the isotope def IsoCheck(z,a): try: x = DaughterNuclide(z,a) if x in Isotopes: return [z,a] else: return [0,0] except: return [0,0] L=[] Isotopes = [[76,191],[78,191]] for a in xrange(1,295): for z in xrange(1,119): if IsoCheck(z,a) != [0,0]: L.append(IsoCheck(z,a)) repeat = 1 #Then, repeat until all chains are over while repeat == 1: repeat = 0 for x in L: if IsoCheck(x) != [0,0] #Lets just pretend it isn't a list L.append(x) repeat = 1 Now, my question is this: what would the equivalent code to perform this task in Mathematica look like?
My question is: What is it that makes those languages suitable? From what I know, they are slower than other languages, and operate at a higher abstraction level, which means they are too far from the hardware. The only reason I could think is because of their advanced string manipulation capabilities, but I believe that other languages have such capabilities. My question is: Languages are useful for Let's look at the ones you've mentioned: So what makes these particularly good for pentesting? Well, most pentesting involves writing up quick throw-away tools to do a specific job for a specific test. Writing such a tool in C or C++ every time you want to do a quick job is cumbersome and time-consuming. Furthermore, they tend to produce platform-specific binaries or source that requires platform-specific compilation, rather than cross-platform scripts that For example, Ruby and Python are popular for more complex tasks because they have comprehensive libraries, whereas Perl is popular for quick data processing hacks. JavaScript is commonly utilised as a simple browser-based language that everyone has access to. Other languages such as C tend to be used for more low-level tasks that interface with the OS. Now, the other side of the coin is languages used as payloads. This is where the line gets blurred, because requirements are so varied. For attacking Windows boxes, any payload that has no dependencies outside of what the OS provides is useful. This might be C, C++, VBScript, x86 asm, C# / VB.NET (.NET 2.0 is on most machines these days), etc. For attacking Linux boxes you might use C, C++, bash scripts or Perl. Java is also common for cross-platform attacks. At the end of the day, pick the language that Here is a great answer I found on a stack overflow question of similar context by @tqbf: (I copied this answer here, because I believe it gives valid reasons for which they may be prefered, so it might be useful to future readers) Libraries, Time to write Code, cross-platform compatibility are key here. I found that using Python I was able to come up with Proof-of-concept exploits in a very short amount of time with minimum lines of code. This is possible because of the extensive standard library and additional libraries that you can download as well. I believe that is python's greatest strength to be used for pentesting and hacking. Ex. you need a string of 1000 characters / 1000 bytes long. In python: print "A"*1000 In C : for(i=0;i<1000;i++)printf("A");` (Apart from all the includes mumbo jumbo and compiling it) That is just a simple example. But as you can see the time taken for such a trivial task is far simpler in python. The difference can be even more enhanced when you want to send http requests etc from your code. With I have zero knowledge in these fields, but the mentioned programming languages all enable rapid programming, i.e. one could try out a much larger number of different ideas in a given time frame than with the more runtime-efficient but inefficient for programming (and debugging) programming languages like C etc. That might be a point. I think what defines a language suited for hacking, is: Take an example of Java. It runs on all platforms, and is installed on a lot of system. This ensures a fairly high probability that the hackers code can run, and the language is installed on the system he targets. The community of given highly used programming language, also occasionally finds vulnerabilities in the language, which allowed hackers to target that vulnerability, and have a very high change of hitting it, due to the high distribution of the language. Some good answers already to this one but I'll provide another perspective. One reason that scripting languages tend to be used for hacking is that they optimize for speed (and ease) of development which is likely to be a key factor. As an example, for penetration testing scripting I use ruby. It has a number of good libraries for things like HTTP which mean I don't have to worry about low level details and writing a quick script is very fast as there's little "formality" required in a ruby script (e.g. method/variable declarations) when compared with languages like Java. One of the downsides of these languages can be that they are slower at run-time, but for a lot of hacking work that's not an issue, speed of development is more important. My two cents: The quickness of the language doesn't matter when you are in full One of the most usefull and powerfull language for this kind of operation seem to be forgotten in your question. Under Un*x, you're primarily logged in a shell console, to be able to run other tools. If it is one of the slower $ time for ((i=1000000;i--;));do :;done real 0m4.755s user 0m4.628s sys 0m0.124s time perl -e 'map{1}(0..1000000)' real 0m0.199s user 0m0.112s sys 0m0.060s $ time python -c 'for a in range(1000000): 1==1 real 0m0.119s user 0m0.096s sys 0m0.020s Yes! More than 4 seconds for a 1 million step loop is very slow, but once you're logged in a command line console... Practical sample you could start from: $ mkdir /tmp/hackingGoogle $ cd $_ than $ nc google.com 80 <<<$'HEAD /fonts/ HTTP/1.0\r\n\r' HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 ... From there, you may use all tool you want, like $ openssl s_client -connect google.com:443 -ign_eof \ <<< $'HEAD / HTTP/1.0\r\n\r' 2>&1 | \ openssl x509 -in /dev/stdin -out certfile $ openssl x509 -in certfile -noout -fingerprint SHA1 Fingerprint=67:1B:98:92:48:86:FF:E1:C5:02:44:C5:9F:F3:96:78:08:F5:0A:45 $ openssl x509 -in certfile -noout -subject subject= /C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.google.com If you're interested about SSL, or... $ wget https://www.google.com/fonts/ $ vi index.html $ wget https://www.google.com/fonts/webfonts.nocache.js $ smjs < <(sed < webfonts.nocache.js 's/Window....') ... for playing with You may benefit of a full environment for storing variables $ ip=();ANS=false;while read -a line;do if [[ "$line" = ";;" ]];then [[ "${line[1]}" = "ANSWER" ]] && ANS=true || ANS=false; fi ; $ANS && [[ "${line[2]}" == "IN" ]] && ip+=(${line[4]});done < <(dig www.google.com) $ printf "%s\n" ${ip[@]} 173.194.116.51 173.194.116.52 173.194.116.48 173.194.116.49 173.194.116.50 Depending on what you're searching for, you could use widely all your tool in all combination. $ grep ^64 < <(for host in ${ip[@]};do ping -c2 $host&done;wait)|sort -t. -nk4 64 bytes from 173.194.113.112: icmp_req=1 ttl=54 time=45.4 ms 64 bytes from 173.194.113.112: icmp_req=2 ttl=54 time=47.8 ms 64 bytes from 173.194.113.113: icmp_req=1 ttl=54 time=41.4 ms 64 bytes from 173.194.113.113: icmp_req=2 ttl=54 time=40.2 ms 64 bytes from 173.194.113.114: icmp_req=1 ttl=54 time=43.1 ms 64 bytes from 173.194.113.114: icmp_req=2 ttl=54 time=39.0 ms 64 bytes from 173.194.113.115: icmp_req=1 ttl=54 time=47.0 ms 64 bytes from 173.194.113.115: icmp_req=2 ttl=54 time=42.1 ms 64 bytes from 173.194.113.116: icmp_req=1 ttl=54 time=43.9 ms 64 bytes from 173.194.113.116: icmp_req=2 ttl=54 time=39.0 ms This could by Mini script from there: With this, you will make two ping, ip=() ANS=false while read -a line;do if [[ "$line" = ";;" ]] ;then [[ "${line[1]}" = "ANSWER" ]] && ANS=true || ANS=false fi $ANS && [[ "${line[2]}" == "IN" ]] && ip+=(${line[4]}) done < <(dig www.google.com) grep ^64 < <( for host in ${ip[@]};do ping -c2 $host & done wait ) | sort -t. -nk4 Other (more efficient) languages Once the goal is fixed, after a lot of The choice of the language used will depend mainly on the hacker's preferences. (If not required by his boss.) #include <stdio.h> int main() { int i, list[1000]; for (i=0;i<1000;i++) { list[i] = 'A'; } return 0; } I don't see any mumbo jumbo here. In fact this is not that much longer than a full python program to do the same. Some loops are shorter in C than they could ever be with python, especially when in C you can use pointers which considerably give much more power and shorten the code to between 10 and 70 percent of the python equivalent. Of course normally C code is longer cause thats just the nature of more powerful languages. Anyway hacking is done in C the best. forget anything else just go C.
pguimier Re : Qarte arte.tv browser (ex Qarte+7) @VinsS en ce moment même elles le sont, je peux les voir. J'ai testé un : rtmpdump -r rtmp://flashstreaming.cdn.arte.tv/a3974/o35 -y "mp4:geo/FR/cathedrale-sbs-logo_FR?h%3D0cbcd9807abb79b532c3a0db53b68be1" -W "http://www.arte.tv/flash/mediaplayer/mediaplayer.swf" -o "Le Defi des batisseurs 3D side by side - arte.mp4" Mais sans succès... Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) J'ai beau multiplier les essais, toujours sans succès RTMPDump v2.3 (c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL Connecting ... INFO: Connected... ERROR: Closing connection: NetStream.Failed Pour ceux qui veulent s'essayer: rtmpdump -r "rtmp://flashstreaming.cdn.arte.tv/a3974/o35/mp4:geo/FR/cathedrale-sbs-logo_FR?h=0cbcd9807abb79b532c3a0db53b68be1" -W "http://www.arte.tv/flash/mediaplayer/mediaplayer.swf" --flv "/home/vincent/plus135566328338.flv" rtmpdump -r "rtmp://flashstreaming.cdn.arte.tv/a3974/o35/mp4:geo/FR/ESPACE-SBS_FR?h=48abe91df455be6fd30d00b32cceced4" -W "http://www.arte.tv/flash/mediaplayer/mediaplayer.swf" --flv "/home/vincent/plus135566328338.flv" rtmpdump -r "rtmp://flashstreaming.cdn.arte.tv/a3974/o35/mp4:geo/FR/FRERE-HUBER-SBS_FR?h=f9a09ec44355c17dd0af13a17adc909f" -W "http://www.arte.tv/flash/mediaplayer/mediaplayer.swf" --flv "/home/vincent/plus135566328338.flv" Changez /home/vincent/ par votre chemin de dossier vidéos, n'enlevez pas les guillemets. @ pguimier tu as eu de la chance, je ne suis jamais parvenu à les voir sur le site. Hors ligne k3c Re : Qarte arte.tv browser (ex Qarte+7) J'ai l'impression que la commande suivante marche (générée par rtmpsrv) rtmpdump -r "rtmp://flashstreaming.cdn.arte.tv/a3974/o35" -a "a3974/o35" -f "LNX 11,2,202,258" -W "http://www.arte.tv/flash/mediaplayer/mediaplayer.swf" -p "http://www.arte.tv/fr/voie-en-3d-en-side-by-side/7134906.html" -y "mp4:geo/FR/ESPACE-SBS_FR?h=48abe91df455be6fd30d00b32cceced4" -o ESPACE-SBS_FR.flv Acer Aspire One 150 8,9 " Norhtec avec une Clé Usb bootable http://www.norhtec.com/products/mcsr/index.html Toshiba Satellite L750 Hors ligne pguimier Re : Qarte arte.tv browser (ex Qarte+7) Super ! Merci beaucoup ! Les deux premières commandes de VinsS et la commande de k3c fonctionnent impec ! Je garde précieusement les codes pour plus tard. @VinsS es-tu sûr de ne pas avoir un truc qui bloque pour ces pages ? À chaque fois que je tente, ça fonctionne. Hors ligne k3c Re : Qarte arte.tv browser (ex Qarte+7) @ pguimier Pour ma part, à part la fois où j'ai téléchargé, je n'ai jamais pu accéder à ces pages. Et mon accès Internet fonctionne. Rappel de la méthode 1) sudo iptables -t nat -A OUTPUT -p tcp --dport 1935 -j REDIRECT 2) lancer rtmpsrv 3) lancer la vidéo 4) dans la fenêtre de rtmpsrv, copier coller la commande générée 5) sudo iptables -t nat -D OUTPUT -p tcp --dport 1935 -j REDIRECT 6) lancer la commande copiée Acer Aspire One 150 8,9 " Norhtec avec une Clé Usb bootable http://www.norhtec.com/products/mcsr/index.html Toshiba Satellite L750 Hors ligne pguimier Re : Qarte arte.tv browser (ex Qarte+7) @ pguimier Pour ma part, à part la fois où j'ai téléchargé, je n'ai jamais pu accéder à ces pages. Et mon accès Internet fonctionne. Rappel de la méthode 1) sudo iptables -t nat -A OUTPUT -p tcp --dport 1935 -j REDIRECT 2) lancer rtmpsrv 3) lancer la vidéo 4) dans la fenêtre de rtmpsrv, copier coller la commande générée 5) sudo iptables -t nat -D OUTPUT -p tcp --dport 1935 -j REDIRECT 6) lancer la commande copiée Et *PAF bookmark ! Merci Hors ligne pistache Re : Qarte arte.tv browser (ex Qarte+7) Bonsoir. Problème avec xubuntu 12.10 (ne se produisait pas avec xubuntu 12.04). Installation de qarte tel indiqué en début de ce sujet (mode ligne de commande). Lors du lancement de l'application, la boite qarte préférence apparait : le moindre clic (par exemple sur le bouton "parcourir" servant à désigner le répertoire cible), fait aussitôt planter l'application. Qarte lancé depuis un terminal renvoit ainsi l'erreur : Erreur de segmentation (core dumped) Ajout : le bug semble référencé : https://bugs.launchpad.net/qarte/+bug/1072342 Ajout 2 : je confirme ce qui est dit dans ce lien, c'est bien un problème avec Greybird, le thème par défaut de xubuntu12.10, car lorsqu'on utilise un autre thème, qarte ne plante pas. Dernière modification par pistache (Le 28/12/2012, à 19:18) Hors ligne lemoineo Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, merci pour ce soft que j'utilise chaque jour, bien plus user friendly que tvdownloader mais qui lui, englobait toutes les chaines de la TNT un souci sous 12.10, un changement dans l'ordre de la pile génère une erreur ubuntu. qui déclare que qarte est arrếté (ce qui est faux) ce 12.10 est tout neuf d'hier (je l'ai réinstallé). Désolé si le message avais été déjà posté, victime du succès, plein de messages .... Ol Dernière modification par lemoineo (Le 30/12/2012, à 11:13) mon boulot : développeur PHP ? mes galeries : http://lemoineo.free.fr Utilisateur Linux dans mes loisirs le Kitesurf me permet de décrocher du PC ! Hors ligne ynad Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, Excellente application que "qarte", mais y a t'il un moyen pour enregistrer les sous titres quand ceux ci sont présents bien sur, j'ai cherché mais rien trouvé. Merci. Hors ligne ynad Re : Qarte arte.tv browser (ex Qarte+7) @ VinsS Oui par exemple: Sur les traces de Moby Dick au début de la vidéo on a l'info que l'émission est sous-titrée, puis en bas à droite apparait en jaune "S/T", puis rien, on enregistre parfaitement la vidéo mais sans les sous titres, il faut peut-être aller fouiller mais je ne sais pas où ?? merci t’intéresser à mon cas... Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Cette vidéo est bien en français. Je l'ai téléchargée peu de temps, hier, après sa mise en ligne. Je précise ceci parce qu' il est déjà arrivé qu'ils placent une version allemande par erreur et que ce ne soit corrigé que le lendemain. J'ignore pourquoi la mention "S/T" apparaît au début, par contre. Dernière modification par VinsS (Le 07/01/2013, à 00:42) Hors ligne ynad Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, Alors il y a peu d'espoir d'avoir les sous-titres... Si quelqu'un a une idée, je suis preneur. la bonne journée, semaine, mois, année à tous. Hors ligne ynad Re : Qarte arte.tv browser (ex Qarte+7) @ VinsS l'explication est simple le sous-titrage est un confort supplémentaire pour des personnes qui ont perdu un peu d'audition, et il se trouve que vit avec moi quelqu'un qui adore les documentaires sous-titrés pour en profiter pleinement, désolé de ces explications personnelles, j'espère que tu comprendras mieux ma requête; et je suis sûr ne pas être seul dans ce cas... cordialement. Hors ligne elrockito87 Re : Qarte arte.tv browser (ex Qarte+7) Salut, tout d'abord merci pour ce magnifique log. En effet cela fait des années que je te suis et je suis devenu "addict" . Seulement voila je suis passé sous Voyager 12.04 (Xubuntu) et lorsque je suis ton 1 er post pour installer qarte tout se passe bien sauf qu'au moment de lancer qarte voila ce que j'ai: qarte Erreur de segmentation (core dumped) Merci de votre aide, comme je ne sais pas comment faire avec ce type d'erreur en retour. N'allez pas là où le chemin peut mener. Allez là où il n'y a pas de chemin et laissez une trace. [Ralph Waldo Emerson] Ne restreins pas le champ du possible aux limites de ton imaginaire. [Antony Bouchardon] Hors ligne kykyou Re : Qarte arte.tv browser (ex Qarte+7) elrockito87 c est un problème propre a voyager 12.04 , change les icônes et l apparence de tes fenêtres .... via gestionnaire de paramètre / apparence par contre moi , il se lance et se ferme immédiatement !! j ai pas tout re-lu le topic , qq un aurait une soluce ?? svp ... Hors ligne joombuntu Re : Qarte arte.tv browser (ex Qarte+7) Bonsoir, Quelqu'un aurait-il une idée pour résoudre ceci : Traceback (most recent call last): File "/usr/bin/qarte", line 131, in <module> Main = Qarte() File "/usr/share/qarte-1.5.0/qarte.py", line 116, in __init__ self.utils.update_data() File "/usr/share/qarte-1.5.0/utils.py", line 123, in update_data self.__get_default_data() File "/usr/share/qarte-1.5.0/utils.py", line 147, in __get_default_data t = float(lvd.UPDATED) UnboundLocalError: local variable 'lvd' referenced before assignment Un qarte -d me renvoie 20:59:31: INFO - utils loading update error: HTTP Error 404: Not Found 20:59:31: INFO - utils updated file not found, use default Merci de votre attention, "Que votre combat ne vous transforme pas en l’image de vos ennemis !" Georges Orwell,La ferme des animaux Hors ligne n.mazerat Re : Qarte arte.tv browser (ex Qarte+7) Bonjoir. Je viens de découvrir ce joli travail. Malheureusement, tout comme joombuntu ci dessus, ça ne fonctionne pas chez moi avec ubuntu 12.10. C'est presque la même erreur. Je n'ai pas su la trouver dans les anciens posts, et je suis pas un cho-lapin du langage info... 21:33:47: INFO - qarte Main thread: <_MainThread(MainThread, started -1221395712)> 21:33:47: INFO - ui_main setup main window 21:33:47: INFO - ui_main set page arte+ 21:33:47: INFO - ui_main set button's group arte+ 21:33:47: INFO - ui_main set basket arte+ 21:33:47: INFO - ui_main set dwnld button arte+ 21:33:47: INFO - ui_main set page arteLive 21:33:47: INFO - ui_main set categories buttons 21:33:47: INFO - ui_main set button's group arteLive 21:33:47: INFO - ui_main set basket arteLive 21:33:47: INFO - ui_main set dwnld buttons 21:33:47: INFO - ui_main set page arteLive extra 21:33:47: INFO - ui_main set extra categories buttons 21:33:47: INFO - ui_main set button's group arteLive extra 21:33:47: INFO - ui_main set basket arteLive extra 21:33:47: INFO - ui_main set extra dwnld buttons 21:33:47: INFO - ui_main set menu bar 21:33:47: INFO - ui_main set status bar 21:33:47: INFO - ui_main set actions 21:33:47: INFO - ui_main make connections 21:33:47: INFO - ui_main set theme 21:33:47: INFO - ui_main main window complete 21:33:47: INFO - utils Updating 21:33:48: INFO - utils loading update error: HTTP Error 404: Not Found Traceback (most recent call last): File "/usr/bin/qarte", line 131, in <module> Main = Qarte() File "/usr/share/qarte-1.5.0/qarte.py", line 116, in __init__ self.utils.update_data() File "/usr/share/qarte-1.5.0/utils.py", line 123, in update_data self.__get_default_data() File "/usr/share/qarte-1.5.0/utils.py", line 137, in __get_default_data import livedata_fr as lvd File "/home/cacao/.Qarte/livedata_fr.py", line 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ^ SyntaxError: invalid syntax Si Vins$ peux nous aider? Dernière modification par n.mazerat (Le 30/01/2013, à 22:40) Hors ligne leTrolldesForets Re : Qarte arte.tv browser (ex Qarte+7) Bonsoir, Il faut rajouter un return à la ligne 132 du fichier /usr/share/qarte-1.5.0/utils.py cela donne comme résultat : 125 def __get_default_data(self): 126 fname = os.path.join(self.user_fld, 'livedata_{0}.py' 127 .format(self.cfg['lang'])) 128 129 if not os.path.isfile(fname): 130 logger.info('updated file not found, use default') 131 self.is_updated = False 132 return 133 134 else: 135 sys.path.append(self.user_fld) 136 try: 137 if self.cfg['lang'] == 'fr': 138 import livedata_fr as lvd 139 140 else: 141 import livedata_fr as lvd 142 except ImportError, why: 143 logger.warning("Unable to import update: {0}".format(why)) 144 self.is_updated = False 145 return 146 147 self.is_updated = True 148 t = float(lvd.UPDATED) J'espère que c'est clair, car j'ai été gourmand en lignes affichées ! Oups, j'allais oublier .... merci à Vincent pour ce beau joujou. Je sens que je vais manger de la vidéo Arte à m'en faire peter les yeux ;-) Dernière modification par leTrolldesForets (Le 30/01/2013, à 23:52) Hors ligne n.mazerat Re : Qarte arte.tv browser (ex Qarte+7) Nop, rien à faire. Presque pareil. Dans tous les cas il lance la fenêtre de qarte, pis ça ferme aussi sec 00:31:14: INFO - utils loading update error: HTTP Error 404: Not Found Traceback (most recent call last): File "/usr/bin/qarte", line 131, in <module> Main = Qarte() File "/usr/share/qarte-1.5.0/qarte.py", line 116, in __init__ self.utils.update_data() File "/usr/share/qarte-1.5.0/utils.py", line 123, in update_data self.__get_default_data()File "/usr/share/qarte-1.5.0/utils.py", line 140, in __get_default_data import livedata_fr as lvd File "/home/cacao/.Qarte/livedata_fr.py", line 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ^ SyntaxError: invalid syntax C'est pas plutôt /home/cacao/.Qarte/livedata_fr.py qui merde? Dernière modification par n.mazerat (Le 31/01/2013, à 01:40) Hors ligne elrockito87 Re : Qarte arte.tv browser (ex Qarte+7) Un petit up pour savoir si qq1 a une idée pour mon pb sous voyager 12.04 qarte Erreur de segmentation (core dumped) Un GRAND merci pour celui qui me permettra d'utiliser a nouveau ce petit bijoux! N'allez pas là où le chemin peut mener. Allez là où il n'y a pas de chemin et laissez une trace. [Ralph Waldo Emerson] Ne restreins pas le champ du possible aux limites de ton imaginaire. [Antony Bouchardon] Hors ligne joombuntu Re : Qarte arte.tv browser (ex Qarte+7) Le "return" a réglé mon problème, merci leTrolldesForets Belle journée à tous, "Que votre combat ne vous transforme pas en l’image de vos ennemis !" Georges Orwell,La ferme des animaux Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Salut, Le problème de cette nuit venait du fichier d'update des URLs qui était illisible, je l'ai changé ce matin, donc tout doit être rentré dans l'ordre. @elrockito87, Plusieurs de ces nouveaux thèmes plantent les applications Qt, c'est le cas de Voyager. Dans l'état, je ne peux rien faire, sinon faire un rapport de bug au dévs de Voyager, mais pour ça il faut que j'installe ce thème et que je fasse une série de tests. Hors ligne
SQL_BUFFER_RESULT creates a temporary table on the server for every result set. This is not a temporary table like CREATE TEMPORARY TABLE - it is an implicit temporary table as would be created when using a GROUP BY clause or with a subquery. As such, all the same rules apply. First, let's talk the problem that SQL_BUFFER_RESULT is designed to solve: When the client requests data from the server, until the entire result set has been transmitted to the client the query is still "running" and some locks may still be held. While the data is being transmitted, it will appear in the Sending data state. It is library dependent on whether the client just gets all the data at once when the query is executed, or if it trickles in as you select rows, but an example of a problem is as follows: resultset = conn["SELECT * FROM bigtable"] resultset.each do |row| data[:value] = row[:value] sleep 10 # do something expensive here end Obviously contrived, but in the case above if there are 1000 rows, the query will still be actively running for 10,000 seconds. That may seem far fetched, but a lot of applications have "think time" in-between fetching each row because they do some processing. This is "a very bad thing to do." Another case where this type of trickle effect could occur is with a large result set over a slow connection. Ultimately, the problem is the trickling of data to the client causing the query to remain in an active state. SQL_BUFFER_RESULT resolves this problem by buffering the result into a temporary table first, which makes the query end faster, thus releasing all of its locks (what locks?). The result set is then fed to the client from the temporary table rather than the query itself. That sounds great! But... Temporary tables take up memory and other resources on the server. Lots of temporary tables == lots of resources. Tables that exceed the minimum of tmp_table_size or max_heap_table_size will end up being converted to on-disk temporary tables, which means additional I/O. It also means that your queries take longer, as once the size of the MEMORY table reaches tmp_table_size, it is then converted to an on-disk MyISAM table. BLOB/TEXT fields cannot be stored as in-memory temporary tables (the MEMORY storage engine does not support them), thus will always be created on disk. creating temporary tables is expensive, especially when they are on-disk. Consider that one of the first things we try to optimize away when looking at an explain plan is "Using temporary." SQL_BUFFER_RESULT literally makes every query include "Using temporary", (nearly) all the time. My little bit of testing showed that there were cases where MySQL did not use a temporary table even with this hint, but they were limited (single row lookups on primary key seemed to be the only case). Here are a few examples to show the effect: -- unindexed lookup w/out SQL_BUFFER_RESULT mysql> explain select * from actor where first_name = 'THORA'\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: actor type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 203 Extra: Using where 1 row in set (0.00 sec) -- unindexed lookup w/SQL_BUFFER_RESULT mysql> explain select sql_buffer_result * from actor where first_name = 'THORA'\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: actor type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 203 Extra: Using where; Using temporary 1 row in set (0.00 sec) -- indexed lookup w/out SQL_BUFFER_RESULT mysql> explain select * from actor where last_name = 'TEMPLE'\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: actor type: ref possible_keys: idx_actor_last_name key: idx_actor_last_name key_len: 137 ref: const rows: 4 Extra: Using where 1 row in set (0.00 sec) -- indexed lookup w/SQL_BUFFER_RESULT mysql> explain select sql_buffer_result * from actor where last_name = 'TEMPLE'\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: actor type: ref possible_keys: idx_actor_last_name key: idx_actor_last_name key_len: 137 ref: const rows: 4 Extra: Using where; Using temporary 1 row in set (0.00 sec) -- primary key lookup w/SQL_BUFFER_RESULT mysql> explain select sql_buffer_result * from actor where actor_id = 200\G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: actor type: const possible_keys: PRIMARY key: PRIMARY key_len: 2 ref: const rows: 1 Extra: 1 row in set (0.00 sec) What is the problem being solved for? "locks." Since this is a hint for SELECT queries, unless you are using FOR UPDATE or LOCK IN SHARED MODE, there are very few locks taken on reads anyhow and they are very fast, so you are mostly solving for a problem that doesn't exist. Exceptions always exist, but the overhead of creating a temporary table for nearly every query will far outweigh any benefit gained from making locks go away faster. MySQL's recommendation is to use the SQL_BUFFERED_RESULT hint when retrieving a very large result set over a network connection to the client. I cannot see any value in using it in another context. All that being said, you can test and set this "globally" by setting sql_buffer_result=1 at the beginning of every session. In an environment with any concurrency, I would predict poor results.
fredajt [Résolu] Installation Tiny-erp Bonsoir, j'essaie d'installer Tiny erp 4.2 depuis trois ou quatre jours sans succès. J'ai suivi différents tutos de la documentation et du forum officiel, mais le client ne veut pas se lancer quand je fais alt+f2. Le seul message d'erreur que j'ai est : File "/usr/lib/python2.5/SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: (98, 'Address already in use') Tout à l'air pourtant installé, enfin je suppose. J'ai essyé à différentes reprise l'installation, par Synaptic aussi, mais rien ne fonctionne. Par désespoir j"ai aussi essayé sur windows xp => le client se lance mais pas de connection avec la base... Je ne sais plus quoi faire. Si quelqu'un à une idée... Ps : Bravo à cette formidable communauté ! fredajt Re : [Résolu] Installation Tiny-erp Au fait je suis sur ubuntu 7.10 oussama Re : [Résolu] Installation Tiny-erp Normalement, avec "Address already in use". Essayez: sudo /etc/init.d/tinyerp-server stop Password: Stopping tinyerp-server: tinyerp-server. tinyerp-server Ce lien peut t'aider : http://doc.ubuntu-fr.org/tinyerp_7.10 Hors ligne fredajt Re : [Résolu] Installation Tiny-erp Merci Oussama, mais ça ne marche pas chez moi. Il me semble pourtant avoir suivit la doc à la virgule près...:rolleyes: shovelhead Re : [Résolu] Installation Tiny-erp 1) d'abord: sudo su- ps aux | grep tiny Ca doit te donner une ligne du genre : root 6154 0.0 6.3 70340 24624 ? Sl Apr08 11:00 python tinyerp-server.py -r terp -d terp -w terp -s --db_port=5433 --db_host=localhost Pour stopper ce processus, faire un : kill 6154 (6154 est le numéro du processus (PID) et sera différent sur ta machine) Ensuite, il faut lancer le serveur en interactif avec les commandes suivantes : cd /usr/lib/python2.5/site-packages/tinyerp-server/ python tinyerp-server.py -r terp -d terp -w terp -s --db_port=5433 --db_host=localhost vérifie le no du port utilisé sur ta machine (c'est 5433 sur la mienne, mais peut être 5432 sur la tienne....). Normalement, le tinyerp-server se lance (vérifier si la connexion à la base de données est réussie). Par contre, on ne récupère pas la ligne de commande du terminal, le tinyerp-server reste actif et attend les commandes des tinyerp-client. 2) Connexion avec le client On lance ensuite un tinyerp-client (sur la même machine ou sur une autre dans le réseau, peu importe). Dans le client, on sélectionne le menu "fichier" -> "Base de données" -> "nouvelle base de données" Dans la fenêtre, il faut mettre : Mot de passe super admin : admin Nouvelle base de données : mettre le nom de la nouvelle base de données (par exemple "monenreprise") Ne pas cocher "démo" pour avoir une base complètement vide!!! et choisiŕ le langage En cliquant sur le bouton "valider", le client va tenter de créer une nouvelle base. Sur le terminal du tinyerp-server, on va te demander le mot de passe pour le serveur mot de passe : terp Tu tapes "terp" et l'installation de la nouvelle base est en route. 3) Lorsque tout est bien installé, on peut redémarrer le serveur en mode normal. On arrête donc le serveur intéractif avec les touches "Control + C", puis le plus simple est de redemarrer la machine (ou alors de faire un /etc/init.d/tinyerp-server restart). facile, quoi? Stefan Dernière modification par shovelhead (Le 08/04/2008, à 15:34) si tu trouves un erreur d'orthographe, tu peux le garder. Je les fais exprès pour l'amusement des lecteurs français Hors ligne fredajt Re : [Résolu] Installation Tiny-erp Bonsoir, et merci pour vos réponses. J'ai bien réussi à stopper le service et à lance le server. Mais lorsque je lance le client pour créer la nouvelle bd j'ai de nouveau le message "could not connect..." et dans mon terminal resté en suspend, le message suivant est apparu : Thu, 10 Apr 2008 22:10:46 ERROR:web-services:Exception in call: Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/tinyerp-server/netsvc.py", line 200, in _dispatch r=m(*params) File "/usr/lib/python2.5/site-packages/tinyerp-server/service/web_services.py", line 250, in list db = sql_db.db_connect('template1') File "/usr/lib/python2.5/site-packages/tinyerp-server/sql_db.py", line 140, in db_connect tdb = psycopg.connect('%s %s %s %s %s' % (host, port, name, user, password), serialize=0, maxconn=maxconn) OperationalError: FATAL: authentification par mot de passe échouée pour l'utilisateur « terp » On dirait bien qu'il y a un pb de mot de passe, mais je n'ai pas l'occasion de le renseigner. Lorsque je tente la manip à nouveauj 'obtiens : File "tinyerp-server.py", line 213, in <module> httpd = netsvc.HttpDaemon(interface,port, secure) File "/usr/lib/python2.5/site-packages/tinyerp-server/netsvc.py", line 265, in __init__ SimpleXMLRPCRequestHandler,0) File "/usr/lib/python2.5/SimpleXMLRPCServer.py", line 523, in __init__ SocketServer.TCPServer.__init__(self, addr, requestHandler) File "/usr/lib/python2.5/SocketServer.py", line 330, in __init__ self.server_bind() File "/usr/lib/python2.5/site-packages/tinyerp-server/netsvc.py", line 233, in server_bind SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) File "/usr/lib/python2.5/SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: (98, 'Address already in use') Je commense à être usé . Merci à tous ! delphin2 Re : [Résolu] Installation Tiny-erp Bonjour, Télécharges ce client là et dézippes-le : http://www.tinyerp.com/index.php?option=com_joomlaxplorer&action=list&dir=stable%2Fsource&order=name&srt=yes Si le lien ne marche pas met-le directement dans la barre d'adresse d'une autre fenêtre. Comprend pas le lien foire:rolleyes: EDIT : sinon ça http://www.tiny-erp.fr/download/ Dernière modification par delphin2 (Le 17/04/2008, à 14:22) Hors ligne Patrice.Lepissier Re : [Résolu] Installation Tiny-erp J'ai eu les mêmes problèmes pour installer Tiny ERP. L'installation du serveur depuis Synaptics n'a jamais fonctionné, par contre en suivant le tuto et après avoir taper les commandes : $ cd /usr/lib/python2.5/site-packages/tinyerp-server/ $ sudo python tinyerp-server.py -r terp -d terp -w terp -s puis pour lancer le serveur tapez tout simplement : $ tinyerp-server Maintenant, pour le serveur ça roule. Par contre pour le client. Si je le lance en m'identifiant en root, ça marche nickel. Si je m'identifie avec mon identifiant personnel (appartenant au groupe root), j'ai le message : patrice@patrice-D430:~$ tinyerp-client Traceback (most recent call last): File "./tinyerp-client.py", line 93, in <module> import modules File "/usr/lib/tinyerp-client/modules/__init__.py", line 30, in <module> import gui File "/usr/lib/tinyerp-client/modules/gui/__init__.py", line 29, in <module> import main File "/usr/lib/tinyerp-client/modules/gui/main.py", line 40, in <module> import rpc File "/usr/lib/tinyerp-client/rpc.py", line 37, in <module> import common File "/usr/lib/tinyerp-client/common/__init__.py", line 29, in <module> from common import * File "/usr/lib/tinyerp-client/common/common.py", line 68, in <module> terp_path_pixmaps('tinyerp-icon-32x32.png')) TypeError: pixbuf_new_from_file() argument 1 must be string, not bool patrice@patrice-D430:~$ Si quelqu'un peut me dire ce qui se passe, je le remercie d'avance. PClF W550SU1 15.6" LED Intel HD 4600 Haswell XUbuntu 14.04 Hors ligne fredajt Re : [Résolu] Installation Tiny-erp 1) d'abord: sudo su- ps aux | grep tiny Ca doit te donner une ligne du genre : root 6154 0.0 6.3 70340 24624 ? Sl Apr08 11:00 python tinyerp-server.py -r terp -d terp -w terp -s --db_port=5433 --db_host=localhost Pour stopper ce processus, faire un : kill 6154 (6154 est le numéro du processus (PID) et sera différent sur ta machine) Ensuite, il faut lancer le serveur en interactif avec les commandes suivantes : cd /usr/lib/python2.5/site-packages/tinyerp-server/ python tinyerp-server.py -r terp -d terp -w terp -s --db_port=5433 --db_host=localhost vérifie le no du port utilisé sur ta machine (c'est 5433 sur la mienne, mais peut être 5432 sur la tienne....). Normalement, le tinyerp-server se lance (vérifier si la connexion à la base de données est réussie). Par contre, on ne récupère pas la ligne de commande du terminal, le tinyerp-server reste actif et attend les commandes des tinyerp-client. Bonjour, et merci beaucoup pour vos conseils. Depuis un moment j'avais laissé tombé l'install sur Ubuntu. Mais j'en ai marre de rebooter sans cesse sur cette M**** de Windows juste pour Tiny. Et depuis cette formidable version 8.04, j'ai qu'une hâte voir tourner Tiny dessus !! Donc, j'ai réussi à killer les processus gênants, et maintenant le server semble trouver la bd, mais, il attends les connections. Du côté du client, il ne peut toujours pas se connecter à la base, ni en créer une nouvelle. J'ai regarder les .terprc er .server-rrvrc qui ont l'air correct. Que faire ?? Et savez-vous ou trouver le fichier qui détermine les port de pgsql ? fredajt Re : [Résolu] Installation Tiny-erp p'tite précision : j'ai pu vérifier/corriger le port de pgsql Après avoir suivi les étapes recommandée par shovelhead, j'ai le client qui bug quand j'essai de créer une nouvelle base, et le server, dans mon terminal, qui attends la connexion et ne me demande pas le mot de passe. J'avance, à pas de fourmis, mais j'avance édit : une étape à été loupée puisque après vérification le server m'indique qu'il ne peut pas se connecter à la db terp Dernière modification par fredajt (Le 05/06/2008, à 16:55) Hors ligne Christouf Re : [Résolu] Installation Tiny-erp p'tite précision : j'ai pu vérifier/corriger le port de pgsql Après avoir suivi les étapes recommandée par shovelhead, j'ai le client qui bug quand j'essai de créer une nouvelle base, et le server, dans mon terminal, qui attends la connexion et ne me demande pas le mot de passe. J'avance, à pas de fourmis, mais j'avance édit : une étape à été loupée puisque après vérification le server m'indique qu'il ne peut pas se connecter à la db terp Je suis exactement au même point!! maintenant Hors ligne fredajt Re : [Résolu] Installation Tiny-erp Bon, après désinstallation/réinstallation et divzers changement de version de logiciels, je suis revenu sur ma première config : Tiny 4.2.2 + pgsql 8.2, et j'en suis de nouveau rendu à la même étape avec le même message 'erreur quand je lance le serveur : Traceback (most recent call last): File "./tinyerp-server.py", line 213, in <module> httpd = netsvc.HttpDaemon(interface,port, secure) File "/usr/lib/python2.5/site-packages/tinyerp-server/netsvc.py", line 265, in __init__ SimpleXMLRPCRequestHandler,0) File "/usr/lib/python2.5/SimpleXMLRPCServer.py", line 523, in __init__ SocketServer.TCPServer.__init__(self, addr, requestHandler) File "/usr/lib/python2.5/SocketServer.py", line 330, in __init__ self.server_bind() File "/usr/lib/python2.5/site-packages/tinyerp-server/netsvc.py", line 233, in server_bind SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) File "/usr/lib/python2.5/SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: (98, 'Address already in use') Que dois-je faire ? Il y a-t-il une meilleur configuration à avoir ? pgsql 8.3 ? avec quelle version de Tiny ? Où ai-je simplement loupé une étape ? Merci d'avance Hors ligne fredajt Re : [Résolu] Installation Tiny-erp Ca y est !! Alors pour ceux qui sont dans mon cas j'ai solutioné le problème de cette façon : Désinstallation de postgresql Effacement des répertoires du server TinyERP dans /usr/lib/python2.5/site-packages et dans /usr/share/ Installation de postgresql-8.2 avec un : apt-get install postgresql-8.2 Téléchargement de tinyerp-server-4.2.2 (dernière version stable) à télécharger ici : http://openerp.com/downloads.html Suivre les indications pour créer une base de donnée UNICODE !! ici http://openerp.com/wiki/index.php/Insta … d_database Suivre les indications pour installer le Tiny server ici : http://doc.ubuntu-fr.org:81/tinyerp_7.10 Et puis la suite classique, création d'une nouvelle base blablabla.... Donc le choix de la version de postgresql est importante. Mais SURTOUT après désinstallations-réinstallation du server Tiny il FAUT purger les répertoires sinon ça bug. En tout cas ça à marché pour moi. :D:P PS: pas besoin d'enlever le client. Dernière modification par fredajt (Le 11/06/2008, à 12:42) Hors ligne
In our Tour of Extensions today's article is about advanced tag indexing. Wehave a great data collection to play with and our goal today is to be ableto quickly find data matching a complex set of tags. So, let's find outthose lastfm tracks that are tagged as blues and rhythm and blues, forinstance. In this article, we're going to play with music related tags We're going to use the Last.fm dataset from the Million Song Dataset project here. The article where they present their similarity searches is providing the whole dataset they have as a SQLite database and they propose to read their python script demo_tags_db.py to make sense of it. The Setup First, we need to import this dataset into a PostgreSQL database. To do thatthe easier path I could think of was to hack the capability into pgloader ofcourse, so here we go: table name read imported errors time------------------------------ --------- --------- --------- --------- tags 0 522366 0 3.922 tids 0 505216 0 3.746 tid_tag 0 8598630 0 115.349 index build completion 0 0 0 33.099------------------------------ --------- --------- --------- --------- create index 0 8 0 38.839 reset sequences 0 0 0 0.064------------------------------ --------- --------- --------- --------- Total streaming time 0 9626212 0 2m36.180s Here, pgloader extracted the table and index definitions from the SQLitedatabase using the sqlite_master catalog and the PRAGMA table_info()commands, and migrated the data in a streaming fashion down to PostgreSQL,using the COPY protocol. Having a look at the demo_tags.py script we can actually see how to use therelations here, and we realize they are using the64-bit signed integer ROWID system column. We need something comparable tobe able to make sense of the data: tags# alter table tags add column rowid serial; ALTER TABLE Time: 3177.603 ms tags# alter table tids add column rowid serial; ALTER TABLE Time: 2528.680 ms tags# SELECT tags.tag, COUNT(tid_tag.tid) FROM tid_tag, tags WHERE tid_tag.tag=tags.ROWID and tags.tag ~* 'setzer' GROUP BY tags.tag; tag | count -----------------------------+------- the brian setzer orchestra | 1 Setzer | 13 rockabilly Setzer style | 4 setzer is a true guitarhero | 9 brian setzer orchestra | 3 brian setzer is GOD | 1 Brian Setzer | 1 brain setzer orchestra | 2 (8 rows) Time: 644.826 ms Here the query is mainly doing a JOIN in between the tid table (containingtrack ids) and the tid_tag table (containing association in between tracksand tags), filtering on the case insensitive regular expression 'setzer'. Aswe can imagine from reading the query execution time, we don't have anyindex to implement the filtering here. Advanced tag indexing PostgreSQL comes with plenty of interesting datatypes, one of them is knownas the Arrays Type. PostgreSQL also provides a very rich set of extensions,some of them found under the contrib package; one of them is intarray. Letme quote for you the most interesting part of the documentation for thatextension: The @@ and ~~ operators test whether an array satisfies a query, which is expressed as a value of a specialized data type query_int. A query consists of integer values that are checked against the elements of the array, possibly combined using the operators & (AND), | (OR), and ! (NOT). Parentheses can be used as needed. For example, the query 1&(2|3) matches arrays that contain 1 and also contain either 2 or 3. PostgreSQL Documentation in F.18. intarray tags# create extension intarray; CREATE EXTENSION The way the intarray extension works, we need to build a new table thatcontains for each track the list of tags it's been associated with, as anarray of integers. We're going to use our rowid identifier for that purpose,as in the following query: tags# SELECT tt.tid, array_agg(tags.rowid) as tags FROM tags JOIN tid_tag tt ON tags.rowid = tt.tag GROUP BY tt.tid LIMIT 3; tid | tags -----+----------- 1 | {1,2} 2 | {3,4} 3 | {5,6,7,8} (3 rows) Time: 942.074 ms So let's build the full table then index it: tags# CREATE TABLE track_tags AS SELECT tt.tid, array_agg(tags.rowid) as tags FROM tags join tid_tag tt on tags.rowid = tt.tag GROUP BY tt.tid; SELECT 505216 Time: 45388.424 ms tags# create index on track_tags using gin(tags gin__int_ops); CREATE INDEX Time: 18645.931 ms Searches Now PostgreSQL is ready for the real magic. Let's find all the tracks wehave that have been tagged as both blues and rhythm and blues: tags# select array_agg(rowid) from tags where tag = 'blues' or tag = 'rhythm and blues'; array_agg ----------- {3,739} (1 row) Time: 0.684 ms Now what we want is a query_int query string, which looks like'(1880&179879)', so rather than just array_agg we're going to use thefollowing query: tags# select format('(%s)', array_to_string(array_agg(rowid), '&') )::query_int as query from tags where tag = 'blues' or tag = 'rhythm and blues'; query --------- 3 & 739 (1 row) Time: 0.747 ms That query here allows us to easily inject as many tags as we want to, sothat it's easy to use it as a template from within an application where theuser is going to provide for the tags list. The intarray extension's queryformat also accepts other operators (or and not) as we saw before, so if youwant to expose those to your users you would need to tweak the query_intbuilding part of the SQL. Now, how many tracks have been tagged with both the bluesand therhythm and bluestags, will you ask me: tags# with t(query) as ( select format('(%s)', array_to_string(array_agg(rowid), '&') )::query_int as query from tags where tag = 'blues' or tag = 'rhythm and blues' ) select count(*) from track_tags, t where tags @@ query; count ------- 2278 (1 row) Time: 8.242 ms Now of course you might want to fetch some track meta-data, here the onlyone we have is the track hash id: tags# with t(query) as ( select format('(%s)', array_to_string(array_agg(rowid), '&') )::query_int as query from tags where tag = 'blues' or tag = 'rhythm and blues' ) select track.tid from track_tags tt join tids track on tt.tid = track.rowid, t where tt.tags @@ t.query limit 10; tid -------------------- TRCJLCC12903CBF4AE TRCIFOV128F92F6F4C TRCYUVJ128F425C8F1 TRCNTFO128F92F6564 TRCDRGT12903CE64BF TRCWAED128F42A837B TRCWFEM128F9320F94 TRCQCQH128F932E707 TRCUMTA12903CD67EE TRJJYUT12903CFB13B (10 rows) Time: 7.630 ms Conclusion The usual way to handle a set of user defined tags and query against itinvolves join against a reference table of tags, but then it's quitecomplicated to express the full search query: we want tracks tagged withboth blues and rhythm and blues and might want then to exclude fingerpicking. The intarray extension provides a powerful query specialized language withdirect index support, so that you can build dynamic indexes searchesdirectly from your application.
Suspending Traffic for Zero-Downtime Migrations Some time ago, we had to perform a fairly intensive database migration. Since we process payments for a number of marketplaces who don’t want any downtime at all, scheduling a maintenance window to perform the migration wasn’t an option. We had to do everything without taking our app offline for even a short period of time. tl;dr We used HAProxy to suspend traffic for a short period of time, while we switched out DBs. The normal way Normally when doing a database migration online, the correct way to do this involves multiple steps: perform schema changes in a way that won’t break existing code (e.g., temporarily allowing new non-nullable columns to be NULL). deploy code that works with both the old and new schema simultaneously, populating any new rows according to the new schema. perform a data migration that backfills any old data correctly, and updates all constraints properly. deploy code that only expects to see the new schema. The harder way Our migration was drastic enough that the amount of code we would have had to write to be compatible with both schemas simultaneously was prohibitive, so we started looking for a simpler way. We reasoned that if we could continue to accept incoming requests, but keep them from hitting our app for a short period of time, we could perform the migration and replace our code in one step. Most clients hitting our API will time out after 60 seconds with no response, so this set an upper bound for how long we could stall traffic. As it happens, we have some customers with even stricter client-side timeouts set, and we wanted to keep everyone happy. This led us to settle on 15 seconds as the longest we could stall traffic and not get any complaints from our users. Since we couldn’t stop requests from coming in, and we didn’t want any incoming requests to fail, we would have to hold them somewhere. We were familiar with the approach that Braintree, another payment service provider, had used to solve a similar issue, but their approach involved custom routing software and holding all requests in a Redis queue, which didn’t really fit with our existing topology. Our topology looks like this: We have an Amazon Elastic Load Balancer at api.balancedpayments.com proxying to a number of nginx instances, which forward traffic to HAProxy load balancers. These HAProxy instances proxy traffic to our Balanced application instances. Being that our topology is so simple, there are only a few places where requests can be held – nginx, HAProxy, or our app itself. Of the three, HAProxy seemed like the most likely candidate. HAProxy is an amazing piece of software. In addition to being extremely quick and reliable, it’s also configurable on the fly, via its (oddly-named) “stats socket”. By piping commands to a UNIX socket, one can dynamically change many parameters and control how requests are proxied. In this case, we wanted to tell HAProxy that Balanced was still up (so it didn’t report 5XX errors to the client), but that it shouldn’t forward any new requests. Initial failures is the maximum number of concurrent connections the frontend will accept to serve. Excess connections will be queued by the system in the socket’s listen queue and will be served once a connection closes. This sounds like what we want – the OS itself will queue requests, and once we’re done we can just modify the config file and SIGHUP HAProxy to get the new value. Except this didn’t work. Setting maxconn to zero worked just fine – requests were kept alive from the client’s point of view, and never hit our app. It turns out, though, that HAProxy responds differently than other software to SIGHUP, and doesn’t use it to reload its config file. Oops. The documentation also mentions using SIGTTOU and the ‘-st’ and ‘-sf’ options as a “soft-reconfiguration mechanism,” which sounds great. Unfortunately, the way it works wasn’t quite as expected – you issue SIGTTOU to pause proxies, then start a new instance with the new config. This means that any connections to the instance of HAProxy with maxconn set to zero will never get a chance to complete. Finally These failures eventually led us to the previously-mentioned stats socket, which allows us to issue the command set maxconn frontend balanced 0 to stop accepting new connections for a given frontend, and set maxconn frontend balanced 100 to start again. So simple! Except – first, we had to upgrade to the HAProxy development version (1.5) to support setting maxconn on the frontend at all. Then, the first command didn’t work, since the ‘set’ command would only accept values over zero. I was about to hack a fix into HAProxy myself, but first decided to contact Willy Tarreu, the author, to see if he had a better recommendation. After discussing the issue, he was kind enough to release a small patch allowing maxconn to be set to zero in the frontend context and test it in the use case I had described. We tested how long the database migration would take on a copy of the database, and got it down to 13 seconds. This gave us a two-second leeway in which to perform all the administrative tasks involved in this migration. We had two people open terminals and prepare the commands to be run, and prepared to execute them rapidly in sequence. The process Deploy an instance of the app with the new code, but don’t route any traffic to it. First engineer suspends all traffic to our Balanced frontend, queueing requests in HAProxy. Yell at the other person to start the data migration. Second engineer starts the data migration. Wait 13 seconds for db migration to complete. Yell at the first engineer that the migration is done. First engineer quickly resumes traffic to the app instance with new code. Deploy updated code to all instances and resume at leisure. The first time we attempted this it worked flawlessly, with no requests failing or timing out. Usage We added two simple tasks to our Fabric fabfile: @parallel def suspend(): """ Suspends all connections to balanced. To be used sparingly. """ with _make_tunnel(): run('echo "set maxconn frontend balanced 0" | socat stdio /var/lib/haproxy/stats') @parallel def resume(): """ Re-allow connections to balanced. """ with _make_tunnel(): run('echo "set maxconn frontend balanced 100" | socat stdio /var/lib/haproxy/stats') Now, using Fabric to automate the stats socket commands across all instances of HAProxy simultaneously, we can issue a simple command like fab suspend to hold all requests indefinitely, perform any time-consuming migrations/code updates/deploys, and then issue fab resume to allow the blocked connections to finally make their way to our backend. We’ve only had to use this heavy-handed approach twice in the past six months, whereas we’ve performed hundreds of code deploys and tens of database migrations, but having the option available to us has been a lifesaver.
I am getting a Unicode decode error while creating unicode item in rdflib namespace $ python Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from rdflib.graph import ConjunctiveGraph >>> from rdflib import Namespace, BNode, Literal, RDF, URIRef ***>>> rdfsNS = Namespace("http://www.w3.org/2000/01/rdf-schema#") >>> item = "Petra Němcová" >>> i = rdfsNS[item]*** Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/rdflib/namespace.py", line 88, in __getitem__ return self.term(key) File "/usr/local/lib/python2.7/dist-packages/rdflib/namespace.py", line 85, in term return URIRef(self + name) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128) Please help resolving this issue.
Bybeu [résolu] Problème veille carte nvidia 4200 nvidia96 EDIT 27 mars 2013: j'ouvre un nouveau fil ici: http://forum.ubuntu-fr.org/viewtopic.php?id=1210781 Bonjour Mon portable 12.04 plante en sortie de veille; J'ai essayé sudo s2ram -n Machine matched entry 222: sys_vendor = 'Dell Computer Corporation' sys_product = 'Latitude D800 *' sys_version = '' bios_version = '' Fixes: 0xc VBE_SAVE VBE_POST This machine can be identified by: sys_vendor = "Dell Computer Corporation" sys_product = "Latitude D800 " sys_version = "" bios_version = "A13 J'ai essayé ensuite sudo s2ram --force --vbe_save --vbe_post mais ça plante quand même; le 0xc c'est un paramètre aussi, c'est pas dans le man? Ils disent qu'il faut décharger et recharger le driver (moi j'ai le nvidia96); Comment on fait ça s'il vous plaît? Ce que j'aimerais si ça marche, ça serait de remplacer les commandes cachées derrière les menus de ubuntu pour mettre ce qu'il faut pour que ça marche; Merci Dernière modification par Bybeu (Le 27/02/2013, à 10:34) Hors ligne ljere Re : [résolu] Problème veille carte nvidia 4200 nvidia96 tu as essayé cette méthode /viewtopic.php?pid=9049191#p9049191 Hors ligne Bybeu Re : [résolu] Problème veille carte nvidia 4200 nvidia96 Oui bien sûr, obligé, sinon le nvidia96 ne serait pas compatible avec ma 12.04; Et aussi obligé car sans nvidia96, le driver nouveau est tout pourri (mais la veille marche ); En fait avec nvidia96 l'écran s'allume en sortie de veille, mais avec une image brouillée pire que canal+ (on devine rien) et puis tout noir, plus rien, même Alt+Imp+K semble n'avoir aucun effet. Hors ligne harlock59 Re : [résolu] Problème veille carte nvidia 4200 nvidia96 bonjour, j'utilise un imac g4 flat panel (tournesol) et j'ai une image horrible. j'ai lancé le cd de precise pangolin, dans yaboot j'ai tapé live nouveau.modeset=0 pour pouvoir continuer sinon j'avais un écran noir. mais je n'arrive pas à instaler nvidia-96 car je suis sur powerpc. ma carte graphique est une geforce 4 mx si quelqu'un pouvait m'aider ? merci. Hors ligne Bybeu Re : [résolu] Problème veille carte nvidia 4200 nvidia96 driver 96 [enfin] dispo dans -proposed: https://bugs.launchpad.net/ubuntu/+sour … bug/948053 Hors ligne Bybeu Re : [résolu] Problème veille carte nvidia 4200 nvidia96 Ouf! J'ai enfin pu avoir un driver video qui marche (au moins pour afficher) avec "Precise" et le xorg actuel (non downgradé); Je suis donc maintenant revenu dans une conf logicielle normale, mais j'ai toujours ce problème d'écran noir au réveil des modes veille et hibernation. Maintenant je vois au moins les étapes de mise en hibernation se succéder correctement à l'écran, et aussi celles du réveil correspondant: on voit le swap se déverser dans des pages de ram jusqu'à 100%... et puis écran noir. Ctrl+Alt+F1 ne donne rien, Alt+Imp+K non plus, seul Alt+Imp+B fait son effet... radical Hors ligne Bybeu Re : [résolu] Problème veille carte nvidia 4200 nvidia96 mâââgik ! Suite à un écroulement de batterie, le portable est parti en hibernation et il s'est réveillé correctement. Incroyable; On va voir si c'est reproductible... et tenter le suspend to ram... Hors ligne Bybeu Re : [résolu] Problème veille carte nvidia 4200 nvidia96 kigâm ça marche une fois sur deux: à la deuxième y'a pas de prise d'image de la ram. L'ordi se bloque avant de s'éteindre. Hors ligne Bybeu Re : [résolu] Problème veille carte nvidia 4200 nvidia96 Hors ligne
I installed Virtualenv on Ubuntu 12.04 and was using it to work on a sample project under the unity desktop. I'm using VirtualBox and was having some issues with the unity desktop so changed to the KDE desktop. I'm now trying to create a new project but the virtualenv won't allow me to create a new environment in my project folder. In the terminal I navigate to the project folder, type virtualenv venv and get the following error messages: Traceback (most recent call last): File "/usr/bin/virtualenv", line 3, in <module> virtualenv.main() File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 938, in main never_download=options.never_download) File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 1039, in create_environment site_packages=site_packages, clear=clear)) File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 1215, in install_python copyfile(stdinc_dir, inc_dir) File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 430, in copyfile copyfileordir(src, dest) File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 405, in copyfileordir shutil.copytree(src, dest, True) File "/usr/lib/python2.7/shutil.py", line 206, in copytree raise Error, errors shutil.Error: [('/usr/include/python2.7/numpy', 'venv/include/python2.7/numpy', '[Errno 30] Read-only file system')] Can anyone help me resolve this? I've tried reinstalling virtualenv but no joy. Thanks
Python Dictionaries A Python dictionary has the same benefit as a regular paper dictionary. It allows you to quickly locate the value (definition) associated with a key (word). Dictionaries are denoted by curly braces and contain a comma-separated sequence of key:value pairs. Dictionaries are not ordered. Instead, dictionary values are accessed by their key value, rather than their position in the sequence. Let's look at some of the methods supported by dictionaries. >>> basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'} >>> basecomplement.keys() ['A', 'C', 'T', 'G'] >>> basecomplement.values() ['T', 'G', 'A', 'C'] >>> basecomplement['A'] 'T' >>> basecomplement['C'] 'G' >>> for base in basecomplement.keys(): ... print "The complement of", base, "is", basecomplement[base] ... The complement of A is T The complement of C is G The complement of T is A The complement of G is C >>> for base in basecomplement: ... print "The complement of", base, "is", basecomplement[base] ... The complement of A is T The complement of C is G The complement of T is A The complement of G is C In this example we also introduced the concept of a for loop, which cycles over the keys of the basecomplement dictionary. Python's for loop can iterate over any sequence. In this example it assigns the first value from the list returned by keys() to the variable named base, executes the print statement, then repeats the process for each subsequent value in the list. In the second for loop example, you can see that when we simply specify "for base in basecomplement" Python defaults to looping over the basecomplement dictionary's keys. More User-defined Functions The next example will demonstrate one other technique we will need in our complement function. It's a relatively new feature of Python, called list comprehensions. >>> letters = list('CCGGAAGAGCTTACTTAG') >>> [basecomplement[base] for base in letters] ['G', 'G', 'C', 'C', 'T', 'T', 'C', 'T', 'C', 'G', 'A', 'A', 'T', 'G', 'A', 'A', 'T', 'C'] A list comprehension returns a list and works similarly to a for loop, but in a much more compact and efficient format. In this case it allows us to return a new list where each base in the original list of letters has been replaced with its complement, which we retrieved from the basecomplement dictionary. Let's see how we put this all together. >>> def complement(s): ... """Return the complementary sequence string.""" ... basecomplement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} ... letters = list(s) ... letters = [basecomplement[base] for base in letters] ... return ''.join(letters) ... >>> complement('CCGGAAGAGCTTACTTAG') 'GGCCTTCTCGAATGAATC' Now that we've got a reverse function and a complement function, we have the building blocks for a reversecomplement function. >>> def reversecomplement(s): ... """Return the reverse complement of the dna string.""" ... s = reverse(s) ... s = complement(s) ... return s ... >>> reversecomplement('CCGGAAGAGCTTACTTAG') 'CTAAGTAAGCTCTTCCGG' It can also be useful to know the percentage of DNA composed of G and C bases. String objects have a count() method that returns the number of character occurences. With that information, calculating the percentage is a simple matter of applying some mathematical calculations. >>> def gc(s): ... """Return the percentage of dna composed of G+C.""" ... gc = s.count('G') + s.count('C') ... return gc * 100.0 / len(s) ... >>> gc('CCGGAAGAGCTTACTTAG') 50.0 >>> gc('CCGGAAGAGCTTACTTAGTTA') 42.857142857142854 Since DNA can be divided into three character segments (codons), a function that returned a list of codons would also be useful. Another simple mathematical calculation determines the ending point for our codons in case the DNA string is not evenly divisible by three. The range() function returns a list of numbers from a beginning point to an ending point, incrementing by some value, in this case 3. This arithmetic progression is used inside a list comprehension combined with string slicing to produce a list of three character strings. >>> def codons(s): ... """Return list of codons for the dna string.""" ... end = len(s) - (len(s) % 3) - 1 ... codons = [s[i:i+3] for i in range(0, end, 3)] ... return codons ... >>> codons('CCGGAAGAGCTTACTTAG') ['CCG', 'GAA', 'GAG', 'CTT', 'ACT', 'TAG'] String slicing is similar to string indexing. Instead of retrieving a single character, string slicing allows us to retrieve sections of characters from a starting position up to, but not including, an ending position. The syntax is s[i:j], where i is the starting position and j is the ending position. So s[0:3] returns a string containing the characters in index positions 0, 1, and 2. >>> s = 'CCGGAAGAGCTTACTTAG' >>> s[0:3] 'CCG' >>> s[3:6] 'GAA' >>> s[6:9] 'GAG' >>> s[9:12] 'CTT' Here is one final, interesting, note about functions. Functions themselves are objects. That means we can examine their attributes using dir(), just like we did for strings and lists. One of the more useful attributes of a function object is its documentation string, which gets stored in its __doc__ property. >>> dir(transcribe) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__name__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> transcribe.__doc__ 'Return dna string as rna string.' Don't worry if this last example is a bit esoteric. The main point of showing it was to emphasize that Python is very powerful and consistent, that everything in Python is an object, and that objects can be inspected on the fly. The result is that as you learn Python you will find that unfamiliar objects often behave exactly as you would expect them to behave the very first time you use them. This is a powerful feeling that's not experienced often enough when using other programming languages. We've seen how to create simple objects, like strings, lists, dictionaries, and functions. Next we're going to look at how we can create our own custom objects with properties and methods that we define.
bleuberry Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! si sa fonctionne sur chrome Adblock ?:P Dernière modification par bleuberry (Le 22/02/2010, à 11:24) Hors ligne sergeG75018 Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Ça fonctionne pas avec epiphany Hors ligne Hizoka Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! apres l'installation de ce hosts, il m'affiche une erreur à chaque utilisation de sudo : sudo: unable to resolve host hizo-pc quand je remets mon ancien fichier, pas de probleme... EDIT : j'ai dû ajouter : 127.0.1.1 hizo-pc Cela fonctionne pas mal Dernière modification par Hizoka (Le 23/02/2010, à 04:13) Hors ligne bleuberry Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! :(elle me fait vraiment chier :http://fr.partypoker.com/td/videopop/pp_videopop.htm Dernière modification par bleuberry (Le 23/02/2010, à 15:33) Hors ligne brizou Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Petite question j'ai une fonction dans mon routeur qui me permet de bloquer des sites Puis-je envoyer selon vous le fichier hosts sur le routeur directement, taper tout à la main, je préfèrerais éviter. Dernière modification par brizou (Le 25/02/2010, à 18:47) Hors ligne Patrik Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Ça fonctionne pas avec epiphany Ça ne peut pas ne pas fonctionner, car c'est au niveau des règles de résolutions des noms de domaines, indépendamment des applications. Hors ligne sergeG75018 Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! fallait juste redémarrer... merci. Hors ligne Lylyrian Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Ca me semble une bonne idée, surtout pour les liens malveillants. Par contre pour la pub, est-ce que ça ne pose pas de problème quand on veut aller sur un site qui d'habitude nous envoie de la pub ? Genre en temps normal on préfère ne pas voir les pubs des Trois pt'its suisses, mais le jour où on a une commande à faire, on a besoin de voir le site... Cela m'est déjà arrivé avec Adblock Plus (me souvient plus sur quels sites), là la solution était simple, désactiver Adblock le temps du surf. Mais s'il faut changer le fichier host c'est moins simple. Est-ce que ce genre de cas est géré d'une manière ou d'une autre ? Mieux vaut poser une question débile et avoir la réponse que de rester comme un con devant son ordi... Hors ligne bleuberry Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! la pub ces comme les cafards Hors ligne Hizoka Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! je vous poste ma version de mise à jour automatique (ajout automatique de 127.0.1.1 nom de la machine) avec un peu de couleur, des vérifications et expliquée : NOIR="\033[1;0m" BLEUFONCE="\033[1;34m" ROUGE="\033[1;31m" echo -e "\n${BLEUFONCE}Comparaison des versions...\n${NOIR}" # Vérification des versions V_local=$(sed -n 's/# AdZHosts v0*\(.*\)/\1/p' /etc/hosts) V_net=$(links -dump http://kosvocore.free.fr/AdZHosts/Version.txt | sed 's/ //g ; s/^0*//') # Comparaison des versions if [[ ${V_local} -lt ${V_net} ]] then echo -e "${BLEUFONCE}Mise à jour en cours...\n${NOIR}" # Téléchargement du fichier hosts wget "http://kosvocore.free.fr/AdZHosts/HOSTS.txt" -O /tmp/hosts # Vérification du download if [[ ! -e /tmp/hosts ]] then echo -e "${ROUGE}Une erreur est survenue pendant la récupération du fichier Hosts.\n${NOIR}" exit 1 fi # Ajout de la ligne 127.0.1.1 nom de la machine sed -i "/127.0.0.1.*localhost/a\127.0.1.1 $(uname -n)" /tmp/hosts # Vérification de la modification if [[ -z $(grep "127.0.1.1 $(uname -n)" /tmp/hosts) ]] then echo -e "${ROUGE}Une erreur est survenue pendant la modification du fichier Hosts.\n${NOIR}" exit 1 fi # Sauvegarde de l'ancinne version hosts sudo cp /etc/hosts /etc/hosts_$(date +%F) #Installation du nouveau hosts sudo cp /tmp/hosts /etc/hosts # Vérification de la bonne copie if [[ /tmp/hosts -nt /etc/hosts ]] then echo -e "${ROUGE}Une erreur est survenue pendant la copie du fichier Hosts.\n${NOIR}" exit 1 else rm /tmp/hosts echo -e "${BLEUFONCE}Mise à jour terminée.\n${NOIR}" fi elif [[ ${V_local} -eq ${V_net} ]] then echo -e "${BLEUFONCE}Fichier hosts déjà à jour...\n${NOIR}" exit 1 else echo -e "${ROUGE}Fichier hosts plus évolué que la version internet ??!\n${NOIR}" exit 1 fi dommage qu'il n'y est pas un fichier hosts sur le serveur, cela aurait permis d'être encore plus court et simple en utilisant le "wget --timestamping" afin de ne mettre à jour que si le fichier est lus recent que le local. si vous pouvez me faire un petit retour merci Dernière modification par Hizoka (Le 14/03/2010, à 00:49) Hors ligne Ctrl + Alt + Sup Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Fonctionne bien... Existe-t-il un moyen de remplacer tous les liens "tricards" par je sais pas, des carrés blancs pour éviter les pollutions genre "Not Found The requested URL bla bla ..." ? Shuttle XPc + Ubuntu 8.04 AMD Athlon(tm) XP2400+ / 2Gb RAM / 2*DD S-ATA 120 Gb / ATI9600 et pourtant tout roule ! Comme quoi ! Numéro d'utilisateur Linux 507046 Hors ligne Hizoka Hors ligne Qid Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! non le 1er est un .txt et le fichier hosts tu crois que c'est quoi ? c'est un fichier texte : je vois mal ce que tu voudrais "GNU/Linux c'est que du bon mais M$ Windows c'est pas si mal" bientôt 1 Gigabyte P35G W$ & UBUNTU pour moi + Ubuntu-gnome & KLXUbuntu + mint mate & cinamon pour démos1 Zalman de 120Go pour le GUL dont je suis le dépanneur de référence1 tablettes ASUS non rootée : Android 4.2.2 | doc.ubuntu-fr/Qid Hors ligne kyncani Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! A voir, si l'on a confiance dans le site. Je me suis également fait mon petit script de mise à jour, les goûts et les couleurs hein J'utilise un fichier /etc/hosts.local pour conserver les préférences locales. Et je ne change pas le fichier /etc/hosts si son contenu n'a pas changé. Le travail se fait silencieusement et il n'affiche quelque chose qu'en cas d'erreur. EDIT: J'ai changé ma procédure de mise à jour. Nouvelle version : #! /usr/bin/env python ####################################################################### ## ## Mise a jour de /etc/hosts a partir de http://www.adzhosts.com ## ## Decouvert via http://forum.ubuntu-fr.org/viewtopic.php?id=371304 ## ## - Les preferences locales du fichier /etc/hosts sont contenues ## dans /etc/hosts.local ## - Les mises a jour sont ignorees si elles redirigent vers un ip ## autre que 127.0.0.1 ou ::1 ## ####################################################################### ## Online host file, with associated valid ips hosts_provider = "http://kosvocore.free.fr/AdZHosts/HOSTS.txt" provider_allowed_ips = "127.0.0.1","::1" ## Host file hosts = "/etc/hosts" ## Local host customization localconfig = "/etc/hosts.local" ####################################################################### import sys import os import shutil import urllib2 import re import time ####################################################################### def url_exception_handler(exc) : """Handle exceptions while fetching data from url""" print >>sys.stderr, "Error while retrieving data from "+url+", aborting ("+str(exc)+")" sys.exit(1) def load_hosts(url) : """Load a hosts file into data and ips global vars""" global data global ips if url.startswith("/") : handler = file(url) islocal = True else : try : handler = urllib2.urlopen(url) except Exception, exc : url_exception_handler(exc) islocal = False data.append("####") data.append("## Beginning of "+url) while True : try : line = handler.readline() except Exception, exc : if not islocal : url_exception_handler(exc) raise ## Handle windows line-termination gracefully line = line.replace("\r", "") if line == "" : break line = line.rstrip("\n") if re.search(r"^\s*(?:#.*)?$", line) : data.append(line) continue m = re.search(r"^(?P<ip>\S+)\s+(?P<hostnames>[^#]*?)\s*(?P<comment>#.*?)?\s*$", line) if not m : if url == localconfig : data.append(line) continue else : print >>sys.stderr, "Ignoring malformed line "+line continue ip = m.group("ip") hostnames = re.split(r"\s+", m.group("hostnames")) ## Ignore ip redirections update if they are deemed unsafe if url != localconfig and ip not in provider_allowed_ips : print >>sys.stderr, "Warning: ignoring unsafe update: "+line continue ## Remove hostnames duplicates newhostnames = [] for h in hostnames : if ips.has_key(h) : continue ips[h] = ip newhostnames.append(h) if len(newhostnames) == 0 : continue if m.group("comment") is not None : data.append(m.group("comment")) ## Only put one hostname per line when using external sources if url == localconfig : data.append(ip+"\t"+" ".join(newhostnames)) else : data.extend([ ip+"\t"+hostname for hostname in newhostnames ]) data.append("## End of "+url) data.append("####") data.append("") ####################################################################### ## Program name prog = os.path.basename(sys.argv[0]) ## New data for /etc/hosts data = [ "##", "## Autogenerated by "+prog+" at "+time.asctime(), "## DO NOT MODIFY, edit "+localconfig+" and rerun "+prog+" instead", "##", "", ] ## Hostname -> ip associations ips = {} ## Backup /etc/hosts the first time we run if not os.path.exists(localconfig) : shutil.copy2(hosts, localconfig) ## Build new hosts file for url in localconfig, hosts_provider : load_hosts(url) ## Don't update config file if hasn't changed rawdata = "\n".join(data)+"\n" if os.path.exists(hosts) and file(hosts).read() == rawdata : sys.exit(0) ## Change hosts file tmp = hosts + os.extsep + "tmp" f = file(tmp, "w") f.write(rawdata) f.flush() f.close() try : shutil.copymode(local, tmp) except Exception : os.chmod(tmp, 00644) os.rename(tmp,hosts) ####################################################################### Ancienne version : #! /usr/bin/env bash ####################################################################### ## Online host file url="http://kosvocore.free.fr/AdZHosts/HOSTS.txt" ## Host file hosts="/etc/hosts" ## Local host customization local="$hosts.local" ## Temporary build location tmp="$hosts.tmp" ####################################################################### ## Backup /etc/hosts the first time we run test -e "$local" || cp -a "$hosts" "$local" || exit 1 ## Build new hosts ! test -e "$tmp" || rm -f "$tmp" || exit 1 { { ! test -e "$local" || cat "$local"; } && wget -q -O- "$url"; } >"$tmp" || exit 1 chmod 00644 "$tmp" || exit 1 ## Don't update config file if it hasn't changed if test -e "$hosts" && diff -q "$hosts" "$tmp" >/dev/null; then rm -f "$tmp" &>/dev/null exit 0 fi ## Change hosts file mv -f "$tmp" "$hosts" ####################################################################### Dernière modification par kyncani (Le 14/03/2010, à 16:45) Hors ligne Hizoka Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Qid => il faudrait que le fichier à dl se nomme de la même façon que le fichier local, soit hosts et non hosts.txt sauf si j'ai raté quelque chose avec l'option de wget... j'ai testé avec -O hosts mais ça ne fonctionne pas. après ça change pas grand chose... kyncani => en effet, chacun ses préférences Hors ligne kyncani Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! C'est -Ohosts, il n'y a pas d'espace après -O. Hors ligne Hizoka Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! ca ne fait pas de différence avec ou sans espace. le truc : -O : permet de lui dire ou télécharger le fichier. --timestamping : permet de dire regarde si le fichier à dl est plus récent que le fichier du dossier actuel, mais si le nom du fichier net et diffèrent du local, ca ne marche pas même si c'est hosts et hosts.txt Hors ligne kyncani Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Il est là http://kosvocore.free.fr/AdZHosts/HOSTS.txt Hors ligne kyncani Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Au fait, je me permet de signaler qu'il est dangereux d'utiliser un fichier /etc/hosts qui vient de l'extérieur sans vérifier son contenu. En particulier, les scripts de mise à jour automatique d'Hizoka et moi-même ne sont pas forcément une bonne idée. Supposez par exemple que quelqu'un décide un jour de mettre dans le fichier hosts.txt la ligne suivante : 10.234.23.17 www.paypal.com Et bien là, lorsque votre navigateur devra contacter www.paypal.com, il se connnectera à l'adresse ip fournie dans le fichier hosts. Et pour certains sites, comme paypal par exemple, il vaut quand même mieux être sur le bon site plutôt qu'un site forgé. Hors ligne dwan Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Je me suis fait la même remarque. Il faudrait un script simple et compréhensible qui vérifie que toutes les adresses que l'on veut blacklister sont bien associées à 127.0.0.1, et qui liste toute autre IP trouvée. Plus simplement, un script qui retourne toute IP différente de 127.0.0.1 et le ou les sites associés. edit : une ligne de ce genre suffirait ? Elle renvoie toutes les lignes du fichier /etc/hosts ne contenant pas 127.0.0.1, précédées de leur numéro de ligne. grep -nv '127.0.0.1' /etc/hosts re-edit : testé chez moi en rajoutant des lignes bizarres et des adresses IP au pif, ça marche bien, adopté ! Dernière modification par dwan (Le 14/03/2010, à 13:28) Hors ligne Hizoka Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! oui c'est pas dur à faire, je l'ajoute vite fait et je poste... NOIR="\033[1;0m" BLEUFONCE="\033[1;34m" ROUGE="\033[1;31m" echo -e "\n${BLEUFONCE}Comparaison des versions...\n${NOIR}" # Vérification des versions V_local=$(sed -n 's/# AdZHosts v0*\(.*\)/\1/p' /etc/hosts) V_net=$(links -dump http://kosvocore.free.fr/AdZHosts/Version.txt | sed 's/ //g ; s/^0*//') # Comparaison des versions if [[ ${V_local} -lt ${V_net} ]] then echo -e "${BLEUFONCE}Mise à jour en cours...\n${NOIR}" # Téléchargement du fichier hosts wget "http://kosvocore.free.fr/AdZHosts/HOSTS.txt" -O /tmp/hosts # Vérification du download if [[ ! -e /tmp/hosts ]] then echo -e "${ROUGE}Une erreur est survenue pendant la récupération du fichier Hosts.\n${NOIR}" exit 1 fi # Ajout de la ligne 127.0.0.1 nom de la machine sed -i "/127.0.0.1.*localhost/a\127.0.0.1 $(uname -n)" /tmp/hosts # Vérification de la modification if [[ -z $(grep "127.0.0.1 $(uname -n)" /tmp/hosts) ]] then echo -e "${ROUGE}Une erreur est survenue pendant la modification du fichier Hosts.\n${NOIR}" exit 1 fi adresse_autre=$(egrep -v "^127.0.0.1|^#|^255.255.255.255|^$|^::1" /etc/hosts) # Vérification des adresses if [[ -n ${adresse_autre} ]] then echo -e "${ROUGE}Attention, des il y a des adresses possiblement dangeureuses :\n${NOIR}" echo "${adresse_autre}" fi # Sauvegarde de l'ancinne version hosts sudo cp /etc/hosts /etc/hosts_$(date +%F) #Installation du nouveau hosts sudo cp /tmp/hosts /etc/hosts # Vérification de la bonne copie if [[ /tmp/hosts -nt /etc/hosts ]] then echo -e "${ROUGE}Une erreur est survenue pendant la copie du fichier Hosts.\n${NOIR}" exit 1 else rm /tmp/hosts echo -e "${BLEUFONCE}Mise à jour terminée.\n${NOIR}" fi elif [[ ${V_local} -eq ${V_net} ]] then echo -e "${BLEUFONCE}Fichier hosts déjà à jour...\n${NOIR}" exit 1 else echo -e "${ROUGE}Fichier hosts plus évolué que la version internet ??!\n${NOIR}" exit 1 fi ajout de : adresse_autre=$(egrep -v "^127.0.0.1|^#|^255.255.255.255|^$|^::1" /etc/hosts) # Vérification des adresses if [[ -n ${adresse_autre} ]] then echo -e "${ROUGE}Attention, des il y a des adresses possiblement dangeureuses :\n${NOIR}" echo "${adresse_autre}" fi il recherche les lignes ne débutant pas par 127.0.0.1 ou 255.255.255.255 ou # ou ::1 ou vide Dernière modification par Hizoka (Le 14/03/2010, à 15:05) Hors ligne kyncani Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! Idem, mais je ne sais toujours pas si je vais l'adopter. Mettre à jour automatiquement son /etc/hosts, bon ... à voir. Donc : - J'utilise un fichier /etc/hosts.local pour conserver les préférences locales. - Je ne change pas le fichier /etc/hosts si son contenu n'a pas changé. - Le travail se fait silencieusement et il n'affiche quelque chose qu'en cas de warning ou d'erreur. - Les mises à jour sont ignorées si elles redirigent vers une ip autre que 127.0.0.1 ou ::1 #! /usr/bin/env python ####################################################################### ## ## Mise a jour de /etc/hosts a partir de http://www.adzhosts.com ## ## Decouvert via http://forum.ubuntu-fr.org/viewtopic.php?id=371304 ## ## - Les preferences locales du fichier /etc/hosts sont contenues ## dans /etc/hosts.local ## - Les mises a jour sont ignorees si elles redirigent vers un ip ## autre que 127.0.0.1 ou ::1 ## ####################################################################### ## Online host file, with associated valid ips hosts_provider = "http://kosvocore.free.fr/AdZHosts/HOSTS.txt" provider_allowed_ips = "127.0.0.1","::1" ## Host file hosts = "/etc/hosts" ## Local host customization localconfig = "/etc/hosts.local" ####################################################################### import sys import os import shutil import urllib2 import re import time ####################################################################### def url_exception_handler(exc) : """Handle exceptions while fetching data from url""" print >>sys.stderr, "Error while retrieving data from "+url+", aborting ("+str(exc)+")" sys.exit(1) def load_hosts(url) : """Load a hosts file into data and ips global vars""" global data global ips if url.startswith("/") : handler = file(url) islocal = True else : try : handler = urllib2.urlopen(url) except Exception, exc : url_exception_handler(exc) islocal = False data.append("####") data.append("## Beginning of "+url) while True : try : line = handler.readline() except Exception, exc : if not islocal : url_exception_handler(exc) raise ## Handle windows line-termination gracefully line = line.replace("\r", "") if line == "" : break line = line.rstrip("\n") if re.search(r"^\s*(?:#.*)?$", line) : data.append(line) continue m = re.search(r"^(?P<ip>\S+)\s+(?P<hostnames>[^#]*?)\s*(?P<comment>#.*?)?\s*$", line) if not m : if url == localconfig : data.append(line) continue else : print >>sys.stderr, "Ignoring malformed line "+line continue ip = m.group("ip") hostnames = re.split(r"\s+", m.group("hostnames")) ## Ignore ip redirections update if they are deemed unsafe if url != localconfig and ip not in provider_allowed_ips : print >>sys.stderr, "Warning: ignoring unsafe update: "+line continue ## Remove hostnames duplicates newhostnames = [] for h in hostnames : if ips.has_key(h) : continue ips[h] = ip newhostnames.append(h) if len(newhostnames) == 0 : continue if m.group("comment") is not None : data.append(m.group("comment")) ## Only put one hostname per line when using external sources if url == localconfig : data.append(ip+"\t"+" ".join(newhostnames)) else : data.extend([ ip+"\t"+hostname for hostname in newhostnames ]) data.append("## End of "+url) data.append("####") data.append("") ####################################################################### ## Program name prog = os.path.basename(sys.argv[0]) ## New data for /etc/hosts data = [ "##", "## Autogenerated by "+prog+" at "+time.asctime(), "## DO NOT MODIFY, edit "+localconfig+" and rerun "+prog+" instead", "##", "", ] ## Hostname -> ip associations ips = {} ## Backup /etc/hosts the first time we run if not os.path.exists(localconfig) : shutil.copy2(hosts, localconfig) ## Build new hosts file for url in localconfig, hosts_provider : load_hosts(url) ## Don't update config file if hasn't changed rawdata = "\n".join(data)+"\n" if os.path.exists(hosts) and file(hosts).read() == rawdata : sys.exit(0) ## Change hosts file tmp = hosts + os.extsep + "tmp" f = file(tmp, "w") f.write(rawdata) f.flush() f.close() try : shutil.copymode(local, tmp) except Exception : os.chmod(tmp, 00644) os.rename(tmp,hosts) ####################################################################### Dernière modification par kyncani (Le 14/03/2010, à 16:46) Hors ligne dwan Re : [astuce] Un fichier HOSTS qui combat les pubs et liens malveillants ! adresse_autre=$(egrep -v "^127.0.0.1|^#|^255.255.255.255|^$|::1" /etc/hosts) # Vérification des adresses if [[ -n ${adresse_autre} ]] then echo -e "${ROUGE}Attention, des il y a des adresses possiblement dangeureuses :\n${NOIR}" echo "${adresse_autre}" fi il recherche les lignes ne débutant pas par 127.0.0.1 ou 255.255.255.255 ou # ou ::1 ou vide Tu as oublié un ^ ? Tu risques de passer à côté de lignes contenant ::1, mais ne débutant pas par ::1, ce qui inclut des adresses potentiellement dangereuses. Je précise que je ne suis pas très familier avec ipv6... @kyncani : Je ne ferai pas non plus de mise à jour automatique. Je téléchargerai au coup par coup, et vérifierai à la main avec une variante de ma commande améliorée grâce au script de Hizoka : ~$ egrep -nv '^127.0.0.1|^::1|^$|^#|' /etc/hosts Dernière modification par dwan (Le 14/03/2010, à 15:06) Hors ligne
Hagar de l'Est [How-To] Installer OpenOffice.org avec les RPMs officiels Si vous n'avez pas la patience d'attendre que les dépôts soient mis à jour pour installer la dernière version d'OOo, voici la méthode manuelle à partir des RPMs officiels. NB: avant d'installer, si vous avez modifié la configuration des dictionnaires dans le répertoire principal d'OOo, faites une sauvegarde de ce dossier car il sera écrasé par la mise à jour. J'ai ouvert un bug report ici : http://www.openoffice.org/issues/show_bug.cgi?id=72559, n'hésitez pas à voter. - Désinstaller la version livrée par défaut avec Ubuntu (tous les paquets OpenOffice.org), inutile si elle avait déjà été désinstallée auparavant. Ne pas supprimer le répertoire de profil de votre user, donc si vous choisissez 'Suppression complète', faites une sauvegarde du répertoire caché /home/<votre user ID>/.openoffice.org2). - Télécharger l'archive française (http://fr.openoffice.org/about-downloads.html RPM - i386) contenant les rpms et la décompresser. - Convertir les rpms et les installer (se mettre dans le répertoire où sont les rpms) : NB: il faut utiliser l'option --scripts car certains RPMs peuvent poser problème (souvent le core10) : cd rep_install_OOo/RPMS sudo alien -d *.rpm --scripts sudo dpkg -i *.deb Mettre à jour le menu Gnome, dans le même terminal (tous les icônes seront dans Bureautique) : cd desktop-integration sudo dpkg -i openoffice.org-debian-menus_2.0.4-2_all.deb Ne pas oublier d'éditer le fichier /opt/openoffice.org2.0/share/dict/ooo/dictionary.lst et de supprimer (ou commenter) toutes les lignes qui ne vous sont pas utiles (ne garder par exemple que les lignes contenant 'en GB' et 'en US'). Votre dico français étant dans votre profil, il est conservé. NB: il faudra peut être ajouter le droit d'écriture sur ce fichier pour root, chez moi, il n'y était pas par défaut. NB: c'est en fait un rappel de ce tuto : http://doc.ubuntu-fr.org/applications/openoffice2 mais une petite piqure de rappel ne fait pas de mal. Dernière modification par Hagar de l'Est (Le 11/01/2007, à 17:22) Hors ligne MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Bonjour, au passage une petite erreur de frappe est présente dans l'url de téléchargement de la VF : http://fr.openoffice.org/about-downloads.html Il y a une virgule dans votre lien. J'ai suivi votre tuto pour installé openoffice 2.0.3 sur ubuntu dapper. Il y a des .deb dispo au passage : ftp://openoffice.cict.fr/openoffice/localized/fr/2.0.3/ ftp://openoffice.cict.fr/openoffice/localized/fr/2.0.3/OOo_2.0.3_LinuxIntel_install_fr_deb.tar.gz Tout à bien fonctionné sauf que j'ai un problème avec l'affichage des menu et des boutons sous gnome... ca chie vraiment dans la colle. J'avais ce problème avec la 2.0.2 et j'avais du supprimer les paquets concernant l'intégration dans gnome. et j'avais pu avoir un menu digne de ce nom. Mais avec la version 2.0.3 pas moyen de trouver le paquet conernant l'intégration dans gnome. Une idée ?? Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne AppleCrow Re : [How-To] Installer OpenOffice.org avec les RPMs officiels ... Heu... Je suis le seul à ne pas avoir de problèmes pour installer OpenOffice 2.0.3 à partir de dapper-proposed? Il suffit de: - décocher le dépôt dapper-proposed et rafraichir la liste des paquets - aller dans synaptic, supprimer (pas suppression complète) tous les paquets OpenOffice installés (suffit de taper openoffice dans "rechercher" et cliquer sur "s" pour que les icones vertes soient en haut). - recocher le dépôt dapper-proposed et rafraichir la liste des paquets - chercher ubuntu-desktop et l'installer (ce qui réinstalle openoffice en version 2.0.3 et tout ce qui lui va bien) - cliquer sur la mise à jour des paquets Et puis ensuite vérifier que le support linguistique fr est toujours cocher dans "support linguistique). Hors ligne pohiohio Re : [How-To] Installer OpenOffice.org avec les RPMs officiels perso le system m'a proposé la mise à jour. rien de spécial à faire. Hors ligne Dude Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Il suffit de: - décocher le dépôt dapper-proposed et rafraichir la liste des paquets. Salut, Comment avoir ce dépôt ? Je ne l'ai pas dans ma liste. Hors ligne fredbezies Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Tu l'ajoutes dans ton /etc/apt/sources.list Mais ne serait-il pas plus simple d'attendre la sortie officielle ? Je dis cela, mais je dis rien, hein... MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Bon je viens d'aciver les dépots français proposed, et j'installe actuellement la version 2.0.3 de openoffice. Espérons que ca fonctionnera et que ca ne me fera pas des couilles dans les menus... edit : tout s'est bien passé Je pense que je vais désactiver le dépot proposed... Dernière modification par MilesTEG (Le 23/08/2006, à 13:12) Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne calamitijo Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Salut quelqu'un peut il me dire quelle ligne c'est "proposed" que je puisse faire la màj, ou la rajouter dans /etc/apt/sources.list? merci MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Salut quelqu'un peut il me dire quelle ligne c'est "proposed" que je puisse faire la màj, ou la rajouter dans /etc/apt/sources.list? merci Dans le sources.list par défaut elle n'y est pas si mes souvenirs sont bons... ## Proposés deb http://fr.archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse # deb http://archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse # deb-src http://archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse Voilà mon sources.list si ca te tente : ##### DAPPER DRAKE # # deb cdrom:[Ubuntu 6.06.1 _Dapper Drake_ - Release i386 (20060807.1)]/ dapper main restricted deb cdrom:[Ubuntu 6.06.1 _Dapper Drake_ - Release i386 (20060807.1)]/ dapper main restricted #### voir http://doc.ubuntu-fr.org/installation/dapper/depots pour détails sur signatures GPG ## Dépôts binaires officiels (les dépôts multiverse ne sont pas supportés par Cannonical et doivent être utilisés à vos propres risques) deb http://fr.archive.ubuntu.com/ubuntu/ dapper main restricted universe multiverse deb http://fr.archive.ubuntu.com/ubuntu/ dapper-updates main restricted universe multiverse deb http://fr.archive.ubuntu.com/ubuntu/ dapper-security main restricted universe multiverse deb http://fr.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu dapper-backports main universe multiverse restricted deb http://archive.ubuntu.com/ubuntu/ dapper main restricted universe multiverse # deb http://ubuntu-backports.mirrormax.net/ dapper-extras main universe multiverse restricted deb http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted universe multiverse # Security Updates deb http://security.ubuntu.com/ubuntu/ dapper-updates main restricted universe multiverse deb-src http://security.ubuntu.com/ubuntu dapper-updates main restricted universe multiverse deb http://security.ubuntu.com/ubuntu/ dapper-security main restricted universe multiverse deb-src http://security.ubuntu.com/ubuntu/ dapper-security main restricted universe multiverse #ntfs-3g & fuse-2.5 repo: deb http://flomertens.keo.in/ubuntu/ dapper main deb-src http://flomertens.keo.in/ubuntu/ dapper main ## Proposés deb http://fr.archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse # deb http://archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse # deb-src http://archive.ubuntu.com/ubuntu dapper-proposed main restricted universe multiverse # Drivers pour webcams # deb http://blognux.free.fr/debian unstable main ## Dépôts source officiels (rarement utiles pour l'utilisateur final -- supprimez les # pour les activer) deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper main restricted universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper-updates main restricted universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper-security main restricted universe multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb-src http://archive.ubuntu.com/ubuntu dapper-backports main universe multiverse restricted # Dépots pour qComicBook deb http://qcomicbook.horisone.com/ dapper main deb-src http://qcomicbook.horisone.com/ dapper main ## Dépôt PLF (ce dépôt n'est pas supporté par Cannonical et doit être utilisé à vos propres risques) ## Dépôt PLF (Penguin Liberation Front) ## http 100mbit/s mirror provided thanks to OVH (http://ovh.com) # deb http://packages.freecontrib.org/ubuntu/plf/ dapper free non-free # deb-src http://packages.freecontrib.org/ubuntu/plf/ dapper free non-free ## Miroirs si ceux du dessus fonctionne pas # deb http://antesis.freecontrib.org/mirrors/ubuntu/plf/ dapper free non-free # deb-src http://antesis.freecontrib.org/mirrors/ubuntu/plf/ dapper free non-free ## Dépôt Pouit (pour i386 et amd64) ## Plus d'infos sur http://mrpouit.free.fr/blog/Depot-ubuntu # deb http://mrpouit.free.fr/ubuntu/ dapper-misc main restricted universe multiverse non-free openalchemist # deb-src http://mrpouit.free.fr/ubuntu/ dapper-misc main restricted universe multiverse non-free openalchemist ## Spécifiques à KDE # KDE (ce dépôt fournit la dernière version de KDE) deb http://kubuntu.org/packages/kde-latest dapper main # KOffice (ce dépôt fournit la dernière version de KOffice) deb http://kubuntu.org/packages/koffice-latest/ dapper main # Amarok (ce dépôt fournit la dernière version de Amarok) deb http://kubuntu.org/packages/amarok-latest dapper main ## Dépot pour Splashy (usplash/bootsplash replacement) Make your boot process eye-candy! ## Cf ce tuto : http://ubuntuforums.org/showthread.php?t=216597 ## Debian Sarge (stable) users: # deb http://splashy.alioth.debian.org/debian stable main ## Debian Etch/Sid (testing/unstable) users: # deb http://splashy.alioth.debian.org/debian unstable main ## ## ## # Skype (dépot debian officiel de skype) # deb http://download.skype.com/linux/repos/debian/ stable non-free # Depots officiel Wine # deb http://wine.sourceforge.net/apt/ binary/ ## Samba # deb http://www.linux2go.dk/ubuntu dapper main ## VLC deb http://nightlies.videolan.org/build/dapper-i386 / ## Firefox # deb http://asher256-repository.tuxfamily.org dapper main dupdate french # deb http://asher256-repository.tuxfamily.org ubuntu main dupdate french # Asher # deb http://asher256-repository.tuxfamily.org dapper main dupdate french # deb http://asher256-repository.tuxfamily.org ubuntu main dupdate french ## Seveas # deb http://seveas.ubuntulinux.nl/ dapper-seveas custom extras freenx java seveas-meta all Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Pour MilesTEG : pas vraiment d'idée pour les menus et boutons. Ceux de OOo je suppose, pas ceux du menu d'applications de Gnome ? As-tu essayé de jouer avec les paramètres d'affichage du menu Outils>Options, section OpenOffice.org>Affichage (notamment le style des icones) ? Il y a eu des problèmes avec les premiers paquets d'OOo 2.0.3 qui étaient dans le repository 'Proposed' (quelques messages à ce sujet sur les forums d'OOo et d'Ubuntu), c'est pour cela que j'avais créé ce post en fait. Pour utiliser les fichiers qui venaient directement d'OpenOffice.org. NB: lien corrigé dans le premier post. Hors ligne MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels en fait c'est pour les menus d'openoffice. Pour réglé le problème j'ai du supprimer l'intégration d'ooo dans gnome : paquet openoffice2.org-gnome, openoffice.org-gnome, openoffice.org-gtk, je les réinstall, si ca foire je fait une capture d'écran... Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Chez moi, j'avais absolument tout viré pour n'installer que les debs issus des aliens de l'archive d'OpenOffice.org. Et je n'ai pas de problème particulier avec Gnome ou les affichages (que ce soit industriel, crystal, ou par défaut). Hors ligne MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Lorsque j'ammene la souris sur un menu et que je clique, ca fait foirer tous les menus de ooo, et les icones pareils... Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Si tu as beaucoup de dictionnaires, essaye de supprimer de ton dictionary.lst ceux dont tu n'as pas besoin. Chez moi, ça allourdissait gravement le système, je mettais une plombe à afficher un menu. Hors ligne MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels là c'est pas que ca met 3 plombes a afficher le menu, il s'affiche bien, mais quand je met la souris sur le menu et/ou je clique dessus, il part en sucette... Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Là, je n'en sais pas plus. Je serais toi, je désinstallerais pour réinstaller à partir des rpms pour voir si ça change quelque chose. Hors ligne fandard Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Bonjour et au secour!!! Un copain trés callé en informatique(pas mon cas)m'a installé ubuntu et open office mais ce dernier est en anglais et l'anglais moi.... Bref comment proceder pour l'avoir en francais.Mercie d'avance Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Menu Système>Administration>Gestionnaire de paquets Synaptic. Installer le paquet openoffice.org-l10n-fr. NB: c'est pour la version 2.0.2. Ce fil concerne au départ la 2.0.3 (qui n'est pas dans Ubuntu 6.06). Dernière modification par Hagar de l'Est (Le 27/08/2006, à 14:51) Hors ligne MilesT3G Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Bonjour, j'ai trouvé ce dépot pour openoffice 2.0.3 http://people.ubuntu.com/~doko/ooo203/ Il ressemble au vieux http://people.ubuntu.com/~doko/OOo2.0.2/ présent dans cette page : http://doc.ubuntu-fr.org/applications/apt/depots Vous en pensez quoi ? Recherchez la liberté et devenez esclave de vos désirs. Recherchez la discipline et trouvez votre liberté.Coda Bene Gesserit Nous avons trop tendance à devenir pareils aux pires de nos ennemis.Coda Bene Gesserit Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Perso je n'ai pas l'ADSL donc je n'utilise pas les dépôts. Si ces dépôts ne sont pas officiels, les RPMs le sont en tout cas, il y a peut-être moins de risques à utiliser ces derniers. Hors ligne Ago Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Merci pour les proposed, je n'avait pas ça dans mon sources.list. Update, upgrade, OOo 2.0.3 Pas besoin de s'emmerder avec les rpms et les dépots bizzares Edit: Oups, petit problème de conflit Un apt-get install -f semble régler le problème cependant Dernière modification par Ago (Le 28/08/2006, à 10:47) Hors ligne montge Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Bonjour, J'ai essayé d'installer OOo 2.0.4 sur Ubuntu 6.06 selon la procédure indiquée en début de ce post. Tout s'est bien passé jusqu'à la dernière opération : $ sudo dpkg -i openoffice.org-debian-menus_2.0.4-2_all.deb Sélection du paquet openoffice.org-debian-menus précédemment désélectionné. dpkg : concernant openoffice.org-debian-menus_2.0.4-2_all.deb contenant openoffice.org-debian-menus : openoffice.org-core entre en conflit avec openoffice.org-unbundled openoffice.org-debian-menus fournit openoffice.org-unbundled et doit être installé. dpkg : erreur de traitement de openoffice.org-debian-menus_2.0.4-2_all.deb (--install) : paquets en conflit - openoffice.org-debian-menus non installé Des erreurs ont été rencontrées pendant l'exécution : openoffice.org-debian-menus_2.0.4-2_all.deb Que faire ? Merci GM Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Si tu avais bien désinstallé tous les paquets de la version précédente et qu'il n'y avait pas d'avertissement sur les scripts pour les paquets *core*, je ne vois pas d'où ça peut venir, désolé. Hors ligne scorpio810 Re : [How-To] Installer OpenOffice.org avec les RPMs officiels Merci pour les proposed, je n'avait pas ça dans mon sources.list. Update, upgrade, OOo 2.0.3 Pas besoin de s'emmerder avec les rpms et les dépots bizzares Edit: Oups, petit problème de conflit Un apt-get install -f semble régler le problème cependant 1 depot proposed, Update, upgrade, OOo 2.0.3 pas de conflit a signaler mais OOo est en anglais !!! 2 desactiver depot proposed, activer depot http://people.ubuntu.com/~doko/ooo203/deb http://people.ubuntu.com/~doko/ooo203/ ./ Update, upgrade Installer le paquet openoffice.org-l10n-fr (version 2.0.3) voila OOo 2.0.3 en fr sur dapper merçi a Hagar de l'Est & a Ago pour ce debut de piste "Le jour où tu découvres le Libre, tu sais que tu ne pourras jamais plus revenir en arrière..." Hors ligne Hagar de l'Est Re : [How-To] Installer OpenOffice.org avec les RPMs officiels voila OOo 2.0.3 en fr sur dapper Ben avec les RPMs, je suis en 2.0.4 sur Dapper Hors ligne
I am trying to dynamically assign a function to __del__ of an instance of a class so that it gets called when using dir() on that object. I need __dir__ to be unique for each instance of the class. As a stripped down example, I have tried: import types class Foo(object): def __init__(self, arg): def __dir__(self): print "in __dir__" return [arg] self.__dir__ = types.MethodType(__dir__, self, self.__class__) foo = Foo('bar') print dir(foo) print print foo.__dir__() This prints: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']in __dir__['bar'] If I instead do this: class Foo(object): def __dir__(self): print "in __dir__" return ['bar'] foo = Foo() print dir(foo) that outputs: in __dir__['bar'] as expected, but can not be customized for each instance of the class. Any ideas?
Hey everyone this code is working fine just one thing to deal with. It overwrites the multiple entries against a key. I need to avoid the overwriting and to save all those entries. Can you help me in this please? #!/usr/bin/python import sys import fileinput #trys to create dictionary from african country list dic = {} for line in sys.stdin: lst = line.split('|') links = lst[4].split() new=links[0] + ' ' + links[len(links)-1] dic[new]=lst[4] # WARNING: overwrites multiple entriess at the moment! :) for newline in fileinput.input('somefile.txt'): asn = newline.split() new = asn[0] + ' ' + asn[1] if new in dic: print "found from " + asn[0] + " to " + asn[1] print dic[new] Note: Sys.stdin takes a string in the following format; 1.0.0.0/24|US|158.93.182.221|GB|7018 1221 3359 3412 2543 1873
I'm very new to Yesod and I'm having trouble building Yesod statically so I can deploy to Heroku. I have changed the default .cabal file to reflect static compilation if flag(production) cpp-options: -DPRODUCTION ghc-options: -Wall -threaded -O2 -static -optl-static else ghc-options: -Wall -threaded -O0 And it no longer builds. I get a whole bunch of warnings and then a slew of undefined references like this: Linking dist/build/personal-website/personal-website ... /usr/lib/ghc-7.0.3/libHSrts_thr.a(Linker.thr_o): In function `internal_dlopen': Linker.c:(.text+0x407): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/unix-2.4.2.0/libHSunix-2.4.2.0.a(HsUnix.o): In function `__hsunix_getpwent': HsUnix.c:(.text+0xa1): warning: Using 'getpwent' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/unix-2.4.2.0/libHSunix-2.4.2.0.a(HsUnix.o): In function `__hsunix_getpwnam_r': HsUnix.c:(.text+0xb1): warning: Using 'getpwnam_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/libpq.a(thread.o): In function `pqGetpwuid': (.text+0x15): warning: Using 'getpwuid_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/libpq.a(ip.o): In function `pg_getaddrinfo_all': (.text+0x31): warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/site-local/network-2.3.0.2/ libHSnetwork-2.3.0.2.a(BSD__63.o): In function `sD3z_info': (.text+0xe4): warning: Using 'gethostbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/site-local/network-2.3.0.2/ libHSnetwork-2.3.0.2.a(BSD__164.o): In function `sFKc_info': (.text+0x12d): warning: Using 'getprotobyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/ghc-7.0.3/site-local/network-2.3.0.2/ libHSnetwork-2.3.0.2.a(BSD__155.o): In function `sFDs_info': (.text+0x4c): warning: Using 'getservbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/libpq.a(fe-misc.o): In function `pqSocketCheck': (.text+0xa2d): undefined reference to `SSL_pending' /usr/lib/libpq.a(fe-secure.o): In function `SSLerrmessage': (.text+0x31): undefined reference to `ERR_get_error' /usr/lib/libpq.a(fe-secure.o): In function `SSLerrmessage': (.text+0x41): undefined reference to `ERR_reason_error_string' /usr/lib/libpq.a(fe-secure.o): In function `initialize_SSL': (.text+0x2f8): undefined reference to `SSL_check_private_key' /usr/lib/libpq.a(fe-secure.o): In function `initialize_SSL': (.text+0x3c0): undefined reference to `SSL_CTX_load_verify_locations' (... snip ...) If I just compile with just -static and without -optl-staticeverything builds fine but the application crashes when it tries tostart on Heroku. 2011-12-28T01:20:51+00:00 heroku[web.1]: Starting process with command `./dist/build/personal-website/personal-website -p 41083` 2011-12-28T01:20:51+00:00 app[web.1]: ./dist/build/personal-website/ personal-website: error while loading shared libraries: libgmp.so.10: cannot open shared object file: No such file or directory 2011-12-28T01:20:52+00:00 heroku[web.1]: State changed from starting to crashed I tried adding libgmp.so.10 to the LD_LIBRARY_PATH as suggested in here and then got the following error: 2011-12-28T01:31:23+00:00 app[web.1]: ./dist/build/personal-website/ personal-website: /lib/libc.so.6: version `GLIBC_2.14' not found (required by ./dist/build/personal-website/personal-website) 2011-12-28T01:31:23+00:00 app[web.1]: ./dist/build/personal-website/ personal-website: /lib/libc.so.6: version `GLIBC_2.14' not found (required by /app/dist/build/personal-website/libgmp.so.10) 2011-12-28T01:31:25+00:00 heroku[web.1]: State changed from starting to crashed 2011-12-28T01:31:25+00:00 heroku[web.1]: Process exited It seems that the version of libc that I'm compiling against is different. I tried also adding libc to the batch of libraries the same way I did for libgmp but this results in a segmentation fault when the application starts on the Heroku side. Everything works fine on my PC. I'm running 64bit archlinux with ghc7.0.3. The blog post on the official Yesod blog looked pretty easybut I'm stumped at this point. Anyone have any ideas? If there's a way to get this thing working without building statically I'm open to that too. EDIT Per Employed Russians answer I did the following to fix this. First created a new directory lib under the project directory and copied the missing shared libraries into it. You can get this information by running ldd path/to/executable and heroku run ldd path/to/executable and comparing the output. I then did heroku config:add LD_LIBRARY_PATH=./lib so when the application is started the dynamic linker will look for libraries in the new lib directory. Finally I created an ubuntu 11.10 virtual machine and built and deployed to Heroku from there, this has an old enough glibc that it works on the Heroku host. Edit: I've since written a tutorial on the Yesod wiki
I've been having trouble with my templates not updating in the Google App Engine Dev Python Server. If I leave the server running for a while, my templates will not update in the browser after I change them. My best guess is that jinja2 is caching these templates some how? I'm rendering my templates using the following code: _jinja_environment = jinja2.Environment( loader = jinja2.FileSystemLoader(root_dir)) def write_template(self, template_name, template_data = {}): template = _jinja_environment.get_template(template_name) self.response.out.write(template.render(template_data)) I've tried restarting my app engine application, as well as undeploying and re-deploying, but the templates still don't update. Anyone got any ideas?
malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Ou alors je n'ai pas trouvé comment faire... Il fallait aller dans le Bios au démarrage et sélectionner le démarrage sur le support d'installation de Ubuntu "sans" UEFI. Comme tu n'y connaissais rien en UEFI, tu as laissé démarrer le PC sur le support sans intervenir, il s'est placé par défaut en mode UEFI et tu t'es retrouvé avec cette installation bancale. J'indique dans ce tuto comment savoir si on est bien en mode Bios ou en mode UEFI : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p7282231 Utilise ce tuto la prochaine fois avant d'installer Ubuntu. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Bonjour une idée de ce que je "risque" en laissant tout comme ça ? à priori pas grand-chose, j'ai déjà vu un autre cas fonctionnel comme vous (grub-efi sans disque GPT). Faites seulement attention à ne pas effacer malencontreusement votre partition EFI (sda2). Dernière modification par YannUbuntu (Le 12/07/2012, à 17:13) Hors ligne Coolmic29 Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Le lien est à corriger - B) redémarrer le PC sur le liveCD de Ubuntu Il faut télécharger l'ISO officiel 64 bits ubuntu-12.04-desktop-i386.iso. Très bon Tuto merci Ubuntu 12.04_64 bits XPC Shuttle SG45H7 Core 2 Duo E8400 3GHz Ubuntu 13.10_64 bits Portable VAIO core I5 carte vidéo ATI Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Coolmic29, J'ai corrigé : ubuntu-12.04.1-desktop-amd64.iso (au lieu de ubuntu-12.04-desktop-i386.iso). Merci pour ta remarque. J'espère que ce tuto "prudent" va devenir obsolète un jour parce que Ubuntu saura s'installer automatiquement sans écraser les glaouis de Windows. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Bonjour J'espère que ce tuto "prudent" va devenir obsolète un jour parce que Ubuntu saura s'installer automatiquement sans écraser les glaouis de Windows. Ca devrait être déjà le cas pour 12.04 (le bug #769669 a été corrigé avant la sortie de Precise). EDIT: ceci dit, le tuto reste intéressant pour apprendre à ne pas mélanger plusieurs partitions EFI Dernière modification par YannUbuntu (Le 27/08/2012, à 10:01) Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI YannUbuntu, J'avais vu que ce bug est sensé être corrigé mais je reste sceptique. J'ai pu voir dans quelques fils que certains avaient pu installer de façon "normale" (sans créer une partition EFI spéciale pour Ubuntu) mais j'ai l'impression qu'on manque de preuves que le bug est effectivement corrigé et que la cohabitation dans la partition EFI préinstallée ne pose plus de problème. Tu as des liens vers des discussions probantes sur le sujet (sur ce forum ou d'autres forum Ubuntu) ? Je veux dire des discussions avec des Boot-Info où on voit clairement que tout s'est bien passé... MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI @YannUbuntu, Il apparaît que l'installation avec une partition EFI dédiée à Ubuntu qui est trop loin du début du disque pose problème d'après ce cas de Mateoz (j'en ai vu d'autres) : http://forum.ubuntu-fr.org/viewtopic.ph … #p10548501 On peut constater que Boot-Repair est efficace pour installer Ubuntu dans la même partition EFI que Windows puisqu'on voit ça dans le Boot-Info de Mateoz après réparation par Boot-Repair : sda3: __________________________________________________________________________ File system: vfat Boot sector type: Windows 7: FAT32 Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: /efi/Boot/bootx64.efi /efi/ubuntu/grubx64.efi C'est à dire, dans la partition EFI : le chargeur d'amorçage pour Win7 (/efi/Boot/bootx64.efi) et le chargeur d'amorçage pour ubuntu (/efi/ubuntu/grubx64.efi) Cela ne répond pas à ma question du post #31 (je m'intéresse aux installations réussies du premier coup) mais ça montre que Boot-Repair fait une réparation correcte. Dernière modification par malbo (Le 28/08/2012, à 14:19) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Je confirme. D'ailleurs: - tu devrais ajouter dans le post#1 A)2) de ce tuto qu'il faut, par précaution, placer la partition EFI en début de disque (de façon à ce qu'elle soit entièrement contenue dans les 100 premiers Go du disque) - ce problème survient aussi pour un /boot séparé. - je pense qu'il s'agit d'une régression de GRUB 12.04: https://bugs.launchpad.net/bugs/1030887 EDIT: dans le post#1 tu indique de créer l'ESP en FAT16, mais il est aussi possible de la créer en FAT32. D'ailleurs il me semble que le format préconisé par le standard UEFI est FAT32. Dernière modification par YannUbuntu (Le 28/08/2012, à 14:43) Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI - tu devrais ajouter dans le post#1 A)2) de ce tuto qu'il faut, par précaution, placer la partition EFI en début de disque (de façon à ce qu'elle soit entièrement contenue dans les 100 premiers Go du disque) J'allais te répondre que le bug en question n’apparaît pas dans le cas de joeypa13 : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p8282351 dont l'installation l'installation de Ubuntu a été faite entièrement au delà de 250 Go par rapport au début du disque dur, mais je viens de me rendre compte que joeypa13 avait installé Ubuntu 11.10 alors que tu as bien noté que ce bug #1030887 est une régression de Ubuntu 12.04... Edit : j'ai trouvé le cas de Xord3 : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9547651 Tu noteras que toute son install de Ubuntu, partition EFI pour Ubuntu comprise, se situe en fin de son disque dur de 1000 Go Dans son cas, le bug #1030887 ne se produit pas, bien qu'il s'agisse de Ubuntu 12.04. Dernière modification par malbo (Le 28/08/2012, à 16:13) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Pour le FAT16, je viens de retrouver pourquoi tu le conseilles http://forum.ubuntu-fr.org/viewtopic.ph … 1#p8791031 Edit : j'ai trouvé le cas de Xord3 : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9547651 Tu noteras que toute son install de Ubuntu, partition EFI pour Ubuntu comprise, se situe en fin de son disque dur de 1000 Go Dans son cas, le bug #1030887 ne se produit pas, bien qu'il s'agisse de Ubuntu 12.04. Bien vu, c'est un cas où /boot et /boot/efi sont à >900Go du début du disque. Le blocage avec /boot/efi trop loin n'est donc pas systématique pour tous les PCs (c'est d'ailleurs la même chose pour le blocage avec /boot trop loin ). Mais comme certains PCs sont affectés, il vaut mieux par précaution conseiller de mettre /boot et /boot/efi en début de disque. Dernière modification par YannUbuntu (Le 28/08/2012, à 17:43) Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Ces blocages (pour /boot éloigné, comme pour /boot/efi éloigné) sont à mon avis soit dûs soit au BIOS (dans ce cas on ne peut rien faire, à part mettre la partition en début de disque), soit à une régression de GRUB (dans ce cas on peut aider à améliorer GRUB en soumettant un rapport de bug). Dans l'éventualité où ça serait une régression, il faut qu'on surveille les cas où ça bloque sur 12.04 après migration depuis 11.10 (ou 10.04). N'hésite pas à me prévenir si tu en vois un! Dernière modification par YannUbuntu (Le 28/08/2012, à 17:45) Hors ligne marco1492 Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Merci beaucoup pour ce tutorial qui m'a grandement aidé. J'ai regardé les différents forums. C'est le seul tutorial qui donne la quasi totalité de la solution pour installer Ubuntu sur un PC avec la nouvelle génération de BIOS-UEFI. Je suis resté longtemps (plus d'une journée à chercher et réfléchir) à l'étape démarrer sur le CDlive Ubuntu 12.04.1 et vérifier que vous avez booté en UEFI. J'ai trouvé la combinaison lors du boot de l'ordinateur. Il s'agit de : 1) Placer le CDlive Ubuntu 12.04.1 dans le lecteur DVD-CD de l'ordinateur 2) Rebooter l'ordinateur en maintenant appuyer la touche "Echap". Ce qui fait apparaître un menu UEFI de boot avec les options suivantes : - P0 : Windows Boot Manager (il s'agit de la partition UEFI de boot, créée par le fabricant du PC), - P2 : <le lecteur DVD/CD> - UEFI : <le lecteur DVD/CD>. 3) Choisir UEFI : <le lecteur DVD/CD>. Je précise : - que j'ai acheté l'ordinateur portable récemment (fin août 2012). C'est un ASUS Série Premium R500VD-SX086V (Core i5), avec UEFI AMI BIOS American Megatrends; - que ni ASUS, ni AMI -American Megatrends mettent à disposition ni un manuel utilisateur du BIOS/UEFI, ni une FAQ sur comment utiliser ce BIOS/UEFI ou comment démarrer un PC avec BIOS/UEFI. Encore merci. Très cordialement. Marc Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI @marco1492 Merci pour ce retour. Aurais-tu l'amabilité de répondre à cette demande : http://doc.ubuntu-fr.org/tutoriel/boot-info Cela permettrait d'enrichir notre expérience dans le domaine. En particulier sur le problème évoqué dans les posts qui précèdent le tien. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI YannUbuntu , Un cas d'installation avec des fichiers de Boot pour Ubuntu éloignés du début du disque dur qui ne présente pas le bug (Boot-Info en bas du post #1 du lien) : http://forum.ubuntu-fr.org/viewtopic.ph … #p10580891 MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Merci pour le lien. Ca confirme donc que ce bug n'est pas systématique. Tout comme le bug du /boot éloigné. Ce que je cherche surtout ce sont des régressions (ça marche avec une ancienne version de GRUB, mais ça plante après une MAJ de GRUB). Dernière modification par YannUbuntu (Le 03/09/2012, à 19:19) Hors ligne marco1492 Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Voici le rapport BootInfo sur mon PC portable Asus i5 64 bits avec BIOS/EFI : http://paste.ubuntu.com/1181051/ que je poste avec plaisir en accord avec les bons principes de la communauté Gnu-Linux et celle d'Ubuntu en particulier, que je partage et j'apprécie depuis 1998. Ce rapport BootInfo généré est à la fois très riche en information et très intéressant. Par contre, j'ai exécuté Boot-Repair en mode 'mise à jour du menu Grub EFI' et depuis je n'arrive plus à booter sur Windows 7. En effet, lors du reboot de mon PC, par défaut, j'ai bien le menu grub-efi. Or, si les options Linux, du menu grub-efi, fonctionnent correctement, par contre, la première (et non les dernières comme nous l'explique YannUbuntu) option de 'Boot sur Windows 7' (générée lors de l'installation d'Ubuntu 12.04.1, et par la suite Boot-repair) me renvoie le message d'erreur "error : invalid EFI file path" et l'exécution du boot BIOS/EFI s'arrête là. Idem lors du reboot du PC quand je maintiens appuyée la touche "Echap", le menu UEFI de boot apparaît : - P1 : Ubuntu (avec BIOS/UEFI) - P0 : Windows Boot Manager (il s'agit de la partition UEFI de boot, créée par le fabricant du PC), - P2 : <le lecteur DVD/CD> - etc ... Quand je choisis l'option "P0 : Windows Boot Manager" (qui est l'option d'origine avant l'installation de Ubuntu 12.04.1 sur le disque), il me renvoit aussi le message d'erreur "error : invalid EFI file path" et l'exécution du boot BIOS/EFI s'arrête là. Concernant l'exécution de Boot-Repair sur ma configuration PC portable Asus i5 64 bits et en particulier BIOS/EFI, je précise : - que lors de la génération du rapport BootInfo, j'ai vu qu'il était produit par Boot-Repair que j'ai utilisé fréquemment et sans souci sur un Ubuntu 10.04.3 et un netbook eeePC Asus avec Bios ancienne génération. Boot-Repair me permettait de nettoyer le menu Grub (Bios) et réduire les options de ce menu; - que j'ai lu au préalable et attentivement les pages Web publiées par YannUbuntu le principal contributeur à BootRepair et vérifié sur ces pages Web que Boot-Repair est compatible avec ma configuration PC i5 64 bits avec BIOS/EFI. Autrement dit, tout va bien sur Ubuntu12.04.1, par contre, je n'arrive plus à booter Windows 7. Je continue à chercher sur les forums. Pour le moment, je n'ai rien cassé sur la 2è partition 'unknow type' (dédiée UEFI), même si çà me démange ! J'ai vu hier après-midi votre tutorial "malbo" de 2011 où vous expliquez la suppression de la fameuse 2ème partition 'unknow type' (dédiée UEFI), puis la reconstruction très complexe de recréation de cette 'unknow type' (dédiée UEFI). Je ne me sens pas capable de procéder à une telle reconstruction. C'est pourquoi, j'avance prudemment (cf. le titre de votre tutorial 'Installation prudente de Ubuntu dans un PC UEFI') en recherchant sur les forums et surtout en m'interdisant de supprimer : - la 2ème partition 'unknow type' (dédiée UEFI), - la 1ère partition 'partition de boot d'origine dont le drapeau n'est plus sur "boot", - ainsi que la 3è partition 'Windows 7 OS'. A noter que je n'ai trouvé aucune documentation officielle et utile concernant EFI sur les sites Web Asus, AMI, Microsoft, etc ...; c'est navrant !!! Seuls les contributions précieuses sur les forums permettent d'avancer pas à pas. Encore merci pour votre tutorial 'Installation prudente de Ubuntu dans un PC UEFI'. Très cordialement Marc Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Bonjour Marco, - avant d'installer Ubuntu, aviez-vous accès à Seven et XP? si oui, comment se faisait le choix? (deviez-vous modifier quelquechose dans le BIOS?) - après avoir installé Ubuntu, qu'observiez-vous au redémarrage du pc? à quels systèmes aviez-vous accès, et comment ? - maintenant (après avoir utilisé la Réparation Recommandée de Boot-Repair): quand vous choisissez l'entrée "P1 : Ubuntu (avec BIOS/UEFI)" , le menu GRUB affiche plusieurs entrées, dont: Ubuntu, avec Linux 3.2.0-30-generic "Windows 7 (loader) (on /dev/sda3)" "Windows Recovery Environment (loader) (on /dev/sda4)" "Windows NT/2000/XP (on /dev/sdb7)" "Windows bootmgfw.efi.bkp, generated by Boot-Repair" "Windows memtest.efi, generated by Boot-Repair" "Boot bootx64.efi.bkp, generated by Boot-Repair" Parmi celles-ci, lesquelles fonctionnent? lesquelles ne fonctionnent pas? Dernière modification par YannUbuntu (Le 03/09/2012, à 21:18) Hors ligne raptor2003 Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI @malbo Petit up vers un topic: http://forum.ubuntu-fr.org/viewtopic.php?id=1032691 Hors ligne chel Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI bonsoir malbo, j'avais déjà posté le 3 septembre à ce sujet et mis en résolu, voir http://forum.ubuntu-fr.org/viewtopic.php?pid=10632411 , mais tout en précisant que cela ne me satisfaisait pas. J'ai depuis trouvé cette discussion qui est à mon avis la plus pointue sur le sujet. J'ai donc reformaté tout mon disque dur (en fait supprimé toutes mes partitions), réinstallé windows7 en uefi (ça marche). Et j'ai suivi à la lettre la procédure d'installation de ubuntu décrite dans ce topic. Il y a juste un hic: la création d'une partition sda4 fat16 après d'autres partitions (windows) de plus de 100Go entraîne un adressage trop élévé pour être lu dans le boot sector de la partition. idem sda7 fat32 que j'avais crée en vue de partager avec windows un répertoire www pour xampp. voir mon paste bin 1197593. On peut le vérifier ainsi: j'ai reformaté puis remonté mon sda7 en ntfs et celà ne pose plus de problème (pastebin 1197661). Maintenant que faire pour que mon sda4 apparaisse en file system: bios boot partition, puisque apparemment c'est la config type qui semble marcher. Je précise quand même je peux accéder sans problème aux deux systèmes en faisant F12 (carte mère gigabyte B75M dual bios efi) juste au démarrage ce qui m'offre un multi boot système de remplacement. Merci de ton attention Hors ligne picolo-84 Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Merci, et comment ce fait-il que sur ce site D'Ubuntu qui est officielle, dans le tutoriel, premier paragraphe, pour les débutant, ici: http://doc.ubuntu-fr.org/efi on conseille d'installer Ubuntu-Secure-Remix 64bits qui n'ai pas officielle ? Je comprends pas, en même temps il faut pas l'installé, cars on m'a dit que je risquerais d'avoir des surprise, et il est indiqué dans le tutoriel, Je ne sais vraiment plus ou donner de la tête. Dernière modification par picolo-84 (Le 30/10/2012, à 23:53) Hors ligne YannUbuntu Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Bonne remarque, je viens de modifier le paragraphe en question pour expliquer le pourquoi de ce conseil. Oui il faut se méfier des ISO ou programmes non officiels. Ubuntu-Secure-Remix n'est pas officiel (il n'est pas créé par Canonical, il est créé par moi-même), mais: - il diffère très peu de l'ISO officielle (voir différences ici), seuls 3 logiciels (libres) ont été ajoutés, donc pas de surprise - et est utilisé par plusieurs milliers de personnes sans soucis depuis ~2 ans. Dans le cas de l'UEFI, vous serez probablement amené à utiliser Boot-Repair, qui est aussi développé par moi-même A vous de juger si je suis digne de confiance ou pas... Hors ligne pinparasol Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI Bonsoir Malbo, Merci pour toute la doc et les infos que tu as mis en ligne, cela m'a beaucoup aidé. Je découvre l'Uefi, je commence à comprendre et j'ai 2 questions: 1- pourquoi conseilles-tu de créer une partition FAT-RESERVE au lieu de juste copier tous les dossiers/fichiers de la FAT32 uefi sur une clé usb ou un autre support ? 2- Dans un autre [Tuto] "Installation prudente de Ubuntu ...", tu as marqué: "il faudra naviguer jusqu'au fichier bootmgfw.efi qui se trouve dans le chemin /EFI/Microsoft/Boot/bootmgfw.efi et donner un nom à l'entrée créée". Que veut dire : "donner un nom à l'entrée créée" ? Merci de bien vouloir m'éclairer. Nota: tu as raison je me m'étais trompé de discussion, j'avais trop d'onglets d'ouverts. Désolé. Hors ligne malbo Re : [Tuto] Installation prudente de Ubuntu dans un PC UEFI pinparasol, Ce tuto a été écrit il y a un an et demie à une époque où Ubuntu s'installait de façon catastrophique dans un ordi préinstallé Windows. A l'heure actuelle, Ubuntu s'installe toujours comme une bouse dans un ordi préinstallé Windows (rapport de Bug #807801) mais au moins il ne saccage plus la partition EFI. Ce tuto est donc obsolète comme je l'ai d’ailleurs rajouté dans l'intro du post #1. Cela étant posé, ton idée de copier les dossiers/fichiers de la FAT32 uefi sur une clé usb ou un autre support doit fonctionner. Pour ta question sur "donner un nom à l'entrée créée", il s'agissait de configurer "à la main" le système UEFI : cette procédure est toujours utilisable sur des ordi équipés d'un système UEFI vieillissant mais là encore, tu t'intéresses à une procédure obsolète puisque j'ai écrit en caractères gras un peu au-dessus : "La partie ci-après qui décrit la configuration à la main de l'UEFI n'est pas nécessaire dans le cas d'un système UEFI performant : la création des entrées est alors faite automatiquement par le système UEFI" En conclusion, je te prie d'arrêter de t'intéresser à ce tuto obsolète sauf si tu as de bonnes raisons de le faire. Dernière modification par malbo (Le 13/06/2013, à 08:32) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne
httplib.HTTPMessage(filehandle).getdate(headername) httplib.HTTPMessage(filehandle).getdate_tz(headername) mimetools.Message(filehandle).getdate() rfc822.parsedate(datestr) rfc822.parsedate_tz(datestr) if you have a raw data stream, you can build an HTTPMessage or a mimetools.Message from it. it may offer additional help while querying the response object for infos if you are using urllib2, you already have an HTTPMessage object hidden in the filehandler returned by urlopen it can probably parse many date formats httplib is in the core NOTE: had a look at implementation, HTTPMessage inherits from mimetools.Message which inherits from rfc822.Message. two floating defs are of your interest maybe, parsedate and parsedate_tz (in the latter) parsedate(_tz) from email.utils has a different implementation, although it looks kind of the same. you can do this, if you only have that piece of string and you want to parse it: >>> from rfc822 import parsedate, parsedate_tz >>> parsedate('Wed, 23 Sep 2009 22:15:29 GMT') (2009, 9, 23, 22, 15, 29, 0, 1, 0) >>> but let me exemplify through mime messages: import mimetools import StringIO message = mimetools.Message( StringIO.StringIO('Date:Wed, 23 Sep 2009 22:15:29 GMT\r\n\r\n')) >>> m <mimetools.Message instance at 0x7fc259146710> >>> m.getdate('Date') (2009, 9, 23, 22, 15, 29, 0, 1, 0) or via http messages (responses) >>> from httplib import HTTPMessage >>> from StringIO import StringIO >>> http_response = HTTPMessage(StringIO('Date:Wed, 23 Sep 2009 22:15:29 GMT\r\n\r\n')) >>> #http_response can be grabbed via urllib2.urlopen(url).info(), right? >>> http_response.getdate('Date') (2009, 9, 23, 22, 15, 29, 0, 1, 0) right? >>> import urllib2 >>> urllib2.urlopen('https://fw.io/').info().getdate('Date') (2014, 2, 19, 18, 53, 26, 0, 1, 0) there, now we now more about date formats, mime messages, mime tools and their pythonic implementation ;-) whatever the case, looks better than using email.utils for parsing http headers.
I'd like to create a drop-in replacement for python's list, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimplement all of list's functionality though. Is there a easy + pythonic way to do it? Pseudocode: class MyList(list): # ... def on_add(self, items): print "Added:" for i in items: print i # and the same for on_remove l = MyList() l += [1,2,3] # etc.
It's probably a dumb question but I don't manage to put a sum expression in a If condition. I work on a CSV file composed of 3 rows A, B and C. Here is my code : #import and export files test = "/home/julien/excel/test.csv" file1 = open (test, 'rb') export_test = "/home/julien/excel/export_test.csv" file2 = open (export_test, 'wb') reader1 = csv.reader (file1, delimiter = ';', quotechar=' ') writer1 = csv.writer (file2, delimiter= ';', quotechar=' ') #conditions on test.csv for row1 in reader1: A = row1[0] B = row1[1] C = row1[2] if (A + B) == C: writer1.writerow (["calcul ok"]) else: writer1.writerow (["fail"]) The problem is that I only have "fail" results whereas it should not. Could you help me ? Thanks !
Deevad [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Update janvier 2011: Besoin d'une documentation claire et bien écrite sur Xsetwacom ? Le contributeur présent sur ce sujet RegisBurin à rédigé la meilleure documentation existante à ce jour sur 'xsetwacom' et c'est tout en français , et elle se trouve ici : http://regisestuncool.wordpress.com/201 … ur-debian/ Je vous invite vivement à passer par là d'abords pour comprendre définitivement comment vous aller pouvoir configurer votre tablette sous Ubuntu/Debian. Bonne lecture et merci Régis ! (note j'ai modifié le titre du sujet en supprimant Karmic/Jaunty... la méthode reste -à quelques variantes près- la même pour les version d'après ) Update janvier 2010: Beaucoup trouverons leur bonheur avec ceci : (un beau *.deb ) http://www.gtk-apps.org/content/show.ph … ent=104309 Une interface graphique pour paramêtrer les boutons et paramêtre des Wacom. Adopté ici, même si je complète toujours d'un peu de script par-ci par-là. Sinon, la méthode pour trouver son identifieur ( "2. Identifier le nom "système" de la tablette" ) , va plus vite avec ça : xinput --list | grep '[w|W]acom' ou lshal | grep '[w|W]acom' Ancien contenu ( mai 2009 ): Bonjour, Beaucoup se demandent comment configurer les boutons , le stylet et le mapping de la tablette de manière complète , et ces informations sont centralisés dans très rare documentation. Aussi la page de référence sur Linuxwacom utilise un jargon informatique assez difficile pour un utilisateur moyen. Depuis les dernières distributions dont Jaunty, les tablettes Wacom ( en USB du moins ) s'installent "out of the box" , de plus elles bénéficient du "plug" à chaud. Par contre, les boutons de raccourcis sur la tablette ne sont pas configurable , ni ceux du stylet. Voici ma méthode pour configurer tout ce que je veux d'une wacom : 1. Installer wacom-Tools Ma méthode consiste à installer uniquement les wacom-tools pour avoir accès a xsetwacom qui en fait parti : $ sudo apt-get install wacom-tools 2. Identifier le nom "système" de la tablette Avec : ( * voir update en haut du post pour une methode plus facile ) $ lshal Vous allez pouvoir connaitre le nom par lequel Ubuntu identifie votre périphérique. il vous retournera beaucoup d'informations à trier aussi le style de ligne à trouver est du genre : $ info.product = 'Wacom [nomdelatablette]' (string) $ info.product = 'Wacom [nomdelatablette] pad' (string)Note : n'hésitez pas à aller dans "terminal">"préférence du profil" et d'augmenter à l'onglet défilement la valeur "Lignes d'historique" sinon vous risquez de ne pas voir l'entièreté du rapport de de "lshal" .Exemples de noms :Wacom BambooFun 6x8 Wacom Intuos3 9x12Wacom Cintiq 12WX 3. Faire un script .sh pour lancer une serie de commande à xsetwacom Le principe est de créer un fichier avec gedit qu'on enregistrera en extension ".sh" qui enverra les commandes a xsetwacom de personalisation. J'ai créer 3 script pour les matériels de l'exemple , ils sont à modifier en fonction de votre nom "système" de la tablette ( voir .2 ) ; ainsi que vos touches pour la personnaliser. Tout est indiqué dans les "commentaires" de ces codes pour une personnalisation plus souple. Script pour Wacom BambooFun 6x8 : (ci-dessous) #!/bin/sh # Script Xsetwacom pour BambooFun A5, sous Ubuntu Jaunty 9.04. # par David Revoy ; www.davidrevoy.com # D'après les infos présent dans le manuel de Xsetwacom sur le LinuxWacom project. # -- Manuel -- # Pour connaitre toutes les touches accessible par xsetwacom, faites : "xsetwacom list mod" ( sans les guillemets ) dans un terminal # Pour connaitre les noms systeme de votre matériel Wacom (ici "Wacom BambooFun 6x8 pad" et "Wacom BambooFun 6x8" ) consultez : "lshal" ( sans les guillemets ) dans un terminal pour connaitre le nom de votre périphérique. il vous retournera beaucoup d'informations à trier. # ligne à trouver du genre; info.product = 'Wacom [nomdelatablette] xxxxxx' (string) # autre ligne à trouver ; info.product = 'Wacom [nomdelatablette] xxxxxx pad' (string) # ou X correspond au model de votre Wacom # Ensuite, changer le script suivant vos infos et personalisez-le avec vos paramêtres. # enregistrer le comme un fichier XXXX.sh ( ou XXXX= votre nom de fichier ) et executer le à votre convenance. # vous pouvez même créer plusieurs scripts en fonctions de vos besoins et les executer en live. # Happy config ;) # ---- Début du script : ----- # 1)Boutons : # strips en anneau haut: xsetwacom set "Wacom BambooFun 6x8 pad" AbsWUp "core key -" # Zoom - # strips en anneau bas: xsetwacom set "Wacom BambooFun 6x8 pad" AbsWDn "core key +" # Zoom + # les quatres boutons : # < = button 1 # Fn1 = button 2 # > = button 3 # Fn2 = button 4 xsetwacom set "Wacom BambooFun 6x8 pad" button1 "core key CONTROL z" # undo xsetwacom set "Wacom BambooFun 6x8 pad" button2 "core key shift" # trace ligne xsetwacom set "Wacom BambooFun 6x8 pad" button3 "core key CONTROL y" # redo xsetwacom set "Wacom BambooFun 6x8 pad" button4 "core key b" # brush # 2)Stylet # Stylet ( button1=pointe ; button2=premier boutton ; button3=second boutton ) xsetwacom set "Wacom BambooFun 6x8" button2 "core key Control" # Control=pipette # 3)Mapping de la zone réactive # Mapping absolue de la tablette xsetwacom set "Wacom BambooFun 6x8" mode Absolute # Mapping de ma tablette 4/3 pour suivre mon ecran wide 16/9 de 1680x1050 # Opération obtenu par le calcul suivant : (si ça vous intéresse pour faire la même chose avec votre ecran) # (1680/1050)=(BottomX21648/BottomY) # donc BottomY=(21648x1050)/1680 # BottomY=13530 # La tablette est déjà "wide" ! # (ci dessous = valeur par defaut de ma tablette) # xsetwacom get "Wacom BambooFun 6x8" TopX 0 # xsetwacom set "Wacom BambooFun 6x8" TopY 0 # xsetwacom set "Wacom BambooFun 6x8" BottomY 13530 # xsetwacom set "Wacom BambooFun 6x8" BottomX 21648 xsetwacom set "Wacom BambooFun 6x8" TopX 0 xsetwacom set "Wacom BambooFun 6x8" TopY 0 xsetwacom set "Wacom BambooFun 6x8" BottomY 13530 xsetwacom set "Wacom BambooFun 6x8" BottomX 21648 # Fin # -------- Script pour Wacom Intuos3 9x12 : (ci-dessous) #!/bin/sh # Script Xsetwacom pour Intuos 3 A4, sous Ubuntu Jaunty 9.04. # par David Revoy ; www.davidrevoy.com # D'après les infos présent dans le manuel de Xsetwacom sur le LinuxWacom project. # -- Manuel -- # Pour connaitre toutes les touches accessible par xsetwacom, faites : "xsetwacom list mod" ( sans les guillemets ) dans un terminal # Pour connaitre les noms systeme de votre matériel Wacom (ici "Wacom Intuos3 9x12 pad" et "Wacom Intuos3 9x12" ) consultez : "lshal" ( sans les guillemets ) dans un terminal pour connaitre le nom de votre périphérique. il vous retournera beaucoup d'informations à trier. # ligne à trouver du genre; info.product = 'Wacom [nomdelatablette] xxxxxx' (string) # autre ligne à trouver ; info.product = 'Wacom [nomdelatablette] xxxxxx pad' (string) # ou X correspond au model de votre Wacom # Ensuite, changer le script suivant vos infos et personalisez-le avec vos paramêtres. # enregistrer le comme un fichier XXXX.sh ( ou XXXX= votre nom de fichier ) et executer le à votre convenance. # vous pouvez même créer plusieurs scripts en fonctions de vos besoins et les executer en live. # Happy config ;) # ---- Début du script : ----- # 1)Boutons : # zones de strips gauche ( haut puis bas ): xsetwacom set "Wacom Intuos3 9x12 pad" striplup "core key :" # touche ;(taille du pinceau xsetwacom set "Wacom Intuos3 9x12 pad" stripldn "core key ;" # touche :(dans ma config Gimp # zones de strips droit ( haut puis bas ): xsetwacom set "Wacom Intuos3 9x12 pad" striprup "core key +" # Zoom - xsetwacom set "Wacom Intuos3 9x12 pad" striprdn "core key -" # Zoom + # Bouttons gauches: # --------- # | | 1 | # | 3 |---| # | | 2 | # |-------| # | 4 | # --------- xsetwacom set "Wacom Intuos3 9x12 pad" button1 "core key CONTROL y" # redo xsetwacom set "Wacom Intuos3 9x12 pad" button2 "core key CONTROL z" # undo xsetwacom set "Wacom Intuos3 9x12 pad" button3 "core key shift" # tracer une ligne xsetwacom set "Wacom Intuos3 9x12 pad" button4 "core key b" # retour au brushs # Bouttons droite: # --------- # | 5 | | # |---| 7 | # | 6 | | # |-------| # | 8 | # --------- xsetwacom set "Wacom Intuos3 9x12 pad" button5 "core key CONTROL y" # redo xsetwacom set "Wacom Intuos3 9x12 pad" button6 "core key CONTROL z" # undo xsetwacom set "Wacom Intuos3 9x12 pad" button7 "core key shift" # shift xsetwacom set "Wacom Intuos3 9x12 pad" button8 "core key b" # brush B # 2)Stylet # Stylet ( button1=pointe ; button2=premier boutton ; button3=second boutton ) xsetwacom set "Wacom Intuos3 9x12" button2 "core key Control" # bouton 2 du stylet pipette # 3)Mapping de la zone réactive # Mapping absolue de la tablette xsetwacom set "Wacom Intuos3 9x12" mode Absolute # Mapping de ma tablette 4/3 pour suivre mon ecran wide 16/9 de 1680x1050 # Opération obtenu par le calcul suivant : (si ça vous intéresse pour faire la même chose avec votre ecran) # (1680/1050)=(BottomX60960/BottomY) # donc BottomY=(60960x1050)/1680 # BottomY=38100 # (ci dessous = valeur par defaut de ma tablette) # xsetwacom set "Wacom Intuos3 9x12" TopX 0 # xsetwacom set "Wacom Intuos3 9x12" TopY 0 # xsetwacom set "Wacom Intuos3 9x12" BottomY 45720 # xsetwacom set "Wacom Intuos3 9x12" BottomX 60960 xsetwacom set "Wacom Intuos3 9x12" TopX 0 xsetwacom set "Wacom Intuos3 9x12" TopY 0 xsetwacom set "Wacom Intuos3 9x12" BottomY 38100 xsetwacom set "Wacom Intuos3 9x12" BottomX 60960 # Fin # -------- Script pour Wacom Cintiq 12WX : (ci-dessous) ( voir dans les commentaires du fichier pour ces particularités de double écran / tablettes ) #!/bin/sh # Script Xsetwacom pour Wacom Cintiq 12WX, sous Ubuntu Jaunty 9.04. # par David Revoy ; www.davidrevoy.com # D'après les infos présent dans le manuel de Xsetwacom sur le LinuxWacom project. # -- Manuel -- # Pour connaitre toutes les touches accessible par xsetwacom, faites : "xsetwacom list mod" ( sans les guillemets ) dans un terminal # Pour connaitre les noms systeme de votre matériel Wacom (ici "Wacom Cintiq 12WX pad" et "Wacom Cintiq 12WX 9x12" ) consultez : "lshal" ( sans les guillemets ) dans un terminal pour connaitre le nom de votre périphérique. il vous retournera beaucoup d'informations à trier. # ligne à trouver du genre; info.product = 'Wacom [nomdelatablette] xxxxxx' (string) # autre ligne à trouver ; info.product = 'Wacom [nomdelatablette] xxxxxx pad' (string) # ou X correspond au model de votre Wacom # Ensuite, changer le script suivant vos infos et personalisez-le avec vos paramêtres. # enregistrer le comme un fichier XXXX.sh ( ou XXXX= votre nom de fichier ) et executer le à votre convenance. # vous pouvez même créer plusieurs scripts en fonctions de vos besoins et les executer en live. # Happy config ;) # Note sur la Cintiq12WX et le double ecran # je l'ai installé avec une carte Nvidia et le pilote propriétaire # grace à "sudo /usr/bin/nvidia-settings" j'ai pu configurer deux ecran en serverX séparé avec Xinerama. # le 1680x1050 est l'écran 0 et la cintiq l'ecran 1 # (note : j'utilise "sudo" pour que nvidia-setting puisse enregistrer le Xorg.) # ---- Début du script : ----- # 1)Boutons : # zones de strips gauche ( haut puis bas ): xsetwacom set "Wacom Cintiq 12WX pad" striplup "core key :" # touche ;(taille du pinceau xsetwacom set "Wacom Cintiq 12WX pad" stripldn "core key ;" # touche :(dans ma config Gimp # zones de strips droit ( haut puis bas ): xsetwacom set "Wacom Cintiq 12WX pad" striprup "core key +" # Zoom - xsetwacom set "Wacom Cintiq 12WX pad" striprdn "core key -" # Zoom + # Bouttons gauches: # --------- # | 9 | # --------- # | | 1 | # | 3 |---| # | | 2 | # |-------| # | 4 | # --------- # Propre à la CINTIQ : # La touche pour changer d'écran # Switch entre mode 2 ecran / ecran 1 / ecran 2 xsetwacom set "Wacom Cintiq 12WX pad" button9 "DISPLAYTOGGLE" xsetwacom set "Wacom Cintiq 12WX pad" button1 "core key CONTROL y" # redo xsetwacom set "Wacom Cintiq 12WX pad" button2 "core key CONTROL z" # undo xsetwacom set "Wacom Cintiq 12WX pad" button3 "core key shift" # tracer une ligne # Bouttons droite: # --------- # | 10 | # --------- # | 5 | | # |---| 7 | # | 6 | | # |-------| # | 8 | # --------- xsetwacom set "Wacom Cintiq 12WX pad" button5 "core key CONTROL y" # redo xsetwacom set "Wacom Cintiq 12WX pad" button6 "core key CONTROL z" # undo xsetwacom set "Wacom Cintiq 12WX pad" button7 "core key shift" # shift xsetwacom set "Wacom Cintiq 12WX pad" button8 "core key b" # brush B xsetwacom set "Wacom Cintiq 12WX pad" button10 "DISPLAYTOGGLE" # change d'ecran # 2)Stylet # Stylet ( button1=pointe ; button2=premier boutton ; button3=second boutton ) xsetwacom set "Wacom Cintiq 12WX" button2 "core key Control" # bouton 2 du stylet pipette # 3)Mapping de la zone réactive # Mapping absolue de la tablette xsetwacom set "Wacom Cintiq 12WX" mode Absolute # Fin # -------- Enfin - Pour une utilisation simple du script ( en admettant que celui ci est installé dans le repertoire "Script" de "home" sous le nom "tablet.sh", j'ai créer dans mon Gnome panel une icône de lancement ( donc vers /home/[monnomd'utilisateur]/Script/tablet.sh ). On peut d'ailleur dans les icônes système, trouver dans les "icônes Gnome>device" une belle icone de tablette graphique. - Ne pas oublier de rendre le fichier *.sh exécutable ( clic droit sur le fichier, Propriété , Permission , Autoriser l'exécution .... ) - Ne pas oublier d'éxecuter le script à chaque lancement. Vous pouvez également vous faire plusieurs script en fonction de différente configuration souhaité. - Ne branchez pas plusieurs tablettes graphiques en même temps , cela provoque des conflits. Bonne installation de vos boutons ! Dernière modification par Deevad (Le 19/01/2011, à 10:23) Hors ligne Brunod Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Dès que je passe sur Jaunty, je mets ça en pratique ! BD 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 alain59144 Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Bonjour, si tu vas sur ce poste comme il n'est pas fermé je pense voici ce que me donne la réponse à lshal udi = '/org/freedesktop/Hal/devices/usb_device_8ca_10_noserial' info.linux.driver = 'usb' (string) info.parent = '/org/freedesktop/Hal/devices/usb_device_1d6b_1_0000_00_02_0' (string) info.product = 'Tablet' (string) info.subsystem = 'usb_device' (string) info.udi = '/org/freedesktop/Hal/devices/usb_device_8ca_10_noserial' (string) info.vendor = 'Aiptek International, Inc.' (string) linux.device_file = '/dev/bus/usb/002/006' (string) linux.hotplug_type = 2 (0x2) (int) linux.subsystem = 'usb' (string) linux.sysfs_path = '/sys/devices/pci0000:00/0000:00:02.0/usb2/2-3' (string) usb_device.bus_number = 2 (0x2) (int) usb_device.can_wake_up = false (bool) usb_device.device_class = 0 (0x0) (int) usb_device.device_protocol = 0 (0x0) (int) usb_device.device_revision_bcd = 261 (0x105) (int) usb_device.device_subclass = 0 (0x0) (int) usb_device.is_self_powered = false (bool) usb_device.linux.device_number = 6 (0x6) (int) usb_device.linux.sysfs_path = '/sys/devices/pci0000:00/0000:00:02.0/usb2/2-3' (string) usb_device.max_power = 26 (0x1a) (int) usb_device.num_configurations = 1 (0x1) (int) usb_device.num_ports = 0 (0x0) (int) usb_device.product = 'Tablet' (string) usb_device.product_id = 16 (0x10) (int) usb_device.speed = 1.5 (1.5) (double) usb_device.vendor = 'Aiptek International, Inc.' (string) usb_device.vendor_id = 2250 (0x8ca) (int) usb_device.version = 1.1 (1.1) (double) udi = '/org/freedesktop/Hal/devices/usb_device_8ca_10_noserial_if0' info.linux.driver = 'aiptek' (string) info.parent = '/org/freedesktop/Hal/devices/usb_device_8ca_10_noserial' (stri j'ai une medion MD 41217 et je suis sous jaunty et je voudrai la faire fonctionner j'ai posté là : http://forum.ubuntu-fr.org/viewtopic.php?pid=2881337 merci de m'aider On a déjà assez de soucis avec ce qui arrive, ne nous prenons pas la tête avec ce qui aurait pu arriver.... ubuntu depuis 2010..j'avance doucement dans la connaissance du système, j'utilise Gimp VLC Openshot EKD Audacity KDEnLive MediaMobilConverter (pour Linux)... Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom j'ai une medion MD 41217 et je suis sous jaunty Désolé Alain59144 je n'ai pas ce genre de matériel et je ne peux donc ni le connaitre ni le tester. Ici je traite des Bamboo et des Intuos 3 ; bon courage. Hors ligne compte supprimé Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Salut et merci pour le tuto. Sais-tu si on peut utiliser/configurer l'inclinaison de la bamboo fun ? La pression et la vitesse sont configurables et utilisables dans Gimp, et Krita, mais je n'arrive pas à trouver comment on fait pour l'inclinaison. Merci pour ton travail. PS : j'adore la "théorie du chaos" au début de la vidéo sur vimeo. Très interréssant, je me lance de suite (j'installe Alchemy) Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Merci deuzene pour ton commentaire ; malheuresement la Bamboo n'a ni rotation/ni inclinaison ; c'est une limitation du matériel. Pour avoir ces performances , il faut la gamme Intuos. Hors ligne totojules Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Salut, merci pour ce tuto simple d'installation (je suis encore en 8.04 mais dès la 9.10 je le mettrai en pratique...). J'ai une remarque et une question. J'ai lu qu'on pouvait aussi passer par un fichier de conf .fdi pré-installé. Est-ce une alternative au script que tu utilises? Je souhaite acquérir une tablette graphique wacom cintiq 12wx et je voudrais l'utiliser sous linux bien sur... Cette tablette nécessite de passer en dual-screen, et le dual sreen sous linux me fait peur!!! Est-ce que la configuration dual-screen + wacom cintiq posent des problèmes? Faut-il privilégier un chip graphique particulier pour le dual-screen (rapport à la guerre des drivers NVIDIA mieux que ATI mieux que NVIDIA mieux que...). Merci. Note : La prochaine fois je lirai mieux y a déjà tout d'écrit pour la partie cintiq.... je laisse ma question sur les chips graphique en vue d'un changement de pc... Dernière modification par totojules (Le 11/09/2009, à 00:51) Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Hello Totojules, Juste un petit mot pour te faire le retour qu'ici je me suis séparé de ma cintiq 12wx ; elle ne m'offrait pas une ergonomie au top après mon passage à Linux ; Certains details cruciaux restent encore brouillon ; comme la calibration de l'ecran par rapport au pointeur, ainsi que la la difficulté d'instalation ( xinerama / nvidia / touche de "toggle" entre ecran. ) . Bref , au final je trouve une simple intuos ou bamboo plus productive. Si j'ai besoin d'avoir une sensation de dessin 'directe' ; rien de mieux que le papier + scanner. La cintiq ne remplace ni n'émule ça. Mais ça reste un chouette matos que j'ai eu entre les mains 1 année. Hors ligne yagraph Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Merci beaucoup Mr David Revoy, j'ai enfin pu complètement configurer une Wacom Cintiq 21UX grâce à ce thread ! je partage donc ici le script employé : #!/bin/sh # Script Xsetwacom pour Wacom Cintiq 21UX, sous Ubuntu Karmic 9.10. # Par Camille Bissuel ; www.yagraph.org # D'après le script pour Wacom Cintiq 21UX de David Revoy ; www.davidrevoy.com # D'après les infos présent dans le manuel de Xsetwacom sur le LinuxWacom project. # -- Manuel -- # Pour connaitre toutes les touches accessible par xsetwacom, faites : "xsetwacom list mod" ( sans les guillemets ) dans un terminal # Pour connaitre les noms systeme de votre matériel Wacom (ici "Wacom Cintiq 21UX pad" et "Wacom Cintiq 21UX 9x12" ) consultez : "lshal" ( sans les guillemets ) dans un terminal pour connaitre le nom de votre périphérique. il vous retournera beaucoup d'informations à trier. # ligne à trouver du genre; info.product = 'Wacom [nomdelatablette] xxxxxx' (string) # autre ligne à trouver ; info.product = 'Wacom [nomdelatablette] xxxxxx pad' (string) # ou X correspond au model de votre Wacom # Ensuite, changer le script suivant vos infos et personalisez-le avec vos paramêtres. # enregistrer le comme un fichier XXXX.sh ( ou XXXX= votre nom de fichier ) et executer le à votre convenance. # vous pouvez même créer plusieurs scripts en fonctions de vos besoins et les executer en live. # Happy config ;) # ---- Début du script : ----- # 1)Boutons : # zones de strips gauche ( haut puis bas ): xsetwacom set "Wacom Cintiq 21UX pad" striplup "core key PageUp" # touche PageUp (taille du pinceau xsetwacom set "Wacom Cintiq 21UX pad" stripldn "core key PageDown" # touche PageDown (dans ma config Gimp et scroll ailleurs # zones de strips droit ( haut puis bas ): xsetwacom set "Wacom Cintiq 21UX pad" striprup "core key +" # Zoom - xsetwacom set "Wacom Cintiq 21UX pad" striprdn "core key -" # Zoom + # Boutons gauches: # --------- # | | 1 | # | 3 |---| # | | 2 | # |-------| # | 4 | # --------- xsetwacom set "Wacom Cintiq 21UX pad" button1 "core key space" # Shift xsetwacom set "Wacom Cintiq 21UX pad" button2 "core key alt" # Alt xsetwacom set "Wacom Cintiq 21UX pad" button3 "core key shift" # Shift xsetwacom set "Wacom Cintiq 21UX pad" button4 "core key ctrl" # Ctrl # Boutons droite: # --------- # | 5 | | # |---| 7 | # | 6 | | # |-------| # | 8 | # --------- xsetwacom set "Wacom Cintiq 21UX pad" button5 "core key CONTROL z" # undo xsetwacom set "Wacom Cintiq 21UX pad" button6 "core key CONTROL y" # redo xsetwacom set "Wacom Cintiq 21UX pad" button7 "core key m" # Outils de déplacement M xsetwacom set "Wacom Cintiq 21UX pad" button8 "core key p" # Pinceau touche P # 2)Stylet # Stylet ( button1=pointe ; button2=premier boutton ; button3=second boutton ) # xsetwacom set "Wacom Cintiq 21UX" button2 "core key Control" # bouton 2 du stylet pipette # 3)Mapping de la zone réactive # Mapping absolue de la tablette xsetwacom set "Wacom Cintiq 21UX" mode Absolute # Fin # -------- Au passage je signale qu'avec cette tablette/écran sur Linux, l'ergonomie est excelente Pensez aussi à Installer Gimp Paint Studio pour en profiter pleinement : http://code.google.com/p/gps-gimp-paint-studio/ Tout mon soutien et mes encouragements pour Durian, ou plutôt Sintel maintenant Dernière modification par yagraph (Le 03/11/2009, à 14:56) Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Super pour la 21UX ! merci aussi pour les encouragements sur le 3eme open movie ; y'en a bien besoin ! Hors ligne doraynico Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom salut a tous, merci pour toutes les infos au dessus. J'ai une cintiq 12, et j'ai biensur des problemes sur ubuntu koala. Je me demande comment parametrer non pas les touchpads mais le menu radial et reussir a activer le basculement entre deux ecrans... parce que là le deuxieme ecran 21 pouces cloné sur la cintiq 12 en 1200x800 c'est lourd. bref a quand un driver wacom propriétaire ? Hors ligne yagraph Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom @ doraynico : C'est assez difficile de te répondre comme ça ... j'ai regardé des photos de la Cintiq 12... mais je n'ai vu de "menu radial". Qu'est ce que c'est ? Pour avoir une liste de toutes les fonctions accessible depuis ta tablette (tu trouvera peut-être quelque chose relatif à ce menu là dedans...) : xsetwacom list param sinon pour le paramétrage de ton double écran, tout dépends de ta carte graphique (ATi, Intel, Nvidia ?)... mais tu as interet à paramétrer ça avec Xrandr ou plutôt son interface graphique grandr, puisque c'est la méthode standard. Tout est là : http://doc.ubuntu-fr.org/xrandr PS : heureusement que le pilote wacom n'est pas propriétaire... avec tout ce qui entre en jeu au niveau du serveur X pour faire tourner une tablette/écran, ce ne serait tout simplement pas possible (multi-écran, branchement et débranchement à chaud, gestion de évènements d'entrée multiples...). De plus tu ne va vraiment pas te faire des amis avec ce genre de remarques ;p Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom le basculement entre deux ecrans... Ca fontionne mais avec une carte Nvidia ; le setup et instruction est dans mon fichier (premier poste). Le menu radial est un software de Wacom, mais pas sous Linux. Le driver Linux ce contente de faire marcher les fonctionalités et bouttons. ( c'est déjà pas mal ) A quand un driver wacom propriétaire ? J'ai déjà fait mon email à Wacom. Si on serait plus, ça marcherais surement mieux. Bon email ! Hors ligne doraynico Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom J'ai aussi écrit a wacom pour leur demander de traiter le probleme. Pour repondre a la question sur le menu radial c'est une nouvelle option du driver wacom qui te permet de faire apparaitre un menu contextuel que tu parametres comme tu veux. C'est pratique pour ceux qui veulent se passer des raccourcis clavier et fluidifier encore les interfaces de leur soft préféré. Je n'arrive pas non plus a parametrer l'alignement du curseur exactement sous la pointe du stylet. C'est configurable facilement avec le driver wacom sous xp et macos. A la limite comme tu dis deevad autant revendre sa cintiq si on veut bosser sur linux et reprendre une tablette sans ecran. Hors ligne lionbeast Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom merci beaucoup pour le script. mais j'ai quand meme un souci. j'utilise photoshop dans wine et la barre d'espace permet de bouger l'image. alors j'ai mis un boutton core key space mais photoshop ne veut rien savoir. pourtant les autres racourcie il les accepte tres bien. sinon j'ai essayer nvidia settings twinview et separate x screens mais le pointeur utlilise les deux ecrans au lieu de juste la cintiq dans les deux cas. Dernière modification par lionbeast (Le 05/01/2010, à 21:19) Hors ligne Elzen Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Kupo les gens... Je remonte le sujet en vitesse : je viens de récupérer une Wacom Volito2, elle marche très bien, sauf que deux choses de la config par défaut ne me conviennent pas, et vous pouvez peut-être m'aider : * la tablette est en mode absolu, je la préférerais largement en relatif. * les deux boutons sur les côtés, celui du bas fait clic gauche et celui du haut clic milieu, l'inverse serait peut-être plus pratique, je ne sais pas, je voudrais essayer. Je tente donc d'utiliser xsetwacom pour régler ça, sauf que je ne comprends pas comment c'est censé marcher : seth@fadreils: ~$ xsetwacom list dev"Wacom Volito2 4x5" eraser ERASER "Wacom Volito2 4x5" cursor CURSOR "Wacom Volito2 4x5" STYLUS seth@fadreils: ~$ xsetwacom set "Wacom Volito2 4x5" mode RelativeCannot find device 'Wacom Volito2 4x5'.seth@fadreils: ~$ xsetwacom set STYLUS mode RelativeCannot find device 'STYLUS'.seth@fadreils: ~$ xsetwacom set stylus mode RelativeCannot find device 'stylus'.seth@fadreils: ~$ xsetwacom set "Wacom Volito2 4x5 STYLUS" mode RelativeCannot find device 'Wacom Volito2 4x5 STYLUS'.seth@fadreils: ~$ xsetwacom set "Wacom Volito2 4x5 Stylus" mode RelativeCannot find device 'Wacom Volito2 4x5 Stylus'.seth@fadreils: ~$ J'ai essayé un paquet d'autres solutions, mais j'obtiens le même "Cannot find device" à chaque fois. Quelqu'un saurait-il m'aider ? Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth) Un script pour améliorer quelques trucs du forum. La joie de t'avoir connu surpasse la peine de t'avoir perdu… J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire. Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Bonjour ArkSeth, Je ne suis pas spécialiste de la Volito ( jamais eu ici ) , mais on peux essayer ; que te retourne un : lshal | grep '[w|W]acom' ? Hors ligne Elzen Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom seth@fadreils: ~$ lshal | grep '[w|W]acom' info.vendor = 'Wacom Co., Ltd' (string) usb_device.vendor = 'Wacom Co., Ltd' (string) info.linux.driver = 'wacom' (string) usb.vendor = 'Wacom Co., Ltd' (string) info.product = 'Wacom Volito2 4x5' (string) input.product = 'Wacom Volito2 4x5' (string)seth@fadreils: ~$ Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth) Un script pour améliorer quelques trucs du forum. La joie de t'avoir connu surpasse la peine de t'avoir perdu… J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire. Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Merci, comme j'y vais à taton, maintenant ceci ( ça devrait renseigner sur les noms du pad / stylus / eraser ). xinput --list | grep '[w|W]acom' Hors ligne Elzen Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Tiens, xinput n'était même pas installé :s J'ai une install minimale de Debian Sid, d'ailleurs, donc ça vient peut-être tout simplement d'un paquet que je n'ai pas installé. seth@fadreils: ~$ xinput --list | grep '[w|W]acom' ⎜ ↳ "Wacom Volito2 4x5" eraser id=10 [slave pointer (2)] ⎜ ↳ "Wacom Volito2 4x5" cursor id=11 [slave pointer (2)] ⎜ ↳ "Wacom Volito2 4x5" id=12 [slave pointer (2)] seth@fadreils: ~$ Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth) Un script pour améliorer quelques trucs du forum. La joie de t'avoir connu surpasse la peine de t'avoir perdu… J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire. Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom J'ai une install minimale de Debian Sid, d'ailleurs, donc ça vient peut-être tout simplement d'un paquet que je n'ai pas installé. Peut-être, car là, je sèche... "Wacom Volito2 4x5" est bien l'identifieur de la tablette, et xsetwacom devrait pouvoir agir dessus. Hors ligne Elzen Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Après recherche, je crois que le problème vient du fait que ma Debian Sid utilise la version 0.10.3+20100109 de xserver-xorg-input-wacom (la même que sur Lucid Lynx), et pas la 0.8.3.2 comme Karmic Koala. Dans cette version, xsetwacom est directement intégré à ce paquet au lieu d'être présent dans le paquet wacom-tools (ce qui m'empêche d'ailleurs d'installer ce dernier, et donc l'outil de configuration proposé dans le premier post qui en dépend, puisqu'il y aurait conflit entre les deux fichiers – d'ailleurs, si wacom-tools est encore dans les dépôts de Sid, il n'a plus l'air d'être dans ceux de Lucid Lynx). Dernière modification par ArkSeth (Le 23/01/2010, à 13:06) Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth) Un script pour améliorer quelques trucs du forum. La joie de t'avoir connu surpasse la peine de t'avoir perdu… J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire. Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Merci ArkSeth pour les précision. Encore des nuits blanches à la prochaine upgrade pour retrouver ce qu'on avait déjà de bien configurer d'avant... ! Peut-être que le GUI tablette dans les users preférences prévue pour Jaunty ( mais au développement arrêté manque de contributeur ) refera son apparition. Ca serait bien ! Hors ligne Elzen Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Bon, je donne quand même des nouvelles : en fait, ça marche bien, mais allez savoir pourquoi, pas par le nom. Je ne sais pas si c'est très normal que "Wacom Volito2 4x5" ne soit pas reconnu, mais en tout cas, cette version-là de xsetwacom reconnaît au moins "12" (l'identifiant chiffré indiqué sur la ligne renvoyée par xinput --list et indiquée ci-dessus). Maintenant, le problème est que cette config est perdue à chaque débranchement, donc je cherche encore, mais au moins, en voilà une bonne partie de résolu Elzen : polisson, polémiste, polymathe ! (ex-ArkSeth) Un script pour améliorer quelques trucs du forum. La joie de t'avoir connu surpasse la peine de t'avoir perdu… J'ai pour qualité de ne jamais attaquer les gens. J'ai pour défaut de souvent avoir l'air de le faire. Hors ligne Deevad Re : [Tuto] Configurer les bouttons Wacom sous Ubuntu/Debian avec Xsetwacom Bon, je donne quand même des nouvelles : en fait, ça marche bien, mais allez savoir pourquoi, pas par le nom. Je ne sais pas si c'est très normal que "Wacom Volito2 4x5" ne soit pas reconnu, mais en tout cas, cette version-là de xsetwacom reconnaît au moins "12" (l'identifiant chiffré indiqué sur la ligne renvoyée par xinput --list et indiquée ci-dessus). Maintenant, le problème est que cette config est perdue à chaque débranchement, donc je cherche encore, mais au moins, en voilà une bonne partie de résolu Cool, je pense que ton problème est résolu en grosse partie. Le fait de perdre la config à chaque débranchage est normal si tu tapes ça dans le terminal. Ici, j'ai 2 tablettes en ce moment, la A4 intuos 3 sur le bureau et la Bamboo Fun en déplacement ; j'ai mis dans mon gnome menu 2 raccourcis vers des scripts *.sh similaires à ceux posté au début du post. A chaque fois que je plug la tablette, je n'ai qu'a lancé le script par un ou dux clics dans mon menu. Ca reste assez ergonomique , et contrairement à la partition Vista, Ubuntu ne se mélange pas les drivers entre les deux tablettes Hors ligne
I have this problem. I'm creating an editor and I need console output(sys.stderr and sys.stdout) outputted to a textview. The problem is that when I start the console, it waits for it to quit, but I want it to catch anything and output it to the textview, so I thought that you might need different threads, but does it not then make it impossible to catch anything from the other thread? I want this in case the editor was not started from a terminal. It will be used as a module if you are wondering. This is the code so far: import sys import gtk import pygtk pygtk.require('2.0') class Console: def __init__(self): tv = gtk.TextView() tv.set_editable(False) tv.set_wrap_mode(gtk.WRAP_WORD) self.buffer = tv.get_buffer() table = gtk.Table(3, 6, gtk.FALSE) table.attach(tv, 0, 6, 0, 1) #### Main window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect('destroy_event', lambda w, e: gtk.mainquit()) self.window.connect('delete_event', lambda w, e: gtk.mainquit()) self.window.set_border_width(10) self.window.add(table) self.window.set_title('Search') self.window.set_default_size(300, 300) self.window.show_all() def main(self): gtk.main() c = Console() class ConsoleOutput: def __init__(self, source): self.source=source self.buf = [] def write(self, data): self.buf.append(data) if data.endswith('\n'): c.buffer.insert(c.buffer.get_end_iter(), ''.join(self.buf)) self.buf = [] def __del__(self): if self.buf != []: c.buffer.insert(c.buffer.get_end_iter(), ''.join(self.buf)) Thank you.
Topic: Sender throttling with Policyd on Debian Squeeze The standard IRedMail instructions for throttling contain errors (for Debian Squeeze) and are very unclear in places (to me at least). Here's how I got it working. I'm posting this as a way of giving back and I hope it helps others. Be warned that until you do the following, there is NO throttling. If a spammer gets hold of an account, they can, and will, blast away until your mail server is on every blacklist in existence. iRedMail version is 0.7.3. There are two files in /etc you need to be concerned with: postfix-policyd.conf and postfix-policyd_throttle.conf. The instructions wrongly refer to a postfix-policyd_sender_throttle.conf which doesn't exist. You could rename postfix-policyd_throttle.conf if you really want, but I'll assume you don't. Now edit postfix-policyd.conf (in /etc), and be sure the following are set as indicated. Most should already be set, but just in case. Warning: This is NOT the complete file! SENDERTHROTTLE=0 SENDER_THROTTLE_SASL=0 SENDER_THROTTLE_HOST=0 RECIPIENTTHROTTLE=1 Now edit postfix-policyd_throttle.conf (in /etc), and be sure the following are set as indicated. Most should already be set, but just in case they aren't, I've listed them. You are turning off almost everything because the other policyd config file will handle that. Warning: This is NOT the complete file! SENDERTHROTTLE=1 SENDER_THROTTLE_SASL=1 SENDER_THROTTLE_HOST=0 RECIPIENTTHROTTLE=0 WHITELISTING=0 #If 1, throttling won't work! BLACKLISTING=0 BLACKLIST_HELO=0 BLACKLISTSENDER=0 HELO_CHECK=0 SPAMTRAPPING=0 GREYLISTING=0 Create the file below as /etc/init.d/postfix-policyd_throttle. This is the complete file. #! /bin/sh ### BEGIN INIT INFO # Provides: postfix-policyd_throttle # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 ### END INIT INFO PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DAEMON=/usr/sbin/postfix-policyd CONFIG=/etc/postfix-policyd_throttle.conf PIDFILE='/var/run/policyd_throttle.pid' NAME=postfix-policyd_throttle DESC="Postfix throttling policy daemon" test -x $DAEMON || exit 0 # Include policyd defaults if available #if [ -f /etc/default/postfix-policyd ] ; then # . /etc/default/postfix-policyd #fi set -e PIDFILE=`grep "PIDFILE" $CONFIG | awk -F "=" '{print $2}' | awk '{print $1}'` case "$1" in start) echo -n "Starting $DESC: " start-stop-daemon --start --quiet --background --pidfile $PIDFILE --exec $DAEMON -- -c $CONFIG echo "$NAME." ;; stop) echo -n "Stopping $DESC: " start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON echo "$NAME." ;; reload|force-reload) echo -n "Reloading $DESC configuration: " start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --exec $DAEMON echo "$NAME." ;; restart) echo -n "Restarting $DESC: " start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON sleep 1 start-stop-daemon --start --quiet --background --pidfile $PIDFILE --exec $DAEMON -- -c $CONFIG echo "$NAME." ;; *) N=/etc/init.d/$NAME echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2 exit 1 ;; esac exit 0 Now set up and restart your policyd daemons by running the following commands: update-rc.d postfix-policyd_sender_throttle defaults /etc/init.d/postfix-policyd_sender_throttle restart /etc/init.d/postfix-policyd restart Now run the following command to see if everything is working right. You should get two lines of output, with the important parts shown below: netstat -ntlp | grep -i 1003tcp 0 0 127.0.0.1:10031 0.0.0.0:*tcp 0 0 127.0.0.1:10032 0.0.0.0:* Next, make one edit in /etc/postfix/main.cf. The following line should already be there, but commented out. Uncomment it. If it's not there, add it. smtpd_end_of_data_restrictions = check_policy_service inet:127.0.0.1:10032 Finally, force postfix to re-read your new configuration. postfix reload If it works, you'll find lines similar to the following in /var/log/mail.log. postfix-policyd: rcpt=81, throttle=update(a), host=127.0.0.1, from=robert@example.com, to=someone@spamtrap.net, size=1749/10240000, quota=30611/250000000, count=9/50(9), rcpt=9/3600(9), threshold=0%|16%|0% Setting individual quotas If you want to set an individual quota, you'll need to use some sql. IRedMail does come with phpmyadmin, which makes this much easier. This needs to entered in the postfixpolicyd database. A sample sql statement to set robert@example.com to 50 emails per hour would be: INSERT INTO throttle (_from,_count_max,_quota_max,_time_limit,_mail_size,_date,_priority) VALUES ('robert@example.com', # from address 50, # maximum messages per time unit 250000000, # size in bytes (250 megs) (maximum is 2gig) 3600, # time unit in seconds (1 day) 10240000, # maximum message size (10 meg) UNIX_TIMESTAMP(), # current time 10); # priority of record Based on some tests I ran, it seems the count is incremented by the number of recipients plus 1, at least for messages sent through roundcube. So if you compose a message to 3 people, your message count goes up by 4, not 3. If you compose to 1 person, your message count goes up by 2. Also, the time unit should really be read as in the last X seconds (I think; I'm not certain what time unit it uses for expiring old counts). For example, if my limit is 50 per hour (as above), and I send 10 messages at 1:00 PM, then 15 more at 1:10 PM (total count 25), at 2:01 PM, I can send 35 more (25 unsent, plus the first 10 have now expired). ---- Urgent issue? Pay iRedMail developer to solve it remotely at $39.
How can I dump a MySQL database without using mysqldump, just by using Python including table structure? I would advise MySQLdb - it provides a MySQL API for Python. However, most probably the API does an indirect call to You might also want to check out Dump tables and data where the exact procedure to dump the table structure and data (down the page) without MySQLdb is shown. I have solved this problem. import MySQLdb import os import datetime con = MySQLdb.connect(host='localhost', user='root', passwd='password', db='test') cur = con.cursor() cur.execute("SHOW TABLES") data = "" tables = [] for table in cur.fetchall(): tables.append(table[0]) for table in tables: data += "DROP TABLE IF EXISTS `" + str(table) + "`;" cur.execute("SHOW CREATE TABLE `" + str(table) + "`;") data += "\n" + str(cur.fetchone()[1]) + ";\n\n" cur.execute("SELECT * FROM `" + str(table) + "`;") for row in cur.fetchall(): data += "INSERT INTO `" + str(table) + "` VALUES(" first = True for field in row: if not first: data += ', ' data += '"' + str(field) + '"' first = False data += ");\n" data += "\n\n" now = datetime.datetime.now() filename = str(os.getenv("HOME")) + "/backup_" + now.strftime("%Y-%m-%d_%H:%M") + ".sql" FILE = open(filename,"w") FILE.writelines(data) FILE.close() Seem to work well from a little testing.
You could subtract 40 from the x-values for your second functions to make the range of x-values continuous. This would give you a range from 0% to 70%. Then you can make set the tics and labes of the x-axis as follows: x_ticks = range(71, 0, 10) a.set_xticks(x_ticks) a.set_xticklabels([str(x) for x in [0, 10, 20, 30, 70, 80, 90, 100]]) Where a is the current axes. So basically, you plot your functions in the range from 0% to 70%, but label the axis with a gap. To illustrate - the following script: from numpy import arange import matplotlib.pyplot as plt x1 = arange(0, 26) # first function y1 = x1**2 x2 = arange(75, 100) # second function y2 = x2*4 + 10 fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x1, y1) ax.plot(x2 - 40, y2) # shift second function 40 to left ax.set_xticks(range(0, 61, 5)) # set custom x-ticks # set labels for x-ticks - labels have the gap we want ax.set_xticklabels([str(x) for x in range(0, 26, 5) + range(70, 101, 5)]) plt.show() Produces the following plot (note the x-labels):
In Generating Graphics With Piddle we generated a gantt chart using piddle and the Python Imaging Library. Now we'll extend this concept to generate graphics in real time on the Web. We'll build on the code from the previous article, making references to it as we go along. Our original script contained a hardcoded data structure that controlled what tasks were displayed, so changing the image required changing the code. That approach works fine for creating images one at a time, but if we want our drawings to respond to input from our users, we'll have to separate the code and data. Python offers dozens of data storage options as well as a hugevariety of web modules, but to keep things simple, we'll stick to the basics:python's bundled shelve and cgimodules. With these tools in hand, we're ready to build an HTMLinterface for customizing our chart. We'll use a model-view-controller design pattern for our program. The model is the data stored in a shelf file. The view will show the rendered gantt chart and lists individual tasks. Each task will have a link to the controller page, to let us add, edit, and delete tasks. The following diagram illustrates this design: This translates to four files: view.cgichart.cgicontroller.cgimodel.shelf A shelf is basically a python dictionary stored on disk. Theshelve module uses pickle to convert objectsto and from strings, and stores those strings in Unix-style databasefiles via anydbm. But we don't have to worry about allthat. All we do is tell shelve where to store thedata. We'll prepopulate our shelf with some variables using the same data structures from last time. To set it up, we'll need some throwaway code. You can run the following as a script or just type it into the python interpreter interactively: import shelve # open the shelf (and create it if it's not there): s = shelve.open("model.shelf") s["now"]=3 s["titles"]=["apr","may","jun","jul","aug","sep"] s["tasks"]=[{"label":"a task", "boxes":[( 3, 10, "crimson"), (12, 13, "teal")]}] # save the data to disk and close the shelf s.close() You can verify that this worked by opening the shelf interactively and examining its contents: >>> import shelve >>> s = shelve.open("model.shelf") >>> s.keys() ['now', 'tasks', 'titles'] >>> s["now"] 3 We can now start coding a CGI script to use our data model. The CGI protocol defines how a web server and script communicate. The server defines some environment variables and makes data from the browser available to the script. The script responds with the type of the content it generates, the content itself, and any other information the browser needs. Python's cgi module takes care of the server side, butwe have to create a well-formed response ourselves. A simple examplelooks like this: #!/path/to/python print "content-type: text/html" print print "hello, world!" Note that every python CGI script must print at least a"content-type" header followed by a blank line, but not every scriptneeds the cgi module. We'll use cgi later,to examine form submissions on the controller page. To run the script above, you'll need to configure your web serverto handle CGI. On Unix-likesystems, this often only requires settingthe read and execute bits on your script. On some systems, CGI maywork only in certain directories (eg, cgi-bin). Consultyour server's documentation for specifics. With what we've learned and a little bit of HTML,view.cgi is easy: tasks;<img> tag to display the image (by setting the src attribute to chart.cgi); The script is mostly plain HTML or code we've already seen, except for the last item, displaying a link to edit each task. This requires a loop: # display the tasks as links: for row in range(len(tasks)): print '<li><a href="controller.cgi?action=edit&row=%i">%s</a>' \ % (row, tasks[row]["label"]) print ' [<a href="controller.cgi?action=delete&row=%i">delete<a>]</li>' \ % row Make sure that the web server has rights to read and writemodel.shelf, and load view.cgi in yourbrowser. If you run this cgi script now, you will see a broken imageand the list of tasks. Next we will work on the chart. To create the image, we'll use the original gannt chart code, with three major changes. The new version will now', 'tasks', and'titles' out of our shelf;content-type to image/jpeg; The first two changes are simple; the third is trickier. In theory,we'd just save the piddle canvas to sys.stdout, but thereare two problems with this approach. The first problem is that piddlePIL doesn't allowsaving images to file objects. Since it comes with full source,however, we can fix it ourselves. Search in piddlePIL.pyfor the save method. You'll see the problem. A couplelines down, there's a bit of code that says: if hasattr(file, 'write'): raise 'fileobj not implemented for piddlePIL' Replace that with the following: if hasattr(file, 'write'): self._image.save(file, format) return Now, displaying the image on the web is easy. Here's the code, fromthe bottom part of chart.cgi: print "content-type: image/jpeg" print import sys c.save(file=sys.stdout, format="jpeg") The second problem only happens under Windows: the output getscorrupted because stdout is not in binary mode bydefault. The fix is arcane, but concise: import os, sys if sys.platform=="win32": import msvcrt msvcrt.setmode(sys.__stdin__.fileno(), os.O_BINARY) msvcrt.setmode(sys.__stdout__.fileno(), os.O_BINARY) Place this before the content-type line and chart.cgishould have no problem displaying the image. The controller is in charge of managing our data. Essentially, it does four things: By default, controller.cgi shows the "add" form. Aparameter called action tells it to do something else. Wecan pass action, either as part of a query string (datafollowing the question mark in a URL) or via a form submission. Thecgi module can handle either method through theFieldStorage class. FieldStorage can betreated almost like a dictionary, although it doesn't implementevery dictionary method. For simple cases like this, it returns valuesas cgi.MiniFieldStorage objects. The following codeshows FieldStorage in action: import cgi request = cgi.FieldStorage() action = "add" # by default if request.has_key("action"): action = request["action"].value In controller.cgi, a set of if/elif blocks looks atthe action parameter and calls the appropriatefunction. In a sense, the controller is several CGI scripts rolledinto one. We could have broken these into separate files, but I preferto keep related logic together. Some of the available actions don't return a page to the browserbut, instead, redirect it to another page. In our case,saveTask and deleteTask both callbackToView, which returns a Location headerrather than a content type. The following line sends the browser backto the view page: print "Location: view.cgi" The rest of controller.cgi, including the code to saveand delete tasks, is pretty straightforward. Consult the source for details. That's it for this whirlwind tour of the gantt chart CGI application. To recap, we've seen how to store and retrieve data from a python shelf, communicate with the browser through CGI, and use piddlePIL to generate graphics in real time on the Web. Copyright © 2009 O'Reilly Media, Inc.
Python: List checking I am trying to write a Python (2.7.3) program that would check a list to see if a the value of a placing for a list has been given or not? input = raw_input("(Enter three numbers separated by commas) >: ") input_list = input.split(" ") replacing_letters = [str(x.strip(" ")) for x in input_list] 'if replacing_letters[2] is blank:' print"Incomplete" 'elif replacing_letters[2] is full': print replacing_letters So if I were to enter three numbers into an input, it would print the list to the user. But say I were to only input two numbers. It would return to the user 'Incomplete'. Any suggestions on a method or code to accomplish this?
How do I replicate the following Python code with the Python C API? class Sequence(): def __init__(self, max): self.max = max def data(self): i = 0 while i < self.max: yield i i += 1 So far, I have this: #include <Python/Python.h> #include <Python/structmember.h> /* Define a new object class, Sequence. */ typedef struct { PyObject_HEAD size_t max; } SequenceObject; /* Instance variables */ static PyMemberDef Sequence_members[] = { {"max", T_UINT, offsetof(SequenceObject, max), 0, NULL}, {NULL} /* Sentinel */ }; static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args, "k", &(self->max))) { return -1; } return 0; } static PyObject *Sequence_data(SequenceObject *self, PyObject *args); /* Methods */ static PyMethodDef Sequence_methods[] = { {"data", (PyCFunction)Sequence_data, METH_NOARGS, "sequence.data() -> iterator object\n" "Returns iterator of range [0, sequence.max)."}, {NULL} /* Sentinel */ }; /* Define new object type */ PyTypeObject Sequence_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "Sequence", /* tp_name */ sizeof(SequenceObject), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ "Test generator object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ Sequence_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Sequence_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static PyObject *Sequence_data(SequenceObject *self, PyObject *args) { /* Now what? */ } But I'm not sure where to go next. Could anyone offer some suggestions? Edit I suppose the main problem I'm having with this is simulating the yield statement. As I understand it, it is a pretty simple-looking, but in reality complex, statement — it creates a generator with its own __iter__() and next() methods which are called automatically. Searching through the docs, it seems to be associated with the PyGenObject; however, how to create a new instance of this object is unclear. PyGen_New() takes as its argument a PyFrameObject, the only reference to which I can find is PyEval_GetFrame(), which doesn't seem to be what I want (or am I mistaken?). Does anyone have any experience with this they can share? Further Edit I found this to be clearer when I (essentially) expanded what Python was doing behind the scenes: class IterObject(): def __init__(self, max): self.max = max def __iter__(self): self.i = 0 return self def next(self): if self.i >= self.max: raise StopIteration self.i += 1 return self.i class Sequence(): def __init__(self, max): self.max = max def data(self): return IterObject(self.max) Technically the sequence is off by one but you get the idea. The only problem with this is it's very annoying to create a new object every time one needs a generator — even more so in Python than C because of the required monstrosity that comes with defining a new type. And there can be no yield statement in C because C has no closures. What I did instead (since I couldn't find it in the Python API — please point me to a standard object if it already exists!) was create a simple, generic generator object class that called back a C function for every next() method call. Here it is (note that I have not yet tried compiling this because it is not complete — see below): #include <Python/Python.h> #include <Python/structmember.h> #include <stdlib.h> /* A convenient, generic generator object. */ typedef PyObject *(*callback)(PyObject *callee, void *info) PyGeneratorCallback; typedef struct { PyObject HEAD PyGeneratorCallback callback; PyObject *callee; void *callbackInfo; /* info to be passed along to callback function. */ bool freeInfo; /* true if |callbackInfo| should be free'()d when object * dealloc's, false if not. */ } GeneratorObject; static PyObject *Generator_iter(PyObject *self, PyObject *args) { Py_INCREF(self); return self; } static PyObject *Generator_next(PyObject *self, PyObject *args) { return self->callback(self->callee, self->callbackInfo); } static PyMethodDef Generator_methods[] = { {"__iter__", (PyCFunction)Generator_iter, METH_NOARGS, NULL}, {"next", (PyCFunction)Generator_next, METH_NOARGS, NULL}, {NULL} /* Sentinel */ }; static void Generator_dealloc(GenericEventObject *self) { if (self->freeInfo && self->callbackInfo != NULL) { free(self->callbackInfo); } self->ob_type->tp_free((PyObject *)self); } PyTypeObject Generator_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "Generator", /* tp_name */ sizeof(GeneratorObject), /* tp_basicsize */ 0, /* tp_itemsize */ Generator_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* Returns a new generator object with the given callback function * and arguments. */ PyObject *Generator_New(PyObject *callee, void *info, bool freeInfo, PyGeneratorCallback callback) { GeneratorObject *generator = (GeneratorObject *)_PyObject_New(&Generator_Type); if (generator == NULL) return NULL; generator->callee = callee; generator->info = info; generator->callback = callback; self->freeInfo = freeInfo; return (PyObject *)generator; } /* End of Generator definition. */ /* Define a new object class, Sequence. */ typedef struct { PyObject_HEAD size_t max; } SequenceObject; /* Instance variables */ static PyMemberDef Sequence_members[] = { {"max", T_UINT, offsetof(SequenceObject, max), 0, NULL}, {NULL} /* Sentinel */ } static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args, "k", &self->max)) { return -1; } return 0; } static PyObject *Sequence_data(SequenceObject *self, PyObject *args); /* Methods */ static PyMethodDef Sequence_methods[] = { {"data", (PyCFunction)Sequence_data, METH_NOARGS, "sequence.data() -> iterator object\n" "Returns generator of range [0, sequence.max)."}, {NULL} /* Sentinel */ }; /* Define new object type */ PyTypeObject Sequence_Type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "Sequence", /* tp_name */ sizeof(SequenceObject), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/ "Test generator object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ Sequence_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Sequence_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static PyObject *Sequence_data(SequenceObject *self, PyObject *args) { size_t *info = malloc(sizeof(size_t)); if (info == NULL) return NULL; *info = 0; /* |info| will be free'()d by the returned generator object. */ GeneratorObject *ret = Generator_New(self, info, true, &Sequence_data_next_callback); if (ret == NULL) { free(info); /* Watch out for memory leaks! */ } return ret; } PyObject *Sequence_data_next_callback(PyObject *self, void *info) { size_t i = info; if (i > self->max) { return NULL; /* TODO: How do I raise StopIteration here? I can't seem to find * a standard exception. */ } else { return Py_BuildValue("k", i++); } } However, unfortunately, I'm still not finished. The only question I have left is: How do I raise a StopIteration exception with the C API? I can't seem to find it listed in the Standard Exceptions. Also, perhaps more importantly, is this the correct way to approach this problem? Thanks to anyone that's still following this.
We have a question we ask at our office during interviews that goes like this. For the sake of consistency, I am restricting the context of this to python. I'm sure there are other answers but I'm really only interested in python answers. Write me a function named say that when called like this: >>> say('Hello')('World') It ONLY Prints (not returns): >>> say('Hello')('World') Hello World >>> We got into a meta discussion after the interview today where I stated that I am always hoping the applicant will answer with the following. def say(x): print "Hello World" return lambda a:None I realized that there is a possibility of shortening this further by replacing the lambda function with a built in of some sort that returns None but I've dug and can't seem to find one that is shorter than lambda a:None So the overall question here is... Can you think of a way to make this shorter, as in less overall characters (ignoring line breaks). Any import statements are counted in your character count. (52 Characters) UPDATE (39 Characters) >>> def p(x): ... print "Hello",x >>> say=lambda x:p >>> say("Hello")("World") Hello World >>> Python 3 Answer (48 Characters) >>> def say(x): ... return lambda a:print("Hello World") >>> say("Hello")("World") Hello World >>>
goyou [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Bonjour, Pour quelqu'un qui a déjà installé numpy sur son pc, l'idée est de pouvoir invoquer un terminal qui charge python et qui charge numpy automatiquement pour s'en servir comme d'une calculatrice. C'est-à-dire qu'on obtient une fenetre en ligne de commande dans laquelle les fonctions telles que exp() sin() log() sont préchargées. En fait je l'ai déjà fait, il m'a fallu créer les trois fichiers suivants : #### /calcupy.sh python -i /calcupy.py #### /calcupy.py from numpy import * print 'Numpy loaded' #### /usr/share/applications/calcupy.desktop [Desktop Entry] Type=Application Encoding=UTF-8 Name=Calcul Numpy GenericName=calcupy Comment=Calculatrice python en terminal Icon=accessories-calculator Exec=sh /calcupy.sh Terminal=true StartupNotify=true Categories=Sciences Path=~ Et cela me crée une nouvelle entrée dans la liste des applications (Le menu Sciences n'existant pas, celle-ci est apparue dans Autres). et j'obtiens une fenêtre nommée "sh" dans laquelle apparait : Numpy loaded >>> et je peux taper : exp(1) ce qui affiche 2.71828... Alors je suis content ! et j'espère que ça pourra servir à quelqu'un. Mais je me pose encore deux questions : Est-il possible de faire ça en créant seulement un ou deux fichier(s) ? Est-il possible de changer le nom de la fenetre : écrire "Calcul numpy" ou "Numpy" au lieu de "sh" ? Dernière modification par goyou (Le 23/01/2013, à 15:05) Hors ligne Maisondouf Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Déjà ça serait bien de mettre tes fichiers python ailleurs que sur la racine du système.... Ensuite pour lancer un terminal qui lance python qui lance numpy, tout ça se fait dans le lanceur "/usr/share/applications/calcupy.desktop" que tu as crée. Remplace ta ligne exec par ça: gnome-terminal -t Numpy -e "python -i /<quelque-part>/calcupy.py" ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½ Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains.... "the secret of my form is summed up in two words, no sport" (Winston Churchill) Hors ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Pour simplifier encore : Remplace ta ligne exec par ça: gnome-terminal -t Numpy -e "python -ic \"from numpy import *; print 'Numpy loaded'\"" ...et passe "Terminal=true" à "Terminal=false" (sinon il va utiliser un terminal pour te lancer gnome-terminal, ce qui est plutôt con (et là tu peux supprimer calcupy.sh et calcupy.py). PS: pourquoi n'utilises-tu pas bc ? $ bc -l bc 1.06.95 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. e(1) 2.71828182845904523536 4^3 64 (45+66)*2^14+e(18) 67478593.13733051113878650325 Dernière modification par tiramiseb (Le 23/01/2013, à 11:59) En ligne goyou Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Merci beaucoup pour vos réponses, je ne suis pas sous gnome mais je vois le truc. J'essaie de lancer la commande suivante : terminal --title=Numpy -e "python -i -c "from numpy import *; print 'Numpy loaded' " " Le problème, c'est qu'il y a deux guillemets d'ouverture mais le système prend le deuxième guillemet comme fermeture du premier, et j'obtiens un message d'erreur : "numpy : option inconnue". Par contre j'obtiens bien python et numpy chargés en ouvrant un terminal et en tapant : python -i -c "from numpy import *; print 'Numpy loaded' " ou j'obtiens bien un terminal avec "Numpy" en titre et python chargé en tapant : terminal --title=Numpy -e "python -i" Mais je ne peux toujours pas avoir Terminal+python+numpy en même temps, à cause du problème des guillemets Donc je peux passer de trois à deux fichiers, si je pouvais résoudre le problème des guillemets je pourrais effectivement passer à un seul fichier. Utiliser bc pourquoi pas, mon idée était cependant que j'utilise déjà numpy à la base alors pourquoi installer des trucs en plus si je peux me démerder en faisant simplement une ligne de commande en script. Et puis c'est toujours intéressant pour l'utilisation des scripts, si je réussis a faire ça ça pourra me servir à autre chose plus tard, ou peut-être même à un lecteur du topic ! Hors ligne Maisondouf Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Essayes ça, sans garantie.... gnome-terminal --title=Numpy -e "python -i -c \"from numpy import *; print 'Numpy loaded' \" " ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½ Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains.... "the secret of my form is summed up in two words, no sport" (Winston Churchill) Hors ligne pingouinux Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Bonjour, Ta commande en #4 est différente de celle que te propose tiramiseb en #3. Il manque des \ devant des ". Hors ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Le problème, c'est qu'il y a deux guillemets d'ouverture mais le système prend le deuxième guillemet comme fermeture du premier, et j'obtiens un message d'erreur : "numpy : option inconnue". Tu n'as pas mis les backslashes que j'ai placés pour échapper les guillemets de la commande python... gnome-terminal --title=Numpy -e "python -i -c \"from numpy import *; print 'Numpy loaded' \"" (désolé je n'ai pas mis les balises "code", c'est pour pouvoir mettre en gras et rouge...) Dernière modification par tiramiseb (Le 23/01/2013, à 14:40) En ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Ou alors tu peux faire la chose suivante : gnome-terminal --title=Numpy -e "python -ic 'from numpy import *'" En ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] pingouinux: Mais t'es chiant ! Même dans mes conversations à moi tu réponds plus vite que moi ! Maisondouf : toi aussi t'es chiant d'ailleurs. Moi j'vais aller bouder. Na ! (bon en vrai je vais surtout un peu travailler...) Dernière modification par tiramiseb (Le 23/01/2013, à 14:43) En ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Utiliser bc pourquoi pas, mon idée était cependant que j'utilise déjà numpy à la base alors pourquoi installer des trucs en plus bc n'est pas un "truc en plus". Ce logiciel installé par défaut sur Ubuntu. En ligne pingouinux Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] @tiramiseb #9 : Je suis désolé Hors ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] En vrai t'es même pas désolé j'suis sûr En ligne goyou Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Owkèy !! ça marche comme ceci : gnome-terminal --title=Numpy -e "python -i -c \"from numpy import *; print 'Numpy loaded' \"" (je peux remplacer gnome-terminal par terminal si je ne suis pas sous gnome) C'est grâce aux backslashes que l'on résout le problème des guillemets !! Donc en résumé, pour créer l'application je crée simplement le fichier suivant : /usr/share/applications/calcupy.desktop [Desktop Entry] Type=Application Encoding=UTF-8 Name=Calcul Numpy GenericName=calcupy Comment=Calculatrice python en terminal Icon=accessories-calculator Exec=gnome-terminal --title=Numpy -e "python -i -c \"from numpy import *; print 'Numpy loaded' \"" Terminal=false StartupNotify=true Categories=Sciences Path=~ Merci beaucoup je suis impressionné par la rapidité et l'exactitude de vos réponses. La petite dernière question subsidiaire : à quoi sert StartupNotify=true|false ? Hors ligne tiramiseb Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] (je peux remplacer gnome-terminal par terminal si je ne suis pas sous gnome) Il faut le remplacer par la commande pour lancer un terminal. Sous GNOME et Unity c'est gnome-terminal, sous KDE c'est konsole, sous XFce c'est xfce4-terminal... Mais je n'en connais pas qui se lance avec la commande "terminal" tout court. La petite dernière question subsidiaire : à quoi sert StartupNotify=true|false ? C'est notamment pour faire apparaître le curseur de chargement au lieu du curseur classique. http://developer.gnome.org/integration- … on.html.en En ligne goyou Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] "terminal" c'est sur openSuse. Mais je suis sur xfce en vrai donc j'ai mis xfce4-terminal. Finalement le programme fonctionne parfaitement lorsque je l'appelle depuis le menu des applications mais ne se lance pas en l'appelant depuis synapse. Hors ligne goyou Re : [Astuce] Calculatrice Numpy dans Python dans un Terminal [Résolu] Aujourd'hui j'ai fait une petite mise à jour : gnome-terminal --title=Numpy -e "python -i -c \"from numpy import *; from math import *; print 'Numpy and math loaded' \"" pour avoir des fonctions en plus, en particulier erfc(x) et assimilées. J'ai aussi mis cette ligne de commande en raccourci clavier (super+C). Hors ligne
Using gensim I was able to extract topics from a set of documents in LSA but how do I access the topics generated from the LDA models? When printing the lda.print_topics(10) the code gave the following error because print_topics() return a NoneType: Traceback (most recent call last): File "/home/alvas/workspace/XLINGTOP/xlingtop.py", line 93, in <module> for top in lda.print_topics(2): TypeError: 'NoneType' object is not iterable The code: from gensim import corpora, models, similarities from gensim.models import hdpmodel, ldamodel from itertools import izip documents = ["Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", "Graph minors A survey"] # remove common words and tokenize stoplist = set('for a of the and to in'.split()) texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents] # remove words that appear only once all_tokens = sum(texts, []) tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1) texts = [[word for word in text if word not in tokens_once] for text in texts] dictionary = corpora.Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts] # I can print out the topics for LSA lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2) corpus_lsi = lsi[corpus] for l,t in izip(corpus_lsi,corpus): print l,"#",t print for top in lsi.print_topics(2): print top # I can print out the documents and which is the most probable topics for each doc. lda = ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=50) corpus_lda = lda[corpus] for l,t in izip(corpus_lda,corpus): print l,"#",t print # But I am unable to print out the topics, how should i do it? for top in lda.print_topics(10): print top
This question already has an answer here: There are many posts about finding the difference between two dates but the values involved start and end with different formatting than those I am using eg: a = 01/01/10 # dd/mm/yy format b = 01/01/05 # dd/mm/yy format So I am after the difference in years, months and days between a and b where the output required is in the format x years, x months, x days (if required) format. I'm reading the datetime documentation and have had a crack at figuring it out (note: admittedly newbie code ahead, i was trying to piece together all the demo's there so had to make a few modifications): from datetime import datetime as dt # calculate duration between two dates # later date later_date = '01/01/10'.replace('/', '') # reverse the order later_date = "".join(reversed([later_datet[i:i+2] for i in range(0, len(later_date), 2)])) # separate with commas every two numbers later_date = ','.join(later_date[i:i+2] for i in range(0, len(later_date), 2)) # convert to datetime object later_date = dt.strptime(later_date, "%y,%m,%d") # earlier date earlier_date = '01/01/05'.replace('/','') # reverse the order earlier_date = "".join(reversed([earlier_date[i:i+2] for i in range(0, len(earlier_date), 2)])) # separate with commas every two numbers earlier_date = ','.join(earlier_date[i:i+2] for i in range(0, len(earlier_date), 2)) # convert to datetime object earlier_date = dt.strptime(earlier_date, "%y,%m,%d") duration = later date - earlier_date print duration print type(duration) is outputting: 1826 days, 0:00:00<type 'datetime.timedelta'> So I think i am somewhat close to getting the correct data, but now i need to convert it into the x years, x months, x days (if required) format. Edit/Solution: I have put some code together and am testing now, I think it is working for all date combinations but if anyone notices a bug please let me know: """ this code calculates the duration between two dates (a later and earlier date) in the format dd/mm/yy and returns the duration in years, months and days with correct formatting in regards to the plurality of the year/s, month/s, and day/s and the punctuation required dependent on whether one or more values are returned ie multiple values are separated by ',' whereas a singular value is terminated by '.'. """ # imported libraries from datetime import datetime as dt from dateutil import relativedelta import sys # initial date objects later_date = '01/01/10' earlier_date = '01/01/05' # convert dates to required format a_date = dt.strptime(later_date, '%d/%m/%y') b_date = dt.strptime(earlier_date, '%d/%m/%y') # get duration using dateutil duration = relativedelta.relativedelta(a_date, b_date) # check if number of years is not false ie != 0 if duration.years != 0: years = duration.years else: years = False # check if number of months is not false ie != 0 if duration.months != 0: months = duration.months else: months = False # check if number of days is not false ie != 0 if duration.days != 0: days = duration.days else: days = False # add values to a list date_list = [years,months,days] # count instances of False in the list false_count = date_list.count(False) # iterate over list with enumeration performing value and # boolean checking to predicate plurality and punctuality # requirements. for n, _ in enumerate(date_list): # year/s - single or plural, lone value or more if _ != False and n == 0: single_year = date_list[0] == 1 # if single and not lone if single_year == True and false_count != 2: sys.stdout.write(str(_)+' year, ') # if single and lone elif single_year == True and false_count == 2: sys.stdout.write(str(_)+' year.') # if not single and not lone elif single_year == False and false_count != 2: sys.stdout.write(str(_)+' years, ') # if not single but lone elif single_year == False and false_count == 2: sys.stdout.write(str(_)+' years.') # if there are no years, still provide value for possible later concatenation if _ == False and n == 0: datasetduration_y = '' # month/s - single or plural, lone value or more if _ != False and n == 1: single_month = date_list[1] == 1 # if single and not lone if single_month == True and false_count != 2: sys.stdout.write(str(_)+' month, ') # if single and lone elif single_month == True and false_count == 2: sys.stdout.write(str(_)+' month.') # if not single and not lone and there are days elif single_month == False and false_count != 2 and date_list[2] != False: sys.stdout.write(str(_)+' months, ') # if not single and not lone and there are no days elif single_month == False and false_count != 2 and date_list[2] == False: sys.stdout.write(str(_)+' months.') # if not single but lone elif single_month == False and false_count == 2: sys.stdout.write(str(_)+' months.') # if there are no months, still provide value for possible later concatenation if _ == False and n == 1: datasetduration_m = '' # day/s - single or plural, lone value or more if _ != False and n == 2: single_day = date_list[2] == 1 # if single and not lone if single_day == True and false_count != 2: sys.stdout.write(str(_)+' day.') # if single and lone elif single_day == True and false_count == 2: sys.stdout.write(str(_)+' day.') # if not single and not lone elif single_day == False and false_count != 2: sys.stdout.write(str(_)+' days.') # if not single but lone elif single_day == False and false_count == 2: sys.stdout.write(str(_)+' days.') # if there are no days, still provide value for possible later concatenation if _ == False and n == 2: datasetduration_d = ''
tshirtman Re : /* Topic des codeurs [8] */ @le rouge: non, j'ai ouvert le code pour regarder l'option pour avoir un fichier wiki, hier, j'ai vu du rouge , j'ai commencé a corriger des trucs, puis j'ai été distrait, j'y suis pas retourné encore :] mais j'y pense ^^ Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ Oké. Vas-y mollo sur les corrections, je pense que je vais réécrire pas mal de trucs sous peu (notamment la gestion des multiples formats). En gros, pour tester le format wiki, il faut lancer ça dans le dossier qui vous intéresse, meuporg -t wiki mettre des items (c'est-à-dire des !TRUCS!) où vous voulez puis lancer meuporg -u et c'est tout. Après, toute contribution plus substantielle est évidemment la bienvenue ^^ @ tshirtman (justement) : je compte faire des « classes » (namespace plutôt) associé à chaque format. Pour chaque format, ils implémenteraient les fonctions suivantes. get_name() """Returns the name of the format.""" line_to_header(line) """Returns False if the line does not correspond to a header and a list containing [depth, title] otherwise.""" header_to_string(depth,title) """Returns a string containing a header with the given title and depth.""" item_to_string(item) """Returns the string containing the data in the item corresponding to this format.""" list_to_string(items) """Returns a string containing the data in each of the item in the item list items.""" L'usage de la première fonction est assez évident. La deuxième serait utile pour parser ; les trois dernières pour écrire les données qu'on veut au bon format. Ce serait bien plus propre et ça permettrait de ne pas être limité aux formats très « orientés texte » (markdown, org, vimwiki). Par exemple, faire des fichiers html serait d'un coup beaucoup plus simple. Qu'est-ce que tu en penses ? Dernière modification par Le Rouge (Le 16/01/2013, à 13:16) Hors ligne grim7reaper Re : /* Topic des codeurs [8] */ Après, toute contribution plus substantielle est évidemment la bienvenue ^^ Bon, j’ai pas tout regardé en détail mais voilà quelques remarques après un rapide survol. Remarques générales : - les parenthèses autour des if c’est pas très Pythonnique. - les import * c’est craignos, ça pollue le namespace et ça peut gêner le refactoring (on est obliger de lire tout le code pour savoir ce que tu utilises vraiment). - remplace dès que possible les couples open/close par la syntaxe with, c’est plus sûre. Sinon, tu devrais passer un coup de pylint sur ton code, ça devrait te donner des indications pour le rendre lisible (c’est pas illisible en l’état hein, juste pas très PEP8) Point de vue design, je trouve pas ça top de mixer configuration et fichier meuporg.MD (ou meup.org), ça t’empêche d’avoir un vrai fichier de conf’ (pas gênant pour le moment, mais si les options venaient à se multiplier tu pourrais avoir à la regretter) Genre , pour rester dans le lisible et facilement éditable à la main, un fichier type INI (et pas besoin de réinventer la roue carrée pour le parser, le module configparser est ton ami). Bon, maintenant, allons y au cas par cas Dans view.py Pour la fonction sort_by_name, tu y gagnerais à utiliser defaultdict. Tu pourrais donc écrire : from collections import defaultdict def sort_by_name(item_list): """Turns a list into a dictionnary where items are sorted by their names. """ result = defaultdict(list) for item in item_list: result[item.name].append(item) return result Je trouve ça plus clair. Dans file_types.py Point de vue design, perso pour gérer les différents formats de sortie je partirais sur le design pattern Factory, ça me semble plus propre et souple. Dans __main__.py Pitié, tu m’as tué là . Sérieusement, getopt… on se croirait de retour en C (même le C++ à un truc mieux foutu, via Boost). je serais toi je passerais par le module argparse. En plus ça va te faire le message d’aide tout seul Dans meuporg.py.py La fonction read_header semble être une copie conforme de la fonction read_header de update.pyread_header de update.py. même remarque pour la fonction update_main_file (bien que là, j’en suis moins sûr car je n’ai pas lu ligne à ligne, mais même si elle sont pas identique elles sont suffisament similaire pour qu’un refactoring soit possible et sûrement souhaitable (la duplication de code c’est jamais bon)). La fin du fichier semble plus ou moins être une copie du fichier __main__.py Bon voilà, y’aurait peut-être encore des choses à dire ou des choses améliorables, mais c’est un premier jet de remarques. Sinon, pour tes histoires de gestion de formats de sortie, je te conseillerais le design pattern Factory (comme mentionné plus haut). C’est un truc du genre (pas tout à fait ça, un truc adapté car code en C mais dans l’esprit ça y est) que j’ai soumis par patch à Rolinh pour dfc et je pense pas qu’il regrette ). @Rolinh : http://projects.gw-computing.net/projec … acker_id=1 me renvoie une erreur 502 (ainsi que 2-3 autres pages), ça vient de moi ou tu as un truc de cassé de ton côté ? Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ Wow, merci pour les idées ! Je vais y jeter un œil de plus près demain, là je suis mort. Je connaissais pas le pattern design "factory" en tant que tel mais j'en avais fait un genre d'implémentation du pauvre avec les classes que j'ai décrites plus haut (je comptais remplacer la liste renvoyée par file_format.formats() par un dictionnaire ou les clefs sont les noms des formats). Enfin bref, je vais arranger tout ça ce WE. Ce code était un prototype pour voir si le concept était utile (il s'avère l'être beaucoup, du moins pour moi) ; je vais donc rendre ça plus lisible/propre. J'ai aussi des idées de fonctionnalités pour le minor-mode mais je vais en baver pour l'implémentation ^^ Bref, merci bien camarade ! Hors ligne Rolinh Re : /* Topic des codeurs [8] */ @Rolinh : http://projects.gw-computing.net/projec … acker_id=1 me renvoie une erreur 502 (ainsi que 2-3 autres pages), ça vient de moi ou tu as un truc de cassé de ton côté ? C'est cassé de mon côté. :-( En plus, je suis à blâmer car ça a péter lors de la dernière mise-à-jour de chiliproject qui ne devait être qu'une mise-à-jour de sécurité et bien sûr, je l'ai appliquée sans faire un dump de ma DB avant... Il faut que je vois si je peux revenir en arrière dans ma migration mais j'ai un peu peu que ce soit bien cassé là Blog "If you put a Unix shell to your ear, do you hear the C ?" Hors ligne Blabla404 Re : /* Topic des codeurs [8] */ Sinon, tu devrais passer un coup de pylintsur ton code, ça devrait te donner des indications pour le rendre lisible (c’est pas illisible en l’état hein, juste pas très PEP8) Je ne connaissais pas pylint (bon la PEP8 non plus), j'ai des scores négatifs sur presque tous mes codes. Bon je vais lire la doc pour voir précisement ce que ça veut dire, mais ça ne me parait pas très encourageant. Hors ligne Mindiell Re : /* Topic des codeurs [8] */ Ce n'est pas très dur, c'est juste un moyen simple de structurer son code afin que d'autres développeurs puissent, plus facilement, relire ton code. Hors ligne Jules Petibidon Re : /* Topic des codeurs [8] */ Faut aussi considérer que PyLint n'est qu'un indicateur et pas obligatoirement courir après des "notes" parfaites dans tous les cas. D'autant qu'il a quelques lacunes qui lui font invalider du code parfaitement valide. Hors ligne Blabla404 Re : /* Topic des codeurs [8] */ Sans chercher à faire la note parfaite, c'est quand même bon de savoir qu'il y a une norme et essayer de la respecter un minimum. En tout cas il sort aussi des warning c'est assez pratique. En revanche il ne comprend pas la syntaxe print(res, end=' ') Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ J'ai aussi des idées de fonctionnalités pour le minor-mode mais je vais en baver pour l'implémentation ^^ Carrément pas en fait, il y avait déjà une fonction qui faisait pratiquement ce que je voulais (en l'occurrence "occur"). emacs <3 Hors ligne grim7reaper Re : /* Topic des codeurs [8] */ Faut aussi considérer que PyLint n'est qu'un indicateur et pas obligatoirement courir après des "notes" parfaites dans tous les cas. D'autant qu'il a quelques lacunes qui lui font invalider du code parfaitement valide. Évidemment. Aucun outil ne peut juger ton code à 100%, cela dit ça reste un très bon indicateur (même si certains trucs sont aberrant, mais Pylint à l‘avantage d’être très configurable). Sans chercher à faire la note parfaite, c'est quand même bon de savoir qu'il y a une norme et essayer de la respecter un minimum. Exactement, c’est de là où je voulais en venir. En revanche il ne comprend pas la syntaxe print(res, end=' ') C’est un des gros défaut de pylint, il chie encore sur des trucs Python 3. En fait, non. Pylint supporte bien Python 3 s’il est en Python 3 : Actually you need the python3 version of pylint in order to analyze python3 code (otherwise, pylint reports tons of syntax errors for non-2 syntax) ... so there'd be a _huge_ benefit from having a py3-version in portage! Le problème c’est qu‘il me semble qu’Ubuntu ne propose que la version Python 2… (Arch’ propose les deux dans mon souvenir). Hors ligne Shanx Re : /* Topic des codeurs [8] */ Je tente de me mettre à vimwiki pour pouvoir prendre des notes et m’organiser un peu. Mais je ne trouve pas le wiki très complet. Quelqu’un a un meilleur lien (ou peu me renseigner sur comment transformer vimwiki pour le rendre plus efficace). « En vérité, je ne voyage pas, moi, pour atteindre un endroit précis, mais pour marcher : simple plaisir de voyager. » R. L. Stevenson -- Blog et randos Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ En fait, vim supporte aussi la syntaxe de l'org-mode d'emacs ; ça peut aussi être une piste à creuser. Hors ligne Shanx Re : /* Topic des codeurs [8] */ J’ai vite fait jeté un œil à org-mode, ça m’a l’air d’être ce que je recherche (y’a même la gestion des échéance, c’est cool). Mais bon, je ne maîtrise absolument pas emacs (j’utilise vim), donc bon, la prise en main attendra la fin des partiels. « En vérité, je ne voyage pas, moi, pour atteindre un endroit précis, mais pour marcher : simple plaisir de voyager. » R. L. Stevenson -- Blog et randos Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ Emacs c'est pas vim hein, ça se prend en main en 15min. Après, au niveau raffinement, tu peux y passer des années :3 Hors ligne Blabla404 Re : /* Topic des codeurs [8] */ C’est un des gros défaut de pylint, il chie encore sur des trucs Python 3. En fait, non. Pylint supporte bien Python 3 s’il est en Python 3 : Je n'avais pas fait attention, je l'ai installé via pip, qui utilisait Python2.7.2. J'ai donc tout mis à jour vers Python3.3 mais maintenant pylint ne fonctionne pas. C'est un bug connu qui n'a pas l'air d'avoir de solution évidente pour le moment. Bon de toute façon pour le moment je n'utilise Python3 que pour rosalind, donc je vais garder le pylint pur python2. C'est pas très pratique d'avoir deux versions qui coexistent quand même. Hors ligne grim7reaper Re : /* Topic des codeurs [8] */ J'ai donc tout mis à jour vers Python3.3 mais maintenant pylint ne fonctionne pas. C'est un bug connu qui n'a pas l'air d'avoir de solution évidente pour le moment. Du genre ? Parce que chezmoiçamarche © (bon, pas testé avec Python 3.3 mais avec Python 3.2.3 car Ubuntu, mais ça doit pas changer grand-chose). Comment tu as mis à jour ? Dernière modification par grim7reaper (Le 19/01/2013, à 06:09) Hors ligne Mindiell Re : /* Topic des codeurs [8] */ C'est pas très pratique d'avoir deux versions qui coexistent quand même. Chanceux oui ! J'ai ça moi : 2.6.5, 2.7.3, 3.1, 3.3 Je m'en sors plus entre les pip et les easy_install Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ Bon, refactoring : check. Plus qu'à réécrire le __main__.py en utilisant argparse. edit : Ayé, sauf que je peux pas pusher sur mon github pour cause de connexion en papier mâché >_<" edit 2 : vu que je suis bonne pâte, je vous mets ce que renvoie la commande sans option (merci argparse) : $ meuporg usage: .meuporg [-h] [-v] [-b] [-d] [-f] [-e TO_EXCLUDE] [-i TO_INCLUDE] [-t TEMPLATE_STYLE] [-o PARSE_AND_SHOW_ORG] [-m PARSE_AND_SHOW_MD] [-w PARSE_AND_SHOW_VIMWIKI] [-u] Parse files/directories to find items and either print them or use them to update a file where information is centralised. optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -b (Backup file): include backup files (file~ and #file#); default behaviour is not to. -d (Dot file): include hidden files and folders (starting with '.'), default behaviour is not to. -f (main File): Returns the path to the main file of the directory (if any). -e TO_EXCLUDE (Exclude): Decides which file pattern(s) to exclude from the search. Repeat to specify several regex to exclude. Default behaviour is to exclude no file (but the backup and hidden ones). -i TO_INCLUDE (Include): Decides which file pattern(s) to include in the search. Repeat to specify several regex to include. Default behaviour is to include every file (but the backup and hidden ones). -t TEMPLATE_STYLE (Template) <format>: <format> has to be either 'md', 'vimwiki' or 'org'. Creates a new meuporg main file in the said format. -o PARSE_AND_SHOW_ORG (Org): outputs the list of items in the given path or folder in org-mode format. -m PARSE_AND_SHOW_MD (Md): outputs the list of items in the given path or folder in markdown. -w PARSE_AND_SHOW_VIMWIKI (vimWiki): outputs the list of items in the given path or folder in vimwiki format. -u (Update): Updates the main file ruling this directory (it might be in the parent directories). Meuporg is intended to help you manage your projects. If you have any suggestions or find a bug, send a mail at leoperrin at picarresurix dot fr. I'll see what I can do. Dernière modification par Le Rouge (Le 19/01/2013, à 22:18) Hors ligne Blabla404 Re : /* Topic des codeurs [8] */ Du genre ? Parce quechezmoiçamarche© (bon, pas testé avec Python 3.3 mais avec Python 3.2.3 car Ubuntu, mais ça doit pas changer grand-chose). Comment tu as mis à jour ? Voilà ce que j'obtiens pip-3.3 install pylint Downloading/unpacking pylint Downloading pylint-0.26.0.tar.gz (222kB): 222kB downloaded Running setup.py egg_info for package pylint warning: no files found matching '*.html' under directory 'doc' warning: no files found matching '*.txt2' under directory 'test' warning: no files found matching 'noext' Requirement already satisfied (use --upgrade to upgrade): logilab-common>=0.53.0 in /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages (from pylint) Requirement already satisfied (use --upgrade to upgrade): logilab-astng>=0.21.1 in /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages (from pylint) Installing collected packages: pylint Running setup.py install for pylint Skipping implicit fixer: buffer Skipping implicit fixer: idioms Skipping implicit fixer: set_literal Skipping implicit fixer: ws_comma changing mode of build/scripts-3.3/pylint from 644 to 755 changing mode of build/scripts-3.3/pylint-gui from 644 to 755 changing mode of build/scripts-3.3/symilar from 644 to 755 changing mode of build/scripts-3.3/epylint from 644 to 755 changing mode of build/scripts-3.3/pyreverse from 644 to 755 warning: no files found matching '*.html' under directory 'doc' warning: no files found matching '*.txt2' under directory 'test' warning: no files found matching 'noext' changing mode of /Library/Frameworks/Python.framework/Versions/3.3/bin/epylint to 755 changing mode of /Library/Frameworks/Python.framework/Versions/3.3/bin/pylint to 755 changing mode of /Library/Frameworks/Python.framework/Versions/3.3/bin/pylint-gui to 755 changing mode of /Library/Frameworks/Python.framework/Versions/3.3/bin/pyreverse to 755 changing mode of /Library/Frameworks/Python.framework/Versions/3.3/bin/symilar to 755 Installing epylint script to /Library/Frameworks/Python.framework/Versions/3.3/bin Installing symilar script to /Library/Frameworks/Python.framework/Versions/3.3/bin Installing pylint-gui script to /Library/Frameworks/Python.framework/Versions/3.3/bin Installing pylint script to /Library/Frameworks/Python.framework/Versions/3.3/bin Installing pyreverse script to /Library/Frameworks/Python.framework/Versions/3.3/bin Successfully installed pylint Cleaning up... pylint --version Problem importing module base.py: No module named 'base' Problem importing module classes.py: No module named 'classes' Problem importing module design_analysis.py: No module named 'design_analysis' Problem importing module exceptions.py: No module named 'exceptions' Problem importing module format.py: No module named 'format' Problem importing module imports.py: No module named 'imports' Problem importing module misc.py: No module named 'misc' Problem importing module newstyle.py: No module named 'newstyle' Problem importing module raw_metrics.py: No module named 'raw_metrics' Problem importing module similar.py: No module named 'similar' Problem importing module string_format.py: No module named 'string_format' Problem importing module typecheck.py: No module named 'typecheck' Problem importing module utils.py: No module named 'utils' Problem importing module variables.py: No module named 'variables' Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pylint/utils.py", line 254, in check_message_id return self._messages[msgid] KeyError: 'W0704' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.3/bin/pylint", line 9, in <module> load_entry_point('pylint==0.26.0', 'console_scripts', 'pylint')() File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pylint/__init__.py", line 21, in run_pylint Run(sys.argv[1:]) File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pylint/lint.py", line 890, in __init__ linter.disable('W0704') File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pylint/utils.py", line 192, in disable msg = self.check_message_id(msgid) File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pylint/utils.py", line 256, in check_message_id raise UnknownMessage('No such message id %s' % msgid) pylint.utils.UnknownMessage: No such message id W0704 En vrai je n'ai pas trop cherché, en ce moment je suis sur un projet en python2 donc je n'ai pas besoin du support de python3. Ça arrivera sans doute bientôt dans les dépôts et je l'installerai comme ça. Chanceux oui ! J'ai ça moi : 2.6.5, 2.7.3, 3.1, 3.3 Je m'en sors plus entre les pip et les easy_install Je ne sais pas comment tu fais, rien qu'avec mes deux versions j'arrive à me planter tous les jours. Apparemment virtualenv permet de gérer ce genre de problèmes, il faut que je regarde. Hors ligne Mindiell Re : /* Topic des codeurs [8] */ Je ne sais pas comment tu fais, rien qu'avec mes deux versions j'arrive à me planter tous les jours. Bah, je me plante Plus sérieusement, j'ai le raccourci python vers 2.6.5 mais je crois que j'ai pip vers 3.1 Enfin bon, c'est pas bien grave, le plus important c'est de conserver le raccourci python pour ubuntu Sinon, j'utilise pas trop pylint pour le moment, et si j'oublie des trucs bah, je verrai plus tard Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ Pylint me donne, après 2-3 modif', 7.76/10. Je m'en contenterai ^^ Maintenant, retour au elisp :] Dernière modification par Le Rouge (Le 20/01/2013, à 14:24) Hors ligne grim7reaper Re : /* Topic des codeurs [8] */ edit 2 : vu que je suis bonne pâte, je vous mets ce que renvoie la commande sans option (merci argparse) C’est cool argparse hein C’est quand même autre chose que getopt et ta suite de if @redoxx : ha ok. Moi je suis pas passé par pip en fait, j’ai tapé direct à la source ^^. Récupération de logilab-common, build puis install. Récupération de logilab-astng, build puis install. Récupération de pylint, build puis install. Et hop, ça fonctionne impec (du coup j’ai viré la version d’Ubuntu) Hors ligne Le Rouge Re : /* Topic des codeurs [8] */ Ayé, version 0.9 en ligne. Code plus propre, interface en CLI plus claire et de nouvelles fonctionnalités pour le minor-mode (emacs). Hors ligne
I have a historical time sequence of seafloor images scanned from film that need registration. from pylab import * import cv2 import urllib urllib.urlretrieve('http://geoport.whoi.edu/images/frame014.png','frame014.png'); urllib.urlretrieve('http://geoport.whoi.edu/images/frame015.png','frame015.png'); gray1=cv2.imread('frame014.png',0) gray2=cv2.imread('frame015.png',0) figure(figsize=(14,6)) subplot(121);imshow(gray1,cmap=cm.gray); subplot(122);imshow(gray2,cmap=cm.gray); I want to use the black region on the left of each image to do the registration, since that region was inside the camera and should be fixed in time. So I just need to compute the affine transformation between the black regions. I determined these regions by thresholding and finding the largest contour: def find_biggest_contour(gray,threshold=40): # threshold a grayscale image ret,thresh = cv2.threshold(gray,threshold,255,1) # find the contours contours,h = cv2.findContours(thresh,mode=cv2.RETR_LIST,method=cv2.CHAIN_APPROX_NONE) # measure the perimeter perim = [cv2.arcLength(cnt,True) for cnt in contours] # find contour with largest perimeter i=perim.index(max(perim)) return contours[i] c1=find_biggest_contour(gray1) c2=find_biggest_contour(gray2) x1=c1[:,0,0];y1=c1[:,0,1] x2=c2[:,0,0];y2=c2[:,0,1] figure(figsize=(8,8)) imshow(gray1,cmap=cm.gray, alpha=0.5);plot(x1,y1,'b-') imshow(gray2,cmap=cm.gray, alpha=0.5);plot(x2,y2,'g-') axis([0,1500,1000,0]); The blue is the longest contour from the 1st frame, the green is the longest contour from the 2nd frame. What is the best way to determine the rotation and offset between the blue and green contours? I only want to use the right side of the contours in some region surrounding the step, something like the region between the arrows. Of course, if there is a better way to register these images, I'd love to hear it. I already tried a standard feature matching approach on the raw images, and it didn't work well enough.
You can use enumerate(): for i, obj in enumerate(object_list): do_something if i == 0: do_something_else if i == len(object_list) - 1: do_another_thing But instead of checking in every iteration which object you are dealing with, maybe something like this is better: def do_with_list(object_list): for obj in object_list: do_something(obj) do_something_else(object_list[0]) do_another_thing(object_list[-1]) Imagine you have a list of 100 objects, then you make 198 unnecessary comparisons, because the current element cannot be the first or last element in the list. But it depends on whether the statements have to be executed in a certain order and what they are doing. Btw. don't shadow object, it is already an identifier in Python ;)
You ever notice how when your script dies because of some uncaught error, you don’t get that error in your log files? This post walks through how to make sure that you log that uncaught exception. This is a trivial script that will raise an uncaught exception (code available here):     $ cat rgl/kaboom1.py     # vim: set expandtab ts=4 sw=4 filetype=python:     import logging     def f():         return g()     def g():         return h()     def h():         return i()     def i():         1/0     if __name__ == '__main__':         logging.basicConfig(             level=logging.DEBUG,             filename='/tmp/kaboom1.log',             filemode='w')         logging.debug('About to do f().')         f() Notice the helpful traceback:     $ python rgl/kaboom1.py     Traceback (most recent call last):       File "rgl/kaboom1.py", line 28, in <module>         f()       File "rgl/kaboom1.py", line 9, in f         return g()       File "rgl/kaboom1.py", line 13, in g         return h()       File "rgl/kaboom1.py", line 17, in h         return i()       File "rgl/kaboom1.py", line 21, in i         1/0     ZeroDivisionError: integer division or     modulo by zero Unfortunately, that helpful traceback does not show up in the output logs!     $ cat /tmp/kaboom1.log     DEBUG:root:About to do f(). You could wrap your code with big try / except This diaper pattern is a popular solution::     try:         f()     except Exception as ex:         logging.exception(ex)         raise Make sure you re-raise the exception, otherwise your program will end with a zero return code. Sidenote: how to log an exception instance If you do any of these, you probably won’t like what you get:     logging.error(ex)     logging.error(str(ex)) In both cases, you are just turning the exception to a string. You won’t see the traceback and you won’t see the exception type. Instead of those, make sure you do one of these:         logging.exception(ex)         # this is exactly what logging.exception does inside         logging.error(ex, exc_info=1)         # sets a higher log level than error         logging.critical(ex, exc_info=1) For the last two, without that exc_info=1 parameter, you won’t see the traceback in your logs. You’ll just see the message from the exception. Or you can use sys.excepthook Instead of nesting your code inside a try-except clause, you can customize the built-in sys.excepthook function. The kaboom2.py script has this extra code:     def log_uncaught_exceptions(ex_cls, ex, tb):         logging.critical(''.join(traceback.format_tb(tb)))         logging.critical('{0}: {1}'.format(ex_cls, ex))     sys.excepthook = log_uncaught_exceptions And here’s the results:     $ python rgl/kaboom2.py     $ cat /tmp/kaboom2.log     DEBUG:root:About to do f().     CRITICAL:root:  File "rgl/kaboom2.py", line 39, in <module>         f()       File "rgl/kaboom2.py", line 9, in f         return g()       File "rgl/kaboom2.py", line 13, in g         return h()       File "rgl/kaboom2.py", line 17, in h         return i()       File "rgl/kaboom2.py", line 21, in i         1/0     CRITICAL:root:<type 'exceptions.ZeroDivisionError'>: integer division or modulo by zero Incidentally, sys.excepthook preserves the non-zero return code. Also incidentally, you can use sys.excepthook for all sorts of fun stuff. This shows how to make it fire off pdb when stuff blows up.
I'm learning how to use pickle. I've created a namedtuple object, appended it to a list, and tried to pickle that list. However, I get the following error: pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P I found that if I ran the code without wrapping it inside a function, it works perfectly. Is there an extra step required to pickle an object when wrapped inside a function? Here is my code: from collections import namedtuple import pickle def pickle_test(): P = namedtuple("P", "one two three four") my_list = [] abe = P("abraham", "lincoln", "vampire", "hunter") my_list.append(abe) f = open('abe.pickle', 'w') pickle.dump(abe, f) f.close() pickle_test()
benjou Re : Aidez moi s'il vous plait pour mon projet benoit@laptop-benoit:~$ picard Traceback (most recent call last): File "/usr/bin/picard", line 2, in ? from picard.tagger import main; main('/usr/share/locale') File "/usr/lib/python2.4/site-packages/picard/tagger.py", line 73, in ? from picard import events, coverartcache, albummanager, util, album, debug, tpmanager, cluster, wpath, cuesheet, playlist, puidmanager File "/usr/lib/python2.4/site-packages/picard/albummanager.py", line 57, in ? import album, artist, track, coverartcache, events, util, cluster, debug File "/usr/lib/python2.4/site-packages/picard/album.py", line 57, in ? import dataobjs, artist, track, util File "/usr/lib/python2.4/site-packages/picard/dataobjs.py", line 55, in ? import util File "/usr/lib/python2.4/site-packages/picard/util.py", line 78, in ? class ConfigSettings(object): File "/usr/lib/python2.4/site-packages/picard/util.py", line 102, in ConfigSettings settingID3Encoding = tunepimp.eUTF8 AttributeError: 'module' object has no attribute 'eUTF8' D'ailleurs si quelqu'un sait installer picard sous dapper... écrasons l'infâme Hors ligne Link31 Re : Aidez moi s'il vous plait pour mon projet http://www.picard.fr/ Hors ligne Gras_du_Bide Re : Aidez moi s'il vous plait pour mon projet Il m'intrigue ce projet... Je tente ma chance: Est-ce que le schimblick sert à convertir les messages d'erreurs en quelque chose de comprehensible pour un débutant? Genre ce qui a coincé et des pistes pour résoudre le problème ? .. En tout cas en tant que débutant un truc du genre me plairait bien! (pas de message d'erreur pour autant sous la main, mais je te garde les suivantes...) Sous Precise: aspire V5-171; X4 640/4Go/GTX 460 ; Clevo M770 2DuoP8400/2Go/Gf9300GS Hors ligne Chompitiarve Re : Aidez moi s'il vous plait pour mon projet EURÉKA ! Un machin qui traduit les erreurs en français et renvoie à leur soluce ? Inutile, puisque Ubuntu sera terminé et définitivement parfait le mois prochain Il n'ya aura donc plus d'erreur, ce qui permettra de supprimer les logiciels de rapport de bug Ainsi que les messages d'erreurs, les correctifs, et les mises à jours. Faudra aussi penser à supprimer l'utilisateur qui ne sert à rien puisqu'il en fait toujours des erreurs. Je me trompe ? Donc zedtux fait un travail muséographique et epistémologique, pour les paléo-informaticiens du siècle prochain. CQFD ==============================>[] (Bon courage, zedtux Dernière modification par Chompitiarve (Le 08/05/2006, à 23:00) Hors ligne Chompitiarve Re : Aidez moi s'il vous plait pour mon projet oui aussi Y'aura enfin la place que mérite le bistrot On pourra même ajouter une aile Hors ligne Chompitiarve Re : Aidez moi s'il vous plait pour mon projet Un squatt de luxe ? Dans lequel on pourra meubler notre désoeuvrement en concevant une nouvelle distrib archi bugguée pour donner quelques loisirs aux anciens errant sur sur leur listes de [résolus] sempiternels, obsolètes et désolants d'uniforminté dont naquit un jour l'ennui frère de la paresse qui est la mère de tous les vices, comme l'a redit bapoumba dans Les Noctambules... Ouais faudrait peut-être qu'on mendie un serveur dédié pour le bistrot, tiens... [edit: Oops! zedtux excuse pour le hors-sujet ] Dernière modification par Chompitiarve (Le 09/05/2006, à 00:08) Hors ligne zedtux Re : Aidez moi s'il vous plait pour mon projet Heu................................. Vous avez pété les plombs ????? Bon arrêter un peu de tous vous impatienter ( même si ca me plait ) je vous dévoile mon projet Trrrrrééééééééééssss bientot !!!!!!!! Mais j'ai fais testé mon projets à quelque personnes qui ont trouvé l'idée en Or. Et veulent absoluement que je continue. J'éspère que vous aurez la même réaction. Quand je vous ouvrirez ses portes, j'éspère pouvoir créé une équipe pour m'aider ! Pas de codage etc...., c'est moi qui m'en occupe, mais pour le recenssement des erreurs etc... mais bon bref, tout vous sera expliqué pour les interessés. Je vais donc faire demain un tour du projet, voire si je trouve des bugs, ou erreurs de ma part. Je vais faire corriger les fautes ( je suis pas écrivaint, mais codeur ou programmeur ) car ca doit être un carnage ( étant jeune -40 aux dictées. ). Et là, je vous ouvrirez les portes de mon projet !!!!!!! Hors ligne benjou Re : Aidez moi s'il vous plait pour mon projet pour picard cf. MusicBrainz écrasons l'infâme Hors ligne Chompitiarve Re : Aidez moi s'il vous plait pour mon projet taratatsin ! Le suspense devient insoutenable ! Hors ligne bergi Re : Aidez moi s'il vous plait pour mon projet tu auras surement plus d'aide quand on serat rassure sur le but de ton logiciel Hors ligne wam Re : Aidez moi s'il vous plait pour mon projet le but du projet, c'est de montrer que la réputation de Linux comme quoi il n'y a pas de bugs est infondée. Il nous demande d'avouer nos bugs, et après, il envoit ça à Microsoft pour se faire plein de blé n'oublie pas de recenser les erreurs produites par ton programme dans la liste Hors ligne zedtux Re : Aidez moi s'il vous plait pour mon projet benoit@laptop-benoit:~$ picard Traceback (most recent call last): File "/usr/bin/picard", line 2, in ? from picard.tagger import main; main('/usr/share/locale') File "/usr/lib/python2.4/site-packages/picard/tagger.py", line 73, in ? from picard import events, coverartcache, albummanager, util, album, debug, tpmanager, cluster, wpath, cuesheet, playlist, puidmanager File "/usr/lib/python2.4/site-packages/picard/albummanager.py", line 57, in ? import album, artist, track, coverartcache, events, util, cluster, debug File "/usr/lib/python2.4/site-packages/picard/album.py", line 57, in ? import dataobjs, artist, track, util File "/usr/lib/python2.4/site-packages/picard/dataobjs.py", line 55, in ? import util File "/usr/lib/python2.4/site-packages/picard/util.py", line 78, in ? class ConfigSettings(object): File "/usr/lib/python2.4/site-packages/picard/util.py", line 102, in ConfigSettings settingID3Encoding = tunepimp.eUTF8 AttributeError: 'module' object has no attribute 'eUTF8' D'ailleurs si quelqu'un sait installer picard sous dapper... As tu suivit les dépendances ?? Exemple, wxPython 2.6.1.x version UNICODE ?? Moi j'ai suivit toute la liste de dépendance, sauf le wxPython 2.6.1.x version UNICODE, et j'ai l'erreur : zedtux@ZubuntuFix:~/Desktop/picard-0.6.0.tar.gz_FILES/picard-0.6.0$ ./tagger.py Traceback (most recent call last): File "./tagger.py", line 62, in ? import sys, os, locale, copy, wx ImportError: No module named wx Donc je pense qu'il me manque plus que wxPython, et ca se lancera ! Offet c'est quoi ce soft ? A quoi il sert axactement ?? Hors ligne benjou Re : Aidez moi s'il vous plait pour mon projet Je n'ai suivi aucune dépendance puisque je l'ai installé via synaptic en ajoutant des dépots (donc c'est pas à moi à gérer les dépendances...) C'est un programme de tag pour fichiers mp3 et ogg écrasons l'infâme Hors ligne Berneri Re : Aidez moi s'il vous plait pour mon projet voilà des erreurs que j'ai régulièrement : postdrop: warning: mail_queue_enter: create file maildrop/800458.13388: Read-only file system C'est assez régulier... "La liberté d'autrui étend la mienne à l'infini." M. Bakounine « Le capitalisme ne se discute pas, il se détruit. » Buenaventura Durruti Hors ligne Enjoy Aspirin Re : Aidez moi s'il vous plait pour mon projet Tu veux faire un programme capable de donner des pistes à l'utilisateur afin qu'il résolve le problème ? Autre façon de dire pour faire classe, un "système expert" ! ted_bundy Re : Aidez moi s'il vous plait pour mon projet j'ai hâte d'installer ton programme en tout cas brova pour ton projet ça a l'air bien classe rien n'est eternel, sauf le gout de la liberté. Hors ligne Chompitiarve Re : Aidez moi s'il vous plait pour mon projet Rha les paris sont tout verts ! Mais si ton projet , zedtux, ressemble à ce que dit Enjoy Aspirin, ça sent son Panthéon ça, entrée triomphale dans Edgy par la grande porte, whâ ! Parce que ça ce serait une belle idée. Bien mieux que le système qui se prétend parfait : le système qui sait aider l'utilisateur à le réparer zedtux Y'a d'la pression là T'as plus droit à l'erreur :lol: Hors ligne zedtux Re : Aidez moi s'il vous plait pour mon projet T'as plus droit à l'erreur :lol: oui c'est clair ! Mais j'ai juste une question pour vous ....... Où vous ai-je dis / Qui vous a dis que mon projet est un programme ?? La ca va la déconcertation total Hors ligne SamheG Re : Aidez moi s'il vous plait pour mon projet Pas de codage etc...., c'est moi qui m'en occupe Disons que çà aide à croire que ce sera un programme ! LMAA Bye ... ça veut dire CIAO en anglais ! Kansas Of Elsass Hors ligne zedtux Re : Aidez moi s'il vous plait pour mon projet zedtux a écrit : Pas de codage etc...., c'est moi qui m'en occupe Disons que çà aide à croire que ce sera un programme ! Y a pas que les programme que l'ont code Hors ligne Enjoy Aspirin Re : Aidez moi s'il vous plait pour mon projet Un site web en php ?
I've managed to get things done this way: query = "<feed xmlns=\"http://www.w3.org/2005/Atom\"" query += " xmlns:media=\"http://search.yahoo.com/mrss/\"" query += " xmlns:batch=\"http://schemas.google.com/gdata/batch\"" query += " xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">" query += "<batch:operation type=\"query\"/>" # Assume ids contain list of YouTube video IDs for vid in ids: query += ("<entry><id>http://gdata.youtube.com/feeds/api/videos/%s</id></entry>" % vid) query += "</feed>" uri = 'http://gdata.youtube.com/feeds/api/videos/batch' feed = client.Post( query, uri, converter=gdata.youtube.YouTubeVideoFeedFromString ) Resulting feed can be iterated as standard youtube api feeds. Although special care of missing videos and other <batch:status>-es should be taken: if len(feed.entry): for entry in feed.entry: skip = False for x in entry.extension_elements: if x.tag == "status" and x.namespace == "http://schemas.google.com/gdata/batch" and x.attributes["code"] != "200": if x.attributes["code"] == "404": skip = True # Likewize you can check for entry's 403 e.g. Quota Exceeded etc ... # Your entry processing goes here
I am having trouble displaying the correct message when file is sucessfully uploaded. What happens is that when a file is successfully uploaded, for a split second it displays the success message but then suddenly it changes to the cancel message. My question is that if a file is successfully uploaded, I want the the success message to be displayed and obviously I don't want it to change to cancel message. Below is a form where it contains a file input as well as and upload and cancel button; <form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target_image' onsubmit='return imageClickHandler(this);' class='imageuploadform' > Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'> <input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label> <input type='reset' name='imageCancel' class='imageCancel' value='Cancel' /></label> <iframe class='upload_target_image' name='upload_target_image' src='#' style='width:0px;height:0px;border:0px;solid;#fff;'></iframe></form> Below is the function where it starts the file uploading: function startImageUpload(imageuploadform){ $(imageuploadform).find('.imagef1_cancel').css('visibility','visible'); sourceImageForm = imageuploadform; $(imageuploadform).find(".imageCancel").on("click", function(event) { $('.upload_target_image').get(0).contentwindow $("iframe[name='upload_target_image']").attr("src", "javascript:'<html></html>'"); $request = $.ajax("cancelimage.php").done(function(data) { return stopImageUpload(2); }); }); return true; } Below is the function where it stop the file uploading: var imagecounter = 0; function stopImageUpload(success, imagefilename){ var result = ''; imagecounter++; if (success == 1){ result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully</span>'; } else if (success == 2){ result = '<span class="imagemsg'+imagecounter+'"> The file upload was cancelled</span>'; } else { result = '<span class="imagemsg'+imagecounter+'">There was an error during file upload</span>'; } $(sourceImageForm).find('.imagef1_cancel').css('visibility','hidden'); $(sourceImageForm).find('.imagemsg').html(result); $(sourceImageForm).find(".fileImage").replaceWith("<input type='file' class='fileImage' name='fileImage' />"); return true; } Below is the clickHandler function: function imageClickHandler(imageuploadform){ if(imageValidation(imageuploadform)){ window.lastUploadImageIndex = $('.imageuploadform').index(imageuploadform); return startImageUpload(imageuploadform); $request.abort() } return false; } Below is the imageupload.php page where it uploads the files: <?php ini_set('display_errors', 1); error_reporting(E_ALL); session_start(); if ($_FILES['fileImage']['error'] === UPLOAD_ERR_OK) { $result = 0; if (getimagesize($_FILES['fileImage']['tmp_name'])) { if ((($_FILES["fileImage"]["type"] == "image/gif") || ($_FILES["fileImage"]["type"] == "image/jpeg") || ($_FILES["fileImage"]["type"] == "image/pjpeg") || ($_FILES["fileImage"]["type"] == "image/jpg")) && ($_FILES['fileImage']['size'] > 0)) { if (is_file("ImageFiles/" . $_FILES['fileImage']['name'])) { $parts = explode(".", $_FILES['fileImage']['name']); $ext = array_pop($parts); $base = implode(".", $parts); $n = 2; while (is_file("ImageFiles/" . $base . "_" . $n . "." . $ext)) $n++; $_FILES['fileImage']['name'] = $base . "_" . $n . "." . $ext; move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]); $result = 1; } else { move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]); $result = 1; } } } } else { echo "Upload was not successful"; } ?>
I'm using PyAudio under the Enthought Python Distribution (Python 2.6.6) in Ubuntu 10.10 x64. >>> import pyaudio >>> pa = pyaudio.PyAudio() >>> pa.get_default_input_device_info() Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> pa.get_default_input_device_info() File "/usr/lib/python_epd/lib/python2.6/site-packages/pyaudio.py", line 936, in get_default_input_device_info device_index = pa.get_default_input_device() IOError: No Default Input Device Available This is the same error I get if I try to open an input stream. There is the corresponding error "IOError: No Default Output Device Available"
Dernière news : Fedora-Fr aux 15èmes Rencontres Mondiales du Logiciel Libre La version bêta de Fedora 17 alias "Beefy Miracle" est à présent disponible. Même si, habituellement, les versions bêta sont déjà relativement stables, n'oubliez pas qu'il s'agit d'une version de développement. Et comme toute version de développement, elle est là pour être testée massivement, pour dénicher et corriger un maximum d'erreurs. On ne le dira jamais assez : la télécharger et la tester c'est bien, mais rapporter les éventuelles anomalies rencontrées, c'est mieux. Merci de privilégier autant que possible le téléchargement via torrent. Profitez de cette installation toute fraîche pour participer aux journées de test afin d'obtenir une version finale au top ! 08 mai 2012 : version Release Candidate 22 mai 2012 : version finale Vous pouvez également ajouter le compte à rebours sur vos sites : http://fedoraproject.org/counter Station : F20 x86_64 sur Core i5 2800 | Portable : F20 x86_64 sur ASUS UL30Vt Le blog de llaumgui : Le journal d'un expert technique en solutions open-source, contributeur à des projets libres. Merci pour l'info. Je suis déjà en train de la tester. Dernière modification par theboogymaster (19/04/2012 19:51:28) je l'attend avec impatience surtout pour avoir la version 1 de pulse audio, la version actuelle de f16 est buggué avec wine :( f16 -> f17 beta par preupgrade ca se fait facilement ? Moi je l'attends sur tout pour le technologie Optimus qui n'as pas marché pour moi sur la F16 Je peux me tromper mais je crains que cette attente soit un peu vaine concernant la technologie Optimus. J'espère me tromper mais pour ma part je l'avais évitée avec soin... Dernière modification par Tlaloc (20/04/2012 12:17:52) «Time present and time past Are both perhaps present in time future, And time future contained in time past.» T.S Eliot je l'attend avec impatience surtout pour avoir la version 1 de pulse audio, la version actuelle de f16 est buggué avec wine :( f16 -> f17 beta par preupgrade ca se fait facilement ? Sans aucune garantie, il me semble avoir vu passer des informations comme quoi preupgrade était pas en forme, ou alors c'était ce qui bloquait la sortie de la bêta, je sais plus trop Enfin, fait toi un live-usb, fait tes sauvegardes et tests On a pas inventé l'électricité en cherchant à améliorer la bougie... -- Si c'est pas sur le bugzilla, c'est pas un bug ! -- Je peux me tromper mais je crains que cette attente soit un peu vaine concernant la technologie Optimus. J'espère me tromper mais pour ma part je l'avais évitée avec soin... On verra ce que ça donne. Pour le moment je tourne très bien sur Arch et Optimus marche d'enfer. Mais j'aimerai tourner plutôt sur Fedora. Comme tu dis, on verra mais je te suggère, si ce n'est fait, de regarder ce qu'il est dit de cette technologie dans le forum... «Time present and time past Are both perhaps present in time future, And time future contained in time past.» T.S Eliot Ben on ne trouve pas beaucoup de discutions la dessus. Je suis celle-ci http://forums.fedora-fr.org/viewtopic.php?id=56550 C'est vrai, il y en a très peu. C'est une autre discussion que j'avais suivie, je ne l'ai pas retrouvée pour le moment. Mes recherches n'ont pas été très intensives, je l'avoue. On peut cependant supposer que les discussions abordant ce sujet se multiplieront dans un futur proche. «Time present and time past Are both perhaps present in time future, And time future contained in time past.» T.S Eliot J'espère qu'il y en aura beaucoup plus... Dernière modification par theboogymaster (20/04/2012 20:53:29) Juste une question les programme pour java 6 son toujours compatible avec le l'openjdk (java 7) ? Ah ben non, c'est bien connu que plus aucun programme ne marche après chaque mise à jour de Java (ou Python, PHP, Perl...). Fedora 19 x86_64 sur Dell Latitude E6400 Prends le temps d'écrire correctement, et on prendra le temps de répondre correctement. ben51 a écrit : Juste une question les programme pour java 6 son toujours compatible avec le l'openjdk (java 7) ? Ah ben non, c'est bien connu que plus aucun programme ne marche après chaque mise à jour de Java (ou Python, PHP, Perl...). ??? Ça dépend des versions dans le cas de Python entre la 3.0 et la 2.X il n'est pas garantie que ton programme fonctionne (http://fr.wikipedia.org/wiki/Python_%28 … ython_3000) Je me pose la question avec de ce qu'il en est avec java 6 et java 7 vue que j'ai un programme qui ne fonctionne plus sur fedora 17. Valdes a écrit :ben51 a écrit : Juste une question les programme pour java 6 son toujours compatible avec le l'openjdk (java 7) ? Ah ben non, c'est bien connu que plus aucun programme ne marche après chaque mise à jour de Java (ou Python, PHP, Perl...). ??? Ça dépend des versions dans le cas de Python entre la 3.0 et la 2.X il n'est pas garantie que ton programme fonctionne (http://fr.wikipedia.org/wiki/Python_%28 … ython_3000) Je me pose la question avec de ce qu'il en est avec java 6 et java 7 vue que j'ai un programme qui ne fonctionne plus sur fedora 17. Java garantit une compatibilité descendante entre ses différentes versions, ce qui n'est en effet pas le cas de Python 2 et Python 3. Tu ne devrais pas avoir de problème à compiler du code écrit pour Java 6 avec OpenJDK 7, ni à interpréter du bytecode compilé avec OpenJDK 6. « …elle excitait si puissamment le désir, que je devins alors très incrédule sur sa vertu. » À propos de Fœdora, dans la Peau de Chagrin (Balzac) Java garantit une compatibilité descendante entre ses différentes versions, ce qui n'est en effet pas le cas de Python 2 et Python 3. Tu ne devrais pas avoir de problème à compiler du code écrit pour Java 6 avec OpenJDK 7, ni à interpréter du bytecode compilé avec OpenJDK 6. J'ai un problème avec minecraft qui plante mais on dirait que le problème vient de librairie non java. Je suis content de cette nouvelle version, maintenant je peux scroller dans nautilus avec les doigts sur ma tablette, sans utiliser les ascenseurs. Manque plus que le clic droit pour que je l'utilise en OS principal dessus. Valdes a écrit :ben51 a écrit : Juste une question les programme pour java 6 son toujours compatible avec le l'openjdk (java 7) ? Ah ben non, c'est bien connu que plus aucun programme ne marche après chaque mise à jour de Java (ou Python, PHP, Perl...). ??? Ça dépend des versions dans le cas de Python entre la 3.0 et la 2.X il n'est pas garantie que ton programme fonctionne (http://fr.wikipedia.org/wiki/Python_%28 … ython_3000) Je me pose la question avec de ce qu'il en est avec java 6 et java 7 vue que j'ai un programme qui ne fonctionne plus sur fedora 17. Merde. Au temps pour moi. Je pensais que Python avait aussi une comptabilité descendante. Mais Java c'est bon t'inquiètes (normalement) Fedora 19 x86_64 sur Dell Latitude E6400 Prends le temps d'écrire correctement, et on prendra le temps de répondre correctement. Merde. Au temps pour moi. Je pensais que Python avait aussi une comptabilité descendante. Mais Java c'est bon t'inquiètes (normalement) Justement avec Minecraft j'ai un problème. Et je ne sais pas qui incriminé d’où ma question. Justement avec Minecraft j'ai un problème. Et je ne sais pas qui incriminé d’où ma question. Sur un nouveau fil, ton problème aura plus de visibilité. Décris bien sur celui-ci la manière dont Minecraft a été installé en particulier. « …elle excitait si puissamment le désir, que je devins alors très incrédule sur sa vertu. » À propos de Fœdora, dans la Peau de Chagrin (Balzac) malgrès mon bug report + l'écriture dans beat fedora ils ont oublié la feature D programming .... Dernière modification par bioinfornatics (24/04/2012 13:10:14) ben51 a écrit : Justement avec Minecraft j'ai un problème. Et je ne sais pas qui incriminé d’où ma question. Sur un nouveau fil, ton problème aura plus de visibilité. Décris bien sur celui-ci la manière dont Minecraft a été installé en particulier. Bien j'ai trouvé la réponse sur le forum, même si je comprend pas trop d’où viens l'erreur et pourquoi ça refonctionne. bonjour, y aurait-il une section où nous pourrions mettre nos soucis avec la nouvelle mouture ?? les soucis que je rencontre ne provoquent pas de déclaration de bug je ne peux lancer la gestion selinux après avoir installé policycoreutils-gui si j'essaie de le lancer à partir du terminal ça me donne : system-config-selinux ** (process:2399): WARNING **: Trying to register gtype 'GMountMountFlags' as enum when in fact it is of type 'GFlags' ** (process:2399): WARNING **: Trying to register gtype 'GDriveStartFlags' as enum when in fact it is of type 'GFlags' ** (process:2399): WARNING **: Trying to register gtype 'GSocketMsgFlags' as enum when in fact it is of type 'GFlags' Gtk-Message: Failed to load module "pk-gtk-module" /usr/share/system-config-selinux/system-config-selinux.py:71: Warning: g_object_get_valist: object class `GnomeProgram' has no property named `default-icon' xml = gtk.glade.XML ("/usr/share/system-config-selinux/system-config-selinux.glade", domain=PROGNAME) ERROR: policydb magic number 0x000008 does not match expected magic number 0xf97cff8c or 0xf97cff8d ERROR: Unable to open policy /sys/fs/selinux/policy. Traceback (most recent call last): File "/usr/share/system-config-selinux/system-config-selinux.py", line 186, in <module> app = childWindow() File "/usr/share/system-config-selinux/system-config-selinux.py", line 91, in __init__ self.add_page(domainsPage.domainsPage(xml)) # domains File "/usr/share/system-config-selinux/domainsPage.py", line 71, in __init__ self.domains=polgen.get_all_domains() File "/usr/share/system-config-selinux/polgen.py", line 106, in get_all_domains types=get_all_types() File "/usr/share/system-config-selinux/polgen.py", line 80, in get_all_types all_types = map(lambda x: x['name'], setools.seinfo(setools.TYPE)) File "/usr/lib64/python2.7/site-packages/setools/__init__.py", line 49, in seinfo dict_list = _seinfo.seinfo(setype, name) RuntimeError: Succès merci de vos réponses qu'on puisse vous donner un coup de main
Ah well, if you're forced to keep that clunky data structure, you can't expect much. The one-liner equivalent of your first solution is going to be something like: def samplesof(requested_cond, conditions): return next(s for c, s in conditions if c==requested_cond) and for the second one, if you insist on one-liners, it's going to be something like: def ordered_union(the_conds, conditions): return [s for c in the_conds for s in samplesof(c, conditions)] There are faster ways to solve the second problem, but they're all multi-line, e.g.: aux_set = set(the_conds) samples_by_cond = dict((c, s) for c, s in conditions if c in aux_set) return [s for c in the_conds for s in samples_by_cond[c]] Note that the key to the reason this latter approach is faster is that it uses the right data structures (a set and a dict) -- unfortunately it has to build them itself, because the incoming conditions nested list is really the wrong data structure. Couldn't you encapsulate conditions as a member variable of a class that builds the crucial (right, fast) auxiliary data structures just once? E.g.: class Sensible(object): def __init__(self, conditions): self.seq = [] self.dic = {} for c, s in conditions: self.seq.append(c) self.dic[c] = s def samplesof(self, requested_condition): return self.dic[requested_condition] def ordered_union(self, the_conds): return [s for c in the_conds for s in self.dic[c]] Now that is fast and elegant! I'm assuming that you need self.seq (the sequence of conditions) for something else (it's certainly not needed for the two operations you mention!), and that there are no repetitions in that sequence and in the samples (whatever your actual specs are they won't be hard to accomodate, but blindly trying to guess them when you mention nothing about them would be very hard and pointless;-).
vallkin Problème wacom MTE-450 sous 12.04 Bonjour à tous, je suis utilisateur occasionnel de Linux depuis la 8.04, et ai décidé de migrer définitivement vers Linux à l'achat de mon prochain PC (berk pas Windows 8). Cependant quelques obstacles viennent encore s'opposer à moi. En effet, étant professionnel, j'ai un besoin vital de ma tablette graphique, une bonne vieille Bamboo MTE-450, qui hélas ne fonctionne pas comme je le voudrais. En effet si je peux me passer du touch ring et des 4 boutons sur la tablette, il n'en est pas autant pour ce qui est des deux boutons du stylet. Dans un soucis de précision, notamment pour récupérer les couleurs sur Mypaint, ou sélectionner les verticles sous Blender, j'ai choisis l'option cliquer et appuyer sous Windows. En conséquent, si j'appuie sur les boutons sans poser le stylet sur la tablette rien ne se passe, au lieu d'avoir le curseur qui se balade comme c'est le cas actuellement sur mon Linux. Ainsi, j'aimerais savoir comment retrouver cette option sous la 12.04. Ça fais quelques jours que je cherche partout sur le web, et je ne trouve pas, alors, ou j'ai du mal à exprimer ma requête (fort probable), ou personne n'a encore été confronté à ce problème. Au delà de ça, la tablette est reconnu immédiatement par linux, sans avoir a installer quelque pilote que ce soit, sauf qu'il n'y a aucune option concernant les boutons. J'ai téléchargé wacom utility en vain. Je viens vers vous en dernier recours, et espère ne pas poser une question qui aurait déjà été posté sur le forum, si ça a déjà été le cas je m'en excuse par avance. Hors ligne vallkin Re : Problème wacom MTE-450 sous 12.04 Ola, je crois que j'ai posé une sacrée colle... Hors ligne Hors ligne vallkin Re : Problème wacom MTE-450 sous 12.04 Uploaded with ImageShack.us Voila exactement de quoi il s'agit. Dernière modification par vallkin (Le 13/09/2012, à 19:17) Hors ligne vallkin Re : Problème wacom MTE-450 sous 12.04 j'ai a peu près la même chose avec ubuntu, mais le paramètre que j'ai présenté sur le screenshot n'est pas disponible. Pourtant, auparavant, j'avais réussi à paramétrer tout ça en modifiant le xorg, si je me rappelle bien. D'ailleurs, je ne trouve plus ma wacom dans le xorg. Probablement a cause de la 12.04. A vrai dire j'étais resté sur une version de ubuntu antérieure à unity. Tout a changé depuis, j'avoue que je suis un peu perdu. Hors ligne stevens4c Re : Problème wacom MTE-450 sous 12.04 sinon il nous reste xsetwacom je sais pas si tu connais. perso j ai configuré ma tablette avec. je te mets le lien d un sujet sur xsetwacom si tu as des question n hésites pas on verra http://forum.ubuntu-fr.org/viewtopic.php?id=319659&p=9 Hors ligne vallkin Re : Problème wacom MTE-450 sous 12.04 C'est bon, il s'agit de la commande set "stylus" TabletPCButton, qui est sur off par défaut. J'ai donc crée un lanceur au démarrage avec la commande suivante : sh -c "sleep 5 && (xsetwacom set 11 TabletPCButton on)" Le sleep de seconde est important, parce que si je lance tout de suite ça ne fonctionne pas, certainement à cause de l'initialisation de la tablette. Bon et bien maintenant, on va essayer de trouver le touch ring, qui n'est visiblement pas reconnu. Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Bonjour, j'ai le même problème, j'ai installé une Bamboo MTE 450, ça fonctionne instantanément sauf les boutons FN1, FN2, <, >. Je désire m'en servir pour par exemple changer de fenêtre ou autre chose. Pour cela, il faut avoir la config du driver je suppose, et en reconnaissant les touches, simplement leur donner une fonction par ex. "alt tab" pour FN1, et page suivante pour FN2. Est-ce possible ?? ou ces touches me seront inutiles à Jamais !!!! Bien à vous Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Merci pour ta réponse, mais je n'ai pas le driver dans le paramètre du matériel. J'essaye avec xsetwacom, j'ai entre temps suivi ton lien très bien fait mais quand je parametre les boutons comme ca, xsetwacom set 18 button 1 key tabxsetwacom set 18 button 2 key altxsetwacom set 18 button 3 key axsetwacom set 18 button 8 key b ca fonctionne au départ et quand je lance un fichier et que je me sert du déplacement du stylet, les boutons ne fonctionnent plus. tu as une idée ? Hors ligne Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 j'ai fait un gedit executable comme indiqué et c'est quand je lance par exemple xournal, je ballade le stylet, et aprés ca, les boutons ne fonctionnent plus alors qu'ils fonctionnaient juste avant. Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Je viens de remarquer que le problème ne vient pas de xournal. voila la config : # herber@amandine-Dell-DC051:~$ xsetwacom list devices # Wacom Bamboo eraser id: 16 type: ERASER # Wacom Bamboo cursor id: 17 type: CURSOR # Wacom Bamboo pad id: 18 type: PAD # Wacom Bamboo stylus id: 19 type: STYLUS ] C'est donc une wacom bamboo Ensuite j'ai pris ton exemple pour configurer ma tablette : # 1)Boutons : # strips en anneau haut: xsetwacom set 18 AbsWUp "core key -" # Zoom - # strips en anneau bas: xsetwacom set 18 AbsWDn "core key +" # Zoom + # les quatres boutons : # < = button 1 # Fn1 = button 2 # > = button 3 # Fn2 = button 8 xsetwacom set 18 button 1 "core key tab" # tabulation xsetwacom set 18 button 2 "core key alt" # Alt xsetwacom set 18 button 3 "core key CONTROL z" # Annuler xsetwacom set 18 button 8 "core key d" # d par ex. Tout ça dans un gedit et changé en .sh et exécutable. Tout fonctionne jusquà ce que ballade le stylet une fois au dessus du pavé et c'est là que ça annule mes touches ALT TAB. (FN1 et <) Le problème est là pour l'instant même si je ne lance pas xournal. C'est pareil avec open office ou gedit ou..... Merci Hors ligne stevens4c Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Voila ce qui en sort : herber@amandine-Dell-DC051:~$ xsetwacom get 18 all Property 'Wacom Tablet Area' does not exist on device. Property 'Wacom Debug Levels' does not exist on device. Property 'Wacom Debug Levels' does not exist on device. Property 'Wacom Sample and Suppress' does not exist on device. Property 'Wacom Sample and Suppress' does not exist on device. Property 'Wacom Pressurecurve' does not exist on device. Property 'Wacom Hover Click' does not exist on device. Property 'Wacom Enable Touch' does not exist on device. Property 'Wacom Enable Touch Gesture' does not exist on device. Property 'Wacom Touch Gesture Parameters' does not exist on device. Property 'Wacom Touch Gesture Parameters' does not exist on device. Property 'Wacom Touch Gesture Parameters' does not exist on device. Property 'Wacom Capacity' does not exist on device. Property 'Wacom Proximity Threshold' does not exist on device. Property 'Wacom Rotation' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Sample and Suppress' does not exist on device. Property 'Wacom Pressure Threshold' does not exist on device. Property 'Wacom Tool Type' does not exist on device. Property 'Wacom Serial IDs' does not exist on device. Property 'Wacom Serial IDs' does not exist on device. Visiblement, rien n'existe !! pourtant la tablette est branchée. Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Ca a changé !!! les affectations ne sont plus les mêmes !! Blizzard !!! Voila ce que j'ai maintenant : herber@amandine-Dell-DC051:~$ xsetwacom list devices Wacom Bamboo eraser id: 10 type: ERASER Wacom Bamboo cursor id: 11 type: CURSOR Wacom Bamboo pad id: 12 type: PAD Wacom Bamboo stylus id: 13 type: STYLUS herber@amandine-Dell-DC051:~$ xsetwacom get 10 all Option "Area" "0 0 14760 9225" Option "ToolDebugLevel" "0" Option "TabletDebugLevel" "0" Option "Suppress" "4" Option "RawSample" "2" Option "PressureCurve" "0 0 100 100" Option "Mode" "Absolute" Property 'Wacom Hover Click' does not exist on device. Option "Touch" "off" Option "Gesture" "off" Option "ZoomDistance" "50" Option "ScrollDistance" "20" Option "TapTime" "250" Option "Capacity" "-1" Property 'Wacom Proximity Threshold' does not exist on device. Option "Rotate" "none" Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Option "RawFilter" "on" Option "Threshold" "27" Option "ToolID" "255" Option "ToolSerial" "0" Option "TabletID" "101" herber@amandine-Dell-DC051:~$ xsetwacom get 11 all Option "Area" "0 0 14760 9225" Option "ToolDebugLevel" "0" Option "TabletDebugLevel" "0" Option "Suppress" "4" Option "RawSample" "2" Property 'Wacom Pressurecurve' does not exist on device. Option "Mode" "Absolute" Property 'Wacom Hover Click' does not exist on device. Option "Touch" "off" Option "Gesture" "off" Option "ZoomDistance" "50" Option "ScrollDistance" "20" Option "TapTime" "250" Option "Capacity" "-1" Option "CursorProximity" "42" Option "Rotate" "none" Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Option "RawFilter" "on" Option "Threshold" "27" Option "ToolID" "8" Option "ToolSerial" "0" Option "TabletID" "101" herber@amandine-Dell-DC051:~$ xsetwacom get 12 all Property 'Wacom Tablet Area' does not exist on device. Option "ToolDebugLevel" "0" Option "TabletDebugLevel" "0" Option "Suppress" "4" Option "RawSample" "2" Property 'Wacom Pressurecurve' does not exist on device. Option "Mode" "Absolute" Property 'Wacom Hover Click' does not exist on device. Option "Touch" "off" Option "Gesture" "off" Option "ZoomDistance" "50" Option "ScrollDistance" "20" Option "TapTime" "250" Option "Capacity" "-1" Property 'Wacom Proximity Threshold' does not exist on device. Option "Rotate" "none" Option "RelWheelUp" "5" Option "RelWheelDown" "4" Option "AbsWheelUp" "4" Option "AbsWheelDown" "5" Option "StripLeftUp" "4" Option "StripLeftDown" "5" Option "StripRightUp" "4" Option "StripRightDown" "5" Option "RawFilter" "on" Option "Threshold" "27" Option "ToolID" "281" Option "ToolSerial" "0" Option "TabletID" "101" herber@amandine-Dell-DC051:~$ Je réessaye le fichier et te dis quoi !! Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Ca fait la même chose Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Oups.... et le 13 herber@amandine-Dell-DC051:~$ xsetwacom get 13 all Option "Area" "0 0 14760 9225" Option "ToolDebugLevel" "0" Option "TabletDebugLevel" "0" Option "Suppress" "4" Option "RawSample" "2" Option "PressureCurve" "0 0 100 100" Option "Mode" "Absolute" Option "TabletPCButton" "off" Option "Touch" "off" Option "Gesture" "off" Option "ZoomDistance" "50" Option "ScrollDistance" "20" Option "TapTime" "250" Option "Capacity" "-1" Property 'Wacom Proximity Threshold' does not exist on device. Option "Rotate" "none" Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Wheel Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Property 'Wacom Strip Buttons' does not exist on device. Option "RawFilter" "on" Option "Threshold" "27" Option "ToolID" "284" Option "ToolSerial" "0" Option "TabletID" "101" herber@amandine-Dell-DC051:~$ Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 J'ai essayé ça : herber@amandine-Dell-DC051:~$ xsetwacom get "Wacom Bamboo pad" Button 1 key +Tab -Tab herber@amandine-Dell-DC051:~$ xsetwacom get "Wacom Bamboo pad" Button 2 key +Alt_L herber@amandine-Dell-DC051:~$ xsetwacom get "Wacom Bamboo pad" Button 3 key +Control_L +z -z herber@amandine-Dell-DC051:~$ xsetwacom get "Wacom Bamboo pad" Button 8 key +d -d Et aprés avoir balladé le stylet, j'ai la même chose (c'est pourtant reconnu) herber@amandine-Dell-DC051:~$ xsetwacom get "Wacom Bamboo pad" Button 1 key +Tab -Tab herber@amandine-Dell-DC051:~$ xsetwacom get "Wacom Bamboo pad" Button 2 key +Alt_L herber@amandine-Dell-DC051:~$ MAIS ça ne fonctionne plus, l'exécution sur l'écran ne se fait plus Dernière modification par leo62 (Le 25/05/2013, à 15:15) Hors ligne leo62 Re : Problème wacom MTE-450 sous 12.04 Oui c'est ça, la config des touches s'annulent. Hors ligne
I'm trying to use python's Regular expression package re from within C++, within boost.python code. Here is an example code snippet in my C++ application: #include <boost/python.hpp> Py_Initialize(); object main = import("__main__"); object main_namespace = main.attr("__dict__"); object ignored = exec( "import re\n" "def run():\n" " rmatch = re.search(r'\d',r'hello3')\n" " print rmatch\n" "\n" "print 'main module loaded'\n", main_namespace); object run_func = main.attr("run"); run_func(); Py_Finalize(); The regular expression should simply pick up the digit in the string hello3. This exact line of code works in Python, however in embedded python, rmatch is always None. Would anyone be able to offer some insight as to why? Thanks!
Is there a more concise, efficient or simply pythonic way to do the following? def product(list): p = 1 for i in list: p *= i return p EDIT: I actually find that this is marginally faster than using operator.mul: from operator import mul # from functools import reduce # python3 compatibility def with_lambda(list): reduce(lambda x, y: x * y, list) def without_lambda(list): reduce(mul, list) def forloop(list): r = 1 for x in list: r *= x return r import timeit a = range(50) b = range(1,50)#no zero t = timeit.Timer("with_lambda(a)", "from __main__ import with_lambda,a") print("with lambda:", t.timeit()) t = timeit.Timer("without_lambda(a)", "from __main__ import without_lambda,a") print("without lambda:", t.timeit()) t = timeit.Timer("forloop(a)", "from __main__ import forloop,a") print("for loop:", t.timeit()) t = timeit.Timer("with_lambda(b)", "from __main__ import with_lambda,b") print("with lambda (no 0):", t.timeit()) t = timeit.Timer("without_lambda(b)", "from __main__ import without_lambda,b") print("without lambda (no 0):", t.timeit()) t = timeit.Timer("forloop(b)", "from __main__ import forloop,b") print("for loop (no 0):", t.timeit()) gives me ('with lambda:', 17.755449056625366) ('without lambda:', 8.2084708213806152) ('for loop:', 7.4836349487304688) ('with lambda (no 0):', 22.570688009262085) ('without lambda (no 0):', 12.472226858139038) ('for loop (no 0):', 11.04065990447998)
I have a fresh centos 6.2 with mysql in 5.1.52. Then I saw two empty user name and I deleted that then I saw 3 root user deleted that and created one like this CREATE USER 'root'@'%' IDENTIFIED BY '**';. But when I go in as root into my phpMyAdmin now I cannot create a new database. What wrong did I do here? I have a fresh centos 6.2 with mysql in 5.1.52. Then I saw two empty user name and I deleted that then I saw 3 root user deleted that and created one like this CREATE USER 'root'@'%' IDENTIFIED BY ' Your problem stems from deleteing all the root users first. When you create a user using CREATE USER root@localhost; GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY 'whatever'; If you do not issue GRANT right away, all the db Privileges are disabled (i.e., in the mysql.user table, update_priv='N', delete_priv='N', etc.) If you have root@localhost and still cannot access it you may have to hack into it like this: STEP 01) Restart mysql like this service mysql restart --skip-grant-tables --skip-networking STEP 02) Enter mysql from the command line (no password needed at this point) STEP 03) Do You will have to tweak each privilege since the GRANT command does not work will Example For MySQL 5.1, you can enter a new root@localhost whose password is 'whatever' as follows: DELETE FROM mysql.user WHERE user='root' AND host='localhost'; INSERT INTO mysql.user SET Host = 'localhost', User = 'root', Password = PASSWORD('whatever'), Select_priv = 'Y', Insert_priv = 'Y', Update_priv = 'Y', Delete_priv = 'Y', Create_priv = 'Y', Drop_priv = 'Y', Reload_priv = 'Y', Shutdown_priv = 'Y', Process_priv = 'Y', File_priv = 'Y', Grant_priv = 'Y', References_priv = 'Y', Index_priv = 'Y', Alter_priv = 'Y', Show_db_priv = 'Y', Super_priv = 'Y', Create_tmp_table_priv = 'Y', Lock_tables_priv = 'Y', Execute_priv = 'Y', Repl_slave_priv = 'Y', Repl_client_priv = 'Y', Create_view_priv = 'Y', Show_view_priv = 'Y', Create_routine_priv = 'Y', Alter_routine_priv = 'Y', Create_user_priv = 'Y', Event_priv = 'Y', Trigger_priv = 'Y', ssl_type = '', ssl_cipher = '', x509_issuer = '', x509_subject = '', max_questions = 0, max_updates = 0; STEP 04) restart mysql You can login as root@localhost from here with the password 'whatever'. Feel free to replace whatever with the password you want. Give it a Try !!! You need to grant the appropriate privileges for the root account, not just create it. MySQL does not know on its own that you want a Super user account. CREATE USER 'root'@'%' IDENTIFIED BY '*'; GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION; You should use the appropriate In case you do not have enough privileges for granting new privileges, you can try a couple of options. To get root access back, stop your server and start it with the If phpMyAdmin lets you login (without a password), or if you have command-line access, connect and issue ( CREATE USER root@localhost IDENTIFIED BY 'xxx'; UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root' AND Host='localhost'; FLUSH PRIVILEGES; Log out and then connect as root@localhost ( GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost`; DROP USER root@`%`; FLUSH PRIVILEGES; You don't want root at any host! Also, you will want to do this as quickly as possible if you still have networking enabled.
Pierre Thibault Comment fonctionnent les pipes et les commandes shell avec Python Bonjour, J'ai de la difficulté à comprendre comment les redirections fonctionnent avec les commandes shell et Python. Par exemple, si dans un shell bash je tape: aa | bb Si je tape la commande précédente, cela veut dire que la sortie de la commande 'aa', stdout, sera l'entrée pour la commande 'bb', stdin, n'est-ce pas? Mon problème se trouve à cette ligne de code en Python : subprocess.call(["xsel", "-b", "-i"], stdin=tmp_file) L'entrée pour la commande 'xsel' se trouve avec le fichier tmp_file. Cette commande fonctionne très bien. Ce que je ne comprends pas est que j'ai dû employer l'option '-i' qui est définie dans la doc de xsel de la façon suivante : -i, --input Read standard input into the selection Ma question est pourquoi dois-je employer cette option? Par exemple, si je tape dans le shell bash : echo xx | xsel xsel lit son information depuis l'entrée standard qui est alimentée par la commande 'echo', n'est-ce pas? Pourquoi n'ai-je pas à employer l'option -i comme pour ma ligne de code Python? Hors ligne Maisondouf Re : Comment fonctionnent les pipes et les commandes shell avec Python parce que le shell, c'est pas du python. Chacun a sa syntaxe et son fonctionnement distinct. By default, this program outputs the selection without modification if both standard input and standard output are terminals (ttys). Otherwise, the current selection is output if standard output is not a terminal (tty), and the selection is set from standard input if standard input is not a terminal (tty). Alors effectivement depuis Python, il n'y pas de notion de pipe au sens shell, c'est le call python qui "déverse" le contenu du fichier dans l'entrée de la commande. Comme si sous shell, on avait fait: cat tmp_file | xsel ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½ Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains.... "the secret of my form is summed up in two words, no sport" (Winston Churchill) Hors ligne Pierre Thibault Re : Comment fonctionnent les pipes et les commandes shell avec Python Alors effectivement depuis Python, il n'y pas de notion de pipe au sens shell, c'est le call python qui "déverse" le contenu du fichier dans l'entrée de la commande. Comme si sous shell, on avait fait:cat tmp_file | xsel Je ne comprends pas. Si je fais la commande précédente dans le terminal, je n'ai pas besoin de l'option -i comme en Python. Est-ce que ça veut dire qu'il y a une erreur dans la documentation de la commande xsel? Hors ligne pingouinux Re : Comment fonctionnent les pipes et les commandes shell avec Python Bonjour, Comme l'indique l'extrait de man xsel (Maisondouf #2), l'entrée standard est traitée différemment si c'est un terminal. Ces trois commandes vont bien lire l'entrée standard : cat tmp_file | xselxsel <tmp_filexset -i # Lecture sur le terminal mais pas celle-ci : xsel Hors ligne Pierre Thibault Re : Comment fonctionnent les pipes et les commandes shell avec Python OK. C'est ce que je vois. Donc on peut détecter si une entrée ou une sortie est un terminal. Je ne savais pas cela. Cela ne me semble pas être en accord avec la doc qui dit: Otherwise, the current selection is output if standard output is not a terminal (tty), and the selection is set from standard input if standard input is not a terminal (tty). Ça dit que ça lit l'entrée standard donc je ne vois pas pourquoi je dois employer l'option -i. Hors ligne aurelien.noce Re : Comment fonctionnent les pipes et les commandes shell avec Python En effet c'est bizarre ton histoire, et surtout je n'ai pas le bug chez moi... c'est quoi ta version de python/xsel ? En même temps, l'auteur lui-même précise que son algo de defaulting est assez limite (src) et qu'il vaut mieux utiliser les options explicites comme le -i ici. Mais bon je suis curieux de voir comprendre le pourquoi du comment. Au hasard, est-tu sûr que ton tmp_file ne vaut pas justement sys.stdin ? Hors ligne Pierre Thibault Re : Comment fonctionnent les pipes et les commandes shell avec Python En effet c'est bizarre ton histoire, et surtout je n'ai pas le bug chez moi... c'est quoi ta version de python/xsel ? > python --version && xsel --versionPython 2.7.3xsel version 1.2.0 by Conrad Parker <conrad@vergenet.net> En même temps, l'auteur lui-même précise que son algo de defaulting est assez limite (src) et qu'il vaut mieux utiliser les options explicites comme le -i ici. OK, ça expliquerait les choses. Mais bon je suis curieux de voir comprendre le pourquoi du comment. Au hasard, est-tu sûr que ton tmp_file ne vaut pas justement sys.stdin ? Non, je ne crois pas. Voici le code Python de mon petit script: #!/usr/bin/env python # Add for 4 spaces at each line of the current selection # store the result in the clipboard import subprocess import tempfile sel = subprocess.check_output("xsel") end_new_line = sel.endswith("\n") sel = sel.replace("\n", "\n ", sel.count("\n") - int(end_new_line)) sel = " " + sel with tempfile.TemporaryFile(mode='w+') as tmp_file: tmp_file.write(sel) tmp_file.seek(0) subprocess.call(["xsel", "-b", "-i"], stdin=tmp_file) Hors ligne aurelien.noce Re : Comment fonctionnent les pipes et les commandes shell avec Python ton code me donne une idée: - essaye laisser le mode par défaut (lecture+ecriture et binaire) sur ton tempfile - essaye d'appeler .flush() sur ton file descripteur histoire d'être sûr d'avoir tout est écrit avant de lancer ton process avec ça ça devrait mieux marcher, tu confirmes ? OK, ça expliquerait les choses. En fait non... le code source est très clair: xsel va lire l'entrée standard ssi isatty(0) renvoie True, et après un rapide test chez moi ce n'est pas le cas dans le cas d'un appel depuis subprocess.call() avec l'option stdin settée à un fichier. D'où l'idée qu'il n'y arrive pas parce que le fichier n'est pas prêt. Dernière modification par aurelien.noce (Le 11/01/2013, à 11:43) Hors ligne Pierre Thibault Re : Comment fonctionnent les pipes et les commandes shell avec Python Voici la nouvelle version du code: #!/usr/bin/env python # Add for 4 spaces at each line of the current selection # store the result in the clipboard import subprocess import tempfile sel = subprocess.check_output("xsel") end_new_line = sel.endswith("\n") sel = sel.replace("\n", "\n ", sel.count("\n") - int(end_new_line)) sel = " " + sel with tempfile.TemporaryFile() as tmp_file: tmp_file.write(sel) tmp_file.flush() tmp_file.seek(0) subprocess.call(["xsel", "-b", "-i"], stdin=tmp_file) Ça fonctionne toujours mais si j'enlève l'option "-i", ça ne fonctionne plus. Hors ligne
while saving an entity that has reference properties, is it the app's responsibility to check that the entities referred to by the reference properties already exist in the datastore? While unit testing with the datastore_v3_stub, I find that app engine will happily save a entity A that has a reference property B associated with it (and B does not exist in the datastore yet). further when A is saved, B is not saved. When you subsequently fetch A from the datastore, and try to navigate to B, you get an exception. Is this expected behavior? Example code: user = MyUser(key_name='2', name='my user 2') e = db.get(user.key()) self.assertTrue(e is None) # user does not exist in datastore yet preferences = Preferences(user=user) # user is a ReferenceProperty preferences.put() e = db.get(user.key()) self.assertTrue(e is None) # user still does not exist in datastore e = db.get(preferences.key()) self.assertFalse(e is None) # but preferences were still stored e.user will give exception EDIT: I am a python newbie, but is it possible to write a class that subclasses db.Model and overrides the put method to enforce referential integrity (by using some kind of reflection) before calling put of db.Model. Then I can just subclass this class to enforce referential integrity on my model classes (A, B above for example) this is what i came up with. can any gurus code-review this: for name, property in obj.properties().items(): if isinstance(property, db.ReferenceProperty): try: value = getattr(essay, name) except datastore_errors.Error: print name, property, 'does not exist in datastore yet' continue key = value.key() o = db.get(key) if o is None: print name, property, value, 'does not exist in datastore yet'
I'm trying to add a dynamic number of pictures to an element called "component". Looking around I've created this code: component.rb class Component < ActiveRecord::Base has_many :images accepts_nested_attributes_for :images, :allow_destroy => true end image.rb class Image < ActiveRecord::Base attr_accessible :component_id, :photo_file_size belongs_to :component, :foreign_key => :component_id has_attached_file :photo, :styles => { :thumb => "75x75>", :small => "200x200>" } end _form.html.erb <%= form_for setup_component(@component) , :html => { :multipart => true } do |f| %> ... <h2> PHOTOS </h2> <% f.fields_for @component.images.build do |p| %> <h2>Photo</h2> <p><%= f.label :data %><br /><%= f.file_field :data %></p> <% end %> application_helper.rb def setup_component(comp) return comp.images.build if comp.images.empty? end So I'm getting the following error when I try going to form: undefined method `images_path'
This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access. You can override the default behavior of the error method: import argparse import sys class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) parser=MyParser() parser.add_argument('foo', nargs='+') args=parser.parse_args() Note that the above solution will print the help message whenever the error method is triggered. For example, test.py --blah will print the help message too if --blah isn't a valid option. If you want to print the help message only if no arguments are supplied on the command line, then perhaps this is still the easiest way: import argparse import sys parser=argparse.ArgumentParser() parser.add_argument('foo', nargs='+') if len(sys.argv)==1: parser.print_help() sys.exit(1) args=parser.parse_args()
gnomeprint.ui.FontPreview — FontPreview object for GnomePrintui class gnomeprint.ui.FontPreview(gtk.Widget): gnomeprint.ui.FontPreview() def set_color(color) def set_font(font) def set_phrase(phrase) +-- gobject.GObject +-- gtk.Object +-- gtk.Widget +-- gnomeprint.ui.FontPreview gnomeprint.ui.FontPreview() :title title of the window. Returns : a new gnomeprint.ui.FontPreview. Creates a new gnomeprint.ui.FontPreview object. def set_color(color) :color The set_color() method def set_font(color) :font The set_font() method def set_phrase(color) :phrase The set_phrase() method
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
Cover Book Actions Average wait: 40d, 2h USA Today Bestselling BookDanger signs rise off Jase Kayrs like steam--the scars, the secrets, the strength. He's got a mission, and he's not interested in much outside of it. Except Brenna Dunne.Brenna was an ass-kicking,... <a class="more" href="/books/detail/B00CLSVNQE/#editorial-review">more</a> Shadowed (Dark Protectors Book 6) The Old Peabody Pew by Kate Douglas Smith Wiggin : This book is one of the best of Wiggin, Kate Douglas Smith books. If you are one of his fan, make sure you have got this book in hand. This book is showed to be brilliant , literary beautif… more The Old Peabody Pew by Kate Douglas Smith Wiggin Wolf Tales Average wait: N/A This book is an illustrated version of Children’s Rights by Kate Douglas Wiggin. “The subject of Children’s Rights does not provoke much sentimentalism in this country, where, as somebody says, the present problem of the children is the pai… more Children’s Rights : A Book of Nursery Logic (Illustrated) Average wait: N/A This book is an illustrated version of the original The Story of Patsy by Kate Douglas Wiggin. “It was a hard-working and bustling place, but a loving and joyous one — that kindergarten by Silver Street where I was working. I grew to knew … more The Story of Patsy (Illustrated) Kate Douglas Wiggin’s classic Christmas tale with an active table of contents. Old Peabody Pew The Girl Scouts The Romance of a Christmas Card ( Annotated ) : By Kate Douglas Wiggin,COME TO YOUR AUNT LETTY THEN AND BE MOTHERED!” SHE SOBBED,”I NEVER THOUGHT OF THEM AS MY CHILDREN BEFORE” The Romance of a Christmas Card ( Annotated ) : By Kate Douglas Wiggin Kate Douglas Wiggin (September 28, 1856 - August 24, 1923) was an American children’s author and educator. Mother Carey’s Chickens Average wait: 176d, 2h “Paranormal romance at its best!” —Cynthia EdenIn human form, Terrent Vilks is all male animal—dark, ripped, predatory. As wolf, he’s unforgettably dangerous, unforgettably hot. Yet Maggie can’t remember him. . ..Not even when she lear… more Twisted (Dark Protectors) Dark Master Average wait: N/A This book is an illustrated version of the original Rose O’ the River by Kate Douglas Wiggin. Published in 1905, Rose O’ the River, became a best-seller for Kate Douglas Wiggin. The novel is populated with charming characters, humour and a … more Rose O’ the River (Illustrated) Children’s Books of Kate Wiggin New Chronicles of Rebecca by Kate Douglas Wiggin. This book tells further stories from the period of Rebecca’s sojourn in Riverboro. New Chronicles of Rebecca [Annotated] Unbound (Demon Lovers Book 2) Average wait: N/A Perfect SubmissionHe wants her.He wants to possess her. Now. And her body says yes. Forever.Talen knows the Black Gryffons are the last line of defense against the Chimera. He must marry in order to carry on the family legacy. But findin… more Darkest Ecstasy (Black Gryffon) Average wait: N/A In the erotically charged world of the Harvesters, taking a woman’s virginity is a man’s greatest responsibility-but unleashing her potential for endless pleasure is the greatest of sins… Enslaved By Desire Virile, golden-haired Kerrick p… more Sinful Harvest (Onic Empire) Average wait: 27d, 17h “A new fantastic ORIGINAL paranormal series is born!” –Paranormal CravingsAlong came a spider…When Trish Muffet is attacked at a grisly crime scene, the last person she expects to come to her rescue is Nicky “Little Boy” Blue. But since wal… more Along Came a Spider (Transplanted Tales) Surrender Average wait: N/A “Edgy and intense, infused with sensuality and danger.” —Jayne Ann KrentzShapeshifting creatures of amazing strength and sensuality, the Chanku now live openly all over the world. Yet the primal power of the pack beckons, calling each one … more Dark Moon (Spirit Wild Book 3)
michcauch my-weather-indicator ne fonctionne plus après mise à jour my-weather-indicator ne fonctionne plus, juste après une mise à jour de my-weather-indicator sous 12.04. J'ai ce message d'erreur quand je le lance depuis un terminal : michel@bureau:~$ my-weather-indicator Traceback (most recent call last): File "/usr/bin/my-weather-indicator", line 26, in <module> import gi ImportError: No module named gi michel@bureau:~$ Je l'ai désinstallé et réinstallé, même message. Je l'ai désinstallé, réinstallé, purgé les fichiers de configuration, même message. Une idée ? Dernière modification par michcauch (Le 22/12/2012, à 12:34) Cordialement Michel ___ Ubuntu 14.04 sur Lenovo ThinkPad Edge E320 et Xubuntu 13.10 sur PC fixe. Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour Moi même chose, d'abord ce fut "minimize-unminimise", maintenant "my weather indocator", autant de petits trucs énervants, j'en viens presque à redouter les mises à jour.... (12.04.1 lts) Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour essaye sudo apt-get install python3-gi python3-dbus python3-cairo Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour Merci, ça fonctionne, par contre, quand on tape le lieu pour la recherche, ça ne fonctionne pas. Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour sans message d'erreur je ne peux pas aider Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour Il n'y a pas de message d'erreur, simplement quand on tape le lieu, et qu'on clique "rechercher", ça ne bouge pas, avant ça mettait le lieu sur la carte et on validait, mais là aucune recherche, rien ne bouge sur la carte. Hors ligne michcauch Re : my-weather-indicator ne fonctionne plus après mise à jour Chez moi tout fonctionne bien maintenant, merci ljere. Je passerai le fil en résolu quand DAnGk41 aura résolu son problème. DAnGk41, as-tu réessayé ? Cordialement Michel ___ Ubuntu 14.04 sur Lenovo ThinkPad Edge E320 et Xubuntu 13.10 sur PC fixe. Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour ok DAnGk41 on va vérifier ton sources.list pour commencer cat /etc/apt/sources.list ls /etc/apt/sources.list.d cat /etc/apt/sources.list.d/* Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour daan@daan-desktop:~$ cat /etc/apt/sources.list # deb cdrom:[Ubuntu 12.04 _Precise Pangolin_ - Release i386 (20120930)]/ precise main restricted # 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 ## 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 deb http://liveusb.info/multisystem/depot all main deb-src http://liveusb.info/multisystem/depot all main deb http://download.virtualbox.org/virtualbox/debian precise non-free contrib daan@daan-desktop:~$ daan@daan-desktop:~$ ls /etc/apt/sources.list.d atareao-atareao-precise.list atareao-atareao-precise.list.save atareao-colorgetter-precise.list atareao-colorgetter-precise.list.save f-muriana-ubuntu-builder-precise.list f-muriana-ubuntu-builder-precise.list.save google-earth.list google-earth.list.save hydr0g3n-qbittorrent-unstable-precise.list hydr0g3n-qbittorrent-unstable-precise.list.save ikarosdev-unity-revamped-precise.list ikarosdev-unity-revamped-precise.list.save ojno-unity-minimize-on-click-precise.list ojno-unity-minimize-on-click-precise.list.save otto-kesselgulasch-gimp-precise.list otto-kesselgulasch-gimp-precise.list.save stebbins-handbrake-snapshots-precise.list stebbins-handbrake-snapshots-precise.list.save tualatrix-ppa-precise.list tualatrix-ppa-precise.list.save yannubuntu-boot-repair-precise.list yannubuntu-boot-repair-precise.list.save daan@daan-desktop:~$ daan@daan-desktop:~$ cat /etc/apt/sources.list.d/* deb http://ppa.launchpad.net/atareao/atareao/ubuntu precise main deb-src http://ppa.launchpad.net/atareao/atareao/ubuntu precise main deb http://ppa.launchpad.net/atareao/atareao/ubuntu precise main deb-src http://ppa.launchpad.net/atareao/atareao/ubuntu precise main deb http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main deb-src http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main deb http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main deb-src http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main deb http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main deb-src http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main deb http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main deb-src http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main ### THIS FILE IS AUTOMATICALLY CONFIGURED ### # You may comment out this entry, but any other modifications may be lost. deb http://dl.google.com/linux/earth/deb/ stable main ### THIS FILE IS AUTOMATICALLY CONFIGURED ### # You may comment out this entry, but any other modifications may be lost. deb http://dl.google.com/linux/earth/deb/ stable main deb http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main deb-src http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main deb http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main deb-src http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main # deb http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main # deb-src http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main # deb http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main # deb-src http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main deb http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main deb-src http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main deb http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main deb-src http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main deb http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main deb-src http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main deb http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main deb-src http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main deb http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main deb-src http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main deb http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main deb-src http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main deb http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main deb-src http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main deb http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main deb-src http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main daan@daan-desktop:~$ Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour ça c'est bon maintenant cat ~/.xsession-errors Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour désolé pour le retard à répondre, j'avais des "obligations" ailleurs.... (sol:2897): Gtk-WARNING **: Theme file for default has no name (sol:2897): Gtk-WARNING **: Theme file for default has no directories (sol:2904): Gtk-WARNING **: Theme file for default has no name (sol:2904): Gtk-WARNING **: Theme file for default has no directories (firefox:2910): Gtk-WARNING **: Theme file for default has no name (firefox:2910): Gtk-WARNING **: Theme file for default has no directories (sol:2997): Gtk-WARNING **: Theme file for default has no name (sol:2997): Gtk-WARNING **: Theme file for default has no directories (firefox:3004): Gtk-WARNING **: Theme file for default has no name (firefox:3004): Gtk-WARNING **: Theme file for default has no directories (firefox:3064): Gtk-WARNING **: Theme file for default has no name (firefox:3064): Gtk-WARNING **: Theme file for default has no directories (gnome-terminal:3130): Gtk-WARNING **: Theme file for default has no name (gnome-terminal:3130): Gtk-WARNING **: Theme file for default has no directories (sol:3159): Gtk-WARNING **: Theme file for default has no name (sol:3159): Gtk-WARNING **: Theme file for default has no directories (firefox:3169): Gtk-WARNING **: Theme file for default has no name (firefox:3169): Gtk-WARNING **: Theme file for default has no directories (firefox:3217): Gtk-WARNING **: Theme file for default has no name (firefox:3217): Gtk-WARNING **: Theme file for default has no directories (update-manager:3270): Gtk-WARNING **: Theme file for default has no name (update-manager:3270): Gtk-WARNING **: Theme file for default has no directories (firefox:3376): Gtk-WARNING **: Theme file for default has no name (firefox:3376): Gtk-WARNING **: Theme file for default has no directories (sol:3446): Gtk-WARNING **: Theme file for default has no name (sol:3446): Gtk-WARNING **: Theme file for default has no directories (sol:3457): Gtk-WARNING **: Theme file for default has no name (sol:3457): Gtk-WARNING **: Theme file for default has no directories (firefox:3463): Gtk-WARNING **: Theme file for default has no name (firefox:3463): Gtk-WARNING **: Theme file for default has no directories (sol:3514): Gtk-WARNING **: Theme file for default has no name (sol:3514): Gtk-WARNING **: Theme file for default has no directories (firefox:3561): Gtk-WARNING **: Theme file for default has no name (firefox:3561): Gtk-WARNING **: Theme file for default has no directories (firefox:3633): Gtk-WARNING **: Theme file for default has no name (firefox:3633): Gtk-WARNING **: Theme file for default has no directories (sol:3706): Gtk-WARNING **: Theme file for default has no name (sol:3706): Gtk-WARNING **: Theme file for default has no directories (firefox:3712): Gtk-WARNING **: Theme file for default has no name (firefox:3712): Gtk-WARNING **: Theme file for default has no directories (gnome-terminal:3761): Gtk-WARNING **: Theme file for default has no name (gnome-terminal:3761): Gtk-WARNING **: Theme file for default has no directories daan@daan-desktop:~$ bluetooth-applet:2333): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « ) » daan@daan-desktop:~$ daan@daan-desktop:~$ ** Message: applet now removed from the notification area brother : commande introuvable daan@daan-desktop:~$ daan@daan-desktop:~$ (nautilus:2332): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (nautilus:2332): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (nm-applet:2329): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (nm-applet:2329): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ ** Message: using fallback from indicator to GtkStatusIcon brother : commande introuvable daan@daan-desktop:~$ Initializing opengl options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing decor options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing vpswitch options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing grid options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing gnomecompat options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing resize options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing place options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing animation options...done Initializing : commande introuvable daan@daan-desktop:~$ I/O warning : failed to load external entity "/home/daan/.compiz/session/10d438814843fbd01b13561714577425500000022430038" bash: I/O: Aucun fichier ou dossier de ce type daan@daan-desktop:~$ Initializing session options...done e Initializing : commande introuvable daan@daan-desktop:~$ /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185: GtkWarning: Theme file for default has no name bash: /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185:: Aucun fichier ou dossier de ce type daan@daan-desktop:~$ daan@daan-desktop:~$ gtk.main() > /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185: GtkWarning: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185: » daan@daan-desktop:~$ daan@daan-desktop:~$ gtk.main() > Initializing unitymtgrabhandles options...done bash: Erreur de syntaxe près du symbole inattendu « Initializing » daan@daan-desktop:~$ Initializing move options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing mousepoll options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing workarounds options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing wall options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing wobbly options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing fade options...done Initializing : commande introuvable daan@daan-desktop:~$ compiz (expo) - Warn: failed to bind image to texture bash: Erreur de syntaxe près du symbole inattendu « expo » daan@daan-desktop:~$ Initializing expo options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing ezoom options...done Initializing : commande introuvable daan@daan-desktop:~$ Initializing scale options...done Initializing : commande introuvable daan@daan-desktop:~$ daan@daan-desktop:~$ (compiz:2312): GConf-CRITICAL **: gconf_client_add_dir: assertion `gconf_valid_key (dirname, NULL)' failed bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ Initializing unityshell options...done Initializing : commande introuvable daan@daan-desktop:~$ Setting Update "main_menu_key" Setting : commande introuvable daan@daan-desktop:~$ Setting Update "run_key" Setting : commande introuvable daan@daan-desktop:~$ Setting Update "launcher_opacity" Setting : commande introuvable daan@daan-desktop:~$ Setting Update "icon_size" Setting : commande introuvable daan@daan-desktop:~$ Setting Update "show_desktop_icon" Setting : commande introuvable daan@daan-desktop:~$ daan@daan-desktop:~$ (my-weather-indicator:2336): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (my-weather-indicator:2336): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ ** Message: moving back from GtkStatusIcon to indicator brother : commande introuvable daan@daan-desktop:~$ daan@daan-desktop:~$ (gnome-settings-daemon:2297): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (gnome-settings-daemon:2297): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2573): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2573): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ ** (gnome-screensaver:2582): WARNING **: l'économiseur d'écran est déjà en cours de fonctionnement pour cette session bash: Erreur de syntaxe près du symbole inattendu « gnome-screensaver:2582 » daan@daan-desktop:~$ /opt/libreoffice3.6/program/../ure-link/lib/libstdc++.so.6: version `GLIBCXX_3.4.11' not found (required by /usr/lib/i386-linux-gnu/libproxy.so.1) > Failed to load module: /usr/lib/i386-linux-gnu/gio/modules/libgiolibproxy.so > > ** (nautilus:2332): WARNING **: Error calling current_status: Method "current_status" with signature "" on interface "com.ubuntuone.SyncDaemon.Status" doesn't exist > > > ** (nautilus:2332): CRITICAL **: syncdaemon_status_info_get_online: assertion `SYNCDAEMON_IS_STATUS_INFO (sinfo)' failed bash: Erreur de syntaxe près du symbole inattendu « ( » daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:2757): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:2757): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (soffice:2702): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (soffice:2702): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2897): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2897): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2904): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2904): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:2910): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:2910): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2997): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:2997): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3004): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3004): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3064): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3064): Gtk-WARNING **: Theme file bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (gnome-terminal:3130): Gtk-WARNING **: Theme file for de bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (gnome-terminal:3130): Gtk-WARNING **: Theme file for default has bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3159): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3159 > > > (firefox:3169): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3217): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (fire > > > (update-manager:3270): Gtk-WARNING **: Theme file for def bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (update-manager:3270): Gtk-WARNI bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3376): Gtk-WARNING **: bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3376): Gtk-WARNING **: Th bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3446): Gtk-WARNING **: Th bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3446): Gtk-WARNING **: Theme fil bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3457): Gtk-WARNING **: Them bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3457): Gtk-WARNING **: The bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3463): Gtk-WARNING **: The bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3463): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3514): Gtk-WARNING **: Theme file for bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3514): Gtk-WARNING **: Theme bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3561): Gtk-WARNING **: Theme file for default has no name bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3561): Gtk-WARNING **: Th bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:36 > > > (firefox:3633): Gtk-WARNING **: Theme file for default has no directories bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3706): Gtk-WARNING **: Theme bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (sol:3706): bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3712): Gtk-WARNING **: Theme file f bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (firefox:3712): Gtk-WARNING ** bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (gnome-terminal:3761): Gtk-WARNING bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ (gnome-terminal:3761): Gtk-WARNING ** bash: Erreur de syntaxe près du symbole inattendu « : » daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ daan@daan-desktop:~$ : commande introuvable daan@daan-desktop:~$ Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour c'est incroyable j'ai jamais vu autant d'erreur tu as fait quoi pour avoir autant d'erreur Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour Heu... hihi je suis un peu "cascadeur", et germaine michu était sans doute mon arrière grand mère (mais soit dit en passant, mon buntu fonctionne impec... étonnant non ?) Edit : non en fait il s'agit d'une distro que j'ai un peu transformé avec ubuntu builder, afin d'avoir les logiciels dont je me sers direct à l'install, je pense que ça vient de ça, ces erreurs "no files etc..." je les ai eues en faisant ma distro (mais bon, tant que ça fonctionne hein...) si un jour j'ai un problème sérieux, bin je réinstallerai. Dernière modification par DAnGk41 (Le 22/12/2012, à 16:21) Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour en ce cas la je vois mal comment t'aider Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour bah ! pas grave, my weather indicator fonctionne avec la réinstallation de python 3, le seul problème est que je ne peux pas mettre le lieu exact, il me met le lieu d'où il voit ma connexion (à environ 120 km de chez moi en ce moment) mais bon, la météo se ressemble d'où il me trouve et où je suis, pas trop important. et merci de t'être penché sur mon problème, bonnes fêtes de fin d'année. Hors ligne ljere Re : my-weather-indicator ne fonctionne plus après mise à jour bonnes fêtes de fin d'année à toi aussi Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour Sniff... my-weather-indicator ne fonctionne encore plus après (sans doute) mises à jour Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour bon, ça refonctionne, je l'ai désinstallé, purgé et réinstallé depuis synaptic. Hors ligne Squashfs Re : my-weather-indicator ne fonctionne plus après mise à jour Salut à tous. Il faut choisir " yahoo! " dans Préférences, services météorologiques. Avec " Open Weather Map " ça ne marche pas aujourd'hui. Dernière modification par Squashfs (Le 06/03/2013, à 20:56) Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour Salut à tous. Il faut choisir " yahoo! " dans Préférences, services météorologiques. Avec " Open Weather Map " ça ne marche pas aujourd'hui. Le problème n'était pas là, simplement my-weather-indicator ne voulait tout simplement pas se lancer. Dernière modification par DAnGk41 (Le 06/03/2013, à 21:00) Hors ligne Squashfs Re : my-weather-indicator ne fonctionne plus après mise à jour my-weather-indicator n'arrive pas a se lancer tant qu'il ne reçoit pas les infos météo. C'est pour cela qu'en changeant le service météorologique, tout rentre dans l'ordre. Hors ligne DAnGk41 Re : my-weather-indicator ne fonctionne plus après mise à jour my-weather-indicator n'arrive pas a se lancer tant qu'il ne reçoit pas les infos météo. C'est pour cela qu'en changeant le service météorologique, tout rentre dans l'ordre. Oui mais le problème, c'est que s'il ne se lance pas, je ne vois pas comment aller dans "préférences" pour changer le service météo... Ceci dit, après réinstallation, ça a à nouveau fonctionné sur "open weather map". Hors ligne Squashfs Re : my-weather-indicator ne fonctionne plus après mise à jour Pas besoin de faire une réinstallation, il suffit juste de supprimer le fichier : my-weather-indicator.conf Qui est dans le dossier : /home/user/.config/my-weather-indicator Ensuite quitter et relancer " my-weather-indicator ", ce qui va démarrer une nouvelle configuration de " my-weather-indicator ". Et enfin, il faut choisir son service météorologique préféré. Dernière modification par Squashfs (Le 07/03/2013, à 04:21) Hors ligne grandtoubab Re : my-weather-indicator ne fonctionne plus après mise à jour Salut, Quelques difficultés depuis 2/3 jours, rien avec "Yahoo", pas de prévisions avec "OpenWeather Map". Heureusement que je suis passé par là car en mettant Yahoo ça ne se lançait plus du tout et il m'a fallu supprimer le fichier de configuration: ~/.config/my-weather-indicator$sudo rm my-weather-indicator.conf 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
For some background, this code is part of a larger script. I'm currently using the .boto config file for my creds. I am able to list all buckets using the boto API call as well as create buckets, however, this section of code is giving me some problems, and it looks spot on (the code itself was actually working in a previous version and now it seems to be getting hung up). #!/usr/bin/python import boto from boto.s3.connection import S3Connection conn = S3Connection() n = "zapbucketx" rs = conn.get_all_buckets() for b in rs: if b.name == n: print b.name + n try: conn.delete_bucket('n') print "Bucket did not contian keys and was deleted!" except: print "WARNING: Bucket Contains Keys!" ans = raw_input("Do you want to continue? (y/n)") mod_ans = str(ans.upper()) if mod_ans == 'Y': #print "got here" full_bucket = conn.get_bucket(n) print "[+] Deleting keys..." for key in full_bucket.list(): key.delete() print "[+] Keys deleted, Deleting Bucket" conn.delete_bucket(n) print "[+] Bucket deleted" exit(0) elif mod_ans == 'N': print "No bucket was deleted." exit(0) else: print "Please answer 'y' or 'n'." exit(0) exit(0) else: print "That bucket does not exist!" exit(0) It seems to not be getting past: if b.name == n: As I am getting my own "error" in the "else" statement: print "That bucket does not exist!" I have tried the code on different instances and double checked the creds in the file (but since I can list buckets, it seems it is not a creds issue). Any help would greatly be appreciated, Thanks!
I've split the problem into sub problems... The test to check it is all working as expected: # These are the two lists I want to pair a = [ "apples" , "oranges" , "bananas" , "blueberries" ] b = [ "apples" , "blueberries" , "oranges" , "bananas" ] # This is the expected result expected = [ (0, 0) , (None, 1) , (1, 2) , (2, 3) , (3, None) ] # Test the function gets the correct result assert expected == get_indexes_for_best_pairing(a, b) print("Tests pass!") 1. Create a list of all of the pairs Create a map of the values from list A with the list of the associated indices... def map_list(list): map = {} for i in range(0, len(list)): # Each element could be contained multiple times in each # list, therefore we need to create a sub array of indices if not list[i] in map: map[list[i]] = [] # Add the index onto this sub array map[list[i]].append(i) return map The map would look like... { "apples": [0] , "oranges": [1] , "bananas": [2] , "blueberries": [3] } Find all of the pairs by cross referencing list B... def get_pairs(a, b): map = map_list(a) pairs = [] for i in range(0, len(b)): v = b[i] if v in map: for j in range(0, len(map[v])): pairs.append((map[v][j], i)) return pairs The pairs are as follows... [ (0, 0) , (3, 1) , (1, 2) , (2, 3) ] 2. Get the scores for each pair Simply loop through the pairs and look up the value in the original list: def get_pairs_scores(pairs, a): return [len(a[i]) for i, _ in pairs] 3. Create a list of pairs that each pair excludes For each pair find the other pairs it excludes... def get_pairs_excluded_by_pair(pairs, i): # Check if the context pair excludes the pair, if both of the # pairs indexes are greater or less than the other pair, then # the pairs are inclusive and we will have a positive number, # otherwise it will be negative return [j for j in range(0, len(pairs)) # If the current context pair is also the pair we are comparing # skip to the next pair if i != j and ((pairs[i][0] - pairs[j][0]) * (pairs[i][1] - pairs[j][1]) < 0)] def get_pairs_excluded_by_pairs(pairs): excludes = [] for i in range(0, len(pairs)): excludes.append(get_pairs_excluded_by_pair(pairs, i)) return excludes The pairs_excludes method will return... [ [] , [2, 3] , [1] , [1] ] 4. Calculate the total cumulative score for each pair minus the pairs it excludes Plus the score of the pairs that are excluded by the pairs it excludes... etc, etc. Use a depth first algorithm to traverse a acyclic graph of excludes to get the cumulative score for each pair... This is the meat of what we need to do... def get_cumulative_scores_for_pairs(pairs, excludes, scores): cumulative = [] # For each pair referenced in the excludes structure we create a new # graph which starting from that pair. This graph tells us the total # cumulative score for that pair for i in range(0, len(pairs)): score = 0 # Keep a reference of the nodes that have already been checked by # in this graph using a set. This makes the graph acyclic checked = set() checked.add(i) # We keep a note of where we are in the graph using this trail # The pairs relate to the index in the pair_excludes. if pair # first is x and pair second is y it refers to pair_excludes[x][y] trail = [] # We start the current x, y to be the first exclude of the current # start node current = [i, 0] # Sorry, tree traversal... Might not very readable could # be done with recursion if that is your flavour while True: # Get the referenced excluded node if len(excludes[current[0]]) > current[1]: j = excludes[current[0]][current[1]] # We do not want to calculate the same pair twice if not j in checked: # It has not been checked so we move our focus to # this pair so we can examine its excludes trail.append(current) # We mark the pair as checked so that we do # not try and focus on it if it turns up again checked.add(j) current = [j, 0] # We perform a trick here, where when we traverse # down or up a layer we flip the sign on the score. # We do this because the score for pairs that we # exclude need to be subtracted from the score whereas # scores for pairs that we now can include because of # that exclude need to be added to the score. score = -score # It the pair has already been checked, check its # next sibling next time around else: current[1] += 1 # There are no more nodes to check at this level else: # We subtract the cumulative score from the score of the # pair we are leaving. We do this when we traverse back up # to the parent or as the last step of each graph finally # subtracting the total cumulative score from the start node # score. score = scores[current[0]] - score if len(trail): # Pop the next item on the trail to become our context # for the next iteration current = trail.pop() # Exit criteria... The trail went cold else: break # Add the score to the array cumulative.append(score) return cumulative This method should return an array that looks like... [ 6 , -3 , 3 , 3 ] 5. Pick only the best pairs We need to then store the index with the score so that we can sort on score without losing the index.Sort the cumulative scores in order we create a list of the indices indices... # Sort pairs by score retaining the index to the pair arr = sorted([(i, cumulative[i]) for i in range(0, len(cumulative))], key=lambda item: item[1]) It looks like... [ (1, -3) , (2, 3) , (3, 3) , (0, 6) ] Pick the top scoring items deleting the excluded items as we go, this way we retain the best pairs and discard the worst... def get_best_pairs(a, b): pairs = get_pairs(a, b) excludes = get_pairs_excluded_by_pairs(pairs) scores = get_pairs_scores(pairs, a) cumulative = get_cumulative_scores_for_pairs(pairs, excludes, scores) # Sort pairs by score retaining the index to the pair arr = sorted([(i, cumulative[i]) for i in range(0, len(cumulative))], key=lambda item: item[1]) # Work through in order of scores to find the best pair combination top = [] while len(arr): topitem = arr.pop() top.append(topitem[0]) # Remove the indices that are excluded by this one arr = [(i, score) for i, score in arr if i not in excludes[topitem[0]]] # Sort the resulting pairs by index return sorted([pairs[i] for i in top], key=lambda item: item[0]) Our top list would look like, where the pair with the index 1 has been dropped because it was low scoring and excluded by higher scoring pairs... [ (0, 0) , (1, 2) , (2, 3) ] 6. Build the result Sort the selected pairs and build the result by incrementing each index to the next pair. When we run out of pairs increment until we reach the end of each list... def get_indexes_for_best_pairing(a, b): pairs = get_best_pairs(a, b) result = []; i = 0 j = 0 next = None pair = None while True: # This is the first loop or we just dropped a pair into the result # vector so we need to get the next one if next == None: # Get the next pair and we will increment the index up to this if len(pairs): next = pairs.pop(0) pair = next # No more pairs increment the index to the end of both lists else: next = (len(a), len(b)) pair = None # We increment the index of the first list first if i < next[0]: result.append((i, None)) i += 1 # We increment the index of the second list when first has reached # the next pair elif j < next[1]: result.append((None, j)) j += 1 # If both indexes are fully incremented up to the next pair and we # have a pair to add we add it to the result and increment both # clearing the next parameter so we get a new one next time around elif pair != None: result.append((pair[0], pair[1])); i += 1 j += 1 next = None # We reached the end else: break return result And finally our result would look like... [ (0, 0) , (None, 1) , (1, 2) , (2, 3) , (3, None) ]
I've written a small plugin that does this. Put this code under "Packages/User/BatchTabToSpaceFixer.py": import sublime import sublime_plugin class BatchTabToSpaceFixerCommand(sublime_plugin.TextCommand): def run(self, view): self.run_all_views() # self.run_current_view() def is_enabled(self): return len(sublime.active_window().views()) > 0 def run_all_views(self): for view in sublime.active_window().views(): self.process(view) def run_current_view(self): self.process(sublime.active_window().active_view()) def process(self, view): # Previous tab size view.run_command('set_setting', {"setting": "tab_size", "value": 3}) # This trick will correctly convert inline (not leading) tabs. view.run_command('expand_tabs', {"set_translate_tabs": True}) # This will touch inline tabs view.run_command('unexpand_tabs', {"set_translate_tabs": True}) # This won't # New tab size view.run_command('set_setting', {"setting": "tab_size", "value": 4}) view.run_command('expand_tabs', {"set_translate_tabs": True}) Then open your project files that you want to be processed. The plugin will process open tabs and leave them dirty. You can do a "Save All" once you think everything is OK. Don't forget to edit your previous and new tab size in the code. For example my case was from 3 (as tab) to 4 (spaces). In such a case this plugin will correctly preserve vertical inline (not leading) alignments that were made using tabs. If you wish, you can assign a shortcut key for this job: {"keys": ["ctrl+alt+t"], "command": "batch_tab_to_space_fixer"}
bisk8 Re : [HOW TO] adesklets : configuration des desklets Bonjour, Alors la je commence a désespérer avec le adesklets: volume.py C'est le seul que je n'arrive pas a faire marcher, tous les autres sont ok. Lorsque je le lance en test python ./chemin/du/script/volume.py --nautilus puis touche t il se lance, n'est pas affiché a l'ecran, apparait bien dans les processus. c'est seulement quand je le tue avec Ctrl+C qu'il me renvoie l'erreur suivante: Now testing... ============================================================ If you do not see anything (or just an initial flicker in the top left corner of your screen), try `--help', and see the FAQ: `info adesklets'. ============================================================ ^CTraceback (most recent call last): File "./.fvwm/aDesklets/marche_pas/volume-0.0.8/volume.py", line 588, in <module> Events(dirname(__file__)).pause() File "./.fvwm/aDesklets/marche_pas/volume-0.0.8/volume.py", line 45, in __init__ self.id = adesklets.get_id() File "/usr/lib/python2.5/site-packages/adesklets/commands.py", line 94, in get_id return comm.out() File "/usr/lib/python2.5/site-packages/adesklets/commands_handler.py", line 93, in out output=self.__comm.out(.01) File "/usr/lib/python2.5/site-packages/adesklets/communicator.py", line 87, in out rd, wr, ex = select.select([self.__stdout],[],[],delay) KeyboardInterrupt Exception exceptions.IOError: (32, 'Broken pipe') in <bound method Events.__del__ of <__main__.Events instance at 0x90d58ac>> ignored Quelqu'un aurait il une piste de réfexion, car la je suis un peu perdu depuis 2 jours. Merci bien d'avance, @ bientôt. Hors ligne fonfonsd Re : [HOW TO] adesklets : configuration des desklets bonjour lors de l install quand je tape ./configure j'ai un message me disant fontes@fontes-portable:~/adesklets-0.6.1$ sudo ./configure configure: error: cannot find sources (src/main.c) in . or .. fontes@fontes-portable:~/adesklets-0.6.1$ merci à tous Hors ligne labo16 Re : [HOW TO] adesklets : configuration des desklets Pourquoi passer par ./configure ? Adesklets est directement dans les dépots (via synaptic) depuis le passage à Hardy Hors ligne fonfonsd Re : [HOW TO] adesklets : configuration des desklets oups j'avais pas vu Hors ligne
I don't have an answer regarding CEF, but I had a look at two solutions to package an HTML based desktop app inside a native looking window: Using PySide with Flask is quite easy, just add the following script close to your Flask app.py file and it should work directly: import os, urllib, sys, time, json # import PySide from PySide.QtGui import * from PySide.QtWebKit import * from PySide.QtCore import * # import Flask from app import app as application class WebApp(QThread): def setApplication(self, app, setup_callback): self.application = app self.setup_callback = setup_callback def run(self): self.setup_callback() self.application.run(use_debugger=True, debug=True, use_reloader=False, port=5000) def main(): global web, env # Init Flask server webappThread = WebApp() def setup_callback(): print 'Do something specific here before app start' webappThread.setApplication(application, setup_callback) webappThread.start() # Init QT app app = QApplication(sys.argv) # Setup WebView (WebKit) web = QWebView() web.resize(992, 800) web.setWindowTitle('Application Name') # web.setWindowIcon(QIcon('static/img/icon.png')) qr = web.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) web.move(qr.topLeft()) web.setUrl('http://127.0.0.1:5000/') # Bind shut down def shutdown(): webappThread.quit() app.aboutToQuit.connect(shutdown) # Start up web.show() sys.exit(app.exec_()) if __name__ == '__main__': main() It opens a window with your HTML displayed in it using Webkit. The problem that I found is that the result look not as good as on a modern web browser meaning that the results was pixelized and slow. However, if this looks OK for you than you have one solution ;) I am now trying to see if can make python to communicate with node-webkit which looks very promising. I have asked a question here re this but I did not get any answer. If you are interested, have a look at this example. I couldn't not make it work, but it definitely looks promising.
raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Je ne faisait aucune allusion au problème de @souen. Dernière modification par raspouillas (Le 15/06/2012, à 20:37) ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] alors voici la première partie du script et la j'ai besoin d'aide car je ne suis sure de rien ]#!/usr/bin/python # encoding: utf-8 from BeautifulSoup import BeautifulSoup import urllib2 import re import time import sys import mechanize# est ce que je peux mette ces 3 lignes sur 1 seul? ignoreList = ( 'compteur des leve tot', )# pourquoi on utilise """ au lieu d'un simple "en début et fin et ne peut on simplifié la phrase? class Day: """un jours dure de 5h à 9h du matin exclu ([5h:9h[) il contient la dernière entrée (points) de ce jour pour chaque joueurs""" def __init__(self): self.entries={} def __str__(self): for entry in self.entries.items(): print entry,'+',entries[entry]# c'est normal que ce def n'est pas aligné aux autres?def utcFrance(): return 1 + time.localtime(time.time())[-1] #1 + 1 si on est a l'heure d'été # ici je crois qu'on doit modifier en def __init__(self,tuple=(5,9),utc=utcFrance()):class Date: def __init__(self,tuple=(20,0),utc=utcFrance()): self.h = (int(tuple[0])-utcFrance()+24+utc)%24 self.m = int(tuple[1]) def __cmp__(self, other): return cmp(self.points(),other.points()) def points(self): pts = {5: 10, 6: 6, 7: 3, 8: 1} return pts.get(self.h, 0) si vous avez les réponses ou d'autres suggestions je vous écoute merci Hors ligne Pylades Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] # est ce que je peux mette ces 3 lignes sur 1 seul? Oui, mais c’est mieux sur trois lignes. # pourquoi on utilise """ au lieu d'un simple "en début et fin et ne peut on simplifié la phrase? Pour pouvoir écrire cette docstring sur plusieurs lignes si besoin. On peut reformuler sans impacter le fonctionnement du programme. # c'est normal que ce def n'est pas aligné aux autres? Oui, faut pas toucher. # ici je crois qu'on doit modifier en def __init__(self,tuple=(5,9),utc=utcFrance()): Possible, mais c’est probablement plus compliqué… ce compteur est presque immaintenable. Mais bon, dans un futur plus ou moins proche, on va refaire un compteur propre pour le TdCT. Du coup, il s’adaptera ici en un clin d’œil. Dernière modification par Πυλάδης (Le 15/06/2012, à 18:49) “Any if-statement is a goto. As are all structured loops. “And sometimes structure is good. When it’s good, you should use it. “And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.” Linus Torvalds – 12 janvier 2003 Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Mais bon, dans un futur plus ou moins proche, on va refaire un compteur propre pour le TdCT. Du coup, il s’adaptera ici en un clin d’œil. c'est marrant nesthib m'a dit la même chose mais quand personne le sais .... donc en attendant si on veut bien continuer à m'aider j’apprends le python et j'arriverai peut être à avoir un compteur viable en attendant un compteur plus maintenable et en phase avec python 2.7.3 alors que le script de tshirtman est prévu pour du python 2.6.* /me est donc décidé à persévérer Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] peux t'on me dire que fait (veut dire) cette partie if ( (str_date.split(' ')[0] in ['Hier'] and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5,24)) or (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5)) ): Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] [ /me est donc décidé à persévérer /me t'encourage vivement, et j'espère que le truc grec t'a donné de vrais conseils hors forum, cause que vu d'ici, cette intervention est aussi péremptoire qu'inutile. Perso, je ne peux que te soutenir et te souhaiter de nous faire "the compteur des Lts" qui sera adapté au Cts. Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] répondu golgoth42 Floyd Pepper merci pour les encouragements, par contre continu de poster le tien j'en ai besoin pour mes test Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 'jour Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] bonjour tout le monde Hors ligne souen Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Hello bonjour Tu es programmé, mais tu es libre. Ubuntu Studio "Si il n'y a pas de solution, c'est qu'il n'y a pas problème !" (sagesse Shadok) Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Salutatous par Toutatis! Un vrai ennemi ne te laissera jamais tomber. En ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] bonjour .... raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] PS: Je n'ai de retour de réponse ? Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] ... bonjour ! Une seconde, on est samedi @ljere: spli permet de séparer une chaine en n morceaux séparés par le caractère donné. En prenant la date affichée : Hier à 21:19 ou Aujourd'hui à 08:56 on obtient alors un tableau du type [0] => "Hier", [1] => "à", [2] => "21:19" Ensuite le triple split, resplite la chaine et utilise le 3eme élément pour tenter d'en extraire l'heure. le split avec '<' est inutile dans ce cas, il a du être rajouté à une époque lointaine (ancien forum ?). On obtient donc un seul élément égal au 3eme élément déjà pris en compte ("21:19"), puis on split par le ":" pour obtenir l'heure et on s'intéresse aux heures comprises entre 5 et 24. Le deuxième partie s'intéresse aux heures entre 0 et 5. Au final, tu obtiens donc les informations pour les dernières 24 heures, et on peut, dès lors, supposer que le compteur se lance tous les jours à 5h00 du matin PS: j'ai pas répondu en mp : c'était déjà fait, et puis ça peut en intéresser d'autres Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] donc comme pour nous on s’intéresse à une période de 6h à 9h if ( (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split(':')[6]) in range(8)) ): comme 9h est exclu je doit bien mettre 8? Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 1 1787 FloydPepper 2 1543 pierguiard 3 1463 MdMax 4 1247 Azurea 5 1199 souen 6 968 Ras&#039; 7 767 raspouillas 8 552 Arcans 9 428 peterp@n 10 359 golgoth42 11 293 mindiell 12 277 omc 13 219 Πυλάδης 14 176 pololasi 15 117 edge_one 16 101 nathéo 17 99 karameloneboudeplus 18 61 agarwood 19 60 Niltugor 20 52 1101011 20 52 jeyenkil 20 52 ljere 23 43 Crocoii 24 42 nakraïou 24 42 DaveNull 26 40 Biaise 27 39 Clem_ufo 28 38 Atem18 29 22 marinmarais 30 18 Ju 31 13 Le grand rohr sha 32 10 Phoenix 32 10 FLOZz 32 10 sakul 32 10 SopolesRâ 36 6 wiscot 36 6 timsy 36 6 Slystone 36 6 Hibou57 36 6 tshirtman 36 6 marting 36 6 c4nuser 43 4 Morgiver 43 4 :!pakman 45 3 Phoenamandre 45 3 gonzolero 45 3 helly 45 3 Le Rouge 49 1 herewegoagain 49 1 TheUploader 49 1 Kyansaa 49 1 Xiti29 Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne Ras&#039; Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] J'me réveille -__________-' C'est trop tard pour les points ? Va t'faire shampouiner en GMT-4 ! http://blag.xserver-x.org/ Les types awesome n'ont rien à prouver. À personne. En ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] J'me réveille -__________-' C'est trop tard pour les points ? nan tu es en avance pour demain! En ligne Ras&#039; Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Va détourer ton avatar au lieu de te moquer ! Va t'faire shampouiner en GMT-4 ! http://blag.xserver-x.org/ Les types awesome n'ont rien à prouver. À personne. En ligne Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] donc comme pour nous on s’intéresse à une période de 6h à 9h if ( (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split(':')[6]) in range(8)) ): comme 9h est exclu je doit bien mettre 8? En fait j'aurai plutôt mis ça : if ( (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split(':')[0]) in range(5,8)) ): Car : - je ne sais pas pourquoi tu mets 6 au lieu de 0 dans le tableau : quand tu coupes 05:34 en chaines par rapport à ":", tu obtiens un tableau de deux éléments : "0" => "05", "1" => "34" - Il faut s'occuper uniquement de 5 à 8 heures Voilà PS: Ah oui, ça à l'air facile python ou pas ? Hors ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Bonjour ... ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] bonjour ... Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] @Mindiell ce n'est pas facile mais c'est intéressant encore merci pour tes conseils et explications Hors ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 'jour Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne
The REST of the Web Pages: 1, 2 Adding Velocity to the Mix Velocity is a templating engine I've written about before, and including a template engine with Jython makes a big difference in simplifying development. To use Velocity with Jython, we'll need to add a few more .jar files to Jetty's ext directory: log4j, Velocity and commons-collections. Also, Velocity will not work out-of-the-box with Jython-generated objects, so we need to customize the Velocity engine slightly. JythonUberspect is the customizer in question, and should be compiled into a .jar and also added to $JETTY_HOME/ext as well. To make your life easier, I've created the jyvel.jar file for you (which just contains JythonUberspect.java and the class files it produces when compiled) and can be found with the sample code. See Resources. Once JythonUberspect has been included, we can modify enhancedservlet as follows, adding an init method: from javax.servlet.http import HttpServlet from org.apache.velocity.app import VelocityEngine from org.apache.velocity.tools.\ generic.introspection import JythonUberspect class enhancedservlet(HttpServlet): ve = None def init(self, config=None): if config: HttpServlet.init(self, config) else: HttpServlet.init(self) if enhancedservlet.ve is None: ve = VelocityEngine() ve.setProperty(VelocityEngine.\ FILE_RESOURCE_LOADER_PATH, self.getServletConfig().\ getServletContext().getRealPath('/') \ + '/WEB-INF/templates') ve.setProperty(VelocityEngine.\ FILE_RESOURCE_LOADER_CACHE, 'true') ve.setProperty('input.encoding', 'UTF-8') ve.setProperty(VelocityEngine.\ RUNTIME_LOG_LOGSYSTEM_CLASS, 'org.apache.velocity.runtime.log.\ SimpleLog4JLogSystem') ve.setProperty(\ 'runtime.log.logsystem.log4j.category', VelocityEngine.getName()) ve.setProperty(VelocityEngine.\ UBERSPECT_CLASSNAME, JythonUberspect.getName()) ve.init() enhancedservlet.ve = ve One point to note in this excerpt is that ve is a variable of the class, and therefore similar to a Java static. So rather than creating a new Velocity engine per servlet, we'll have one global engine. Templates are served from a templates directory in WEB-INF (i.e., ${YOUR_WEBAPP_DIR}/WEB-INF/templates). Keeping them in the WEB-INF directory keeps nosy surfers out of your template code. The completed enhancedservlet can be found in the sample code. RESTified Servlets Now I want to create a (reasonably) standards-compliant servlet, using the correct HTTP methods for my operations. I'll start with a simple screen to display a data list, and then a screen to display a single record in editable form. list.vm (see Resources) is the template for displaying lists of my data: <html> <body> <table border="1"> #foreach ( $row in $rows ) <tr> #foreach ( $col in $row.cols ) <td> #if ( $col == $row.key ) <a href="test5.py?key=${col}"> ${col}</a> #else${col}#end</td> #end </tr> #end </table> <a href="test5.py?key=None">Add</a> </body> </html> You'll notice that I have a $rows object (which is a list), and each $row object has attributes for columns and its key. If the column matches the key, then I create a link for editing that row using the column value. edit.vm is the template for editing a row of data: <html> <head> <body> <form action="test5.py" method="POST"> <table border="1"> #foreach ( $col in $obj.cols ) <tr> <td>Column #${velocityCount}</td> <td> <input name="col${velocityCount}" type="text" #if ( $col == $obj.key ) disabled="disabled" #end value="${col}" /></td> </tr> #end </table> <br /> <input type="hidden" name="key" value="${obj.key}" /> <input type="hidden" name="method" value="${method}" /> <input type="submit" value="Save" /> </form> #if ( $method == 'POST' ) <form action="test5.py" method="GET"> <input type="hidden" name="key" value="${obj.key}" /> <input type="hidden" name="method" value="DELETE" /> <input type="submit" value="Delete" /> </form> #end <form action="test5.py" method="GET"> <input type="submit" value="Cancel" /> </form> </body> </html> This displays the data columns, disabling the key value so it can't be edited. While I could use JavaScript to modify a form parameter for overriding the method, in this case I use multiple forms. The first gets a method parameter, which is passed from the servlet depending upon whether this is an existing record (therefore an UPDATE or doPost) or a new record (an INSERT or doPut). The second form--only displayed if this is an existing record, and therefore with the method set to POST--has the method override parameter set to DELETE, while the last is just a call back to the servlet with no parameters so we can display the list again. The servlet (with the file name test5.py) looks like this, so far: from javax.servlet.http import HttpServlet from org.apache.velocity import VelocityContext from utils import * # a simple data object with a key and some columns class dataobj: def __init__(self, key, cols): self.key = key self.cols = cols global sequence sequence = 1 # a map containing data objects mydata = { } # prepopulate with a few rows for sequence in xrange(1, 4): mydata['row%s_key' % sequence] = dataobj('row%s_key' % sequence, [ 'row%s_key' % sequence, 'row%s_col2' % sequence, 'row%s_col3' % sequence ]) class test5(enhancedservlet): def doGet(self, request, response): ctx = VelocityContext() key = request.getParameter('key') if key: t = enhancedservlet.ve.\ getTemplate('edit.vm') if key != 'None': ctx.put('obj', mydata[key]) ctx.put('method','POST') else: ctx.put('obj', dataobj('None', [ 'None', '', '' ])) ctx.put('method','PUT') else: t = enhancedservlet.ve.\ getTemplate('list.vm') ctx.put('rows', mydata.values()) response.setContentType(\ 'text/html;charset=UTF-8') pw = response.getWriter() t.merge(ctx, pw) pw.close() From the code above you can see that if the parameter key is present we use the template edit.vm; otherwise, we use list.vm. The Velocity context is populated with data depending upon whether key is an actual key value or set to None. In the case of None, we construct a blank data object and put that in the context. This much allows us to display a list of rows, and display a single row for editing. Next I'll implement a doDelete method: def doDelete(self, request, response): key = request.getParameter('key') if not key or key == '': response.sendError(\ response.SC_BAD_REQUEST, 'no key specified') return if not mydata.has_key(key): response.sendError(response.SC_NOT_FOUND, '%s was not found' % key) return del mydata[key] wrappedrequest = modifiablerequest(request) wrappedrequest.delParameter('key') self.doGet(wrappedrequest, response) This method performs some simple validation (checking for the presence of a key parameter, and checking for the existence of that key), before deleting the data from the map. modifiablerequest (also found in utils.py) is a subclass of HttpServletRequestWrapper, and provides set and delete parameter methods, so a request may be modified and then pushed on to another method for processing. (In the above example, we perform the delete, then pass the request on to doGet after deleting the parameter key, so that doGet displays the main data list.) The doPut method again performs some simple validation (also checking for the existence of a key parameter), before creating a data object and then adding it to the map. Again, processing is passed on to doGet: def doPut(self, request, response): key = request.getParameter('key') if key and key != 'None': response.sendError(\ response.SC_BAD_REQUEST, 'there is an existing key') return # generate a new key global sequence sequence = sequence + 1 key = 'row%s_key' % sequence # create the data object data = dataobj( key, [ key, request.getParameter('col2'), request.getParameter('col3') ]) mydata[key] = data wrappedrequest = modifiablerequest(request) wrappedrequest.delParameter('key') self.doGet(wrappedrequest, response) Finally, the doPost method checks for the existence of a key, and updates the requisite data object, before calling doGet: def doPost(self, request, response): key = request.getParameter('key') if not key or key == 'None' or \ not mydata.has_key(key): response.sendError(\ response.SC_BAD_REQUEST, 'invalid or missing key') return data = mydata[key] data.cols[1] = request.getParameter('col2') data.cols[2] = request.getParameter('col3') wrappedrequest = modifiablerequest(request) wrappedrequest.delParameter('key') self.doGet(wrappedrequest, response) Figures 1 to 3 show the final result when running the Jython servlet under Jetty. Figure 1 shows the initial list of data rows provided by the doGet, Figure 2 shows the edit screen when adding a record, and Figure 3 shows the list screen again after the row has been added. Figure 1. The list data screen Figure 2. The edit screen Figure 3. Back to the list screen with a new row Conclusion This is a simple example, but hopefully gives you some idea of the flexibility of this approach. There is a clean delineation of operations and responsibilities within the servlet: Velocity gives you a nice separation of view and, combined with Jython, gives the flexibility of rapid web development. The amount of code you are required to write for a typical web app, particularly traditional GET/POST servlets handling a variety of different operations, can be prodigious, so sticking to the HTTP protocol does force you to cut to the essentials. But certainly, in my experience, simplifying your code to basic HTTP operations does not necessarily mean losing functionality for your end users, and it can help focus your efforts on the important fundamentals. Resources Sample code for this article Better, Faster, Lighter Java The Pragmatic Programmer Jython Essentials Jason R. Briggs is an architect/developer working in the United Kingdom. Return to ONJava.com.
i am also working in python 2.6 and i want to send SMS to a mobile while my cell phone i.e. Nokia E-72 is connected to PC via Data Cable. The mobile is connected through a serial port and the code prompts the correct port as well and there is no error in the code but still the message is not being sent... Please help me for the issue. My code is as follows: enter code here import serial import time phone = serial.Serial() phone.baudrate = 38400 phone.bytesize = 8 phone.stopbits = 1 phone.xonxoff = 0 phone.rtscts = 0 phone.timeout = 0 phone.port = 4 #try different ports here, if this doesn't work. phone.parity=serial.PARITY_NONE phone.open() print phone.portstr recipient = "+923219409998" message = "We did it!" try: time.sleep(0.5) phone.write(b'ATZ\r') time.sleep(0.5) phone.write(b'AT+CMGF=1\r') time.sleep(0.5) phone.write(b'AT+CMGS="' + recipient.encode() + b'"\r') time.sleep(0.5) phone.write(message.encode() + b"\r") time.sleep(0.5) phone.write(bytes([26])) time.sleep(0.5) phone.readall() finally: phone.close()
I've written a function that should return a list of column numbers that correspond to specific variables I'd like to extract later on from a csv file. The variable names are specified by state_aggregate_vars. import csv import numpy def compute_countyStats(state_aggregate, year, state_aggregate_vars, listCounties, county_var, int_obese, int_healthy, int_refuse): : f = open(state_aggregate, 'r') readit = csv.reader(f) headers = readit.next() use_cols = [] for name in state_aggregate_vars: use_cols.append(headers.index(name)) return use_cols county_data = numpy.genfromtxt(f, dtype=float, delimiter=',', names = state_aggregate_vars, filling_values= -1, usecols= use_cols, usemask=False) sorted_array = county_data(numpy.argsort(county_data, axis= headers.index(county_var)) for code in listCounties: temp = [] for entry in sorted_array: if entry[0] == code: temp.append(float(entry[1])) else: continue percent_healthy = numpy.true_divide(temp.count(int_healthy),num_obs) percent_obese = numpy.true_divide(temp.count(int_obese),num_obs) percent_refused = numpy.true_divide(temp.count(int_refuse),num_obs) county_stats[code] = year, code, percent_healthy, percent_obese, percent_refused, return county_stats Next, I call this function using the following: state_aggregate = "Aggregate_test90.csv" year = 1990 state_aggregate_vars = ['_BMI90', 'AGE90', 'CTYCODE90', 'IYEAR90', 'SEX90', '_RFOBESE90'] listCounties = [31, 43, 163, 32, 167, 97] county_var = 'CTYCODE90' int_obese = 2 int_healthy = 1 int_refuse = 0 test = compute_countyStats(state_aggregate, year, state_aggregate_vars, listCounties, county_var, int_obese, int_healthy, int_refuse) Here is my error: SyntaxError: invalid syntax in line 6: for name in state_aggregate_vars: What could be going wrong? Here is my python -V: Python 2.7.3 -- EPD 7.3-2 (32-bit)
This is not homework! Simply example to complex problem. Right now I take arrays, create vectors, then use equation with vectors as inputs. Everything works fine. But, wondering if I could skip vector creation and use the array slicing to the samething. import numpy as np a = [[ 7., 5.], [ 9., 3.], [ 7., 2.], [ 7., 8.], [ 6., 8.], [ 3., 2.]] a = np.asarray(list(a), np.float) x = np.asarray(a[:,(0)], np.float) y = np.asarray(a[:,(1)], np.float) foo = 5*x+y*y print foo
If d = date(2011, 1, 1) is in UTC: >>> from datetime import datetime, date >>> import calendar >>> timestamp1 = calendar.timegm(d.timetuple()) >>> datetime.utcfromtimestamp(timestamp1) datetime.datetime(2011, 1, 1, 0, 0) If d is in local timezone: >>> import time >>> timestamp2 = time.mktime(d.timetuple()) >>> datetime.fromtimestamp(timestamp2) datetime.datetime(2011, 1, 1, 0, 0) timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC. To convert datetime.date object that represents date in UTC without calendar.timegm(): timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60 How can I get a date converted to seconds since epoch according to UTC? To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float). Python 3.3+ datetime.timestamp(): timestamp = dt.replace(tzinfo=timezone.utc).timestamp() Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone. Python < 3.3 From the docs for datetime.utcfromtimestamp(): There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) And for an aware dt: timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1) Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed? See also: datetime needs an "epoch" method Python 2 To adapt the above code for Python 2: timestamp = (dt - datetime(1970, 1, 1)).total_seconds() where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled. from datetime import datetime, timedelta def totimestamp(dt, epoch=datetime(1970,1,1)): td = dt - epoch # return td.total_seconds() return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 1e6 now = datetime.utcnow() print now print totimestamp(now) Output 2012-01-08 15:34:10.022403 1326036850.02
Using SAX for Proper XML Output In an earlier Python and XML column I discussed ways to achieve proper XML output from Python programs. That discussion included basic considerations and techniques in generating XML output in Python code. I also introduced a couple of useful functions for helping with correct output: xml.sax.saxutils.escape from core Python 2.x and Ft.Xml.Lib.String.TranslateCdata from 4Suite. There are other tools for helping with XML generation. In this article I introduce an important one that comes with Python itself. Generating XML from Python is one of the most common XML-related tasks the average Python user will face; thus, having more than one way to complete such a common task is especially helpful. Pushing SAX Probably the most effective general approach to creating safe XML output is to use SAX more fully than just cherry-picking xml.sax.saxutils.escape. Most users think of SAX as an XML input system, which is generally correct; because, however, of some goodies in Python's SAX implementation, you can also use it as an XML output tool. First of all, Python's SAX is implemented with objects which have methods representing each XML event. So any code that calls these methods on a SAX handler can masquerade as an XML parser. Thus, your code can pretend to be an XML parser, sending events from the serialized XML, while actually computing the events in whatever manner you require. On the other end of things, xml.sax.XMLGenerator, documented in the official Python library reference, is a utility SAX handler that comes with Python. It takes a stream of SAX events and serializes them to an XML document, observing all the necessary rules in the process. You might have gathered from this description how this tandem of facilities leads to an elegant method for emitting XML, If not, listing 1 illustrates just how this technique may be used to implement the code pattern from the earlier XML output article (that is, creating an XML-encoded log file). Listing 1 (listing1.py): Generating an XML log file using Python's SAX utilities import time from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesNSImpl LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR'] class xml_logger: def __init__(self, output, encoding): """ Set up a logger object, which takes SAX events and outputs an XML log file """ logger = XMLGenerator(output, encoding) logger.startDocument() attrs = AttributesNSImpl({}, {}) logger.startElementNS((None, u'log'), u'log', attrs) self._logger = logger self._output = output self._encoding = encoding return def write_entry(self, level, msg): """ Write a log entry to the logger level - the level of the entry msg - the text of the entry. Must be a Unicode object """ #Note: in a real application, I would use ISO 8601 for the date #asctime used here for simplicity now = time.asctime(time.localtime()) attr_vals = { (None, u'date'): now, (None, u'level'): LOG_LEVELS[level], } attr_qnames = { (None, u'date'): u'date', (None, u'level'): u'level', } attrs = AttributesNSImpl(attr_vals, attr_qnames) self._logger.startElementNS((None, u'entry'), u'entry', attrs) self._logger.characters(msg) self._logger.endElementNS((None, u'entry'), u'entry') return def close(self): """ Clean up the logger object """ self._logger.endElementNS((None, u'log'), u'log') self._logger.endDocument() return if __name__ == "__main__": #Test it out import sys xl = xml_logger(sys.stdout, 'utf-8') xl.write_entry(2, u"Vanilla log entry") xl.close() I've arranged the logic in a class that encapsulates the SAX machinery. xml_logger is initialized with an output file object and an encoding to use. First I set up an XMLGenerator instance which will accept SAX events and emit XML text. I immediately start using it by sending SAX events to initialize the document and create a wrapper element for the overall log. You should not forget to send startDocument. In opening the top-level element, logs, I use the namespace-aware SAX API, even though the log XML documents do not use namespaces. This is just to make the example a bit richer, since the namespace-aware APIs are more complex than the plain ones. You ordinarily don't have to worry about how the instances of attribute information are created, unless you're writing a driver, filter, or any other SAX event emitter such as this one. Unfortunately for such users, the creation APIs for the AttributesImpl and AttributesNSImpl classes are not as well documented as the read APIs. It's not even clear whether they are at all standardized. The system used in the listing does work with all recent Python/SAX and PyXML SAX versions. In the case of the namespace-aware attribute information class, you have to pass in two dictionaries. One maps a tuple of namespace and local name to values, and the other maps the same to the qnames used in the serialization. This may seem a rather elaborate protocol, but it is designed to closely correspond to the standard read API for these objects. In the initializer in the listing I create an empty AttributesNSImpl object by initializing it with two empty dictionaries. You can see how this works when there are actually attributes by looking in the write_entry method. Once the AttributesNSImpl object is ready, creating an element is a simple matter of calling the startElementNS method on the SAX handler using the (namespace, local-name), qname convention and attribute info object. And don't forget to call the the endElementNS method to close the element. In the initializer of xml_logger, closing the top-level element and document itself is left for later. The caller must call the close method to wrap things up and have well-formed output. The rest of the xml_logger class should be easy enough to follow. The character of SAX In the last article on XML output I walked through all the gotchas of proper character encoding. This SAX method largely frees you from the worry of all that. The most important thing to remember is to use Unicode objects rather than strings in your API calls. This follows the principle I recommended in the last article: In all public APIs for XML processing, character data should be passed in strictly as Python Unicode objects. There are in fact a few areas where simple, ASCII only strings are safe: for example, output encodings passed to the initializer of XMLGenerator and similar cases. But these areas are unusual. Listing 2 demonstrates a use of the xml_logger class to output a more interesting log entry. from listing1 import xml_logger import cStringIO stream = cStringIO.StringIO() xl = xml_logger(stream, 'utf-8') xl.write_entry(2, u"In any triangle, each interior angle < 90\u00B0") xl.close() print repr(stream.getvalue()) I use cStringIO to capture the output as a string. I then display the Python representation of the output in order to be clear about what is produced. The resulting string is basically (rearranged to display nicely here): <?xml version="1.0" encoding="utf-8"?> <log><entry level="ERROR" date="Sat Mar 8 08:55:11 2003"> in any triangle, each interior angle &lt; 90\xc2\xb0 </entry></log> You can see that the character passed in as "<" has been escaped to "&lt;" and that the character given using the Unicode character escape "\u00B0" (the degree symbol) is rendered as the UTF-8 sequence "\xc2\xb0". If I specify a different encoding for output, as in listing 3, the library will again handle things. Listing 3: Using xml_logger to emit non-ASCII and escaped characters with ISO-8859-1 encoding from listing1 import xml_logger import cStringIO stream = cStringIO.StringIO() xl = xml_logger(stream, 'iso-8859-1') xl.write_entry(2, u"In any triangle, each interior angle < 90\u00B0") xl.close() print repr(stream.getvalue()) Which results in <?xml version="1.0" encoding="iso-8859-1"?> <log><entry level="ERROR" date="Sat Mar 8 09:35:56 2003"> In any triangle, each interior angle &lt; 90\xb0 </entry></log> If you use encodings which aren't in the Unicode or ISO-8859 family, or which are not available in the "encodings" directory of the Python library, you may have to download third-party codecs in order to use them in your XML processing. This includes the popular JIS, Big-5, GB, KS, and EUC variants in Asia. You may already have these installed for general processing; if not, it requires a significant amount of sleuthing right now to find them. Eventually they may be available all together in the Python Codecs project. For now you can download particular codecs from projects such as Python Korean Codecsand Tamito Kajiyama's Japanese codecs (page in Japanese). Other Developments The built-in SAX library is but one of the available tools for dealing with all the complexities of XML output. It has the advantage of coming with Python, but in future columns I will cover other options available separately. Another useful but less common SAX usage pattern is chaining SAX filters. Soon after this article is published, I'll have an article out with more information on using SAX filters with Python's SAX. Watch my publications list to see when it appears. The past month or so has been another busy period for Python-XML development. There has been a lot of discussion of the future direction of the PyXML project. Martijn Faassen made " a modest proposal" for changing the fact that PyXML overwrites the xml module in a Python installation. This led to the Finding _xmlplus in Python 2.3a2 thread in which I proposed that parts of PyXML, pysax, and the dom package (excepting 4DOM) should simply be moved in to the Python core. Discussion of these matters is still proceeding, but if you are interested in the road map for PyXML, you might wish to join the discussion. Francesco Garelli announced Satine, an interesting package which converts XML documents to Python lists of objects which have Python attributes mirroring the XML element attributes, a data structure he calls an "xlist". The package is designed for speed, with key parts coded in C. It also has a web services module which supports plain XML and SOAP over HTTP. Garelli would be grateful for contributors of binary packages on various platforms. Mark Bucciarelli was having problems handling WSDL, which eventually led to his contributing a patch to wsdllib that makes it work with the most recent 4Suite. I'll release an updated version of wsdllib that incorporates this patch. Listing 1 Problems 2003-11-13 09:44:08 J Chik Listing 1 Problems 2003-11-14 06:50:35 Uche Ogbuji 2003-03-14 10:26:32 Matthew Shomphe Scaling... 2003-03-15 13:19:06 Uche Ogbuji
Eric_P Re : TuXtremsplit - Recoller vos fichier .xtm PPPFFFFF !!!! Que n'y ai-je pensé avant, je ne t'aurais pas dérangé. En tout cas merci beaucoup, ça roule maintenant. Super logiciel, merci pour ton travail. Cordialement. Éric. Hors ligne cheetah Re : TuXtremsplit - Recoller vos fichier .xtm @wido Bonjour, je m'adresse à wido : ce post n'a rien à voir avec la discussion : je n'arrive pas à vous contacter par mail car vous n'avez pas activé cette option sur ubuntu, pouvez-vous m'envoyer un mail, j'ai des questions à propos de ce sujet : http://forum.ubuntu-fr.org/viewtopic.php?id=680241 Je vous remercie d'avance Hors ligne ub821 Re : TuXtremsplit - Recoller vos fichier .xtm Bonsoir à Toutes et Tous Comme je souhaite utiliser la compression de documents, autant utiliser tuxtremsplit Voui, mais... il refuse de se lancer ! voici ce qu'il indique : [bernard@bernard-desktop:~] $ tuxtremsplit Warning: The Launchpad Bug Reporter module is not importable ! Traceback (most recent call last): File "/usr/bin/tuxtremsplit", line 57, in <module> txsrouter.start() File "/usr/lib/pymodules/python2.6/tuxtremsplit/core/txsrouter.py", line 77, in start self.launch_main_window() File "/usr/lib/pymodules/python2.6/tuxtremsplit/core/txsrouter.py", line 85, in launch_main_window MainWindow() File "/usr/lib/pymodules/python2.6/tuxtremsplit/mainwindow.py", line 55, in __init__ self.builder.add_from_file(os.path.join(DATA_DIR, "glade", "mainwindow.glade")) glib.GError: /usr/share/tuxtremsplit/data/glade/mainwindow.glade: required gtk+ version 2.24, current version is 2.20 [bernard@bernard-desktop:~] $ Hein que c'est ballot... surtout pour celles et ceux qui savent comment s'en sortir... J'ai bien cherché gtk+, python dans synaptic, et bien sur... rien trouvé en gtk+ 2.20 et 2.24 Merci d'avance pour vos futurs conseils Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne Joyfik Re : TuXtremsplit - Recoller vos fichier .xtm Est-ce le lien des dépôts a changé ? Hors ligne
Fabric: a System Administrator's Best Friend The Basics Now that you understand the groundwork of Fabric, you can start puttingit to use. For this article, I explain how to make asimple fabfile for the purpose of installing/removing software and yourmachines. First, you need what is called a fabfile. The fabfilecontains all of your Fabric functions. By default, it needs to be namedfabfile.py and be in the working directory, but as mentioned previously, you canspecify the fabfile from the command line if need be. So, open your fabfileand start it with from fabric.api import * to include all the Fabricfunctionality. Then define all of your functions. Let's start with installingsome software: def install(pkg=None): if pkg is not None: env["pkg"] = pkg elif pkg is None and env.get("pkg") is None: env["pkg"] = prompt("Which package? ") sudo('yum install -y %s' % env["pkg"]) You then can install a package via yum on all of your machines by running: $ fab --hosts=host1,host2,host3 install Then, you'll be prompted for the package to install only once.Alternatively, since you indicated an optional parameter ofpkg, you canindicate that from the command line so you won't be prompted on execution,like this: $ fab --hosts=host1,host2,host3 install:pkg=wormux or: $ fab --hosts=host1,host2,host3 install:wormux Also note that you are prompted for the password for both SSH and sudo only once. Fabric stores this in memory and reuses it, if possible, for every other machine. Congratulations! You've just successfully created your first Fabric script. It's as simple as that! Tips and Tricks I've picked up some neat tricks since I've started with Fabric. First, you generally never see a Fabric command as simple as what is above. When fully automated, it looks more like this: $ fab --skip-bad-hosts -u user -p 12345 -i ~/.ssh/id_dsa --warn-only &rarrhk;--hosts=host1,host2,host3,host4,host5,host6,host7,host8,host9,host10 &rarrhk;--parallel --pool-size=20 install:pkg=wormux Who wants to type that out every time they want to run a command? No one! That's why aliasing almost all of that is so convenient and efficient. Add the following to your .bashrc file: alias f="fab --skip-bad-hosts -u user -p 12345 -i ~/.ssh/id_dsa &rarrhk;--warn-only &rarrhk;--hosts=host1,host2,host3,host4,host5,host6,host7,host8,host9,host10 &rarrhk;--parallel" Then, all you have to do each time you want to run Fabric is this: $ f install:pkg=wormux Even using this technique, your alias can become cumbersome if you have more than a few machines you commonly administer. A simple solution to that is to add this function to your fabfile: def set_hosts(): env.hosts = open('hosts', 'r').readlines() Then, put all your hostnames in a file called hosts in the same directory as your fabfile, and modify your alias to look like this: alias f="fab --skip-bad-hosts -u user -p 12345 -i ~/.ssh/id_dsa &rarrhk;--warn-only --parallel set_hosts" This is particularly convenient if you have a variety of fabfiles that you use on different groups of machines, or in different contexts. There are occasions when you need to execute certain commands fromwithin a specific directory. Because each command is a discrete andnon-persistent connection to the machine, this is not inherently simple.However, simply by enclosing the necessary commands in awith statement, youhave a solution: with cd("~/gitrepo"): run('git add --all') run('git commit -m "My super awesome automated &rarrhk;commit script for `date`"') More Information There are several ways to get help with Fabric. The most effective is to use the fab-file mailing list. The developers are generally very prompt in responding. There is also a Fabric Twitter account @pyfabric where Fabric news and announcements are released. You can submit and view bugs through the Fabric Github page. Of course, you also can't discount the #fabric channel on Freenode, where you can connect with the community and get some quick answers. Finally, you always can browse the documentation hosted at http://www.fabfile.org. Geolocation Give new life to old phones and tablets with these tips! Lucidchart Memory Ordering in Modern Microprocessors, Part I Linux Systems Administrator Source Code Scanners for Better Code Senior Perl Developer Technical Support Rep Tech Tip: Really Simple HTTP Server with Python Putlocker!! Watch Begin Again Online 2014 Streaming Full Movie
Here's my data model: BlogPost(ndb.Model): title = ndb.StringProperty() body = ndb.TextProperty() author_key = ndb.KeyProperty() Author(ndb.Model): name = ndb.StringProperty() fav_colour = ndb.StringProperty() I am currently on my home page ('/'), and I would like to: query for a list of all BlogPost entities, and query for their respective authors to be displayed alongside a BlogPost entity. I can query for all BlogPosts simply like this: class BlogPostHandler(webapp2.RequestHandler): def get(self): posts = BlogPost.query().fetch() self.render('index.html', posts = posts) #renders in Jinja2 template The Jinja2 index.html template is this: {% for p in posts %} {{p}} {{p's AUTHOR TO BE DISPLAYED HERE. Example: author.name, author.fav_colour}} {% endfor %} So, I would like to know how I can display the Author entity which is associated with each BlogPost entity. Thank you.
mastergb Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour à tous, Suite à l'énorme thread précédent (et à la demande de ljere) , j'aimerais reprendre un sujet vraiment dédié a vpnautoconnect. Le logiciel n'est plus à présenter. On l'aime (ou pas), il permet entre autre de répondre à une lacune du network manager et un besoin grandissant : l'anonymat. Attention: Il ne vous permet pas d'être anonyme mais ameliore juste une fonctionnalité déjà présente sur votre ubuntu préféré. J'essaierais de répondre un maximum aux diverses questions et bugs que vous allez pouvoir me communiquer. Il y a parfois des gens qui répondent parfaitement aux question posés comme bhubuntu. Je ne trouve pas l’intérêt de rajouter quelque chose quand la question est parfaitement traitée par un autre membre du forum mais ça ne veut pas dire que je n'ai pas pris la peine de vous lire. Je suis actuellement overbooké professionnellement mais je vais quand même essayer de dégager du temps pour essayer maintenir un développement régulier. N'oubliez surtout pas de compléter vpnautoconnect avec un firewall bien configuré: Il ne faut pas oublier qu'un VPN est un réseau local. Votre box ne vous protège plus. Voila pour les présentations je passe aux nouvelles: Je tourne actuellement sur vpnautoconnect 2.2 avec beaucoup de codes réécris. J'ai actuellement un problème avec apparmor (mais de toute façon les anciennes versions l'ont également). Vu le lot de problèmes grandissant je vais donc sortir la 2.2 avant la fin de la semaine. Dernière modification par mastergb (Le 27/11/2012, à 22:14) Hors ligne ljere Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) bonjour je repose donc ma question à quoi sert cette ligne dans la conf AddrToPingIfDNSDown=198.41.0.4,192.33.4.12 faut-il la modifier? Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour, Heureux de trouver ici un sujet dédié à vpnautoconnect. Bonne initiative en tous cas que de créer un nouveau fil ici même, l'ancien commençait à peser avec ses 30 pages de lecture... Actuellement, je suis sous Ubuntu 12.10 depuis peu et vpnautoconnect ne fonctionne plus malheureusement... J'ai donc désinstallé complètement Vpnautoconnect puis réinstallé celui-ci. (v2.1) Il se lance bien au démarrage et l'icône apparait dans le systray. Jusque là normal, mais lorsque j'ouvre les "préférences" pour y cocher "suivre le parent et reconnecter", ou y ajouter un vpn, rien n'est enregistré après avoir cliqué sur "sauver"... C’est-à-dire que si je rouvre les préférences, tout a disparu ! marc@ubuntu:~$ cat /var/log/syslog | grep "vpnautoconnect" Dec 7 09:04:19 ubuntu AptDaemon: INFO: CommitPackages() was called: dbus.Array([dbus.String('vpnautoconnect')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')) Dec 7 09:04:19 ubuntu AptDaemon.Worker: INFO: Committing packages: dbus.Array([dbus.String('vpnautoconnect')], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')) Dec 7 09:04:32 ubuntu AptDaemon: INFO: InstallFile() was called: /home/marc/Desktop/vpnautoconnect_2.1.0ubuntu5_i386.deb Dec 7 09:04:39 ubuntu AptDaemon.Worker: INFO: Installing local package file: /home/marc/Desktop/vpnautoconnect_2.1.0ubuntu5_i386.deb Dec 7 09:04:43 ubuntu AptDaemon.Worker: INFO: Installing local package file: /home/marc/Desktop/vpnautoconnect_2.1.0ubuntu5_i386.deb Dec 7 09:28:39 ubuntu named[1647]: error (network unreachable) resolving 'vpnautoconnect.svn.sourceforge.net/A/IN': 2001:500:94:1::3#53 Dec 7 09:38:46 ubuntu AptDaemon: INFO: CommitPackages() was called: dbus.Array([dbus.String('vpnautoconnect')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')), dbus.Array([dbus.String('')], signature=dbus.Signature('s')) Dec 7 09:38:46 ubuntu AptDaemon.Worker: INFO: Committing packages: dbus.Array([dbus.String('vpnautoconnect')], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')), dbus.Array([], signature=dbus.Signature('s')) Dec 7 09:38:54 ubuntu AptDaemon: INFO: InstallFile() was called: /home/marc/Desktop/vpnautoconnect_2.1.0ubuntu5_i386.deb Dec 7 09:39:00 ubuntu AptDaemon.Worker: INFO: Installing local package file: /home/marc/Desktop/vpnautoconnect_2.1.0ubuntu5_i386.deb Dec 7 09:39:05 ubuntu AptDaemon.Worker: INFO: Installing local package file: /home/marc/Desktop/vpnautoconnect_2.1.0ubuntu5_i386.deb Puis-je installer la v2.2 sous 12.10 ou dois-je forcer la version 2.1oubuntu4 comme indiqué sur cette page ? (Quantal) https://launchpad.net/~barraudmanuel/+a … /+packages Vos suggestions sont les bienvenues. "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Le ppa de Manu n'a peut-être pas été poussé sous quantal. ( je suis encore sous precise ). Il faut que tu modifies la source, soit par synaptic, soit en éditant le fichier concerné. gksudo gedit /etc/apt/sources.list.d/barraudmanuel-vpnautoconnect-quantal.list Remplaces quantal par precise. Ensuite, sudo apt-get update && sudo apt-get upgrade Normalement, une mise à jour vers la version 2.2 devrait être proposée. Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) @ lynn J'avais déjà modifié le dépôt, et rechargé mais aucune mise à jour proposée concernant vpnautoconnect. "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) C'est curieux ça ! Quand la nouvelle version est sortie, moi je l'ai eu tout de suite via le gestionnaire de mises à jour... Tu as essayé de faire le ménage en désinstallant complètement tout ce qui concerne vpnautoconnect ainsi que son ppa ? Juste après avoir fait ça : sudo apt-get autoremove && sudo apt-get autoclean && sudo apt-get clean Maintenant, tu ajoutes le ppa disponible ici et installes vpnauconnect pour repartir sur une base propre. Logiquement, tu devrais avoir la version 2.2... sinon je ne vois pas ce qui peut empêcher cette version de s'installer chez toi. Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour, Force est de constater qu'aucune version ne semble fonctionner sous 12.10 Quantal... (versions 32 bits 2.1Oubuntu.4_i386 ; idem 2.1.5 et 2.2.2) Soit j'ai droit à "Le daemon ne répond pas, le programme va se terminer automatiquement", ou lorsque le lancement réussi après reboot, aucune connexion et tous les champs dans "préférences" sont vides. De plus, si l'on tente de modifier ou ajouter des valeurs, rien n'est mémorisé après avoir "sauver". C'est à dire qu'à la réouverture, tous les champs sont de nouveau vides... C'est curieux ça ! Quand la nouvelle version est sortie, moi je l'ai eu tout de suite via le gestionnaire de mises à jour... Idem chez moi, la v2.2.2 mais alors j'étais sous 12.04. Personne qui utilise la 12.10 et vpnautoconnect ? Actuellement, lancement du vpn manuellement en espérant que la connexion ne tombe pas... "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Personne n'utilise vpnautoconnect sous 12.10 actuellement ? J'aimerais bien comparer vos expériences, afin d'essayer de comprendre ce qui se passe avec cette nouvelle version.d'Ubuntu. Pour le moment, c'est connexion vpn manuelle via networkmanager et firewall maison. (merci manu pour son aide précieuse) "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) @Ansuz J'ai installé Ubuntu 12.10 sous VirtualBox pour tester vpnautoconnect. Le daemon se lance bien, l'icône est bien présente dans le systray ( après avoir ajouté "vpnautoconnect" dans "application au démarrage" ) mais aucune connexion automatique malgré tous les paramètres correctement renseignés. Ca a été résolu en supprimant la demande du mot de passe du trousseau de clé ( seahorse ). Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Donc, de façon virtuelle ça fonctionne avec vpnautoconnect v2.2 sous 12.10 ? De mon côté impossible d'enregistrer la moindre valeur dans préférences... Rien n'est sauvegardé. Ca a été résolu en supprimant la demande du mot de passe du trousseau de clé ( seahorse ) Peux-tu m'en dire plus la dessus ? "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Peux-tu m'en dire plus la dessus ? J'ai commencé par viré les fichiers .keyring dans ~/.local/share/keyrings ensuite, j'ai lancé seahorse et avec le "+" en haut à gauche, "trousseau de mot de passe", tu le nommes comme tu veux et à la proposition du mot de passe, tu laisses vide. Redémarres ta session ou ton pc et normalement, ça devrait fonctionner. Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) @ lynn J'avoue avoir du mal à appréhender le rapport entre seahorse et le lancement de vpnautoconnect. Comment ce fait-il que ça fonctionnait parfaitement jusqu'à la 12.10 ? (Je n'ai rien modifié du point de vue autorisation, mot de passe...) Le souci, c’est que je n'est pas de fichiers keyrings dans ~/.local/share. Par contre, j'ai un dossier dans /usr/share/keyrings (est-ce celui-ci dont tu parles ? n'y a t-il aucun risque à le supprimer ?) J'ai bien créé un nouveau trousseau suivant tes conseils, mais aucun changement... L’icône de vpnautoconnect et bien lancée dans le systray, mais il m'est toujours impossible d'ajouter ou modifier la moindre valeur dans "préférences" qui demeure désespérément vide ! (le bouton "sauver" ne sauvegarde rien) "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) @Ansuz As-tu le fichier appelé "config" situé dans ~/.vpnautoconnect ? Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) A priori, non. "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Crées un fichier "config" nano ~/.vpnautoconnect/config et insères ce qui suit en adaptant les deux dernières lignes à ta configuration #VPNAutoconnect Config [global] FollowReconnectParent=yes reconnectAfterDisconnectManual=no HostToPing=google.fr AddrToPingIfDNSDown=198.41.0.4,192.33.4.12 scriptEvenement= TimeoutBeforeSwitch=15 [openvpn-de] # à modifier suivant ton fournisseur vpn connectionSupport=Connexion filaire 1 # à modifier suivant ton interface réseau Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Merci lynn pour ton aide et la patience dont tu fais preuve. Fichier "config" ok, mais toujours au point mort. Aucun changement... comment ce fait-il que les champs dans préférences restent définitivement vides malgré tout ??? Ça commence à devenir désespérant, personne n'utilise vpnautoconnect sous 12.10 ? "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) @ lynn C'est exactement ça, dans cette fenêtre, tous les champs sont vides malgré le fichier config, rien n'est sauvegardé si je rentre ou modifie des valeurs. A la réouverture, tout à disparu... Idem si je rentre un vpn. "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne gregolak Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour, je viens d'installer ubuntu 12.04 64bits, et plus possible de faire fonctionner vpnautoconnect. J'ai la dernière version du ppa (2.2.0), lorsque je le lance il ne se passe rien. Idem avec le flag --nounity (j'utilise Gnome). J'ai essayé d'installer la 2.0.4-1ubuntu1_no_unity_amd64 au cas où, pas mieux... (au passage ça n'a dans doute rien à voir mais network-manager ne connecte plus automatiquement le VPN malgré la case "connecter automatiquement" cochée) Merci d'avance ! Hors ligne mastergb Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour à tous. Je prend juste connaissance su problème avec quantal. Je ne suis pas encore passé dessus donc je n'ai pas pu voir les problèmes (peut être uniquement un problème de lib) Je vais regarder ce week end. Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Merci manu, ça fait plaisir de te revoir parmi nous ! Je commençais à désespérer obtenir une solution pour Quantal. Au plaisir de te lire... "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne mastergb Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour, Je viens de migrer une de mes machines sous quantal (non pas sans mal ) Aucun problème concernant vpnautoconnect. IL faut vraiment que je vois précisement avec toi ansuz. (session SSH, + version vpnautoconnect avec symbol de deboggage +gdb). Il faudra environ une petite demi heure. Voila dis moi tes dispos par mail ou skype. Dernière modification par mastergb (Le 22/12/2012, à 11:37) Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Salut manu, Je t'ai envoyé un mail, mais il va falloir me rappeler la marche à suivre. (session SSH, + version vpnautoconnect avec symbol de deboggage +gdb) ... "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne Ansuz Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Salut à tous, Bien, après deux échanges en live avec mastergb, tout semble rentré dans l'ordre. Non sans mal il faut dire... en effet quantal donne pas mal de fil à retordre aux développeurs tel que mastergb. Qu'il soit ici remercié comme il se doit, pour son dévouement hors pair, sa patience sans limites et ses compétences hors-norme dans le domaine... Force est de constater que vpnautoconnect fonctionne de nouveau sous quantal, après pas mal d'efforts. (de sa part) Mais je préfère laisser la plume à mastergb, afin qu'il nous explique lui-même ce qui clochait sur ma machine. J'en serais moi-même incapable, rendons à césar ce qui appartient à césar Dès qu'il passera par ici. Merci Manu! "Mieux vaut ne rien savoir que beaucoup savoir à moitié !" Friedrich Nietzsche Hors ligne lynn Re : Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!) Bonjour, Il y'a quelques minutes, je viens d'avoir une mise à jour de vpnautoconnect et depuis ça ne fonctionne plus... Une fenêtre s'ouvre : Le daemon ne répond pas le programme va se fermer automatiquement Apparemment, lvpnc ne se lance plus. Ca fonctionnait avec la version précédente. Ubuntu 12.10 64 bits. Si tu passes par là Manu Edit : En lançant lvpnc dans un terminal et en regardant dans le moniteur système, on voit que lvpnc se lance et se ferme aussitôt. Par contre, si je lance lvpnc en mode root via le terminal sudo lvpnc lvpnc se lance et reste mais la reconnexion automatique en cas de coupure vpn ne fonctionne pas... Dernière modification par lynn (Le 27/12/2012, à 13:32) Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne
I have the following problem: A mail server, sends emails with rate $7.5/\text{hour}$. What is the probability that it will send exactly $5$ emails in one hour? To solve it, I did the following using a Poisson distribution: $$\frac{7.5^5 e^{-7.5}}{5!}$$ or with sage math: def dpoi(x): return (7.5^x * (e^-7.5)) / factorial(x) dpoi(5) 0.109374594682555$$ is that right?
Your posted code had a few minor typos in it (firstame="bob" in data vs. firstname="bob", lastname vs. last), but after cleaning them up, it looks pretty good. If you print out the result, you get: ['firstname', 'bob', 'lastname', 'stewart', 'dob', '2010-0206', 'hobbies', 'reading, singing', 'drawing', 'is_minor', 'True'] First off, let me suggest that, just as you defined list_of_names (from your earlier SO question pyparsing string of quoted names) as a possible value type you define a boolean value to parse True/False values. Using oneOf is good, let's add a parse action to convert from the strings "True" and "False" to actual Python boolean values: boolean_value = oneOf("True False").setParseAction(lambda t: t[0]=='True') This is similar to using removeQuotes on quotedString. Now, the parsed results now look like: ['firstname', 'bob', 'lastname', 'stewart', 'dob', '2010-0206', 'hobbies', 'reading, singing', 'drawing', 'is_minor', True] Note that True is now not a string, but the Python value True (no quotes around the value). Now to the first part of your question, how to make this into a dict. Pyparsing allows you to define results names for different parts of your grammar, so that after the data is parsed, you can access those values by name. The syntax for doing this used to be to call the method setResultsName: my_data = person_start + first.setResultsName("firstname") + last.setResultsName("lastname") + ... I found this to be kind of cumbersome, and that the expression was harder to read with all the ".setResultsName" method calls. So a while back I changed the API to accept this syntax: my_data = person_start + first("firstname") + last("lastname") + ... But what you have defined as first, last, etc. contain more than just the value, they also include the label. One way to simplify your grammar is to make a small helper method of your own, let's call it named_parameter: def named_parameter(label, paramtype): expr = Literal(label) + Suppress('=') + paramtype(label) return expr Note that label is used to specify both the literal string and the value's results name. Now you can define your grammar as: first = named_parameter("firstname", quotedString) last = named_parameter("lastname", quotedString) dob = named_parameter("dob", quotedString) hobbies = named_parameter("hobbies", Suppress("[") + list_of_names + Suppress("]")) is_minor = named_parameter("is_minor", boolean_value) With the values named, you can then access the parsed results as a Python dict: print result["firstname"] print result["hobbies"] prints: bob ['reading, singing', 'drawing'] Or if you prefer, you can also use object attribute notation: print result.firstname print result.hobbies To answer the second part of your question, you asked how to handle the case where the parameters could be out of order. The easiest way to do this is to use delimitedList again: parameter = first | last | dob | hobbies | is_minor my_data = person_start + delimitedList(parameter) + person_end This is not a rigorous parser, it will accept parameter lists that don't have all the parameters, or lists with duplicate parameters. But for existing valid code, it will parse lists with parameters in any order. Here's the final parser: quotedString.setParseAction(removeQuotes) list_of_names = delimitedList(quotedString) boolean_value = oneOf("True False").setParseAction(lambda t: t[0]=='True') def named_parameter(label, paramtype): expr = Literal(label) + Suppress('=') + paramtype(label) return expr person_start = Literal("person(").suppress() first = named_parameter("firstname", quotedString) last = named_parameter("lastname", quotedString) dob = named_parameter("dob", quotedString) hobbies = named_parameter("hobbies", Suppress("[") + list_of_names + Suppress("]")) is_minor = named_parameter("is_minor", boolean_value) person_end = Suppress(")") comma = Literal(",").suppress() parameter = first | last | dob | hobbies | is_minor my_data = person_start + delimitedList(parameter) + person_end
I want to run a mysql command and set the output of that to be a variable in my python script. Here is the shell command I'm trying to run: $ mysql my_database --html -e "select * from limbs" | ./script.py Here is the python script: #!/usr/bin/env python import sys def hello(variable): print variable How would I accept the variable in the python script and have it print the output?
If you're just asking how to tile four images together into a larger image, this is easy to do with most image-processing libraries. I'll show how to do it using PIL/Pillow: import sys from PIL import Image width, height = int(8.27 * 300), int(11.7 * 300) # A4 at 300dpi images = sys.argv[1:] groups = [images[i:i+4] for i in range(0, len(images), 4)] for i, group in enumerate(groups): page = Image.new('RGB', (width, height), 'white') page.paste(Image.open(group[0]), box=(0, 0)) page.paste(Image.open(group[1]), box=(int(width/2.+.5), 0)) page.paste(Image.open(group[2]), box=(0, int(height/2.+.5))) page.paste(Image.open(group[3]), box=(int(width/2.+.5), int(height/2.+.5))) page.save('page{}.pdf'.format(i)) This is meant as sample code, not a complete solution to your problem. A few caveats: This generates a separate PDF file for each page. I placed the PNG files at the upper-left corner of each quadrant of the page. I don't know where you want them placed, but it's probably not exactly that. (Many printers can't print all the way to the margins, and, even if they can, you usually don't want them to.) I didn't scale the images, which might be a problem if your graphs are 100x100, or 2000x2000. I assumed you wanted to print out at 300dpi.
JavaScript stevenhu — 2012-09-21T16:02:46-04:00 — #1 I am trying to delete a row in a database via external JS, but don't think the syntax is right. What I have right now is my best guess as to what it should be. The database rows show an ID, filename, and title (context: a bookmarked or favorite page), and when a query is made, it shows two buttons side by side for each row; the left button shows the title and when tapped goes to the page, while the right button is used to remove the row. This code successfully generates the buttons (via innerHtml): function querySuccess(tx, results) { var len = results.rows.length; console.log("BOOKMARKS table: " + len + " rows found."); for (var i=0; i<len; i++) { <font color='"#FF0000"'>rowId = results.rows.item(i).id;</font> document.getElementById("output").innerHTML +="<div class='row'>" + "<a href='" + results.rows.item(i).filename + "'><input type='button' class='buttonBM' value='" + results.rows.item(i).title + "'></a></div>" + "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('" + <font color='"#FF0000"'>rowId</font> + "')'></a></div>"; } } What I need to do is take the rowId and use it to delete the correct row in the DB, and I do it like this: function removeRow() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); <font color='"#FF0000"'>var rowId;</font> db.transaction(function(tx) { tx.executeSql("delete from BOOKMARKS where id='" + <font color='"#FF0000"'>rowId</font> + "'"); }, errorCB, successCB()); alert('Bookmark removed.'); } However, it fails to delete the row. Google Tools gives the error as "Uncaught SyntaxError: Unexpected token }" which is on the external HTML page (which could be any page in the app containing the Add Bookmark button). The error points to the <HTML> line, so it could be anything. Below is the above code in context: // Add row via button on external page function insertRow() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(function(tx) { var id, filename = window.location.pathname, title = document.title; tx.executeSql("insert into BOOKMARKS(id, filename, title) values(?,?,?)", [id, filename, title]); }, errorCB, successCB()); alert('Bookmark added.'); } // Display DB results (onLoad) function queryDB(tx) { tx.executeSql("SELECT * FROM BOOKMARKS", [], querySuccess, errorCB); } function querySuccess(tx, results) { var len = results.rows.length; console.log("BOOKMARKS table: " + len + " rows found."); for (var i=0; i<len; i++) { rowId = results.rows.item(i).id; document.getElementById("output").innerHTML +="<div class='row'>" + "<a href='" + results.rows.item(i).filename + "'><input type='button' class='buttonBM' value='" + results.rows.item(i).title + "'></a></div>" + "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('" + rowId + "')'></a></div>"; } } // Remove row via button on this page function removeRow() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); var rowId; db.transaction(function(tx) { tx.executeSql("delete from BOOKMARKS where id='" + rowId + "'"); }, errorCB, successCB()); alert('Bookmark removed.'); } // Transaction error callback (corrected per Sitepoint.com post) function errorCB(tx, err) { alert('Error processing SQL: ' + err); } Of course, the Google error could be pointing to an entirely different part of the two pages! paul_wilkins — 2012-09-21T17:05:07-04:00 — #2 I think that the problem is in some other part of the code. There aren't any unexpected }'s in that code. Not even after using jslint to help tidy it up. The only other issue there is that successCB() isn't correct, it should be just a reference to a function instead, like with the errorCB function. The successCB one is optional though, so you can remove the function and the reference to it if you don't want to use it. // Transaction error callback (corrected per Sitepoint.com post) function errorCB(tx, err) { alert('Error processing SQL: ' + err); } function successCB() { } // Add row via button on external page function insertRow() { var db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(function (tx) { var id, filename = window.location.pathname, title = document.title; tx.executeSql("insert into BOOKMARKS(id, filename, title) values(?,?,?)", [id, filename, title]); }, errorCB, successCB); alert('Bookmark added.'); } function querySuccess(tx, results) { var len = results.rows.length, i, rowId; console.log("BOOKMARKS table: " + len + " rows found."); for (i = 0; i < len; i += 1) { rowId = results.rows.item(i).id; document.getElementById("output").innerHTML += "<div class='row'>" + "<a href='" + results.rows.item(i).filename + "'><input type='button' class='buttonBM' value='" + results.rows.item(i).title + "'></a></div>" + "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('" + rowId + "')'></a></div>"; } } // Display DB results (onLoad) function queryDB(tx) { tx.executeSql("SELECT * FROM BOOKMARKS", [], querySuccess, errorCB); } // Remove row via button on this page function removeRow() { var db = window.openDatabase("Database", "1.0", "Bookmarks", 200000), rowId; db.transaction(function (tx) { tx.executeSql("delete from BOOKMARKS where id='" + rowId + "'"); }, errorCB, successCB); alert('Bookmark removed.'); } stevenhu — 2012-09-21T17:13:09-04:00 — #3 Thanks, Paul. Here is the HTML the error code points to. The external JS' innerHtml is written to the span=output part: <!DOCTYPE html> <html> ==> Uncaught SyntaxError: Unexpected token } <== <head> <title>Bookmarks 3 html</title> <script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script> <script type="text/javascript" charset="utf-8" src="original4.js"></script> <script> </script> <style type="text/css"> body {margin:0; padding:0; background-color: #aaa;} div#wrapper{width:100%;padding:.5em;} div.row{font-family:Helvetica, Arial, sans-serif; color: #333; margin:0;padding:0; } /* input */ input[type="button"] { background-color:#fff;font-family:Helvetica, Arial, sans-serif; color: #333; text-align:center;margin:0;padding:1em;float:left; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 5px 5px 4px 0px #888; /* Safari 3-4, iOS 4.0.2 &#8211; 4.2, Android 2.3+ */ box-shadow: 5px 5px 4px 0px #888; /* Opera 10.5, IE9, Firefox 4+, Chrome 6+, iOS 5 */ border:1px #666 solid; } input[type="button"]:hover {background-color:#ddd;} .buttonBM { width:70%; } .buttonEdit { width:28%; } .addBM {width:100%; float:left;clear:both;margin:1em;} </style> </head> <body onload="onDeviceReady()"> <div id="wrapper"><span id="output"></span></div> <br> <a href="original3.html"><p style="padding: .5em;line-height:4em;">Back</p></a> </body> </html> stevenhu — 2012-09-21T17:37:11-04:00 — #4 Your version of the code places my functions in a different order. Can you explain why? paul_wilkins — 2012-09-21T18:17:28-04:00 — #5 Because it's not good to use a function before it has been defined. When using a function statement you can mostly get away with it because functions within the same scope are defined first, after which scripting it processed. But if you ever use function expressions then the problem becomes quite obvious. someFunc('Did this run?'); // nope var someFunc = function (str) { alert(str); } So declare what you need (the function in this case) before making use of it. That helps to prevent all sorts of problems. var someFunc = function (str) { alert(str); } someFunc('Did this run?'); // yes Because the ordering does affect function statements, and function statements are used interchangably with function expressions, it's best if the one ordering rule is applied across both of them. This helps to simplify things, and allows the code to more easily be improved upon at later stages as well. paul_wilkins — 2012-09-21T18:31:27-04:00 — #6 Remove everything you can until you are left with the core code that still causes the problem. How much of it can you remove while still retaining the same problem? stevenhu — 2012-09-21T18:50:16-04:00 — #7 I did the following one at a time, cutting, saving, testing, then replacing to remove something else: I removed the entire CSS style section. Still errors. I removed the Back link, still errors. Removed <HTML>. Still errors. Removed <!DOCTYPE html>. Still errors. Removed empty <script>tags. Still errors. That leaves the innerHtml span id = output line. Can't take that out, or there are no buttons to press! I suppose, in conclusion, the error is happening in the innerHtml output? paul_wilkins — 2012-09-21T19:36:54-04:00 — #8 Currently we're not focused on having a working system. Right now we're focused on figuring out where that error with the brace is coming from. Keep on chopping things out. stevenhu — 2012-09-24T11:24:14-04:00 — #9 If I remove the innerHtml line, then there is no content on the page, so I get the error, Uncaught TypeError: Cannot read property 'innerHTML' of null The error only occurs after I click on one of the Remove buttons, which is rendered inside the innerHtml. I separated the css and js content into their own files. HTML: <!DOCTYPE html> <html> <head> <title>Bookmarks 3 html</title> <script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script> <script type="text/javascript" charset="utf-8" src="original4.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="bookmarks3.css"> <style type="text/css"> </style> </head> <body onload="onDeviceReady()"> <div id="wrapper"><span id="output"></span></div> <a href="original3.html"><p style="padding: .5em;">Back</p></a> </body> </html> CSS: body {margin:0; padding:0; background-color: #aaa;} div#wrapper{width:100%;padding:.5em;} div.row{font-family:Helvetica, Arial, sans-serif; color: #333; margin:0;padding:0; } div.bookmark {margin:.5em;} p{text-align:left;} p.title {font-weight:bold;font-size:1em;text-align:center; color:#000} a {color:#666} /* input */ input[type="button"] { background-color:#fff;font-family:Helvetica, Arial, sans-serif; color: #333; text-align:left;margin:0;padding:1em;float:left; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 5px 5px 4px 0px #888; /* Safari 3-4, iOS 4.0.2 – 4.2, Android 2.3+ */ box-shadow: 5px 5px 4px 0px #888; /* Opera 10.5, IE9, Firefox 4+, Chrome 6+, iOS 5 */ border:1px #666 solid; } .buttonBM { width:67%; } .buttonEdit { width:33%; } .addBM {width:100%; float:left;clear:both;margin:1em;} JS: /* Helpful info: base: http://docs.phonegap.com/en/2.0.0/cordova_storage_storage.md.html#Storage modifications: http://tv.adobe.com/watch/adc-presents/phonegap-storage-api/eng/ */ // Wait for Cordova to load document.addEventListener("deviceready", onDeviceReady, false); var db; function onDeviceReady() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(populateDB, errorCB, successCB); } // Transaction error callback (corrected per Sitepoint.com post) function errorCB(tx, err) { alert('Error processing SQL: ' + err); } // Transaction success callback function successCB() { var db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(queryDB, errorCB); } // Display the rows on this page (onLoad) function querySuccess(tx, results) { var len = results.rows.length; console.log("BOOKMARKS table: " + len + " rows found."); for (var i=0; i<len; i++) { rowId = results.rows.item(i).id; document.getElementById("output").innerHTML +="<div class='row'>" + "<a href='" + results.rows.item(i).filename + "'><input type='button' class='buttonBM' value='" + results.rows.item(i).title + "'></a></div>" + "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('" + rowId + "')'></a></div>"; } document.getElementById("output").innerHTML +="<div class='row'><p style='line-height:2em;'>You have " + len + " bookmarks.</p></div>"; } // Query the DB function queryDB(tx) { tx.executeSql("SELECT * FROM BOOKMARKS", [], querySuccess, errorCB); } // Remove row via button on this page function removeRow() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); var rowId; db.transaction(function(tx) { tx.executeSql("delete from BOOKMARKS where id='" + rowId + "'"); }, errorCB, successCB()); alert('Bookmark removed.'); } // Add row via button on external page function insertRow() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(function(tx) { var id, filename = window.location.pathname, title = document.title; tx.executeSql("insert into BOOKMARKS(id, filename, title) values(?,?,?)", [id, filename, title]); }, errorCB, successCB()); alert('Bookmark added.'); } // Create the database function populateDB(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS BOOKMARKS (id INTEGER NOT NULL, filename TEXT NOT NULL, title TEXT NOT NULL)'); } // Cordova is ready function onDeviceReady() { var db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(populateDB, errorCB, successCB); } stevenhu — 2012-09-24T13:11:25-04:00 — #10 In Google Tools, I clicked on the Elements tab and examined the innerHtml content as output to the screen. I think I found the problem. The innerHtml line has (copying and pasting): "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('" + rowId + "')'></a></div>"; The Elements tab has (copying and pasting): <input type="button" class="buttonEdit" value="Remove" onclick="removeRow(" undefined')'=""> The rowId is not rendering properly. Also, the copy/paste from google Tools Elements tab shows more than what I see on the Elements tab on screen. On screen, I don't see undefined')'=""> but undefined')'> It looks like we need to figure out why the variable is not being populated. On a separate HTML page, which contains the button to execute the code to enter a new row, the code used is: <div class="bookmark"><input type="button" class="addBM" value="Add Bookmark" onclick="insertRow('100', window.location.pathname, document.title)"></div> Is the syntax wrong? The pathname and title are all appearing correctly. Would the following function understand the order of the three variables, and understand the first one is id?: function insertRow() { db = window.openDatabase("Database", "1.0", "Bookmarks", 200000); db.transaction(function(tx) { var id, filename = window.location.pathname, title = document.title; tx.executeSql("insert into BOOKMARKS(id, filename, title) values(?,?,?)", [id, filename, title]); }, errorCB, successCB()); alert('Bookmark added.'); } stevenhu — 2012-09-24T13:47:43-04:00 — #11 You know, since I am using an ID number to reference the row to delete, but it isn't showing up, BUT the title is showing up, I might as well remove the ID completely and substitute with the title, which IS showing up. So far, that isn't working either, for the output is generated as <input type="button" class="buttonEdit" value="Remove" onclick="removeRow(" original="" 3="" html')'> even though the JS line in innerHtml is: "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('"+results.rows.item(i).title+"')'></div>"; The quotes are still not right, and the generated output adds a space before the row title and quotes within the title. (I also tried it with the filename, but it gave a long pathname rather than just the filename. I don't see a window.location code that retrieves only the filename.) stevenhu — 2012-09-24T15:57:54-04:00 — #12 You know, since I am using an ID number to reference the row to delete, but it isn't showing up, BUT the title is showing up, I might as well remove the ID completely and substitute with the title, which IS showing up. So far, that isn't working either, for the output is generated as <input type="button" class="buttonEdit" value="Remove" onclick="removeRow(" original="" 3="" html')'> even though the JS line in innerHtml is: "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('"+results.rows.item(i).title+"')'></div>"; stevenhu — 2012-09-24T18:34:11-04:00 — #13 Now I've got the removeRow to show the title without the ="" within the words, and the database is showing correct entries. But I am still getting the "unexpected token }" error. paul_wilkins — 2012-09-24T19:21:23-04:00 — #14 From the code that you had in post #9 I'm seeing that it should just be the quotes that are causing the issue. This line seems to be the problem: "<div class='buttonRemove'><input type='button' class='buttonEdit' value='Remove' onclick='removeRow('" + rowId + "')'><font color='"red"'></a></font></div>"; By the way - the </a> from the javascript code part shouldn't be there either. It results in this HTML code: <div class="buttonRemove"><input type="button" class="buttonEdit" value="Remove" onclick="removeRow(<font color='"red"'>"</font> row1<font color='"red"'>')'=""</font>></div> See how the quotes are all messed up? What you need there instead is: onclick="removeRow('row1')" Notice though that even when we start the javascript string with single quotes, that by the time we get through the HTML double quotes and once more to the single quotes required for the removeRow part, that we're going to end up closing the string instead. So, for those innermost single quotes we'll need to escape them as \' instead. '<div class="buttonRemove"><input type="button" class="buttonEdit" value="Remove" onclick="removeRow(\\'' + rowId + '\\')"></div>'; That seems to work now. stevenhu — 2012-09-25T17:08:17-04:00 — #15 Wow, this is very good! Clicking on Remove now fires the removeRow function. Unfortunately, the screen is refreshing and inserting all the previous rows under the table, so the table is showing up multiplied by the number of times one clicks on Remove. We need to terminate the script so this doesn't happen. However, I'm not sure that exit(); is the approved way to do this. Thanks again, Paul! stevenhu — 2012-09-25T17:20:06-04:00 — #16 Actually, I click on Remove, and see the "Bookmark removed" alert, then the row is NOT REMOVED but repeated below the "You have X Bookmarks" message. If I go back a page, then return to the bookmarks page, the bookmarks I removed are gone. For some reason, when I comment out the successCB as you suggest, the bookmarks don't appear on the page (the area is just blank, showing the background). Uncommenting the lines causes them to appear again. Here is the current JS code: /* Helpful info: base: http://docs.phonegap.com/en/2.0.0/cordova_storage_storage.md.html#Storage modifications: http://tv.adobe.com/watch/adc-presents/phonegap-storage-api/eng/ */ // Wait for Cordova to load document.addEventListener("deviceready", onDeviceReady, false); var db; function onDeviceReady() { db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000); db.transaction(populateDB, errorCB, successCB); } // Create the database function populateDB(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS BOOKMARKS3 (id INTEGER NOT NULL, filename TEXT NOT NULL, title TEXT NOT NULL)'); } // 1. Transaction error callback (corrected per Sitepoint.com post) function errorCB(tx, err) { alert('Error processing SQL: ' + err); } // 2. Transaction success callback function successCB() { var db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000); db.transaction(queryDB, errorCB); } // 3. Add row via button on external page function insertRow() { db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000); db.transaction(function(tx) { var id, filename = window.location.pathname, title = document.title; tx.executeSql("insert into BOOKMARKS3(id, filename, title) values(?,?,?)", [id, filename, title]); }, errorCB, successCB()); alert('Bookmark added.'); } // 4. Display the rows on this page (onLoad) function querySuccess(tx, results) { var len = results.rows.length; console.log("BOOKMARKS3 table: " + len + " rows found."); for (var i=0; i<len; i++) { rowId = results.rows.item(i).id; document.getElementById("output").innerHTML +="<div class='row'>" + "<a href='" + results.rows.item(i).filename + "'><input type='button' class='buttonBM' value='" + results.rows.item(i).title + "'></a></div>" + '<div class="buttonRemove"><input type="button" class="buttonEdit" value="Remove" onclick="removeRow(\\'' + rowId + '\\')"></div>'; } document.getElementById("output").innerHTML +="<div class='row'><p style='line-height:2em;'>You have " + len + " BOOKMARKS3.</p></div>"; } // 5. Query the DB function queryDB(tx) { tx.executeSql("SELECT * FROM BOOKMARKS3", [], querySuccess, errorCB); } // 6. Remove row via button on this page function removeRow() { db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000); var rowId; db.transaction(function(tx) { tx.executeSql("delete from BOOKMARKS3 where id='" + rowId + "'"); }, errorCB, successCB()); alert('Bookmark removed.'); } exit; // Cordova is ready function onDeviceReady() { var db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000); db.transaction(populateDB, errorCB, successCB); } stevenhu — 2012-09-25T17:49:02-04:00 — #17 I solved the problem by replacing the successCB() with a doNothing() function to the removeRow(). Now it does not add a new row, and refreshes the page to show the new status: function removeRow() { db = window.openDatabase("Database", "1.0", "BOOKMARKS3", 200000); var rowId; db.transaction(function(tx) { tx.executeSql("delete from BOOKMARKS3 where id='" + rowId + "'"); }, errorCB, doNothing()); alert('Bookmark removed.'); } function doNothing() { window.location.href=window.location.href; } Is this syntax OK, or is this unconventional? stevenhu — 2012-09-25T18:13:10-04:00 — #18 You know, when I press the button to add that page's title and filename to the database, it works because of this in the page's head: <script type="text/javascript" charset="utf-8" src="original4.js"></script> However, that means ALL the JS functions on that page try to execute whenever I first open the page AND after I click on the Add Bookmark button. Obviously, I'm going to turn off the debugging alerts when I'm done, but is there a more "correct" way of doing this? The bookmarking code will appear on over 200 pages in a book app I'm working on.
Very occasionally, I write code where I’m given an object of some class (usually from a library call), but I wish to use additional methods on that class as though they had been defined there. In some languages (Objective-C shines in this regard with categories), you can do this very naturally. In Python, most people probably resort to monkey patching to accomplish this. This is Probably An Anti-Pattern I want to preface this with an admission that I have no idea if this will generally work (please comment if you know of a reason why it won’t!), and that I suspect that this is a horrible idea. And yet, here we go: import copy class Base(object): def __init__(self): self.base_init = True def foo(self): return 'base foo' def bar(self): return 'base bar' class Child(Base): def __new__(cls, other): if isinstance(other, Base): other = copy.copy(other) other.__class__ = Child return other return object.__new__(cls) def __init__(self, other): self.child_init = True def bar(self): return 'child bar' b = Base() assert b.base_init == True assert b.foo() == 'base foo' assert b.bar() == 'base bar' assert b.__class__ == Base c = Child(b) assert c.base_init == True assert c.child_init == True assert c.foo() == 'base foo' assert c.bar() == 'child bar' assert c.__class__ == Child assert b.__class__ == Base Have I made some glaring mistake? Is there something obviously wrong with this, other than the abuse of the language inherent in trying to do such a thing?
Názory k článku Perličky: úvod do referencí mach(neregistrovaný) ve článku nikdo nikoho nenutil se něco učit. Tento jazyk byl vymyslen člověkem z praxe pro lidi, řešící praktické věci. V žádném případě není výlupek ctností a akademické krásy - na druhou stranu, zatím co v jiných jazycích dokončujete ještě deklarace, tak perlista už balí. Používám několik jazyků, ale díky organizované strávě modulů (CPAN) a díky časovému stresu jsem si za hlavní (a poslední) jazyk zvolil perl. A udělal jsem dobře. uživatel si přál zůstat v anonymitě def merge(a, b): ret = [] ia = ib = 0 while 1: if ia == len(a): if ib == len(b): break ret.append(b[ib]); ib += 1 elif ib == len(b) or a[ia] < b[ib]: ret.append(a[ia]); ia += 1 else: ret.append(b[ib]); ib += 1 return ret sub merge { my ($a, $b) = @_; my $ret = []; my $ia = 0; my $ib = 0; while (1) { if ($ia == @$a) { last if $ib == @$b; push @$ret, $$a[$ia++]; elsif ($ib == @$b or $$a[$ia] < $$b[$ib]) { push @$ret, $$a[$ia++]; } else { push @$ret, $$b[$ib++]; } } return $ret; } Yenya(neregistrovaný) Jo, nemuzete pastnout kod do HTML komentaroveho systemu, nemuzete psat one-linery, atd. Pred elsif Vam chybi zavorka. Misto $$a[$ia++] je myslim citelnejsi psat $a->[$ia++]. Hmm, jak vlastne v Pythonu reknu ze mam lokalni promennou? Pri prvnim prirazeni? To je fakt spatne, protoze pak neodhalite preklep ve jmene promenne uz v compile-time. Michani objektoveho zapisu s funkcemi (ret.append() versus len(a)) je taky dost divne. -Yenya VM(neregistrovaný) Souhlasim s kritikou. Navic ta dvojita reference (push @$ret, ...) je zbytecna - staci push @ret... a pak return [ @ret ]; To je argumentace stylem : umim Perl jen trochu - jednoduchy problem v nem vyresim neprehledne - takze Perl je spatny. Ja osobne bych to resil takhle - myslim ze to je jeste lepsi nez ten ukazkovy Python. sub merge { my @a=@{$_[0]}; my @b=@{$_[1]}; my @ret=(); my $minlen = (@a<@b ? @a : @b); push @ret, map { shift @a, shift @b } (0 .. $minlen-1); push @ret, @a; push @ret, @b; return [ @ret ]; } Nicmene mi mergesort neprijde jako prilis stastny priklad, jelikoz jedna z velkych vyhod mergesortu je, ze umi radit seznamy daleko vetsi nez je dostupna pamet. Tudiz bych v tomto algoritmu neoperoval vubec s poli, ale spise bych sekvencne nacital vstupy (maximalne bych pouzil tieovane pole, ktere umi jen operace push a shift). (Pokud chci radit neco co se vejde do pameti, muzu pouzit rovnou vestavenou funkci sort.) Jinak souhlasim s tim, ze uvedeny priklad vyse byl na primitivni urovni a navic prasacky napsan. Hodne lidi pouziva Perl jako nejake "C na steroidech". (A nejen Perl ale i PHP a dalsi jazyky s C-like syntaxi.) I temto je urcen tento serial. JS(neregistrovaný) def merge(a,b): for aa in a: for bb in b: if bb>=aa: break yield bb yield aa for aa in a: if aa>bb: break yield aa yield bb for bb in b: yield bb a=iter([3,5,7,9,11,13,15]) b=iter([1,2,4,6,12,14,16,17]) c=merge(a,b) print list(c)Nejen ze funguje na jakekoli iteratory, tedy i treba radky ve 2 souborech, ale bude patrne i rychlejsi. Rejpal(neregistrovaný) Tyhle čachry s iterátorama mi teda nepřijdou moc srozumitelný. Nepřijde mi kupříkladu příliš intuitivní, jakým způsobem se tady střídá řízení mezi těmi výběry. Musel jsem nad tím chvíli přemýšlet, abych to přečetl. Inu, Python. :-) A co takhle pěkně čistě deklarativně, pánové? ;-) (define (merge . lists) (match lists ((xs ()) xs) ((() xs) xs) (((x . xs) (y . ys)) (if (< x y) (cons x (merge xs (cons y ys))) (cons y (merge (cons x xs) ys)))))) 1. Že jsou komentářové systémy špatně napsané, není chyba Pythonu. Není však nic jednoduššího, než na začátek každého řádku napsat třeba tečku a pak ji odstranit v editoru pomocí označení sloupcového bloku. Na Rootu to lze udělat pomocí html tagu: def hello(): print "hello"Takže v tomto případě je chybou autora, že nepoužil náhled a situaci nějak nevyřešil. 2. V Pythonu jsou všechny modifikované proměnné lokální, pokud nepoužijeme klíčové slovo global. Ochránit kód před překlepy není vždy možné a to bez ohledu na použitý programovací jazyk. Rozumný pythonista ale používá nástroje pylint nebo pychecker, které potenciálních problémů najdou opravdu hodně. 3. One-linery psát lze, ikdyž je to samozřejmě samozřejmě obtížnější než v některých jiných jazycích. Zde je moje one-line (z ohledů ke čtenářům rozdělená do více řádků, ale funguje i po spojení do jednoho řádku) verze programu beer bottles: print (lambda beers : (globals().setdefault('beers', beers) and beers(99)))(lambda count:(((count == 0) and ("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.")) or ((count == 1) and ("1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n\n" + beers(count - 1))) or (("%d bottles of beer on the wall, %d bottles of beer.\nTake one down and pass it around, %d bottle of beer on the wall.\n\n" % (count, count, count - 1)) + beers(count - 1)) )) Nevidím ale stejně moc důvodů one-linery používat. Pokud chci použít Python k rychlému jednorázovému řešení nějaké situace, tak buďto použiju interaktivní prostředí Pythonu (nejlépe ipython) - Perl pokud vím tuto možnost ani nemá - a tam není důvod omezovat se jednou řádkou nebo pro opakované použití napíšu skript a tam můžu mít řádek rovněž kolik chci. nutnost explicitních dereferencí je něco, co by se v moderním jazyku už dávno vyskytovat nemělo. S tim nesouhlasim. Pokud to syntakticky neodlisite, musite zaridit, aby se kazda reference chovala jako samotny objekt. To znamena, ze pri kopii reference budete kopirovat i objekt. V opacnem pripade programator nebude vedet, co se stane, kdyz napise a<-b. Respektive to bude muset nejak "odtusit" z kontextu, coz rozhodne neprispiva k vytvoreni korektniho kodu. Číst Perl je díky těm operátorovým zvratkám vo držku Reference v Perlu jsou jako Perl samotny. Kdo tomu nerozumi, mysli si ze to je o drzku a dela si z toho vtipy. Kdo tomu rozumi, tak uz nechce jinak :-) Navic jako v kazdem jazyce, i v Perlu lze psat uhledny kod i bordel. Na druhou stranu, sebelepe formatovany kod nepomuze, pokud nekdo nezna syntaxi jazyka. a to by se v perlu navíc správně mělo místo "@$a" psát "scalar(@{$a})" atp.. Nemelo, @$a je naprosto spravny zapis. Navic scalar(@{$a}) dela neco jineho. Miloš(neregistrovaný) Nečitelnost není vlastností jazyka ale programátora. Co třeba takhle? sub merge { my $r_a=shift; my $r_b=shift; my @ret=(); my ($ia,$ib)=(0,0); my ($ctia,$ctib)=(1,1); # 0..necti 1..cti 2..konec my ($maxa,$maxb); # maximalni indexy my $prveka; my $prvekb; $maxa=$#{@{$r_a}}; $maxb=$#{@{$r_b}}; while (1) { $ctia=2 if ($ia>$maxa); $ctib=2 if ($ib>$maxb); last if ($ctia==2 and $ctib==2); if ($ctia==1) { $prveka=$r_a->[$ia++]; $ctia=0; } if ($ctib==1) { $prvekb=$r_b->[$ib++]; $ctib=0; } if ($prveka<$prvekb) { push(@ret,$prveka); $ctia=1; } elsif ($prveka==$prvekb) { push(@ret,$prveka); push(@ret,$prvekb); $ctia=$ctib=1; } else { push(@ret,$prvekb); $ctib=1; } } return (\@ret); VM(neregistrovaný) tukan(neregistrovaný) Síla? Vážně? A kromě toho, že se to vám nováčkům pěkně čte to má jaké unikátní výhody? Zatím jsem si totiž všiml jediné věci: když se kód rozformátuje, tak jste v hajzlu a opravit to znamená projít a zkontrolovat celou funkcionalitu, protože pouhé odsazení má syntaktický význam - náležitost do sub-bloků kódu. Kromě toho to taky znamená, že si s tím moc nepohrajete, co? Jak to není pod sebou, je to blbě... Zajímavá myšlenka, opravdu! Co mě ale nejvíc fascinuje - když nějaký beginner (soudím podle tvé implementace) porovnává dva jazyky a přitom zná jen jeden z nich. Fakt přínos. Teď ti ukážu čtyři možnosti implementace: tvoji, a la Perl, lepší a správnou. První tři jsou ekvivalentní, čtvrtá funguje jak bych si představoval (obecněji). Je to subjektivní hodnocení, takže necháme ostatní, aby to posoudili. Samozřejmě existuje nekonečně mnoho způsobů jak v Perlu správně napsat to, oč jsi se pokusil ty, a to je důvod, proč mám Perl rád. Mimochodem, nikdy nemám problém s "čitelností", kde se tahle kravina vzala? A reference? Kde bysme byli s C bez pointerů (i.e. referencí) nebo hůř, kdyby C (de)referenci provádělo automaticky? Přiložený zdroják je samostatný, stačí paste a spustit. Je to i s benchmarkem všech metod. #!/usr/bin/env perl # vi:ft=perl use Benchmark qw( :all ); my @TA1 = qw/ 1 2 3 /; # Test case A my @TA2 = qw/ 1 5 3 4 5 6/; my @TB1 = qw/ 2 2 3 4 5 6/; # Test case B my @TB2 = qw/ 1 3 3 4 7 /; my (@M1, @M2); # Vysledky #########################[ Reseni 1 ]######################## # # Tvoje sragora, mimochodem v prvnim "push" jsi mel chybu, # cpal jsi do vysledku prvky pole A misto pole B. A chybela # ti zavorka pred elsif. # # Uz jen ty reference a dereference vsude, pane boze!! #sub merge { my ($a, $b) = @_; my $ret = []; my $ia = 0; my $ib = 0; while (1) { if ($ia == @$a) { last if $ib == @$b; push @$ret, $$b[$ib++]; } elsif ($ib == @$b or $$a[$ia] < $$b[$ib]) { push @$ret, $$a[$ia++]; } else { push @$ret, $$b[$ib++]; } } return $ret; }@M1 = @{merge(\@TA1, \@TA2)}; @M2 = @{merge(\@TB1, \@TB2)}; print "Reseni 1a: @M1\tReseni 1b: @M2\n"; #########################[ Reseni 2 ]######################## # # Takhle bych to napsal od boku. # Lepsi? Co myslis? # sub merge2( \@\@ ) { my @a = @{$_[0]}; my @b = @{$_[1]}; my @c = map { my @c; push @c, shift @b while $b[0]<=$_ && @b; @c, $_ } @a; return @c, @b; } @M1 = merge2 @TA1, @TA2; @M2 = merge2 @TB1, @TB2; print "Reseni 2a: @M1\tReseni 2b: @M2\n"; #########################[ Reseni 3 ]######################## # # To same, jen bez kopirovani poli a s primou indexaci. #sub merge3( \@\@ ) { my ($a, $b) = @_; my (@c, $i); map { push @c, $b->[$i++] while $b->[$i] <= $_; push @c, $_ } @{$a}; return @c, @{$b}[$i..$#{$b}]; }@M1 = merge3 @TA1, @TA2; @M2 = merge3 @TB1, @TB2; print "Reseni 3a: @M1\tReseni 3b: @M2\n"; #########################[ Reseni 4 ]######################## # # Tvuj priklad ale testovaci pole spojuje blbe, viz vystup, # protoze predpoklada, ze jsou obe setridena. Co z toho leze # kdyz nejsou jsi videl. Ale beru, zes to tak treba chtel. # # Tohle reseni je ze vsech nejlepsi, protoze pole zmerguje # i v pripade, ze nejsou predem setridena a hlavne je trikat # rychlejsi nez ostatni (a nepotrebuje extra funkci:) # @M1 = sort @TA1, @TA2; @M2 = sort @TB1, @TB2; print "Reseni 4a: @M1\tReseni 4b: @M2\n\n"; ##########################[ Timing ]######################### my $c = 100000; print "Cas reseni 1:\n\t"; timethis($c, sub { @M1 = @{merge(\@TA1, \@TA2)}; @M2 = @{merge(\@TB1, \@TB2)} }); print "Cas reseni 2:\n\t"; timethis($c, sub { @M1 = merge2 @TA1, @TA2; @M2 = merge2 @TB1, @TB2 }); print "Cas reseni 3:\n\t"; timethis($c, sub { @M1 = merge3 @TA1, @TA2; @M2 = merge3 @TB1, @TB2 }); print "Cas reseni 4:\n\t"; timethis($c, sub { @M1 = sort @TA1, @TA2; @M2 = sort @TB1, @TB2 }); Výstup: Reseni 1a: 1 1 2 3 5 3 4 5 6 Reseni 1b: 1 2 2 3 3 3 4 4 5 6 7 Reseni 2a: 1 1 2 3 5 3 4 5 6 Reseni 2b: 1 2 2 3 3 3 4 4 5 6 7 Reseni 3a: 1 1 2 3 5 3 4 5 6 Reseni 3b: 1 2 2 3 3 3 4 4 5 6 7 Reseni 4a: 1 1 2 3 3 4 5 5 6 Reseni 4b: 1 2 2 3 3 3 4 4 5 6 7 Cas reseni 1: timethis 100000: 3 wallclock secs ( 2.93 usr + 0.00 sys = 2.93 CPU) @ 34129.69/s (n=100000) Cas reseni 2: timethis 100000: 3 wallclock secs ( 3.05 usr + 0.00 sys = 3.05 CPU) @ 32786.07/s (n=100000) Cas reseni 3: timethis 100000: 3 wallclock secs ( 2.75 usr + 0.00 sys = 2.75 CPU) @ 36363.64/s (n=100000) Cas reseni 4: timethis 100000: 1 wallclock secs ( 0.97 usr + 0.00 sys = 0.97 CPU) @ 103092.78/s (n=100000) Yenya(neregistrovaný) Kod je zda se dobry, ale nektere konstrukty bych nepouzil. V prvni verzi kodu bych asi spis nadeklaroval pole @ret a na konci udelal "return \@ret;" - uvnitr kodu by bylo mene dereferencovani a byl by tak jeste o kousek citelnejsi a mozna i rychlejsi. Vsem kdo v Perlu pisou delsi veci doporuji knihu Perl Best Practices: http://www.oreilly.com/catalog/perlbp/ - ne ze bych se vsim tam uvedenym souhlasil pro sve projekty, ale aspon se autor obtezuje vysvetlit, proc si mysli ze by soucasti programatorskeho stylu neco konkretniho melo nebo nemelo byt. Je to pekne psane a prinuti to cloveka se zamyslet. Z konstrukci ktere PerlBP nedoporucuje bych tady konkretne nepouzil prototypy v merge2 a merge3 - prototypy maji nekolik podstatnych nevyhod: napriklad chovaji se jinak v kodu ktery je uvedeny drive nez ta funkce a jinak v kodu pod ni; dale pokud uz reference na ta dve pole mate nekde z drivejska v promenne, tak nemuzete zavolat merge3(@moje_dva_arrayrefy). Ale jinak samozrejme, TIMTOWTDI. -Yenya JS(neregistrovaný) Kdyz je clanek o referencich, historku ze zivota: Znal jsem cloveka, co byl zaryty Perlista, a na Python take velmi nadaval. Shodou okolnosti nechapal, proc Python reference nepotrebuje - v Perlu mu prisly nezbytne. Pozdeji zkusil programovat v Pythonu; dnes na nej neda dopustit, a na Perl si ani nevzpomene. Václav Haisman(neregistrovaný) Napsal jsem jednu netrivialni aplikaci v Pythonu. Reknu Vam, co se mi na Pythonu oproti Perlu nelibilo: 1. Zadne deklarace. Nekdo to povazuje za vyhodu, me to desne chybelo. Hledat chyby v kodu, kde se clovek prepise v nazvu promenne nebo kde zapomene vytvorit promennou pred telem vnoreneho bloku je fakt opruz. 2. Prakticky nepouzitelne defaultni hodnoty parametru funkci. Myslim, ze jednoduchy priklad je dostacujici vysvetleni: def t (s = []): s.append (1) return s print t() print t() 3. Nedostacujici uzavery/lambda funkce. Python ma sice konstrukt lambda:, ale v jeho tele muze byt pouze vyraz. 4. Chybejici reference. Chybejici reference znemoznuje napsat neco tak zakladniho, jako je funkce swap. Tohle jsou vsechno zasadni veci. Pak existuje spousta dalsich mensich problemu jako napr. osklive __identifikatory__, nutnost psat vsude self., chybejici autovivifikace atd. 2. Prakticky nepoužitelný příklad. V praxi tohle vůbec není problém, věř mi (nebo mě zkus přesvědčit). 3. Silnější lambda funkce by spousta lidí uvítala. O nějakých praktických problémech s uzávěry ale nevím (opět se nechám přesvědčit). 4. V Pythonu se swap píše a, b = b, a - problém je vyřešen ;). Pythonu má holt některé typy proměnlivé a jiné neměnné. Podle toho se volí hodnoty parametrů. V praxi opět nevidím problém. Ty __identifikátory__ jsou "ošklivé" záměrně - aby se "magické metody" nepletly s klasickými metodami. Autovivifikace je typický perlismus. Pokud někdo řekne, že potřebuje autovivifikaci, pak ho neuspokojí žádný jiný jazyk. Pro mě to například zase je víceméně nesmyslná vlastnost. Rejpal(neregistrovaný) 3. Pythonovské uzávěry neposkytují mutable bindings, jen immutable. Ač je přiřazení zlo, občas je nutné (pokud jazyk nemá monády nebo něco podobně ztřěštěného :-)). Pravda je, že zrovna v Pythony tyhle věci na přestřes tak často nepřijdou, ostatně lambda je spíš na výrazy než side-effecting akce, ale týká se to třeba vnořených funkcí. 4. Hmm, to je jen speciální případ. ;-) Ale netuším, jak zrovna tohle souvisí s immutable daty. Pokud jde o podtržítka, je zajímavé, že třeba SmallTalk se bez nich obejde, a to je charakterově velmi podobný jazyk. Taktéž Ruby. Možná je to ale jen kulturní záležitost... Pravda je, že SmallTalk má velkou výhodu díky kategoriím metod, které umožňují dělat v metodách pořádek trošku jinak. :-) []použijeme Nonea není s tím žádný problém. Mně toto chování přijde konzistentní, protože []je jenom syntaktický cukr pro list()a jako pythonista když vidím list, čekám, že sekonstrukce hned provede. Opožděné provádění kódu jako třeba v MetaOCamlu je určitě příjemná vlastnost, ale Python jím zkrátka nedisponuje. S immutable daty to tedy souvisí tak, že jako implicitní hodnota parametru se muttable v zásadě nepoužívají a dávají se tam jenom "konstanty". Ve jiných jazycích se to dělá podobně a ještě jsem neslyšel názor, že jsou proto implicitní hodnoty parametrů "nepoužitelné". Pokud jde o podtržítka, kdo sleduje vývoj Pythonu, ten ví, že magické metody přibývají snad s každou novou verzí. Určitě by bylo pro vývojáře nemilé, pokud by měli nadefinovanou nějakou metodu, jejíž název se v další verzi zalíbí vývojářům Pythonu a následkem té kolize bude objekt v některých situacích vykazovat podivné chování nebo házet výjimky kvůli odlišnému počtu parametrů. Ano, Python jiný prostředek nenabízí. Jiné jazyky však nenabízejí ani tento. Václav Haisman(neregistrovaný) 2. Tenhle priklad je pochopitelne zjednoduseny a ciste pro demonstraci, ale nerekl bych, ze prakticky nepouzitelny. Naopak, nepouzitelna je semantika defaultnich parametru Pythonu. Rozhodne tedy pro cloveka, ktery je zvykly na pekne pouzitelne defaultni parametry z jazyku jako C++ ci Ada. 4. Swap neni jedina vec, kterou absence referenci znemoznuje. Znemoznuje jakoukoliv zmenu promenne primitivniho typu jako vedlejsi efekt. To je pro praci v imperativnim jazyce dosti omezujici. skutečněomezuje. def minmax(a, b): return min(a, b), max(a, b) a, b = minmax(a, b)Pokud budu mít složitější program, stejně budu pravděpodobně pracovat se složenými typy a ne s primitivními. Co se týče příkladu na tu implicitní hodnotu, tam není důvod implicitní hodnotu vynechat a případný prázdný seznam posílat explicitně. Jasně, Perl dovoluje každý problém řešit ne dvěma nebo pěti způsoby jako Python, ale dvaceti až padesáti. Toto Python neumožňuje schválně, což však někteří z nás spíše vítají. Pokud má někdo námitku, že nějaký problém v Pythonu špatně řešitelný, pobavme se o tom. Pokud ale námitka zní, že v Perlu nebo některém jiném jazyce to dělá takhle a Python to neumožňuje (ne, skutečně nepotřebuju sahat na parametry funkce pomocí shift ani $_), není to pro mě argument. MikRom(neregistrovaný) 1. Ziadne deklaracie ma nijako nerozculuju. Ani v Perle predsa netreba premenne deklarovat. Alebo ako to myslis? 2. Pre pouzitie defaultnych hodnot si zvolil akurat priklad so zoznamom v ktorom to nefunguje. Python vzdy vytvara na zoznamy referencie a z toho plynie aj spravanie funkcie t(). Ak ju zavolas s argumentom prazdnym alebo neprazdnym zoznamom, bude fungovat, tak ako ocakavas, napr: print t([]) print t([]) print t(t([])) print t(['a','b']) print t(['x'])Toto ako zaobchadza Python s listami ma tiez netesi, lebo pri priradeni list2=list1 sa vytvori len nova referencia na ten isty list. Ak chce clovek vytvorit novy list ako kopiu stareho treba urobit list2=list1[:] Inac ale defaultne hodnoty vo funkciach prakticky funguju, napr: def halo(meno="Vaclav"): return "Halo %s" % meno print halo() print halo ('MikRom')3. Lambda funkcie neposkytuju taku funkcionalitu ako pomenovane funkcie - ano s tym suhlasim, ale Guido sam nema zrejme lambdy rad a chcel ich v Pythone 3000 povodne aj zrusit. Zrejme si mysli, ze sa moc nepouzivaju. 4. Ze referencie nechybaju, toho dokazom je tvoj priklad s funkciou t(). Na zoznamy sa vzdy pouzivaju referencie. Swap tiez funguje l1=['a','b'] l2=['x','y'] print "l1=%s, l2=%s" % (l1, l2) l1, l2 = l2, l1 print "l1=%s, l2=%s" % (l1, l2)Ina vec je, ze netreba explicitne dereferencovat ako v Perle. Ale to pracu so zlozitejsimi strukturami podla mna skor zjednodusuje. 5. __identifikatory__: Ano v Pythone si treba zapamatat co znamena if __name__ == "__main__": ...ale je to podobne ako vediet v Perle, co to je $_,@_,... 6. self: Python prostrednictvom self pri premennej, resp. funkcii rozlisuje, ci sa jedna o atribut, resp. metodu aktualneho objektu, alebo o nejaky globalny identifikator (ak tam self nie je). Self je vlastne referencia na slovnik, ktory reprezentuje dany objekt. Identifikator self pochadza z Perlu. Python prebral z Perlu sposob, ze objekty su reprezentovane cez asociativne polia (t.j. slovniky). A v Perle sa tiez doporucuje odkaz na aktualny objekt oznacovat ako $self. MikRom(neregistrovaný) Vynutene odsadzovanie ma aj svoje vyhody - precitaj si napriklad toto: Python: Myths about Indentation Petr(neregistrovaný) Dekuji za radu, ale rozhodl jsem se ji nenasledovat. JS(neregistrovaný) def generuj_soucet(a,b): yield 'print '+str(a)+'+'+str(b) def generuj_funkci_soucet(x,y): yield 'def soucet('+str(x)+','+str(y)+')' for s in generuj_soucet(a,b): yield ' '+s for s in generuj_soucet(1,2): print s for s in generuj_funkci_soucet('cislo1','cislo2'): print sPak muzete generator generuj_soucet pouzit na obou urovnich, a budete mit zarovnani spravne, jak ukazuje funkce generuj_funkci_soucet. Rejpal(neregistrovaný) JS(neregistrovaný) Nevim co nazyvate "cistym zpusobem generovani kodu" - kod (ve smyslu zdrojak) jsou prece retezce. Nevim, jak byste to chtel delat cisteji bez retezcu, asi by zase pomohl nejaky priklad. Vyse uvedeny program si navic nedava vyssi ambice, nez byt kratkou ilustraci toho, o cem autor tvrdil, ze to neni mozne. Rejpal(neregistrovaný) Tomu moc nerozumim. Neni proste v dynamickem jazyce lepsi, nez ten kod vygenerovat, ho rovnou provest?Jako přes eval? A co když ten jazyk používá inkrementální in-memory kompilátor, jako třeba všelijaké mutace Lispu? to ho budete pokaždé znovu kompilovat? ;-) A generovat kod, ktery bude dale nekdo upravovat rucne, mi nepripada zrovna dobry napad (z hlediska spravy).Proč? To nepoužíváte kompilátory? Nikdo snad neříká, že by se ručně upravoval vygenerovaný kód, takoví šílenci snad už vyhynuli. Pokud generátor vytváří správný výstup, není třeba vrtat se v jeho výstupu - přece když potřebuju upravit program, taky se nevrtám ve strojáku hexeditorem, ale upravím zdrojový kód a zrekompiluju ho. Nevim co nazyvate "cistym zpusobem generovani kodu" - kod (ve smyslu zdrojak) jsou prece retezce.Ehm, řetězce? Už jste slyšel o syntaktickych stromech? A o jejich transformátorech? Nebo třeba o partial application? Pokud vím, partial application používá třeba Psyco. JS(neregistrovaný) O AST vim, ale pokud by ten dotycny generoval primo AST (a ja bych to mimochodem delal take tak, ale v Pythonu pro to skutecne nevidim zadny duvod), pak by samozrejme problemy s whitespace asi nemel. ;-) Rejpal(neregistrovaný) Tomu moc nerozumim. Neni proste v dynamickem jazyce lepsi, nez ten kod vygenerovat, ho rovnou provest?Jako přes eval? A co když ten jazyk používá inkrementální in-memory kompilátor, jako třeba všelijaké mutace Lispu? to ho budete pokaždé znovu kompilovat? ;-) A generovat kod, ktery bude dale nekdo upravovat rucne, mi nepripada zrovna dobry napad (z hlediska spravy). Nikdo snad neříká, že by se ručně upravoval vygenerovaný kód, takoví šílenci snad už vyhynuli. Pokud generátor vytváří správný výstup, není třeba se vůbec vrtat v jeho výstupu - přece když potřebuju upravit program, taky se nevrtám ve strojáku hexeditorem, ale upravím zdrojový kód a zrekompiluju ho. Nevim co nazyvate "cistym zpusobem generovani kodu" - kod (ve smyslu zdrojak) jsou prece retezce. Ehm, řetězce? Už jste slyšel o syntaktickych stromech? A o jejich transformátorech? Nebo třeba o partial application? Pokud vím, partial application používá třeba Psyco. Techniky jako partial application dále stírají rozdíly mezi kompilátory a interprety a přitom můžou často vyžadovat generování kódu za chodu, s tím, že za to něco přinesou - v případě Psyca třeba ten výkon. :-) Probém je, kam to generování napasujete. Pokud jazyk AST nějakým způsobem neexponuje (což většina jazyků nedělá), holt se člověk musí uchýlit ke generování textu. Tím sice nenapíšete něco jako Psyco, ale něco jako třeba ESQL už ano, a i k takovým věcem se generování kódu často používá. Nebo třeba AOP, pokud to jazyk neumí lepšími prostředky, jako je třeba metaobjektový protokol. Ale určitě má smysl tyhle věci dělat. Petr(neregistrovaný) Pokud mate na mysli "z Pythonu generuji dalsi Python", pak to muze byt lepsi - ale stejne nemusi. Priklady: a. Generovani kodu muze byt cast "build" procesu. Nikoliv dynamicky za behu aplikace, ale dynamicky z makefilu. b. Proc bych nemohl Python generovat z jineho jazyka? Napriklad z C aplikace? Napriklad protoze ke generovani kodu musim analyzovat velke mnozstvi dat a mam na to v C hotove a odladene knihovny? c. A z druhe strany, proc bych nemohl Python generovat ze skriptu nebo treba z sqlplus? Zejmena *tady* mam problem s nejakym globalnim trackovanim hloubky vnoreni. Petr(neregistrovaný) Pokud vase druha veta naznacuje, ze by snad generovany kod mel byt "spravne strukturovany" a ze by to nemel byt "jeden velky skript", pak nechapu proc. Vystup z lexu nebo yaccu snad hezky a strukturovany je? Proc by mel vubec byt? 1. Nadeklarujeme FUNCSTACK = []. Volající zavolá podřízený generátor, ten vygeneruje funkci stackFunc(). Volající udělá FUNCSTACK.append(stackFunc()). Toto udělá nadřízený generátor kolikrát potřebuje, vybere si funkce ve své funkci třeba pomocí FUNCSTACK.pop() a volá je podle potřeby. Takto si nikdo žádný globální stav pamatovat nemusí; jediný globální stav je v globální proměné FUNCSTACK. 2. Volající si pamatuje jenom svůj lokální stav a indentuje o jednu úroveň přijatý kód od volaného, kdykoliv je potřeba. class Generator(object): def __init__(self): self.codeRows = [] def indent(self): self.add('$I') def detent(self): self.add('$D') def add(self, row): self.codeRows.append(row) def process(self): indentLevel = 0 indentedRows = [] for row in self.codeRows: if row == '$I': indentLevel += 1 elif row == '$D': indentLevel -= 1 else: indentedRows.append(indentLevel * 4 * ' ' + row) exec '\n'.join(indentedRows) g = Generator() g.add('print "Zaciname"') g.add('for a in xrange(3):') g.indent() g.add('for b in xrange(4):') g.indent() g.add('print a * b') g.detent() g.detent() g.add('print "Vse v poradku"') g.process()Řešení č. 4: Nasazení preprocesoru případně i v kombinaci s řešením č. 3. def process_code(code): indentLevel = 0 indentedRows = [] for row in (r.strip() for r in code.split('\n')): if (not row): continue if row == 'BEGIN': indentLevel += 1 elif row == 'END': indentLevel -= 1 else: indentedRows.append(indentLevel * 4 * ' ' + row) return '\n'.join(indentedRows) exec process_code(''' print "Zaciname" for a in xrange(3): BEGIN for b in xrange(4): BEGIN print a * b END END print "Vse v poradku" ''') def process_code(code): indentLevel = 0 indentedRows = [] for row in (r.strip() for r in code.split('\n')): if (not row): continue if row == 'BEGIN': indentLevel += 1 elif row == 'END': indentLevel -= 1 else: indentedRows.append(indentLevel * ' ' + row) return '\n'.join(indentedRows) exec process_code(''' print "Kaslu na level" for a in xrange(3): BEGIN for b in xrange(4): BEGIN print a * b END END print "Vse v poradku" ''')Tak co, Petře, furt problémy? Panove, musim vam neco duleziteho rict. Ne ze bych vam chtel v necem branit, to by me ani ve snu. Jen me to tak napadlo, ... mozna je to malickost, bezvyznamny detail. Ale dobra, kdyz ven s tim tak ven s tim. Jste s touhle diskusi celkem brutalne off-topic. :D JS(neregistrovaný) Petr(neregistrovaný) Smyslem meho argumentu bylo, ze existuji niche, ve kterych Python bidne hyne zatimco Perl si jich uziva. Implicitne pak tvrdim, ze na zaklade toho je Perl obecnejsi a ma vyssi hodnotu (a ted kvantifikuji, napriklad pro me). Nevyslovena premisa konecne je, ze neexistuje niche, ve kterem prezije Python a ne Perl. JS(neregistrovaný) Navic, opravdu nic nebrani tomu, generovat z te aplikace jenom nejaky mezivysledek, ktery se pote Pythonem zpracuje nebo zkompiluje (i kdyby slo jen o pridani nejakych znacek zacatek a konec bloku, ale ja bych spis vytahl z te aplikace co vlastne chce a kod vygeneroval Pythonem). Tam uz si to zarovnani pamatovat lze. Nakonec tim usetrite cas, protoze pokud je jazyk, z ktereho chcete ten Python generovat, natolik dementni, ze si nemuzete pamatovat odsazeni, pak si co nejrychlejsim prechodem do Pythonu praci jen usnadnite. :) Predchozi odstavec plati i pro Perl, samozrejme. Perl a Python jsou prinejmensim ekvivalentni jazyky (to spis Python ma sirsi zaber, protoze treba takovy Blender nebo Maya skriptovani v Perlu neumoznuje). Takze asi tezko najdete situaci, kde by se dal pouzit jenom Perl. 43 tukan(neregistrovaný) Jedine, co se mi na tom nelibi, jsou scrollbary, jelikoz misty mi ten pre blok pretejka horizontalni rozmer clanku. To ale hraje jen pro "pre" teorii, jelikoz bez toho tagu by se browser pokusil zalamovat slova. Mozna je neco spatne ve Vasem prohlizeci, nebo mozna nejakym zahadnym zpusobem dostavate z roota jiny clanek nebo style sheet nez ja. 98 Je to pro jistotu, po vas to samozrejme bude jeste nekdo cist, ale aby se treba v casove tisni na takovou "malickost" nezapomelo (jako jednou davno v mem pripade, ale to byla moje chyba, protoze davam clanky na posledni chvili a chudak sefredaktor :-). tukan(neregistrovaný) Tady máte screenshot: http://img519.imageshack.us/img519/254/rootqx2.png Napriklad clanek http://www.root.cz/clanky/hratky-z-radky-kombinace-procesu-podruhe/ pouziva ty same PRE tagy jako muj, ten se vam zobrazi jak? Dival jsem se do zdrojovych kodu clanku (online verzi) a PRE tagy tam jsou. A ve stylesheetu je monospace "cerne na bilem", tak opravdu nevim v cem je problem. Ptal jsem se na to i v redakci a pochodil jsem stejne - jim se zobrazuje clanek spravne a navic mezi PRE a CODE-AREA necini rozdil (krom toho ze CODE-AREA ma zvlastni ramecek). Navic CODE-AREA je pouze interni tag a nepatri do html. Takze v podstate nevim co mam delat, aby bylo PRE jeste vic PREformatovane nez ted. :)
My apologies if this has been asked before. My impression is that in numpy, 2 arrays can share the same memory. Take the following example: import numpy as np a=np.arange(27) b=a.reshape((3,3,3)) a[0]=5000 print (b[0,0,0]) #5000 #some tests: a.data is b.data #False a.data == b.data #True c=np.arange(27) c[0]=5000 a.data == c.data #True ( Same data, not same memory storage ), False positive So clearly b didn't make a copy of a, it just created some new meta-data and attached it to the same memory buffer that a is using. Is there a way to check if two arrays reference the same memory buffer? My first impression was to us a.data is b.data, but that returns false. I can do a.data == b.data which returns True, but I don't think that checks to make sure a and b share the same memory buffer, only that the block of memory referenced by a and the one referenced by b have the same bytes.
In a certain way, you can see some of the operator function as these as well. For example, operator.itemgetter() works this way: import operator get1 = operator.itemgetter(1) # creates a function which gets the item #1 of the given object get1([5,4,3,2,1]) # gives 4 This is often used e. g. as a key= function of sorting functions and such. Similiar, more dedicated use cases are easily imaginable if you have a concrete problem which you can solve with that. In the same league you have these "decorator creators": def indirect_deco(outer_param): def real_deco(func): def wrapper(*a, **k): return func(outer_param, *a, **k) return wrapper return real_deco @indirect_deco(1) def function(a, b, c): print (((a, b, c)) function(234, 432) Here as well, the outer function is a factory function which creates the "real deco" function. This, in turn, even creates another oner which replaces the originally given one.
I have the same question as this poor app engine developer: https://groups.google.com/group/google-appengine/browse_thread/thread/f7a44b707119013c/81ba15c883ba95fe My json serialization crashes when it hits the binary data for the png image (0x89) in my model. I don't need to serialize this data so I'd either like to skip the field or simply output something like <binary>. this is the handler: class FillList(webapp.RequestHandler): def get(self): fills = Fill.all() self.response.headers['Content-Type'] = 'application/json' self.response.out.write(jsonGQL.encode(fills.fetch(100))) I tried this: elif isinstance(obj, db.Blob): return "<binary>" but the error persists. The traceback is: Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__ handler.get(*groups) File "~/app/api.py", line 61, in get self.response.out.write(jsonGQL.encode(fills.fetch(100))) File "~/app/jsonGQL.py", line 103, in encode return GqlEncoder().encode(input, exclude=[]) File "~/app/jsonGQL.py", line 87, in encode return simplejson.JSONEncoder.encode(self, o) File "~/app/simplejson/encoder.py", line 216, in encode chunks = list(chunks) File "~/app/simplejson/encoder.py", line 482, in _iterencode for chunk in _iterencode_list(o, _current_indent_level): File "~/app/simplejson/encoder.py", line 380, in _iterencode_list for chunk in chunks: File "~/app/simplejson/encoder.py", line 496, in _iterencode for chunk in _iterencode(o, _current_indent_level): File "~/app/simplejson/encoder.py", line 485, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "~/app/simplejson/encoder.py", line 439, in _iterencode_dict yield _encoder(value) File "~/app/simplejson/encoder.py", line 50, in py_encode_basestring_ascii s = s.decode('utf-8') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte
mars Connaissances de base pour Kubuntu Bienvenue à tous les lecteurs. Ce sujet a pour but d'apporter les connaissances de base à toute personne débutant sous Kubuntu. Il est très bon pour tout débutant de lire ce post, mais il est aussi très conseillé aux personnes plus expérimenté, car il contiendra des conseils de base mais aussi des astuces d'utilisation pas inutiles. Ce post n'est EN AUCUN CAS réservé à des questions. Les commentaires posté ici doivent être limités à des propositions d'ajouts. Nous essayerons, dans la limite de nos capacités, de faire en sorte que ce post soit à jour pour chaque version stable de Kubuntu, mais peut-être aussi pour la version LTS de Kubuntu et la version unstable du moment (requiert plus de travail). Bien entendu, toute aide de la part des membres de ce forum pour maintenir ce post est bienvenue. SOMMAIRE : - Les dépôts - Les paquets souvent utilisés (multimédia, autres) - conseil de bases sur l'utilisation de Kubuntu - Les dépôts Un fichier sources.list de base : Linux utilise pour installer ses logiciels des dépôts. Pour avoir un maximum de logiciels disponibles, ainsi qu'un maximum de fonctionnalités il vous faut un maximum de dépôts. Mais ATTENTION, les dépôts sont une partie sensible de Linux. Si un paquet (conteneur de logiciel) a été mal fait, il peut entièrement casser votre système. Pour cela, nous vous proposons ici un fichier sources.list très complet ne contenant que des dépôts officiels ou maintenus par des gens compétents. Pour l'utiliser, il vous faudra éditer le fichier sources.list avec cette commande à entrer dans une Konsole kdesu kwrite /etc/apt/sources.list et d'y coller ceci en remplacement du contenu de ce fichier : # # dépôt du CD utilisé pour l'installation et à utiliser en cas de problème et de pertes du réseau # deb cdrom:[Kubuntu 6.10 _Edgy Eft_ - Bêta i386 (20060928)]/ edgy main restricted # dépôt officiel basique de Kubuntu deb http://archive.ubuntu.com/ubuntu feisty main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu feisty-updates main restricted universe multiverse # dépôt source officiel basique de Kubuntu ; ces dépôts sont peu utiles au quotidien et sont donc commentés # deb-src http://fr.archive.ubuntu.com/ubuntu feisty main restricted universe multiverse # deb-src http://fr.archive.ubuntu.com/ubuntu feisty-updates main restricted universe multiverse # mise à jour de sécurité de Kubuntu deb http://security.ubuntu.com/ubuntu feisty-security main restricted universe multiverse # deb-src http://security.ubuntu.com/ubuntu feisty-security main restricted universe multivers # dépot backports de Kubuntu ; ces dépôts contiennent des mises à jour de logiciels ne concernant pas la sécurité deb http://archive.ubuntu.com/ubuntu feisty-backports main universe multiverse restricted # COMMERCIAL ce dépôt contient des logiciels commerciaux deb http://archive.canonical.com feisty-commercial main #LES DÉPÔTS SUIVANT NE SONT PAS SUPPORTES PAR CANNONICAL, LA SOCIÉTÉ DÉVELOPPANT KUBUNTU #LES BUGS NE SONT DONC PAS IMPUTABLE A CANNONICAL #VOUS LES UTILISEZ DONC A VOS DÉPEND #KDE latest : ce dépôt fourni par les développeurs de KDE contient des mises à jour spécifiques à KDE #deb http://kubuntu.org/packages/kde-latest feisty main #Koffice latest : ce dépôt fourni par les développeurs de KDE contient des mises a jour de Koffice #deb http://kubuntu.org/packages/koffice-latest feisty main #amarok latest : ce dépôt fourni par les développeurs de KDE contient des mises à jour d'Amarok #deb http://kubuntu.org/packages/amarok-latest feisty main #medibuntu : ces dépôts contiennent des logiciels à la légalité douteuse dans certains pays, faute de brevets logiciels deb http://medibuntu.sos-sts.com/repo/ feisty free non-free il se peut que vous ayez des erreurs lors du lancement de cette commande. Dans ce cas allez voir ce post : http://forum.kubuntu-fr.org/viewtopic.php?id=53202 qui explique comment régler le problème. Il vous faudra taper cette commande aprés avoir modifier ce fichier. En effet les paquets sont signés pour éviter le piratage mais pour cela il vous faut la clé pour vérifier les paquets : wget -q http://medibuntu.sos-sts.com/repo/medibuntu-key.gpg -O- | sudo apt-key add - && wget http://people.ubuntu.com/~jriddell/kubuntu-packages-jriddell-key.gpg && sudo apt-key add kubuntu-packages-jriddell-key.gpg && rm kubuntu-packages-jriddell-key.gpg Les lignes commencant par un # ne sont pas lu par le programme et donc ignoré. Certaines sont des commentaires du fichier, d'autres des dépots utile au développeur (les dépots deb-src) et d'autres (comme les dépots contenant -latest) des dépots de mise a jour non encore activé car n'en contenant pas. Si vous voulez vous tenir au courant de mises a jour vous pouvez le faire en regardant de temps en temps ce site : http://www.kubuntu.org/ ou les mises a jour sont annoncés. Commandes courantes à utiliser pour gérer les logiciels : Nous vous donnons ici les commandes de base à utiliser pour gérer les logiciels, en installer, en supprimer, les mettre à jour. Ces commandes seront données deux fois, une à utiliser en console, l'autre, de manière graphique dans le logiciel adept_manager que l'on trouve dans le menu KDE, sous-menu Système, sous le nom de Gestionnaire de paquets Adept. Ces commandes sont équivalentes ; les une se font en ligne de commandes et les autres en graphique, à la souris. Avant toute chose : mettre à jour la liste des logiciels fournis par les dépôts avec la commande : en konsole : sudo apt-get update dans adept : le bouton recharger en haut à gauche du logiciel Installer un logiciel : en konsole : sudo apt-get install le_nom_du_logiciel dans adept : rechercher dans la liste des logiciels celui que vous voulez installer. Vous pouvez filtrer la liste grâce à la zone Recherche. Une fois le logiciel trouvé, vous pouvez l'installer en faisant un clic droit sur le nom du logiciel et en choisissant "request install". Lorsque vous avez choisi tous les logiciels à installer, cliquez sur "Appliquer les changements" Supprimer un logiciel : en konsole : sudo apt-get remove le_nom_du_logiciel dans adept : rechercher dans la liste des logiciels celui que vous voulez installer comme pour en installer un. Une fois le logiciel trouvé, vous pouvez le supprimer en faisant un clic droit sur le nom du logiciel et en choisissant "request remove". Lorsque vous avez choisi tous les logiciels à supprimer, cliquez sur "Appliquer les changements" Mettre à jour vos logiciels : en konsole : sudo apt-get dist-upgrade dans adept : cliquez sur le bouton "Tout mettre a jour" suivi de "Appliquer" ou alors, attendez de voir dans votre zone de notification KDE (à gauche de l'heure) de voir une icône "Notification de mise à jour" qui vous permettra d'effectuer les mises à jour En cas de crash d'adept il se peut que vous n'arriviez plus a utiliser ni adept ni apt-get et qu'il vous gronde avec un message complexe disant qu'une autre instance de apt-get tourne. Dans ce cas essayez ceci (un reboot sera peut étre nécessaire (seulement pour les débutants aprés il faudra apprendre a chercher et tuer un processus)) : sudo fuser -vki /var/lib/dpkg/lock && sudo dpkg --configure -a ATTENTION : les commandes donnée ici sont les commandes recommandés par debian et ubuntu. Des alternatives a ces commandes existent tels que aptitude qui peuvent apporter des améliorations a celles ci. Sachez que seul les commandes donné ci dessus sont supporté par debian et ubuntu, les autres peuvent et ont déja causé des problèmes parfois grave et nécessitant une réinstallation complète du système. Nous vous déconseillons d'utiliser ces commandes tant que vous n'avez pas une maîtrise complète de votre système. Cette maîtrise viendra avec le temps. - Les paquets souvent utilisés (multimédia, autres) Voici une liste de logiciels que vous trouverez dans les dépôts et qui vous permettront d'améliorer votre expérience sur Linux. - w32codecs Permet la lecture de formats Microsoft sous linux (wma, wmv, sans DRM) - libdvdcss2 Permet la lecture de DVD crypté sous linux - libdvdread3 Permet la lecture de DVD avec les menu sous linux - libxine-extracodecs Permet d'avoir accès a la lecture d'un maximum de format de média sous Kubuntu - libk3b2-mp3 Permet de graver des Cd audio depuis K3B - libtunepimp5-mp3 Permet de compléter les tags de fichier mp3 dans amarok - sun-java6-plugin Plugin java pour la navigation web - flashplugin-nonfree Plugin flash pour la navigation web - printconf Permet la configuration facile d'imprimante (il n'est pas installé par défaut dans feisty) - Flac et Sox Permettent une gestion de l'encodage plus poussé dans entre autre k3b conseil de bases sur l'utilisation de Kubuntu Tout d'abord un premier conseil : oubliez vos réflexes de windowsien. Vous ne savez pas (encore) vous servir de votre systéme, et il peut tout faire pour vous a condition que vous lui parliez gentiment. Sachez que la stabilitéde linux n'est pas une légende, certaines personnes n'éteigne jamais leur pc et font des "combats" d'uptime (l'uptime mesure le temps depuis lequel le pc n'a pas été redémarré). Des valeurs courante d'uptime atteigne plusieurs années, mais pour ca il faut parler gentiment a son systéme. Un des premiers réflexes a perdre est de chercher a tout prix a installer un antivirus, un firewall et des logiciels créant de beaux effets de bureau. Dites vous que vous avez le temps et que ces logiciels sont soit inutile (firewall et antivirus) soit nécessite de connaitre son systéme (firewall et effets 3D). Donc prenez votre temps, attendez quelques mois avant d'essayer beryl. Quelques astuces de kde : - rajouter la corbeille sur le bureau : éditer le fichier de la corbeille (sous linux tout est fichier c'est un concept que je développerais peut étre plus tard) : kate ~/Desktop/trash.desktop ce fichier doit aprés modification ressembler a ca : [Desktop Entry] Comment=Contains removed files Comment[fr]=Contient les fichiers supprimés EmptyIcon=trashcan_empty Encoding=UTF-8 Hidden=false Icon=trashcan_full Name=Trash Name[fr]=Corbeille Type=Link URL=trash:/ - sauvegarde de session : kde comme vous l'avez peut étre remarqué sauvegarde votre session. le probléme est que lorsqu'une application a planté et n'est pas visible kde va la relancer inlassablement a chaque démarrage. pour cela il y a deux parades. La premiére consiste a arréter cette sauvegarde de session puis de relancer les programmes a chaque démarrage en les placant dans ~/.kde/Autostart La deuxiéme consiste a sauvegardé une session type qui sera celle lancé a chaque démarrage. Je ne développe pas plus ici ces deux méthodes car ca nécessiterait bien plus de place et on déja été bien documenté ailleurs : http://forum.kubuntu-fr.org/viewtopic.php?id=107453 (lien temporaire en attendant que je fasse un truc plus clair) - connexion automatique au réseau : Un outil trés pratique est maintenant dans kubuntu : Knetworkmanager. Celui ci a pour but de rendre la connexion au réseau transparente. Vous découvrez un réseau knetworkmanager enregistre sa configuration et vous y connectera automatiquement la prochaine fois. Il sait aussi choisir entre plusieurs réseau disponible celui qui offrira la meilleur qualité. Pour l'utilisé au mieux il vous faut laisser kwalletmanager lancé. Celui ci sert a stocker tout vos mot de passe. Seulement pas soucis de sécurité il demande lui aussi un mot de passe avant de vous laisser accéder a ceux qu'il a enregistré. On est pas la NASA donc par soucis de praticité je vous conseille de mettre un mot de passe vierge. POST EN COURS DE RÉDACTION Hors ligne mars Re : Connaissances de base pour Kubuntu réservé Hors ligne mars Re : Connaissances de base pour Kubuntu réservé Hors ligne CorSu Re : Connaissances de base pour Kubuntu Bonjour, quand je tape la commande: kdesu kwrite /etc/apt/sources.list j'obtiens ca: X Error: BadDevice, invalid or uninitialized input device 168 Major opcode: 145 Minor opcode: 3 Resource id: 0x0 Failed to open device X Error: BadDevice, invalid or uninitialized input device 168 Major opcode: 145 Minor opcode: 3 Resource id: 0x0 Failed to open device Quelqu'un sait d'où ca vient ? Merci Woshee Re : Connaissances de base pour Kubuntu C'est pas une erreur, tu peux l'ignorer. Pour mettre a jour les logiciels, utiliser aptitude plutot qu'apt-get, et upgrade, pas dist-upgrade. Devenez parrain Linux ou trouvez quelqu'un pour vous aider près de chez vous: http://parrains.linux.free.fr/ Hors ligne CorSu Re : Connaissances de base pour Kubuntu Mais ca ne me permet pas d'ouvrir la liste pour y copier le code... il n'y a pas un autre moyen d'acceder à cette liste ? SamheG Re : Connaissances de base pour Kubuntu LMAA Bye ... ça veut dire CIAO en anglais ! Kansas Of Elsass Hors ligne CorSu Re : Connaissances de base pour Kubuntu C'est bon, merci beaucoup mars Re : Connaissances de base pour Kubuntu C'est pas une erreur, tu peux l'ignorer. Pour mettre a jour les logiciels, utiliser aptitude plutot qu'apt-get, et upgrade, pas dist-upgrade. Bon jusqu'a maintenant je disais trop rien mais la j'interviens! NE SURTOUT PAS UTILISER APTITUDE il n'apporte rien de plus et apporte des emmerdes! Debian est une distribution pensée, avec des outils pensée et aptitude n'en fait pas partie et comme tout outil non pensé pour debian il est trés bien mais pas pour des débutants. pour stopper net les controverses sachez que un grand nombre de personnes qui ont fait l'upgrade edgy -> feisty avec aptitude ont risqué de tout casser (quand ils ne l'ont pas fait) car aptitude ne voulait pas supprimer mdadm alors que apt le supprimé. deuxiéme raison valable : pourquoi tout les "pro" debian utilisent apt-get et pas aptitude. edit : rajout dans le tuto d'un avertissement sur aptitude et de la modification a faire pour supprimer les messages d'erreur X en console. Hors ligne Woshee Re : Connaissances de base pour Kubuntu Dis upgrade c'est pour aller d'une version d'ubuntu a l'autre (d'ou le dist comme distribution) et pas pour mettre a jour des paquets. Aptitude gère merveilleusement mieux les dépendances que apt-get, et tu dois être la seule personne ici qui en dise du mal. De plus les personnes qui ont fait la migration edgy->feisty en console n'ont pas utilisé les outils graphiques bien plus puissants mis a leur disposition. Devenez parrain Linux ou trouvez quelqu'un pour vous aider près de chez vous: http://parrains.linux.free.fr/ Hors ligne mars Re : Connaissances de base pour Kubuntu Dis upgrade c'est pour aller d'une version d'ubuntu a l'autre (d'ou le dist comme distribution) et pas pour mettre a jour des paquets. Aptitude gère merveilleusement mieux les dépendances que apt-get, et tu dois être la seule personne ici qui en dise du mal. De plus les personnes qui ont fait la migration edgy->feisty en console n'ont pas utilisé les outils graphiques bien plus puissants mis a leur disposition. 1/ faire un apt-get upgrade n'a aucune raison sous ubuntu ca en a sous debian sid mais aucune sous ubuntu! trouve moi une seule raison valable (avec justification) d'utiliser upgrade a la place de dist-upgrade et je remplace dans le tuto. 2/ t'as raison pour aptitude j'ai tort et tout les dev ubuntu et kubuntu aussi. Comme on avait tort sur les dépots czessi et kubuntu-de. et ceux qui ont cassé leur distrib aussi. 3/ pour ma part j'ai fait ca en console avec apt-get c'est passé comme une lettre a la poste. De plus cette page n'est pas un tuto pour faire une mise a jour edgy -> feisty Hors ligne Neuro Re : Connaissances de base pour Kubuntu Faut il enlever les # devant les lignes # deb ... ? Hors ligne mars Re : Connaissances de base pour Kubuntu non. Les # servent a commenté des lignes qui ne sont donc pas prises en compte. Soit ce sont des commentaires soit des dépots qui n'ont pas encore été activé. Hors ligne Neuro Re : Connaissances de base pour Kubuntu non. Les # servent a commenté des lignes qui ne sont donc pas prises en compte. Soit ce sont des commentaires soit des dépots qui n'ont pas encore été activé. Et comment savoir quand ils le seront ? (désolé mais j' aimerai comprendre). Hors ligne mars Re : Connaissances de base pour Kubuntu c'est normal et tu as raison je vais le rajouter dans le post! pour savoir quand ils le seront c'est simple : il faut regarder une fois de temps en temps ici : http://www.kubuntu.org/ des annonces de sortie de mise a jour de logiciels sont faites et a ce moment on peut activer le dépot. Par exemple si une mise a jour amarok sort tu active le dépot d'amarok et quelques jours aprés tu aura la mise a jour de disponible. Pour étre honnéte, pour feisty il y a TRES peu de chance qu'il y en ait sauf peut étre pour kde mais rien n'est moins sur. Hors ligne Neuro Re : Connaissances de base pour Kubuntu Merci pour ces précisions et pour ce sujet mars. Dernière modification par Neuro (Le 21/04/2007, à 14:57) Hors ligne beware Re : Connaissances de base pour Kubuntu Bonjour n'y a t il pas un risque d'instabilité a utilisé les backports? Hors ligne mars Re : Connaissances de base pour Kubuntu oui! mais si tu veux etre absolument stable tu dois utiliser dapper. La on parle d'une distribution desktop personnel. Aprés les risques d'instabilité sont tout de meme TRES limité. Hors ligne bruno Re : Connaissances de base pour Kubuntu t'as raison pour aptitude j'ai tort et tout les dev ubuntu et kubuntu aussi. Comme on avait tort sur les dépots czessi et kubuntu-de. et ceux qui ont cassé leur distrib aussi. C'est intéressant cette remarque sur aptitude vs apt-get, personnellement j'ai toujours pensé qu'il valait mieux utiliser aptitude (construction de l'arbre des dépendances, gestions des tags et des informations d'état, suppression des paquets marqués "auto", etc.). Aptitude à toujours beaucoup mieux fonctionné pour moi que apt-get (depuis Edgy, pas Dapper). Il me semble avoir lu à plusieurs reprises qu'aptitude était l'interface APT recommandée par Debian (cf. http://www.debian.org/doc/manuals/reference/ch-package.fr.html) As-tu des liens, ou des infos complémentaires là dessus ? Pour l'utilisation de upgrade / dist-upgrade je ne comprend pas bien ta remarque. Normalement upgrade ne proposera que de mettre à jour des paquets déjà installés, en aucun cas cela ne supprimera ou ajoutera des paquets, alors que dist-upgrade est sensé faire une mise à jour "intelligente" en gérant les conflits et dépendances, avec donc la possibilité de suppression de paquets ou installation de nouveaux paquets. Donc dans le cadre de l'utilisation d'une version desktop stable dist-upgrade est recommandé pour faire une mise à jour complète "intelligente", et commencer par un upgrade (mise à jour plus conservatrice) n'aurait de sens que sur une version instable. Est-ce bien ce que tu as voulu dire ? Sinon je pense que ce sujet épinglé est réellement très utile Dernière modification par bruno (Le 22/04/2007, à 08:17) Hors ligne mars Re : Connaissances de base pour Kubuntu alors : apt vs aptitude! déja AUCUNE doc debian ne conseil aptitude! ils le donnent juste en front end amélioré de apt-get. Ensuite il faut bien savoir que TOUT ce que fait aptitude apt-get sais le faire. Sauf que les paquets de transition, les paquets un peu particulier sont pensé sur la maniére de réagir de apt-get donc dans 99% des cas aptitude marche nickel et meme selon les gouts de certains mieux que apt-get vue qu'il automatise certaines choses. Seulement dans 1% des cas il va pas marché comme les dév l'ont envisagé (exemple de la mise a jour edgy-> feisty). Et la il va tout cassé. pour update <-> dist-upgrade tu as tout a fait raison tu as tout compris! dans debian sid il arrive souvent qu'on ait X mise a jour dont la moitié sont annoncé comme des paquets cassant le systéme avec plein de dépedances croisé... dans ce cas la on veut en général ne mettre a jour que les logiciels n'etant pas touché par ces mises a jour dangereuse et LA update a son utilité. Mais c'est tout. Sinon pour essayer de faire comprendre mes propos : debian est un systéme trés solide mais trés complexe. Quoi qu'on fasse on arrivera meme en lisant toutes les docs du monde jamais a le maitriser en quelques mois. Et c'est pour cette raison que je me permets de donner des conseils. Je ne sais pas tout loin de la. Mais j'ai assez d'expérience pour savoir certaines choses : - les dépots tiers c'est trés bien jusqu'au jour ou c'est a chié - aptitude c'est trés bien mais ca nécessite une forte expérience de apt-get pour étre sur que aptitude fait pas de bétises. Et le probléme c'est que souvent des gens avec peu d'expérience arrivent et explique qu'ils savent tout et que les dépots tier c'est le réve surtout avec aptitude... et du coup nous on est décridibilisé parce que c'est vrai que ca semble trés bien. Jusqu'au jour ou ca péte tout. mais la il est trop tard. Donc voila chacun fait ce qu'il veut moi j'ai fait cette doc, je donne les info que je connais et dont je suis certains. Aprés ........ Hors ligne Neuro Re : Connaissances de base pour Kubuntu Sujet trés utile qui m' a permis d 'aider quelques nouveaux venus alors que mon expérience est plutôt faible. Hors ligne Smarter Re : Connaissances de base pour Kubuntu Intéressant ce post Quelques trucs comme ça: - C'est Canonical, pas Cannonical - Même si il est vrai qu'il faut faire gaffe à aptitude, apt-get est maintenant fortement déconseillé par Debian - Je ne sais pas si rajouter un raccourci vers la poubelle est une "connaissance de base pour Kubuntu" - KDE 3.5.7 est prévu pour dans pas longtemps, pareil pour Amarok 1.4.6 donc oui, les dépots de kubuntu.org serviront bientôt à quelque chose. - fuser(pratique d'ailleurs, je connaissais pas) n'est pas nécessaire pour réparer apt en cas de mise à jour interrompu. Voila, à part ça c'est pas mal Hors ligne mars Re : Connaissances de base pour Kubuntu alors! - pour cannonica j'ai honte! - ensuite aptitude trouve moi une doc qui justifie tes propos clairement! pour ma part je connais pas un seul DD ou dev ubuntu qui utilise aptitude alors pour le conseiller je les vois mal le faire. (d'autant plus qu'ils le déconseillent) -la poubelle c'est vrai mais c'est une question assez souvent posé - kde 3.5.7 ne sera peut étre pas dans les dépots kubuntu! riddell est pas chaud pour se le faire vue que ca coincider avec pas mal d'autres truc (kde4 alpha, dépots gutsy entre autres, ...) - j'avoue que c'est loin d'étre obligatoire mais j'ai chopé cette commande "toute faite" sur le chan des devs kubuntu et je me suis dit bon je fais pas comme ca mais ca a l'air a la porté du premier con venu et si eux le donne ca doit marcher. (moi j'utilisais fuser a l'époque pour voir qui m'empéchait de démonter mes périph usb!) Hors ligne Smarter Re : Connaissances de base pour Kubuntu ensuite aptitude trouve moi une doc qui justifie tes propos clairement! pour ma part je connais pas un seul DD ou dev ubuntu qui utilise aptitude alors pour le conseiller je les vois mal le faire. (d'autant plus qu'ils le déconseillent) Tout droit sortie de la release note de Etch: http://www.fr.debian.org/releases/etch/i386/release-notes/ch-whats-new.fr.html#s-pkgmgmt kde 3.5.7 ne sera peut étre pas dans les dépots kubuntu! riddell est pas chaud pour se le faire vue que ca coincider avec pas mal d'autres truc (kde4 alpha, dépots gutsy entre autres, ...) Ah ouais? Je vais peut-être faire un passage à Gutsy plutôt que prévu, moi qui m'étais promis de me retenir pour cette fois-ci j'avoue que c'est loin d'étre obligatoire mais j'ai chopé cette commande "toute faite" sur le chan des devs kubuntu et je me suis dit bon je fais pas comme ca mais ca a l'air a la porté du premier con venu et si eux le donne ca doit marcher. (moi j'utilisais fuser a l'époque pour voir qui m'empéchait de démonter mes périph usb!) D'ailleurs je viens de me rendre compte que c'est ce qui est utilisé(fuser -v ) par KDE quand on a quelque chose qui empéche le démontage d'une clé usb, c'est pratique mais ça ne doit pas dire grand chose à un utilisateur lambda... Hors ligne rlb29 Re : Connaissances de base pour Kubuntu Debian préconise l'utilisation d'aptitude : http://www.debian.org/doc/manuals/refer … ge.en.html Il gère mieux les dépendances qu'apt-get...si ils les connait !...donc éviter de faire un coup apt-get, un coup aptitude..etc, car dans ce cas là il sera dans l'ignorance de ce que apt-get a bien pu faire. Debian-sid - kernel 2.6.30-5-amd64 - gestionnaire de fenêtres : xmonad Hors ligne
Module ParseBlastTable source code A parser for the NCBI blastpgp version 2.2.5 output format. Currently only supports the '-m 9' option, (table w/ annotations). Returns a BlastTableRec instance reader_keywords = {'BLASTP': 'version', 'Database': 'database'... __package__ = 'Bio.Blast' reader_keywords Value: {'BLASTP': 'version', 'Database': 'database', 'Fields': 'fields', 'Iteration': 'iteration', 'Query': 'query'}
From PEP 328, http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports you should actually avoid naming a python module starting with a "dot" because it means relative imports in Python. If you really insist on doing so, you can but you will have to use the imp module. Example usage:- import imp with open('.secret/__init__.py', 'rb') as fp: secret = imp.load_module('.secret', fp, '.secret/__init__.py', \ ('.py', 'rb', imp.PY_SOURCE)) So for your use case where you want to load in values from db.py, it would look something like this:- import imp with open('.secret/db.py', 'rb') as fp: db = imp.load_module('.secret', fp, '.secret/db.py', \ ('.py', 'rb', imp.PY_SOURCE)) print db.DB_PASSWORD # This will print out your DB_PASSWORD's value. Or use it whichever way you want. Won't advise on it though.
Expect4r – Interact with Cisco IOS, IOS-XR, and Juniper JUNOS CLI. Expect4r is a library that enables a ruby program to 'talk' to routers following a written ruby script. You talk to routers by connecting to them using ssh or telnet and send exec or config command and collect router output than can be parsed using ruby. Connect to routers ios = Ios.new_telnet :host=> "hostname", :user=> "username", :pwd => "password" ios.login iox = Iox.new_telnet 'host', 'username', 'password' iox.login j = J.new_telnet :host=> '', :user=> 'lab', :pwd => 'lab' j.login Connect to a box via another my_mac = RShell.new_ssh 'mac', 'me' router = Iox.new_telnet 'hostname', 'username' router.login_via my_mac Push configurations to routers ios.config 'no logging console' ios.config %{ interface loopback0 shutdown } iox.config iox.exp_send 'interface GigabitEthernet0/2/0/0' iox.exp_send 'desc to switch port 13' iox.exp_send 'ipv4 address 190.0.0.9 255.255.255.252' iox.exp_send 'no shut' iox.commit iox.config %| interface GigabitEthernet0/2/0/0 desc to switch port 13' ipv4 address 190.0.0.9 255.255.255.252' no shut' | j.config %{ edit logical-router Orleans protocols bgp edit group session-to-200 set type external set peer-as 200 set neighbor 40.0.2.1 peer-as 200 } exec commands j.exec 'set cli screen-length 0' iox.exec "terminal len 0\nterminal width 0" exec shell commands iox.shell 'pidin' interact with CLI. irb> r.interact # # ^Z to terminate. # router#clear line 2 [confirm] [OK] router# ^Z => nil irb> irb(main):210:0* j.interact # # ^Z to terminate. # jme@router> configure Entering configuration mode The configuration has been changed but not committed [edit] jme@router# rollback load complete [edit] jme@router# show | compare [edit] jme@router# ^Z => nil irb(main):211:0> Parsing output The output is returned as an array of arrays of responses to commands. Each response is returned as an array of lines. Parsing a response becomes a matter of iterating an array using the Arrays's enumerator methods such as find, find_all ... irb> output = ts.exec %{ irb" show terminal | include History irb" show line | include AUX irb" } => [ ["show terminal | include History", "History is enabled, history size is 10.", "ios#"], ["show line | include AUX", " 17 AUX 9600/9600 - 0/0 -", "ios#"] ] output[0] contains output for 1st command 'show terminal'. output[1] contains output for 1st command 'show line'. ... output[n-1] contains output for nth command. Ios Ping irb(main):016:0> ios.ping '192.168.1.23', :count=> 100, :pct_success=>90, :sweep_max_size=> 1500 => [ 99, [146148, 146500], [["ping", "Protocol [ip]: ", "", "Target IP address: ", "192.168.1.23", "Repeat count [5]: ", "100", "Datagram size [100]: ", "", "Timeout in seconds [2]: ", "", "Extended commands [n]: ", "", "Sweep range of sizes [n]: ", "yes", "Sweep min size [36]: ", "", "Sweep max size [18024]: ", "1500", "Sweep interval [1]: ", "", "Type escape sequence to abort.", "Sending 146500, [36..1500]-byte ICMP Echos to 192.168.1.23, timeout is 2 seconds:", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!.!!!!!!!!!!!!.!!!!!!!!.!!!!!!!!!!!!!!!!!!!", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", ... "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "Success rate is 99 percent (146148/146500), round-trip min/avg/max = 1/7/924 ms", "ios#"]]] Iox ping irb> iox.ping '192.168.1.100' => [100, [5, 5], [["ping 192.168.1.100", "\rTue Oct 26 08:42:58.235 UTC", "Type escape sequence to abort.", "Sending 5, 100-byte ICMP Echos to 192.168.1.100, timeout is 2 seconds:", "!!!!!", "Success rate is 100 percent (5/5), round-trip min/avg/max = 1/1/2 ms", "RP/0/0/CPU0:Paris-rp0#"]]] irb> iox.ping '192.168.1.100', :sweep_min_size => 1000, :sweep_max_size => 1300 => [100, [1505, 1505], [["ping", "\rTue Oct 26 08:44:33.024 UTC", "Protocol [ipv4]: ", "", "\rTarget IP address: ", "192.168.1.100", "\rRepeat count [5]: ", "", "\rDatagram size [100]: ", "", "\rTimeout in seconds [2]: ", "", "\rExtended commands? [no]: ", "", "\rSweep range of sizes? [no]: ", "yes", "\rSweep min size [36]: ", "1000", "\rSweep max size [18024]: ", "1300", "\rSweep interval [1]: ", "", "\rType escape sequence to abort.", "Sending 1505, [1000..1300]-byte ICMP Echos to 192.168.1.100, timeout is 2 seconds:", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", ... "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "Success rate is 100 percent (1505/1505), round-trip min/avg/max = 1/1/3 ms", "RP/0/0/CPU0:Paris-rp0#"]]] Junos ping irb> j.ping '192.168.1.123' => [5, [5, 0], [["ping 192.168.1.123 rapid ", "PING 192.168.1.123 (192.168.1.123): 56 data bytes", "!!!!!", "--- 192.168.1.123 ping statistics ---", "5 packets transmitted, 5 packets received, 0% packet loss", "round-trip min/avg/max/stddev = 2.310/2.943/4.390/0.753 ms", "", junos> "]]]
A friend and I have been playing around with pygame some and came across this tutorial for building games using pygame. We really liked how it broke out the game into a model-view-controller system with events as a go-between, but the code makes heavy use of isinstance checks for the event system. Example: class CPUSpinnerController: ... def Notify(self, event): if isinstance( event, QuitEvent ): self.keepGoing = 0 This results in some extremely unpythonic code. Does anyone have any suggestions on how this could be improved? Or an alternative methodology for implementing MVC? This is a bit of code I wrote based on @Mark-Hildreth answer (how do I link users?) Does anyone else have any good suggestions? I'm going to leave this open for another day or so before picking a solution. class EventManager: def __init__(self): from weakref import WeakKeyDictionary self.listeners = WeakKeyDictionary() def add(self, listener): self.listeners[ listener ] = 1 def remove(self, listener): del self.listeners[ listener ] def post(self, event): print "post event %s" % event.name for listener in self.listeners.keys(): listener.notify(event) class Listener: def __init__(self, event_mgr=None): if event_mgr is not None: event_mgr.add(self) def notify(self, event): event(self) class Event: def __init__(self, name="Generic Event"): self.name = name def __call__(self, controller): pass class QuitEvent(Event): def __init__(self): Event.__init__(self, "Quit") def __call__(self, listener): listener.exit(self) class RunController(Listener): def __init__(self, event_mgr): Listener.__init__(self, event_mgr) self.running = True self.event_mgr = event_mgr def exit(self, event): print "exit called" self.running = False def run(self): print "run called" while self.running: event = QuitEvent() self.event_mgr.post(event) em = EventManager() run = RunController(em) run.run() This is another build using the examples from @Paul - impressively simple! class WeakBoundMethod: def __init__(self, meth): import weakref self._self = weakref.ref(meth.__self__) self._func = meth.__func__ def __call__(self, *args, **kwargs): self._func(self._self(), *args, **kwargs) class EventManager: def __init__(self): # does this actually do anything? self._listeners = { None : [ None ] } def add(self, eventClass, listener): print "add %s" % eventClass.__name__ key = eventClass.__name__ if (hasattr(listener, '__self__') and hasattr(listener, '__func__')): listener = WeakBoundMethod(listener) try: self._listeners[key].append(listener) except KeyError: # why did you not need this in your code? self._listeners[key] = [listener] print "add count %s" % len(self._listeners[key]) def remove(self, eventClass, listener): key = eventClass.__name__ self._listeners[key].remove(listener) def post(self, event): eventClass = event.__class__ key = eventClass.__name__ print "post event %s (keys %s)" % ( key, len(self._listeners[key])) for listener in self._listeners[key]: listener(event) class Event: pass class QuitEvent(Event): pass class RunController: def __init__(self, event_mgr): event_mgr.add(QuitEvent, self.exit) self.running = True self.event_mgr = event_mgr def exit(self, event): print "exit called" self.running = False def run(self): print "run called" while self.running: event = QuitEvent() self.event_mgr.post(event) em = EventManager() run = RunController(em) run.run()
We seem to have a tradition of using the Homestar Runner character 'Trogdor the Burninator' to request tag deletion. I thought we could use crisper images, so I made my own. >:) Request: Burninated: BONUS: The above were made using a Trogdor reference from an unknown person on the internet, which has some inaccuracies. I went to the source (Strongbad), and retraced Trogdor. This is the real Trogdor, in color, in higher definition: This inspired me, so I made some ASCII: { ( ) } "--____ )) " ) -_( \/ ( ___-´ \ | _( 0 o )_- `_ / (__-+`''-------=. _____ )_- \,/-' ,--______: .--´ / ___ __.-----_)_-\ <( V v v ---' _'=-----'/ .´ -- / `-----___. -__ {__ `----'_ | , .´ ___----------' `-_ '-----___----' ( /'--'| -- `--.__---'' ( / ' / | /_ | | ( _-) \ \ '-_) '. \_ -_ \_ `--_ `-__ `-__ `-_ /\ `-_ \ --.__A-/__\ _) | B U R N I N A T E D ! `-- `-/\_-' _/ `-__ ___-' | `-.--' | \ L__ \_.- @iglvzx's Trogdor is great, sure, but I always imagined trogdor as having a red skin (yes, I have played peasant's quest, but my artistic style is not to be questioned!). I have also taken on the daunting task of converting our good friend Mr. Troggie into a vector format (SVG), which you can download here: And for those of you who don't have a browser capable of SVG, then here's a PNG render: Do what you will with this file, and hopefully trogdor can burninate more!
First, you will need the Color class from Gdk and the Gtk class: from gi.repository import Gtk from gi.repository.Gdk import Color Then, in your handler, change the foreground color of the text field: COLOR_INVALID = Color(50000, 0, 0) // A dark red color text_field.modify_fg(Gtk.StateFlags.NORMAL, COLOR_INVALID) If you want to change the color back to the default when the text field is modified, put this in the change handler: text_field.modify_fg(Gtk.StateFlags.NORMAL, None) The RBG values for the Color class are in a range from 0-65535. For more information, see the PyGTK documentation, specifically the Widget and Color classes.
Currently I have the following code: class User(db.Model): field_names = db.StringListProperty(indexed=False) field_values = db.StringListProperty(indexed=False) field_scores = db.ListProperty(int, indexed=False) def fields_add(user_key_name, field_name, field_value, field_score): user = User.get(user_key_name) if user: try: field_index = user.field_names.index(field_name) # (1) user.field_values[field_index] = field_value user.field_scores[field_index] = field_score except ValueError: # field wasn't added to the list before user.field_names.append(field_name) user.field_values.append(field_value) user.field_scores.append(field_score) user.put() It works well, but I would like to optimize that - serialize field_name, field_value and field_score and store in one BlobProperty: class User(db.Model): fields = db.ListProperty(indexed=False) f = { 'f': field_name, 'v': field_value, 's': field_score, } user.fields = simplejson.dumps(f) But how should code (1) look like with such approach? How to find record for update?
raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Je ne faisait aucune allusion au problème de @souen. Dernière modification par raspouillas (Le 15/06/2012, à 20:37) ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] alors voici la première partie du script et la j'ai besoin d'aide car je ne suis sure de rien ]#!/usr/bin/python # encoding: utf-8 from BeautifulSoup import BeautifulSoup import urllib2 import re import time import sys import mechanize# est ce que je peux mette ces 3 lignes sur 1 seul? ignoreList = ( 'compteur des leve tot', )# pourquoi on utilise """ au lieu d'un simple "en début et fin et ne peut on simplifié la phrase? class Day: """un jours dure de 5h à 9h du matin exclu ([5h:9h[) il contient la dernière entrée (points) de ce jour pour chaque joueurs""" def __init__(self): self.entries={} def __str__(self): for entry in self.entries.items(): print entry,'+',entries[entry]# c'est normal que ce def n'est pas aligné aux autres?def utcFrance(): return 1 + time.localtime(time.time())[-1] #1 + 1 si on est a l'heure d'été # ici je crois qu'on doit modifier en def __init__(self,tuple=(5,9),utc=utcFrance()):class Date: def __init__(self,tuple=(20,0),utc=utcFrance()): self.h = (int(tuple[0])-utcFrance()+24+utc)%24 self.m = int(tuple[1]) def __cmp__(self, other): return cmp(self.points(),other.points()) def points(self): pts = {5: 10, 6: 6, 7: 3, 8: 1} return pts.get(self.h, 0) si vous avez les réponses ou d'autres suggestions je vous écoute merci En ligne Pylades Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] # est ce que je peux mette ces 3 lignes sur 1 seul? Oui, mais c’est mieux sur trois lignes. # pourquoi on utilise """ au lieu d'un simple "en début et fin et ne peut on simplifié la phrase? Pour pouvoir écrire cette docstring sur plusieurs lignes si besoin. On peut reformuler sans impacter le fonctionnement du programme. # c'est normal que ce def n'est pas aligné aux autres? Oui, faut pas toucher. # ici je crois qu'on doit modifier en def __init__(self,tuple=(5,9),utc=utcFrance()): Possible, mais c’est probablement plus compliqué… ce compteur est presque immaintenable. Mais bon, dans un futur plus ou moins proche, on va refaire un compteur propre pour le TdCT. Du coup, il s’adaptera ici en un clin d’œil. Dernière modification par Πυλάδης (Le 15/06/2012, à 18:49) “Any if-statement is a goto. As are all structured loops. “And sometimes structure is good. When it’s good, you should use it. “And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.” Linus Torvalds – 12 janvier 2003 Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Mais bon, dans un futur plus ou moins proche, on va refaire un compteur propre pour le TdCT. Du coup, il s’adaptera ici en un clin d’œil. c'est marrant nesthib m'a dit la même chose mais quand personne le sais .... donc en attendant si on veut bien continuer à m'aider j’apprends le python et j'arriverai peut être à avoir un compteur viable en attendant un compteur plus maintenable et en phase avec python 2.7.3 alors que le script de tshirtman est prévu pour du python 2.6.* /me est donc décidé à persévérer En ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] peux t'on me dire que fait (veut dire) cette partie if ( (str_date.split(' ')[0] in ['Hier'] and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5,24)) or (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5)) ): En ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] [ /me est donc décidé à persévérer /me t'encourage vivement, et j'espère que le truc grec t'a donné de vrais conseils hors forum, cause que vu d'ici, cette intervention est aussi péremptoire qu'inutile. Perso, je ne peux que te soutenir et te souhaiter de nous faire "the compteur des Lts" qui sera adapté au Cts. Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] répondu golgoth42 Floyd Pepper merci pour les encouragements, par contre continu de poster le tien j'en ai besoin pour mes test En ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 'jour Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] bonjour tout le monde En ligne souen Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Hello bonjour Tu es programmé, mais tu es libre. Ubuntu Studio "Si il n'y a pas de solution, c'est qu'il n'y a pas problème !" (sagesse Shadok) Hors ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Salutatous par Toutatis! Un vrai ennemi ne te laissera jamais tomber. Hors ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] bonjour .... raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] PS: Je n'ai de retour de réponse ? Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] ... bonjour ! Une seconde, on est samedi @ljere: spli permet de séparer une chaine en n morceaux séparés par le caractère donné. En prenant la date affichée : Hier à 21:19 ou Aujourd'hui à 08:56 on obtient alors un tableau du type [0] => "Hier", [1] => "à", [2] => "21:19" Ensuite le triple split, resplite la chaine et utilise le 3eme élément pour tenter d'en extraire l'heure. le split avec '<' est inutile dans ce cas, il a du être rajouté à une époque lointaine (ancien forum ?). On obtient donc un seul élément égal au 3eme élément déjà pris en compte ("21:19"), puis on split par le ":" pour obtenir l'heure et on s'intéresse aux heures comprises entre 5 et 24. Le deuxième partie s'intéresse aux heures entre 0 et 5. Au final, tu obtiens donc les informations pour les dernières 24 heures, et on peut, dès lors, supposer que le compteur se lance tous les jours à 5h00 du matin PS: j'ai pas répondu en mp : c'était déjà fait, et puis ça peut en intéresser d'autres Hors ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] donc comme pour nous on s’intéresse à une période de 6h à 9h if ( (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split(':')[6]) in range(8)) ): comme 9h est exclu je doit bien mettre 8? En ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 1 1787 FloydPepper 2 1543 pierguiard 3 1463 MdMax 4 1247 Azurea 5 1199 souen 6 968 Ras&#039; 7 767 raspouillas 8 552 Arcans 9 428 peterp@n 10 359 golgoth42 11 293 mindiell 12 277 omc 13 219 Πυλάδης 14 176 pololasi 15 117 edge_one 16 101 nathéo 17 99 karameloneboudeplus 18 61 agarwood 19 60 Niltugor 20 52 1101011 20 52 jeyenkil 20 52 ljere 23 43 Crocoii 24 42 nakraïou 24 42 DaveNull 26 40 Biaise 27 39 Clem_ufo 28 38 Atem18 29 22 marinmarais 30 18 Ju 31 13 Le grand rohr sha 32 10 Phoenix 32 10 FLOZz 32 10 sakul 32 10 SopolesRâ 36 6 wiscot 36 6 timsy 36 6 Slystone 36 6 Hibou57 36 6 tshirtman 36 6 marting 36 6 c4nuser 43 4 Morgiver 43 4 :!pakman 45 3 Phoenamandre 45 3 gonzolero 45 3 helly 45 3 Le Rouge 49 1 herewegoagain 49 1 TheUploader 49 1 Kyansaa 49 1 Xiti29 Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne Ras&#039; Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] J'me réveille -__________-' C'est trop tard pour les points ? Va t'faire shampouiner en GMT-4 ! http://blag.xserver-x.org/ Les types awesome n'ont rien à prouver. À personne. En ligne PPdM Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] J'me réveille -__________-' C'est trop tard pour les points ? nan tu es en avance pour demain! Hors ligne Ras&#039; Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Va détourer ton avatar au lieu de te moquer ! Va t'faire shampouiner en GMT-4 ! http://blag.xserver-x.org/ Les types awesome n'ont rien à prouver. À personne. En ligne Mindiell Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] donc comme pour nous on s’intéresse à une période de 6h à 9h if ( (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split(':')[6]) in range(8)) ): comme 9h est exclu je doit bien mettre 8? En fait j'aurai plutôt mis ça : if ( (str_date.split(' ')[0] in ["Aujourd\'hui"] and int(str_date.split(' ')[2].split(':')[0]) in range(5,8)) ): Car : - je ne sais pas pourquoi tu mets 6 au lieu de 0 dans le tableau : quand tu coupes 05:34 en chaines par rapport à ":", tu obtiens un tableau de deux éléments : "0" => "05", "1" => "34" - Il faut s'occuper uniquement de 5 à 8 heures Voilà PS: Ah oui, ça à l'air facile python ou pas ? Hors ligne raspouillas Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] Bonjour ... ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] bonjour ... En ligne ljere Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] @Mindiell ce n'est pas facile mais c'est intéressant encore merci pour tes conseils et explications En ligne Floyd Pepper Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4] 'jour Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys. Le plus tu t'fais chier, le plus t'es emmerdé. Hors ligne
Because I added "Add Key" yesterday, today I wanted to be symmetrical, so I added "delete keys". This turned out to be much more work. First, I ended up creating another quickly.prompt, and then I had to dive into the internals of CouchGrid, and also do some hair raising mucking with desktop couch. quickly.prompts.checklist() When the developer clicks the "delete keys" button, I wanted to present them with a list of keys they could choose from. And then have all of those get deleted. This seemed like the kind of thing that I'd want to use in other programs, so I decided to solve this problem generically by adding it to quickly.prompts. I accomplished this by deriving from quickly.prompts.Prompt, and also creating a helper function. CheckListPrompt works as you would expect for prompt. You set it up by passing in some configuration info, including a dictionary of strings as keys, which will be labels for the checkboxes, and a bool value to determine if the box is checked by default. You get back a response and val. The val is a dictionary of keys again, with bools for whether the checkboxes are active or not. So to use the CheckListBox, I just pass in a dictionary of the keys for the CouchGrid, and then see if any were selecct: val = {} for k in self.grid.keys: val[k] = False response, val = checklist(title, message, val) if response == gtk.RESPONSE_OK: #do stuff Hair Raising Munging Since "do stuff" is pretty destructive, I use a quickly.prompts.yes_no to confirm that the users wants to blow away all the data and screw up their database. Assuming they do want to delete the keys and values in the desktopcouch database, it turns out to be *not* easy to do the deletion without reading way into CouchGrid. The issue here is the couchdb reserves anything staring with a "_" for itself. But DictionaryGrid uses "__" as a convention to determine that a key should be hidden in the grid by default. So as a result of this CouchGrid munges _id and _rev and record_type before it reads to and from the database. The second troublesome part was dealing with desktopcouch. It turns out that you can't just delete a key from a record. You have a delete the whole record and then create a new record without that key. so as a result the code deletes and recreates each and every row. I really think this code belongs inside CouchGrid: def delete_keys_from_store(self, model, path, iter, keys_to_delete): for k in keys_to_delete: d = model.get_value(iter,len(self.grid.keys)) if k in d: del(d[k]) if '__desktopcouch_id' in d: keys = d.keys() for k in keys: if k.startswith("__desktopcouch"): dc_key = k.split("__desktopcouch")[1] d[dc_key] = d[k] del(d[k]) if k == "__record_type": d["record_type"] = d["__record_type"] del(d["__record_type"]) self.database.delete_record(d['_id']) del(d["_rev"]) del(d["_id"]) self.database.put_record(Record(d)) Who would ever be able to figure out to do all this? Refresh So after this the refresh function was trivial. Just tell the CouchGrid to reset, and then recreate the grid: def refresh(self, widget, data=None): self.grid._refresh_treeview() self.remove(self.filt) self.filt = GridFilter(self.grid) self.pack_start(self.filt, False, False) self.reorder_child(self.filt,1) self.filt.show() desktopcouch Editor So now with adding a removing records and keys, along with freshing, I have a functional desktopcouch editor. This tool has already proved a bit useful in getting a peak into certain database. However, I can't actually create new record types yet. Maybe tomorrow? Read more
I'm trying to follow PEP 328, with the following directory structure: pkg/ __init__.py components/ core.py __init__.py tests/ core_test.py __init__.py In core_test.py I have the following import statement from ..components.core import GameLoopEvents However, when I run, I get the following error: tests$ python core_test.py Traceback (most recent call last): File "core_test.py", line 3, in <module> from ..components.core import GameLoopEvents ValueError: Attempted relative import in non-package
ljere Re : Live Voyager 12.10 merci pour les précisions c'est vraiment cool je plains rodofr si il veut intégrer tout ça Hors ligne metalux Re : Live Voyager 12.10 Le repos aura été de courte durée, qu'est-ce qu'on peut dire des C.....quand on a un coup de barre! Quelqu'un a testé ce que j'ai exposé au post #314? De mon côté ça passe, si le wall est écrasé dû à de multiples clics rapprochés sur les applets(encore faut le vouloir!), cette ligne répare automatiquement en rétablissant le fond du bureau. Si vos test sont également concluants, je mettrai l'archive à jour jeudi, je serai de repos et vu le temps annoncé, ça sera une bonne excuse pour rester au chaud. @jpdipsy Je n'ai jamais le réflexe d'utiliser $1, $2, etc.... Didier-T l'a déjà utilisé avec Voyager_Wall pour changer les fonds d'écran et toi ici avec un glisser/déposer auquel je n'aurais jamais pensé! Merci, ça m'ouvre de nouvelles perspectives et j’essaierai à l'avenir de retenir la leçon des paramètres de positions. A part ça comme ljere je trouve ça cool, tout le mal que je puisse souhaiter à tes scripts, c'est que rodofr les retiennent! merci pour les précisions c'est vraiment cool je plains rodofr si il veut intégrer tout ça Pour le glisser/déposer d'une image sur les applets, si rodofr souhaite l'intégrer, c'est déjà testé avec le wall1 de mon côté et c'est OK. Il restera Voyager_Wall à adapter au fichier de config fondcfg et certainement d'autres choses à voir auxquelles je ne pense pas sur le moment . Par contre pour tester, il faut rectifier le deuxième script en remplaçant fond-gestion1.sh par fond-gestion.sh et voici le wall1 à adapter (faire de même pour les autres walls sur cette base en adaptant 0-fond.png ou 0 est le bureau1,etc...) #!/bin/bash # License GPL # by rodofr Live Voyager # Display the action selector sauvegardes=~/.config/fondcfg bureau=$1 if [ ! -z "$2" ];then ~/.scripts/Wall/fond-gestion.sh sauvegarde "$bureau" "$2" fi if [[ ! $(wmctrl -d | grep '*' | cut -d " " -f1) -eq 0 ]]; then echo "1" > ~/.scripts/Wall/changement_dash wmctrl -s"$1" fi xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" -s "$sauvegardes/0-fond.png" xfdesktop --reload exit 0 Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement Hors ligne ljere Re : Live Voyager 12.10 j'ai pas trop le temps de tester en ce moment mais je vous rappelle que le salon IRC est toujours ouvert pour discuter de vos idées de projet, pour l'instant on es 3 dessus dont kura et Didier-T Hors ligne Hors ligne rodofr Re : Live Voyager 12.10 @jpdipsy cool ton idée, j'ai essayé avec la modification de @metalux mais cela marche qu'à moitié...J'ai pas trop de temps de m'y pencher. Je verrais cela ce soir en rentrant. Merci en tout cas et aussi à @metalux et Didier -t et à tous aussi... Hors ligne Didier-T Re : Live Voyager 12.10 Re-Bonjour a tous, Comme je le disais plus haut j'adore l'idée de jpdipsy (le glisser/déposer) j'ai donc un peut remanié les scripts, et pour ce que j'ai testé sa fonctionne impeccable. voici le pack, à décompresser dans le home. Les lanceurs seront automatiquement remplacé. Attention, tous n'est certainement pas testé, mais je n'ai pas rencontré le moindre problème. Dernière modification par Didier-T (Le 17/01/2013, à 17:55) Hors ligne rodofr Re : Live Voyager 12.10 Didier-T@ merci je viens de tester ton pack, mais pas de wall pris en compte. Par contre le roulement d'applet se passe bien quand on glisse le wall. Je vois pas trop d'où cela peut venir ? Hors ligne metalux Re : Live Voyager 12.10 Je viens d'intégrer les notifications Moc et corrigé une erreur dans Voyager_Wall.J'en ai profité pour ajouter le correctif en cas d'appuis multiples. Patiente si tu es toujours là rodofr, j'upload dans les 5 Min. Par contre, ça fonctionne chez moi, tout est Ok. Ça y est c'est fait: wget http://luccio_script.perso.sfr.fr/Voyager.tar.gz tar zxvf Voyager.tar.gz PS: Ne pas oublier d'installer python-wnck si test en live car non présent sur Voyager 12.10 par défaut. Dernière modification par metalux (Le 17/01/2013, à 01:23) Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement Hors ligne rodofr Re : Live Voyager 12.10 metalux@ super ça marche impeccable. Vraiment, c'est le top. Merci à tous pour votre travail. Vous êtes une équipe de choc. Je vous envois le reste du pack fait pour voyager 13.04. L'applet gestionnaire de bureau avec l’icône oeil, toutes les icônes à mettre dans /.awn1/, et les flèches auhohide regroupées toutes sur le panel droit comme indiqué ci-dessous. Donc enlever la flèche du panel bas. Ainsi, vous verrez ce que cela donne pour voyager 13.04. wget http://voyager.legtux.org/scripts/Voyager-13.04.tar.gz tar zxvf Voyager-13.04.tar.gz Voici aussi le nouveau thème par défaut, normalement. J'ai changer en blanc mat les 2 icônes centre du panel bas, bureau et Applfinder, pour que le tout s'équilibre bien, dans thunar aussi avec l'orange. Il y a de la couleur mais comme d'habitude, beaucoup de thèmes seront proposés. Après tout, on est pas là pour être triste. A bientôt Hors ligne metalux Re : Live Voyager 12.10 Je ne sais pas si tu as téléchargé l'archive avant, mais j'ai apporté un dernier correctif car le wall ne s'affichait pas directement pour ranger,terminal,etc... en cas de glisser/déposer. j'adore ton nouveau thème, Voyager 13.04 sera encore plus esthétique que les versions précédentes. Et comme dit ma fille:Ça gère la fougère!!! Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement Hors ligne rodofr Re : Live Voyager 12.10 Je ne sais pas si tu as téléchargé l'archive avant, mais j'ai apporté un dernier correctif car le wall ne s'affichait pas directement pour ranger,terminal,etc... en cas de glisser/déposer. j'adore ton nouveau thème, Voyager 13.04 sera encore plus esthétique que les versions précédentes. Et comme dit ma fille:Ça gère la fougère!!! merci c'est vrai que c'est mieux. Sinon, pour l'esthétique, marre de cette époque morose, je veux vivre dans la couleur ! Et puis j'adore l'orange mais pas trop quand même. Dernière modification par rodofr (Le 17/01/2013, à 03:43) Hors ligne Didier-T Re : Live Voyager 12.10 @ metalux, Il manque une condition au if de Voyager_Wall, celle de "Pindgin" avec ceci ce serait bien #!/bin/sh # License GPL # Live Voyager rodofr@ # Script of rodofr, ljere & etc... :) # Modifié par Didier-T le 28 Nov 2012 # Modifié par Didier-T le 29 Nov 2012 suite remarque de metalux http://forum.ubuntu-fr.org/viewtopic.php?pid=11673371#p11673371 # Modified by metalux for dynamic change wallpapers # script d'action personnalisé pour l'activer copier le contenu de ce script dans un fichier Fond_voyager → Fermer # clic droit sur le fichier → Propriété → onglet Permissions cocher la case Autoriser ce fichier à être exécuter comme un programme → Fermer # ouvrir Thunar → menu éditer → configurer les actions personnalisées → ajouter une action personnalisée, # une nouvelle fenêtre va alors s'ouvrir # onglet Base 1 Nom: Fond pour Voyager 2 Description: Sélectionner une image comme fond d'écran 3 Commande: (le chemin ou vous avez placé le script) # onglet Conditions d'apparition: 1 Motif de fichier: * 2 fichiers image doit être coché tout seul current_desktop=$(wmctrl -d | grep '*' | cut -d " " -f1) fct () { if [ -d $3 ]; then fond=$(sed -n "/^xfconf.*$/ p" ~/.scripts/Wall/wall$2 | sed 's/^.*-s //;s/"//g') xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" -s "$fond" xfdesktop-settings fond=$(xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" | sed 's/\//\\\//g') fi sed -i "0,/^xfconf.*$/ s//xfconf-query -c xfce4-desktop -p \"\/backdrop\/screen0\/monitor0\/image-path\" -s \"$fond\"/" ~/.scripts/Wall/wall$2 ~/.scripts/Wall/wall$(( current_desktop + 1 )) } fct2 () { if [ -d $3 ]; then fond=$(sed -n "/xfconf-query/ p" ~/.scripts/Wall/wall$2 | sed 's/^.*-s //;s/"//g;s/\\//g' ) xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" -s "$fond" xfdesktop-settings fond=$(xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" | sed 's/\//\\\//g') fi sed -i "/wall=/ s/wall.*$/wall=\"xfconf-query -c xfce4-desktop -p \\\\\"\/backdrop\/screen0\/monitor0\/image-path\\\\\" -s \\\\\"$fond\\\\\"\"/" ~/.scripts/Wall/wall$2 ~/.scripts/Wall/wall$(( current_desktop + 1 )) } if ! [ -d $3 ]; then xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" -s "$3" fond=$(echo "$3" | sed 's/\//\\\//g') if [ $2 -le 4 ]; then fct $1 $2 $3 echo $fond > ~/.scripts/Wall/.sav$2 sed -i 's/\\//g' ~/.scripts/Wall/.sav$2 else fct2 $1 $2 $3 fi else ANS=$(zenity --title='Voyager Wall' --list --text "Select list" --radiolist --height=320 --width=300 --column "Select" --column "Menu" FALSE "Bureau 1" FALSE "Bureau 2" FALSE "Bureau 3" FALSE "Bureau 4" FALSE "Ranger" FALSE "Terminal" FALSE "Moc" FALSE "Freetux TV" FALSE "Pidgin") ret=$? if [ $ret -eq 1 ]; then exit 1 else if ! [ -d $1 ]; then xfconf-query -c xfce4-desktop -p "/backdrop/screen0/monitor0/image-path" -s "$1" fond=$(echo "$1" | sed 's/\//\\\//g') fi if [ "$ANS" = "Bureau 1" ]; then fct 0 1 $1 elif [ "$ANS" = "Bureau 2" ]; then fct 1 2 $1 elif [ "$ANS" = "Bureau 3" ]; then fct 2 3 $1 elif [ "$ANS" = "Bureau 4" ]; then fct 3 4 $1 elif [ "$ANS" = "Ranger" ]; then fct2 2 5 $1 elif [ "$ANS" = "Terminal" ]; then fct2 2 6 $1 elif [ "$ANS" = "Moc" ]; then fct2 3 7 $1 elif [ "$ANS" = "Freetux TV" ]; then fct2 3 9 $1 elif [ "$ANS" = "Pidgin" ]; then fct2 3 10 $1 fi fi fi # Fin du script : exit 0 Par contre pourquoi lance tu les scripts Wall à la fin du changement de fond ? sa te renvoi sur le bureau d'origine, tu ne peut donc pas voir le changement de fond directement, si tu n'était pas sur le bureau à modifier auparavant. Hors ligne metalux Re : Live Voyager 12.10 @Didier-T Pour pidgin, je me suis aperçu, je vais mettre à jour dans la journée. Si tu as lu PDF que j'ai fais il y a quelques jours (point 5), j'avais décidé de virer les walls pour pidgin, et j'ai oublié de le retirer de la fenêtre zenity. Par contre pourquoi lance tu les scripts Wall à la fin du changement de fond ? Je préfère ce comportement en restant sur le bureau sur lequel on se trouve. Le fond s'affiche bien avant avec xfdesktop-settings lors du choix mais pas après la fermeture de celui-ci. Les goûts et les couleurs A rodofr de retenir le comportement qu'il préfère. Pour la correction, je parlais plus de if [ $2 -le 4 ]; then fct $1 $2 $3 au lieu de if [ $2 -lt 4 ]; then fct $1 $2 $3 sinon c'était la fonction2 qui était attribué au bureau4 (lt correspond à plus petit que et le à plus petit ou égal si ma mémoire est bonne) Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement Hors ligne jpdipsy Re : Live Voyager 12.10 Toutes,tous Désolé de ne avoir pu vous répondre à tous mais free m'a pêté ma ligne pendant deux jours. Comme ça à bien bossé et que vous pouvez vous en sortir seuls (je vous remercie de vos compliments par ailleurs) de mon côté je prépare un script pour moc afin que le conky dédié affiche les pochettes au changement de chanson ou pour le streaming radio. A+ Hors ligne Didier-T Re : Live Voyager 12.10 @ metalux, comme tu le dis les goûts et les couleurs, en même temps, pour mois sa ne change rien, je modifie très rarement mes fond d'écran. Bien vue pour le -le a la place du -lt, voila ce qui ce passe quand ont veux aller trop vite. Hors ligne metalux Re : Live Voyager 12.10 J'ai mis l'archive à jour. wget http://luccio_script.perso.sfr.fr/Voyager.tar.gz tar zxvf Voyager.tar.gz et sudo cp -r ~/Voyager/.awn1 / pour installer le pack d'icônes. Il s'avère en effet pas très judicieux de lancer les scripts Wall à la fin du changement de fond,même si pour ma part je préfère ce comportement. On se retrouve alors avec 2 comportements différents selon comment on change le fond d'écran. Du coup, j'ai rétabli le changement de bureau. J'ai modifié pour les applications, elles s'ouvrent désormais avec l'usage du clic droit ou de l'applet œil du panel de façon à avoir le même comportement que le glisser/déposer. J'ai profité d'ajouter le démarrage de bureau.py ainsi que l'action personnalisé thunar. Pour les panels, je te laisse mettre à jour rodofr, je n'y arrives pas. J'avais ajouté ~/.config/xfce4/panel mais apparemment ce n'est pas suffisant. J'ai supprimé Les walls pour pidgin pour éviter les conflits avec Voyager Terminal pour l'instant, si vous avez une meilleure idée je vous laisse faire @rodofr Pour l'autohide des panels, tu n'utilises pas le dernier scripts mais peut-être est-ce volontaire. Klong avait fait une juste remarque en souhaitant rétablir le réglage habituel après l'autohide. Je l'ai ajouté, il s'agit de ~/.scripts/panel/panelall.sh au cas ou... Bon, là je crois que nous avons fait le tour pour les walls, restent les idées à jpdipsy pour remplacer le conky wall que je trouve bien sympas (sauf la photo de sa belle-mère ). A plus tard pour de nouvelles aventures Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement Hors ligne rodofr Re : Live Voyager 12.10 metalux@ Merci et oui pour l'autohide c'est la version pour la futur 13.04 pour ceux qui souhaite voir ce que cela donne. Tout regrouper au panel. Par contre, j'ai un problème depuis hier. Terminal pour le scripts wall6. Impossible de le faire partir du panel du haut pour venir se finir au milieu de l'écran. Il ne s'ouvre qu'à partir du bas. A l'époque quand je l'ai fait ça marchait sans problème et là plus rien. Pour plus de précision faire dans terminal : man xfce4-terminal Le ligne c'est celle-là dans wall6 xfce4-terminal --title='Voyager Terminal' --geometry 1920x25 --hide-menubar --hide-borders J'ai beau changer rien y fait. Vous avez ce problème ou pas. Je l'ai depuis les mises à jour. Dernière modification par rodofr (Le 18/01/2013, à 00:48) Hors ligne ljere Re : Live Voyager 12.10 j'ai testé ta commande rodofr le premier terminal s'ouvre en effet en bas puis si je relance la commande il s'ouvre en haut Hors ligne Didier-T Re : Live Voyager 12.10 @ rodofr, Pour ton problème de Terminal, tu devrais tester avec ceci xfce4-terminal --title='Voyager Terminal' --geometry 1920x25+0+0 --hide-menubar --hide-borders Hors ligne jpdipsy Re : Live Voyager 12.10 Toutes,tousse.... (hommage à la dame aux camélia) gag Bon je vous livre les deux scripts d'annotation d'image tel que montré dans les vidéos précédentes: le bouton: #!/bin/bash #Crée par JPDipsy # imagemagick doit etre installé echelle=50 placex=650 placey=10 font="Ubuntu-Bold" fonttaille="72" # pour changer de fonte dans un terminal : # convert -list font |grep "Font: "|less # vous donnera la liste de vos fontes bureau="$1" image="$2" tailleecran="$(wmctrl -d | grep "[*] DG" | cut -d " " -f5 )" cd /tmp/ #important pour éviter d'avoir une image déformée convert -quiet -quality 50 -resize $tailleecran! "$image" imagetemp.png #creation du bouton----------------------- convert -size 100x100 xc:black -fill white -draw 'circle 50,50 45,10' masque.png && convert masque.png -blur 0x3 -shade 120x45 -normalize masque.png +matte -compose CopyOpacity -composite bouton.png convert -size 100x100 xc:none -font $font -pointsize $fonttaille \ -fill Black -annotate +35+80 "$((bureau+1))" -channel RGBA -blur 0x5 \ -fill white -stroke black -draw "text 30,75 '$bureau'" \ num.png #mise a l'echelle du bouton -------------- convert bouton.png num.png -background transparent -gravity Center -resize $echelle%! -composite num.png #assemblage------------------------------- convert -quality 50 imagetemp.png /tmp/num.png -background transparent -gravity South -geometry +$placex+$placey -composite image-finale.png rm num.png masque.png bouton.png imagetemp.png enlevez la ligne suivante pour utiliser dans un script display image-finale.png vous sauvegardez ou vous voulez sous ce que voulez bouton.sh par ex: rendez executable L'appel se fait par /chemin/bouton.sh bureau image soit : par ex: /chemin/bouton.sh 2 /chemincomplet/image donc pas de ~/ pour la reference à votre rep perso libelle : #!/bin/bash #Crée par JPDipsy # imagemagick doit etre installé # echelle=50 placex=645 placey=40 font="Liberation-Mono-Bold" fonttaille="20" couleur="blue";back=white #couleur="white";back=black #couleur="yellow";back=blue #couleur="red";back=white # pour changer de fonte dans un terminal : # convert -list font |grep "Font: "|less # vous donnera la liste de vos fontes titre="$1" image="$2" tailleecran="$(wmctrl -d | grep "[*] DG" | cut -d " " -f5 )" cd /tmp/ #important pour éviter d'avoir une image déformée convert -quiet -quality 50 -resize $tailleecran! "$image" imagetemp.png echo -n "$titre" | sed 's/./&@/g; s/@$//' | tr '@' '\012' |\ convert -quality 50 -background none -fill $couleur -font $font -pointsize $fonttaille -gravity center label:@- -trim \ \( +clone -background $back -shadow 100x1 -channel A -level 0,6% +channel \) +swap +repage -gravity center -composite titre.png composite -quality 50 -compose Over -gravity South -geometry +645+40 -dissolve 40,40 titre.png imagetemp.png image-finale.png rm titre.png imagetemp.png #enlevez la ligne suivante pour utiliser dans un script display image-finale.png vous sauvegardez ou vous voulez sous ce que voulez libelle.sh par ex: rendez executable L'appel se fait par : libelle.sh libelle /chemincomplet/image ex: libelle.sh VIDÉO-2 /chemincomplet/image meme remarque que plus haut après vous en faites ce que vous voulez Hors ligne jpdipsy Re : Live Voyager 12.10 Phyton addic une question pour vous même si c'est pas le lieu j'utilise ceci pour le changement et l'ajout d'un bureau: #! /usr/bin/python # -*- coding: utf-8 -*- ## python-wnck doit être installé import os, wnck, gtk ## Fonction qui modifie les fonds d'écrans au changement de Bureau def changement_de_bureau(screen, previous): ## on récupère le bureau actif actif = screen.get_active_workspace() ## on récupère son index index = screen.get_workspace_index(actif) os.system('fond-gestion.sh affiche '+`index`) def detruit(screen, space): os.system('fond-gestion.sh efface') ## Lancement du daemon bureau = wnck.screen_get_default() bureau.connect('active-workspace-changed', changement_de_bureau) bureau.connect('workspace-destroyed',detruit) gtk.main () du classique mais si je crée une fonction avec workspace-created du style def creation(screen, space): os.system('lancement d'un script') l'appel bureau.connect('workspace-created',creation) le script est lancé x fois (autant que de bureau existant) Y'a-t-il un moyen de contrecarrer cela en ne lançant le script qu'a la toute dernière fois (ou autre soluce) Merki Hors ligne kurapika29 Re : Live Voyager 12.10 Pour ceux qui voudrait changer facilement les couleurs de leur thème, GTK theme preferences vient d'avoir une mise à jour qui commence à le rendre pas mal pour xfce surtout Ça créer juste un ~/.gtkrc-2.0 avec ce que vous lui dite Dispo en ajoutant le ppa shimmerproject sudo add-apt-repository ppa:shimmerproject/ppa sudo apt-get update sudo apt-get install gtk-theme-config Disponible sur IRC, sur le serveur irc.freenode.net salon ##ubuntu-voyager (et aussi sur plein d'autre serveur/salon) Venez si vous avec besoin d'aide ou pour causer ;) suffit d'avoir Xchat ou un autre client IRC Où sinon en cliquant sur se lien http://kiwiirc.com/client/irc.freenode. … tu-voyager Hors ligne Didier-T Re : Live Voyager 12.10 @ jpdipsy, Tient mon papy éclate toi bien #! /usr/bin/python # -*- coding: utf-8 -*- import wnck import gtk import os ##Fonction qui modifie les fonds d'écrans au changement def changement_de_bureau(screen, previous): homedir = os.path.expanduser('~') ## on récupère le bureau actif actif = screen.get_active_workspace() ## on récupère son index index = screen.get_workspace_index(actif) fichier = open(homedir+"/.scripts/Wall/changement_dash", "r") info = fichier.readline() fichier.close() if info == "0": if index == 0: os.system("~/.scripts/Wall/wall1") elif index == 1: os.system("~/.scripts/Wall/wall2") elif index == 2: os.system("~/.scripts/Wall/wall3") elif index == 3: os.system("~/.scripts/Wall/wall4") fichier = open(homedir+"/.scripts/Wall/changement_dash", "w") fichier.write("0") fichier.close() def creation(screen, space): Nouv_Nb_Bureau=screen.get_workspace_count() global Nb_Bureau if Nb_Bureau == 0: Nb_Bureau=Nouv_Nb_Bureau if Nb_Bureau != Nouv_Nb_Bureau: Nb_Bureau=Nouv_Nb_Bureau os.system(Ce que tu veux lancer) def detruit(screen, space): Nouv_Nb_Bureau=screen.get_workspace_count() global Nb_Bureau Nb_Bureau=Nouv_Nb_Bureau os.system(Ce que tu veux lancer) ##Lancement du daemon d'écoute Nb_Bureau=0 bureau = wnck.screen_get_default() bureau.connect('active-workspace-changed', changement_de_bureau) bureau.connect('workspace-created',creation) bureau.connect('workspace-destroyed',detruit) gtk.main() tu as juste a changer "Ce que tu veux lancer" par le script avec ces arguments si tu as des question je suis sur le chan irc ##ubuntu-voyager Dernière modification par Didier-T (Le 18/01/2013, à 15:26) Hors ligne metalux Re : Live Voyager 12.10 @jpdipsy Merci pour les scripts.@Didier-T Eh bien je vois que le python t'a piqué! Au fait c'est quoi un chan?@rodofr Pour le terminal, pareil pour moi,ça s'ouvre en bas mais c'est Ok avec la correction de Didier-T Xubuntu 14.04 LTS sur HP Pavilion t728.fr Precise Pangolin 64 bits sur Acer aspire 5738ZG Voyager 13.04 mise à niveau en 14.04 sur TOSHIBA Satellite C870-196. Faîtes la mise à jour de vos P.P.A. automatiquement Hors ligne
JavaScript todd_temple — 2014-01-09T11:07:17-05:00 — #1 I have a page shown here that uses a modified PrettyPhoto gallery. The modification is for it to show a thumbnail view of the other images within the same gallery along the bottom of the overlay image. Works well for me, but the client is unhappy about the small size of the thumbnail images. I am looking for some input on how I would be able to increase the size of these thumbnail images. I have tinkered around with the image source width (around line 243): toInject += "<li class='" + classname + "'><a href='#'><img src='" + img_src + "' width='80' alt='' /></a></li>" but a new issue arose regarding the last thumbnail image being cropped inside the div .pp_gallery. The script seems to dynamically choose how many thumbnails will fit inside the allotted space. How can I increase the thumbnail sizes and ensure that the thumbs won't be cropped off? FYI, here is the complete version of the script: /* ------------------------------------------------------------------------ Class: prettyPhoto Use: Lightbox clone for jQuery Author: Stephane Caron (http://www.no-margin-for-errors.com) Version: 3.1.5 ------------------------------------------------------------------------- */ (function (e) { function t() { var e = location.href; hashtag = e.indexOf("#prettyPhoto") !== -1 ? decodeURI(e.substring(e.indexOf("#prettyPhoto") + 1, e.length)) : false; return hashtag } function n() { if (typeof theRel == "undefined") return; location.hash = theRel + "/" + rel_index + "/" } function r() { if (location.href.indexOf("#prettyPhoto") !== -1) location.hash = "prettyPhoto" } function i(e, t) { e = e.replace(/[\\[]/, "\\\\[").replace(/[\\]]/, "\\\\]"); var n = "[\\\\?&]" + e + "=([^&#]*)"; var r = new RegExp(n); var i = r.exec(t); return i == null ? "" : i[1] } e.prettyPhoto = { version: "3.1.5" }; e.fn.prettyPhoto = function (s) { function g() { e(".pp_loaderIcon").hide(); projectedTop = scroll_pos["scrollTop"] + (d / 2 - a["containerHeight"] / 2); if (projectedTop < 0) projectedTop = 0; $ppt.fadeTo(settings.animation_speed, 1); $pp_pic_holder.find(".pp_content").animate({ height: a["contentHeight"], width: a["contentWidth"] }, settings.animation_speed); $pp_pic_holder.animate({ top: projectedTop, left: v / 2 - a["containerWidth"] / 2 < 0 ? 0 : v / 2 - a["containerWidth"] / 2, width: a["containerWidth"] }, settings.animation_speed, function () { $pp_pic_holder.find(".pp_hoverContainer,#fullResImage").height(a["height"]).width(a["width"]); $pp_pic_holder.find(".pp_fade").fadeIn(settings.animation_speed); if (isSet && S(pp_images[set_position]) == "image") { $pp_pic_holder.find(".pp_hoverContainer").show() } else { $pp_pic_holder.find(".pp_hoverContainer").hide() } if (settings.allow_expand) { if (a["resized"]) { e("a.pp_expand,a.pp_contract").show() } else { e("a.pp_expand").hide() } } if (settings.autoplay_slideshow && !m && !f) e.prettyPhoto.startSlideshow(); settings.changepicturecallback(); f = true }); C(); s.ajaxcallback() } function y(t) { $pp_pic_holder.find("#pp_full_res object,#pp_full_res embed").css("visibility", "hidden"); $pp_pic_holder.find(".pp_fade").fadeOut(settings.animation_speed, function () { e(".pp_loaderIcon").show(); t() }) } function b(t) { t > 1 ? e(".pp_nav").show() : e(".pp_nav").hide() } function w(e, t) { resized = false; E(e, t); imageWidth = e, imageHeight = t; if ((p > v || h > d) && doresize && settings.allow_resize && !u) { resized = true, fitting = false; while (!fitting) { if (p > v) { imageWidth = v - 200; imageHeight = t / e * imageWidth } else if (h > d) { imageHeight = d - 200; imageWidth = e / t * imageHeight } else { fitting = true } h = imageHeight, p = imageWidth } if (p > v || h > d) { w(p, h) } E(imageWidth, imageHeight) } return { width: Math.floor(imageWidth), height: Math.floor(imageHeight), containerHeight: Math.floor(h), containerWidth: Math.floor(p) + settings.horizontal_padding * 2, contentHeight: Math.floor(l), contentWidth: Math.floor(c), resized: resized } } function E(t, n) { t = parseFloat(t); n = parseFloat(n); $pp_details = $pp_pic_holder.find(".pp_details"); $pp_details.width(t); detailsHeight = parseFloat($pp_details.css("marginTop")) + parseFloat($pp_details.css("marginBottom")); $pp_details = $pp_details.clone().addClass(settings.theme).width(t).appendTo(e("body")).css({ position: "absolute", top: -1e4 }); detailsHeight += $pp_details.height(); detailsHeight = detailsHeight <= 34 ? 36 : detailsHeight; $pp_details.remove(); $pp_title = $pp_pic_holder.find(".ppt"); $pp_title.width(t); titleHeight = parseFloat($pp_title.css("marginTop")) + parseFloat($pp_title.css("marginBottom")); $pp_title = $pp_title.clone().appendTo(e("body")).css({ position: "absolute", top: -1e4 }); titleHeight += $pp_title.height(); $pp_title.remove(); l = n + detailsHeight; c = t; h = l + titleHeight + $pp_pic_holder.find(".pp_top").height() + $pp_pic_holder.find(".pp_bottom").height(); p = t } function S(e) { if (e.match(/youtube\\.com\\/watch/i) || e.match(/youtu\\.be/i)) { return "youtube" } else if (e.match(/vimeo\\.com/i)) { return "vimeo" } else if (e.match(/\\b.mov\\b/i)) { return "quicktime" } else if (e.match(/\\b.swf\\b/i)) { return "flash" } else if (e.match(/\\biframe=true\\b/i)) { return "iframe" } else if (e.match(/\\bajax=true\\b/i)) { return "ajax" } else if (e.match(/\\bcustom=true\\b/i)) { return "custom" } else if (e.substr(0, 1) == "#") { return "inline" } else { return "image" } } function x() { if (doresize && typeof $pp_pic_holder != "undefined") { scroll_pos = T(); contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width(); projectedTop = d / 2 + scroll_pos["scrollTop"] - contentHeight / 2; if (projectedTop < 0) projectedTop = 0; if (contentHeight > d) return; $pp_pic_holder.css({ top: projectedTop, left: v / 2 + scroll_pos["scrollLeft"] - contentwidth / 2 }) } } function T() { if (self.pageYOffset) { return { scrollTop: self.pageYOffset, scrollLeft: self.pageXOffset } } else if (document.documentElement && document.documentElement.scrollTop) { return { scrollTop: document.documentElement.scrollTop, scrollLeft: document.documentElement.scrollLeft } } else if (document.body) { return { scrollTop: document.body.scrollTop, scrollLeft: document.body.scrollLeft } } } function N() { d = e(window).height(), v = e(window).width(); if (typeof $pp_overlay != "undefined") $pp_overlay.height(e(document).height()).width(v) } function C() { if (isSet && settings.overlay_gallery && S(pp_images[set_position]) == "image") { itemWidth = 52 + 5; navWidth = settings.theme == "facebook" || settings.theme == "pp_default" ? 50 : 30; itemsPerPage = Math.floor((a["containerWidth"] - 100 - navWidth) / itemWidth); itemsPerPage = itemsPerPage < pp_images.length ? itemsPerPage : pp_images.length; totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1; if (totalPage == 0) { navWidth = 0; $pp_gallery.find(".pp_arrow_next,.pp_arrow_previous").hide() } else { $pp_gallery.find(".pp_arrow_next,.pp_arrow_previous").show() } galleryWidth = itemsPerPage * itemWidth; fullGalleryWidth = pp_images.length * itemWidth; $pp_gallery.css("margin-left", -(galleryWidth / 2 + navWidth / 2)).find("div:first").width(galleryWidth + 5).find("ul").width(fullGalleryWidth).find("li.selected").removeClass("selected"); goToPage = Math.floor(set_position / itemsPerPage) < totalPage ? Math.floor(set_position / itemsPerPage) : totalPage; e.prettyPhoto.changeGalleryPage(goToPage); $pp_gallery_li.filter(":eq(" + set_position + ")").addClass("selected") } else { $pp_pic_holder.find(".pp_content").unbind("mouseenter mouseleave") } } function k(t) { if (settings.social_tools) facebook_like_link = settings.social_tools.replace("{location_href}", encodeURIComponent(location.href)); settings.markup = settings.markup.replace("{pp_social}", ""); e("body").append(settings.markup); $pp_pic_holder = e(".pp_pic_holder"), $ppt = e(".ppt"), $pp_overlay = e("div.pp_overlay"); if (isSet && settings.overlay_gallery) { currentGalleryPage = 0; toInject = ""; for (var n = 0; n < pp_images.length; n++) { if (!pp_images[n].match(/\\b(jpg|jpeg|png|gif)\\b/gi)) { classname = "default"; img_src = "" } else { classname = ""; img_src = pp_images[n] } toInject += "<li class='" + classname + "'><a href='#'><img src='" + img_src + "' width='50' alt='' /></a></li>" } toInject = settings.gallery_markup.replace(/{gallery}/g, toInject); $pp_pic_holder.find("#pp_full_res").after(toInject); $pp_gallery = e(".pp_pic_holder .pp_gallery"), $pp_gallery_li = $pp_gallery.find("li"); $pp_gallery.find(".pp_arrow_next").click(function () { e.prettyPhoto.changeGalleryPage("next"); e.prettyPhoto.stopSlideshow(); return false }); $pp_gallery.find(".pp_arrow_previous").click(function () { e.prettyPhoto.changeGalleryPage("previous"); e.prettyPhoto.stopSlideshow(); return false }); $pp_pic_holder.find(".pp_content").hover(function () { /* ruata $pp_pic_holder.find(".pp_gallery:not(.disabled)").fadeIn()*/ }, function () { /* ruata $pp_pic_holder.find(".pp_gallery:not(.disabled)").fadeOut()*/ }); itemWidth = 52 + 5; $pp_gallery_li.each(function (t) { e(this).find("a").click(function () { e.prettyPhoto.changePage(t); e.prettyPhoto.stopSlideshow(); return false }) }) } if (settings.slideshow) { $pp_pic_holder.find(".pp_nav").prepend('<a href="#" class="pp_play">Play</a>'); $pp_pic_holder.find(".pp_nav .pp_play").click(function () { e.prettyPhoto.startSlideshow(); return false }) } $pp_pic_holder.attr("class", "pp_pic_holder " + settings.theme); $pp_overlay.css({ opacity: 1, height: e(document).height(), width: e(window).width() }).bind("click", function () { if (!settings.modal) e.prettyPhoto.close() }); e("a.pp_close").bind("click", function () { e.prettyPhoto.close(); return false }); if (settings.allow_expand) { e("a.pp_expand").bind("click", function (t) { if (e(this).hasClass("pp_expand")) { e(this).removeClass("pp_expand").addClass("pp_contract"); doresize = false } else { e(this).removeClass("pp_contract").addClass("pp_expand"); doresize = true } y(function () { e.prettyPhoto.open() }); return false }) } $pp_pic_holder.find(".pp_previous, .pp_nav .pp_arrow_previous").bind("click", function () { e.prettyPhoto.changePage("previous"); e.prettyPhoto.stopSlideshow(); return false }); $pp_pic_holder.find(".pp_next, .pp_nav .pp_arrow_next").bind("click", function () { e.prettyPhoto.changePage("next"); e.prettyPhoto.stopSlideshow(); return false }); x() } s = jQuery.extend({ hook: "rel", animation_speed: "fast", ajaxcallback: function () {}, slideshow: 5e3, autoplay_slideshow: false, opacity: 1, show_title: true, allow_resize: true, allow_expand: true, default_width: 500, default_height: 344, counter_separator_label: "/", theme: "pp_default", horizontal_padding: 20, hideflash: false, wmode: "opaque", autoplay: true, modal: false, deeplinking: true, overlay_gallery: true, overlay_gallery_max: 35, keyboard_shortcuts: true, changepicturecallback: function () {}, callback: function () {}, ie6_fallback: true, markup: '<div class="pp_pic_holder"> <div class="ppt">*</div> <div class="pp_top"> <div class="pp_left"></div> <div class="pp_middle"></div> <div class="pp_right"></div> </div> <div class="pp_content_container"> <div class="pp_left"> <div class="pp_right"> <div class="pp_content"> <div class="pp_loaderIcon"></div> <div class="pp_fade"> <a href="#" class="pp_expand" title="Expand the image">Expand</a> <div class="pp_hoverContainer"> <a class="pp_next" href="#">next</a> <a class="pp_previous" href="#">previous</a> </div> <div id="pp_full_res"></div> <div class="pp_details"> <div class="pp_nav"> <a href="#" class="pp_arrow_previous">Previous</a> <p class="currentTextHolder">0/0</p> <a href="#" class="pp_arrow_next">Next</a> </div> <p class="pp_description"></p> <div class="pp_social">{pp_social}</div> <a class="pp_close" href="#">Close</a> </div> </div> </div> </div> </div> </div> <div class="pp_bottom"> <div class="pp_left"></div> <div class="pp_middle"></div> <div class="pp_right"></div> </div> </div> <div class="pp_overlay"></div>', gallery_markup: '<div class="pp_gallery"> <a href="#" class="pp_arrow_previous">Previous</a> <div> <ul> {gallery} </ul> </div> <a href="#" class="pp_arrow_next">Next</a> </div>', image_markup: '<img id="fullResImage" src="{path}" />', flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>', quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>', iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>', inline_markup: '<div class="pp_inline">{content}</div>', custom_markup: "", social_tools: '<!--<div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>--><!--<div class="facebook"><iframe src="//www.facebook.com/plugins/like.php?locale=en_US&href={location_href}&layout=button_count&show_faces=true&width=500&action=like&font&colorscheme=light&height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div>-->' }, s); var o = this, u = false, a, f, l, c, h, p, d = e(window).height(), v = e(window).width(), m; doresize = true, scroll_pos = T(); e(window).unbind("resize.prettyphoto").bind("resize.prettyphoto", function () { x(); N() }); if (s.keyboard_shortcuts) { e(document).unbind("keydown.prettyphoto").bind("keydown.prettyphoto", function (t) { if (typeof $pp_pic_holder != "undefined") { if ($pp_pic_holder.is(":visible")) { switch (t.keyCode) { case 37: e.prettyPhoto.changePage("previous"); t.preventDefault(); break; case 39: e.prettyPhoto.changePage("next"); t.preventDefault(); break; case 27: if (!settings.modal) e.prettyPhoto.close(); t.preventDefault(); break } } } }) } e.prettyPhoto.initialize = function () { settings = s; if (settings.theme == "pp_default") settings.horizontal_padding = 16; theRel = e(this).attr(settings.hook); galleryRegExp = /\\[(?:.*)\\]/; isSet = galleryRegExp.exec(theRel) ? true : false; pp_images = isSet ? jQuery.map(o, function (t, n) { if (e(t).attr(settings.hook).indexOf(theRel) != -1) return e(t).attr("href") }) : e.makeArray(e(this).attr("href")); pp_titles = isSet ? jQuery.map(o, function (t, n) { if (e(t).attr(settings.hook).indexOf(theRel) != -1) return e(t).find("img").attr("alt") ? e(t).find("img").attr("alt") : "" }) : e.makeArray(e(this).find("img").attr("alt")); pp_descriptions = isSet ? jQuery.map(o, function (t, n) { if (e(t).attr(settings.hook).indexOf(theRel) != -1) return e(t).attr("title") ? e(t).attr("title") : "" }) : e.makeArray(e(this).attr("title")); if (pp_images.length > settings.overlay_gallery_max) settings.overlay_gallery = false; set_position = jQuery.inArray(e(this).attr("href"), pp_images); rel_index = isSet ? set_position : e("a[" + settings.hook + "^='" + theRel + "']").index(e(this)); k(this); if (settings.allow_resize) e(window).bind("scroll.prettyphoto", function () { x() }); e.prettyPhoto.open(); return false }; e.prettyPhoto.open = function (t) { if (typeof settings == "undefined") { settings = s; pp_images = e.makeArray(arguments[0]); pp_titles = arguments[1] ? e.makeArray(arguments[1]) : e.makeArray(""); pp_descriptions = arguments[2] ? e.makeArray(arguments[2]) : e.makeArray(""); isSet = pp_images.length > 1 ? true : false; set_position = arguments[3] ? arguments[3] : 0; k(t.target) } if (settings.hideflash) e("object,embed,iframe[src*=youtube],iframe[src*=vimeo]").css("visibility", "hidden"); b(e(pp_images).size()); e(".pp_loaderIcon").show(); if (settings.deeplinking) n(); if (settings.social_tools) { facebook_like_link = settings.social_tools.replace("{location_href}", encodeURIComponent(location.href)); $pp_pic_holder.find(".pp_social").html(facebook_like_link) } if ($ppt.is(":hidden")) $ppt.css("opacity", 1).show(); $pp_overlay.show().fadeTo(settings.animation_speed, settings.opacity); $pp_pic_holder.find(".currentTextHolder").text(set_position + 1 + settings.counter_separator_label + e(pp_images).size()); if (typeof pp_descriptions[set_position] != "undefined" && pp_descriptions[set_position] != "") { $pp_pic_holder.find(".pp_description").show().html(unescape(pp_descriptions[set_position])) } else { $pp_pic_holder.find(".pp_description").hide() } movie_width = parseFloat(i("width", pp_images[set_position])) ? i("width", pp_images[set_position]) : settings.default_width.toString(); movie_height = parseFloat(i("height", pp_images[set_position])) ? i("height", pp_images[set_position]) : settings.default_height.toString(); u = false; if (movie_height.indexOf("%") != -1) { movie_height = parseFloat(e(window).height() * parseFloat(movie_height) / 100 - 150); u = true } if (movie_width.indexOf("%") != -1) { movie_width = parseFloat(e(window).width() * parseFloat(movie_width) / 100 - 150); u = true } $pp_pic_holder.fadeIn(function () { settings.show_title && pp_titles[set_position] != "" && typeof pp_titles[set_position] != "undefined" ? $ppt.html(unescape(pp_titles[set_position])) : $ppt.html("*"); imgPreloader = ""; skipInjection = false; switch (S(pp_images[set_position])) { case "image": imgPreloader = new Image; nextImage = new Image; if (isSet && set_position < e(pp_images).size() - 1) nextImage.src = pp_images[set_position + 1]; prevImage = new Image; if (isSet && pp_images[set_position - 1]) prevImage.src = pp_images[set_position - 1]; $pp_pic_holder.find("#pp_full_res")[0].innerHTML = settings.image_markup.replace(/{path}/g, pp_images[set_position]); imgPreloader.onload = function () { a = w(imgPreloader.width, imgPreloader.height); g() }; imgPreloader.onerror = function () { alert("Image cannot be loaded. Make sure the path is correct and image exist."); e.prettyPhoto.close() }; imgPreloader.src = pp_images[set_position]; break; case "youtube": a = w(movie_width, movie_height); movie_id = i("v", pp_images[set_position]); if (movie_id == "") { movie_id = pp_images[set_position].split("youtu.be/"); movie_id = movie_id[1]; if (movie_id.indexOf("?") > 0) movie_id = movie_id.substr(0, movie_id.indexOf("?")); if (movie_id.indexOf("&") > 0) movie_id = movie_id.substr(0, movie_id.indexOf("&")) } movie = "http://www.youtube.com/embed/" + movie_id; i("rel", pp_images[set_position]) ? movie += "?rel=" + i("rel", pp_images[set_position]) : movie += "?rel=1"; if (settings.autoplay) movie += "&autoplay=1"; toInject = settings.iframe_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, movie); break; case "vimeo": a = w(movie_width, movie_height); movie_id = pp_images[set_position]; var t = /http(s?):\\/\\/(www\\.)?vimeo.com\\/(\\d+)/; var n = movie_id.match(t); movie = "http://player.vimeo.com/video/" + n[3] + "?title=0&byline=0&portrait=0"; if (settings.autoplay) movie += "&autoplay=1;"; vimeo_width = a["width"] + "/embed/?moog_width=" + a["width"]; toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, a["height"]).replace(/{path}/g, movie); break; case "quicktime": a = w(movie_width, movie_height); a["height"] += 15; a["contentHeight"] += 15; a["containerHeight"] += 15; toInject = settings.quicktime_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, pp_images[set_position]).replace(/{autoplay}/g, settings.autoplay); break; case "flash": a = w(movie_width, movie_height); flash_vars = pp_images[set_position]; flash_vars = flash_vars.substring(pp_images[set_position].indexOf("flashvars") + 10, pp_images[set_position].length); filename = pp_images[set_position]; filename = filename.substring(0, filename.indexOf("?")); toInject = settings.flash_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, filename + "?" + flash_vars); break; case "iframe": a = w(movie_width, movie_height); frame_url = pp_images[set_position]; frame_url = frame_url.substr(0, frame_url.indexOf("iframe") - 1); toInject = settings.iframe_markup.replace(/{width}/g, a["width"]).replace(/{height}/g, a["height"]).replace(/{path}/g, frame_url); break; case "ajax": doresize = false; a = w(movie_width, movie_height); doresize = true; skipInjection = true; e.get(pp_images[set_position], function (e) { toInject = settings.inline_markup.replace(/{content}/g, e); $pp_pic_holder.find("#pp_full_res")[0].innerHTML = toInject; g() }); break; case "custom": a = w(movie_width, movie_height); toInject = settings.custom_markup; break; case "inline": myClone = e(pp_images[set_position]).clone().append('<br clear="all" />').css({ width: settings.default_width }).wrapInner('<div id="pp_full_res"><div class="pp_inline"></div></div>').appendTo(e("body")).show(); doresize = false; a = w(e(myClone).width(), e(myClone).height()); doresize = true; e(myClone).remove(); toInject = settings.inline_markup.replace(/{content}/g, e(pp_images[set_position]).html()); break } if (!imgPreloader && !skipInjection) { $pp_pic_holder.find("#pp_full_res")[0].innerHTML = toInject; g() } }); return false }; e.prettyPhoto.changePage = function (t) { currentGalleryPage = 0; if (t == "previous") { set_position--; if (set_position < 0) set_position = e(pp_images).size() - 1 } else if (t == "next") { set_position++; if (set_position > e(pp_images).size() - 1) set_position = 0 } else { set_position = t } rel_index = set_position; if (!doresize) doresize = true; if (settings.allow_expand) { e(".pp_contract").removeClass("pp_contract").addClass("pp_expand") } y(function () { e.prettyPhoto.open() }) }; e.prettyPhoto.changeGalleryPage = function (e) { if (e == "next") { currentGalleryPage++; if (currentGalleryPage > totalPage) currentGalleryPage = 0 } else if (e == "previous") { currentGalleryPage--; if (currentGalleryPage < 0) currentGalleryPage = totalPage } else { currentGalleryPage = e } slide_speed = e == "next" || e == "previous" ? settings.animation_speed : 0; slide_to = currentGalleryPage * itemsPerPage * itemWidth; $pp_gallery.find("ul").animate({ left: -slide_to }, slide_speed) }; e.prettyPhoto.startSlideshow = function () { if (typeof m == "undefined") { $pp_pic_holder.find(".pp_play").unbind("click").removeClass("pp_play").addClass("pp_pause").click(function () { e.prettyPhoto.stopSlideshow(); return false }); m = setInterval(e.prettyPhoto.startSlideshow, settings.slideshow) } else { e.prettyPhoto.changePage("next") } }; e.prettyPhoto.stopSlideshow = function () { $pp_pic_holder.find(".pp_pause").unbind("click").removeClass("pp_pause").addClass("pp_play").click(function () { e.prettyPhoto.startSlideshow(); return false }); clearInterval(m); m = undefined }; e.prettyPhoto.close = function () { if ($pp_overlay.is(":animated")) return; e.prettyPhoto.stopSlideshow(); $pp_pic_holder.stop().find("object,embed").css("visibility", "hidden"); e("div.pp_pic_holder,div.ppt,.pp_fade").fadeOut(settings.animation_speed, function () { e(this).remove() }); $pp_overlay.fadeOut(settings.animation_speed, function () { if (settings.hideflash) e("object,embed,iframe[src*=youtube],iframe[src*=vimeo]").css("visibility", "visible"); e(this).remove(); e(window).unbind("scroll.prettyphoto"); r(); settings.callback(); doresize = true; f = false; delete settings }) }; if (!pp_alreadyInitialized && t()) { pp_alreadyInitialized = true; hashIndex = t(); hashRel = hashIndex; hashIndex = hashIndex.substring(hashIndex.indexOf("/") + 1, hashIndex.length - 1); hashRel = hashRel.substring(0, hashRel.indexOf("/")); setTimeout(function () { e("a[" + s.hook + "^='" + hashRel + "']:eq(" + hashIndex + ")").trigger("click") }, 50) } return this.unbind("click.prettyphoto").bind("click.prettyphoto", e.prettyPhoto.initialize) }; })(jQuery); var pp_alreadyInitialized = false system — 2014-01-09T11:58:53-05:00 — #2 Look at the insertgallery function, itemWidth, navWidth, itemsPerPage, in the original script. That would be function C() in your script. function _insert_gallery(){ if(isSet && settings.overlay_gallery && _getFileType(pp_images[set_position])=="image") { itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin. navWidth = (settings.theme == "facebook" || settings.theme == "pp_default") ? 50 : 30; // Define the arrow width depending on the theme itemsPerPage = Math.floor((pp_dimensions['containerWidth'] - 100 - navWidth) / itemWidth); itemsPerPage = (itemsPerPage < pp_images.length) ? itemsPerPage : pp_images.length; totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1; // Hide the nav in the case there's no need for links if(totalPage == 0){ navWidth = 0; // No nav means no width! $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').hide(); }else{ $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').show(); }; galleryWidth = itemsPerPage * itemWidth; fullGalleryWidth = pp_images.length * itemWidth; // Set the proper width to the gallery items $pp_gallery .css('margin-left',-((galleryWidth/2) + (navWidth/2))) .find('div:first').width(galleryWidth+5) .find('ul').width(fullGalleryWidth) .find('li.selected').removeClass('selected'); goToPage = (Math.floor(set_position/itemsPerPage) < totalPage) ? Math.floor(set_position/itemsPerPage) : totalPage; $.prettyPhoto.changeGalleryPage(goToPage); $pp_gallery_li.filter(':eq('+set_position+')').addClass('selected'); }else{ $pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave'); // $pp_gallery.hide(); } } todd_temple — 2014-01-09T13:26:21-05:00 — #3 I modified those settings and had to modify the CSS as well to get the thumbnails larger. But now the thumbnails are still being cropped. Take a look at the link below and let me know if there is a solution to ensure that the entire thumbnail would be visible. http://tds-exhibits.com/portfolio/index.010814.php system — 2014-01-09T14:11:32-05:00 — #4 In function k(t) you still got the old values. itemWidth = 52 + 5;
Past midnight and maybe someone has an idea how to tackle a problem of mine. I want to count the number of adjacent cells (which means the number of array fields with other values eg. zeroes in the vicinity of array values) as sum for each valid value!. Example: import numpy, scipy s = ndimage.generate_binary_structure(2,2) # Structure can vary a = numpy.zeros((6,6), dtype=numpy.int) # Example array a[2:4, 2:4] = 1;a[2,4] = 1 # with example value structure print a >[[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 1 1 1 0] [0 0 1 1 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0]] # The value at position [2,4] is surrounded by 6 zeros, while the one at # position [2,2] has 5 zeros in the vicinity if 's' is the assumed binary structure. # Total sum of surrounding zeroes is therefore sum(5+4+6+4+5) == 24 How can i count the number of zeroes in such way if the structure of my values vary? I somehow believe to must take use of the binary_dilation function of SciPy, which is able to enlarge the value structure, but simple counting of overlaps can't lead me to the correct sum or does it? print ndimage.binary_dilation(a,s).astype(a.dtype) [[0 0 0 0 0 0] [0 1 1 1 1 1] [0 1 1 1 1 1] [0 1 1 1 1 1] [0 1 1 1 1 0] [0 0 0 0 0 0]]
This is what I came up with to calculate all subsets of length 0, 1, ... , n of a set of length n with doubling single elements. Difficult to describe... def subsets(seq, *args): seqstart = [[seq[i] for i in args], ] if len(args) == 0: for i in range(len(seq)): seqstart += subsets(seq, i) elif len(args) < len(seq): for i in range(args[-1], len(seq)): seqstart += subsets(seq, *args + (i, )) return seqstart Examples: >>> subsets(['x', 'y']) [[], ['x'], ['x', 'x'], ['x', 'y'], ['y'], ['y', 'y']] >>> subsets(['x', 'y', 'z']) [[], ['x'], ['x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'y'], ['x', 'x', 'z'], ['x', 'y'], ['x', 'y', 'y'], ['x', 'y', 'z'], ['x', 'z'], ['x', 'z', 'z'], ['y'], ['y', 'y'], ['y', 'y', 'y'], ['y', 'y', 'z'], ['y', 'z'], ['y', 'z', 'z'], ['z'], ['z', 'z'], ['z', 'z', 'z']] What is the length of subsets(sequence) dependent on the length of the sequence? (I killed the process after 50 hours with n=14) Thank You Michael edit: Thank you all. So it is the Binomial Coefficient of 2n over n. To obtain all subsets instead of multisets (so a total length of 2^n) I needed to replace for i in range(args[-1], len(seq)): with for i in range(args[-1] + 1, len(seq)):
I am trying to run rpart through RPY2 using Python 2.6.5 and R 10.0. I create a data frame in python and pass it along but I get an error stating: Error in function (x) : binary operation on non-conformable arrays Traceback (most recent call last): File "partitioningSANDBOX.py", line 86, in <module> model=r.rpart(**rpart_params) File "build/bdist.macosx-10.3-fat/egg/rpy2/robjects/functions.py", line 83, in __call__ File "build/bdist.macosx-10.3-fat/egg/rpy2/robjects/functions.py", line 35, in __call__ rpy2.rinterface.RRuntimeError: Error in function (x) : binary operation on non-conformable arrays Can anyone help me determine what I am doing wrong to throw this error? the relevant part of my code is this: import numpy as np import rpy2 import rpy2.robjects as rob import rpy2.robjects.numpy2ri #Fire up the interface to R r = rob.r r.library("rpart") datadict = dict(zip(['responsev','predictorv'],[cLogEC,csplitData])) Rdata = r['data.frame'](**datadict) Rformula = r['as.formula']('responsev ~.') #Generate an RPART model in R. Rpcontrol = r['rpart.control'](minsplit=10, xval=10) rpart_params = {'formula' : Rformula, \ 'data' : Rdata, 'control' : Rpcontrol} model=r.rpart(**rpart_params) The two variables cLogEC and csplitData are numpy arrays of float type. Also, my data frame looks like this: In [2]: print Rdata ------> print(Rdata) responsev predictorv 1 0.6020600 312 2 0.3010300 300 3 0.4771213 303 4 0.4771213 249 5 0.9242793 239 6 1.1986571 297 7 0.7075702 287 8 1.8115750 270 9 0.6020600 296 10 1.3856063 248 11 0.6127839 295 12 0.3010300 283 13 1.1931246 345 14 0.3010300 270 15 0.3010300 251 16 0.3010300 246 17 0.3010300 273 18 0.7075702 252 19 0.4771213 252 20 0.9294189 223 21 0.6127839 252 22 0.7075702 267 23 0.9294189 252 24 0.3010300 378 25 0.3010300 282 and the formula looks like this: In [3]: print Rformula ------> print(Rformula) responsev ~ .