├── os
├── example_pipeline.py
├── os_module_puzzle.pdf
└── README.rst
├── cover.jpg
├── cover.png
├── re
├── regex.pdf
├── kingkong.py
├── exercises
│ ├── regex_sub.py
│ ├── regex_exercises.md
│ ├── regex_sub_solution.py
│ ├── regex_search.py
│ └── regex_solution.py
├── phone.py
├── fox.py
├── biological_seq
│ ├── finditer.py
│ └── SRC_HUMAN.fasta
└── README.rst
├── PuLP
├── bricks.png
├── bricks_solution.png
├── README.md
├── magic_sqare.py
├── BricksLinear.ipynb
└── bricks.svg
├── images
├── imap.png
├── wave.gif
├── balls.png
├── barplot.png
├── errorbars.png
├── histogram.png
├── lineplot.png
├── piechart.png
├── sinfunc.png
└── ipythonblocks.png
├── numpy
├── blur.png
├── dim.png
├── flip.png
├── roll.png
├── purple.png
├── mandelbrot.png
├── python_logo.png
├── mandelbrot.py
├── transform_logo.py
└── README.rst
├── oauth_git
├── run.sh
└── github.py
├── pillow
├── five.png
├── python_logo.png
├── snowflake3.png
├── carrots
│ ├── arial.ttf
│ ├── brain.png
│ ├── carrot.png
│ ├── step07_final.png
│ ├── step01-paste.py
│ ├── step02-resize.py
│ ├── step03-arrow.py
│ ├── step06-text.py
│ ├── step05-filters.py
│ ├── step04-gradient.py
│ └── step07-full_image.py
├── pylogo_warhol.png
├── dice_images
│ ├── drei.png
│ ├── eins.png
│ ├── vier.png
│ ├── zwei.png
│ ├── blank.png
│ ├── fuenf.png
│ ├── sechs.png
│ ├── wuerfel.png
│ ├── double_dice.png
│ └── wuerfel.py
├── flower_movie
│ ├── flower.jpg
│ ├── flower_movie.avi
│ └── flower_movie.py
├── half_size.py
├── dice.py
├── README.md
├── warhol.py
└── snowflake.py
├── scipy
├── fit.png
├── curve_fit.py
└── README.rst
├── moviepy
├── panda.png
├── end_credits.avi
├── end_credits.txt
└── end_credits.py
├── pandas
├── panda.png
├── hexpanda.png
├── README.rst
└── hexpanda.py
├── pydocx
├── hamlet.docx
├── read_word_doc.py
├── create_doc.py
└── README.md
├── tkinter
├── titanic.png
├── titanic2.png
├── README.rst
├── titanic.py
└── titanic_sinks.svg
├── wordcloud
├── cloud.png
├── README.md
└── create_wordcloud.py
├── matplotlib
├── barplot.png
├── errorbars.png
├── lineplot.png
├── piechart.png
├── scatterplot.png
├── lineplot.py
├── errorbars.py
├── balls.py
├── piechart.py
├── barplot.py
└── README.md
├── tqdm
├── progress_bar.py
└── README.rst
├── scikit_image
├── python_logo.png
├── wave
│ ├── out000.png
│ ├── out001.png
│ ├── out002.png
│ ├── out003.png
│ ├── out004.png
│ ├── out005.png
│ ├── out006.png
│ ├── out007.png
│ ├── out008.png
│ ├── out009.png
│ ├── out010.png
│ ├── out011.png
│ ├── out012.png
│ ├── out013.png
│ ├── out014.png
│ ├── out015.png
│ ├── out016.png
│ ├── out017.png
│ ├── out018.png
│ └── out019.png
├── README.md
└── wave_transform.py
├── random
├── random_order.py
├── example_random.py
├── random_set.py
└── README.rst
├── httpx
├── example_requests.py
├── search_with_parameters.py
└── README.rst
├── pytesseract
├── ocr.py
└── README.md
├── email
├── README.md
├── smtp_example.py
└── send_email.py
├── xml
├── hamlet.xml
├── parse_xml.py
├── write_xml.py
└── README.rst
├── turtle
├── fibo_spiral.py
├── snowflake.py
├── koch.py
├── dragon.py
└── many_snowflakes.py
├── fuzzywuzzy
├── README.md
└── fuzzy_search.py
├── pypdf2
├── merge.py
├── README.md
└── extras
│ ├── pdf.py
│ └── pdf2txt.py
├── vader
├── vader.py
└── README.rst
├── playwright
├── playwright_example.py
└── README.md
├── psycopg2
├── docker-compose.yml
└── crud.py
├── itertools
├── example_itertools.py
└── README.rst
├── networkx
├── README.md
├── city_pairs.csv
└── page_rank.py
├── beautiful_soup
├── README.md
└── example_bs4.py
├── folium
├── README.md
└── berlin_map.py
├── sqlalchemy
├── README.md
└── example_sqlalchemy.py
├── flask
├── README.md
├── run_flask_server.py
└── templates
│ └── main.html
├── sqlite3
├── README.md
└── example_sqlite.py
├── sklearn
├── example_sklearn.py
└── README.md
├── paramiko
└── ssh_task.py
├── pymongo
├── pymongo_connect.py
└── README.rst
├── curses
├── README.rst
└── pac.py
├── zipfile
└── README.rst
├── math
└── README.rst
├── LICENSE.TXT
├── json
└── README.rst
├── sys
└── README.rst
├── .gitignore
├── time
└── README.rst
├── ipyvolume
└── volume.ipynb
├── index.rst
├── ipywidgets
└── ipywidgets.ipynb
└── README.md
/os/example_pipeline.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/cover.jpg
--------------------------------------------------------------------------------
/cover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/cover.png
--------------------------------------------------------------------------------
/re/regex.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/re/regex.pdf
--------------------------------------------------------------------------------
/PuLP/bricks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/PuLP/bricks.png
--------------------------------------------------------------------------------
/images/imap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/imap.png
--------------------------------------------------------------------------------
/images/wave.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/wave.gif
--------------------------------------------------------------------------------
/numpy/blur.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/blur.png
--------------------------------------------------------------------------------
/numpy/dim.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/dim.png
--------------------------------------------------------------------------------
/numpy/flip.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/flip.png
--------------------------------------------------------------------------------
/numpy/roll.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/roll.png
--------------------------------------------------------------------------------
/oauth_git/run.sh:
--------------------------------------------------------------------------------
1 | export FLASK_APP=github.py
2 | export FLASK_DEBUG=True
3 | flask run
4 |
5 |
--------------------------------------------------------------------------------
/pillow/five.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/five.png
--------------------------------------------------------------------------------
/scipy/fit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scipy/fit.png
--------------------------------------------------------------------------------
/images/balls.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/balls.png
--------------------------------------------------------------------------------
/moviepy/panda.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/moviepy/panda.png
--------------------------------------------------------------------------------
/numpy/purple.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/purple.png
--------------------------------------------------------------------------------
/pandas/panda.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pandas/panda.png
--------------------------------------------------------------------------------
/images/barplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/barplot.png
--------------------------------------------------------------------------------
/images/errorbars.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/errorbars.png
--------------------------------------------------------------------------------
/images/histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/histogram.png
--------------------------------------------------------------------------------
/images/lineplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/lineplot.png
--------------------------------------------------------------------------------
/images/piechart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/piechart.png
--------------------------------------------------------------------------------
/images/sinfunc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/sinfunc.png
--------------------------------------------------------------------------------
/numpy/mandelbrot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/mandelbrot.png
--------------------------------------------------------------------------------
/pandas/hexpanda.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pandas/hexpanda.png
--------------------------------------------------------------------------------
/pydocx/hamlet.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pydocx/hamlet.docx
--------------------------------------------------------------------------------
/tkinter/titanic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/tkinter/titanic.png
--------------------------------------------------------------------------------
/tkinter/titanic2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/tkinter/titanic2.png
--------------------------------------------------------------------------------
/wordcloud/cloud.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/wordcloud/cloud.png
--------------------------------------------------------------------------------
/matplotlib/barplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/matplotlib/barplot.png
--------------------------------------------------------------------------------
/numpy/python_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/numpy/python_logo.png
--------------------------------------------------------------------------------
/pillow/python_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/python_logo.png
--------------------------------------------------------------------------------
/pillow/snowflake3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/snowflake3.png
--------------------------------------------------------------------------------
/PuLP/bricks_solution.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/PuLP/bricks_solution.png
--------------------------------------------------------------------------------
/images/ipythonblocks.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/images/ipythonblocks.png
--------------------------------------------------------------------------------
/matplotlib/errorbars.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/matplotlib/errorbars.png
--------------------------------------------------------------------------------
/matplotlib/lineplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/matplotlib/lineplot.png
--------------------------------------------------------------------------------
/matplotlib/piechart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/matplotlib/piechart.png
--------------------------------------------------------------------------------
/moviepy/end_credits.avi:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/moviepy/end_credits.avi
--------------------------------------------------------------------------------
/os/os_module_puzzle.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/os/os_module_puzzle.pdf
--------------------------------------------------------------------------------
/pillow/carrots/arial.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/carrots/arial.ttf
--------------------------------------------------------------------------------
/pillow/carrots/brain.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/carrots/brain.png
--------------------------------------------------------------------------------
/pillow/carrots/carrot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/carrots/carrot.png
--------------------------------------------------------------------------------
/pillow/pylogo_warhol.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/pylogo_warhol.png
--------------------------------------------------------------------------------
/matplotlib/scatterplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/matplotlib/scatterplot.png
--------------------------------------------------------------------------------
/pillow/dice_images/drei.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/drei.png
--------------------------------------------------------------------------------
/pillow/dice_images/eins.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/eins.png
--------------------------------------------------------------------------------
/pillow/dice_images/vier.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/vier.png
--------------------------------------------------------------------------------
/pillow/dice_images/zwei.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/zwei.png
--------------------------------------------------------------------------------
/tqdm/progress_bar.py:
--------------------------------------------------------------------------------
1 | import time
2 | from tqdm import tqdm
3 |
4 | for i in tqdm(range(100)):
5 | time.sleep(0.1)
6 |
--------------------------------------------------------------------------------
/pillow/dice_images/blank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/blank.png
--------------------------------------------------------------------------------
/pillow/dice_images/fuenf.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/fuenf.png
--------------------------------------------------------------------------------
/pillow/dice_images/sechs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/sechs.png
--------------------------------------------------------------------------------
/pillow/dice_images/wuerfel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/wuerfel.png
--------------------------------------------------------------------------------
/pillow/flower_movie/flower.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/flower_movie/flower.jpg
--------------------------------------------------------------------------------
/scikit_image/python_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/python_logo.png
--------------------------------------------------------------------------------
/scikit_image/wave/out000.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out000.png
--------------------------------------------------------------------------------
/scikit_image/wave/out001.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out001.png
--------------------------------------------------------------------------------
/scikit_image/wave/out002.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out002.png
--------------------------------------------------------------------------------
/scikit_image/wave/out003.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out003.png
--------------------------------------------------------------------------------
/scikit_image/wave/out004.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out004.png
--------------------------------------------------------------------------------
/scikit_image/wave/out005.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out005.png
--------------------------------------------------------------------------------
/scikit_image/wave/out006.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out006.png
--------------------------------------------------------------------------------
/scikit_image/wave/out007.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out007.png
--------------------------------------------------------------------------------
/scikit_image/wave/out008.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out008.png
--------------------------------------------------------------------------------
/scikit_image/wave/out009.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out009.png
--------------------------------------------------------------------------------
/scikit_image/wave/out010.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out010.png
--------------------------------------------------------------------------------
/scikit_image/wave/out011.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out011.png
--------------------------------------------------------------------------------
/scikit_image/wave/out012.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out012.png
--------------------------------------------------------------------------------
/scikit_image/wave/out013.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out013.png
--------------------------------------------------------------------------------
/scikit_image/wave/out014.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out014.png
--------------------------------------------------------------------------------
/scikit_image/wave/out015.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out015.png
--------------------------------------------------------------------------------
/scikit_image/wave/out016.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out016.png
--------------------------------------------------------------------------------
/scikit_image/wave/out017.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out017.png
--------------------------------------------------------------------------------
/scikit_image/wave/out018.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out018.png
--------------------------------------------------------------------------------
/scikit_image/wave/out019.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/scikit_image/wave/out019.png
--------------------------------------------------------------------------------
/pillow/carrots/step07_final.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/carrots/step07_final.png
--------------------------------------------------------------------------------
/random/random_order.py:
--------------------------------------------------------------------------------
1 | from random import shuffle
2 |
3 | data = ['A','B','C','D']
4 |
5 | shuffle(data)
6 | print(data)
7 |
--------------------------------------------------------------------------------
/pillow/dice_images/double_dice.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/dice_images/double_dice.png
--------------------------------------------------------------------------------
/pillow/flower_movie/flower_movie.avi:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/krother/Python3_Package_Examples/HEAD/pillow/flower_movie/flower_movie.avi
--------------------------------------------------------------------------------
/httpx/example_requests.py:
--------------------------------------------------------------------------------
1 |
2 | import httpx
3 |
4 | r = httpx.get('https://www.python.org')
5 | print(r.status_code)
6 | print(r.text[:1000])
7 |
--------------------------------------------------------------------------------
/pytesseract/ocr.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image
3 | import pytesseract
4 |
5 | im = Image.open('myimage.jpg')
6 | print(pytesseract.image_to_string(im))
7 |
--------------------------------------------------------------------------------
/email/README.md:
--------------------------------------------------------------------------------
1 |
2 | # email
3 |
4 | ### What is it good for?
5 |
6 | Sends emails. You still need to have a mail server (SMTP).
7 |
8 | ### Installed by default?
9 |
10 | yes
--------------------------------------------------------------------------------
/random/example_random.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | print(random.randint(1, 6)) # integer
4 | print(random.random()) # float
5 | print(random.gauss(0.0, 1.0)) # standard normal dist
6 |
--------------------------------------------------------------------------------
/xml/hamlet.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | the Prince of Denmark
4 | Ophelias father
5 |
6 |
--------------------------------------------------------------------------------
/pydocx/read_word_doc.py:
--------------------------------------------------------------------------------
1 |
2 | from docx import Document
3 |
4 | document = Document('hamlet.docx')
5 |
6 | print(document)
7 |
8 | for para in document.paragraphs:
9 | print(para.text)
10 |
--------------------------------------------------------------------------------
/turtle/fibo_spiral.py:
--------------------------------------------------------------------------------
1 |
2 | import turtle
3 |
4 | a = 1
5 | b = 1
6 |
7 | depth = 0
8 | maxdepth = 15
9 |
10 | while depth < maxdepth:
11 | turtle.circle(a, 90)
12 | a, b = b, a + b
13 | depth += 1
14 |
15 | input()
16 |
--------------------------------------------------------------------------------
/scikit_image/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Scikit-Image
3 |
4 | ### What it is good for?
5 |
6 | Advanced image filters and transformations
7 |
8 | ### Installed with Python or Anaconda
9 |
10 | no
11 |
12 | ## Example
13 |
14 | 
15 |
--------------------------------------------------------------------------------
/fuzzywuzzy/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Fuzzywuzzy
3 |
4 | ### What it is good for?
5 |
6 | Match strings with typos.
7 |
8 | ### Installed with Python or Anaconda
9 |
10 | no
11 |
12 | ### How to install it?
13 |
14 | :::text
15 | pip install fuzzywuzzy
16 |
--------------------------------------------------------------------------------
/pydocx/create_doc.py:
--------------------------------------------------------------------------------
1 |
2 | # Create a Word document:
3 |
4 | from docx import Document
5 |
6 | d = Document()
7 |
8 | d.add_heading('Hamlet')
9 | d.add_heading('dramatis personae', 2)
10 | d.add_paragraph('Hamlet, the Prince of Denmark')
11 |
12 | d.save('hamlet.docx')
13 |
--------------------------------------------------------------------------------
/pypdf2/merge.py:
--------------------------------------------------------------------------------
1 |
2 | from PyPDF2 import PdfFileMerger
3 |
4 | merger = PdfFileMerger()
5 |
6 | merger.append(open("doc1.pdf", "rb"))
7 | merger.append(open("doc2.pdf", "rb"))
8 |
9 | # Write to an output PDF document
10 | output = open("result.pdf", "wb")
11 | merger.write(output)
12 |
--------------------------------------------------------------------------------
/httpx/search_with_parameters.py:
--------------------------------------------------------------------------------
1 |
2 | import httpx
3 |
4 | # Search scientific articles on PubMed:
5 | url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
6 | param_dict = {'db':'pubmed', 'term':'escherichia', 'rettype':'uilist'}
7 |
8 | r = httpx.get(url, params=param_dict)
9 | print(r.text)
10 |
--------------------------------------------------------------------------------
/random/random_set.py:
--------------------------------------------------------------------------------
1 |
2 | import random
3 |
4 | # random set with repeats
5 | ALPHABET = list('AGCT')
6 | dna = [random.choice(ALPHABET) for i in range(50)]
7 | print(''.join(dna))
8 |
9 |
10 | # random set without repeats
11 | NUMBERS = range(1, 101)
12 | print(random.sample(NUMBERS, 10))
13 |
--------------------------------------------------------------------------------
/pillow/carrots/step01-paste.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image
3 |
4 | img = Image.new('RGBA', (800, 500), "white")
5 |
6 | carrot = Image.open('carrot.png')
7 | brain = Image.open('brain.png')
8 |
9 | img.paste(carrot, (100, 80))
10 | img.paste(brain, (500, 100))
11 |
12 | img.save('step01.png')
13 |
14 |
--------------------------------------------------------------------------------
/re/kingkong.py:
--------------------------------------------------------------------------------
1 | """
2 | Advanced example:
3 | Why is humpty-dumpty not matched?
4 | """
5 |
6 | import re
7 |
8 | text = """
9 | ping-pong
10 | king-kong
11 | flip-flop
12 | hip-hop
13 | humpty-dumpty
14 | """
15 |
16 | for line in text.split():
17 | if re.search(r"^(\w+)i(\w+)[- ]\1o\2", line):
18 | print(line)
19 |
--------------------------------------------------------------------------------
/pytesseract/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Pytesseract
3 |
4 | ### What it is good for?
5 |
6 | Extract text from images (Optical Character Recognition / OCR).
7 |
8 | ### Installed with Python or Anaconda
9 |
10 | no
11 |
12 | ### How to install it?
13 |
14 | :::text
15 | sudo apt install tesseract-ocr
16 | pip install pytesseract
17 |
--------------------------------------------------------------------------------
/vader/vader.py:
--------------------------------------------------------------------------------
1 | from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
2 |
3 | s = SentimentIntensityAnalyzer()
4 |
5 | text_a = "\ntoday is a great day to code!"
6 | text_b = "\nsyntax errors really suck"
7 |
8 | print(text_a)
9 | print(s.polarity_scores(text_a))
10 |
11 | print(text_b)
12 | print(s.polarity_scores(text_b))
13 |
--------------------------------------------------------------------------------
/fuzzywuzzy/fuzzy_search.py:
--------------------------------------------------------------------------------
1 |
2 | from fuzzywuzzy import process
3 |
4 | movie_titles = ['Titanic', 'Star Wars', 'Breakfast at Tiffanys']
5 |
6 | # find the most similar match and a quality score
7 | print(process.extractOne('Star Wors', movie_titles))
8 | print(process.extractOne('Star', movie_titles))
9 | print(process.extractOne('Tutunuc', movie_titles))
10 |
--------------------------------------------------------------------------------
/tqdm/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to create a progress bar on the console?
3 | ============================================
4 |
5 | The `tqdm` library has just one purpose: Drawing progress bars.
6 |
7 | Install it with:
8 |
9 | .. code::
10 |
11 | pip install tqdm
12 |
13 | Here is an example code piece:
14 |
15 | .. literalinclude:: progress_bar.py
16 |
--------------------------------------------------------------------------------
/pillow/carrots/step02-resize.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image
3 |
4 | img = Image.new('RGBA', (800, 500), "white")
5 |
6 | carrot = Image.open('carrot.png')
7 | brain = Image.open('brain.png')
8 |
9 | carrot = carrot.resize((250, 250))
10 |
11 | img.paste(carrot, (100, 80))
12 | img.paste(brain, (500, 100))
13 |
14 | img.save('step02.png')
15 |
16 |
--------------------------------------------------------------------------------
/playwright/playwright_example.py:
--------------------------------------------------------------------------------
1 |
2 | from playwright.sync_api import sync_playwright
3 |
4 |
5 | with sync_playwright() as p:
6 | browser = p.firefox.launch(headless=False)
7 | page = browser.new_page()
8 | page.goto("http://www.academis.eu")
9 | page.is_visible('#headline')
10 | html = page.inner_html('#headline')
11 | print(html[:190])
12 |
--------------------------------------------------------------------------------
/xml/parse_xml.py:
--------------------------------------------------------------------------------
1 |
2 | from xml.dom.minidom import parse
3 |
4 | document = parse('hamlet.xml')
5 |
6 | actors = document.getElementsByTagName("actor")
7 | for act in actors:
8 | name = act.getAttribute('name')
9 | for node in act.childNodes:
10 | if node.nodeType == node.TEXT_NODE:
11 | print("{} - {}".format(name, node.data))
12 |
--------------------------------------------------------------------------------
/wordcloud/README.md:
--------------------------------------------------------------------------------
1 |
2 | # wordcloud
3 |
4 | ### What it does
5 |
6 | `wordcloud` draws word clouds from a string of words.
7 |
8 | It allows to create clouds in arbitrary shapes.
9 |
10 | 
11 |
12 | ### Installed with Python or Anaconda
13 |
14 | no
15 |
16 | ### How to install it
17 |
18 | :::text
19 | pip install wordcloud
20 |
21 |
--------------------------------------------------------------------------------
/pillow/half_size.py:
--------------------------------------------------------------------------------
1 |
2 | # Convert all `.png` images in the directory to half their size
3 | from PIL import Image
4 | import os
5 |
6 | for filename in os.listdir('.'):
7 | if filename.endswith('.png'):
8 | im = Image.open(filename)
9 | x = im.size[0] // 2
10 | y = im.size[1] // 2
11 | small = im.resize((x, y))
12 | small.save('sm_' + filename)
13 |
--------------------------------------------------------------------------------
/matplotlib/lineplot.py:
--------------------------------------------------------------------------------
1 |
2 | from matplotlib import pyplot as plt
3 | import math
4 |
5 | plt.figure()
6 |
7 | x = [0.01 * i for i in range(1000)]
8 | y = [math.sin(j) for j in x]
9 |
10 | plt.plot(x, y, 'k-', linewidth=1)
11 | plt.text(5, 0, "$y = sin(x)$", horizontalalignment='center', fontsize=20)
12 | plt.axis([0, 3*math.pi, -1.2, 1.2])
13 |
14 | plt.savefig('sinfunc.png')
15 |
--------------------------------------------------------------------------------
/psycopg2/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.8'
2 |
3 | services:
4 | db:
5 | image: postgres:latest
6 | container_name: postgres
7 | environment:
8 | POSTGRES_USER: myuser
9 | POSTGRES_PASSWORD: mypassword
10 | POSTGRES_DB: mydatabase
11 | ports:
12 | - "8000:5432"
13 | volumes:
14 | - pgdata:/home/kristian/pgdata
15 |
16 | volumes:
17 | pgdata:
18 |
--------------------------------------------------------------------------------
/re/exercises/regex_sub.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | text = "7 apples, 24 bananas, 14 carrots, and oranges are fruit"
4 |
5 | # replace one word by another
6 | result = re.sub('','',text)
7 | assert result == "7 apples, 24 bananas, 14 pears, and oranges are fruit"
8 |
9 | # remove all numbers
10 | result = re.sub('','',text)
11 | assert result == "apples, bananas, carrots, and oranges are fruit"
12 |
--------------------------------------------------------------------------------
/pillow/dice.py:
--------------------------------------------------------------------------------
1 | # generate dice image
2 |
3 | from PIL import Image
4 | from PIL import ImageDraw
5 |
6 | five = Image.new('RGB', (64,64), '#80b940')
7 | d = ImageDraw.Draw(five)
8 |
9 | d.ellipse(((26, 26), (38, 38)), '#ffffff')
10 | d.ellipse(((10, 10), (22, 22)), '#ffffff')
11 | d.ellipse(((42, 42), (54, 54)), '#ffffff')
12 | d.ellipse(((10, 42), (22, 54)), '#ffffff')
13 | d.ellipse(((42, 10), (54, 22)), '#ffffff')
14 | five.save('five.png')
15 |
--------------------------------------------------------------------------------
/turtle/snowflake.py:
--------------------------------------------------------------------------------
1 |
2 | from turtle import forward, left, right, width, color, clearscreen
3 |
4 | clearscreen()
5 | color("lightblue")
6 | width(3)
7 |
8 | for i in range(6):
9 | forward(50)
10 | left(60)
11 | forward(25)
12 | left(180)
13 | forward(25)
14 | left(60)
15 | forward(25)
16 | left(180)
17 | forward(25)
18 | right(120)
19 | forward(25)
20 | left(180)
21 | forward(75)
22 | left(120)
23 |
--------------------------------------------------------------------------------
/re/phone.py:
--------------------------------------------------------------------------------
1 |
2 | import re
3 |
4 | phone = re.compile("(00|0 0|\+)\s*4\s*9[0-9 ]+")
5 |
6 | examples = [
7 | "0049 190 34 57 90",
8 | "+49 190 34 57 90",
9 | "00 00 00 49 190 34 57 90 33",
10 | "00 49 190 34 57 90",
11 | "0049190345790",
12 | "+48 60 60 606 9",
13 | "+41 55 55 55 55"
14 | ]
15 |
16 | for e in examples:
17 | if phone.match(e):
18 | print(e, "is a German phone number")
19 | else:
20 | print(e, "is some other number")
21 |
--------------------------------------------------------------------------------
/re/fox.py:
--------------------------------------------------------------------------------
1 |
2 | import re
3 |
4 | text = "the quick brown fox jumps over the lazy dog"
5 |
6 | # Search for `o` and show adjacent characters:
7 | print(re.findall(".o.", text))
8 |
9 | # Search for three-letter words enclosed by whitespace:
10 | print(re.findall("\s(\wo\w)\s*", text))
11 |
12 | # Substitute any of `dflj` by a `w`:
13 | print(re.sub("[dflj]", "w", text))
14 |
15 | # Check if `jumps` or `swims` occurs and return details:
16 | print(re.search('jumps|swims', text))
17 |
--------------------------------------------------------------------------------
/pypdf2/README.md:
--------------------------------------------------------------------------------
1 |
2 | # PyPDF2
3 |
4 | ### What is it good for?
5 |
6 | `PyPDF2` manipulates PDF documents on the page level, e.g. merging two or more PDFs.
7 |
8 |
9 | ### Installed with Python or Anaconda
10 |
11 | no
12 |
13 | ### How to install it?
14 |
15 | :::text
16 | pip install pypdf2
17 |
18 | ### Where to learn more?
19 |
20 | There are a few other PDF libraries that allow to read PDFs or create them from scratch.
21 | See :::file extras/pdf.py or :::file extras/pdf2txt.py
22 |
23 |
--------------------------------------------------------------------------------
/itertools/example_itertools.py:
--------------------------------------------------------------------------------
1 |
2 | import itertools
3 |
4 | # concatenate lists
5 | ch = itertools.chain([1, 2], [3, 4], [5, 6])
6 | print(list(ch))
7 |
8 | # repeat lists
9 | print(list(itertools.repeat([1, 2], 3)))
10 |
11 | # Permutations and combinations of list elements:
12 | p = itertools.permutations([1, 2, 3])
13 | print(list(p))
14 |
15 | c = itertools.combinations([1, 2, 3], 2)
16 | print(list(c))
17 |
18 | # Pairwise combinations
19 | pr = itertools.product("ABC", [1, 2, 3])
20 | print(list(pr))
21 |
--------------------------------------------------------------------------------
/matplotlib/errorbars.py:
--------------------------------------------------------------------------------
1 |
2 | from matplotlib import pyplot as plt
3 |
4 | plt.figure()
5 |
6 | # scatterplot with error bars
7 | x1 = [0.1, 0.3, 0.5, 0.6, 0.7]
8 | y1 = [1, 5, 5, 10, 20]
9 | err1 = [3, 3, 3, 10, 12]
10 | plt.errorbar(x1, y1, err1 , fmt='ro')
11 |
12 | # barplot with error bars
13 | x2 = [1.1, 1.2, 1.3, 1.4, 1.5]
14 | y2 = [10, 15, 10, 15, 17]
15 | err2 = (2, 3, 4, 1, 2)
16 | width = 0.05
17 | plt.bar(x2, y2, width, color='r', yerr=err2, ecolor="black")
18 |
19 | plt.savefig('errorbars.png')
20 |
--------------------------------------------------------------------------------
/networkx/README.md:
--------------------------------------------------------------------------------
1 |
2 | # NetworkX
3 |
4 | ### What it does
5 |
6 | `NetworkX` processes and plots graphs.
7 |
8 | ### Installed with Python or Anaconda
9 |
10 | no
11 |
12 | ### How to install it
13 |
14 | :::text
15 | pip install networkx
16 |
17 | ### Example: PageRank
18 |
19 | The example below uses the [PageRank algorithm](https://en.wikipedia.org/wiki/PageRank) to calculate the importance (centrality) of nodes in the graph.
20 |
21 | The code uses the file :::file city_pairs.csv .
22 |
23 |
--------------------------------------------------------------------------------
/xml/write_xml.py:
--------------------------------------------------------------------------------
1 |
2 | import xml.etree.ElementTree as ET
3 |
4 | data = ET.Element('play')
5 |
6 | # add subtags with attributes
7 | actors = ET.SubElement(data, 'actors')
8 |
9 | ham = ET.SubElement(actors, 'actor')
10 | ham.set('name', 'Hamlet')
11 | ham.text = "Hamlet, the Prince of Denmark"
12 |
13 | oph = ET.SubElement(actors, 'actress')
14 | oph.set('name', 'Ophelia')
15 | oph.text = "Ophelia"
16 |
17 | # write as a binary string
18 | with open("actors.xml", "wb") as f:
19 | f.write(ET.tostring(data))
20 |
--------------------------------------------------------------------------------
/beautiful_soup/README.md:
--------------------------------------------------------------------------------
1 |
2 | # BeautifulSoup
3 |
4 | ### What it is good for?
5 |
6 | BeautifulSoup parses HTML pages.
7 |
8 | Beautiful soup is much, much easier to use than the default HTML parser installed with Python.
9 |
10 | ### Installed with Python or Anaconda
11 |
12 | no
13 |
14 | ### How to install it?
15 |
16 | :::text
17 | pip install bs4
18 |
19 | ### Where to learn more?
20 |
21 | [http://www.crummy.com/software/BeautifulSoup/bs4/doc/](http://www.crummy.com/software/BeautifulSoup/bs4/doc/)
22 |
--------------------------------------------------------------------------------
/folium/README.md:
--------------------------------------------------------------------------------
1 |
2 | # folium
3 |
4 | ### What it does
5 |
6 | `folium` plots maps.
7 |
8 | The package is built on top of the JavaScript library **leaflet** (hence the name).
9 | It produces HTML documents:
10 |
11 | ### Installed with Python or Anaconda
12 |
13 | no
14 |
15 | ### How to install it
16 |
17 | :::text
18 | pip install folium
19 |
20 | ### See also
21 |
22 | [https://python-visualization.github.io/folium/quickstart.html](https://python-visualization.github.io/folium/quickstart.html)
23 |
24 |
--------------------------------------------------------------------------------
/pydocx/README.md:
--------------------------------------------------------------------------------
1 |
2 | # python-docx
3 |
4 | ### What it is good for?
5 |
6 | `python-docx` reads and writes MS Word documents.
7 |
8 | A straightforward library to access documents in MS Word format. Available features include text, labeled sections, pictures and tables.
9 |
10 | ### Installed with Python or Anaconda
11 |
12 | no
13 |
14 | ### How to install it?
15 |
16 | :::text
17 | pip install python-docx
18 |
19 | ### Where to learn more?
20 |
21 | [https://python-docx.readthedocs.org](https://python-docx.readthedocs.org)
22 |
--------------------------------------------------------------------------------
/re/exercises/regex_exercises.md:
--------------------------------------------------------------------------------
1 | ## Regex and Text Processing exercises
2 |
3 | Wörter: Wie oft kommt Löw im Text vor?
4 |
5 | Wörter in Tabelle schreiben
6 |
7 | Lukas Podolski einlesen
8 |
9 | Regex Crossword lösen
10 |
11 | Warum manchmal nur ein Land?
12 |
13 | Spielergebnisse parsen
14 |
15 | Count number of words in a text.
16 |
17 | Count most frequent character in a text.
18 |
19 | Count which pairs of subsequent words occurs most often.
20 |
21 | Calculate the entropy of some data.
22 |
23 | Filter certain words out of a text.
24 |
--------------------------------------------------------------------------------
/sqlalchemy/README.md:
--------------------------------------------------------------------------------
1 |
2 | # SQLAlchemy
3 |
4 | ### What it is good for?
5 |
6 | Create and use a *SQL* databases.
7 |
8 | SQLAlchemy is a generic interface to all databases.
9 | You can use it so connect to MySQL, PostGreSQL, Oracle(?), SQLite and many others with the same or very similar code.
10 |
11 | It contains a powerful ORM (Object-Relational Mapper) where you define your tables as classes.
12 |
13 | ### Installed with Python?
14 |
15 | no
16 |
17 | ### Where to learn more?
18 |
19 | [http://sqlalchemy.org/](http://sqlalchemy.org/)
20 |
--------------------------------------------------------------------------------
/itertools/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to flatten a list of lists?
3 | ===============================
4 |
5 | The builtin module `itertools` contains plenty of functions to work with lists and iterators.
6 | Most functions in this module return *iterators* themselves, so they can be consumed by loops or `next()`. You can also convert them to a list.
7 |
8 | Below you find a few examples:
9 |
10 | .. literalinclude:: example_itertools.py
11 |
12 | .. seealso::
13 |
14 | `Documentation of the itertools module `__
15 |
--------------------------------------------------------------------------------
/matplotlib/balls.py:
--------------------------------------------------------------------------------
1 |
2 | import math
3 | import random
4 | from matplotlib import pyplot as plt
5 |
6 | # prepare random data
7 | n_balls = 50
8 | x = [random.triangular() for i in range(n_balls)]
9 | y = [random.gauss(0.5, 0.15) for i in range(n_balls)]
10 | colors = [random.randint(1, 4) for i in range(n_balls)]
11 | areas = [math.pi * random.randint(5, 15)**2 for i in range(n_balls)]
12 |
13 | # draw the figure
14 | plt.figure()
15 | plt.scatter(x, y, s=areas, c=colors, alpha=0.75)
16 | plt.axis([0.0, 1.0, 0.0, 1.0])
17 | plt.savefig('balls.png')
18 |
--------------------------------------------------------------------------------
/flask/README.md:
--------------------------------------------------------------------------------
1 |
2 | # flask
3 |
4 | ### What is it good for?
5 |
6 | `flask` is a lightweight web server.
7 |
8 | You can create APIs and simple web pages with very little code.
9 |
10 |
11 | ### Installed with Python or Anaconda
12 |
13 | no
14 |
15 | ### How to install it?
16 |
17 | :::text
18 | pip install flask
19 |
20 | ### Where to learn more?
21 |
22 | * [flask.palletsprojects.com](https://flask.palletsprojects.com)
23 | * [The Flask Mega Tutorial](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) by Miguel Grinberg
24 |
--------------------------------------------------------------------------------
/flask/run_flask_server.py:
--------------------------------------------------------------------------------
1 |
2 | from flask import Flask, render_template
3 |
4 | app = Flask(__name__)
5 |
6 | @app.route("/hello")
7 | def hello():
8 | return """Hello World! """
9 |
10 | @app.route("/hello/")
11 | def hello_name(name):
12 | return f"""Hello {name}! """
13 |
14 | @app.route("/")
15 | def main():
16 | return render_template('main.html',
17 | title='Start page',
18 | animals=['cat', 'dog', 'fish', 'platypus']
19 | )
20 |
21 |
22 | if __name__ == "__main__":
23 | app.run()
24 |
--------------------------------------------------------------------------------
/tkinter/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to create a graphical desktop window?
3 | =========================================
4 |
5 | Tkinter allows you to create graphical interfaces.
6 | It's a bit oldschool and the class structure appears convoluted in 2025, but some might want to try it anyway.
7 |
8 | `Tk` is installed with Python by default.
9 |
10 | Here is an example program with two images:
11 |
12 | - :download:`titanic.py`
13 | - :download:`titanic.png`
14 | - :download:`titanic2.png`
15 |
16 | .. seealso::
17 |
18 | `Tkinter documentation `__
19 |
--------------------------------------------------------------------------------
/vader/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to calculate a simple sentiment score for a text?
3 | =====================================================
4 |
5 | The `vader` libary provides a straightforward sentiment score.
6 | It is based on a word list, so it is not super accurate and does not catch any nuances.
7 | But it is fast and sufficient for a quick scan.
8 |
9 | Installation
10 | ------------
11 |
12 | ::
13 |
14 | pip install vaderSentiment
15 |
16 | Usage
17 | -----
18 |
19 | .. literalinclude:: vader.py
20 |
21 | The sentiment includes a positive, negative and neutral score, which add up to 1.0.
22 |
--------------------------------------------------------------------------------
/PuLP/README.md:
--------------------------------------------------------------------------------
1 |
2 | # PuLP
3 |
4 | ### What it is good for?
5 |
6 | PuLP is a simple **Linear Problem Solver**. It solves systems with many linear equations, e.g. Sudokus, scheduling trains and many more. For complex LES problems you will need commercial software (like Gurobi), but PuLP helps you get the taste of it.
7 |
8 | ### Installed with Python or Anaconda
9 |
10 | no
11 |
12 | ### How to install it?
13 |
14 | :::text
15 | pip install pulp
16 |
17 | ## Example
18 |
19 | Solve a magic square (insert the numbers 1..9 in to a 3x3 square
20 | so that all rows and columns sum up to 15).
21 |
--------------------------------------------------------------------------------
/flask/templates/main.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | {{title}}
11 |
12 |
13 |
14 |
15 | {{ title }}
16 | Hello World page
17 |
18 | {% for ani in animals %}
19 | {{ ani }}
20 | {% endfor %}
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/beautiful_soup/example_bs4.py:
--------------------------------------------------------------------------------
1 | from bs4 import BeautifulSoup
2 |
3 | html = """
4 | Hamlet
5 |
6 | Hamlet
7 | Polonius
8 | Ophelia
9 | Claudius
10 |
11 |
12 | William Shakespeare
13 |
14 | """
15 |
16 | soup = BeautifulSoup(html, "lxml")
17 |
18 | for ul in soup.find_all('ul'):
19 | if "cast" in ul.get('class', []):
20 | for item in ul.find_all('li'):
21 | print(item.get_text(), end=", ")
22 | print()
23 |
--------------------------------------------------------------------------------
/random/README.rst:
--------------------------------------------------------------------------------
1 |
2 |
3 | How to generate random numbers?
4 | -------------------------------
5 |
6 | .. literalinclude:: example_random.py
7 |
8 | How to put a list in random order?
9 | ----------------------------------
10 |
11 | .. literalinclude:: random_order.py
12 |
13 | How to pick a random sample?
14 | ----------------------------
15 |
16 | .. literalinclude:: random_set.py
17 |
18 | .. seealso::
19 |
20 | The `random` module generates random numbers from common distributions.
21 | It does not require installation.
22 |
23 | `Documentation for the random module `__
22 |
--------------------------------------------------------------------------------
/numpy/mandelbrot.py:
--------------------------------------------------------------------------------
1 | """
2 | Drawing the Mandelbrot set
3 | based on R code by Myles Harrison
4 | http://www.everydayanalytics.ca
5 | """
6 | import numpy as np
7 | from PIL import Image
8 |
9 |
10 | SIZE = 500
11 |
12 | x = np.linspace(-2.0, 1.0, SIZE)
13 | y = np.linspace(-1.5, 1.5, SIZE)
14 |
15 | ones = np.ones(SIZE)
16 |
17 | c = np.outer(x, ones) + 1j * np.outer(ones, y)
18 |
19 | z = np.zeros((SIZE, SIZE)) * 1j
20 | k = np.zeros((SIZE, SIZE))
21 |
22 | for i in range(100):
23 | index = z < 2
24 | z[index] = z[index] ** 2 + c[index]
25 | k[index] = k[index] + 1
26 |
27 |
28 | # save the image
29 | im = Image.fromarray(k).convert('RGB')
30 | im.save('mandelbrot.png')
31 |
--------------------------------------------------------------------------------
/folium/berlin_map.py:
--------------------------------------------------------------------------------
1 | import folium
2 |
3 |
4 | berlin_map = folium.Map(location=[52.50, 13.35], zoom_start=13)
5 |
6 | folium.Marker(
7 | (52.5157669, 13.3771557),
8 | popup="Brandenburger Tor",
9 | icon=folium.Icon(icon="map-marker", color="blue"),
10 | ).add_to(berlin_map)
11 |
12 | folium.Marker(
13 | (52.5141987, 13.350284),
14 | popup="Siegessäule",
15 | icon=folium.Icon(icon="star", color="orange"),
16 | ).add_to(berlin_map)
17 |
18 | folium.Marker(
19 | (52.4681216, 13.332078), popup="Home", icon=folium.Icon(icon="home", color="green")
20 | ).add_to(berlin_map)
21 |
22 | berlin_map.save("berlin_map.html")
23 |
24 | berlin_map # in Jupyter to see the result
25 |
--------------------------------------------------------------------------------
/re/biological_seq/finditer.py:
--------------------------------------------------------------------------------
1 | '''
2 |
3 | Pattern Matching - Example
4 |
5 | The script checks if the SRC_HUMAN sequence has
6 | the following phosphorylation site: 'R(.)[ST][^P]' and prints
7 | the match, the start and end of the match and the
8 | amino acid in the second position of the match.
9 |
10 | '''
11 |
12 | import re
13 |
14 | F = open('SRC_HUMAN.fasta')
15 | seq = ''
16 | for line in F:
17 | if line[0] != '>':
18 | seq = seq + line.strip()
19 |
20 | S = 'R(.)[ST][^P]'
21 | regexp = re.compile(S)
22 | iter = regexp.finditer(seq)
23 | for s in iter:
24 | print("match:", s.group(0))
25 | print("start, end", s.span())
26 | print("aa in second position:", s.group(1))
27 |
--------------------------------------------------------------------------------
/re/biological_seq/SRC_HUMAN.fasta:
--------------------------------------------------------------------------------
1 | >sp|P12931|SRC_HUMAN Proto-oncogene tyrosine-protein kinase Src OS=Homo sapiens GN=SRC PE=1 SV=3
2 | MGSNKSKPKDASQRRRSLEPAENVHGAGGGAFPASQTPSKPASADGHRGPSAAFAPAAAE
3 | PKLFGGFNSSDTVTSPQRAGPLAGGVTTFVALYDYESRTETDLSFKKGERLQIVNNTEGD
4 | WWLAHSLSTGQTGYIPSNYVAPSDSIQAEEWYFGKITRRESERLLLNAENPRGTFLVRES
5 | ETTKGAYCLSVSDFDNAKGLNVKHYKVALITGGGSGITSRTQFNSLQQLVAYYSKHADGL
6 | CHRLTTVCPTSKPQTQGLAKDAWEIPRESLRLEVKLGQGCFGEVWMGTWNGTTRVAIKTL
7 | KPGTMSPEAFLQEAQVMKKLRHEKLVQLYAVVSEEPIYIVTEYMSKGSLLDFLKGETGKY
8 | LRLPQLVDMAAQIASGMAYVERMNYVHRDLRAANILVGENLVCKVADFGLARLIEDNEYT
9 | ARQGAKFPIKWTAPEAALYGRFTIKSDVWSFGILLTELTTKGRVPYPGMVNREVLDQVER
10 | GYRMPCPPECPESLHDLMCQCWRKEPEERPTFEYLQAFLEDYFTSTEPQYQPGENL
11 |
--------------------------------------------------------------------------------
/matplotlib/barplot.py:
--------------------------------------------------------------------------------
1 |
2 | from matplotlib import pyplot as plt
3 |
4 | nucleotides = ["A", "G", "C", "U"]
5 |
6 | counts = [
7 | [606, 1024, 759, 398],
8 | [762, 912, 639, 591],
9 | ]
10 |
11 | plt.figure()
12 |
13 | x1 = [2.0, 4.0, 6.0, 8.0]
14 | x2 = [x - 0.5 for x in x1]
15 |
16 | plt.xticks(x1, nucleotides)
17 |
18 | plt.bar(x1, counts[1], width=0.5, color="#cccccc", label="E.coli 23S")
19 | plt.bar(x2, counts[0], width=0.5, color="#808080", label="T.thermophilus 23S")
20 |
21 | plt.legend()
22 | plt.axis([1.0, 9.0, 0, 1200])
23 |
24 | plt.title('RNA nucleotides in the ribosome')
25 | plt.xlabel('RNA')
26 | plt.ylabel('base count')
27 | plt.savefig('barplot.png')
28 |
--------------------------------------------------------------------------------
/numpy/transform_logo.py:
--------------------------------------------------------------------------------
1 | #
2 | # more examples that transform the Python logo
3 | #
4 |
5 | import numpy as np
6 | from PIL import Image
7 |
8 |
9 | def imsave(filename, a):
10 | Image.fromarray(a).convert('RGB').save(filename)
11 |
12 | im = Image.open('python_logo.png')
13 | a = np.array(im)
14 |
15 |
16 | # reduce brightness
17 | d = a // 2
18 | imsave('dim.png', d)
19 |
20 | # flip over
21 | b = a[:,::-1,:]
22 | imsave('flip.png', b)
23 |
24 | # remove color channel
25 | g = np.array(a)
26 | g[:,:,1] = 0
27 | imsave('purple.png', g)
28 |
29 | # rolling displacement
30 | roll = np.array(a)
31 | roll[:,:,2] = np.roll(roll[:,:,2], 25)
32 | roll[:,:,1] = np.roll(roll[:,:,1], 50)
33 | imsave('roll.png', roll)
34 |
--------------------------------------------------------------------------------
/scipy/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to optimize parameters of a function with SciPy?
3 | ====================================================
4 |
5 | .. figure:: fit.png
6 |
7 | Scipy is a Python library for **numerical analyses** like fitting functions, signal processing, Fourier Transform, generating random datasets and many more. Scipy uses `numpy` and `matplotlib`.
8 |
9 | Install it with:
10 |
11 | .. code::
12 |
13 | pip install scipy
14 |
15 | The following code creates noisy data and fits a polynomial function to it:
16 |
17 | .. literalinclude:: curve_fit.py
18 |
19 | In :download:`peak_recognition.ipynb` you find a notebook for recognizing peaks.
20 |
21 | .. seealso::
22 |
23 | `scipy.org/ `__
24 |
--------------------------------------------------------------------------------
/wordcloud/create_wordcloud.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | from matplotlib import pyplot as plt
4 | import wordcloud
5 | import this
6 |
7 | # store the Zen of Python in a string
8 | text = ''.join([this.d.get(c, ' ') for c in this.s]).lower()
9 |
10 | # leave a blank square in the cloud
11 | mask = np.zeros((500, 500, 3), np.uint8)
12 | mask[150:350,150:350,:] = 255
13 |
14 | cloud = wordcloud.WordCloud(background_color="white",
15 | max_words=50,
16 | mask=mask,
17 | collocations=False,
18 | contour_color='steelblue').generate(text)
19 |
20 | plt.figure(num = None, figsize = (8, 8))
21 | plt.imshow(cloud, interpolation='bilinear')
22 | plt.savefig('cloud.png')
23 |
--------------------------------------------------------------------------------
/turtle/koch.py:
--------------------------------------------------------------------------------
1 |
2 | # by: Kristian Rother, Nils Goldmann
3 |
4 | from turtle import *
5 | import time
6 |
7 | def move_to(x,y):
8 | up()
9 | setx(x)
10 | sety(y)
11 | down()
12 |
13 |
14 | def curve(length, depth):
15 | if depth==0:
16 | forward(length)
17 | else:
18 | curve(length*0.333,depth-1)
19 | right(60)
20 | curve(length*0.333,depth-1)
21 | left(120)
22 | curve(length*0.333,depth-1)
23 | right(60)
24 | curve(length*0.333,depth-1)
25 |
26 | reset()
27 | left(180)
28 |
29 | move_to(100, 100)
30 | curve(200, 1)
31 |
32 | move_to(100, 0)
33 | curve(200, 2)
34 |
35 | move_to(100, -100)
36 | curve(200, 3)
37 |
--------------------------------------------------------------------------------
/pillow/carrots/step06-text.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image, ImageDraw, ImageChops, ImageFont
3 |
4 | img = Image.new('RGBA', (800, 500), "white")
5 |
6 | carrot = Image.open('carrot.png')
7 | brain = Image.open('brain.png')
8 |
9 | carrot = carrot.resize((250, 250))
10 |
11 | arrow = Image.open('arrow.png')
12 | gradient = Image.open('gradient.png')
13 |
14 | arrow = ImageChops.screen(arrow, gradient)
15 |
16 | img.paste(carrot, (100, 80))
17 | img.paste(arrow, (325, 150))
18 | img.paste(brain, (500, 100))
19 |
20 | draw = ImageDraw.Draw(img)
21 | arial = ImageFont.truetype('arial.ttf', 40)
22 | draw.text((220, 360), "Carrots rock your brain!", fill=(0,0,0), font=arial)
23 |
24 | img.save('step06.png')
25 |
26 |
--------------------------------------------------------------------------------
/pandas/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to section a panda into hexagons with pandas?
3 | =================================================
4 |
5 | .. figure:: hexpanda.png
6 |
7 | `pandas` is an extremely powerful library to analyze, combine and manipulate data in many ways.
8 | It provides a class for tables called *DataFrames* that are inspired from R. DataFrames have an index column and functions for plotting and reading from CSV or Excel files are included by default. Pandas uses `numpy` under the hood.
9 |
10 | Install it with:
11 |
12 | .. code::
13 |
14 | pip install pandas
15 |
16 | The following code creates some eye candy:
17 |
18 | .. literalinclude:: hexpanda.py
19 |
20 | .. seealso::
21 |
22 | - `pandas.pydata.org/ `__
23 |
--------------------------------------------------------------------------------
/turtle/dragon.py:
--------------------------------------------------------------------------------
1 | from turtle import *
2 |
3 | def vorbereiten():
4 | reset()
5 | up()
6 | setx(-200)
7 | sety(50)
8 | down()
9 |
10 |
11 | def kurve(laenge,tiefe):
12 | if tiefe==1:
13 | forward(laenge)
14 | else:
15 | kurve(laenge*0.25,tiefe-1)
16 | left(90)
17 | kurve(laenge*0.25,tiefe-1)
18 | right(90)
19 | kurve(laenge*0.25,tiefe-1)
20 | right(90)
21 | kurve(laenge*0.5,tiefe-1)
22 | left(90)
23 | kurve(laenge*0.25,tiefe-1)
24 | left(90)
25 | kurve(laenge*0.25,tiefe-1)
26 | right(90)
27 | kurve(laenge*0.25,tiefe-1)
28 |
29 | speed('fastest')
30 | vorbereiten()
31 | kurve(400, 3)
32 |
33 |
--------------------------------------------------------------------------------
/numpy/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to draw a fractal image with NumPy?
3 | =======================================
4 |
5 | .. figure:: mandelbrot.png
6 |
7 | The Numpy library makes it easy to work with matrices in Python.
8 |
9 | Because it is implemented in C, `numpy` accelerates many calculations. It is also type-safe - all elements of a matrix have the same type. Many of the most powerful Python libraries like `pandas`, `scikit-learn` and `PILLOW` have been built on top of numpy.
10 |
11 | Install it with:
12 |
13 | .. code::
14 |
15 | pip install numpy
16 |
17 | The following code draws the the Mandelbrot set:
18 |
19 | .. literalinclude:: mandelbrot.py
20 |
21 |
22 | .. seealso::
23 |
24 | - `Numpy Graphics Tutorial `__
25 | - `www.numpy.org/ `__
26 |
--------------------------------------------------------------------------------
/pymongo/pymongo_connect.py:
--------------------------------------------------------------------------------
1 | import pymongo
2 |
3 | client = pymongo.MongoClient("localhost", 27017) # not necessary on localhost
4 | db = client.test
5 | print(db.name)
6 |
7 | print(db.my_collection)
8 | db.my_collection.insert_one({"x": 10})
9 | db.my_collection.insert_one({"x": 8})
10 | db.my_collection.insert_one({"x": 11})
11 |
12 | # get one entry
13 | print(db.my_collection.find_one())
14 |
15 | # iterate over entries
16 | for item in db.my_collection.find():
17 | print(item["x"])
18 |
19 | # accelerate query with an index
20 | db.my_collection.create_index("x")
21 |
22 | # sort results
23 | for item in db.my_collection.find().sort("x", pymongo.ASCENDING):
24 | print(item["x"])
25 |
26 | # chain multiple functions
27 | print([item["x"] for item in db.my_collection.find().limit(2).skip(1)])
28 |
--------------------------------------------------------------------------------
/pymongo/README.rst:
--------------------------------------------------------------------------------
1 | How to connect Python to MongoDB?
2 | =================================
3 |
4 | The `pymongo` library connects to a Mongo database server.
5 | It is capable of interacting with both local and remote databases.
6 | To connect to a local instance, no extra parameters are necessary.
7 |
8 | Install it with:
9 |
10 | .. code::
11 |
12 | pip install pymongo
13 |
14 | Launch MongoDB through docker
15 | -----------------------------
16 |
17 | To try MongoDB, it is best to launch it in a local docker container:
18 |
19 | .. code::
20 |
21 | docker run -d -p 27017:27017 mongo
22 |
23 | Run queries
24 | -----------
25 |
26 | The following code connects and runs a few queries:
27 |
28 | .. literalinclude:: pymongo_connect.py
29 |
30 | .. seealso::
31 |
32 | `Pymongo documentation `__
33 |
--------------------------------------------------------------------------------
/curses/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to create a 2D game in the terminal?
3 | ========================================
4 |
5 | The `curses` library creates x/y output in a console window.
6 | It supports colors and Unicode tiles (depending on your terminal).
7 | `curses` is installed with Python by default.
8 |
9 | On Windows you may need to install `windows-curses`.
10 |
11 | Running the example:
12 | --------------------
13 |
14 | In :download:`pac.py`, you find a minimalistic Pac game.
15 | Run it from a terminal.
16 |
17 |
18 | .. warning::
19 |
20 | If you get the error message:
21 |
22 | ``curses function returned NULL``
23 |
24 | It likely means that your window is too small.
25 |
26 | .. seealso::
27 |
28 | My first contact with curses was inspired by `manti_go `__ written by my course participants.
29 |
--------------------------------------------------------------------------------
/networkx/page_rank.py:
--------------------------------------------------------------------------------
1 | # draw a graph between cities and color by PageRank
2 |
3 | import pandas as pd
4 | import networkx as nx
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | pairs1 = pd.read_csv("city_pairs.csv", names=["city1", "city2"])
9 | pairs2 = pd.read_csv("city_pairs.csv", names=["city2", "city1"])
10 | pairs = pd.concat([pairs1, pairs2])
11 |
12 | # create adjacency matrix
13 | cities = pd.crosstab(pairs["city1"], pairs["city2"])
14 |
15 | # create graph object with NetworkX library
16 | g = nx.from_pandas_adjacency(cities)
17 |
18 | # calculate node centrality with the PageRank algorithm
19 | rank = nx.pagerank(g, alpha=0.80)
20 | cities["rank"] = pd.Series(rank) / max(rank.values())
21 |
22 | # draw graph, color by rank
23 | plt.figure()
24 | nx.draw(g, node_color=cities["rank"], cmap='coolwarm', labels=dict(zip(g.nodes(), g.nodes())))
25 |
26 | plt.show()
27 |
--------------------------------------------------------------------------------
/sqlite3/example_sqlite.py:
--------------------------------------------------------------------------------
1 |
2 | import sqlite3
3 |
4 | DB_SETUP = '''
5 | CREATE TABLE IF NOT EXISTS person (
6 | id INTEGER,
7 | name VARCHAR(32),
8 | description TEXT
9 | );
10 |
11 | CREATE UNIQUE INDEX IF NOT EXISTS i1 ON person(id);
12 | '''
13 |
14 | # watch out for the file 'hamlet.db' being created.
15 | db = sqlite3.connect('hamlet.db')
16 | db.executescript(DB_SETUP)
17 |
18 | # write data
19 | query = 'INSERT INTO person VALUES (?,?,?)'
20 | # The ?,?,? are a SQLite-specific way of formating strings.
21 | # There are special precautions against SQL injection
22 | db.execute(query, (1, "Hamlet", "the prince of Denkmark"))
23 | db.execute(query, (2, "Polonius", "Ophelias father"))
24 |
25 | # read data
26 | query = '''SELECT name, description FROM person'''
27 | result = db.execute(query) # returns an iterator
28 | print(list(result))
29 |
30 |
31 | db.close()
32 |
--------------------------------------------------------------------------------
/pillow/carrots/step05-filters.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image, ImageDraw, ImageChops
3 |
4 | carrot = Image.open('carrot.png')
5 | brain = Image.open('brain.png')
6 |
7 | carrot = carrot.resize((250, 250))
8 |
9 | arrow = Image.new('RGBA', (250, 250), "white")
10 | draw = ImageDraw.Draw(arrow)
11 | draw.rectangle((0, 50, 100, 100), fill="black")
12 | draw.polygon((100, 25, 100, 125, 150, 75), fill="black")
13 |
14 | gradient = Image.new('RGBA', (250, 250), "white")
15 | draw = ImageDraw.Draw(gradient)
16 | for x in range(250):
17 | box = (x, 0, x+1, 250)
18 | color = (255, (255-x), 0)
19 | draw.rectangle(box, fill=color)
20 |
21 | f1 = ImageChops.multiply(brain, carrot)
22 | f1.save('filter1.png')
23 |
24 | f2 = ImageChops.blend(brain, carrot, 0.2)
25 | f2.save('filter2.png')
26 |
27 | f3 = ImageChops.screen(carrot, gradient)
28 | f3.save('filter3.png')
29 |
--------------------------------------------------------------------------------
/pandas/hexpanda.py:
--------------------------------------------------------------------------------
1 |
2 | # create a hex-binned plot from randomly sampled panda pixels
3 |
4 | import pandas as pd
5 | import pylab as plt
6 | from PIL import Image
7 | import numpy as np
8 |
9 | # read image and convert it to a numpy array
10 | panda = np.array(Image.open('panda.png'))
11 | panda = panda[:,:,:3].mean(axis=2) # aggregate each color channel separately
12 | print(panda.shape) # rows and columns
13 |
14 | pixels = pd.DataFrame(255 - panda)
15 |
16 | # extract dark pixels
17 | pixels = pixels.unstack()
18 | pixels = pixels[pixels > 0]
19 |
20 | # select 10% of pixels
21 | n_points = pixels.shape[0] // 10
22 | sample = pixels.sample(n_points)
23 |
24 | # create new table from indices
25 | coords = sample.index.to_frame().values
26 | df = pd.DataFrame({'x': coords[:,0], 'y': -coords[:,1], 'n': sample.values})
27 |
28 | df.plot.hexbin(x='x', y='y', gridsize=24, cmap=plt.get_cmap('Greys'))
29 |
30 | plt.savefig('hexpanda.png')
31 |
--------------------------------------------------------------------------------
/httpx/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to Download a web page?
3 | ===========================
4 |
5 | The `httpx` library sends HTTP requests to web pages and allows you to read their content.
6 | Most standard tasks are much easier than the standard module `urllib` and implemented cleaner than the outdated `requests` library.
7 | Sending data to web forms via HTTP GET and POST, submitting files and managing cookies are features of this useful library.
8 |
9 | Install `httpx` with:
10 |
11 | .. code::
12 |
13 | pip install requests
14 |
15 | The following code reads a static web page:
16 |
17 | .. literalinclude:: example_requests.py
18 |
19 | How to submit a HTTP GET request from Python?
20 | =============================================
21 |
22 | Here is a search with HTTP GET parameters:
23 |
24 | .. literalinclude:: search_with_parameters.py
25 |
26 | .. seealso::
27 |
28 | `https://www.python-httpx.org/ `__
29 |
--------------------------------------------------------------------------------
/sqlalchemy/example_sqlalchemy.py:
--------------------------------------------------------------------------------
1 |
2 | from sqlalchemy import create_engine, text
3 |
4 | # connection string - specifies
5 | engine = create_engine("sqlite:///example.db", echo=False)
6 |
7 | with engine.connect() as conn:
8 |
9 | # write data
10 | conn.execute(text('''
11 | CREATE TABLE IF NOT EXISTS person (
12 | id INTEGER,
13 | name VARCHAR(32),
14 | description TEXT
15 | );'''))
16 |
17 | conn.execute(text('INSERT INTO person VALUES (:id,:name,:role)'),
18 | [
19 | {"id": 1, "name": "Hamlet", "role": "the prince of Denkmark"},
20 | {"id": 2, "name": "Kunigunde", "role": "the queen of Denkmark"},
21 | ])
22 | conn.commit() # writes to DB
23 |
24 | # read data
25 | result = conn.execute(text('SELECT name, description FROM person'))
26 | for name, description in result:
27 | print(name, description)
28 |
--------------------------------------------------------------------------------
/pillow/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Pillow
3 |
4 | ### What it is good for?
5 |
6 | `Pillow` reads, writes and edits images.
7 |
8 | It contains simple drawing tools and filters that can be applied to pixel based images.
9 | The most important feature of `Pillow` is that it can read and write almost all popular image formats.
10 |
11 | ### Installed with Python by default
12 |
13 | no
14 |
15 | ### Installed with Anaconda
16 |
17 | yes
18 |
19 | ### How to install it?
20 |
21 | :::text
22 | pip install pillow
23 |
24 | ### Where to learn more?
25 |
26 | [https://pillow.readthedocs.org](https://pillow.readthedocs.org)
27 |
28 | ### Shrink images
29 |
30 | :::include half_size.py
31 |
32 | ### Create a dice image
33 |
34 | 
35 |
36 | :::include dice.py
37 |
38 | ### Mix color channels
39 |
40 | 
41 |
42 | :::include warhol.py
43 |
44 | ### Create turtle graphics
45 |
46 | 
47 |
48 | :::include snowflake.py
49 |
50 |
--------------------------------------------------------------------------------
/pillow/carrots/step04-gradient.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image, ImageDraw, ImageChops
3 |
4 | img = Image.new('RGBA', (800, 500), "white")
5 |
6 | carrot = Image.open('carrot.png')
7 | brain = Image.open('brain.png')
8 |
9 | carrot = carrot.resize((250, 250))
10 |
11 | arrow = Image.new('RGBA', (250, 250), "white")
12 | draw = ImageDraw.Draw(arrow)
13 | draw.rectangle((0, 50, 100, 100), fill="black")
14 | draw.polygon((100, 25, 100, 125, 150, 75), fill="black")
15 | arrow.save('arrow.png')
16 |
17 | gradient = Image.new('RGBA', (250, 250), "white")
18 | draw = ImageDraw.Draw(gradient)
19 | for x in range(250):
20 | box = (x, 0, x+1, 250)
21 | color = (255, (255-x), 0)
22 | draw.rectangle(box, fill=color)
23 | gradient.save('gradient.png')
24 |
25 | arrow = ImageChops.screen(arrow, gradient)
26 | arrow.save('grad_arrow.png')
27 |
28 | img.paste(carrot, (100, 80))
29 | img.paste(arrow, (325, 150))
30 | img.paste(brain, (500, 100))
31 |
32 | img.save('step04.png')
33 |
34 |
--------------------------------------------------------------------------------
/email/smtp_example.py:
--------------------------------------------------------------------------------
1 | import smtplib
2 | from email.mime.multipart import MIMEMultipart
3 | from email.mime.text import MIMEText
4 |
5 | # Set up the email parameters
6 | sender_email = 'your_email@gmail.com'
7 | sender_password = 'your_password'
8 | receiver_email = 'recipient@example.com'
9 | subject = 'Hello from Python!'
10 | message = 'This is a test email sent from Python.'
11 |
12 | # Create the email message
13 | msg = MIMEMultipart()
14 | msg['From'] = sender_email
15 | msg['To'] = receiver_email
16 | msg['Subject'] = subject
17 | msg.attach(MIMEText(message, 'plain'))
18 |
19 | # Connect to Gmail's SMTP server
20 | try:
21 | server = smtplib.SMTP('smtp.gmail.com', 587)
22 | server.starttls()
23 | server.login(sender_email, sender_password)
24 |
25 | # Send the email
26 | server.sendmail(sender_email, receiver_email, msg.as_string())
27 | print("Email sent successfully!")
28 |
29 | # Close the SMTP server
30 | server.quit()
31 | except Exception as e:
32 | print(f"An error occurred: {str(e)}")
33 |
--------------------------------------------------------------------------------
/zipfile/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to create a zip archive?
3 | ============================
4 |
5 | With the builtin module `zipfile`, you can add both existing files and strings to a zip file. If you are adding strings you need to specify the file name it is written to. When you extract files to a folder, the output folder is automatically created.
6 |
7 | .. code:: python3
8 |
9 | import zipfile
10 |
11 | z = zipfile.ZipFile('archive.zip', 'w')
12 | z.write('myfile.txt') # already existing file
13 | z.writestr('test.txt', 'Hello World') # string to new file
14 | z.close()
15 |
16 | How to read a zip archive?
17 | ==========================
18 |
19 | List the contents of a zip file:
20 |
21 | .. code:: python3
22 |
23 | z = zipfile.ZipFile('archive.zip')
24 | print(z.namelist())
25 |
26 |
27 | Extract a file to a new folder:
28 |
29 | .. code:: python3
30 |
31 | print(z.extract('test.txt', 'myfolder'))
32 | z.close()
33 |
34 |
35 | .. seealso::
36 |
37 | `Documentation of the zipfile module `__
38 |
--------------------------------------------------------------------------------
/math/README.rst:
--------------------------------------------------------------------------------
1 |
2 |
3 | How to calculate a square root?
4 | ===============================
5 |
6 | .. code:: python3
7 |
8 | import math
9 |
10 | print(math.sqrt(49))
11 |
12 |
13 | How to calculate a trigonometric function?
14 | ==========================================
15 |
16 | .. code:: python3
17 |
18 | import math
19 |
20 | print(math.sin(math.pi / 2))
21 |
22 | How to calculate an exponential function?
23 | =========================================
24 |
25 | .. code:: python3
26 |
27 | import math
28 |
29 | print(math.exp(1.0) == math.e)
30 |
31 | How to calculate a logarithm?
32 | =============================
33 |
34 | .. code:: python3
35 |
36 | import math
37 |
38 | print(math.log(256, 2))
39 |
40 | .. seealso::
41 |
42 | The builtin `math` module contains mathematical functions similar to a scientific calculator.
43 | In the module, you find various trigonometric and exponential functions. In addition the two constants `pi` and `e` are included.
44 |
45 | `math documentation `__
46 |
--------------------------------------------------------------------------------
/pillow/warhol.py:
--------------------------------------------------------------------------------
1 |
2 | # example: create Andy-Warhol like images
3 |
4 | from PIL import Image, ImageDraw
5 |
6 | pylogo = Image.open("python_logo.png")
7 | print(pylogo.size)
8 |
9 | r, g, b, a = pylogo.split()
10 |
11 | pylogo1 = Image.merge("RGB", (b, g, r))
12 | pylogo2 = Image.merge("RGB", (r, b, g))
13 | pylogo3 = Image.merge("RGB", (g, b, r))
14 | pylogo4 = Image.merge("RGB", (g, r, b))
15 |
16 | collage = Image.new("RGBA",(600,600), "#FFFFFF")
17 |
18 | collage.paste(pylogo1,(58,58))
19 | collage.paste(pylogo2,(354,58))
20 | collage.paste(pylogo3,(58,354))
21 | collage.paste(pylogo4,(354,354))
22 |
23 | draw_tool = ImageDraw.Draw(collage)
24 | draw_tool.line(((5, 5),(595, 5)), fill=(0,0,0),width=5)
25 | draw_tool.line(((595, 5),(595, 595)), fill=(0,0,0),width=5)
26 | draw_tool.line(((5, 5),(5, 595)), fill=(0,0,0),width=5)
27 | draw_tool.line(((5, 595),(595, 595)), fill=(0,0,0),width=5)
28 | draw_tool.line(((300, 5),(300, 595)), fill=(0,0,0),width=5)
29 | draw_tool.line(((5, 300),(595, 300)), fill=(0,0,0),width=5)
30 |
31 | collage.save('pylogo_warhol.png')
32 | collage.show()
33 |
--------------------------------------------------------------------------------
/turtle/many_snowflakes.py:
--------------------------------------------------------------------------------
1 |
2 | from turtle import forward, left, right, width, color, clearscreen
3 | from turtle import setx, sety, speed, up, down
4 | from random import randint
5 |
6 |
7 | def zeichne_flocke(groesse):
8 | """
9 | Funktion, wird hier definiert
10 | und weiter unten verwendet.
11 | """
12 | for i in range(6):
13 | forward(groesse)
14 | left(60)
15 | forward(groesse / 2)
16 | left(180)
17 | forward(groesse / 2)
18 | left(60)
19 | forward(groesse / 2)
20 | left(180)
21 | forward(groesse / 2)
22 | right(120)
23 | forward(groesse / 2)
24 | left(180)
25 | forward(groesse * 1.5)
26 | left(120)
27 |
28 |
29 | # Hauptprogramm
30 | clearscreen()
31 | color("lightblue")
32 | width(3)
33 | speed(20)
34 |
35 | for i in range(10):
36 | # Stift an zufällige Position setzen
37 | up()
38 | setx(randint(-250, 250))
39 | sety(randint(-200, 200))
40 | down()
41 | # Flocke in zufälliger Größe zeichnen
42 | groesse = randint(10, 30)
43 | zeichne_flocke(groesse)
44 |
45 |
--------------------------------------------------------------------------------
/LICENSE.TXT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Dr. Kristian Rother
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/json/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to write a JSON file?
3 | =========================
4 |
5 | The builtin module `json` module converts Python dictionaries to JSON and back.
6 | The *JavaScript Object Notation (JSON)* is frequently used to send structured data around the web or store it painlessly in files.
7 | The `json` modules utilizes the similarity of the JSON format to Python dictionaries.
8 |
9 | .. code:: python3
10 |
11 | import json
12 |
13 | data = {"apples": 1, "bananas": "two", "cherries": [3,4,5]}
14 | with open("data.json", "w") as f:
15 | jj = json.dumps(data)
16 | f.write(jj)
17 |
18 | .. note::
19 |
20 | You could write to the file directly with `json.dump`.
21 |
22 | How to read a JSON file?
23 | ========================
24 |
25 | Loading a JSON data structure from a file results in a list or dictionary:
26 |
27 | .. code:: python3
28 |
29 | with open("data.json") as f:
30 | data = json.loads(f.read())
31 | print(data)
32 |
33 | Instead of parsing a string object, you could parse from the file directly with `json.load()`
34 |
35 | .. seealso::
36 |
37 | `Documentation of the json module `__
38 |
--------------------------------------------------------------------------------
/matplotlib/README.md:
--------------------------------------------------------------------------------
1 |
2 | # matplotlib
3 |
4 | ### What it is good for?
5 |
6 | Plotting diagrams.
7 |
8 | `matplotlib` is capable of producing static images of all common types of diagrams in print quality: line plots, scatter plots, bar charts, pie charts, histograms, heat maps etc.
9 |
10 |
11 | ### Installed with Anaconda
12 |
13 | yes
14 |
15 | ### How to install it:
16 |
17 | :::text
18 | pip install matplotlib
19 |
20 | ### Where to learn more?
21 |
22 | A good way to learn what you can do is to browse the examples gallery on [matplotlib.org/](http://matplotlib.org/)
23 |
24 | You find a comprehensive tutorial on [https://scipy-lectures.org/intro/matplotlib/index.html](https://scipy-lectures.org/intro/matplotlib/index.html)
25 |
26 |
27 | ### Scatterplot
28 |
29 | 
30 |
31 | :::include balls.py
32 |
33 | ### Bar Plot
34 |
35 | 
36 |
37 | :::include barplot.py
38 |
39 | ### Line Plot
40 |
41 | 
42 |
43 | :::include lineplot.py
44 |
45 | ### Error Bars
46 |
47 | 
48 |
49 | :::include errorbars.py
50 |
51 | ### Pie Chart
52 |
53 | 
54 |
55 | :::include piechart.py
56 |
--------------------------------------------------------------------------------
/pillow/carrots/step07-full_image.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image, ImageDraw, ImageChops, ImageFont
3 |
4 | img = Image.new('RGBA', (800, 500), "white")
5 |
6 | # load starting bitmaps
7 | logo = Image.open('python_logo.png')
8 | brain = Image.open('brain.png')
9 |
10 | logo = logo.resize((150, 150))
11 |
12 | # draw an arrow
13 | arrow = Image.new('RGBA', (250, 250), "white")
14 | draw = ImageDraw.Draw(arrow)
15 | draw.rectangle((0, 50, 100, 100), fill="black")
16 | draw.polygon((100, 25, 100, 125, 150, 75), fill="black")
17 |
18 | # add gradient to arrow
19 | gradient = Image.new('RGBA', (250, 250), "white")
20 | draw = ImageDraw.Draw(gradient)
21 | for x in range(250):
22 | box = (x, 0, x+1, 250)
23 | color = (255, (255-x), 0)
24 | draw.rectangle(box, fill=color)
25 |
26 | arrow = ImageChops.screen(arrow, gradient)
27 |
28 | # combine all component images
29 | img.paste(logo, (100, 147))
30 | img.paste(arrow, (325, 150))
31 | img.paste(brain, (500, 100))
32 |
33 | # add text
34 | draw = ImageDraw.Draw(img)
35 | arial = ImageFont.truetype('arial.ttf', 40)
36 | draw.text((220,360),"Python rocks your brain!",fill=(0,0,0),font=arial)
37 |
38 | img.save('step07_final.png')
39 |
40 |
--------------------------------------------------------------------------------
/re/exercises/regex_search.py:
--------------------------------------------------------------------------------
1 |
2 | # Exercise: Regular expression search
3 | #
4 | # Find the right regular expressions that find something in the text.
5 | #
6 | # 1. Replace the 'regex' in the code
7 | # 2. Run the program to see whether it works.
8 | # 3. As soon as it does, uncomment the next example.
9 |
10 | import re
11 |
12 | text = """
13 | 2ow8 3.71 tRNA_Phe ribosome_(p-site)
14 | 1b23 2.60 tRNA_Cys Ef-Tu
15 | 1qrt 2.70 tRNA_Gln GlnRS
16 | 1qf6 2.90 tRNA_Thr ThrRS
17 | 1j1u 1.95 tRNA_Tyr TyrRS
18 | 2fk6 2.90 tRNA_Thr RNase_Z
19 | 2hgr 4.51 tRNA_Phe ribosome_(e_or_p-site)
20 | """
21 |
22 | # find all words 'tRNA'
23 | result = re.findall('regex',text)
24 | assert len(result) == 7
25 |
26 | # extract all PDB codes
27 | #result = re.findall('regex',text)
28 | # assert result == ['2ow8','1b23','1qrt','1qf6','1j1u','2fk6','2hgr']
29 |
30 | # extract all aromatic amino acids
31 | #result = re.findall('regex',text)
32 | # assertt result == ['tRNA_Phe','tRNA_Tyr','tRNA_Phe']
33 |
34 | # extract elements flanked by spaces on the left and right (2 middle columns)
35 | # result = re.findall('regex',text)
36 | # assertt len(result) == 14
37 |
38 | # extract a whole line containing key phrase 'Ef-Tu'
39 | # result = re.findall('regex',text)
40 | # assertt result == ['1b23 2.60 tRNA_Cys Ef-Tu']
41 |
--------------------------------------------------------------------------------
/re/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to search text with Regular Expressions?
3 | ============================================
4 |
5 | The builtin module `re` implements **Regular Expression**, a powerful syntax for search patterns in text.
6 | You need to know some special characters to build your own patterns, although LLMs should be able to assist with that.
7 | Regular Expressions are very similar in most programming languages.
8 |
9 | Here are a couple of examples in Python:
10 |
11 | .. literalinclude:: fox.py
12 |
13 | .. seealso::
14 |
15 | - `Regex 101 `__ - Shows matched text with explanation.
16 | - `regexone.com/ `__ - Learn regular expressions by simple, interactive examples. Great place to start.
17 | - `Regex crossword `__ - Train proper use of single characters, wildcards and square brackets. Easy.
18 | - `Regex golf `__ - Advanced exercises. Match as many phrases with as few key strokes as possible.
19 | - `Python Regex HOWTO `__
20 | - `docs.python.org/3/library/re.html `__
21 | - `Quick Reference `__ - a reference sheet for looking up metacharacters. Uses the **Python syntax**.
22 |
--------------------------------------------------------------------------------
/scikit_image/wave_transform.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 | from skimage.transform import PiecewiseAffineTransform, warp
4 | from imageio import imread, imsave
5 |
6 | image = imread('python_logo.png')
7 |
8 | rows, cols = image.shape[0], image.shape[1]
9 |
10 | src_cols = np.linspace(0, cols, 20)
11 | src_rows = np.linspace(0, rows, 10)
12 | src_rows, src_cols = np.meshgrid(src_rows, src_cols)
13 | src = np.dstack([src_cols.flat, src_rows.flat])[0]
14 |
15 | # add sinusoidal oscillation to row coordinates
16 | FRAMES = 20
17 | for i in range(0, FRAMES):
18 | amplitude = 15
19 | phase = i / FRAMES * 2 * np.pi
20 |
21 | dst_rows = src[:, 1] - np.sin(np.linspace(phase, phase + 3 * np.pi, src.shape[0])) * amplitude
22 | dst_cols = src[:, 0]
23 | dst_rows *= 1.5
24 | dst_rows -= 1.5 * 50
25 | dst = np.vstack([dst_cols, dst_rows]).T
26 |
27 | tform = PiecewiseAffineTransform()
28 | tform.estimate(src, dst)
29 |
30 | out = warp(image, tform, output_shape=(rows, cols))
31 | imsave(f'wave/out{i:03d}.png', out)
32 |
33 |
34 | # create animated GIF
35 | import imageio
36 | import os
37 |
38 | f = []
39 | for fn in sorted(os.listdir('wave')):
40 | fn = 'wave/' + fn
41 | f.append(imageio.imread(fn))
42 |
43 | imageio.mimsave('output.gif', f, fps=20)
44 |
--------------------------------------------------------------------------------
/psycopg2/crud.py:
--------------------------------------------------------------------------------
1 | # pip install psycopg2-binary
2 |
3 | import psycopg2
4 |
5 | # Database connection details (must match your Docker container setup)
6 | DB_NAME = "mydatabase"
7 | DB_USER = "myuser"
8 | DB_PASS = "mypassword"
9 | DB_HOST = "localhost" # or "127.0.0.1"
10 | DB_PORT = "8000"
11 |
12 | # Connect to PostgreSQL
13 | conn = psycopg2.connect(
14 | dbname=DB_NAME,
15 | user=DB_USER,
16 | password=DB_PASS,
17 | host=DB_HOST,
18 | port=DB_PORT
19 | )
20 |
21 | cur = conn.cursor()
22 |
23 | # 1) Create table
24 | cur.execute("""
25 | CREATE TABLE IF NOT EXISTS flowers (
26 | id SERIAL PRIMARY KEY,
27 | name VARCHAR(50),
28 | latin_species VARCHAR(100),
29 | color VARCHAR(30)
30 | );
31 | """)
32 |
33 | # 2) Insert 3 rows
34 | flowers = [
35 | ("Rose", "Rosa rubiginosa", "Red"),
36 | ("Sunflower", "Helianthus annuus", "Yellow"),
37 | ("Lavender", "Lavandula angustifolia", "Purple")
38 | ]
39 |
40 | cur.executemany(
41 | "INSERT INTO flowers (name, latin_species, color) VALUES (%s, %s, %s);",
42 | flowers
43 | )
44 |
45 | # Commit the transaction
46 | conn.commit()
47 |
48 | # 3) Read them
49 | cur.execute("SELECT * FROM flowers;")
50 | rows = cur.fetchall()
51 |
52 | print("🌸 Flowers in database:")
53 | for row in rows:
54 | print(row)
55 |
56 | # Clean up
57 | cur.close()
58 | conn.close()
59 |
--------------------------------------------------------------------------------
/pillow/dice_images/wuerfel.py:
--------------------------------------------------------------------------------
1 | """
2 | Generiert Bilder von Wuerfelseiten
3 | """
4 |
5 | from PIL import Image
6 | from PIL import ImageDraw
7 |
8 | w = Image.new('RGB', (64,64), '#80b940')
9 |
10 | blank = w.copy()
11 | blank.save('blank.png')
12 |
13 | d = ImageDraw.Draw(w)
14 |
15 | d.ellipse(((26, 26), (38, 38)), '#ffffff')
16 | eins = w.copy()
17 | eins.save('eins.png')
18 |
19 | d.ellipse(((10, 10), (22, 22)), '#ffffff')
20 | d.ellipse(((42, 42), (54, 54)), '#ffffff')
21 | drei = w.copy()
22 | drei.save('drei.png')
23 |
24 | d.ellipse(((10, 42), (22, 54)), '#ffffff')
25 | d.ellipse(((42, 10), (54, 22)), '#ffffff')
26 | fuenf = w.copy()
27 | fuenf.save('fuenf.png')
28 |
29 | d.ellipse(((26, 26), (38, 38)), '#80b940')
30 | vier = w.copy()
31 | vier.save('vier.png')
32 |
33 | d.ellipse(((10, 42), (22, 54)), '#80b940')
34 | d.ellipse(((42, 10), (54, 22)), '#80b940')
35 | zwei = w.copy()
36 | zwei.save('zwei.png')
37 |
38 | d.ellipse(((10, 42), (22, 54)), '#ffffff')
39 | d.ellipse(((42, 10), (54, 22)), '#ffffff')
40 | d.ellipse(((26, 10), (38, 22)), '#ffffff')
41 | d.ellipse(((26, 42), (38, 54)), '#ffffff')
42 | sechs = w.copy()
43 | sechs.save('sechs.png')
44 |
45 | w = Image.new('RGB', (64*6,64), '#80b940')
46 | w.paste(eins, box=(64 * 0, 0))
47 | w.paste(zwei, box=(64 * 1, 0))
48 | w.paste(drei, box=(64 * 2, 0))
49 | w.paste(vier, box=(64 * 3, 0))
50 | w.paste(fuenf, box=(64 * 4, 0))
51 | w.paste(sechs, box=(64 * 5, 0))
52 | w.save('wuerfel.png')
53 |
--------------------------------------------------------------------------------
/sys/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to find out where the interpreter is looking for importable modules?
3 | ========================================================================
4 |
5 | The builtin module `sys` provides an access point to the Python environment.
6 | You find there command line arguments, the import path settings, the standard input, output and error stream and many more.
7 |
8 | The `sys.path` variable contains the current directory, everything from the `PYTHONPATH` environment variable, and Pythons own folders.
9 |
10 | .. code:: python3
11 |
12 | print(sys.path)
13 |
14 |
15 | How to call a Python program with command-line parameters?
16 | ==========================================================
17 |
18 | The variable ``sys.argv`` contains a list of command-line arguments.
19 | The first one is usually the name of the called script.
20 |
21 | .. code:: python3
22 |
23 | import sys
24 |
25 | print sys.argv
26 |
27 | When you call this program with any of:
28 |
29 | ::
30 |
31 | python script.py
32 | python script.py hello world
33 | python script.py 1 2 3
34 |
35 | You should see a difference.
36 |
37 | How to terminate a Python program gracefully?
38 | =============================================
39 |
40 | The `sys.exit()` function ends execution of the Python interpreter immediately.
41 |
42 | .. code:: python3
43 |
44 | import sys
45 |
46 | sys.exit()
47 |
48 |
49 | .. seealso::
50 |
51 | `Documentation of the sys module `__
52 |
--------------------------------------------------------------------------------
/oauth_git/github.py:
--------------------------------------------------------------------------------
1 | """
2 | https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/
3 | https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
4 | """
5 |
6 | import requests
7 | from flask import Flask, redirect, url_for, escape, request
8 | import re
9 |
10 | app = Flask(__name__)
11 |
12 | CLIENT_ID = "..."
13 | CLIENT_SECRET = "..."
14 | AUTH_URL = "https://github.com/login/oauth/authorize"
15 | REDIRECT_URI = "http://localhost:5000/redirect/"
16 |
17 |
18 | app = Flask(__name__)
19 |
20 |
21 | @app.route('/')
22 | def login():
23 | """1. Request a user's GitHub identity"""
24 | url = AUTH_URL + f"?client_id={CLIENT_ID}&login=krother&redirect_uri={REDIRECT_URI}"
25 | return redirect(url)
26 |
27 |
28 | @app.route('/redirect/')
29 | def redirect_from_github():
30 | """2. Users are redirected back to your site by GitHub"""
31 | params = {'client_id': CLIENT_ID,
32 | 'client_secret': CLIENT_SECRET,
33 | 'code': request.args['code'],
34 | }
35 | r = requests.post("https://github.com/login/oauth/access_token", params)
36 | if r.status_code == 200:
37 | print(r.text)
38 | access_token = re.findall('access_token\=([^\&]+)', r.text)[0]
39 | print(access_token)
40 | #
41 | # now do stuff with access token
42 | #
43 | return redirect(url_for('goal'))
44 | return redirect(url_for('fail'))
45 |
46 |
47 | @app.route('/goal')
48 | def goal():
49 | return "DONE!!!"
50 |
51 | @app.route('/fail')
52 | def fail():
53 | return "*** FAIL ***"
54 |
--------------------------------------------------------------------------------
/moviepy/end_credits.txt:
--------------------------------------------------------------------------------
1 | ;
2 | Moderation;Florian Kindermann
3 | ;Eva Hieninger
4 | ;Peter Henrich
5 |
6 | Redner;Andrej Laue
7 | ;Barbara Bosch
8 |
9 | Bewerter;Kristian Rother
10 | ;Sascha Goldmann
11 | ;Jan Schmeiser
12 |
13 | Zeitnehmer;Marek Schiffer
14 | ;
15 | Produktionsleitung;Sascha Goldmann
16 | Regie;David Madry
17 | Drehbuch;Kristian Rother
18 | Redaktion;Wendy Wallace Husser
19 |
20 | Kamera;Thomas Lewin
21 | ;Carsten Bellon
22 | ;Jörg Langrock
23 | Bildregie;Klaus Boettcher
24 | Licht;Martin Christoph
25 | Ton;Martin Christoph
26 | Tonassistenz;Angelika Firschke
27 | Intro und Abspann;Kristian Rother
28 | Schnitt;Klaus Boettcher
29 | ;Robert Klein
30 |
31 | Gästebetreuung;Antje Bellon
32 | Maske;Sabine Niemann
33 | Runner;Jörg Langrock
34 | Helfer;Gérald Hägele
35 | ;Fritz Boettcher
36 | ;Tristan Strauß
37 |
38 | Beratung;Schifra Wittkopp
39 | Studio CvD;Andrea Brehme
40 |
41 | Abspann erstellt mit;moviepy (by zulko)
42 |
43 |
44 | #wir danken ALEX Berlin
45 | #für die Unterstützung bei den Dreharbeiten.
46 |
47 |
48 |
49 | #Disclaimer:
50 |
51 | #Toastmasters International® and all other
52 | #Toastmasters International trademarks and
53 | #copyrights are the sole property of
54 | #Toastmasters International. This video was
55 | #created by Sascha Goldmann (District 95)
56 | #and is independent of Toastmasters International.
57 | #It is not authorized, endorsed, sponsored,
58 | #affiliated, or otherwise approved
59 | #training material by Toastmasters International.
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | Sendungsverantwortlicher;Sascha Goldmann
70 |
71 | May 2016, Berlin, Germany
72 |
--------------------------------------------------------------------------------
/PuLP/magic_sqare.py:
--------------------------------------------------------------------------------
1 |
2 | from pulp import *
3 |
4 | prob = LpProblem("PULPTEST", LpMinimize)
5 |
6 | # model variables
7 | XCOORD = [0, 1, 2]
8 | YCOORD = [0, 1, 2]
9 | NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9]
10 |
11 | # variable is a 3 x 3 x 9 matrix of binary values
12 | allocation = LpVariable.dicts("square", (XCOORD, YCOORD, NUMBERS), 0, 1, LpInteger)
13 |
14 | # target function
15 | prob += 0, "Arbitrary Objective Function"
16 |
17 | # constraint: sum over rows
18 | for x in XCOORD:
19 | prob += lpSum([n * allocation[x][y][n] for y in YCOORD for n in NUMBERS]) == 15
20 |
21 | # constraint: sum over columns
22 | for y in YCOORD:
23 | prob += lpSum([n * allocation[x][y][n] for x in XCOORD for n in NUMBERS]) == 15
24 |
25 | # constraint: each number only once
26 | for n in NUMBERS:
27 | prob += lpSum([allocation[x][y][n] for x in XCOORD for y in YCOORD]) == 1
28 |
29 | # constraint: three numbers per column
30 | for x in XCOORD:
31 | prob += lpSum([allocation[x][y][n] for y in YCOORD for n in NUMBERS]) == 3
32 |
33 | # constraint: three numbers per row
34 | for y in YCOORD:
35 | prob += lpSum([allocation[x][y][n] for x in XCOORD for n in NUMBERS]) == 3
36 |
37 | # constraint: 9 numbers set
38 | prob += lpSum([allocation[x][y][n] for x in XCOORD for y in YCOORD for n in NUMBERS]) == 9
39 |
40 | # run the solver
41 | prob.solve()
42 |
43 | print("Status:", LpStatus[prob.status])
44 |
45 | # print the numbers that have been found
46 | for y in YCOORD:
47 | for x in XCOORD:
48 | for n in NUMBERS:
49 | if value(allocation[x][y][n]) == 1:
50 | print(n, end=' ')
51 | #print(x, y, n)
52 | print()
53 |
--------------------------------------------------------------------------------
/os/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to check whether a file exists?
3 | ===================================
4 |
5 | The `os` module provides an easy way to interact with files, directories and other parts of your operating system. It contains many functions to list, change, copy, remove and examine files and directories.
6 |
7 | .. code:: python3
8 |
9 | import os
10 |
11 | print(os.path.exists('README.rst'))
12 |
13 | How to copy or remove a file?
14 | =============================
15 |
16 | `os` does these as well:
17 |
18 | .. code:: python3
19 |
20 | import os
21 |
22 | os.system('cp README.md copy.md')
23 |
24 | os.remove('copy.md')
25 |
26 |
27 | How to loop over all files in a directory?
28 | ==========================================
29 |
30 | The following code prints all Python files in a given folder:
31 |
32 | .. code:: python3
33 |
34 | import os
35 |
36 | for filename in os.listdir("/home/participant/"):
37 | if filename.endswith(".py"):
38 | print(filename)
39 |
40 |
41 | How to run a command-line program from Python?
42 | ==============================================
43 |
44 | A very simple way to start other processes is the `os.system()` function.
45 | The following example starts a program to list contents of a folder and redirects the output to a file:
46 |
47 | .. code:: python3
48 |
49 | import os
50 |
51 | os.system("ls -l > result.txt")
52 |
53 | .. warning::
54 |
55 | `os.system` does not allow for any communication with the running process.
56 | If it crashes or runs forever, your Python code won't learn about it.
57 | A safer alternative is the `multiprocessing` module.
58 |
59 | .. seealso::
60 |
61 | `Documentation of the os module `__
62 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/email/send_email.py:
--------------------------------------------------------------------------------
1 |
2 | import smtplib
3 | from email.mime.text import MIMEText
4 |
5 | class MailAccount:
6 | """
7 | Stores settings for an email account.
8 | """
9 | def __init__(self, server, login, password, sender_email, \
10 | sender_name, use_tls=False):
11 | self.server = server
12 | self.login = login
13 | self.password = password
14 | self.mail = sender_email
15 | self.sender = '"%s" <%s>'%(sender_name, sender_email)
16 | self.use_tls = use_tls
17 |
18 | def send_email(self, recipient_email, subject, body):
19 | """Sends an email to a defined address. """
20 | # prepare message
21 | message = MIMEText(body)
22 | message["Subject"] = subject
23 | message["From"] = self.mail
24 | message["To"] = recipient_email
25 | msg = message.as_string()
26 |
27 | server = smtplib.SMTP(self.server)
28 | server.set_debuglevel(1)
29 |
30 | if self.use_tls: # deliberately starts tls if using TLS
31 | server.ehlo()
32 | server.starttls()
33 | server.ehlo()
34 |
35 | server.login(self.login, self.password)
36 | server.sendmail(self.mail, recipient_email, msg)
37 | server.quit()
38 |
39 | if __name__ == '__main__':
40 | accounts = [
41 | MailAccount('mailserver_address', \
42 | 'your_account', 'your_password', 'your_email', \
43 | 'Your Name', use_tls=True),
44 | ]
45 |
46 | for account in accounts:
47 | try:
48 | account.send_email('test@testdomain.de', 'Title', 'Content')
49 | print ('\nSENT!!\n\n\n')
50 | except smtplib.SMTPAuthenticationError:
51 | print ('\nFAIL\n\n')
52 |
--------------------------------------------------------------------------------
/time/README.rst:
--------------------------------------------------------------------------------
1 |
2 | How to format the current time as a string?
3 | ===========================================
4 |
5 | The builtin module `time` contains a convenient one-stop function:
6 |
7 | .. code:: python3
8 |
9 | import time
10 |
11 | print(time.asctime())
12 |
13 | An alternative is to retrieve the time and date as a `datetime` object that can be formated to custom strings:
14 |
15 | .. code:: python3
16 |
17 | print(time.strftime('%a %d.%m.', time.localtime()))
18 |
19 | How to use a datetime object?
20 | =============================
21 |
22 | The `date` and `datetime` objects have attributes for time components:
23 |
24 | .. code:: python3
25 |
26 | import datetime
27 |
28 | date = datetime.date(2025, 9, 30)
29 | print(date.year, date.month, date.day)
30 |
31 | You can use explicit attribute names when creating date objects:
32 |
33 | .. code:: python3
34 |
35 | timestamp = datetime.datetime(year=2025, month=9, day=30, hour=7, minute=25, second=0)
36 | print(timestamp.minute)
37 |
38 | How to let a program wait for a while?
39 | ======================================
40 |
41 | The `time.sleep()` function gives back control to the Python interpreter. If you are running multiple threads they may do something.
42 |
43 | .. code:: python3
44 |
45 | import time
46 |
47 | time.sleep(3)
48 |
49 | Note that if you are in an asynchronous function, you will have to use `asyncio.sleep()`.
50 |
51 | .. code:: python3
52 |
53 | import asyncio
54 |
55 | async def wait():
56 | await asyncio.sleep(3)
57 |
58 | asyncio.run(wait())
59 |
60 | .. seealso::
61 |
62 | - `Documentation for the time module `__
63 | - `Documentation for the datetime module `__
64 |
--------------------------------------------------------------------------------
/tkinter/titanic.py:
--------------------------------------------------------------------------------
1 | import tkinter as tk
2 | from tkinter.messagebox import showwarning
3 | from PIL import Image, ImageTk
4 |
5 |
6 | class Application(tk.Frame):
7 | def __init__(self, master=None):
8 | super().__init__(master)
9 | self.titanic = Image.open("titanic.png")
10 | self.titanic2 = Image.open("titanic2.png")
11 | self.pack()
12 | self.create_widgets()
13 |
14 | def send_sos(self):
15 | showwarning(title="S.O.S.", message="we are sinking")
16 |
17 | def collision(self):
18 | photo = ImageTk.PhotoImage(self.titanic2)
19 | self.canvas.image = photo
20 | self.im = self.canvas.create_image(0, 0, image=photo, anchor='nw')
21 |
22 | def create_widgets(self):
23 | photo = ImageTk.PhotoImage(self.titanic)
24 | self.canvas = tk.Canvas(self, width=700, height=178, bg='black')
25 | self.canvas.pack(side='top', fill='both', expand='yes')
26 | self.canvas.image = photo # keep a reference!
27 | self.im = self.canvas.create_image(0, 0, image=photo, anchor='nw')
28 |
29 | self.quit = tk.Button(self, text="Abandon ship",
30 | command=root.destroy)
31 | self.quit.pack(side="bottom", fill="both", expand="yes")
32 |
33 | self.sos = tk.Button(self, fg="red")
34 | self.sos["text"] = "Send out S.O.S."
35 | self.sos["command"] = self.send_sos
36 | self.sos.pack(side="bottom", fill="both", expand="yes")
37 |
38 | self.sink = tk.Button(self)
39 | self.sink["text"] = "Full Speed"
40 | self.sink["command"] = self.collision
41 | self.sink.pack(side="bottom", fill="both", expand="yes")
42 |
43 |
44 |
45 | root = tk.Tk()
46 | app = Application(master=root)
47 | app.master.title("Titanic-Simulator 1.0")
48 | app.mainloop()
49 |
--------------------------------------------------------------------------------
/moviepy/end_credits.py:
--------------------------------------------------------------------------------
1 |
2 | import gizeh as gz
3 | import moviepy.editor as mpy
4 | from moviepy.editor import ImageClip, CompositeVideoClip
5 | from faker import Factory
6 |
7 | W, H = 1200, 1000
8 |
9 | DURATION = 25 # seconds
10 |
11 | LEFTCOL = 450
12 | RIGHTCOL = 490
13 | TEXTSIZE = 28
14 | LINE_HEIGHT = 50
15 |
16 | SCROLLSPEED = 130
17 | BOTTOM_START = H * 1.2
18 |
19 | N_NAMES = 30
20 |
21 | # load image that does not move at all
22 | LOGO_POS = 950, 300
23 | LOGO_SIZE = 235, 298
24 | LOGO = ImageClip("panda.png").resize(LOGO_SIZE).set_pos(LOGO_POS)
25 | LOGO.duration = DURATION
26 |
27 |
28 | # create fake text
29 | fake = Factory.create()
30 | text = []
31 | while len(text) < N_NAMES:
32 | job = fake.job()
33 | name = fake.name()
34 | if len(job) < 25:
35 | text.append((job, name))
36 |
37 |
38 | def make_frame(t):
39 | """Draw text elements in each frame"""
40 | surface = gz.Surface(W, H, bg_color=(0,0,0))
41 | for i, line in enumerate(text):
42 | job, name = line
43 | ypos = LINE_HEIGHT * i - int(t * SCROLLSPEED) + BOTTOM_START
44 |
45 | txt = gz.text(job, "Amiri", TEXTSIZE, fontweight='bold', \
46 | h_align='right', fill=(1,1,1))
47 | left = gz.Group([txt]).translate((LEFTCOL, ypos))
48 | left.draw(surface)
49 | txt = gz.text(name, "Amiri", TEXTSIZE, \
50 | fontweight='normal',h_align='left', fill=(1,1,1))
51 | right = gz.Group([txt]).translate((RIGHTCOL, ypos))
52 | right.draw(surface)
53 | return surface.get_npimage()
54 |
55 |
56 | clip = mpy.VideoClip(make_frame, duration=DURATION)
57 |
58 | # mix text and logo together
59 | final = CompositeVideoClip([clip, LOGO])
60 | final.subclip(0, DURATION).write_videofile("abspann.avi", codec="h264", fps=24)
61 | #final.subclip(0, DURATION).write_videofile("abspann.mp4", codec="mpeg4", fps=24)
62 |
--------------------------------------------------------------------------------
/ipyvolume/volume.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "import ipyvolume as ipv\n",
10 | "import numpy as np"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": null,
16 | "metadata": {},
17 | "outputs": [],
18 | "source": [
19 | "x, y, z = np.random.normal(0.0, 1.0, (3, 1000))"
20 | ]
21 | },
22 | {
23 | "cell_type": "code",
24 | "execution_count": null,
25 | "metadata": {},
26 | "outputs": [],
27 | "source": [
28 | "fig = ipv.quickscatter(x, y, z, size=1, marker=\"sphere\")\n",
29 | "fig"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": null,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "V = np.zeros((128,128,128)) # our 3d array\n",
39 | "# outer box\n",
40 | "V[30:-30,30:-30,30:-30] = 0.75\n",
41 | "V[35:-35,35:-35,35:-35] = 0.0\n",
42 | "# inner box\n",
43 | "V[50:-50,50:-50,50:-50] = 0.25\n",
44 | "V[55:-55,55:-55,55:-55] = 0.0\n",
45 | "ipv.quickvolshow(V, level=[0.25, 0.75], opacity=0.03, level_width=0.1, data_min=0, data_max=1)"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": null,
51 | "metadata": {},
52 | "outputs": [],
53 | "source": []
54 | }
55 | ],
56 | "metadata": {
57 | "kernelspec": {
58 | "display_name": "Python 3",
59 | "language": "python",
60 | "name": "python3"
61 | },
62 | "language_info": {
63 | "codemirror_mode": {
64 | "name": "ipython",
65 | "version": 3
66 | },
67 | "file_extension": ".py",
68 | "mimetype": "text/x-python",
69 | "name": "python",
70 | "nbconvert_exporter": "python",
71 | "pygments_lexer": "ipython3",
72 | "version": "3.6.1"
73 | }
74 | },
75 | "nbformat": 4,
76 | "nbformat_minor": 2
77 | }
78 |
--------------------------------------------------------------------------------
/re/exercises/regex_solution.py:
--------------------------------------------------------------------------------
1 |
2 | import re
3 | from compare import compare
4 |
5 | def substitution_examples():
6 | """Some examples of using regular expression substitution."""
7 | # example text
8 | text = "7 apples, 24 bananas, 14 carrots, and oranges are fruit"
9 |
10 | # replace one word by another
11 | result = re.sub('carrots','pears',text)
12 | compare(result,"7 apples, 24 bananas, 14 pears, and oranges are fruit")
13 |
14 | # remove all numbers
15 | result = re.sub('\d+ ','',text)
16 | compare(result,"apples, bananas, carrots, and oranges are fruit")
17 |
18 |
19 |
20 | def search_examples():
21 | """Some examples of using regular expression search."""
22 | # example text body: tRNA structures from the PDB
23 | text = """
24 | 2ow8 3.71 tRNA_Phe ribosome_(p-site)
25 | 1b23 2.60 tRNA_Cys Ef-Tu
26 | 1qrt 2.70 tRNA_Gln GlnRS
27 | 1qf6 2.90 tRNA_Thr ThrRS
28 | 1j1u 1.95 tRNA_Tyr TyrRS
29 | 2fk6 2.90 tRNA_Thr RNase_Z
30 | 2hgr 4.51 tRNA_Phe ribosome_(e_or_p-site)
31 | """
32 |
33 | # count frequency of the word 'tRNA'
34 | result = re.findall('tRNA',text)
35 | compare(len(result),7)
36 |
37 | # extract all PDB codes
38 | result = re.findall('\d\w\w\w',text)
39 | compare(result,['2ow8','1b23','1qrt','1qf6','1j1u','2fk6','2hgr'])
40 |
41 | # extract all aromatic amino acids
42 | result = re.findall('tRNA_Phe|tRNA_Tyr|tRNA_Trp',text)
43 | compare(result,['tRNA_Phe','tRNA_Tyr','tRNA_Phe'])
44 |
45 | # extract elements separated by spaces (2 middle columns)
46 | result = re.findall(' [^ ]+ ',text)
47 | compare(len(result),14)
48 |
49 | # extract a whole line containing key phrase 'Ef-Tu'
50 | result = re.findall('(\d.*Ef-Tu.*)\n',text)
51 | compare(result,['1b23 2.60 tRNA_Cys Ef-Tu'])
52 |
53 |
54 | # run both examples
55 | substitution_examples()
56 | search_examples()
57 |
--------------------------------------------------------------------------------
/pillow/snowflake.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image, ImageDraw, ImageFont, ImageFilter
3 | import math
4 |
5 |
6 | class Turtle:
7 | """
8 | Draws turtle graphics on a white background.
9 |
10 | The turtle has a position and a direction,
11 | and can move forward and turn left and right.
12 | """
13 | def __init__(self):
14 | """Initializes the turtle."""
15 | self.x = 0
16 | self.y = 200
17 | self.angle = 0.0
18 | self.image = Image.new('RGB', (500, 250), (255,255,255))
19 | self.draw_tool = ImageDraw.Draw(self.image)
20 |
21 | def turn_left(self,ang):
22 | self.angle -= ang
23 | if self.angle<0: self.angle += 360
24 |
25 | def turn_right(self,ang):
26 | self.angle += ang
27 | if self.angle>=360: self.angle -= 360
28 |
29 | def move_forward(self,length,draw=True):
30 | """
31 | Moves the turtle forward in its current direction.
32 | It draws a line (can be turned off optionally."""
33 | new_x = self.x + length * math.cos(math.radians(self.angle))
34 | new_y = self.y + length * math.sin(math.radians(self.angle))
35 | self.draw_tool.line(((self.x,self.y),(new_x,new_y)), fill=(0,0,0),width=2)
36 | self.x = new_x
37 | self.y = new_y
38 |
39 |
40 |
41 | def snowflake(turtle, length, depth):
42 | """Draws a recursive snowflake curve with the given turtle."""
43 | if depth == 0:
44 | turtle.move_forward(length)
45 | else:
46 | snowflake(turtle, length * 0.333, depth-1)
47 | turtle.turn_left(60)
48 | snowflake(turtle, length * 0.333, depth-1)
49 | turtle.turn_right(120)
50 | snowflake(turtle, length * 0.333, depth-1)
51 | turtle.turn_left(60)
52 | snowflake(turtle, length * 0.333, depth-1)
53 |
54 |
55 |
56 | if __name__ == '__main__':
57 | """Main program. Starts the turtle and draws a snowflake."""
58 | # try different values for 'depth'
59 | t = Turtle()
60 | snowflake(t, 500, 1)
61 | t.image.save('snowflake1.png')
62 | t = Turtle()
63 | snowflake(t, 500, 2)
64 | t.image.save('snowflake2.png')
65 | t = Turtle()
66 | snowflake(t, 500, 5)
67 | t.image.save('snowflake3.png')
68 |
--------------------------------------------------------------------------------
/curses/pac.py:
--------------------------------------------------------------------------------
1 | import curses
2 | import random
3 | import time
4 |
5 | # WASD keys + exit key (X)
6 | KEY_COMMANDS = {97: (-1, 0), 100: (1, 0), 119: (0, -1), 115: (0, 1), 120: (0, 0)}
7 |
8 | # prepare the screen
9 | screen = curses.initscr()
10 | curses.start_color()
11 | curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
12 | curses.curs_set(0)
13 | curses.noecho()
14 | curses.raw()
15 | screen.keypad(False)
16 |
17 | win = curses.newwin(30, 15, 0, 0)
18 | win.nodelay(True)
19 |
20 |
21 | def draw(level, player, ghost, screen, win):
22 | """create a 2D landscape"""
23 | screen.clear()
24 | for y, row in enumerate(level):
25 | for x, char in enumerate(row):
26 | screen.addch(y, x*2, char, curses.color_pair(1))
27 | screen.addch(player[1], player[0] * 2, "O", curses.color_pair(1))
28 | screen.addch(ghost[1], ghost[0] * 2, "G", curses.color_pair(1))
29 | win.refresh()
30 | screen.refresh()
31 |
32 |
33 | def move(position, direction, level):
34 | """change positions"""
35 | x, y = position
36 | dx, dy = direction
37 | nx, ny = x + dx, y + dy
38 | if level[ny][nx] == "#":
39 | return x, y
40 | return nx, ny
41 |
42 |
43 | def move_player(player, direction, level):
44 | """changes position and eats dots"""
45 | x, y = move(player, direction, level)
46 | level[y] = level[y][:x] + " " + level[y][x+1:]
47 | return x, y
48 |
49 |
50 | def move_ghost(ghost, level):
51 | direction = random.choice(list(KEY_COMMANDS.values())[:-1])
52 | return move(ghost, direction, level)
53 |
54 |
55 | def get_keyboard(win):
56 | char = win.getch()
57 | return KEY_COMMANDS.get(char)
58 |
59 | def pac_game(screen):
60 | """called by curses"""
61 | level = """
62 | ###########
63 | #....#....#
64 | #.##...##.#
65 | #.#..#..#.#
66 | #....#....#
67 | ##.#####.##
68 | #....#....#
69 | #.#..#..#.#
70 | #.##...##.#
71 | #....#....#
72 | ###########""".strip().split()
73 | player = 1, 1
74 | ghost = 9, 9
75 |
76 | while player != ghost and any([row for row in level if "." in row]):
77 | ghost = move_ghost(ghost, level)
78 | draw(level, player, ghost, screen, win)
79 | if direction := get_keyboard(win):
80 | if direction == (0, 0):
81 | player = ghost
82 | else:
83 | player = move_player(player, direction, level)
84 | else:
85 | time.sleep(0.1)
86 |
87 |
88 | if __name__ == "__main__":
89 | curses.wrapper(pac_game)
90 | curses.endwin()
--------------------------------------------------------------------------------
/pillow/flower_movie/flower_movie.py:
--------------------------------------------------------------------------------
1 |
2 | from PIL import Image, ImageDraw, ImageFont, ImageFilter
3 | import random
4 |
5 |
6 | NPIECES = 25 # 16
7 | EDGEWIDTH = 16 # 25
8 | VEC_GROWTH = 1.020 # 1.03
9 | PHASE1_FRAMES = 250
10 | PHASE2_FRAMES = 100
11 |
12 |
13 | def create_pieces(filename):
14 | """
15 | Takes a picture and dissects it into NPIECES**2
16 | smaller images
17 | """
18 | flower = Image.open(filename, 'r')
19 | flower = flower.resize((NPIECES * EDGEWIDTH, NPIECES * EDGEWIDTH))
20 |
21 | pieces = []
22 | positions = []
23 | for x in range(NPIECES):
24 | for y in range(NPIECES):
25 | copy = flower.copy()
26 | piece = copy.crop((x * EDGEWIDTH, y * EDGEWIDTH,
27 | (x + 1) * EDGEWIDTH, (y + 1) * EDGEWIDTH))
28 | pieces.append(piece)
29 | positions.append((x * EDGEWIDTH, y * EDGEWIDTH))
30 | return pieces, positions
31 |
32 |
33 | def increment():
34 | """Returns a random number from +-0.1 .. 1.1"""
35 | inc = random.random() + 0.1
36 | if random.random() > 0.5:
37 | return -inc
38 | return inc
39 |
40 |
41 | def randvec():
42 | """Returns a random (x, y) vector"""
43 | return increment(), increment()
44 |
45 |
46 | def create_image(pieces, positions):
47 | """Assembles all small pieces to a big image"""
48 | img = Image.new("RGB", (NPIECES * EDGEWIDTH, NPIECES * EDGEWIDTH))
49 | for pc, pos in zip(pieces, positions):
50 | img.paste(pc, pos)
51 | return img
52 |
53 |
54 | def move_pieces(positions, vectors):
55 | """modifies positions of images"""
56 | new_pos = []
57 | for pos, vec in zip(positions, vectors):
58 | new_pos.append((pos[0] + int(vec[0]), pos[1] + int(vec[1])))
59 | return new_pos
60 | # TODO: this would be much easier with pandas!!!
61 |
62 |
63 | def increase_vectors(vectors):
64 | """accelerate so that pieces move faster in earlier frames"""
65 | new_vecs = []
66 | for vec in vectors:
67 | new_vecs.append((vec[0]*VEC_GROWTH, vec[1]*VEC_GROWTH))
68 | return new_vecs
69 |
70 |
71 | if __name__ == '__main__':
72 | pcs, pos = create_pieces('flower.jpg')
73 | vecs = [randvec() for i in pos]
74 |
75 | # writing standstill frames at the end.
76 | img = create_image(pcs, pos)
77 | for iframe in range(PHASE1_FRAMES, PHASE1_FRAMES + PHASE2_FRAMES):
78 | img.save('out/frame_{:04d}.png'.format(iframe))
79 |
80 | # writing gradually dissipating frames
81 | for iframe in range(PHASE1_FRAMES, 0, -1):
82 | img = create_image(pcs, pos)
83 | img.save('out/frame_{:04d}.png'.format(iframe))
84 | pos = move_pieces(pos, vecs)
85 | vecs = increase_vectors(vecs)
86 |
--------------------------------------------------------------------------------
/index.rst:
--------------------------------------------------------------------------------
1 | Python Library Examples
2 | =======================
3 |
4 | Here you find easy copy-paste examples of my favourite Python libraries.
5 |
6 |
7 | Builtin modules
8 | ---------------
9 |
10 | .. toctree::
11 | :maxdepth: 2
12 |
13 | itertools/README.rst
14 | math/README.rst
15 | os/README.rst
16 | pathlib/README.rst
17 | random/README.rst
18 | re/README.rst
19 | sys/README.rst
20 | time/README.rst
21 |
22 | Reading and Writing Files
23 | -------------------------
24 |
25 | .. toctree::
26 | :maxdepth: 2
27 |
28 | json/README.rst
29 | xml/README.rst
30 | zipfile/README.rst
31 |
32 |
33 | ::
34 |
35 | pydocx](pydocx/) | read Word documents |
36 | pypdf2](pypdf2/) | merge PDF documents |
37 |
38 |
39 | Data Science
40 | ------------
41 |
42 | .. toctree::
43 | :maxdepth: 2
44 |
45 | numpy/README.rst
46 | pandas/README.rst
47 | scipy/README.rst
48 |
49 | scikit-learn](sklearn/) | Machine Learning |
50 | PuLP](PuLP/) | linear equation solver |
51 | fuzzywuzzy](fuzzywuzzy/) | fuzzy text search |
52 | vader/README.rst
53 | statsmodels (external)](http://statsmodels.sourceforge.net/) | Hypothesis tests and statistical models |
54 |
55 |
56 | Plotting
57 | --------
58 |
59 | folium](folium/) | drawing maps |
60 | matplotlib](matplotlib/) | plotting diagrams |
61 | NetworkX](networkx/) | analyze and plot graphs |
62 | wordcloud](wordcloud/) | plot word clouds |
63 |
64 | Image Processing
65 | ----------------
66 |
67 | pillow - image manipulation](pillow/) | |
68 | pytesseract](pytesseract/) | extract text from images (OCR) |
69 | scikit-image](scikit_image/) | Advanced image processing |
70 |
71 | Databases
72 | ---------
73 |
74 | pymongo/README.rst
75 | sqlite3](sqlite3/) | a simple SQL database |
76 |
77 | Web programming
78 | ---------------
79 |
80 | httpx/README.rst
81 | BeautifulSoup4](beautiful_soup/) | parse HTML pages |
82 | email](email/) | send emails |
83 | flask](flask/) | a simple web server |
84 | OAUTH - authentication](oauth_git/) | authentication |
85 | scrapy (external)](http://scrapy.org/) | collect data from entire websites |
86 |
87 | User Interfaces
88 | ---------------
89 |
90 | .. toctree::
91 | :maxdepth: 2
92 |
93 | tqdm/README.rst
94 | tkinter/README.rst
95 | curses/README.rst
96 |
97 | Acknowledgements
98 | ----------------
99 |
100 | Thanks to Emely Henninger for finding a nasty bug in networkx!
101 |
102 |
103 | .. topic:: License
104 |
105 | © 2025 Dr. Kristian Rother (`kristian.rother@posteo.de`)
106 |
107 | The code is distributed under the conditions of the MIT License. See :download:`LICENSE.TXT` for details.
108 |
109 | Text may be reused under the conditions of the Creative Commons Attribution Share-alike License 4.0 (CC-BY-SA 4.0).
110 | See `creativecommons.org `__ for details
111 |
--------------------------------------------------------------------------------
/pypdf2/extras/pdf.py:
--------------------------------------------------------------------------------
1 | import textract # modul zum extrahieren von text aus pdf datein
2 | import re # reguläre ausdrücke
3 | import operator # hilfe beim sortieren nach value
4 |
5 | # text aus pdf extrahieren
6 | text = textract.process("skript_101.pdf", encoding="utf-8")
7 | # bytestring zu utf-8 dekodieren
8 | text = text.decode('utf-8')
9 |
10 | # zeilen am newline character "\n" splitten
11 | lines = text.split('\n')
12 |
13 | titleIndex = 0 # dokumententitel
14 | authorIndex = 1 # dokumentenautorin
15 | dropIndex = [3,4] # müll
16 |
17 | title = lines[titleIndex]
18 | author = lines[authorIndex]
19 |
20 | # überschriften + unnötige lines im skript löschen
21 | counter = 0
22 | for i in drop_index:
23 | del lines[i-counter]
24 | counter += 1
25 | del lines[authorIndex]
26 | del lines[titleIndex]
27 |
28 | # funktion um herauszufinden welcher teil vom skript einem sprecher zuzuordnen ist
29 | def isName(str):
30 | if str:
31 | if len(str.split(' ')) == 1 and \
32 | str[0].isupper() and \
33 | str[-1:].isalpha():
34 | return True
35 | return False
36 |
37 | # zeilen für jeden sprecher in ein dictionary einsortieren
38 | speakerText = dict()
39 | for i, l in enumerate(lines):
40 | if isName(l):
41 | name = l
42 | text = ""
43 | counter = 2
44 | # suche nach zusätzlichen zeilen
45 | tmp = lines[i+counter] # potentielle neue zeile
46 | while tmp: # tmp ist nicht leer
47 | if counter > 2: # neue zeile gefunden
48 | text += " " # trennen mit leerzeichen
49 | text += tmp # zeilen kombinieren
50 | counter += 1 # zähler erhöhen
51 | tmp = lines[i+counter] # tmp updaten
52 | if not text: # text ist leer
53 | continue # nächste zeile
54 | if name in speakerText: # key (name des sprechers) vorhanden
55 | speakerText[name].append(text) # array anfügen
56 | else: # key unbekannt
57 | speakerText[name] = [text] # neues array mit text
58 |
59 | # für jeden sprecher die worthäufigkeit zählen
60 | speakerWordCount = dict()
61 | for name, lines in speakerText.items():
62 | wordCount = dict()
63 | for l in lines: # für jede zeile
64 | # ignoriere alle satzzeichen, finde wörter
65 | words = re.findall("[A-Za-z\[\]äöüß]+", l.lower())
66 | for w in words:
67 | if w in wordCount: # key vorhanden
68 | wordCount[w] += 1
69 | else: # key unbekannt
70 | wordCount[w] = 1
71 | speakerWordCount[name] = wordCount
72 |
73 | # wortanzahl pro sprecher
74 | speakerCount = dict()
75 | for name in wordFrequency:
76 | total = 0
77 | for key,value in wordFrequency[name].items():
78 | total += value # summiere worthäufigkeit
79 | speakerCount[name] = total
80 |
81 | # sortierte wortzahl
82 | sorted(speakerCount.items(), key=operator.itemgetter(1),reverse=True)
83 |
84 | # justus häufigste wörter
85 | sorted(wordFrequency["Justus"].items(), key=operator.itemgetter(1),reverse=True)
86 |
87 | # peters häufigste wörter
88 | sorted(wordFrequency["Peter"].items(), key=operator.itemgetter(1),reverse=True)
89 |
90 | # bobs häufigste wörter
91 | sorted(wordFrequency["Bob"].items(), key=operator.itemgetter(1),reverse=True)
92 |
93 |
94 |
--------------------------------------------------------------------------------
/ipywidgets/ipywidgets.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# IPywidgets\n",
8 | "see https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20List.html"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 1,
14 | "metadata": {},
15 | "outputs": [],
16 | "source": [
17 | "from ipywidgets import interact, widgets"
18 | ]
19 | },
20 | {
21 | "cell_type": "code",
22 | "execution_count": 2,
23 | "metadata": {},
24 | "outputs": [
25 | {
26 | "data": {
27 | "application/vnd.jupyter.widget-view+json": {
28 | "model_id": "b4ccba38a0164c59bf72c2a64ee7c6cd",
29 | "version_major": 2,
30 | "version_minor": 0
31 | },
32 | "text/plain": [
33 | "interactive(children=(IntSlider(value=30, description='x', max=60, step=2), Output()), _dom_classes=('widget-i…"
34 | ]
35 | },
36 | "metadata": {},
37 | "output_type": "display_data"
38 | },
39 | {
40 | "data": {
41 | "text/plain": [
42 | ""
43 | ]
44 | },
45 | "execution_count": 2,
46 | "metadata": {},
47 | "output_type": "execute_result"
48 | }
49 | ],
50 | "source": [
51 | "def show_number(x):\n",
52 | " print('=' * x)\n",
53 | " \n",
54 | "interact(show_number, x=(0, 60, 2))"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": 3,
60 | "metadata": {},
61 | "outputs": [
62 | {
63 | "data": {
64 | "application/vnd.jupyter.widget-view+json": {
65 | "model_id": "1ef02f50e77d401e86f2350046c85dee",
66 | "version_major": 2,
67 | "version_minor": 0
68 | },
69 | "text/plain": [
70 | "interactive(children=(ColorPicker(value='blue', description='Pick a color'), Output()), _dom_classes=('widget-…"
71 | ]
72 | },
73 | "metadata": {},
74 | "output_type": "display_data"
75 | },
76 | {
77 | "data": {
78 | "text/plain": [
79 | ""
80 | ]
81 | },
82 | "execution_count": 3,
83 | "metadata": {},
84 | "output_type": "execute_result"
85 | }
86 | ],
87 | "source": [
88 | "col = widgets.ColorPicker(\n",
89 | " concise=False,\n",
90 | " description='Pick a color',\n",
91 | " value='blue',\n",
92 | " disabled=False\n",
93 | ")\n",
94 | "\n",
95 | "def clicked(color):\n",
96 | " print(\"you picked: \", color)\n",
97 | " \n",
98 | "interact(clicked, color=col)"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {},
105 | "outputs": [],
106 | "source": []
107 | }
108 | ],
109 | "metadata": {
110 | "kernelspec": {
111 | "display_name": "Python 3",
112 | "language": "python",
113 | "name": "python3"
114 | },
115 | "language_info": {
116 | "codemirror_mode": {
117 | "name": "ipython",
118 | "version": 3
119 | },
120 | "file_extension": ".py",
121 | "mimetype": "text/x-python",
122 | "name": "python",
123 | "nbconvert_exporter": "python",
124 | "pygments_lexer": "ipython3",
125 | "version": "3.6.5"
126 | }
127 | },
128 | "nbformat": 4,
129 | "nbformat_minor": 2
130 | }
131 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Python Library Examples
3 |
4 | Here you find easy copy-paste examples of my favourite Python libraries.
5 |
6 | ## Builtin modules
7 |
8 | | package | description |
9 | |---------|-------------|
10 | | [itertools](itertools/) | working with lists and generators |
11 | | [math](math/) | mathematical functions |
12 | | [os](os/) | working with files and directories |
13 | | [random](random/) | generating random numbers |
14 | | [re](re/) | pattern matching in text |
15 | | [sys](sys/) | settings of the Python interpreter |
16 | | [time](time/) | working with dates and times |
17 |
18 | ## Reading and Writing Files
19 |
20 | | package | description |
21 | |---------|-------------|
22 | | [json](json/) | read/write JSON files |
23 | | [pydocx](pydocx/) | read Word documents |
24 | | [pypdf2](pypdf2/) | merge PDF documents |
25 | | [xml](xml/) | parse XML files |
26 | | [zipfile](zipfile/) | read and write .zip files |
27 | | [librosa (external)](https://librosa.org/) | process and analyze sound and music |
28 |
29 |
30 | ## Data Science
31 |
32 | | package | description |
33 | |---------|-------------|
34 | | [numpy](numpy/) | fast numerical calculations |
35 | | [pandas](pandas/) | analyze tabular data |
36 | | [scipy](scipy/) | scientific calculations |
37 | | [scikit-learn](sklearn/) | Machine Learning |
38 | | [RPy2](RPy/) | Use R functions from within Python |
39 | | [PuLP](PuLP/) | linear equation solver |
40 | | [fuzzywuzzy](fuzzywuzzy/) | fuzzy text search |
41 | | [vader](vader/) | sentiment analysis |
42 | | [statsmodels (external)](http://statsmodels.sourceforge.net/) | Hypothesis tests and statistical models |
43 |
44 |
45 | ## Plotting
46 |
47 | | package | description |
48 | |---------|-------------|
49 | | [folium](folium/) | drawing maps |
50 | | [matplotlib](matplotlib/) | plotting diagrams |
51 | | [NetworkX](networkx/) | analyze and plot graphs |
52 | | [wordcloud](wordcloud/) | plot word clouds |
53 | | [seaborn (external)](https://seaborn.pydata.org/) | a more powerful interface for matplotlib |
54 | | [altair (external)](https://altair-viz.github.io/) | plotting library with JSON backend |
55 | | [geopandas (external)](http://geopandas.org/) | plot DataFrames on maps |
56 | | [panel (external)](http://panel.pyviz.org/) | create interactive plots |
57 |
58 | ## Image Processing
59 |
60 | | package | description |
61 | |---------|-------------|
62 | | [pillow - image manipulation](pillow/) | |
63 | | [ipythonblocks](ipythonblocks/) | drawing blocks in notebooks |
64 | | [pytesseract](pytesseract/) | extract text from images (OCR) |
65 | | [scikit-image](scikit_image/) | Advanced image processing |
66 | | [CV2 (external)](https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_tutorials.html) | processing camera images and movies |
67 |
68 | ## Databases
69 |
70 | | package | description |
71 | |---------|-------------|
72 | | [pymongo](pymongo/) | adapter for the MongoDB NoSQL database |
73 | | [sqlite3](sqlite3/) | a simple SQL database |
74 |
75 | ## Web programming
76 |
77 | | package | description |
78 | |---------|-------------|
79 | | [BeautifulSoup4](beautiful_soup/) | parse HTML pages |
80 | | [email](email/) | send emails |
81 | | [flask](flask/) | a simple web server |
82 | | [requests](requests/) | retrieve web pages |
83 | | [OAUTH - authentication](oauth_git/) | authentication |
84 | | [scrapy (external)](http://scrapy.org/) | collect data from entire websites |
85 |
86 | ## User Interfaces
87 |
88 | | package | description |
89 | |---------|-------------|
90 | | [curses](curses/) | interactive terminal interface |
91 | | [tkinter](tkinter/) | graphical user interfaces |
92 | | [tqdm](tqdm/) | draw progress bars |
93 |
94 |
95 | ## More Libraries
96 |
97 | * [Awesome Python](https://awesome-python.com/) is a curated list of Python libraries and tools.
98 |
99 | ## Source
100 |
101 | [github.com/krother/Python3_Package_Examples](https://github.com/krother/Python3_Package_Examples)
102 |
103 | ## Acknowledgements
104 |
105 | Thanks to Emely Henninger for finding a nasty bug in networkx!
106 |
107 | ## License
108 |
109 | © 2025 Dr. Kristian Rother (krother@academis.eu)
110 |
111 | The code is distributed under the conditions of the MIT License. See :::file LICENSE.TXT for details.
112 |
--------------------------------------------------------------------------------
/pypdf2/extras/pdf2txt.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """
4 | Converts PDF text content (though not images containing text) to plain text, html, xml or "tags".
5 | """
6 | import sys
7 | import logging
8 | import six
9 | import pdfminer.settings
10 | pdfminer.settings.STRICT = False
11 | import pdfminer.high_level
12 | import pdfminer.layout
13 | from pdfminer.image import ImageWriter
14 |
15 |
16 | def extract_text(files=[], outfile='-',
17 | _py2_no_more_posargs=None, # Bloody Python2 needs a shim
18 | no_laparams=False, all_texts=None, detect_vertical=None, # LAParams
19 | word_margin=None, char_margin=None, line_margin=None, boxes_flow=None, # LAParams
20 | output_type='text', codec='utf-8', strip_control=False,
21 | maxpages=0, page_numbers=None, password="", scale=1.0, rotation=0,
22 | layoutmode='normal', output_dir=None, debug=False,
23 | disable_caching=False, **other):
24 | if _py2_no_more_posargs is not None:
25 | raise ValueError("Too many positional arguments passed.")
26 | if not files:
27 | raise ValueError("Must provide files to work upon!")
28 |
29 | # If any LAParams group arguments were passed, create an LAParams object and
30 | # populate with given args. Otherwise, set it to None.
31 | if not no_laparams:
32 | laparams = pdfminer.layout.LAParams()
33 | for param in ("all_texts", "detect_vertical", "word_margin", "char_margin", "line_margin", "boxes_flow"):
34 | paramv = locals().get(param, None)
35 | if paramv is not None:
36 | setattr(laparams, param, paramv)
37 | else:
38 | laparams = None
39 |
40 | imagewriter = None
41 | if output_dir:
42 | imagewriter = ImageWriter(output_dir)
43 |
44 | if output_type == "text" and outfile != "-":
45 | for override, alttype in ( (".htm", "html"),
46 | (".html", "html"),
47 | (".xml", "xml"),
48 | (".tag", "tag") ):
49 | if outfile.endswith(override):
50 | output_type = alttype
51 |
52 | if outfile == "-":
53 | outfp = sys.stdout
54 | if outfp.encoding is not None:
55 | codec = 'utf-8'
56 | else:
57 | outfp = open(outfile, "wb")
58 |
59 |
60 | for fname in files:
61 | with open(fname, "rb") as fp:
62 | pdfminer.high_level.extract_text_to_fp(fp, **locals())
63 | return outfp
64 |
65 | # main
66 | def main(args=None):
67 | import argparse
68 | P = argparse.ArgumentParser(description=__doc__)
69 | P.add_argument("files", type=str, default=None, nargs="+", help="Files to process.")
70 | P.add_argument("-d", "--debug", default=False, action="store_true", help="Debug output.")
71 | P.add_argument("-p", "--pagenos", type=str, help="Comma-separated list of page numbers to parse. Included for legacy applications, use -P/--page-numbers for more idiomatic argument entry.")
72 | P.add_argument("--page-numbers", type=int, default=None, nargs="+", help="Alternative to --pagenos with space-separated numbers; supercedes --pagenos where it is used.")
73 | P.add_argument("-m", "--maxpages", type=int, default=0, help = "Maximum pages to parse")
74 | P.add_argument("-P", "--password", type=str, default="", help = "Decryption password for PDF")
75 | P.add_argument("-o", "--outfile", type=str, default="-", help="Output file (default/'-' is stdout)")
76 | P.add_argument("-t", "--output_type", type=str, default="text", help = "Output type: text|html|xml|tag (default is text)")
77 | P.add_argument("-c", "--codec", type=str, default="utf-8", help = "Text encoding")
78 | P.add_argument("-s", "--scale", type=float, default=1.0, help = "Scale")
79 | P.add_argument("-A", "--all-texts", default=None, action="store_true", help="LAParams all texts")
80 | P.add_argument("-V", "--detect-vertical", default=None, action="store_true", help="LAParams detect vertical")
81 | P.add_argument("-W", "--word-margin", type=float, default=None, help = "LAParams word margin")
82 | P.add_argument("-M", "--char-margin", type=float, default=None, help = "LAParams char margin")
83 | P.add_argument("-L", "--line-margin", type=float, default=None, help = "LAParams line margin")
84 | P.add_argument("-F", "--boxes-flow", type=float, default=None, help = "LAParams boxes flow")
85 | P.add_argument("-Y", "--layoutmode", default="normal", type=str, help="HTML Layout Mode")
86 | P.add_argument("-n", "--no-laparams", default=False, action="store_true", help = "Pass None as LAParams")
87 | P.add_argument("-R", "--rotation", default=0, type=int, help = "Rotation")
88 | P.add_argument("-O", "--output-dir", default=None, help="Output directory for images")
89 | P.add_argument("-C", "--disable-caching", default=False, action="store_true", help="Disable caching")
90 | P.add_argument("-S", "--strip-control", default=False, action="store_true", help="Strip control in XML mode")
91 | A = P.parse_args(args=args)
92 |
93 | if A.page_numbers:
94 | A.page_numbers = set([x-1 for x in A.page_numbers])
95 | if A.pagenos:
96 | A.page_numbers = set([int(x)-1 for x in A.pagenos.split(",")])
97 |
98 | imagewriter = None
99 | if A.output_dir:
100 | imagewriter = ImageWriter(A.output_dir)
101 |
102 | if six.PY2 and sys.stdin.encoding:
103 | A.password = A.password.decode(sys.stdin.encoding)
104 |
105 | if A.output_type == "text" and A.outfile != "-":
106 | for override, alttype in ( (".htm", "html"),
107 | (".html", "html"),
108 | (".xml", "xml" ),
109 | (".tag", "tag" ) ):
110 | if A.outfile.endswith(override):
111 | A.output_type = alttype
112 |
113 | if A.outfile == "-":
114 | outfp = sys.stdout
115 | if outfp.encoding is not None:
116 | # Why ignore outfp.encoding? :-/ stupid cathal?
117 | A.codec = 'utf-8'
118 | else:
119 | outfp = open(A.outfile, "wb")
120 |
121 | ## Test Code
122 | outfp = extract_text(**vars(A))
123 | outfp.close()
124 | return 0
125 |
126 |
127 | if __name__ == '__main__': sys.exit(main())
128 |
--------------------------------------------------------------------------------
/tkinter/titanic_sinks.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
19 |
21 |
24 |
32 |
33 |
34 |
53 |
55 |
56 |
58 | image/svg+xml
59 |
61 |
62 |
63 |
64 |
65 |
69 |
78 |
84 |
87 |
93 |
98 |
99 |
101 |
107 |
112 |
113 |
116 |
122 |
127 |
128 |
131 |
137 |
142 |
143 |
148 |
154 |
155 |
163 |
172 | muahaha
194 |
201 |
202 |
203 |
--------------------------------------------------------------------------------
/PuLP/BricksLinear.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Bricks\n",
8 | "*a linear optimization problem solved with PuLP*"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {},
14 | "source": [
15 | "## Problem Description\n",
16 | "\n",
17 | "We want to place a series of colored bricks in a N x M box\n",
18 | "\n",
19 | ""
20 | ]
21 | },
22 | {
23 | "cell_type": "markdown",
24 | "metadata": {},
25 | "source": [
26 | "The bricks need to be placed according the following rules:\n",
27 | "\n",
28 | "* all bricks with the same colour should end up in the same column\n",
29 | "* if this is not possible, the rightmost column of one colour should be filled up first\n",
30 | "* bricks of one colour should be as close to each other on the x-axis as possible\n",
31 | "\n",
32 | "A possible solution could look like this:\n",
33 | "\n",
34 | "\n",
35 | "\n",
36 | "This notebook shows how to solve this problem using the **linear equation solver PuLP**."
37 | ]
38 | },
39 | {
40 | "cell_type": "markdown",
41 | "metadata": {},
42 | "source": [
43 | "## Preparations\n",
44 | "\n",
45 | "First, we define the bricks and their colours in Python:"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": 1,
51 | "metadata": {
52 | "collapsed": false
53 | },
54 | "outputs": [],
55 | "source": [
56 | "bricks = ['a1', 'a2', 'a3', 'b1', 'b2', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'e1']"
57 | ]
58 | },
59 | {
60 | "cell_type": "markdown",
61 | "metadata": {},
62 | "source": [
63 | "We also define the size of the box to stack bricks in. A list of positions will help us later."
64 | ]
65 | },
66 | {
67 | "cell_type": "code",
68 | "execution_count": 2,
69 | "metadata": {
70 | "collapsed": true
71 | },
72 | "outputs": [],
73 | "source": [
74 | "XSIZE = 4\n",
75 | "YSIZE = 3\n",
76 | "positions = [(x,y) for x in range(XSIZE) for y in range(YSIZE)]"
77 | ]
78 | },
79 | {
80 | "cell_type": "markdown",
81 | "metadata": {},
82 | "source": [
83 | "## Modeling a Linear Equation System\n",
84 | "To model our problem using **PuLP**, we need to perform four steps:\n",
85 | "\n",
86 | "1. Define the model variables\n",
87 | "2. Define the optimization function\n",
88 | "3. Add linear constraints\n",
89 | "4. Run the solver\n"
90 | ]
91 | },
92 | {
93 | "cell_type": "markdown",
94 | "metadata": {},
95 | "source": [
96 | "### Step 1: Define the model variables\n",
97 | "\n",
98 | "Our model variable will be a binary matrix with four dimensions. The first two dimensions are quite obvious: each space in the box has its own **x, y** position in the matrix. The third dimension are the bricks **b** themselves. We use them to specify, which brick occupies a certain space. \n",
99 | "\n",
100 | "The fourth dimension is probably the least obvious: It is the column **rb** in which bricks of one colour should be placed. We use it to link bricks of the same colour together."
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": 3,
106 | "metadata": {
107 | "collapsed": false
108 | },
109 | "outputs": [],
110 | "source": [
111 | "from pulp import *\n",
112 | "\n",
113 | "v = LpVariable.dicts(\"bricks\", (range(XSIZE), range(YSIZE), bricks, range(XSIZE)), \\\n",
114 | " lowBound = 0, upBound = 1, cat = LpInteger)"
115 | ]
116 | },
117 | {
118 | "cell_type": "markdown",
119 | "metadata": {},
120 | "source": [
121 | "#### Why don't we simply assign each brick a number instead of an extra dimension?\n",
122 | "Yes, it would be nice to cut out an extra dimension from the matrix. However, we cannot discretisize numbers in a linear equation system (e.g. say *\"If x is 3 do this, if x is 4 do something else\"*). I find this quite a strong limitation, and the binary matrix is the proper way to say *\"I have discrete bricks a, b, c.. in my system\".*.\n",
123 | "\n",
124 | "#### I don't understand why range(XSIZE) appears twice.\n",
125 | "Each brick has two X values assigned: the first is the column **x** in which the brick actually is, the second is the rightmost column **rb** in which bricks of this colour should gather. We need this second value to implement the second and third rule above."
126 | ]
127 | },
128 | {
129 | "cell_type": "markdown",
130 | "metadata": {},
131 | "source": [
132 | "### Step 2: Define the Optimization Function\n",
133 | "\n",
134 | "We first tell PuLP that we have something to minimize:"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": 4,
140 | "metadata": {
141 | "collapsed": true
142 | },
143 | "outputs": [],
144 | "source": [
145 | "m = LpProblem(\"Bricks\", LpMinimize)"
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {},
151 | "source": [
152 | "We want to tell PuLP to minimize the distance bricks have from their colleagues to the right. For that, we need to construct a penalty matrix first. We say that any block in column *x* that ought to be in colum *rb* has a penalty of `10` for each column in between:"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": 5,
158 | "metadata": {
159 | "collapsed": false
160 | },
161 | "outputs": [
162 | {
163 | "data": {
164 | "text/plain": [
165 | "{(0, 0): 0,\n",
166 | " (0, 1): 10,\n",
167 | " (0, 2): 20,\n",
168 | " (0, 3): 30,\n",
169 | " (1, 0): 10,\n",
170 | " (1, 1): 0,\n",
171 | " (1, 2): 10,\n",
172 | " (1, 3): 20,\n",
173 | " (2, 0): 20,\n",
174 | " (2, 1): 10,\n",
175 | " (2, 2): 0,\n",
176 | " (2, 3): 10,\n",
177 | " (3, 0): 30,\n",
178 | " (3, 1): 20,\n",
179 | " (3, 2): 10,\n",
180 | " (3, 3): 0}"
181 | ]
182 | },
183 | "execution_count": 5,
184 | "metadata": {},
185 | "output_type": "execute_result"
186 | }
187 | ],
188 | "source": [
189 | "penalties = {}\n",
190 | "for x in range(XSIZE):\n",
191 | " for rb in range(XSIZE):\n",
192 | " penalties[(x, rb)] = 10 * abs(rb - x)\n",
193 | "penalties"
194 | ]
195 | },
196 | {
197 | "cell_type": "markdown",
198 | "metadata": {},
199 | "source": [
200 | "In a linear equation system, everything needs to be composed of terms like `a*x` that are added together. This is why you will see **sum** symbols frequently. Our minimization function *m* is:\n",
201 | "\n",
202 | "$$m(v) = \\sum_{x,y,b,rb}penalties_{x,rb} * v_{x,y,n,rb}$$ \n",
203 | "\n",
204 | "In PuLP, this minimization function is formulated as a sum with a scary-looking list comprehension:"
205 | ]
206 | },
207 | {
208 | "cell_type": "code",
209 | "execution_count": 6,
210 | "metadata": {
211 | "collapsed": false
212 | },
213 | "outputs": [],
214 | "source": [
215 | "m += lpSum([penalties[(x,rb)] * v[x][y][b][rb] for x,y in positions for b in bricks for rb in range(XSIZE)])"
216 | ]
217 | },
218 | {
219 | "cell_type": "markdown",
220 | "metadata": {},
221 | "source": [
222 | "### Step 3: Adding linear constraints\n",
223 | "Now we specify additional rules and conditions. We need to formulate these in the linear form as well. More sums, that is.\n",
224 | "\n",
225 | "#### Condition 1: One brick per position\n",
226 | "First, we want to specify that there can be only one brick per position. In math notation this is:\n",
227 | "\n",
228 | "$$\\sum_{b,rb} v_{x,y,b,rb} <= 1$$\n",
229 | "\n",
230 | "This condition must be true for each possible **x** and **y** value.\n",
231 | "\n",
232 | "In Python, it looks similar if you are familiar with **list comprehensions**."
233 | ]
234 | },
235 | {
236 | "cell_type": "code",
237 | "execution_count": 7,
238 | "metadata": {
239 | "collapsed": false
240 | },
241 | "outputs": [],
242 | "source": [
243 | "for x, y in positions:\n",
244 | " m += lpSum([v[x][y][b][rb] for b in bricks for rb in range(XSIZE)]) <= 1"
245 | ]
246 | },
247 | {
248 | "cell_type": "markdown",
249 | "metadata": {},
250 | "source": [
251 | "#### Condition 2: One position per brick\n",
252 | "Likewise, each brick can have only one position. This should be obvious, but given the binary matrix we still have to say it explicitly:"
253 | ]
254 | },
255 | {
256 | "cell_type": "code",
257 | "execution_count": 8,
258 | "metadata": {
259 | "collapsed": false
260 | },
261 | "outputs": [],
262 | "source": [
263 | "for b in bricks:\n",
264 | " m += lpSum([v[x][y][b][rb] for x, y in positions for rb in range(XSIZE)]) == 1"
265 | ]
266 | },
267 | {
268 | "cell_type": "markdown",
269 | "metadata": {},
270 | "source": [
271 | "#### Condition 3: no bricks right of the rb column\n",
272 | "We want to implement the column **rb** (our fourth dimension) as a hard boundary. So no bricks should appear right of it. Hopefully this results in bricks stackin up in the **rb** column, and those left over left of it.\n",
273 | "\n",
274 | "We do this by adding a constraint that certain columns need to be zero."
275 | ]
276 | },
277 | {
278 | "cell_type": "code",
279 | "execution_count": 9,
280 | "metadata": {
281 | "collapsed": true
282 | },
283 | "outputs": [],
284 | "source": [
285 | "for x in range(XSIZE):\n",
286 | " for rb in range(XSIZE):\n",
287 | " if x > rb:\n",
288 | " m += lpSum([v[x][y][b][rb] for y in range(YSIZE) for b in bricks]) == 0"
289 | ]
290 | },
291 | {
292 | "cell_type": "markdown",
293 | "metadata": {},
294 | "source": [
295 | "The art of formulating a linear problem with PuLP is to know, when to put a for loop into the sum (corresponding to an index in a sum symbol) or outside (corresponding to having multiple sums)."
296 | ]
297 | },
298 | {
299 | "cell_type": "markdown",
300 | "metadata": {},
301 | "source": [
302 | "#### Condition 4: bricks of same colour stick together\n",
303 | "This was the tough one while developing the example. We tell our equation system that any two bricks of the same colour must have the same right boundary **rb**. This way, we enforce that the same penalties in the minimization apply to one colour.\n",
304 | "\n",
305 | "For the implementation, we need to add a separate constraint for each pair of bricks. For each pair and rb value, the corresponding values in **v** are either both 1 or both 0, which we can check by calculating their difference:"
306 | ]
307 | },
308 | {
309 | "cell_type": "code",
310 | "execution_count": 10,
311 | "metadata": {
312 | "collapsed": true
313 | },
314 | "outputs": [],
315 | "source": [
316 | "pairs = [('a1', 'a2'), ('a1', 'a3'), ('a2', 'a3'), \n",
317 | " ('b1', 'b2'),\n",
318 | " ('c1', 'c2'), ('c1', 'c3'), ('c2', 'c3'), ('c1', 'c4'), ('c2', 'c4'), ('c3', 'c4'),\n",
319 | " ('d1', 'd2')\n",
320 | " ]\n",
321 | "\n",
322 | "for b1, b2 in pairs:\n",
323 | " for rb in range(XSIZE):\n",
324 | " m += lpSum([v[x][y][b1][rb] for x,y in positions] + [-v[x][y][b2][rb] for x,y in positions]) == 0"
325 | ]
326 | },
327 | {
328 | "cell_type": "markdown",
329 | "metadata": {},
330 | "source": [
331 | "#### Remark\n",
332 | "You might realize two things from this:\n",
333 | "* If you were to implement this as an algorithm, it would be **much easier**. But in a linear system it is not\n",
334 | "* The number of constraints explodes if you have more bricks or a bigger box. The complexity is something like $O(b^2 * x)$, which certainly is bad news."
335 | ]
336 | },
337 | {
338 | "cell_type": "markdown",
339 | "metadata": {},
340 | "source": [
341 | "### Step 4: Run the Solver\n",
342 | "Finally we can ask PuLP to solve the problem:"
343 | ]
344 | },
345 | {
346 | "cell_type": "code",
347 | "execution_count": 11,
348 | "metadata": {
349 | "collapsed": false
350 | },
351 | "outputs": [
352 | {
353 | "name": "stdout",
354 | "output_type": "stream",
355 | "text": [
356 | "Status: Optimal\n"
357 | ]
358 | }
359 | ],
360 | "source": [
361 | "m.solve()\n",
362 | "print(\"Status:\", LpStatus[m.status])"
363 | ]
364 | },
365 | {
366 | "cell_type": "markdown",
367 | "metadata": {},
368 | "source": [
369 | "## Display the result\n",
370 | "Lets see whether it really worked:"
371 | ]
372 | },
373 | {
374 | "cell_type": "code",
375 | "execution_count": 12,
376 | "metadata": {
377 | "collapsed": false
378 | },
379 | "outputs": [
380 | {
381 | "name": "stdout",
382 | "output_type": "stream",
383 | "text": [
384 | "b2[0]\ta3[1]\td1[2]\tc1[3]\t\n",
385 | "e1[0]\ta1[1]\td2[2]\tc2[3]\t\n",
386 | "b1[0]\ta2[1]\tc3[3]\tc4[3]\t\n"
387 | ]
388 | }
389 | ],
390 | "source": [
391 | "for y in range(YSIZE):\n",
392 | " row = \"\"\n",
393 | " for x in range(XSIZE):\n",
394 | " for b in bricks:\n",
395 | " for rb in range(XSIZE):\n",
396 | " val = value(v[x][y][b][rb])\n",
397 | " if val == 1:\n",
398 | " row += '{}[{}]'.format(b, rb)\n",
399 | " row += '\\t'\n",
400 | " print(row)"
401 | ]
402 | },
403 | {
404 | "cell_type": "markdown",
405 | "metadata": {
406 | "collapsed": true
407 | },
408 | "source": [
409 | "Which is one of the possible solutions."
410 | ]
411 | },
412 | {
413 | "cell_type": "code",
414 | "execution_count": null,
415 | "metadata": {
416 | "collapsed": true
417 | },
418 | "outputs": [],
419 | "source": []
420 | }
421 | ],
422 | "metadata": {
423 | "kernelspec": {
424 | "display_name": "Python 3",
425 | "language": "python",
426 | "name": "python3"
427 | },
428 | "language_info": {
429 | "codemirror_mode": {
430 | "name": "ipython",
431 | "version": 3
432 | },
433 | "file_extension": ".py",
434 | "mimetype": "text/x-python",
435 | "name": "python",
436 | "nbconvert_exporter": "python",
437 | "pygments_lexer": "ipython3",
438 | "version": "3.4.0"
439 | }
440 | },
441 | "nbformat": 4,
442 | "nbformat_minor": 0
443 | }
444 |
--------------------------------------------------------------------------------
/PuLP/bricks.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
20 |
38 |
40 |
41 |
43 | image/svg+xml
44 |
46 |
47 |
48 |
49 |
50 |
54 |
64 |
74 |
84 |
94 |
104 |
114 |
124 |
134 |
144 |
154 |
164 |
174 |
184 |
190 |
197 |
204 |
211 |
218 |
225 |
232 |
239 |
246 |
253 |
260 |
267 |
274 |
275 |
285 |
291 |
298 |
305 |
312 |
319 |
326 |
333 |
340 |
347 |
354 |
361 |
368 |
375 |
376 |
386 |
396 |
401 |
411 |
421 |
431 |
432 |
442 |
452 |
462 |
472 |
482 |
492 |
502 |
503 |
504 |
--------------------------------------------------------------------------------