diff --git a/docs/Linux/ack.md b/docs/Linux/ack.md new file mode 100644 index 0000000..9e851cf --- /dev/null +++ b/docs/Linux/ack.md @@ -0,0 +1,4 @@ +# ack + + + diff --git a/docs/Linux/commandes.md b/docs/Linux/commandes.md index 76001c0..c9207fe 100644 --- a/docs/Linux/commandes.md +++ b/docs/Linux/commandes.md @@ -117,3 +117,35 @@ $ usermod -G "" ``` + + +### Code de sortie: + +Chaque commande renvoie un *code de sortie* (quelque fois nommé *état de retour* ). + +Une commande ayant réussi renvoie un 0. + +Une commande ayant échoué renvoie une valeur différente de zéro qui est habituellement interprétable comme un code d'erreur. + +De même, les fonctions dans un script et le script lui-même renvoient un code de sortie. La dernière commande exécutée dans la fonction ou le script détermine le code de sortie. + +À l'intérieur d'un script, une commande **exit nnn** peut être employée pour retourner un code de sortie *nnn* au shell (*nnn* doit être un nombre décimal compris entre 0 et 255). + +```bash +$ hostname +silverbook.home +$ echo $? +0 +$ hostnam +-bash: hostnam: command not found +$ echo $? +127 +``` + +```bash +$ hostname +silverbook.home +bruno@SilverBook:~/.kymsu/plugins.d$ if [ $? -eq 0 ]; then echo "ok"; else echo "nok"; fi +ok +``` + diff --git a/docs/Linux/conditions.md b/docs/Linux/conditions.md index 014d5e7..cbfbf0b 100644 --- a/docs/Linux/conditions.md +++ b/docs/Linux/conditions.md @@ -26,6 +26,12 @@ else fi ``` +### if (one-line) + +```bash +if [ "$choice" == "72" ]; then echo "sphp 72"; elif [ "$choice" == "73" ]; then echo "sphp 73"; fi +``` + ### if imbriqué diff --git a/docs/Linux/for.md b/docs/Linux/for.md index 175c25f..09816e7 100644 --- a/docs/Linux/for.md +++ b/docs/Linux/for.md @@ -5,7 +5,7 @@ #### 1ere syntaxe: ```bash -bash for variable in liste_valeurs +for variable in liste_valeurs do instruction(s) done ``` diff --git a/docs/Linux/grep.md b/docs/Linux/grep.md index d6a624b..7f03984 100644 --- a/docs/Linux/grep.md +++ b/docs/Linux/grep.md @@ -36,6 +36,14 @@ grep -l -r "brew" ./docs/ +Chercher dans tous les fichiers 'php' ou 'html' (et ignorer les dossiers '.git'): + +```bash +grep pattern $(find . -name '*.php' -or -name '*.html' | grep -v .git) +``` + + + Regex: ```bash diff --git a/docs/Programmation/Python/class.md b/docs/Programmation/Python/class.md index ee2164d..0d5bb74 100644 --- a/docs/Programmation/Python/class.md +++ b/docs/Programmation/Python/class.md @@ -1,6 +1,6 @@ -# class +# Les classes diff --git a/docs/Programmation/Python/dictionnaire.md b/docs/Programmation/Python/dictionnaire.md index d248994..31dcced 100644 --- a/docs/Programmation/Python/dictionnaire.md +++ b/docs/Programmation/Python/dictionnaire.md @@ -33,6 +33,18 @@ C'est une collection **non ordonnée**, **modifiable** et **indexée**. {'marque': 'Ford', 'modele': 'Mustang', 'annee': 1964} ``` +```python +# Liste l de couples transformée en dictionnaire +>>> l = [('a',1), ('b',2)] +>>> dict(l) +{'a': 1, 'b': 2} +``` + +```python +>>> dict(zip('abc',range(3))) +{'a': 0, 'b': 1, 'c': 2} +``` + ##### Accéder à un item: ```python @@ -82,6 +94,15 @@ C'est une collection **non ordonnée**, **modifiable** et **indexée**. {'language': 'python', 'version': '3.7'} ``` +##### Ajouter des valeurs (update): + +```python +>>> d = {'a':0} +>>> d.update(zip('bcd',range(1,4))) +>>> d +{'a': 0, 'b': 1, 'c': 2, 'd': 3} +``` + ##### Vérifier la présence d'une clé (in): ```python @@ -181,7 +202,7 @@ language python version 3.7 ``` -Vérifier si une clé existe dans un dictionnaire: +##### Vérifier si une clé existe dans un dictionnaire: ```python >>> dict = {'language': 'python', 'version': '3.7'} @@ -191,7 +212,7 @@ Vérifier si une clé existe dans un dictionnaire: 'language' est dans dict ``` -Longueur d'un dictionnaire: +##### Longueur d'un dictionnaire: ```python >>> dict = {'language': 'python', 'version': '3.7'} @@ -199,33 +220,96 @@ Longueur d'un dictionnaire: 2 ``` - - ##### Copier un dictionnaire (copy): ```python >>> autre_dict = dict.copy() >>> autre_dict {'language': 'python', 'version': '3.7'} + +>>> autre_dict['language'] = 'PYTHON' +>>> autre_dict +{'language': 'PYTHON', 'version': '3.7'} +>>> dict +{'language': 'python', 'version': '3.7'} ``` +##### Fromkeys(): +```python +>>> d3 = {} +>>> d3 = {}.fromkeys('abcde', 0) +>>> d3 +{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0} +``` #### Méthodes: -| Méthode | Description | -| ------------ | ----------- | -| clear() | | -| copy() | | -| fromkeys() | | -| get() | | -| items() | | -| keys() | | -| pop() | | -| popitem() | | -| setdefault() | | -| update() | | -| values() | | +| Méthode | Description | +| -------------------- | ------------------------------------------------------------ | +| d.clear() | supprime tous les éléments de `d` | +| d.copy() | shallow copie de `d` | +| {}.fromkeys(s,v) | créée un dict avec les clés de `s` et la valeur `v` | +| d.get(k [,v]) | envoie la valeur `d[k]` si elle existe v sinon | +| d.items() | liste des items `(k,v)` de `d` | +| d.keys() | liste des clés | +| d.pop(k [,v]) | enlève `d[k]` s’il existe et renvoie sa valeur ou `v` sinon | +| d.popitem() | supprime un item `(k,v)` et retourne l’item sous forme de tuple | +| d.setdefault(k [,v]) | `d[k]` si elle existe sinon `v` et rajoute `d[k] = v` | +| d.update(s) | `s` est une liste de tuples que l’on rajoute à `d` | +| d.values() | liste des valeurs de `d` | + + + +#### Dictionnaires persistants: + +Python permet de créer des dictionnaires persistants, grâce au module `shelve`. + +`shelve` fournit une solution de persistance de type “base de données” très simple qui sera gérée automatiquement dans un fichier. + +La méthode `shelve.open('f')` crée dans le répertoire courant de votre ordinateur, un fichier de sauvegarde “f.db” s’il n’existe pas, et retourne un objet de type `shelve` ; un `shelve` fonctionne comme un dictionnaire. La plupart des opérations et méthodes des dictionnaires lui sont applicables ; toute modification appliquée au `shelve` est automatiquement sauvegardée. La méthode `shelve.close` permet de fermer le `shelve`, comme pour un fichier. + +```python +>>> import shelve +>>> t = [0,1,2,3,4,5,6,7] +>>> p = (1,2,3) +>>> i = 23 +>>> s = 'Bonjour' +>>> db = shelve.open('data') +>>> db['liste'] = t +>>> db['point'] = p +>>> db['entier'] = i +>>> db['chaine'] = s +>>> print(dict(db)) +{'point': (1, 2, 3), 'entier': 23, 'liste': [0, 1, 2, 3, 4, 5, 6, 7], 'chaine': 'Bonjour'} +>>> db.close() +>>> exit() + +~$ ls -la +-rw-r--r-- 1 bruno staff 16384 25 mar 08:55 data + +# On relance une session Python + +>>> import shelve +>>> with shelve.open('data') as db: +... print(db['liste']) +... for k in db: +... print(db[k]) +... +[0, 1, 2, 3, 4, 5, 6, 7] +(1, 2, 3) +23 +[0, 1, 2, 3, 4, 5, 6, 7] +Bonjour +``` + +Si votre code modifie plusieurs fois certaines entrées lors de la même session, lors de l’ouverture du `shelve`, il est important, dans la méthode `open` associée au `shelve`, de mettre le paramètre `writeback` à vrai, comme suit : + +```python +shelve.open('data', writeback=True) +``` + +Grâce à cette option, chaque fois qu’une modification est réalisée au `shelve`, cette modification est correctement répercutée sur la mémoire morte (le disque dur) de votre ordinateur. diff --git a/docs/Programmation/Python/fichiers.md b/docs/Programmation/Python/fichiers.md index 54d8ffc..3fe715c 100644 --- a/docs/Programmation/Python/fichiers.md +++ b/docs/Programmation/Python/fichiers.md @@ -38,7 +38,23 @@ Parcourrir un fichier ligne par ligne: >>> for x in fichier: ... print(x) ... +``` +```python +>>> with open("pecl-help.txt") as fichier: +... for line in fichier: +... print(line, end='') +... +``` + +Ouverture d'un fichier binaire: + +```python +>>> with open('file', 'rb') as fichierbinaire: +... octets = fichierbinaire.read() # le fichier est lu en entier +... print("on a lu un objet de type", type(octets)) +... for i, octet in enumerate(octets): +... print(f"{i} → {repr(chr(octet))} [{hex(octet)}]") ``` @@ -56,8 +72,8 @@ fichier.close() ##### Type d'ouverture: ```python -r, pour une ouverture en lecture (READ). -w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas python le crée. +r, pour une ouverture en lecture (READ). (Par défaut) +w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas, Python le crée. a, pour une ouverture en mode ajout à la fin du fichier (APPEND). Si le fichier n'existe pas python le crée. b, pour une ouverture en mode binaire. t, pour une ouverture en mode texte. @@ -92,7 +108,7 @@ if os.path.exists("empty_folder"): -#### Chemins +#### Chemins (os.path) ##### Méthodes: @@ -206,3 +222,37 @@ os.rename(old, new) → Renomme le fichier / dossier indiqué +#### pathlib + +Depuis Python 3.4, le module `os.path` est obsolète et est remplacé par la librairie `pathlib`. + +```python +from pathlib import Path + +help(pathlib) +``` + +```python +from pathlib import Path +filename = 'scratch.py' +path = Path(filename) + +if path.exists(): + print("existe") + print(path.stat().st_size) # taille + print(path.stat().st_mtime) # dernière modif + +try: + path.unlink() +except FileNotFoundError: + print("Pas de fichier à supprimer") +``` + +```python +from pathlib import Path +dirpath = Path('.') # répertoire courant + +for py in dirpath.glob("*.py"): + print(py) # liste des fichiers Python du répertoire courant +``` + diff --git a/docs/Programmation/Python/for.md b/docs/Programmation/Python/for.md new file mode 100644 index 0000000..fa4d30a --- /dev/null +++ b/docs/Programmation/Python/for.md @@ -0,0 +1,65 @@ +# For + + + +##### Range: + +```python +>>> somme = 0 +>>> for i in range(10): +... somme += i +... +>>> print(somme) +45 +``` + +##### Parcourir une liste: + +```python +>>> thislist = ["alpha", "beta", "gamma"] +>>> for elem in thislist: +... print(elem) +... +alpha +beta +gamma +``` + +##### Parcourir une chaine: + +```python +>>> language = "Python" +>>> for c in language: +... print("Caractère : ", c) +... +Caractère : P +Caractère : y +Caractère : t +Caractère : h +Caractère : o +Caractère : n +``` + +##### Parcourir une chaine par les indices: + +```python +>>> language = "Python" +>>> for i in range(len(language)): +... print("Caractère d'indice",i," :",language[i]) +... +Caractère d'indice 0 : P +Caractère d'indice 1 : y +Caractère d'indice 2 : t +Caractère d'indice 3 : h +Caractère d'indice 4 : o +Caractère d'indice 5 : n +``` + +##### Plusieurs variables dans une boucle for: + +```python +entrees = [(1, 2), (3, 4), (5, 6)] +for a, b in entrees: + print(f"a={a} b={b}") +``` + diff --git a/docs/Programmation/Python/image-20190317181121361.png b/docs/Programmation/Python/image-20190317181121361.png new file mode 100644 index 0000000..4f71078 Binary files /dev/null and b/docs/Programmation/Python/image-20190317181121361.png differ diff --git a/docs/Programmation/Python/in.md b/docs/Programmation/Python/in.md new file mode 100644 index 0000000..cfd2ae5 --- /dev/null +++ b/docs/Programmation/Python/in.md @@ -0,0 +1,209 @@ +# In + + + +##### Test si un item est présent dans une liste: + +```python +>>> language = ["Python", "Perl", "C++"] +>>> i = "Python" +>>> if i in language: +... print("Python appartient à language") +... +Python appartient à language +``` + +##### Test si une liste est présent dans une autre liste: + +```python +>>> liste1 = [9,18,3,5,7,21] +>>> liste2 = [9,18,[3,5,7],21] +>>> [3,5,7] in liste1 +False +>>> [3,5,7] in liste2 +True +``` + +##### Test su une séquence est présent dans une chaine: + +```python +>>> language = "Python" +>>> 'thon' in language +True +``` + + + +### Slicing: + +##### Sous-séquence: + +```python +>>> str = "Bonjour, ça va ?" +>>> str[1:3] +'on' +>>> str[:3] +'Bon' +>>> str[3:] +'jour, ça va ?' +``` + +##### Copie de séquence: + +```python +>>> prem = [1,2,3,5,7] +>>> sec = prem[:] +>>> sec +[1, 2, 3, 5, 7] +``` + +##### Pas: + +```python +>>> language = "Python" +>>> language[::2] +'Pto' +# On prend 1 lettre sur 2 + +>>> language[::-1] +'nohtyP' +# On part de la fin +``` + +##### Gestion mémoire des séquences: + +```python +>>> prem = [2, 3] +>>> prem = sec = [2, 3] +>>> id(prem) +4468993928 +>>> id(sec) +4468993928 + +>>> trois = [2, 3] +>>> id(trois) +4468967496 + +>>> prem is sec +True +>>> prem is trois +False +>>> prem == trois +True + +>>> prem.append(5) +>>> prem +[2, 3, 5] +>>> sec +[2, 3, 5] +>>> trois +[2, 3] +``` + + + +```python +1 prem = sec = [1, 3] +2 trois = [1, 3] +3 prem[0] = 2 +4 prem.append(5) +5 prem.extend([7, 11]) +6 t = 'Bonjour' +7 t2 = 'B' + t[1:] +``` + +![image-20190317181121361](image-20190317181121361.png) + + + + + +```python +>>> tex = "bonjour" +>>> prem = [2, 3, 5, 7, 8, 9, 10, 17] + +>>> prem[4:7] = [11, 13] # on remplace les éléments 4 à 7 exclu +>>> prem +[2, 3, 5, 7, 11, 13, 17] +``` + + + +#### Pack / Unpack: + + + +```python +>>> tp = 2, 3, 5 # on crée un tuple +>>> type(tp) + +>>> x, y, z = tp # les 3 variables x, y, z prennent les valeurs des 3 éléments du tuple +>>> x +2 +>>> y +3 +>>> z +5 +``` + +```python +>>> x, y = 33, 666 +>>> x, y = y, x # permutation +>>> x +666 +>>> y +33 +``` + + + +##### Lecture et initialisation d’une chaîne de caractères: + +```python +>>> s = input() +4 +>>> s +'4' +>>> type(s) + +``` + +##### Lecture et initialisation d’un tuple de valeurs: + +```python +>>> eval("2 + 2") +4 + +>>> t = eval(input()) +2, 3, 4, 5 +>>> t +(2, 3, 4, 5) +>>> type(t) + + +>>> t = eval(input()) +"alpha", "beta", "gamma" +>>> t +('alpha', 'beta', 'gamma') +>>> type(t) + + +``` + +##### Création d'une séquence à partir d'une autre: + +```python +>>> t = (1, 2, 3, 4) +>>> t +(1, 2, 3, 4) # tuple +>>> l = list(t) +>>> l +[1, 2, 3, 4] # liste + +>>> l = list("Bonjour") # str +>>> l +['B', 'o', 'n', 'j', 'o', 'u', 'r'] # liste + + +``` + diff --git a/docs/Programmation/Python/Python.md b/docs/Programmation/Python/index.md similarity index 93% rename from docs/Programmation/Python/Python.md rename to docs/Programmation/Python/index.md index d451918..d59153e 100644 --- a/docs/Programmation/Python/Python.md +++ b/docs/Programmation/Python/index.md @@ -3,10 +3,10 @@ 1. collections: - 1. [liste](liste.md) - 2. [dictionnaire](dictionnaire.md) - 3. [tuple](tuple.md) - 4. [set](set.md) + 1. [liste []](liste.md) + 2. [dictionnaire {}](dictionnaire.md) + 3. [tuple ()](tuple.md) + 4. [set {}](set.md) 2. [class - objet](class.md) 3. [date](date.md) 4. [fichiers](fichiers.md) @@ -25,6 +25,16 @@ https://www.w3schools.com/python/default.asp +| Hashable (non modifiable) | Unhashable | +| ------------------------- | --------------- | +| int | liste [] | +| float | set {} | +| bool | dictionnaire {} | +| str | | +| tuples () | | + + + #### Instruction de boucles ##### while: diff --git a/docs/Programmation/Python/json.md b/docs/Programmation/Python/json.md new file mode 100644 index 0000000..0c7c731 --- /dev/null +++ b/docs/Programmation/Python/json.md @@ -0,0 +1,26 @@ +# json + + + + + +```python +import json + +# En partant d'une donnée construite à partir de types de base +data = [ + # des types qui ne posent pas de problème + [1, 2, 'a', [3.23, 4.32], {'eric': 32, 'jean': 43}], + # un tuple + (1, 2, 3), +] + +# sauver ceci dans un fichier +with open("s1.json","w", encoding='utf-8') as json_output: + json.dump(data, json_output) + +# et relire le résultat +with open("s1.json", encoding='utf-8') as json_input: + data2 = json.load(json_input) +``` + diff --git a/docs/Programmation/Python/liste.md b/docs/Programmation/Python/liste.md index 9561134..b3b0375 100644 --- a/docs/Programmation/Python/liste.md +++ b/docs/Programmation/Python/liste.md @@ -251,6 +251,11 @@ False >>> a.extend(b) >>> print(a) [1, 2, 3, 4, 5, 6] + +>>> a.extend([7, 8, 9]) +>>> print(a) +[1, 2, 3, 7, 8, 9] + >>> c = a + b >>> print(c) [1, 2, 3, 4, 5, 6, 4, 5, 6] @@ -272,6 +277,21 @@ if "alpha" in thislist: print("Oui, 'alpha' est dans la liste") ``` +##### Liste d'éléments de types différents: + +```python +>>> s = [1, 3, 3.14, ("bon","jour"), [5, 7]] +>>> len(s) +5 +>>> len(s[3]) # tuple +2 +>>> len(s[3][1]) # tuple - str "jour" +4 +>>> s[4][1] = 666 # sous-liste - int 7 +>>> s +[1, 3, 3.14, ('bon', 'jour'), [5, 666]] +``` + #### Méthodes: diff --git a/docs/Programmation/Python/requests.md b/docs/Programmation/Python/requests.md new file mode 100644 index 0000000..ce31407 --- /dev/null +++ b/docs/Programmation/Python/requests.md @@ -0,0 +1,170 @@ +# Requests + + + +https://realpython.com/python-requests/ + +https://realpython.com/caching-external-api-requests/ + + + +```bash +pip3 install requests +``` + + + +#### Requête GET: + +```python +>>> import requests +>>> requests.get('https://api.github.com') + + +>>> requests.get('https://api.github.com', timeout=1) + +# nb de second avant un timeout +``` + +##### Status Code: + +```python +>>> response = requests.get('https://api.github.com') +>>> print(response) + +>>> response.status_code +200 +>>> if response.status_code == 200: +... print('Success!') +... elif response.status_code == 404: +... print('Not Found.') +... +Success! +``` + +```python +import requests +from requests.exceptions import HTTPError + +for url in ['https://api.github.com', 'https://api.github.com/invalid']: + try: + response = requests.get(url) + + # If the response was successful, no Exception will be raised + response.raise_for_status() + except HTTPError as http_err: + print(f'HTTP error occurred: {http_err}') # Python 3.6 + except Exception as err: + print(f'Other error occurred: {err}') # Python 3.6 + else: + print('Success!') + +# la 1ere url répond par un Success +# la 2nde par une erreur +``` + +##### Content: + +```python +# bytes +>>> response.content +b'{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}' + +# string +>>> response.encoding = 'utf-8' +>>> response.text + +# JSON +>>> response.json() +{'current_user_url': 'https://api.github.com/user', 'current_user_authorizations_html_url': 'https://github.com/settings/connections/applications{/client_id}', 'authorizations_url': 'https://api.github.com/authorizations', 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}', 'commit_search_url': 'https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}', 'emails_url': 'https://api.github.com/user/emails', 'emojis_url': 'https://api.github.com/emojis', 'events_url': 'https://api.github.com/events', 'feeds_url': 'https://api.github.com/feeds', 'followers_url': 'https://api.github.com/user/followers', 'following_url': 'https://api.github.com/user/following{/target}', 'gists_url': 'https://api.github.com/gists{/gist_id}', 'hub_url': 'https://api.github.com/hub', 'issue_search_url': 'https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}', 'issues_url': 'https://api.github.com/issues', 'keys_url': 'https://api.github.com/user/keys', 'notifications_url': 'https://api.github.com/notifications', 'organization_repositories_url': 'https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}', 'organization_url': 'https://api.github.com/orgs/{org}', 'public_gists_url': 'https://api.github.com/gists/public', 'rate_limit_url': 'https://api.github.com/rate_limit', 'repository_url': 'https://api.github.com/repos/{owner}/{repo}', 'repository_search_url': 'https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}', 'current_user_repositories_url': 'https://api.github.com/user/repos{?type,page,per_page,sort}', 'starred_url': 'https://api.github.com/user/starred{/owner}{/repo}', 'starred_gists_url': 'https://api.github.com/gists/starred', 'team_url': 'https://api.github.com/teams', 'user_url': 'https://api.github.com/users/{user}', 'user_organizations_url': 'https://api.github.com/user/orgs', 'user_repositories_url': 'https://api.github.com/users/{user}/repos{?type,page,per_page,sort}', 'user_search_url': 'https://api.github.com/search/users?q={query}{&page,per_page,sort,order}'} +# retourne un dictionnaire +``` + +##### Headers: + +```python +>>> response.headers +{'Server': 'GitHub.com', 'Date': 'Fri, 29 Mar 2019 15:32:44 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Status': '200 OK', 'X-RateLimit-Limit': '60', 'X-RateLimit-Remaining': '59', 'X-RateLimit-Reset': '1553877164', 'Cache-Control': 'public, max-age=60, s-maxage=60', 'Vary': 'Accept', 'ETag': 'W/"7dc470913f1fe9bb6c7355b50a0737bc"', 'X-GitHub-Media-Type': 'github.v3; format=json', 'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'deny', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'origin-when-cross-origin, strict-origin-when-cross-origin', 'Content-Security-Policy': "default-src 'none'", 'Content-Encoding': 'gzip', 'X-GitHub-Request-Id': 'B245:1134:87E5:14D2A:5C9E3A9C'} + +# retourne un dictionnaire + +>>> response.headers['Content-Type'] +'application/json; charset=utf-8' +``` + +##### Query strings parameters: + +```python +import requests + +# Search GitHub's repositories for requests +response = requests.get( + 'https://api.github.com/search/repositories', + params={'q': 'requests+language:python'}, +) + +# Inspect some attributes of the `requests` repository +json_response = response.json() +repository = json_response['items'][0] +print(f'Repository name: {repository["name"]}') # Python 3.6+ +print(f'Repository description: {repository["description"]}') # Python 3.6+ + +Repository name: requests +Repository description: Python HTTP Requests for Humans™ ✨🍰✨ +``` + +##### Autres méthodes HTTP: + +```python +>>> requests.post('https://httpbin.org/post', data={'key':'value'}) +>>> requests.put('https://httpbin.org/put', data={'key':'value'}) +>>> requests.delete('https://httpbin.org/delete') +>>> requests.head('https://httpbin.org/get') +>>> requests.patch('https://httpbin.org/patch', data={'key':'value'}) +>>> requests.options('https://httpbin.org/get') + +``` + + + +#### Requête POST: + +```python +>>> requests.post('https://httpbin.org/post', data={'key':'value'}) + +``` + +```python +>>> response = requests.post('https://httpbin.org/post', json={'key':'value'}) +>>> json_response = response.json() +>>> json_response['data'] +'{"key": "value"}' +>>> json_response['headers']['Content-Type'] +'application/json' +``` + +```python +>>> response = requests.post('https://httpbin.org/post', json={'key':'value'}) +>>> response.request.headers['Content-Type'] +'application/json' +>>> response.request.url +'https://httpbin.org/post' +>>> response.request.body +b'{"key": "value"}' +``` + + + +Authentification: + +```python +>>> from requests.auth import HTTPBasicAuth +>>> from getpass import getpass +>>> requests.get( +... 'https://api.github.com/user', +... auth=HTTPBasicAuth('bruno@xxxxx.info', getpass()) +... ) +Password: + +``` + diff --git a/docs/Programmation/Python/set.md b/docs/Programmation/Python/set.md index 65a938d..3691184 100644 --- a/docs/Programmation/Python/set.md +++ b/docs/Programmation/Python/set.md @@ -1,8 +1,8 @@ -# Set +# Set (ensemble) -Une liste est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter. +Un set est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter. @@ -12,6 +12,17 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p >>> un_set = {"alpha", "beta", "gamma"} >>> un_set {'alpha', 'beta', 'gamma'} +>>> type(un_set) + +``` + +```python +>>> autre_set = {"alpha", "beta", "gamma", "beta", "alpha"} +>>> len(autre_set) +3 +>>> autre_set +{'beta', 'alpha', 'gamma'} + ``` ```python @@ -54,6 +65,12 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p >>> un_set.remove("beta") >>> un_set {'gamma', 'alpha'} + +# Si on retire un élément qui n'existe pas => Erreur +>>> un_set.remove("delta") +Traceback (most recent call last): + File "", line 1, in +KeyError: 'delta' ``` ##### Supprimer un item (discard): @@ -63,6 +80,12 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p >>> un_set.discard("beta") >>> un_set {'gamma', 'alpha'} + +# Si on retire un élément qui n'existe pas. +>>> un_set = {"alpha", "beta", "gamma"} +>>> un_set.discard("delta") +>>> un_set +{'alpha', 'gamma', 'beta'} ``` ##### Vider un set: @@ -105,6 +128,23 @@ print("alpha" in un_set) True ``` +##### Set => pas d'indice: + +```python +>>> un_set = {"alpha", "beta", "gamma"} +>>> un_set[0] +Traceback (most recent call last): + File "", line 1, in +TypeError: 'set' object does not support indexing +``` + +##### Opérateurs: + +- `a | b` (union), +- `a & b` (intersection), +- `a - b` (différence), +- `a ^ b` (différence symétrique) + #### Méthodes: diff --git a/docs/Programmation/Python/string.md b/docs/Programmation/Python/string.md index c8c85d8..b5347ce 100644 --- a/docs/Programmation/Python/string.md +++ b/docs/Programmation/Python/string.md @@ -2,6 +2,51 @@ +```python +>>> mon_str = "bonjour" +>>> print(mon_str) +bonjour + +>>> long_str = """*********** +... * Bonjour * +... *********** +... """ +>>> long_str +'***********\n* Bonjour *\n***********\n' +>>> print(long_str) +*********** +* Bonjour * +*********** +``` + +```python +# Concaténation +>>> mon_str + " Bruno" +'bonjour Bruno' + +# Répétition +>>> "ha " * 5 +'ha ha ha ha ha ' + +# Longueur de la chaine +>>> len(mon_str) +7 + +# Indice +>>> mon_str[0] +'b' +>>> mon_str[6] +'r' +>>> mon_str[len(mon_str)-1] +'r' +>>> mon_str[-1] +'r' +>>> mon_str[-3] +'o' +``` + + + ##### str.count() ```python diff --git a/docs/Programmation/Python/zip.md b/docs/Programmation/Python/zip.md new file mode 100644 index 0000000..1e932cc --- /dev/null +++ b/docs/Programmation/Python/zip.md @@ -0,0 +1,39 @@ +# zip + + + +La fonction `zip` associe 2 listes et retourne une liste de tuples. + +```python +villes = ["Paris", "Rome", "Göteborg"] +pays = ["France", "Italie", "Suède"] + +print(list(zip(villes, pays))) + +for ville, etat in zip(villes, pays): + print(ville, " est la capitale de ", etat) + + +[('Paris', 'France'), ('Rome', 'Italie'), ('Göteborg', 'Suède')] +Paris est la capitale de France +Rome est la capitale de Italie +Göteborg est la capitale de Suède +``` + +Si le nombre d'item diffère: + +```python +villes = ["Paris", "Rome", "Göteborg"] +pays = ["France", "Italie", "Suède", "Suisse"] + +print(list(zip(villes, pays))) + +for ville, etat in zip(villes, pays): + print(ville, " est la capitale de ", etat) + +[('Paris', 'France'), ('Rome', 'Italie'), ('Göteborg', 'Suède')] +Paris est la capitale de France +Rome est la capitale de Italie +Göteborg est la capitale de Suède +``` + diff --git a/docs/macos/homebrew/brew-cask.md b/docs/macos/homebrew/brew-cask.md index 7cc20b3..912ac49 100644 --- a/docs/macos/homebrew/brew-cask.md +++ b/docs/macos/homebrew/brew-cask.md @@ -86,6 +86,8 @@ $ brew cask home ### Aller à la page du Cask: ```bash +$ brew cask home {{cask_name}} + $ brew cask home qlstephen ``` @@ -102,6 +104,17 @@ $ brew cask outdated +### Version du Cask: + +```bash +$ brew cask _stanza version {{cask_name}} + +$ brew cask _stanza version bettertouchtool +2.800 +``` + + + ### Installer les mises-à-jour: ```bash diff --git a/docs/macos/homebrew/brew.md b/docs/macos/homebrew/brew.md index de8a6cf..72e7616 100644 --- a/docs/macos/homebrew/brew.md +++ b/docs/macos/homebrew/brew.md @@ -293,6 +293,15 @@ $ brew uses x264 --installed ffmpeg ``` +```bash +$ brew list -1 | while read cask; do echo -ne "\x1B[1;34m $cask \x1B[0m"; brew uses $cask --installed | awk '{printf(" %s ", $0)}'; echo ""; done + ack + aom ffmpeg + apr apr-util httpd php php@7.2 + .../... + x264 ffmpeg +``` + ### Outils: diff --git a/docs/macos/node/node-js.md b/docs/macos/node/node-js.md index 85f8d94..1b86d81 100644 --- a/docs/macos/node/node-js.md +++ b/docs/macos/node/node-js.md @@ -150,6 +150,39 @@ Verify cache contents verified 2159 tarballs +#### Info sur un package: + +```bash +$ npm show cli + +# idem: +# npm info cli +# npm view cli + +cli@1.0.1 | MIT | deps: 2 | versions: 59 +A tool for rapidly building command line apps +http://github.com/node-js-libs/cli + +keywords: cli, command line, opts, parseopt, opt, args, console, argsparse, optparse, autocomplete, command, autocompletion + +dist +.tarball: https://registry.npmjs.org/cli/-/cli-1.0.1.tgz +.shasum: 22817534f24bfa4950c34d532d48ecbc621b8c14 + +dependencies: +exit: 0.1.2 glob: ^7.1.1 + +maintainers: +- cohara87 + +dist-tags: +latest: 1.0.1 + +published over a year ago by cohara87 +``` + + + #### Packages: [Rechercher un package](https://npms.io) diff --git a/docs/macos/python/pip.md b/docs/macos/python/pip.md index 567412b..a94ec6c 100644 --- a/docs/macos/python/pip.md +++ b/docs/macos/python/pip.md @@ -72,7 +72,9 @@ pip --no-cache-dir install mkdocs -### Installer un module (mkdocs): +### Installer des modules: + +#### Installer un module pour l'utilisateur courant (mkdocs): ```bash $ pip install --user mkdocs @@ -84,7 +86,7 @@ Les modules sont ici: -### Désinstaller un module: +#### Désinstaller un module: ```bash $ pip uninstall @@ -92,7 +94,7 @@ $ pip uninstall -### Installer une ancienne version d'un module: +#### Installer une version précise d'un module: ```bash $ pip3 show tornado @@ -109,12 +111,15 @@ Installing collected packages: tornado Successfully installed tornado-4.5.3 $ pip3 install 'tornado>=4.1.0,<4.5.3' +# Installe une version comprise entre 4.1.0 et 4.5.3 +$ pip3 install 'tornado~=4.5.2' +# Installe une version “==4.5.*” qui est aussi “>=4.5.2”. ``` -### Informations sur un module: +#### Informations sur un module: ```bash $ pip show @@ -133,7 +138,15 @@ Requires: tornado, PyYAML, click, Markdown, Jinja2, livereload -### Liste des modules installés: +#### Installer une liste de modules requis: + +```bash +$ pip install -r requirements.txt +``` + + + +#### Liste des modules installés: ```bash # --format=columns (par defaut) @@ -178,7 +191,9 @@ $ pip install .pybundle -### Liste des modules mis-à-jour: +### Mise-à-jour: + +#### Liste des modules mis-à-jour: ```bash $ pip list --outdated --format=columns @@ -225,7 +240,7 @@ $ pip3 list --outdated --format=json -### Mettre à jour un module: +#### Mettre à jour un module: ```bash $ pip install --user --upgrade diff --git a/docs/macos/python/virtuel.md b/docs/macos/python/virtuel.md index cd03112..a8bd821 100644 --- a/docs/macos/python/virtuel.md +++ b/docs/macos/python/virtuel.md @@ -2,6 +2,8 @@ +### venv + On crée un dossier pour regrouper tous les environnements virtuels: ```bash @@ -138,3 +140,16 @@ Le module installé dans l'environnement virtuel est disponible UNIQUEMENT dans [https://docs.python.org/fr/3/library/venv.html](https://docs.python.org/fr/3/library/venv.html) + + + + +### pyvenv + +#### Installer des modules pour un projet: + +```bash +cd myproject +pipenv install requests +``` + diff --git a/mkdocs.yml b/mkdocs.yml index c789e05..05072df 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -58,6 +58,7 @@ nav: - Django: macos/python/Django.md - pip: macos/python/pip.md - Python 3: macos/python/python3.md + - Environnement virtuel: macos/python/virtuel.md - Sécurité (Gatekeeper): macos/securite.md - ssh: - SSH: macos/ssh/ssh.md @@ -88,6 +89,22 @@ nav: - Plesk Onyx: - Index: Plesk/index.md - Ghost: Plesk/Ghost.md + - Programmation: + -Python: + - Index: Programmation/Python/index.md + - Classes: Programmation/Python/class.md + - Date: Programmation/Python/date.md + - Dictionnaire: Programmation/Python/dictionnaire.md + - Fabric SSH Python: Programmation/Python/fabric-ssh.md + - Fichiers: Programmation/Python/fichiers.md + - Fonctions: Programmation/Python/fonctions.md + - Boucle For: Programmation/Python/for.md + - In: Programmation/Python/in.md + - Listes: Programmation/Python/liste.md + - Les regex: Programmation/Python/regex.md + - Sets: Programmation/Python/set.md + - Strings: Programmation/Python/string.md + - Tuples: Programmation/Python/tuple.md - Raspberry: - Index: Raspberry/index.md - apt-get: Raspberry/apt-get.md