Cette page donne des réponses à diverses questions informatique (Etienne Pallier)
Voir aussi ComputerScience (informations sur générales sur des notions informatique)
Voir aussi InformationAboutThisTwiki (informations sur ce wiki)
Ce chapitre n'est qu'un résumé de ce qui est vraiment important. Il est encore incomplet et sera enrichi progressivement.
Pour tout ce qui n'est pas (encore) dit, respecter les conventions de la PEP08 : https://www.python.org/dev/peps/pep-0008/
Principe global : KISS (https://fr.wikipedia.org/wiki/Principe_KISS)
(Vous-mêmes ou à plus forte raison quelqu'un d'autre, doit pouvoir relire votre code plusieurs années après et le comprendre rapidement)
Ces règles générales sont valables quelque soit le langage utilisé (Python, Php, Java, ...)
(cf https://hackernoon.com/oo-tricks-the-art-of-command-query-separation-9343e50a3de0)
En d'autres termes : "Functions that change state should not return values and functions that return values should not change state"
ex: int m(); // query void n(); // command
(cf https://hackernoon.com/object-oriented-tricks-2-law-of-demeter-4ecc9becad85)
LoD tells us that it is a bad idea for single functions to know the entire navigation structure of the system.
“Each unit should have only limited knowledge about other units: only units “closely” related to the current unit. Each unit should only talk to its friends; don’t talk to strangers.”
(cf https://hackernoon.com/oo-tricks-the-art-of-command-query-separation-9343e50a3de0)
Utiliser le tag "TODO:" en début de ligne pour marquer une action à faire (Attention: bien mettre les 2 points à la fin)
Simple caractère => simple quote (apostrophe) :
c = 'c'
Chaine de caractères => double quote (guillemets) :
s = "ma jolie chaine"
LIMIT_MAX
LIMIT_MIN
Dans la mesure du possible, ne pas dépasser les 80 caractères
Une méthode ou fonction doit être la plus concise possible, et en tous cas elle doit tenir en entier sur l'écran pour qu'on comprenne rapidement ce qu'elle fait. De manière générale, rester en dessous des 30 lignes.
Pour chaque méthode ou fonction, mettre un commentaire AVANT (triple quote) :
''' Commentaire sur une seule ligne ''' ou bien ''' \t Commentaire sur plusieurs lignes \t Deuxième ligne \t Troisième ligne ''' def myMethod(): ...
Commentaire TODO ou bien "mise en commentaire" d'une ligne de code => #
# TODO: bla bla bla #s = readline()
S'assurer de la bonne lisibilité du code en employant des noms de méthodes en "anglais courant".
Exemples:
isWriteable() isReadable() hasComponents() makesNoise() # => ne pas confondre avec "makeNoise()" qui sera plutôt une méthode fabriquant du bruit (et non pas retournant un booléen) doesNoise() # => idem, ne pas confondre avec "doNoise()"
Pour privatiser un attribut ou une méthode, les préfixer par un underscore (souligné).
Exemple :
_my_private_attribute _myPrivateMethod()
(TODO:)
Utiliser les "type hints" pour donner le type de tous les paramètres d'une méthode, ainsi que le type de retour
Ex:
def reverse_slice(text: str, start: int, end: int) -> str: return text[start:end][::-1]
Dans la mesure du possible, 1 classe = 1 fichier du même nom
Ex: vehicule.py ne devrait contenir QUE la classe Vehicule
Utiliser du Camel Case pour les Classes (majuscule au début) et et les méthodes et instances de classes (minuscule au début) : MyClass, myClassInstance, myMethod()
Utiliser du Snake Case pour les attributs : my_own_attribute
ex: 3 tests unitaires de la méthode "addItem()" d'une classe: * test_firstCase_addItem() * test_secondCase_addItem() * test_thirdCase_addItem()
ex: * test_func_alertCompleteProcessing()
ex: * test_perf_scheduler()
ex: * test_stress_scheduler()
1) Imprimer sur Sprinter (bureau Chemcam 58) :
http://planetowiki.irap.omp.eu/do/view/Computers/SprinterPrinter
2) Imprimer sur les imprimantes générales du labo :
Article général sur l'intranet : https://intranet.irap.omp.eu/spip.php?article205
Je donne ici quelques raccourcis et petites mises à jour par rapport à cette doc, pour installer notamment l'imprimante improche3 :
a) Installation sur Mac OS
Mon expérience sur OS 10.10 (Yosemite) :
Préférences Système / Imprimantes
Cliquer sur bouton "+"
Adresse : impression.irap.omp.eu
Protocole : IPP
File d'attente : /printers/improche3
Cliquer sur "Ajouter"
Cocher "unité d'impression duplex" pour le recto-verso
b) Installation sur Linux
Mon expérience sur Fedora 20 :
Par défaut, ça ne marche pas car le protocole IPP n'est pas autorisé par le firewall. Donc, à moins de l'autoriser dans la config du firewall, ne pas passer par Preferences / Imprimantes, mais plutôt par le script d'installation :
sudo system-config-printer
Ajouter une imprimante
Cliquer sur "Imprimante Réseau", puis "IPP"
Là, on nous propose d'activer IPP qui n'est pas forcément activé par défaut
OK
Entrer directement l'URI complète de l'imprimante : ipp://impression.irap.omp.eu/printers/improche3
Le bon pilote devrait être automatiquement sélectionné
Activer le recto-verso dans les options
https://intranet.irap.omp.eu/spip.php?article103
Comment accéder à l'intranet depuis l'extérieur ?
1) Créer un tunnel (entre le port local 9443 et le port distant 443 du serveur web du labo, via la passerelle)
ssh -L 9443:SERVEURINTRANET.LAB_DOMAIN:443 MON_LOGIN_DU_LABO@SERVEURGATEWAY.LAB_DOMAIN
(Pour les personnes qui utilisent Windows, vous pouvez faire la même chose avec le logiciel Putty, en vous inspirant de ce qui est décrit sur cette même page au point 4) a) de l'article http://planetoweb.cesr.fr/twiki/bin/view/Main/HowtoInformatique#Se_connecter_un_serveur_linux_en)
2) Pointer son navigateur sur https://localhost:9443
Accepter le certificat, et le tour est joué, vous êtes sur l'intranet !
Comment accéder au site redmine depuis l'extérieur ?
C'est la même chose qu'au point précédent, mais en remplaçant SERVEURINTRANET par SERVEURREDMINE
Pour accéder au site de réservation des ressources, il suffit de faire comme au premier point ci-dessus (intranet), et de renseigner l’adresse du site : https://localhost:9443/grr
Comment accéder à un serveur interne au labo depuis l'extérieur, avec le logiciel Putty (souvent utilisé sur Windows)
(NB : si vous voulez vraiment utiliser ce logiciel sur Mac OS, il faut le faire via macport ; voici un lien utile : http://korben.info/installer-putty-mac.html)
A. Solution simple, sans tunnel
1) Démarrer Putty
2) Remplir les champs suivants :
Host Name = GATEWAY (nom à remplacer par le VRAI que je tairai sur cette page publique)
port = 22
connection type = ssh
3) Cliquer sur la catégorie "SSH" (à gauche), et sélectionner X11
4) Cocher "Enable X11 forwarding"
5) Cliquer sur la catégorie "Session" (à gauche, tout en haut)
6) Donner un nom à cette session dans le champ "Saved Sessions", par exemple "passerelle_labo"
7) Cliquer sur le bouton "Save"
From here, si on veut pouvoir visualiser des plots idl, il faut aussi démarrer le logiciel Xming (qu'on peut trouver ici : http://www.clubic.com/lancer-le-telechargement-202646-0-xming.html)
8) Exécuter cette session en cliquant sur le bouton "Open"
9) Saisir votre login puis votre mot de pass (ceux du webmail)
==> c'est bon, on est sur la passerelle
10) pour se loguer sur TEAM_SERVER, taper ceci :
ssh -X monlogin@TEAM_SERVER.LAB_DOMAIN
(le "-X" pas nécessaire si on ne veut pas d'affichage graphique)
(attention, ici utiliser le login TEAM_SERVER, pas celui du webmail)
puis entrer votre mot de passe de TEAM_SERVER (pas celui du webmail)
==> c'est bon, on est sur TEAM_SERVER
11) Tester si on a bien une connexion graphique
xterm
ou bien démarrer idl et faire un plot
Si ça ne marche pas c'est qu'il faut donner le nom exact du DISPLAY dans la session putty.
Depuis TEAM_SERVER, pour voir le numero exact du display (normalement quelque chose comme localhost:11.0 ou 11.1...), taper :
echo $DISPLAY
et mettre ce nom dans putty, dans SSH/X11/"X display location" (avec "Enable X11 forwarding" coché)
A. Solution avec tunnel
Si on a besoin de faire ça souvent, il vaut mieux "creuser" un tunnel d'accès direct au serveur TEAM_SERVER (ou autre), afin de pouvoir s'y connecter directement (sans l'étape passerelle, qui devient un intermédiaire transparent).
//TODO
Il faut créer la bd une première fois :
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
http://macvim.org/OSX/index.php
By default, Vim runs in "compatible" mode. That is, it acts a lot like traditional vi, without the improvements. Unless you want a maximally vi-compatible version of vim, I recommend that you copy the standard startup files to your home directory, and name them .vimrc and .gvimrc.
Ce que j'ai fait simplement :
1) recherche de vimrc_example :
locate vimrc
2) Copie locale :
cp /usr/share/vim/vim73/vimrc_example.vim .vimrc
Version 1.7.3
http://www.apachefriends.org/en/xampp-macosx.html
(ou aussi en french, mais moins à jour, http://www.apachefriends.org/fr/xampp-macosx.html)
1) Download
2) Install (environ 300Mo)
XAMPP est installé dans le répertoire/Applications/XAMPP
3) Démarrer
sudo /Applications/XAMPP/xamppfiles/xampp start
Sur l'écran devrait apparaitre les instructions suivantes:
Démarre XAMPP pour MacOS X 1.7.3... XAMPP: Démarre Apache avec SSL... XAMPP: Démarre MySQL... XAMPP: Démarre ProFTPD... XAMPP démarré.
Moi j'ai plutôt un pb avec proftpd, sans doute incompatible avec mac :
File permissions are being checked...ok. Starting XAMPP for Mac OS X 1.7.3... XAMPP: Starting Apache...ok. XAMPP: Starting MySQL...ok. XAMPP: Starting ProFTPD...XAMPP/XAMPP/xamppfiles/xampp: line 184: /Applications/XAMPP/xamppfiles//var/proftpd/start.err: No such file or directory fail. Contents of "/Applications/XAMPP/xamppfiles//var/proftpd/start.err": cat: /Applications/XAMPP/xamppfiles//var/proftpd/start.err: No such file or directory
4) Tester
http://localhost/ pointe automatiquement sur :
http://localhost/xampp/splash.php
et ça marche !
Si plus tard on remplace la page d'accueil de XAMPP par la sienne, on peut toujours joindre la page d'accueil de XAMPP avec http://localhost/xampp/
5) Aspects sécurité
Comme cela a déjà été expliqué antérieurement XAMPP n'est pas fait pour l'emploi de production, mais seulement pour développeur et l'environnement du développement. Cela a pour suite que XAMPP est volontairement préconfiguré pour ne pas être restrictif et être au contraire trés ouvert. Pour un développeur cela est idéal qu'il ne soit pas limité par les limites du systéme. Par contre pour un emploi en production cela est absolument pas recommendable.
Ici, une liste de choses donc XAMPP est volontairement(!) insécurisé:
1. L'administrateur (root)MySQL n'a pas de mot de passe. 2. Le démon MySQL est joignable par le réseau. 3. Le démon ProFTPD utilise le mot de passe "xampp". 4. PhpMyAdmin est joignable par le réseau. 5. MySQL et Apache fonctionne sous le même utilisateur (nobody)
Dans la page XAMPP-Demo (que l'on trouve sous http://localhost) il y a le point "Security check". À cet endroit on peut faire apparaître le niveau de sécurité actuel de XAMPP.
Si on veut utiliser XAMPP en réseau , pour que le serveur XAMPP soit accessible par d'autres utilisateurs, alors il faut impérativement exécuter les commandes suivantes avec lesquelles ont pourra alors limiter les failles de sécurité:
/Applications/XAMPP/xamppfiles/xampp security
6) START et STOP
To start XAMPP simply open XAMPP Control and start Apache, MySQL and ProFTPD.
Mais, on peut aussi utiliser la commande /Applications/XAMPP/xamppfiles/xampp :
on peut non seulement démarrer Xampp mais aussi exécuter d'autres commandes :
Pour arrêter XAMPP simplement entrer cette commande:
/Applications/XAMPP/xamppfiles/xampp stop
Pour démarrer Apache avec support SSL suivre les commandes suivantes:
/Applications/XAMPP/xamppfiles/xampp startssl
Et Apache avec support SSL fonctionne déjà. Joignable sous https://localhost.
Liste des autres commandes : http://www.apachefriends.org/fr/xampp-macosx.html#3413
7) FICHIERS ET RÉPERTOIRES IMPORTANTS
/Applications/XAMPP/xamppfiles/bin
Ici les commandes pour XAMPP.
(il suffit de placer /Applications/XAMPP/xamppfiles/bin dans mon $PATH pour que j'ai accès à toutes les commandes de xampp directement, telles que "mysql")
/Applications/XAMPP/xamppfiles/bin/mysql appelle par ex .MySQL.
/Applications/XAMPP/htdocs/
Le répertoire Root du serveur web Apache. Ici sont les pages web d'Apache.
/Applications/XAMPP/etc/httpd.conf
Le fichier central de configuration du serveur web Apache.
/Applications/XAMPP/etc/my.cnf
Le fichier de configuration pour le serveur MySQL -Base de données.
/Applications/XAMPP/etc/php.ini
Le fichier de configuration de PHP.
/Applications/XAMPP/etc/proftpd.conf
le fichier de configuration de ProFTPd.
8) Mes Sites Webs
You can put your Websites in /Applications/XAMPP/htdocs/ and access them via http://localhost/
Or you put your Websites in the Sites-Folder in your Home and access them via http://localhost/~pallier/.
Whats the username and the password for MySQL?
Username: root Password: No password
9) Désinstallation
To uninstall XAMPP just stop it and move it to the Trash.
Ou bien
sudo rm -rf /Applications/XAMPP
http://www.blogafab.com/installer-apache-2-mysql-5-et-php-5-3-sur-mac-os-10-7-lion-avec-macport/
Install XCode4 via AppleStore (1,8 Go) (AC)
Install MacPort2 (1,7Mo only) :
Téléchargez MacPorts 2.0 sur le site officiel http://www.macports.org/
Ouvrez le fichier .dmg que vous venez de télécharger
Lancez le fichier .pkg et suivez les instructions
Crée un fichier ~pallier/.bash_login qui ajoute /opt/local/bin au PATH
sudo port -v selfupdate
Téléchargez et installez Apache2 et ses dépendances :
sudo port install apache2
Une fois l’installation terminée, vous pouvez activer lancement automatique de Apache au démarrage de l’ordinateur :
sudo port load apache2
fichiers sont dans /Library/LaunchDaemons/org.macports.apache2.plist
Téléchargez et installez MySQL 5 et ses dépendances :
sudo port install mysql5
Installez/Activez le serveur MySQL 5 :
sudo port install mysql5-server
Une fois l’installation terminée, vous pouvez activer le lancement automatique de MySQL au démarrage de l’ordinateur :
sudo port load mysql5-server
Terminez l’installation de MySQL :
sudo -u _mysql mysql_install_db5
Une fois l’installation terminée, vous pouvez lancer MySQL au démarrage de l’ordinateur :
sudo port load mysql5
Téléchargez et installez PHP 5.3 et ces dépendances. A noter ici que je choisi également d’activer le PEAR, d’où le +pear.
sudo port install php5 +pear
Ajoutez le module PHP pour Apache 2 :
sudo /opt/local/apache2/bin/apxs -a -e -n "php5" /opt/local/apache2/modules/libphp5.so
Créez le fichier de configuration php.inide PHP :
sudo cp /opt/local/etc/php5/php.ini-development /opt/local/etc/php5/php.ini
Installez et activez MySQL pour PHP :
sudo port install php5-mysql
Étape optionnelle : Installez quelques extensions utiles pour PHP (apc, curl, gd, iconv, mbstring, …).
sudo port install php5-apc php5-curl php5-gd php5-iconv php5-intl php5-mbstring php5-mcrypt php5-posix php5-sqlite php5-xdebug php5-zip
Les étapes ci-dessous permettent de configurer le support de PHP dans Apache et d’activer le module UserDir (facultatif).
Activer PHP dans Apache Éditez le fichier /opt/local/apache2/conf/httpd.conf Ajoutez à la fin du fichier
# Include PHP configuration Include conf/extra/mod_php.conf
Ajouter index.php dans les pages d’index reconnues par Apache Éditez le fichier /opt/local/apache2/conf/httpd.conf Recherchez la ligne ci-dessous :
DirectoryIndex index.html
Ajoutez sur la même ligne, à la fin :
index.php
Étape optionnelle : Activer l’extension UserDir pour Apache. Cette extension permet d’avoir des urls dédiées pour chaque utilisateur de l’ordinateur du type http://localhost/~utilisateur/
Éditez le fichier /opt/local/apache2/conf/httpd.conf
Recherchez et décommentez la ligne ci-dessous :
#Include conf/extra/httpd-userdir.conf
Étape optionnelle : Autoriser l’ajout/suppression d’options via un .htaccess (exemple Options +FollowSymLinks) Éditez le fichier /opt/local/apache2/conf/extra/httpd-userdir.conf Recherchez la ligne ci-dessous :
AllowOverride FileInfo AuthConfig Limit Indexes
Ajoutez sur la même ligne, à la fin :
Options
Une fois les modifications effectuées, vous pouvez (re)démarrer Apache :
sudo /opt/local/apache2/bin/apachectl restart
Les étapes ci-dessous ont pour objectif de configurer et sécuriser votre serveur MySQL.
Démarrez le serveur MySQL
sudo /opt/local/lib/mysql5/bin/mysqld_safe &
Sécurisez votre serveur MySQL. Je vous recommande de configurer le mot de passe root et de répondre « Yes » à toutes les questions.
sudo /opt/local/lib/mysql5/bin/mysql_secure_installation
Configurer MySQL pour PHP Éditez le fichier /opt/local/etc/php5/php.ini Recherchez les paramètres pdo_mysql.default_socket, mysql.default_socket, mysqli.default_socketet mettez comme valeur ceci :
/opt/local/var/run/mysql5/mysqld.sock
Configurer le fuseau horaire par défaut Éditez le fichier /opt/local/etc/php5/php.ini Recherchez la ligne suivante :
;date.timezone =
Remplacez par :
date.timezone = "Europe/Paris"
Étape optionnelle : Activer les archives Phar Éditez le fichier /opt/local/etc/php5/php.ini Recherchez et décommentez la ligne ci-dessous
;phar.readonly = On
Une fois les modifications terminées, redémarrez votre serveur Apache 2.
Apache :
Fichier gestion : /Library/LaunchDaemons/org.macports.apache2.plist
start : sudo port load apache2 (apachectl start/stop ne semble pas marcher)
Voir les processus apache : ps -efl|grep apac
stop : sudo port load apache2
(le Apache d'origine de Mac est démarré via les préférences systèmes, partage, web : on voit alors les processus avec "ps -efl | grep http")
apache déjà installé, mais pas activé
php déjà installé mais pas activé
mysql à installer
Pour activer le serveur, allez dans Préférences système -> Partage et cochez la case Partage Web. Si elle est déjà cochée, décochez-la pour arrêter le serveur et recochez-là pour que la modification du fichier httpd.conf soit prise en compte.
v2.2.20
/usr/sbin/
Documents : /Library/Webserver/Documents/
v5.3.6
Php : /usr/lib/
Pour activer PHP il faut décommenter la ligne #LoadModule php5_module libexec/apache2/libphp5.so du fichier httpd.conf situé dans le dossier apache2 du dossier etc.
Ensuite réactiver le serveur apache (voir ci-dessus)
Ajouter test.php dans le rep doc de apache qui contient :
ou encore http://localhost:80/test
http://www.patpro.net/blog/index.php/2008/01/27/135-mysql-sur-mac-os-x-105-en-5-minutes/
Download :
http://dev.mysql.com/downloads/
Community server
version 64 bits (format DMG) pour Mac OS 10.6
masquer/afficher le dock (barre du bas) : cmd-alt-D
Avoir accès au labo depuis l'extérieur (via la passerelle SSH du labo) : suivre la procédure décrite sur l'intranet (https://intranet.irap.omp.eu/spip.php?article103)
Par défaut, root n'a pas de mot de passe, il faut donc en définir un :
su passwd root
Ensuite, pour passer root, comme d'hab :
su -
ou
su - root
ou
sudo -s
pomme, préférences systèmes, partage : changer le nom, puis fermer
(sudo hostname newname ne change que temporairement)
sudo scutil --set HostName hostname[.domain]
(if the domain is not specified the hostname will be automatically configured as .local)
vi .bash_login : source .bash_rc
vi .bash_rc : alias l="ls -l"
Pref Sys / Imprimantes
bouton "+"
bouton "IP"
rechercher "sprinter.cesr.fr"
elle est trouvée en tant que "hp laserjet 2300 series"
http://www.osxfacile.com/partition.html
Applications / Utilitaires / Utilitaire de disque
onglet "Partition"
Diminuer la partition unique "Macintosh HD" de 500 à 100Go
Bouton "+" pour ajouter une nouvelle partition de 400Go
http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&item_id=ukelele
http://support.apple.com/kb/HT1220
ScrapBook plugin : Volumes/DATA/ScrapBook
Visualiser un dossier ou fichier caché : http://perso.univ-lyon2.fr/~brogniar/articles/mosx-fichier-invisible.html
maj-pom-G
Pour montrer les éléments cachés il faut taper la commande "defaults write com.apple.finder AppleShowAllFiles 1". Pour cacher à nouveau les fichiers et dossiers spéciaux il faut taper la commande "defaults write com.apple.finder AppleShowAllFiles 0". L'utilitaire TinkerTool de Marcel Bresink permet de régler ces préférences d'une manière plus conviviale.
home : cmd left end : cmd right mot : alt left/right Effacer le mot suivant Ctrl+Suppr
entre applis : Cmd Tab entre onglets d'une mm appli : ctrl tab entre fenêtres d'une mm appui : (alt tab ???) cmd * (sur clavier mac, c'est cmd `, sous le £), à droite de la lettre "m"
packages = .dmg
Pas de /etc/init.d/
A la place :
/System/Library/StartupItems et /Library/StartupItems
Apple provides a program called SystemStarter which is used to start and stop scripts in the /System -> Library -> StartupItems and /Library -> StartupItems folders. You can use it to restart services like so: % sudo SystemStarter restart NetInfo Or if you've just installed GimpPrint and need to restart CUPS for it to find your printer: % sudo SystemStarter restart PrintingServices The one caveat is that all the start, stop, and restart options do is pass this argument to the various scripts. If the script doesn't respond to that argument, nothing happens. An example is AppServices, which controls coreservicesd. Sending stop or restart to this script has no effect.
Type man SystemStarter and browse through the various scripts to learn more about the program and the scripts.
RACCOURCIS
caractère DIESE : maj alt * (touche à droite du "m")
Refaire (Ctrl+Maj+Z) Cmd+Maj+Z Ouvrir un menu contextuel (Maj+F10) Ctrl+Espace
(Windows-E) Cmd-Maj-C Ouvre la fenêtre Computer sous Windows. / Va sur la vue Computer dans le Finder sous Mac OS X
(Ctrl-Maj-Echap) Cmd-Option-Esc Ouvre une fenêtre permettant de forcer l'arrêt d'une application
Quitter un programme
Afficher les propriétés
<Command> + <I>
Forcer à quitter : Command + Option + Escape
Capture d'écran : Command + Shift + 3
Bureau : F11
Voir l'ensemble des appris en réduction : F9 et F10
Masquer finder : cmd H
Masquer les autres : cmd alt H
Créer un alias : Pom-alt + déplacer une icone sur bureau
Créer un alias/raccourci : Command + L
=========================================================
http://www.vogella.de/articles/JavaIntroduction/article.html#classpath
Run your program outside Eclipse :
Open a command shell, e.g. under Microsoft Windows select Start -> Run and type in cmd. This should open a consle.
Switch to your output directory, e.g. by typing cd path, e.g. if you jar is located in "c:\temp" type "cd c:\temp".
To run this program you need to include the jar file into your classpath.
java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass
You can use the classpath to run the program from another place in your directory.
Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any directory you want. Type:
java HelloWorld
If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass
To use the class type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.
java -classpath "mydirectory" HelloWorld
Create an executable JAR
A JAR file is a Java Archive based on the pkzip file format. A jar files can contain java classes and other resources (icons, property files) and can be executable.
JAR files are the deployment format for Java. You can distribute your program in a jar file or you can use exiting java code via jars by putting them into your classpath.
An executable JAR means the end-user doesn't have to pull the class files out before running the program. This is done via a manifest.txt file which tells the JVM which class has the main() method. The content of the manifest.txt file:
Manifest-Version: 1.0 Main-Class: MyApp Class-Path: . lib/jcommon-1.0.6.jar lib/itext-1.4.6.jar "Empty Line"
An empty line is required otherwise the jar won't be executable. Space after a new line is also required
To create one executable JAR file run on the command line
jar -cvmf mainfest.txt app1.jar *.class
Window -> show view -> Other... -> SVN repositories
sélectionner une location et la supprimer (touche suppr)
1) Download Yoxos :
http://eclipsesource.com/en/downloads/eclipse-indigo-download/
download for mac 64 bits
2) Run Yoxos :
Add "Eclipse for java developpers"
SwingDesigner (inclus) : http://code.google.com/intl/fr/javadevtools/wbpro/whatsnew/index.html
WindowBuilder (inclus) : http://code.google.com/intl/fr/javadevtools/wbpro/quick_start.html
(Junit est déjà inclut)
Add subclipse
Add pdt
Add MakeGood (TDD intégré à pdt)
Add php source feature (automatic php code generation, getters, setters...)
FEST ??? :
http://code.google.com/p/fest/
http://fest.easytesting.org/
http://docs.codehaus.org/display/FEST/Home
CA NE MARCHE PAS !!!
DONC, INSTALLATION MANUELLE (ci-dessous)
1) (Pas sûr que ça soit nécessaire) install client subversion en local sur le disque (avec JavaHL)
(http://subclipse.tigris.org/wiki/JavaHL#head-5bf26515097c3231c1b04dfdb22c036bc511926b)
http://www.open.collab.net/downloads/community/
downloaded subversion 1.6.x
Installé dans /opt/subversion (/opt a été créé pour l'occasion lors de l'installation !!!!)
Uninstallation Notes To uninstall the Subversion 1.6.17 Universal binary, just run the following:
sudo rm -fR /opt/subversion pkgutil --forget net.collab.subversion
2) install subclipse (plugin eclipse)
Help / Install new software
http://subclipse.tigris.org/update_1.6.x/ (la version 1.8 ne marchait pas)
(pour info, voir http://subclipse.tigris.org)
1) installer Eclipse pour Java (testé avec 3.7 Indigo)
Download "Eclipse IDE for Java Developers" from http://www.eclipse.org/downloads
2) installer Junit
http://www.vogella.de/articles/JUnit/article.html
http://junit.sourceforge.net/doc/cookbook/cookbook.htm
When you need to test something, here is what you do:
Annotate a method with @org.junit.Test When you want to check a value, import org.junit.Assert.* statically, call assertTrue() and pass a boolean that is true if the test succeeds (Use a method provides by JUnit to check the expected result of the code execution versus the actual result)
For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:
@Test public void simpleAdd() { Money m12CHF= new Money(12, "CHF"); Money m14CHF= new Money(14, "CHF"); Money expected= new Money(26, "CHF"); Money result= m12CHF.add(m14CHF); assertTrue(expected.equals(result)); }
Fixture :
What if you have two or more tests that operate on the same or similar sets of objects?
Tests need to run against the background of a known set of objects. This set of objects is called a test fixture. When you are writing tests you will often find that you spend more time writing the code to set up the fixture than you do in actually testing values.
To some extent, you can make writing the fixture code easier by paying careful attention to the constructors you write. However, a much bigger savings comes from sharing fixture code. Often, you will be able to use the same fixture for several different tests. Each case will send slightly different messages or parameters to the fixture and will check for different results.
When you have a common fixture, here is what you do:
Add a field for each part of the fixture
Annotate a method with @org.junit.Before and initialize the variables in that method
Annotate a method with @org
.junit.After to release any permanent resources you allocated in setUp
For example, to write several test cases that want to work with different combinations of 12 Swiss Francs, 14 Swiss Francs, and 28 US Dollars, first create a fixture:
public class MoneyTest { private Money f12CHF; private Money f14CHF; private Money f28USD;
@Before public void setUp() {
f12CHF= new Money(12, "CHF");
f14CHF= new Money(14, "CHF");
f28USD= new Money(28, "USD");
}
}
Once you have the Fixture in place, you can write as many Test Cases as you'd like. Add as many test methods (annotated with @Test) as you'd like.
You use a tool like Eclipse or the class "org.junit.runner.JUnitCore" to run the test.
Download junit-dep-4.10 from https://github.com/KentBeck/junit/downloads
3) Créer un projet Java
Create a new project "de.vogella.junit.first".
We want to create the unit tests in a separate folder. Create therefore a new source folder "test" via right mouse click on your project, select properties and choose the "Java Build Path". Select the tab source code. Press "Add folder" then then press "Create new folder". Create the folder "test". The creation of an separate folder for the test is not mandatory. But it is good advice to keep the test coding separate from the normal coding.
Create a Java class
Create a package "de.vogella.junit.first" and the following class.
package de.vogella.junit.first; public class MyClass { public int multiply(int x, int y) { return x / y; } }
4) Create a JUnit test
Select your new class, right mouse click and select New ->JUnit Test case, change the source folder to JUnit. Select "New JUnit 4 test". Make sure you change the source folder to test.
Press next and select the methods which you want to test.
If you have not yet JUnit in your classpath, Eclipse will asked you if it should be added to the classpath.
Create a test with the following code.
package de.vogella.junit.first; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MyClassTest { @Test public void testMultiply() { MyClass tester = new MyClass(); assertEquals("Result", 50, tester.multiply(10, 5)); } }
5) Run your test via Eclipse
Right click on your new test class and select Run-As-> Junit Test.
The test should be failing (indicated via a red bar). This is due to the fact that our multiplier class is currently not working correctly (it does a division instead of multiplication). Fix the bug and re-run test to get a green light.
If you have several tests you can combine them into a test suite. All test in this test suite will then be executed if you run the test suite. To create a new test suite, select your test classes, right mouse click-> New-> Other -> JUnit -Test Suite
Select next and select the methods you would like to have test created for.
cela crée une classe AllTests.java :
package de.vogella.junit.first; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ MyClassTest.class, OtherClassTest.class }) public class AllTests { }
If you later develop another test you can add it to @Suite.SuiteClasses
6) Run your test via code
You can also run your test via your own coding. The class "org.junit.runner.JUnitCore" provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of type "org.junit.runner.Result". This object can be used to retrieve information about the tests and provides information about the failed tests.
Create in your "test" folder a new class "MyTestRunner" with the following coding. This class will execute your test class and write potential failures to the console.
package de.vogella.junit.first; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class MyTestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MyClassTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } } }
7) Annotations and Assert statements
a) Annotations
The following give an overview of the available annotations in JUnit 4.x
Annotation Description @Test public void method() Annotation @Test identifies that this method is a test method. @Before public void method() Will perform the method() before each test. This method can prepare the test environment (called a "fixture"), e.g. read input data, initialize the class) @After public void method() Test method must start with test @BeforeClass public void method() Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database @AfterClass public void method() Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database @Ignore Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included. @Test(expected=IllegalArgumentException.class) Tests if the method throws the named exception @Test(timeout=100) Fails if the method takes longer then 100 milliseconds
b) Assert statements
The following gives an overview of the available test methods:
Statement Description fail(String) Let the method fail, might be usable to check that a certain part of the code is not reached. assertTrue(true); True assertsEquals([String message], expected, actual) Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays assertsEquals([String message], expected, actual, tolerance) Usage for float and double; the tolerance are the number of decimals which must be the same assertNull([message], object) Checks if the object is null assertNotNull([message], object) Check if the object is not null assertSame([String], expected, actual) Check if both variables refer to the same object assertNotSame([String], expected, actual) Check that both variables refer not to the same object assertTrue([message], boolean condition) Check if the boolean condition is true.
8) Fixture (see http://junit.sourceforge.net/doc/cookbook/cookbook.htm)
9) Running Tests FROM JAVA (see http://junit.sourceforge.net/doc/cookbook/cookbook.htm)
10) Expected Exceptions (see http://junit.sourceforge.net/doc/cookbook/cookbook.htm)
(pour les admins, voir aussi InformationAboutThisTwiki)
Par exemple, créer comme raccourci de l'icône TODO :
Editer TWikiPreferences
* Set TD = %ICONURL{todo}% * Set DONE = %ICONURL{done}%
Html comment = <!-- comment --> Twiki comment = # comment
Pour savoir ce qui a changé (en ordre chronologique) sur le web Team, consulter cette page : WebChanges
Changements survenus sur le web "twiki" : WebChanges
on peut aussi s'inscrire sur cette page pour recevoir les changements du web Team par email : WebNotify
Vous êtes vivement encouragés à contribuer au contenu de ce site.
Pour modifier n'importe quelle page du site :
Il vaut mieux utiliser des noms de fichier assez génériques (par exemple FDD.pdf au lieu de FF_v1.4.pdf) ainsi on peut mettre à jour un document sans changer son nom et les liens vers ce fichier
%Y% |
![]() |
%TD%ou %ICONURL{todo}% |
![]() |
%DO%ou %ICONURL{done}% |
![]() |
%CL%ou %ICONURL{closed}% |
![]() |
http://planetowiki.irap.omp.eu/do/view/Computers/Hyperion2Server#How_to_use_my_personal_IDL_from
Selectionner Window/Source Control Tools/Subversion
Selectionner le connecteur SVN nommé SVNKit 1.3.0 (for svn 1.6.2) (ou un plus ancien car le serveur svn qui est sur planetoweb est une ancienne version 1.4.4)
Terminer l'installation, redémarrer IDL, c'est fait
Le depot (repository) svn de chemcam est http://planetoweb.cesr.fr/chemcam_svn et accepte les comptes créés sur ce wiki
Voici ce qu'il faut faire pour corriger le pb :
cd /Applications/itt/idl/idl81/bin/bin.darwin.x86_64/
mv libcurl.4.0.1.dylib libcurl.4.0.1.dylib.bak
mv libcurl.4.dylib libcurl.4.dylib.bak
mv libcurl.dylib libcurl.dylib.bak
Lire l'article complet sur le pb :
The "Direct Rendering Infrastructure" (DRI) or "Direct hardware rendering" is described here :
http://www.ittvis.com/services/techtip.asp?ttid=3524
As it currently does not work on TEAM_SERVER, we have to deactivate it and activate "software rendering" instead (slower).
How to set IDL to use "software rendering" (IDL 8 issue) ?
Fenêtre/Préférences/IDL/Graphiques :
Méthode de rendu pour les objets graphiques : sélectionner "Logiciel" au lieu de "Matériel"
There are a couple of ways to set IDL to use software rendering, besides from the IDLDE.
If you want to set the entire IDL session to use software rendering, then when you start up IDL, you could use this command:
idl -IDL_GR_WIN_RENDERER 1 (for Windows) or idl -IDL_GR_X_RENDERER 1 (for X Windows)
If you want to switch from the default hardware rendering to software rendering in the middle of an IDL session, you could use this command:
PREF_SET, 'IDL_GR_WIN_RENDERER', '1', /COMMIT (for Windows) or PREF_SET, 'IDL_GR_X_RENDERER', '1', /COMMIT (for X Windows)
Je livre ici une synthèse des conseils de Michael Galloy pour bien documenter un code IDL (Lire "A style guide" pour la version complète avec justifications) :
1. Code is for humans.
2. Do not mix styles.
3. Avoid redundancy.
4. Use an easy to maintain style.
1. Layout should enhance the logical structure of the code.
2. Use two spaces (not tabs) per indentation level.
3. Use a maximum line length of 79 characters.
4. Write code in paragraphs.
Example:
function mg_sample, nValues, nIndices, seed=seed compile_opt strictarr ; get random nIndices by finding the indices of the smallest ; nIndices in an array of random values values = randomu(seed, nValues) ; our random values are uniformly distributed, so ideally ; the nIndices smallest values are in the first bin of the ; below histogram nBins = nValues / nIndices h = histogram(values, nbins=nBins, reverse_indices=ri) ; the candidates for being in the first nIndices will live in ; bins 0..bin nCandidates = 0L for bin = 0L, nBins - 1L do begin nCandidates += h[bin] if (nCandidates ge nIndices) then break endfor ; get the candidates and sort them candidates = ri[ri[0] : ri[bin + 1L] - 1L] sortedCandidates = sort(values[candidates]) ; return the first nIndices of them return, (candidates[sortedCandidates])[0:nIndices-1L] end
5. Insert two blank lines between routines.
One blank line separates "paragraphs"; two blank lines separate "sections."
1. Document intent.
2. Keep comments up to date with the code.
3. For a short comment, use a phrase with lowercase first letter and no period. For longer comments, use all normal grammar rules.
5. Write a complete header for each routine.
Use comments between ;+ and ;- before the routine. Document the purpose of the routine, the return value (if a function), and side effects of the routine (which you should strive to eliminate). Each parameter should be documented with whether it is an input and/or output, optional or required, data type expected, default value (if any) and a description of its purpose.
For example, the below is an IDLdoc formatted header for the routine listed above:
;+ ; Get nIndices random indices for an array of size nValues (do ; not repeat an index). ; ; :Returns: lonarr(nIndices) ; ; :Params: ; nValues : in, required, type=long ; size of array to choose indices from ; nIndices : in, required, type=long ; number of indices needed ; ; :Keywords: ; seed : in, out, optional, type=long or lonarr(36) ; seed to use for random number generation, a new seed ; will be output ;- function mg_sample, nValues, nIndices, seed=seed
6. Indent a comment along with the code it's documenting.
7. Document paragraph by paragraph.
Each paragraph of code may need a comment to document its purpose, but inside a paragraph use only end-of-line comments to comment particular lines. It can be helpful to write the comments first, providing an outline of the code to write.
ex of end-of-line comment :
if (event.type eq 2) then begin ; type 2 = motion events
9. Don't repeat the code in the comments.
Don't document the obvious.
10. Don't add extra comments for convoluted code; improve the code.
Don't document bad code—rewrite it. (Kernighan and Plauger, The Elements of Programming Style)
For example, use:
compile_opt strictarr if (not done) then readf, lun, line
For example, don't write:
a = 1 & b = 2
For a single, long statement, use:
for i = 0, 10 do begin print, i, format='("The index is ", I0, ".")' end
But never write:
for i = 0, 10 do $ print, i, format='("The index is ", I0, ".")'
For example, use:
point = { x: 0.0, y:0.0 } state = { x: 0.0, $ y: 0.0, $ pdata: ptr_new(), $ ; image data drawId: 0L $ ; window identifier }
ex:
slope = (y0 - y1) / (x0 - x1)
tvscl, im, true=1
bin = arr[r[r[i]:r[i + 1] - 1]]
point = { x: 0.0, y: 0.0 }
Also, don't add extra spaces in order to align values.
Use double single quotes if you need a single quote. For example,
sign = 'Eat at Joe''s'
Use 0L not 0l because "l" (lowercase letter el) looks like "1" (integer one). Use '5'o and '5'x, not '5'O and '5'X.
Use
compile_opt strictarr
in each routine to prevent issues with IDL confusing arrays and functions calls.
1. Use good variable names.
2. Variable names should be in camel case.
Camel case uppercases the first letter of each word in the name except for the first letter.
Uppercase each letter in an abbreviation that appears in a variable name unless it starts the name:
noaaWeatherURL.
Prefix the name with "n" for variables that hold counts, "o" for object references, "p" for pointers, "id" for iTools identifiers.
Examples that follow this convention,
nFiles oModel pState idPlot
3. Prefer pointers, objects, and passing local variables over common blocks or system variables.
Occasionally there is a reason to use common blocks or system variables, but you should have a good argument for it.
When using direct graphics, prefer using graphics keywords of the plotting routines over setting system variables directly.
4. Define common blocks and named structures in only one location.
Define the variables in a common block only once in a batch file. Include that file where needed.
map_proj_init_commonblock.pro is an example of this.
Define a named structure using automatic structure definition. For example, define MG_Point in a routine named MG_POINT__DEFINE in a file named mg_point__define.pro.
1. For any file containing IDL code, filenames should always be in lower case and use the ".pro" extension.
2. Each file should include only one routine called from outside the file.
Each file should contain only one routine called from outside that file. Add the ".pro" extension to the routine name of the externally called routine to get the filename. For example, the routine MG_LINEAR_FUNCTION should be in a file named mg_linear_function.pro. If there are multiple routines in the file, make sure the externally called routine is last in the file.
3. Routine names should be lower case, begin with a short organization prefix, and separate words with underscores.
The prefix indicates the individual or group responsible for the code. It is usually the initials of the individual or orgranization. Limit to two or three letters. Don't use the "IDL", "RSI", "ITT", "cw", "it", or empty prefixes.
4. Routines should fit on one screen.
5. Keywords should always be optional for the caller; positional parameters should generally be required.
Keywords should either be an optional input with a reasonable default value or an extra output (i.e. not the main purpose of the routine).
6. Keyword names should be lowercase and separate words with underscores.
For example,
filename ntests eye_separation left_image
7. Always use the full keyword name when calling the routine.
8. If the purpose of a routine is to return a value, use a function, otherwise use a procedure.
9. Status and error codes should be returned via keyword.
1. Class names should begin with a prefix indicating organization and a code indicating the class' area of use. Each word should be capitalized
Use the same prefix as given to normal routine names; avoid "IDL", "ITT", "RSI", and the empty prefix.
Codes already in use by IDL: an (analysis), com (COM), db (database), ex (example), ff (file format), gr (graphics), it (iTools), sys (system), net (network), and _ (general use). Make use of the existing codes and make up new ones as necessary.
Use all caps for abbreviations in class names, as in IDLnetURL.
2. Put all the methods and the routine defining the instance variables for a class into a single file.
For the definition of MGexClass, the file should be named mgexclass__define.pro. The last routine in this file should be MGEXCLASS__DEFINE and should define the instance variables for the class (i.e. create a named structure with name MGexClass).
Define only one structure/class name in the __DEFINE routine.
3. Method names should be a verb phrase in camel case.
For example, here are some method names following these conventions:
getProperty setProperty add findTestNames runTest reportTestResult
Use the conventions that are used by the IDL library classes. For example, use the GETPROPERTY and SETPROPERTY scheme of procedures to handle getting and setting properties of a class.
4. Begin "protected" methods' names with a underscore.
For example,
MGexSomeClass::_helperMethod
is a helper method called by other methods in MGexSomeClass, but should not be called from outside of MGexSomeClass.
5. Beware of multiple inheritance.
Use multiple inheritance as a last resort. Prefer delegation for one of the parent classes i.e. make the new class contain the secondary parent class as an instance variable.
;+ ; NAME: ; ROUTINE_NAME ; ; PURPOSE: ; Tell what your routine does here. I like to start with the words: ; "This function (or procedure) ..." ; Try to use the active, present tense. ; ; CATEGORY: ; Put a category (or categories) here. For example: ; Widgets. ; ; CALLING SEQUENCE: ; Write the calling sequence here. Include only positional parameters ; (i.e., NO KEYWORDS). For procedures, use the form: ; ; ROUTINE_NAME, Parameter1, Parameter2, Foobar ; ; Note that the routine name is ALL CAPS and arguments have Initial ; Caps. For functions, use the form: ; ; Result = FUNCTION_NAME(Parameter1, Parameter2, Foobar) ; ; Always use the "Result = " part to begin. This makes it super-obvious ; to the user that this routine is a function! ; ; INPUTS: ; Parm1: Describe the positional input parameters here. Note again ; that positional parameters are shown with Initial Caps. ; ; OPTIONAL INPUTS: ; Parm2: Describe optional inputs here. If you don't have any, just ; delete this section. ; ; KEYWORD PARAMETERS: ; KEY1: Document keyword parameters like this. Note that the keyword ; is shown in ALL CAPS! ; ; KEY2: Yet another keyword. Try to use the active, present tense ; when describing your keywords. For example, if this keyword ; is just a set or unset flag, say something like: ; "Set this keyword to use foobar subfloatation. The default ; is foobar superfloatation." ; ; OUTPUTS: ; Describe any outputs here. For example, "This function returns the ; foobar superflimpt version of the input array." This is where you ; should also document the return value for functions. ; ; OPTIONAL OUTPUTS: ; Describe optional outputs here. If the routine doesn't have any, ; just delete this section. ; ; COMMON BLOCKS: ; BLOCK1: Describe any common blocks here. If there are no COMMON ; blocks, just delete this entry. ; ; SIDE EFFECTS: ; Describe "side effects" here. There aren't any? Well, just delete ; this entry. ; ; RESTRICTIONS: ; Describe any "restrictions" here. Delete this section if there are ; no important restrictions. ; ; PROCEDURE: ; You can describe the foobar superfloatation method being used here. ; You might not need this section for your routine. ; ; EXAMPLE: ; Please provide a simple example here. An example from the ; DIALOG_PICKFILE documentation is shown below. Please try to ; include examples that do not rely on variables or data files ; that are not defined in the example code. Your example should ; execute properly if typed in at the IDL command line with no ; other preparation. ; ; Create a DIALOG_PICKFILE dialog that lets users select only ; files with the extension `pro'. Use the `Select File to Read' ; title and store the name of the selected file in the variable ; file. Enter: ; ; file = DIALOG_PICKFILE(/READ, FILTER = '*.pro') ; ; MODIFICATION HISTORY: ; Written by: Your name here, Date. ; July, 1994 Any additional mods get described here. Remember to ; change the stuff above if you add a new keyword or ; something! ;- PRO TEMPLATE PRINT, "This is an example header file for documenting IDL routines" END
Le même bloc de commentaires, mais vide :
;+ ; NAME: ; ; ; ; PURPOSE: ; ; ; ; CATEGORY: ; ; ; ; CALLING SEQUENCE: ; ; ; ; INPUTS: ; ; ; ; OPTIONAL INPUTS: ; ; ; ; KEYWORD PARAMETERS: ; ; ; ; OUTPUTS: ; ; ; ; OPTIONAL OUTPUTS: ; ; ; ; COMMON BLOCKS: ; ; ; ; SIDE EFFECTS: ; ; ; ; RESTRICTIONS: ; ; ; ; PROCEDURE: ; ; ; ; EXAMPLE: ; ; ; ; MODIFICATION HISTORY: ; ;-
doc_library affiche seulement "tel quel" le bloc de commentaires complet compris entre ";+" et ";-", et affiche le chemin du fichier.
Pour documenter une fonction ou une procédure :
IDL> doc_library, 'DIST' ----- Documentation for C:\Program Files\ITT\IDL\IDL80\lib\dist.pro NAME: DIST PURPOSE: Create a rectangular array in which each element is proportional to its frequency. This array may be used for a variety of purposes, including frequency-domain filtering and making pretty pictures. CATEGORY: Signal Processing. CALLING SEQUENCE: Result = DIST(N [, M]) INPUTS: N = number of columns in result. M = number of rows in result. If omitted, N is used to return a square array. OUTPUTS: Returns an (N,M) floating array in which: R(i,j) = SQRT(F(i)^2 + G(j)^2) where: F(i) = i IF 0 <= i <= n/2 = n-i IF i > n/2 G(i) = i IF 0 <= i <= m/2 = m-i IF i > m/2 SIDE EFFECTS: None. RESTRICTIONS: None. PROCEDURE: Straightforward. The computation is done a row at a time. MODIFICATION HISTORY: Very Old. SMR, March 27, 1991 - Added the NOZERO keyword to increase efficiency. (Recomended by Wayne Landsman) DMS, July, 1992. - Added M parameter to make non-square arrays. CT, RSI, March 2000: Changed i^2 to i^2. to avoid overflow.
IDL> doc_library, 'plot' ----- Documentation for C:\Program Files\ITT\IDL\IDL80\lib\graphics\plot.pro :Description: Create IDL Plot graphic. :Params: arg1 : optional generic argument arg2 : optional generic argument :Keywords: _REF_EXTRA
Dans ce dernier exemple (plot), on se rend compte que depuis idl 8, les nouvelles fonctions/procédures (telles que la fonction plot) ne sont plus commentées au format "idl" mais "rst", qui semble donc être le nouveau format à utiliser pour commenter du code idl.
Cet outil génère une doc html d'un fichier ou même d'un répertoire complet :
ex: documentation du fichier dist.pro:
MK_HTML_HELP, 'C:\Program Files\ITT\IDL\IDL80\lib\dist.pro', 'help_dist.html' ; La doc générée est help_dist.html
ex: documentation d'une arborescence complète:
MK_HTML_HELP, 'C:\Program Files\ITT\IDL\IDL80\lib', 'help.html' ; La doc générée est help.html
home: http://idldoc.idldev.com/
download: http://idldoc.idldev.com/wiki/Downloads
tutoriel: http://idldoc.idldev.com/wiki/GettingStarted
idldoc est un outil qui permet de générer une doc à partir du code idl
Il propose 3 formats différents :
Ce dernier format ("idl") a juste le "mérite" d'être un standard pour les routines IDL, mais il est peu et mal exploité par IdlDoc qui ne reconnait que très peu de balises de commentaires (seulement 6) parmis celles proposées dans template.pro, et les met mal en valeur dans la doc générée.
Les 6 balises exploitées sont :
; PURPOSE:
; SIDE EFFECTS:
; RESTRICTIONS:
; PROCEDURE:
; EXAMPLE:
; MODIFICATION HISTORY:
Cette dernière balise est affichée en tant que "Author information" dans la doc générée
Quant à la balise suivante...
; CALLING SEQUENCE:
... elle n'est pas reconnue, mais elle semble inutile puisque cette information est automatiquement générée par idldoc.
Voir mes commentaires à l'auteur du logiciel et ses réponses:
http://michaelgalloy.com/2010/10/20/idldoc-3-3-released.html
(NB: sur TEAM_SERVER, c'est déjà installé sous /usr/local/itt/idldoc/idldoc)
1) Download
2) Copier et dézipper dans un dossier de mon choix (ex : D:/idldoc/idldoc-3.3)
3) Ajouter le chemin vers idldoc dans le IDL_PATH (Fenêtre/Preferences/IDL/Chemins/Insérer (puis Appliquer)
Pour générer la doc avec idldoc :
IDL> idldoc, root='path_vers_mon_repertoire_source', output='path_vers_mon_repertoire_doc'
Puis, 2clic sur index.html
Exemple plus complet:
IDL> idldoc, root='path_vers_mon_repertoire_source', output='path_vers_mon_repertoire_doc', title='DOC pour mon projet', subtitle='generated with idldoc 3.3', format_style='rst', overview='path_vers_mon_fichier_overview'
Remarque: format_style peut prendre les 3 valeurs "rst", "idl" ou "idldoc"
; envoi vers fichier postscript set_plot, 'ps' ; éventuellement donner un nom device, filename='toto.ps' plot, findgen(2) ; retour à l'affichage sur écran device, /close set_plot, 'x'
http://blog.pascal-martin.fr/post/php-5.3-1-closures-et-lambdas
$f1= function () { echo "<p>Hello, World!</p>"; }; $f2= function ($param) { echo "<p>Hello, $param!</p>"; };
call :
$f1();
$f2('there');
call_user_func($f1);
call_user_func($f2, 'You');
call_user_func_array($f1, array());
call_user_func_array($f2, array('You'));
Exemple d'utilisation avec array_map :
$data = array('iron maiden', 'judas priest', 'rammstein'); $output = array_map(function ($item) { return ucwords($item); }, $data); var_dump($output);
Résultat :
array 0 => string 'Iron Maiden' (length=11) 1 => string 'Judas Priest' (length=12) 2 => string 'Rammstein' (length=9)
Un autre exemple, en utilisant cette fois-ci array_walk, qui attend une fonction de callback travaillant avec un paramètre passé par référence :
$data = array('iron maiden', 'judas priest', 'rammstein'); array_walk($data, function (& $item) { $item = ucwords($item); }); var_dump($data);
Le résultat obtenu sera exactement le même que juste au-dessus, à savoir :
array 0 => string 'Iron Maiden' (length=11) 1 => string 'Judas Priest' (length=12) 2 => string 'Rammstein' (length=9)
Utilisé pour les fonctions anonymes, le mot-clef "use" permet d’importer (en lecture seule) des variables externes, issues de l’espace de noms « global », au sein de la fonction lambda.
$var = 'World'; $f2 = function () use ($var) { echo "<p>Hello, $var!</p>"; }; $f2(); // Hello, World!
En quelque sorte, "use" fait penser à l’instruction "global", que nous rencontrions parfois auparavant… Mais global ne répond pas aux besoins des closures
Import de variable par référence :
$var = 0; $func2 = function () use (& $var) { echo "<p>Début 2 : $var</p>"; $var = 2; echo "<p>Fin 2 : $var</p>"; }; et le résultat : echo "<p>Avant 2 : $var</p>"; // Avant 2 : 0 $func2(); // Début 2 : 0 // Fin 2 : 2 echo "<p>Après 2 : $var</p>"; // Après 2 : 2
Mais, qu'est-ce qu'une fonction anonyme pour php ?
$func = function ($param) { echo "<p>Hello, $param!</p>"; }; var_dump($func); Le résultat obtenu est le suivant : object(Closure)[1]
Pour PHP, une fonction anonyme — une lambda — est un objet : une instance de classe Closure…
http://blog.pascal-martin.fr/post/php-5.3-2-closures-et-lambdas
Une closure est une fonction qui est évaluée dans un environnement contenant une ou plusieurs variables liées, auxquelles elle peut accéder au moment de son exécution.
Dans certains langages — dont Javascript, et PHP >= 5.3 — une closure peut exister lorsqu’une fonction est définie au sein d’une autre, et que la fonction interne fait référence à des variables de la fonction externe. A l’exécution, une closure est formée : elle est constituée du code de la fonction interne et des références aux variables externes utilisées par celle-ci.
En PHP, une closure se construit de la manière suivante :
Ex :
$func = function ($arg) { $compteur = $arg; // Copie privée, en lecture seule return function () use ($compteur) { return ++$compteur; }; }; $a1 = $func(10); $a2 = $func(50); Nous venons ici de créer deux fonctions anonymes echo 'a1 : ' . $a1() . "\n"; // 11 echo 'a2 : ' . $a2() . "\n"; // 51 echo 'a1 : ' . $a1() . "\n"; // 11 echo 'a2 : ' . $a2() . "\n"; // 51 echo 'a1 : ' . $a1() . "\n"; // 11 echo 'a2 : ' . $a2() . "\n"; // 51
$func = function ($arg) { $compteur = $arg; // Copie privée, en lecture / écriture return function () use (& $compteur) { return ++$compteur; }; }; echo 'a1 : ' . $a1() . "\n"; // 11 echo 'a2 : ' . $a2() . "\n"; // 51 echo 'a1 : ' . $a1() . "\n"; // 12 echo 'a2 : ' . $a2() . "\n"; // 52 echo 'a1 : ' . $a1() . "\n"; // 13 echo 'a2 : ' . $a2() . "\n"; // 53
Le mécanisme de closure permet donc de créer des variables au sein de la fonction "externe", qui conserveront leur valeur aussi longtemps que l’on aura conservé un pointeur sur la fonction "interne". Ces variables seront accessibles par la fonction interne, éventuellement en écriture si nous avons utilisé & lors de leur import, tout en n’étant pas visibles du reste de notre script.
PHP 5.3 ajoute la possibilité d’utiliser la syntaxe d’un appel de fonction sur un objet, en lui appliquant l’opérateur ().
Pour cela, une nouvelle méthode magique a été ajoutée : __invoke :
lors d’un appel de fonction sur une instance de classe comportant une méthode __invoke, c’est cette méthode qui sera appelée.
Voici une classe d’exemple :
class MyString { public $str; public function __construct($a) { $this->str = $a; } // Appelée quand on appelle dynamiquement un // objet instance de cette classe public function __invoke($a) { var_dump(__METHOD__); $this->str = $a; } }
Endroit où sont stockés les fichiers (temporaires) de session : session.save_path (php.ini)
Dans xampp : session.save_path = "D:\xampp\tmp"
Sur linux : session.save_path = "/var/lib/php/session" (/etc/php.ini)
La façon la plus sécurisée est d'utiliser les cookies
1) Le client (navigateur) demande un identifiant de session (jeton)
2) Le serveur crée l'identifiant et le retourne au client
3) Le client stocke sur son disque dur cet identifiant sous la forme d'un cookie qu'il enverra désormais à chaque requête
Nom du jeton par défaut = PHPSESSID (cf php.ini session.name et fonction session_name())
Sur le serveur, ce jeton aura le nom "sess_" suivi de sa valeur
Valeur du jeton = string générée aléatoirement par php (fonction session_id() retourne cette valeur et permet éventuellement de la fixer, mais déconseilllé)
Paramètres php.ini à positionner (on peut utiliser session_set_cookie_params() pour cela, il y a aussi ini_get() et ini_set()) :
session.use_cookies = 1 session.use_only_cookies = 1 session.use_trans_sid = 0 (si cookies pas acceptés, ne pas pour autant transmettre l'id de session dans l'url) session.cookie_lifetime = 0 (jusqu'au moment de quitter le navigateur) session.auto_start = 0 session.save_handler = files session.save_path = ...
La fonction session_start() crée ou restaure une session (à mettre en première ligne du bootstrap)
session_regenerate_id() regénère l'id de session afin d'éviter une fixation de la session
appeler session_destroy() à la déconnexion du user
http://r-benyacoub.developpez.com/tutoriels/php/zend-framework/zend-auth/
http://framework.zend.com/manual/1.11/en/zend.auth.adapter.dbtable.html
best :
http://framework.zend.com/manual/en/learning.quickstart.create-project.html
Le contrôleur de Zend Framework réserve une action "index" comme action par défaut. C'est-à-dire que pour l'URI "http://localhost/tutoriel-zf/actualités/", l'action "index" est exécutée. Le framework réserve également un nom de contrôleur si aucun n'est fourni dans l'URI : aucune surprise qu'il soit également appelé "index". Ainsi, l'URI "http://localhost/tutoriel-zf/" appelle le contrôleur "index" avec l'action "index".
1) install
Download zf
Copier dans D:\ProgFilesNoInstall\zf
Ajouter D:\ProgFilesNoInstall\zf\bin dans PATH windows
2) Créer un projet
Dans Eclipse, créer un projet PHP nommé "zfquickstart"
Ouvrir une console DOS
Aller dans xampp/htdocs
zf create project zfquickstart
crée 3 dossiers :
- application/ qui contient Bootstrap.php et configs/application.ini
- public/
- library/
public/ contient 2 fichiers importants :
.htaccess :
RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L]
index.php : qui lance $application->bootstrap() et ->run()
3) The Bootstrap
Your Bootstrap class defines what resources and components to initialize. By default, Zend Framework's Front Controller is initialized, and it uses the application/controllers/ as the default directory in which to look for action controllers
// application/Bootstrap.php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { }
4) Configuration
While Zend Framework is itself configurationless, you often need to configure your application. The default configuration is placed in application/configs/application.ini, and contains some basic directives for setting your PHP environment (for instance, turning error reporting on and off), indicating the path to your bootstrap class (as well as its class name), and the path to your action controllers.
; application/configs/application.ini [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "Application" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.params.displayExceptions = 0 [staging : production] [testing : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1
First, when using INI-style configuration, you can reference constants directly and expand them; APPLICATION_PATH is actually a constant.
Additionally note that there are several sections defined: production, staging, testing, and development. The latter three inherit settings from the "production" environment. This is a useful way to organize configuration to ensure that appropriate settings are available in each stage of application development.
5) Action Controllers
Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.
An action controller should have one or more methods ending in "Action"; these methods may then be requested via the web. By default, Zend Framework URLs follow the schema /controller/action, where "controller" maps to the action controller name (minus the "Controller" suffix) and "action" maps to an action method (minus the "Action" suffix).
Typically, you always need an IndexController, which is a fallback controller and which also serves the home page of the site, and an ErrorController, which is used to indicate things such as HTTP 404 errors (controller or action not found) and HTTP 500 errors (application errors).
// application/controllers/IndexController.php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { // action body } } And the default ErrorController is as follows: // application/controllers/ErrorController.php class ErrorController extends Zend_Controller_Action { public function errorAction() { $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'Page not found'; break; default: // application error $this->getResponse()->setHttpResponseCode(500); $this->view->message = 'Application error'; break; } $this->view->exception = $errors->exception; $this->view->request = $errors->request; } }
You'll note that the IndexController contains no real code, and the ErrorController makes reference to a "view" property. That leads nicely into our next subject.
6) Views
Views in Zend Framework are written in plain old PHP. View scripts are placed in application/views/scripts/, where they are further categorized using the controller names. In our case, we have an IndexController and an ErrorController, and thus we have corresponding index/ and error/ subdirectories within our view scripts directory. Within these subdirectories, you will then find and create view scripts that correspond to each controller action exposed; in the default case, we thus have the view scripts index/index.phtml and error/error.phtml.
View scripts may contain any markup you want, and use the closing tag to insert PHP directives.
<!-- application/views/scripts/index/index.phtml --> <style> a:link, a:visited { color: #0398CA; } span#zf-name { color: #91BE3F; } div#welcome { color: #FFFFFF; background-image: url(http://framework.zend.com/images/bkg_header.jpg); width: 600px; height: 400px; border: 2px solid #444444; overflow: hidden; text-align: center; } div#more-information { background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif); height: 100%; } </style> <div id="welcome"> <h1>Welcome to the <span id="zf-name">Zend Framework!</span><h1 /> <h3>This is your project's main page<h3 /> <div id="more-information"> <p> <img src="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png" /> </p> <p> Helpful Links: <br /> <a href="http://framework.zend.com/">Zend Framework Website</a> | <a href="http://framework.zend.com/manual/en/">Zend Framework Manual</a> </p> </div> </div> <="" span=""> The error/error.phtml view script is slightly more interesting as it uses some PHP conditionals: <!-- application/views/scripts/error/error.phtml --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"; "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Zend Framework Default Application</title> </head> <body> <h1>An error occurred</h1> <h2><?php echo $this->message ?></h2> <?php if ('development' == $this->env): ?> <h3>Exception information:</h3> <p> <b>Message:</b> <?php echo $this->exception->getMessage() ?> </p> <h3>Stack trace:</h3> <pre><?php echo $this->exception->getTraceAsString() ?> </pre> <h3>Request Parameters:</h3> <pre><?php echo var_export($this->request->getParams(), 1) ?> </pre> <?php endif ?> </body> </html>
7) Create a virtual host
Dans "D:\xampp\apache\conf\extra\myvhosts", créer un fichier "zfquickstart.conf"
Listen 8087 <VirtualHost *:8087> ServerName zfquickstart.local ServerAlias zfquickstart.local zfquickstart #ServerName .local DocumentRoot "D:/xampp/htdocs/zfquickstart/public" # This should be omitted in the production environment SetEnv APPLICATION_ENV "development" <Directory "D:/xampp/htdocs/zfquickstart/public"> DirectoryIndex index.php #Options Indexes MultiViews FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>
There are several things to note. First, note that the DocumentRoot setting specifies the public subdirectory of our project; this means that only files under that directory can ever be served directly by the server. Second, note the AllowOverride, Order, and Allow directives; these are to allow us to use htacess files within our project. During development, this is a good practice, as it prevents the need to constantly restart the web server as you make changes to your site directives; however, in production, you should likely push the content of your htaccess file into your server configuration and disable this. Third, note the SetEnv directive. What we are doing here is setting an environment variable for your virtual host; this variable will be picked up in the index.php and used to set the APPLICATION_ENV constant for our Zend Framework application. In production, you can omit this directive (in which case it will default to the value "production") or set it explicitly to "production".
Avec un
Finally, you will need to add an entry in your hosts file corresponding to the value you place in your ServerName directive. On *nix-like systems, this is usually /etc/hosts; on Windows, you'll typically find it in C:\WINDOWS\system32\drivers\etc. Regardless of the system, the entry will look like the following:
127.0.0.1 zfquickstart.local
Start your webserver (or restart it), and you should be ready to go.
NB: il faut ajouter le chemin vers ZF ("D:\ProgFilesNoInstall\zf\library") :
// Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( //EP added : "D:\ProgFilesNoInstall\zf\library", realpath(APPLICATION_PATH . '/../library'), get_include_path(), )));
8) Create A Layout
http://framework.zend.com/manual/en/learning.quickstart.create-layout.html
To get started using Zend_Layout, first we need to inform our bootstrap to use the Layout resource. This can be done using the zf enable layout command:
% zf enable layout Layouts have been enabled, and a default layout created at application/layouts/scripts/layout.phtml A layout entry has been added to the application config file.
As noted by the command, application/configs/application.ini is updated, and now contains the following within the production section:
; application/configs/application.ini ; Add to [production] section: resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
We also want to ensure we have an XHTML DocType declaration for our application. To enable this, we need to add a resource to our bootstrap.
The simplest way to add a bootstrap resource is to simply create a protected method beginning with the phrase _init. In this case, we want to initialize the doctype, so we'll create an _initDoctype() method within our bootstrap class.
Within that method, we need to hint to the view to use the appropriate doctype. But where will the view object come from? The easy solution is to initialize the View resource; once we have, we can pull the view object from the bootstrap and use it.
To initialize the view resource, add the following line to your application/configs/application.ini file, in the section marked production:
resources.view[] =
This tells us to initialize the view with no options (the '[]' indicates that the "view" key is an array, and we pass nothing to it).
Now that we have a view, let's flesh out our _initDoctype() method. In it, we will first ensure the View resource has run, fetch the view object, and then configure it:
// application/Bootstrap.php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { protected function _initDoctype() { $this->bootstrap('view'); $view = $this->getResource('view'); $view->doctype('XHTML1_STRICT'); } }
Now that we've initialized Zend_Layout and set the Doctype, let's create our site-wide layout:
<!-- application/layouts/scripts/layout.phtml --> <?php echo $this->doctype() ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Zend Framework Quickstart Application</title> <?php echo $this->headLink()->appendStylesheet('/css/global.css') ?> </head> <body> <div id="header" style="background-color: #EEEEEE; height: 30px;"> <div id="header-logo" style="float: left"> <b>ZF Quickstart Application</b> </div> <div id="header-navigation" style="float: right"> <a href="<?php echo $this->url( array('controller'=>'guestbook'), 'default', true) ?>">Guestbook</a> </div> </div> <?php echo $this->layout()->content ?> </body> </html>
We grab our application content using the layout() view helper, and accessing the "content" key. You may render to other response segments if you wish to, but in most cases, this is all that's necessary.
Note also the use of the headLink() placeholder. This is an easy way to generate the HTML for elements, as well as to keep track of them throughout your application. If you need to add additional CSS sheets to support a single action, you can do so, and be assured it will be present in the final rendered page.
9) Create a Model and Database Table
http://framework.zend.com/manual/en/learning.quickstart.create-model.html
Your application bootstrap will by default use the module prefix "Application". As such, our models, forms, and table classes will all begin with the class prefix "Application_".
zf configure db-adapter 'adapter=PDO_SQLITE&dbname=APPLICATION_PATH "/../data/db/guestbook.db"' production
php scripts/load.sqlite.php --withdata
zf create db-table Guestbook guestbook
zf create model GuestbookMapper
zf create model Guestbook
zf create controller Guestbook
This will create a new controller, GuestbookController, in application/controllers/GuestbookController.php, with a single action method, indexAction(). It will also create a view script directory for the controller, application/views/scripts/guestbook/, with a view script for the index action.
We'll use the "index" action as a landing page to view all guestbook entries.
Now, let's flesh out the basic application logic. On a hit to indexAction(), we'll display all guestbook entries. This would look like the following:
// application/controllers/GuestbookController.php class GuestbookController extends Zend_Controller_Action { public function indexAction() { $guestbook = new Application_Model_GuestbookMapper(); $this->view->entries = $guestbook->fetchAll(); } } And, of course, we need a view script to go along with that. Edit application/views/scripts/guestbook/index.phtml to read as follows: <!-- application/views/scripts/guestbook/index.phtml --> <p><a href="<?php echo $this->url( array( 'controller' => 'guestbook', 'action' => 'sign' ), 'default', true) ?>">Sign Our Guestbook</a></p> Guestbook Entries: <br /> <dl> <?php foreach ($this->entries as $entry): ?> <dt><?php echo $this->escape($entry->email) ?></dt> <dd><?php echo $this->escape($entry->comment) ?></dd> <?php endforeach ?> </dl>
Now browse to "http://localhost/guestbook"
10) Create A Form
http://framework.zend.com/manual/en/learning.quickstart.create-form.html
% zf create form Guestbook
Next, we will add a signAction() to our GuestbookController which will process the form upon submission. To create the action and related view script, execute the following:
% zf create action sign Guestbook
Now browse to "http://localhost/guestbook/sign".
Depuis v5.3 : http://fr.php.net/manual/fr/migration53.ini.php
Le fichier standard php.ini a été réorganisé, et renommé :
On les trouve dans /usr/share/doc/php-common-5.3.3
Voici la différence entre les 2 :
[root@planetoweb etc]# diff /usr/share/doc/php-common-5.3.3/php.ini-development /usr/share/doc/php-common-5.3.3/php.ini-production 514c514 < error_reporting = E_ALL | E_STRICT --- > error_reporting = E_ALL & ~E_DEPRECATED 531c531 < display_errors = On --- > display_errors = Off 542c542 < display_startup_errors = On --- > display_startup_errors = Off 586c586 < track_errors = On --- > track_errors = Off 604c604 < html_errors = On --- > html_errors = Off 1248a1249,1256 > ; Allow accessing, from PHP's perspective, local files with LOAD DATA statements > ; http://php.net/mysqli.allow_local_infile > ;mysqli.allow_local_infile = On > > ; Allow or prevent persistent links. > ; http://php.net/mysqli.allow-persistent > mysqli.allow_persistent = On > 1297c1305 < mysqlnd.collect_memory_statistics = On --- > mysqlnd.collect_memory_statistics = Off 1566c1574 < session.bug_compat_42 = On --- > session.bug_compat_42 = Off 1575c1583 < session.bug_compat_warn = On --- > session.bug_compat_warn = Off 1593d1600 < session.entropy_file =
La syntaxe Heredoc se comporte exactement comme une chaîne à guillemets doubles, sans les guillemets doubles. Cela signifie que vous n'avez pas à échapper les guillemets (simples ou doubles) dans cette syntaxe. Les variables sont remplacées par leur valeur et le même soin doit leur être apporté que dans les chaînes à guillemets doubles. Exemple de chaîne HereDoc
<?php $str = <<<EOD Exemple de chaîne s'étalant sur plusieurs lignes avec la syntaxe heredoc EOD; /* Exemple plus complexe, avec des variables. */ class foo { var $foo; var $bar; function foo() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MonNom'; echo <<<EOT Mon nom est "$name". J'affiche des $foo->foo. Maintenant, j'affiche un {$foo->bar[1]}. Ceci se traduit par un 'A' majuscule : \x41 EOT; ?> <?php class foo { public $bar = <<<EOT bar EOT; } ?>
<?php $t = array (2,3,6,7,9,2,43,5,2,54,65,34,23,54,23,654,43); print_r ($t); uasort ($t, function ($x,$y) { return $x > $y;}); print_r ($t); printf ("somme = %d\n", array_reduce ($t, function ($x,$y) { return $x+$y;})); ?>
- Supprimer une partie de la chaîne : str_replace()
- sous-chaîne : substr()
- tester la présence d'une sous-chaine dans la chaine (et récupérer sa position) : strpos()
- parser une chaine de paramètres html, et les placer dans un tableau : parse_str($chaine, $args)
- remplacer une partie de la chaine : $bodytag = str_replace("%body%", "black", "");
- merge : $GET = array_merge($GET,$args)
- dispatcher contenu array dans n strings (explode) : $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
- regrouper contenu array dans 1 string (implode) : $array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // lastname,email,phone
print FUNCTION." in ".__FILE__." at ".__LINE__."\n";
Ou bien (php5) :
$modelReflector = new ReflectionClass (CLASS);
$method = $modelReflector->getMethod(METHOD);
- echo "cette variable n'existe pas mais ca ne génère aucune erreur !!!!!!!" . $nimportekoi;
- echo "cette propriété (attribut, variable) n'existe pas mais ca ne génère aucune erreur !!!!!!!" . $this->nimportekoi;
http://forum.webrankinfo.com/petite-astuce-pour-afficher-simplement-code-html-t32812.html
La commande top classe tous les processus par leur consommation de la CPU et de la mémoire
Elle affiche le "top 20" sous forme d'une table
top -n 1 -b > top.txt affiche tous les processus
top -n 1 -b -p
http://www.simplehelp.net/2009/01/19/monitor-your-linux-machine-with-netstat/
Voir les connexions au port 8080 sur mon pc :
$> netstat -ant|grep 8080 tcp4 0 0 195.83.102.52.54533 195.83.102.176.8080 ESTABLISHED tcp6 0 0 ::1.8080 ::1.53481 ESTABLISHED tcp6 0 0 ::1.53481 ::1.8080 ESTABLISHED tcp6 0 0 ::1.8080 ::1.50287 ESTABLISHED tcp6 0 0 ::1.50287 ::1.8080 ESTABLISHED tcp46 0 0 *.8080 *.* LISTEN
Je vois ainsi que ma machine est connectée à 195.83.102.176 via le port 8080 en TCP
Pour savoir qui c'est, j'utilise la commande "host" ou "nslookup" :
$> host 195.83.102.176
Idem pour mysql :
$> netstat -ant | grep 3306
This tells me how many connections of different types of state I have on my machine. I can run a similar command to see a complete picture of the state of all the connections made to my web server:
$> netstat -ant | grep 80 | awk ‘{print $6}’ | sort | uniq -c | sort -n 1 FIN_WAIT1 4 LISTEN 6 FIN_WAIT2 17 CLOSE_WAIT 94 ESTABLISHED 534 TIME_WAIT
cat /proc/meminfo
http://www.cyberciti.biz/faq/linux-display-cpu-information-number-of-cpus-and-their-speed/
cat /proc/cpuinfo
Plus précisément :
Exact number of available cores, virtual or not (8 pour TEAM_SERVER, soit 2 proc x 4 cores) : grep -c processor /proc/cpuinfo
Nb de processeurs "physiques" (2 pour TEAM_SERVER) : grep core\ id /proc/cpuinfo | grep -c \ 0$
The following (clumsy) group of commands will return the number of physical CPUs regardless of if there is only a single core per CPU (2 pour planetoweb et surfasafe) :
grep core\ id /proc/cpuinfo | grep -c \ 0$ | grep ^0$ >> /dev/null && grep -c processor /proc/cpuinfo || grep core\ id /proc/cpuinfo | grep -c \ 0$
Processeur(s) virtualisable(s) ? (cpuinfo doit contenir le flag vmx pour un processeur intel, et svm pour AMD) : egrep '(vmx|svm)' /proc/cpuinfo
Information détaillée : dmidecode
dmidecode --type 4 | grep -c Socket
CPU utilization
TOP : Informations sur la charge CPU et la consommation mémoire provoquée par les processus
http://www.loligrub.be/contrib/tlepoint/BASE/node104.html
http://www.cyberciti.biz/tips/how-do-i-find-out-linux-cpu-utilization.html
La commande top classe tous les processus par leur consommation de la CPU et de la mémoire.
Elle affiche le "top 20" sous forme d'une table
top -n 1 -b > top.txt affiche tous les processus
top -n 1 -b -p
O N pour trier par occupation mémoire
O K pour trier par charge CPU (par défaut)
1 pour montrer/cacher chaque processeur séparément
mpstat (fait partie du package sysstat)
mpstat -P ALL
You can display today’s CPU activity, with sar
sar
For example display comparison of CPU utilization; 2 seconds apart; 5 times, use:
# sar -u 2 5
(for each 2 seconds. 5 lines are displayed)
To get multiple samples and multiple reports, set an output file for the sar command. Run the sar command as a background process using.
# sar -o output.file 12 8 >/dev/null 2>&1 &
Better use nohup command so that you can logout and check back report later on:
# nohup sar -o output.file 12 8 >/dev/null 2>&1 &
puis pour lire : sar -f output.file
%user = % temps cpu utilisé par les applications
%system = % temps cpu utilisé par le kernel
%iowait = % temps cpu utilisé à attendre une requête I/O
displays the top 10 CPU users :
ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
ps command displays every process (-e) with a user-defined format (-o pcpu). First field is pcpu (cpu utilization). It is sorted in reverse order to display top 10 CPU eating process.
iostat :
It can be use to find out your system's average CPU utilization since the last reboot.
$ iostat
This gives you three outputs every 5 seconds (as previous command gives information since the last reboot):
$ iostat -xtc 5 3
gnome-system-monitor : allows you to view and control the processes
Voir aussi http://www.cyberciti.biz/tips/top-linux-monitoring-tools.html
# ssh user@server bash -c "ls -l"
Mode raccourci:
# ssh user@server "ls -l"
# ssh surfasafe "ls -l"
# ssh root@surfasafe "ls -l"
# ssh root@surfasafe bash -c "ls -l"
# ssh pallier@sauvcesr2 bash -c "ls -l"
This account is restricted by rssh.
Allowed commands: scp sftp rsync
If you believe this is in error, please contact your system administrator.
Par exemple, depuis chez moi, je veux me connecter à TEAM_SERVER
Il me faut donc passer par GATEWAY (la passerelle du labo)
1) le plus simple, méthode manuelle (depuis mon pc)
ssh GATEWAY (entrer le mot de passe utilisé pour le mail)
puis
ssh TEAM_SERVER.LAB_DOMAIN (entrer votre mot de passe TEAM_SERVER)
(NB : "ssh -X GATEWAY", puis "ssh -X TEAM_SERVER" si on veut l'affichage graphique)
Il faut taper 2 fois "exit" pour revenir à mon pc.
2) Pour accélérer la connexion : ETAPE 1, générer des clés ssh
DEPUIS MON PC, je génère une paire de clés privée et publique :
ssh-keygen -t dsa
Puis, je distribue ensuite la clé publique à la fois sur GATEWAY ET sur TEAM_SERVER :
ssh-copy-id -i /home/USERNAME/.ssh/id_dsa.pub GATEWAY
ssh-copy-id -i /home/USERNAME/.ssh/id_dsa.pub TEAM_SERVER.LAB_DOMAIN
Tester maintenant à nouveau la double connexion (GATEWAY, puis TEAM_SERVER) :
ssh GATEWAY (sans mot de passe)
puis
ssh TEAM_SERVER.LAB_DOMAIN (avec mot de passe)
Malheureusement, il faut encore entrer un mot de passe pour se connecter à TEAM_SERVER, bouh...
(je tape 2 fois "exit" pour revenir à mon pc)
3) Pour accélérer la connexion : ETAPE 2, automatiser le "rebond" par GATEWAY
On va maintenant rendre transparent le passage via GATEWAY. Il suffit pour cela de créer un fichier de config :
DEPUIS MON PC, j'édite le fichier /home/USERNAME/.ssh/config, et j'y mets le contenu suivant :
Host hyp TEAM_SERVER TEAM_SERVER.LAB_DOMAIN Hostname TEAM_SERVER.LAB_DOMAIN ProxyCommand ssh GATEWAY nc %h %p 2> /dev/null
(Pour plus de détails : http://franek.chicour.net/post/2009/10/16/SSH-%3A-simplifier-les-connexions-avec-rebond)
VOILA C FINI, OUF !
Désormais, depuis votre pc, il suffit de faire un bête ssh :
ssh hyp (avec l'option -X pour l'affichage graphique)
(ou "ssh TEAM_SERVER" ou "ssh TEAM_SERVER.LAB_DOMAIN")
On n'a plus besoin de rentrer aucun mot de passe (ni de GATEWAY, ni de TEAM_SERVER), c'est direct !
(il suffit de taper une seule fois "exit" pour revenir à mon pc)
Pleins d'exemples ici : http://sed.sourceforge.net/sed1line_fr.html
cat monfichier.txt | sed -e 3,6"s/tutu/toto/" >| monfichiertemp.txt
/titi/,/toto/s/tutu/toto/
ou encore :
sed -e "/$debut/,/$fin/"'s#HostId="t3://.*\n#HostId="t3://'"$WLS_ADM_HOST:$PORT\"/" < "$file1" > "$file2"
Afficher uniquement les lignes de commentaire:
egrep '^#' fichier
Ne pas afficher les lignes de commentaire:
egrep -v '^#' fichier
N'afficher que les lignes utiles (tout sauf commentaires et lignes vides) :
egrep -v '^(#|$)' fichier
Sauvegarder (de façon incrémentielle) des répertoires du poste A vers le poste B :
1) Depuis A...
A#> rsync -avz /rep/rep1 /rep/rep2 B:/rep/
option -v = verbose
attention aux slashes '/' :
/rep/rep1 écrit un répertoire rep1 sur B
/rep/rep1/ écrit directement le contenu du répertoire rep1 sur B
2) ... ou Depuis B
rsync -avz A:/rep/rep1 A:/rep/rep2 ./rep
Chercher le fichier "foo" sur tout le disque :
find / -name foo
(si on n'est pas root, on voit plein de messages d'erreur, donc pour éviter ça :
find / -name foo 2>/dev/null
Supprimer tous les répertoires CVS/ dans toute une arborescence (à partir du répertoire courant) :
find . -name "CVS" -exec \rm -r {} \; > /dev/null 2>&1
Combien de fichiers dans un répertoire (y-compris les sous-rep) :
find rep | wc -l
Affecter des droits spécifiques à certains éléments d'un répertoire (tout le contenu, y-compris sous-dossiers) :
dossiers:
find /home/jsmith/awstats/ -type d | xargs chmod 0755
fichiers:
find /home/jsmith/awstats/ -type f | xargs chmod 0644
fichiers perl:
find /home/jsmith/awstats/ -type f -name *.pl | xargs chmod 0755
http://www.feep.net/sendmail/tutorial/intro/forward.html
Par exemple, je veux forwarder mes mails de pallier@planetoweb.cesr.fr vers ma boite LABO ou encore ma boite perso :
cd ~
créer un fichier ".forward" contenant mon adresse LABO ou perso
S'il s'agit de forwarder les mails adressés à root@planetoweb.cesr.fr, on peut utiliser la même solution, mais on peut aussi ajouter cette ligne tout à la fin du fichier /etc/aliases
root: etienne.pallier@cesr.fr
find . -name filename_searched
grep "mot" *.pro
grep -i "mot" .
L'option "-i" permet de ne pas tenir compte de la casse
grep -r -i "mot" .
Depuis répertoire courant, supprimer tous les dossiers "CVS" (récursivement) :
find . -name CVS -exec rm -rf {} \;
Exemple : quand on tape "l" ça fera "ls -l"
alias l="ls -l"
Cette ligne doit être placée dans votre ~/.bashrc
Pour les configurations perso, les placer dans son ~/.bash_profile (ce script appelle ~/.bashrc qui doit contenir les alias et fonctions)
Mettre les configurations générales dans /etc/profile.d/profile_etienne.sh (elles seront ainsi valables pour TOUS les users du serveur)
Ce fichier est automatiquement lu par /etc/profile au démarrage d'une session
Pour installer l'imprimante "sprinter", voir SprinterPrinter
Pour faire de cette imprimante l'imprimante par défaut, ajouter cette ligne dans votre ~/.bash_profile :
export PRINTER=sprinter (mettre le nom de votre imprimante à la place de "sprinter")
Pour imprimer du texte, on peut utiliser les utilitaires "a2ps" ou "enscript"
display
Note : display permet aussi de convertir une image d'un format vers un autre (enregistrer sous...)
Voir aussi "xv" et "gthumb"
PS to PDF : ps2pdf
Voir aussi l'utilitaire convert
En mode interactif, On peut aussi utiliser display (voir ci-dessus)
Taper dans un terminal la commande suivante
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=fichier_reduit.pdf fichier_a_reduire.pdf
La commande peut se faire avec l'option suivante (non obligatoire):
-dPDFSETTINGS=/screen (qualité faible - compression forte) -dPDFSETTINGS=/ebook (qualité moyenne - compression moyenne) -dPDFSETTINGS=/printer (qualité élevée - compression faible)
1) Créer le user
dans /home, avec tel group id (gid) : useradd <username> -g 500 dans /home/STAGIAIRES : useradd <username> -g 500 --base-dir /home/STAGIAIRES avec tel user id (uid) : -u 1000
2) Lui créer un password
passwd username
3) Créer éventuellement un lien dans son home vers les données de projet
4) L'ajouter dans son ou ses groupes projets d'affectation
(pour avoir accès au sous répertoires correspondants dans "data", par exemple odyssey, msl, etc...)
vim /etc/group
(l'ajouter aussi dans son groupe privé)
Vérifier avec : id username
chgrp -R surfaces /home/username/
chmod -R 750 /home/username/
5) L'ajouter au service samba (si nécessaire)
pdbedit -a username
Vérifier qu'il est bien inscrit :
pdbedit -L
6) L'ajouter dans la liste des arrivants
http://planetowiki.irap.omp.eu/do/view/Team/WebHome#Les_Nouveaux_Arrivants
7) L'enregistrer sur le wiki (il ne peut pas le faire lui-meme)
http://planetowiki.irap.omp.eu/do/view/TWiki/TWikiRegistration
/etc/init.d/iptables status
ls /etc/sysconfig/iptables*
cd /etc/sysconfig/
1) modifs à faire sur iptables.clean
2) cp iptables.clean iptables
3) /etc/init.d/iptables restart
4) /etc/init.d/iptables save
5) /etc/init.d/iptables status (vérifier que les nouvelles règles apparaissent bien)
Voir l'exemple du projet Europlanet : http://planetowiki.irap.omp.eu/do/view/Team/EuroplanetProject#Serveur_SVN
Voir l'exemple de la configuration pour chemcam : /etc/httpd/conf.d/vhosts/chemcam.conf (planetoweb)
Besoins à considérer avant de mettre en place une solution svn :
- accès via apache (et non pas seulement en svnserve) pour assurer un accès depuis l'extérieur et qui passe les firewall
- AUTH : accès authentifié (AuthType, AuthUserFile et Require valid-user)
Exceptionnellement, sur un projet avec différents groupes (mais uniquement si nécessaire car ralentit les accès svn et alourdit la gestion) :
- ACL : contrôle d'accès basé sur les chemins : (grâce au module authz_svn_module et à la directive AuthzSVNAccessFile), pour pouvoir réserver certains répertoires à certains groupes...
Exemple de config (chemcam) authentifiée mais SANS ACL :
DAV svn ErrorDocument 404 default # Only 1 repository : SVNPath /home/projects/chemcam/svn # Many repositories : # any "/svn/foo" URL will map to a repository /home/svn/foo #SVNParentPath /home/svn #SVNListParentPath on # Desactiver completement les controles sur les chemins (par defaut = on) SVNPathAuthz off # For any operations other than these (GET, PROFIND...), require an authenticated user # Require valid-user # # AUTH AuthType Basic AuthName "CHEMCAM Subversion repository" # password file : AuthUserFile /chemin/vers/fichier/des/mots/de/passe # For any operations other than these, require an authenticated user (this would allow anybody to READ without authentication) # Custom log file and format : LogFormat "%t %u %h %{SVN-ACTION}e" svn CustomLog logs/journal-svn.log svn env=SVN-ACTION
Exemple de config (chemcam) authentifiée et AVEC ACL :
DAV svn ErrorDocument 404 default # Only 1 repository : SVNPath /home/projects/chemcam/svn # Many repositories : # any "/svn/foo" URL will map to a repository /home/svn/foo #SVNParentPath /home/svn #SVNListParentPath on # Desactiver completement les controles sur les chemins (par defaut = on) SVNPathAuthz on # ACL # politique de controle d'acces (uses apache module mod_authz_svn) AuthzSVNAccessFile /chemin/vers/fichier/police_acces_svn # For any operations other than these (GET, PROFIND...), require an authenticated user # Require valid-user # # AUTH AuthType Basic AuthName "CHEMCAM Subversion repository" # password file : AuthUserFile /chemin/vers/fichier/des/mots/de/passe # For any operations other than these, require an authenticated user (this would allow anybody to READ without authentication) # Custom log file and format : LogFormat "%t %u %h %{SVN-ACTION}e" svn CustomLog logs/journal-svn.log svn env=SVN-ACTION
Format du fichier de police d'accès aux répertoires du projet svn (nommé police_acces_svn ci-dessus) :
[groups] # Virtual Machine only group : cc-vm = user1, user20, user7 # Privileged access group : cc-privileged = user3, user2, user6, user8, user30 [/] # cc-privileged group has total access to the project (and no one else) @cc-privileged = rw # access given to ALL users !!! #* = rw [/trunk/vm] # cc-vm group has read only access to the /vm dir (and no other dir) @cc-vm = r # cc-vm group has no access at all to the /vm dir #@cc-vm =
http://www.linux-mag.com/id/7454
LVM can be used to effectively manage storage to make expansion, snapshots, and other aspects of storage fairly easy.
LVM allows you to abstract various pieces of physical storage into groups that can be carved into chunks that form the basis of file systems (virtual partitions if you like). It also allows you to combine physical partitions into groups, resize these groups (grow or shrink), and effectively manage these groups.
1) h physical hd découpés chacun en p physical partitions (PP) (pas forcément le même nb de partitions pour chaque hd)
ex : sda découpé en /dev/sda1, /dev/sda2 et sdb découpé en /dev/sdb1, /dev/sdb2, /dev/sdb3
2) mapping identité entre les partitions physiques (PP) et virtuelles (PV) : 1 PV = 1 PP
Make sure the partition type for the physical volumes is correct. The partition type should be “8e”.
# fdisk -l /dev/sdb Disk /dev/sdb: 500.1 GB, 500107862016 bytes 255 heads, 63 sectors/track, 60801 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System /dev/sdb1 1 30400 244187968+ 8e Linux LVM /dev/sdb2 30401 60801 244196032+ 8e Linux LVM
# pvcreate /dev/sdb1 /dev/sdb2 /dev/sdc1 /dev/sdc2 Physical volume "/dev/sdb1" successfully created Physical volume "/dev/sdb2" successfully created Physical volume "/dev/sdc1" successfully created Physical volume "/dev/sdc2" successfully created
# pvdisplay "/dev/sdb1" is a new physical volume of "232.88 GB" --- NEW Physical volume --- PV Name /dev/sdb1 VG Name PV Size 232.88 GB Allocatable NO PE Size (KByte) 0 Total PE 0 Free PE 0 Allocated PE 0 PV UUID j4XKT6-OI2y-cPMK-YpNR-gmgc-es67-ey4CV2 "/dev/sdb2" is a new physical volume of "232.88 GB" --- NEW Physical volume --- ...
Notice that each PV is given a PV UUID
3) Les PV sont regroupés en 1 à n volume group (VG) (a VG can be seen as a "virtual hd")
ex : le VG primary_vg regroupera /dev/sda1, /dev/sda2 , /dev/sdb1, et /dev/sdb3
# vgcreate primary_vg /dev/sdb1 /dev/sdb2 /dev/sdc1 /dev/sdc2 Volume group "primary_vg" successfully created
# vgdisplay --- Volume group --- VG Name primary_vg System ID Format lvm2 Metadata Areas 4 Metadata Sequence No 1 VG Access read/write VG Status resizable MAX LV 0 Cur LV 0 Open LV 0 Max PV 0 Cur PV 4 Act PV 4 VG Size 931.52 GB PE Size 4.00 MB Total PE 238468 Alloc PE / Size 0 / 0 Free PE / Size 238468 / 931.52 GB VG UUID oNH6jk-PBE0-mR0c-aaDi-3Fys-y5SQ-0tVaxX
If you don't happen to remember the name of a VG or you happen upon a new system to administer, then you can use a command called "vgscan" that will tell what VG's are on the system.
# vgscan Reading all physical volumes. This may take a while... Found volume group "primary_vg" using metadata type lvm2
4) Chaque VG est redécoupé en m logical volume (LV) : 1 VG = m LV (a LV can be seen as a "virtual partition")
ex : le VG primary_vg est redécoupé en 2 LV : /dev/primary_vg/home_lv et /dev/primary_vg/data_lv
# lvcreate --name /dev/primary_vg/home_lv --size 450G Logical volume "home_lv" created lvdisplay... lvscan...
5) Sur chaque LG, on monte un système de fichier (FS) :
ex : /home monté en ext3 sur le LV home_lv et /data monté en xfs sur le LV data_lv Comment
# mkfs.ext3 /dev/primary_vg/home_lv ...
Comment faire un snaphot ?
http://www.linux-mag.com/id/7454/2/
For example, if the file system says it has 29G used (29 GB), then you should snapshot a little larger – perhaps 30-32 GB (always good to have a cushion). This cushion isn’t strictly necessary, but a little safety never hurts...
http://smpfr.mesdiscussions.net/smpfr/Software/soft-linux-nuls-sujet_338_1.htm
Vous pouvez faire vos tests sur des fichiers ou des clefs USB pour commencer... Remplacez simplement le "device" par un fichier existant. Ex : /dev/sdX par /home/moi/raid-test/disque-1.img.
Pour créer un fichier quelque part avec la bonne taille : dd if=/dev/zero of=/home/moi/raid-test/disque-1.img count=10000 bs=65535. Pour en savoir plus : man dd.
Apres on fait un : mdadm --create /dev/md0 --level=1 --raid-devices=/home/moi/raid-test/disque-1.img,/home/moi/raid-test/disque-2.img
Et voila un RAID 1 créé avec deux fichiers stockés sur le disque dur.
J'ai testé le Raid0 sur 2DD externes de 2,5" en USB, et j'arrive à 45Mo sec avec mon portable...
Avant de mettre un raid sur une machine en production VERIFIEZ les noms des disques et des partitions !!! Préférez les /dev/disk/by-id, vous ferez moins facilement des erreurs qu'en mettant seulement /dev/sde, surtout si vous ajoutez des disques par la suite...
L'outil magique de management du RAID sous Linux : mdadm
Quelques exemples : (vous noterez que l'on utilise la syntaxe /dev/sdX alors que c'est mal.. mais c'est plus lisible que /dev/disk/by-id/ata-ST3250310AS_6RY7R988-part1)
création d'une pile raid :
mdadm --create /dev/mdX --level=[01456] --raid-devices={/dev/sdYZ, missing, ...}
crée un device /dev/mdX (X étant un chiffre) de niveau (--level) 0 (stripping), 1 (mirroring), 4 (comme le 5 mais la parité est toujours sur le même disque), 5 ou 6 (2 disques de parité) à partir des devices /dev/sdYZ (Y est une lettre indiquant un disque physique , Z un chiffre indicant un numéro de partition).
On peut également mettre missing dans la liste des devices. C'est très utile lorsque l'on passe son système sur un raid 1
Mise en échec d'un disque (pour test par ex.) : mdadm --manage /dev/mdX --failed /dev/sdYZ
"Ejection" d'un disque d'une pile : mdadm --manage /dev/mdX --remove /dev/sdYZ
Ajout d'un disque à une pile : mdadm --manage /dev/mdX --add /dev/sdYZ
Liste des périphériques d'une pile : mdadm --misc --detail /dev/mdX
On peux aussi faire :
cat /proc/mdstat
La première étape consiste à repérer quel device correspond aux partitions que tu veux redimensionner. Pour cela tu peux utiliser la commande :
sudo fdisk -l
# fdisk -l Disque /dev/sda: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sda1 * 1 25 200781 83 Linux /dev/sda2 26 535 4096575 82 Linux swap / Solaris /dev/sda3 536 30401 239898645 83 Linux Disque /dev/sdb: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sdb1 * 1 30401 244196001 fd Linux raid autodetect Disque /dev/sdc: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sdc1 * 1 30401 244196001 fd Linux raid autodetect Disque /dev/sdd: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sdd1 * 1 30401 244196001 fd Linux raid autodetect Disque /dev/md0: 500.1 Go, 500113080320 octets 2 heads, 4 sectors/track, 122097920 cylinders Unités = cylindres de 8 * 512 = 4096 octets Disque /dev/md0 ne contient pas une table de partition valide
Pour avoir un résultat plus parlant (tailles en octets + système de fichiers) tu peux utiliser cfdisk : sudo cfdisk /dev/sda
L'ext3 c'est en fait de l'ext2 mais avec un "journal" et c'est pour ça qu'il est facile de passer d'ext2 à ext3 et réciproquement.
Les outils de redimensionnement s'appliquent à de l'ext2 ce qui nécessitera de passer d'ext3 à ext2, redimensionner, puis repasser en ext3
http://www.webactus.net/coin-du-geek/linux/2704-linux-augmenter-la-taille-dune-partition-ext3/
http://www.oxygenepc.com/forum/cloner-un-disque-dur-t486.html
http://www.oxygenepc.com/forum/cloner-un-disque-dur-t486.html
http://www.linuxquestions.org/linux/answers/Applications_GUI_Multimedia/How_To_Do_Eveything_With_DD
http://www.debianhelp.co.uk/ddcommand.htm
The basic command is structured as follows:
dd if=
Source is the data being read. Target is where the data gets written. If you mess up, and accidentally reverse the source and target, you can wipe out a lot of data.
(http://www.efense.com/helix is a good boot cd : The helix boot environment contains the DoD version of dd called dcfldd. It works the same way, but is has a progress bar)
Using dd you can create backups of an entire harddisk or just a parts of it. This is also usefull to quickly copy installations to similar machines. It will only work on disks that are exactly the same in disk geometry, meaning they have to the same model from the same brand.
Examples:
dd if=/dev/hdx of=/dev/hdy dd if=/dev/hdx of=/path/to/image dd if=/dev/hdx | gzip > /path/to/image.gz
Hdx could be hda, hdb etc. In the second example gzip is used to compress the image if it is really just a backup.
dd if=/path/to/image of=/dev/hdx
gzip -dc /path/to/image.gz | dd of=/dev/hdx
In order to backup only the first few bytes containing the MBR and the partition table you can use dd as well.
dd if=/dev/hdx of=/path/to/image count=1 bs=512
dd if=/path/to/image of=/dev/hdx
Add "count=1 bs=446" to exclude the partition table from being written to disk. You can manually restore the table.
dd if=/dev/sda2 of=/dev/sdb2 bs=4096 conv=notrunc,noerror
sda2, sdb2 are partitions. You want to copy sda2 to sdb2. If sdb2 doesn't exist, dd will start at the beginning of the disk, and create it. Be careful with order of if and of. You can write a blank disk to a good disk if you get confused.
dd if=/dev/hdc of=/home/sam/mycd.iso bs=2048 conv=notrunc
CD sectors are 2048 bytes, so this copies sector for sector. The result will be a hard disk image file of the CD. You can use "chmod a+rwx mycd.iso" to make the image writable. You can mount the image with "mkdir /mnt/mycd", this line in fstab: "/home/sam/mycd.iso /mnt/mycd iso9660 rw,user,noauto 0 0", save fstab, "mount -o loop /mnt/mycd". Then the file system will be viewable as files and directories in the directory /mnt/mycd. You can edit the image as you wish, and the new file will be "/home/sam/mycd.iso" dd does not write to CD's. You need to use a burning utility, or the cdrdao command
dd if=/dev/sda of=/dev/sdb conv=notrunc,noerror
In this example, sda is the source. sdb is the target. Do not reverse the intended source and target. Surprisingly many people do. notrunc means to not truncate. noerror means to keep going if there is an error. Normally dd stops at any error. if you have a question about a hard drive on whether or not it works, you can try to use it as the source drive for the dd command. You should get an error if it is not working. target drives need to be really messed up to give an error in dd.
dd if=/dev/sda of=/home/sam/MBR.image bs=446 count=1
this will copy the first 446 bytes of the hard drive to a file. If you haven't already guessed, reversing the objects of if and of, in the dd command line reverses the direction of the write.
dd if=/dev/sda of=mbr.bin count=1
Put this on a floppy you make with
dd if=boot.img of=/dev/fd0
Along with dd. Boot from the floppy and
dd if=mbr.bin of=/dev/sda count=1
Will restore the MBR
dd if=/dev/sdb2 of=/home/sam/partition.image bs=4096 conv=notrunc,noerror
This will make a file that is an exact duplicate of the sdb2 partition. You can substitue hdb, sda, hda, or whatever the disk is called.
dd if=/home/sam/partition.image of=/dev/sdb2 bs=4096 conv=notrunc,noerror
This way you can get a bazonga hard drive and partition it so you can back up your root partition. If you mess up your root partition, you just boot from the helix cd and restore the image.
J'ai un disque qui montre des faiblesses
Je veux le remplacer par un nouveau disque
Je dois donc faire une image du disque et la copier ensuite sur le nouveau disque
1) Télécharger une ISO de SystemRescueCd (x86)
http://www.sysresccd.org/Download
2) Vérifier le checksum de cette ISO
md5sum systemrescuecd-x86-2.1.1.iso
Pour faire ça depuis Windows, télécharger md5deep (http://sourceforge.net/projects/md5deep/files/md5deep/md5deep-1.12/md5deep-1.12.zip/download)
Il contient md5sum, que l'on peut appeler sous Dos : md5sum systemrescuecd-x86-2.1.1.iso
3) Créer un DVD à partir de cette ISO
4) Identifier les partitions du disque à copier (avec df, fdisk, et /proc/partitions)
Dans mon cas, c'était le disque système qui montrait des faiblesses
Il s'appelle /dev/sda et contient 3 partitions
# df -h Sys. de fich. Tail. Occ. Disp. %Occ. Monté sur /dev/sda3 222G 18G 193G 9% / /dev/sda1 190M 18M 163M 10% /boot ... # fdisk -l Disque /dev/sda: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sda1 * 1 25 200781 83 Linux /dev/sda2 26 535 4096575 82 Linux swap / Solaris /dev/sda3 536 30401 239898645 83 Linux Disque /dev/sdb: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sdb1 * 1 30401 244196001 fd Linux raid autodetect Disque /dev/sdc: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sdc1 * 1 30401 244196001 fd Linux raid autodetect Disque /dev/sdd: 250.0 Go, 250059350016 octets 255 heads, 63 sectors/track, 30401 cylinders Unités = cylindres de 16065 * 512 = 8225280 octets Périphérique Amorce Début Fin Blocs Id Système /dev/sdd1 * 1 30401 244196001 fd Linux raid autodetect Disque /dev/md0: 500.1 Go, 500113080320 octets 2 heads, 4 sectors/track, 122097920 cylinders Unités = cylindres de 8 * 512 = 4096 octets Disque /dev/md0 ne contient pas une table de partition valide # fdisk /dev/sda ... Commande (m pour l'aide): p Périphérique Amorce Début Fin Blocs Id Système /dev/sda1 * 1 25 200781 83 Linux /dev/sda2 26 535 4096575 82 Linux swap / Solaris /dev/sda3 536 30401 239898645 83 Linux # cat /proc/partitions major minor #blocks name 8 0 244198584 sda 8 1 200781 sda1 8 2 4096575 sda2 8 3 239898645 sda3 8 16 244198584 sdb 8 17 244196001 sdb1 8 32 244198584 sdc 8 33 244196001 sdc1 8 48 244198584 sdd 8 49 244196001 sdd1 9 0 488391680 md0 # cat /etc/fstab LABEL=/ / ext3 defaults 1 1 LABEL=/boot1 /boot ext3 defaults 1 2 devpts /dev/pts devpts gid=5,mode=620 0 0 tmpfs /dev/shm tmpfs defaults 0 0 /dev/md0 /home ext3 defaults 1 2 proc /proc proc defaults 0 0 sysfs /sys sysfs defaults 0 0 LABEL=SWAP-sda2 swap swap defaults 0 0 /dev/cdrom /media/cdrom udf,iso9660 user,noauto,exec 0 0
La virtualisation consiste à faire cohabiter plusieurs (VM) machines "virtuelles" (OS) sur une même machine physique
Prérequis :
http://planetoweb.cesr.fr/twiki/bin/view/Team/EuroplanetProject#Serveur_SVN
http://en.wikipedia.org/wiki/X_display_manager
http://en.wikipedia.org/wiki/X_Window_System_protocols_and_architecture
http://tldp.org/HOWTO/XDMCP-HOWTO/intro.html
Le serveur X tourne localement sur mon pc (win ou lin), c'est à dire le pc avec un écran (output), un clavier et une souris (inputs).
Il se connecte à un display manager (xdm ou gdm ou kdm...) qui peut être local ou distant (sur un autre pc) :
Ainsi, le serveur X (local) communique avec différents clients graphiques (qui peuvent être distants) à qui il envoit les inputs et de qui il reçoit les outputs.
Pour CentOS, le DM par défaut est sélectionné dans /etc/X11/prefdm (qui regarde si un DM par défaut est donné dans /etc/sysconfig/desktop)
C'est le fichier /etc/X11/xinit/Xsession qui exécute notre environnement.
xdm : voir /etc/X11/
kdm : voir /etc/kdm/
gdm : voir /etc/gdm/ Il devrait s'y trouver un gdm.conf
gdm appelle /etc/X11/xinit/Xsession avec les bonnes options
http://projects.gnome.org/gdm/docs/gdmtalk.pdf
Attention, X et XDMCP sont tous les 2 non sécurisés !!!
Vérifier /etc/resolv.conf
Vérifier /etc/init.d/xfs (font server)
Vérifier que dans /etc/inittab, le default runlevel est bien 5 :
id:5:initdefault:
Vérifier /etc/X11/xorg.conf
Sur serveur boulot, on voit bien que c'est gdm qui tourne :
# ps -efl|grep gdm 4 S root 3815 1 0 76 0 - 41936 429493 2010 ? 00:00:00 /usr/sbin/gdm-binary -nodaemon 5 S root 3917 3815 0 76 0 - 48714 pipe_w 2010 ? 00:00:00 /usr/sbin/gdm-binary -nodaemon 4 S root 3919 1 0 77 0 - 47464 304555 2010 ? 00:00:04 /usr/libexec/gdm-rh-security-token-helper 4 S root 3920 3917 0 75 0 - 22128 - 2010 tty7 00:03:08 /usr/bin/Xorg :0 -br -audit 0 -auth /var/gdm/:0.Xauth -nolisten tcp vt7 4 S gdm 3946 3917 0 75 0 - 56317 - 2010 ? 00:00:02 /usr/libexec/gdmgreeter
Log de X : /var/log/Xorg.0.log
Config de X : /etc/X11/xorg.conf
Synthèse du workflow : bootloader ==> noyau + initramfs + arguments ==> montage de la racine
C'est le 1er prog à s'exécuter. Différent selon les architectures (pc x86, station Sun, Mac PPC...) Rôle: mettre en RAM le noyau (kernel), lui passer des arguments, copier un ramdisk en RAM, et passer la main au noyau Ex: lilo, grup, outils syslinux (bien adapté à partifion FAT, clé usb, cd) Etapes : - allumage électrique - POST (Power On Self Test) - BIOS (dans lequel le periph d'amorçage est défini) - lancement bootloader installé sur periph amorcé Ex: noyau grub, /boot/bzImage-2.6 Ex: ramdisk grub, /boot/initrd.img
Rôle : monter la racine et lancer /sbin/init situé dessus Au boot, le noyau décourvre son environnement (ram, cpu, disque...). Ces périph sont gérés par des pilotes (drivers), des "modules" qui sont compilés dans le noyau ou dans des fichiers externes (souvent dans /lib/modules/). Les fichiers modules sont situés sur une partition qui n'est pas encore montée, et donc les périph correspondants ne peuvent pas être utilisés. Le noyau monte sa racine avec /bin/mount ex: montage de /dev/sda1 en lecture seule avec sys de fichier ext4 $ mount -t ext4 -o ro /dev/sda1 / Les arguments passés au noyau peuvent être relus après boot : $ cat /proc/cmdline On peut aussi passer l'argument "init=/bin/bash" pour accéder au système au démarrage avec un shell bash.
Rôle : permettre une détection plus intelligente de la racine ainsi qu'une facilité de configuration. S'appelait initrd, mais est de plus en plus remplacé par initramfs L'initramsf est un ensemble de fichiers qui vont être directement copiés dans le cache de système de fichiers sous la racine (tous les sys 2.6 utilisent un rootfs, cf "cat /proc/mounts"). Il doit au moins contenir un programme /init exécutable que le noyau va lancer pour qu'il trouve la racine et la monte. C'est un microsystème linux à part entière. Le prog /init est souvent un script shell, simple à lire. Avec un initramfs, il devient possible de conserver un noyau minimal et de mettre les modules essentiels au boot dans l'initramfs (évite de devoir recompiler le noyau). Il contient aussi l'image qui permet un affichage graphique pendant le boot. /init parse donc la ligne /proc/cmdline, cherche la racine, et la monte pour ensuite basculer le noyau dessus, et enfin s'autoremplace par le vrai binaire /sbin/init.
Arrivé à ce point, la noyau tourne, la racine de la distrib est montée (souvent en "ro") et le binaire /sbin/init est lancé, premier processus.
Si ce processus meurt (pid=1), le noyau fait un kernel panic. Il est aussi responsable de l'extinction de la machine. Si on passe au noyau l'argument "init=/bin/bash", seul "bash" est lancé (à la place de /sbin/init) et on a ainsi un accès root sur la racine (utile pour réparer une distrib, ou modifier mot passe root dans /etc/shadow)
/sbin/init a pour fichier de conf, /etc/inittab : décrit les processus lancés au démarrage et à surveiller durant le fonctionnement normal du système. Init à 7 runlevels (0=stop, ..., 6=reboot). Runlevel 1 est pour la maintenance (nb minimum de processus et user root only). Chaque ligne est composée de 4 paramètres : référence:runlevel:manière de lancer la commande:commande Runlevel par défaut (ici, le 3): id:3:initdefault: On peut modifier ça avec un argument au noyau, par ex: root=/dev/hda2 ro 1 Runlevel courant ? $ runlevel Changer de runlevel ? $ init n
sysinit est lancé au boot, mais avant les cdes boot: si::sysinit:/etc/rc.d/rc.sysinit
reset: ca::ctrlaltdel:/sbin/shutdown -t3 -r now
wait, lance un process et attend sa fin pour continuer: l5:5:wait:/etc/rc.d/rc 5
respawn, relance le process quand il se termine (ex: les gettys texte, alt-F1... relancés dès qu'on se délogue) 5:2345:respawn:/sbin/mingetty tty5
Relecture de inittab après modif ? kill -HUP 1
inittab lance des script rc (run command) de 2 façons selon les familles de systèmes linux :
Voyons ici la façon SystemV (plus élaborée que BSD)
en fait, inittab lance le script rc général et lui passe le runlevel en argument: l5:5:wait:/etc/rc.d/rc 5 rc va lancer les scripts du runlevel associé, dans l'ordre alpha. /etc/rc.d/ contient un dossier rcN.d/ par runlevel (N) ex: /etc/rc.d/rc5.d/ Ce dossier contient simplement des liens vers les scripts de /etc/init.d/ (qui doivent accepter au moins les arguments "start" et "stop") Ces liens sont préfixés par S (Start) ou K (Kill). Quand on entre dans un runlevel, tous les liens S* de ce runlevel sont exécutés (dans l'ordre alpha) Quand on sort d'un runlevel, tous les liens K* de ce runlevel sont exécutés Ex: S85httpd lancera "/etc/init.d/httpd start" Un lien /etc/rc.d/rc5.d/S42foobar sera exécuté à l'entrée du runlevel 5, et appellera /etc/init.d/foobar start Il sera exécuté avant l'appel de S95barqux Sur RedHat, seul le runlevel 5 lance X : x:5:respawn:/etc/X11/prefdm -nodaemon
Le dernier script à être lancé est /etc/rc.d/rc.local (on peut y mettre tout ce qu'on veut voir exécuter au boot) Le prog update-rc.d peut être utilisé pour activer/désactiver des scripts au démarrage.
Ubuntu propose Upstart en remplacement du couple init/inittab MacOS propose un "super-daemon" launchd qui regroupe les fonctionnalités de init (lance démon lors du démarrage), crond (lance démon lors de top horaires), et (x)inetd (lance démon lors de requêtes réseaux)
Pour tester manuellement une entrée du cron.daily :
run-parts /etc/cron.daily
ex: installation ftp pour l'expérience RAMAN (sur ExoMars)
http://www.obs-mip.fr/index.php/fre/recherche/techniques-missions-spatiales/Exomars-RAMAN
La mission ExoMars, de l’Agence Spatiale Européenne (ESA), est une mission du programme Aurora. Son objectif est de caractériser l’environnement biologique martien pour préparer l’exploration humaine de la planète rouge.
EXLIBRIS serait capable d’effectuer une ablation des roches puis l’analyse de la composition de cette roche à la fois en chimie élémentaire (ultra-violet), en minéraux et composés organiques (Raman). Le LABO serait responsable de la partie LIBS (ultra-violet) et de la calibration de l’instrument. F. Rull Pérez (Centro de Astrobiologia , Espagne) serait en charge de la partie Raman. Contexte de réalisation
Mission ESA : Tir prévu en 2013.
Voir en ligne (Site Officiel d’ExoMars à l’ESA) : http://www.esa.int/esaSC/SEMGB7MJ74G_index_0.html
Ajout 2 users ftpread et ftpw (groupe ftpgroup) dans /etc/passwd (et /etc/shadow), et leur donner pour home /projects/raman/ftp/files
Leur attribuer un pass via "password"
Leur donner un accès exclusif a leur home:
chown ftpw:ftpgroup /projects/raman/ftp/files/
Faire en sorte que ftpread n'est qu'un accès en lecture seule (via son groupe ftpgroup) :
chmod 755 /projects/raman/ftp/files/ --> "rwxr-xr-x"
Les autoriser en les ajoutant dans dans /etc/vsftpd/user_list
(chroot doit être activé par défaut pour tous les users internes)
/etc/init.d/vsftpd restart
/var/log
auth.log ou secure (sur Redhat)
Outil de visualisation graphique des logs : gnome-system-log
Common Linux log files name and usage :
/var/log/message: General message and system related stuff /var/log/auth.log: Authenication logs /var/log/kern.log: Kernel logs /var/log/cron.log: Crond logs (cron job) /var/log/maillog: Mail server logs /var/log/qmail/ : Qmail log directory (more files inside this directory) /var/log/httpd/: Apache access and error logs directory /var/log/lighttpd: Lighttpd access and error logs directory /var/log/boot.log : System boot log /var/log/mysqld.log: MySQL database server log file /var/log/secure: Authentication log /var/log/utmp or /var/log/wtmp : Login records file /var/log/yum.log: Yum log files
In short /var/log is the location where you should find all Linux logs file. However some applications such as httpd have a directory within /var/log/ for their own log files. You can rotate log file using logrotate software and monitor logs files using logwatch software.
/etc/logrotate.conf
/etc/logrotate.d/
Forcer une rotation :
sudo logrotate -f /etc/logrotate.conf
==> new file "messages", "messages" devient "messages1", "messages1" devient "messages2"...
by default, runs daily on yesterday's logs (/etc/cron.daily/0logwatch qui pointe sur /usr/share/logwatch/scripts/logwatch.pl), includes all services, and sends a mail to root
Configuration locale :
Exemples :
info sur l'activité sshd d'aujourd'hui :
logwatch --service sshd --range=Today
Plus de détails :
logwatch --service sshd --range=Today --detail=Medium (ou High)
Pour créer un fichier au lieu d'un mail : --save=logwatch.today
Bonne config de logwatch.conf :
Range=All (au lieu de "Yesterday") Detail=High Archives=Yes (ajoute les logs des semaines précédentes, pas seulement le log en cours)
Equivalent commande : --range=All --archives
Exemple de config sur planetoweb (aug 2010) :
Création d'une config locale /etc/logwatch/conf/logwatch.conf :
Range = All Detail = High Archives = Yes Output = html Save = /var/www/html/servers/planetoweb/logwatch.html
Résultat sur http://planetoweb/servers/planetoweb/logwatch.html
http://www.linux-mag.com/id/7807
yum install swatch
[root@planetoweb planetoweb]# rpm -ql swatch /usr/bin/swatch /usr/lib/perl5/vendor_perl/5.8.8/Swatch /usr/lib/perl5/vendor_perl/5.8.8/Swatch/Actions.pm /usr/lib/perl5/vendor_perl/5.8.8/Swatch/Threshold.pm /usr/lib/perl5/vendor_perl/5.8.8/Swatch/Throttle.pm /usr/lib/perl5/vendor_perl/5.8.8/auto/Swatch /usr/lib/perl5/vendor_perl/5.8.8/auto/Swatch/Actions /usr/lib/perl5/vendor_perl/5.8.8/auto/Swatch/Actions/autosplit.ix /usr/share/doc/swatch-3.2.1 /usr/share/doc/swatch-3.2.1/CHANGES /usr/share/doc/swatch-3.2.1/COPYING /usr/share/doc/swatch-3.2.1/COPYRIGHT /usr/share/doc/swatch-3.2.1/KNOWN_BUGS /usr/share/doc/swatch-3.2.1/README /usr/share/doc/swatch-3.2.1/examples /usr/share/doc/swatch-3.2.1/examples/SendMail.pm /usr/share/doc/swatch-3.2.1/tools /usr/share/doc/swatch-3.2.1/tools/reswatch /usr/share/doc/swatch-3.2.1/tools/swatch_oldrc2newrc /usr/share/man/man1/swatch.1.gz /usr/share/man/man3/Swatch::Actions.3pm.gz /usr/share/man/man3/Swatch::Threshold.3pm.gz /usr/share/man/man3/Swatch::Throttle.3pm.gz
/usr/share/doc/swatch
Créer un startup script : vi /etc/init.d/swatch
#!/bin/sh # Simple Log Watcher Program case "$1" in 'start') /usr/bin/swatch --daemon --config-file=/etc/swatch.conf --tail-file=/var/log/auth.log --pid-file=/var/run/swatch.pid ;; 'stop') PID=`cat /var/run/swatch.pid` kill $PID ;; *) echo "Usage: $0 { start | stop }" ;; esac exit 0
chmod 755 /etc/init.d/swatch
Make sure swatch starts automatically at my runlevels :
# ln -s /etc/init.d/swatch /etc/rc2.d/S99swatch # ln -s /etc/init.d/swatch /etc/rc3.d/S99swatch # ln -s /etc/init.d/swatch /etc/rc5.d/S99swatch
Créer un fichier de conf /etc/swatch.conf :
watchfor /invalid|repeated|incomplete/ echo write khess mail addresses=khess@localhost, subject=Authentication Problems
/etc/init.d/swatch start ==> créer un pid dans /var/run/swatch.pid et un fichier /root/.swatch_script.xxxx (avec xxxx = pid - 2)
1) Accès ssh direct en root autorisé seulement depuis mon pc
http://www.ibm.com/developerworks/aix/library/au-ssh_restrict/
vi /etc/ssh/sshd_config :
PermitRootLogin yes AllowUsers moi@MONPC moi@MONPC.domain root@MONPC root@MONPC.domain moi@PASSERELLE
(le moi@PASSERELLE est nécessaire pour que je puisse aussi me connecter depuis chez moi)
/etc/init.d/sshd restart
Si j'essaye une connexion (moi ou root) depuis MONPC, ça passe
Si j'essaye une connexion (moi ou root) depuis un AUTREPC, je suis rejeté
On voit le refus de connexion dans /var/log/secure :
User root from AUTREPC not allowed because not listed in AllowUsers Jul 16 14:57:06 planetoweb sshd[28008]: input_userauth_request: invalid user root Jul 16 14:57:11 planetoweb sshd[28007]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=AUTREPC user=root Jul 16 14:57:13 planetoweb sshd[28007]: Failed password for invalid user root from AUTREPC_IP port 60246 ssh2
2) Encore plus strict, AUCUN accès ssh direct en root autorisé
http://www.howtogeek.com/howto/linux/security-tip-disable-root-ssh-login-on-linux/
vi /etc/ssh/sshd_config (Port 22 : on pourrait mettre ici un autre port, genre 2010, histoire de brouiller les pirates...) PermitRootLogin yes changed to : PermitRootLogin no LoginGraceTime 2m changed to : LoginGraceTime 30 /etc/init.d/sshd restart
last reboot
lastlog
dmesg
lspci
/var/log/messages
/var/log/secure
/var/log/boot.log
Voir aussi section suivante (test des disques)
Occupation disques : df -h
# df -h Sys. de fich. Tail. Occ. Disp. %Occ. Monté sur /dev/sda3 178G 63G 106G 38% / /dev/sdb1 2,7T 1,4T 1,3T 52% /data /dev/sda1 99M 29M 65M 31% /boot tmpfs 24G 4,0K 24G 1% /dev/shm
cat /proc/partitions
cat /etc/mtab
cat /proc/mounts (equivalent de la commande "mount")
cat /proc/scsi/scsi
Voir aussi si messages d'erreur disques dans /var/log/messsages
Tester aussi la commande dmesg (equivalent à /var/log/dmesg)
Annuler l'information sur les updates disponibles :
/etc/init.d/yum-updatesd stop
su -c 'chkconfig --level 2345 yum-updatesd off'
Every other workaround seems to only kill yum-updatesd for runlevel 5.
Try yum update after that.
Keep in mind that you will no longer be informed that there updates available and as such you will need to check periodically with yum check-update
Quels sont les packages commençant par "mesa-" installés + à installer ? --> yum list mesa-*
Installation du service sur le serveur :
service smb start
chkconfig --level 345 smb on
Est-ce que samba est à l'écoute ? : service smb status
Redémarrer samba : service smb restart
Corriger un bug sur Mac Leopard (pas sur Tiger) : samba ne suit pas les liens qui vont vers un disque différent
Pour corriger ce bug, il suffit d'ajouter cette ligne dans la partie "[global]" du smb.conf :
unix extensions = no
Gestion des utilisateurs :
Les utilisateurs enregistrés sont dans /etc/samba/smbpasswd
Créer un new user "toto" : sbmpasswd -a toto
Pour modifier le mot de passe de "toto" : smbpasswd toto
Connexion depuis un poste client Windows :
clic droit sur Poste de Travail / Créer un lecteur réseau / "\\nom_du_serveur\mon_nom"
Cas particulier des clients Windows 8 :
Try making the following adjustments on the Windows 8 machine that needs to connect to the Samba share. This type of problem usually requires that you change the lanman server parameters in order to get Windows 8 working with older servers. Control Panel - Administrative Tools - Local Security Policy Local Policies - Security Options Network security: LAN Manager authentication level Set to Send LM & NTLM responses only Set the Minimum session security for NTLM SSP Disable Require 128-bit encryption Reboot
Connexion depuis un poste client Mac :
CMD-K sur une fenetre (finder), puis saisir "smb://TEAM_SERVER" (ou encore "smb://moi@TEAM_SERVER")
Problèmes sur Mavericks (Mac OS 10.9) : http://cammodude.blogspot.fr
Workaround Option 1:
To force your connection to be SMB1, simply type cifs://servername instead of smb://servername when connecting to a Windows or NAS share. This is by far easier and requires no real configuration changes.
Workaround Option 2:
To force all connections to be SMB1:
Open A terminal window paste in the following line followed by the return key(should be all on one line):
echo "[default]" >> ~/Library/Preferences/nsmb.conf; echo "smb_neg=smb1_only" >> ~/Library/Preferences/nsmb.conf
Reboot
This command adds directives to force SMB connections to use the SMB1 protocol. This is slower but stable.
Il s'agit ici de récupérer le bureau complet d'un serveur linux distant sur l'écran de mon pc Windows (ou Linux) depuis le boulot (ou la maison).
1) L'administrateur du serveur linux doit y avoir installé freenx (yum install freenx)
C'est fait pour TEAM_SERVER
2) Installer sur mon pc Windows (ou linux) un client de connexion au serveur freenx
Pour Windows, télécharger et installer "NX client for Windows" ici : http://www.nomachine.com/download.php
(ou NX client for Linux pour un pc linux)
(Si nécessaire, voici les instructions d'installation pour le client Windows : http://www.nomachine.com/documents/client/install.html#2)
3) Exemple : Configurer une session graphique vers TEAM_SERVER (depuis le boulot)
Démarrer le "NX Connection Wizard" (un des programmes installés avec le client)
Cliquer sur Next
Cliquer sur Next
Cliquer sur Next
Cliquer sur Next
Une fenetre de connexion s'affiche (que vous pourrez relancer à loisir en cliquant sur votre raccourci bureau portant le nom de votre session)
Cliquer sur "Configure"
(pour info, cette clé provient du fichier /etc/nxserver/client.id_dsa.key dans l'installation du serveur freenx)
Par soucis de sécurité, je ne diffuse pas la clé ici (vous l'avez reçue par mail)
Entrer votre login/pass pour TEAM_SERVER
Cliquer sur "Login"
Et voilà !
(Lorsque votre bureau TEAM_SERVER s'affiche, répondre à la question posée en choisissant "GNOME")
Si le clavier est qwerty, pour passer à un clavier azerty :
(Plus d'information sur la configuration du client ici : http://www.nomachine.com/documents/configuration/client-guide.php)
(pour savoir qui est connecté : ps -efl|grep NX)
4) C'est très bien tout ça, mais comment je fais depuis chez moi ???
C'est un peu plus compliqué car il faut installer un tunnel qui passe par le GATEWAY LABO.
a) Creuser un tunnel
Sur Windows, on crée le tunnel avec le logiciel Putty
Exécuter Putty
Si vous avez déjà une session vers GATEWAY, inutile d'en recréer une autre, vous pouvez l'utiliser. Sinon, il faut créer une nouvelle session :
Host name : GATEWAY
Port : 22
Saved Sessions : GATEWAY (ou ce que vous voulez, par exemple "le GATEWAY du LABO")
Dans le panneau de gauche (Category:), cliquer sur l'arbre "Connection", puis "SSH", puis "Tunnels"
(si vous avez déjà un ou plusieurs tunnels créés, pas de problème, vous pouvez en ajouter un de plus)
Source Port : 9022
Destination : TEAM_SERVER.LAB_DOMAIN:22
Cliquer sur bouton "Add"
Dans le panneau de gauche (Category:), cliquer sur l'arbre "Session"
Cliquer sur bouton "Save"
Ouvrir cette session (GATEWAY) que vous venez de créer, et se connecter sur GATEWAY (avec votre mot de passe mail).
b) Créer une session graphique
Suivre toutes les étapes du point 3) mais en remplaçant "TEAM_SERVER.LAB_DOMAIN (port 22)" par "localhost (port 9022)"
Ya pu ka tester !
Installer GhostScript (engine) puis GhostView (frontend)
http://pages.cs.wisc.edu/~ghost/
Pour info, sur Linux, c'est très simple, il suffit d'utiliser la commande "convert" (ou plus spécifique "ps2...")
Sous Windows, c'est un peu plus compliqué.
GhostScript converts PS to PNG, JPEG, PNM, TIFF, BMP, PCX, PSD, PDF, EPS, PCL-XL.
1) Télécharger la version Windows de GhostScript et l'installer
http://pages.cs.wisc.edu/~ghost/
ou encore:
http://ghostscript.com/releases/
2) Ajouter le dossier exécutable de GhosScript dans votre PATH windows
set PATH=%PATH%;C:\Program Files\gs\gs9.00\bin
3) Exemple de conversion d'un fichier PS en JPG:
Aller dans le dossier qui contient le fichier PS (somefile.ps) à convertir (cd ...)
L'instruction suivante créera un fichier somefile.jpg dans c:\temp :
gswin32c -sDEVICE=jpeg -o c:\temp\somefile.jpg somefile.ps
Pour plus d'information sur les possibilités de GhostScript : http://pages.cs.wisc.edu/~ghost/doc/cvs/Use.htm
REMARQUE : pour faire la même chose en mode graphique, il existe une interface graphique qui s'installe par-dessus GhostScript (en frontend), c'est GhostView (gsview) :
http://pages.cs.wisc.edu/~ghost/gsview/index.htm
Il faut acheter la licence Microsoft. La démarche dépend de la marque du PC.
Pour un hp : aller sur le site hp et rechercher "windows upgrade"
Modèles éligibles : http://h41112.www4.hp.com/promo/win7web/fr/fr/eligmodels.html
http://welcome.hp.com/country/fr/fr/mda/windows7/upgrade/which_version.html?jumpid=reg_R1002_FRFR
http://h41112.www4.hp.com/promo/win7web/fr/fr/
1) "Creuser" un tunnel avec Putty
Créer une nouvelle session que vous appelerez par exemple "tunnel_mail_LABO", et qui créera un tunnel entre le port local 9025 et le port SMTP (25) du serveur de mail LABO (GATEWAY).
La procédure est décrite sur la faq informatique du LABO :
http://www1.cesr.fr/intranet/informatique/faq/ssh-tunnels/ssh.htm#_Toc150503764
(Exemple 1, cas numéro 2)
Il faudra lancer cette session (et la garder ouverte en tâche de fond) avant d'envoyer un mail
2) Configurer votre client mail Outlook
Bien sûr, il faut tout remettre en place quand on revient au LABO (en fait, on pourrait aussi fonctionner en permanence avec le tunnel, même au LABO...)
http://content.techrepublic.com.com/2346-10877_11-191016.html
On propose d'utiliser Xming qui est un serveur X gratuit pour Windows
Il suffit d'éxécuter Xming avant de lancer une session graphique via putty (ou autre shell)
Installation : http://sourceforge.net/projects/xming
Cliquer sur Download
1) Installer Xming
2) Installer Xming-fonts (surtout nécessaire pour Emacs)
Les jumper sur les disque sata ne sont pas la pour specifier si le disque est slave, master ou en cable select
mais pour pouvoir brider le disque en sata1 ( dans certain cas ca peut resoudre un probleme de compatibilité)
donc pas de jumper = sata2 , le jumper est mis = sata1
Comme il est mis la il est en sata 1 donc bridé à 150Mo/sec Si on l'enlève on passe en sata2 donc 375Mo/sec
Mais comme ton disque ne doit pas dépasser 100Mo/sec tu ne veras pas du tout la difference
moved to EuroplanetProject
I | Attachment | History | Action | Size | Date | Who | Comment |
---|---|---|---|---|---|---|---|
![]() |
idldoc-reference.pdf | r1 | manage | 120.0 K | 2010-11-09 - 21:28 | EtiennePallier | |
![]() |
idldoc-tutorial.pdf | r1 | manage | 109.7 K | 2010-11-09 - 21:27 | EtiennePallier | |
![]() |
styleguide.pdf | r1 | manage | 57.3 K | 2010-11-09 - 21:27 | EtiennePallier |