Archive for the ‘Programmierung’ Category.

Auto-Documenting Python Code

A while ago I thought about auto-documenting Python code, here’s what resulted from those experiments. (It’s far away from production quality, so use at your own risk)#

Let’s assume we have a Python file without docstrings:

class HalloWelt:
 
	def Hallo(welt):
		return welt
 
 
print(HalloWelt.Hallo("Welt"))

My experimental Python code:

import re
 
class Dokumenter:
	"""
	Fügt einer bestehenden Python-Datei Docstrings hinzu, falls keine vorhanden sind.
	"""
 
	def dokumentme(filename):
		print(">> Prüfe",filename,"auf Docstrings\n")
 
		with open(filename+"_bak", 'w') as outfile:
			with open(filename, 'r') as infile:
				rowIter= iter(infile)
				for row in rowIter:
					# schreibe die Zeile auf jeden Fall in die Zieldatei
					outfile.write(row)
					# Ist in der Zeile ein 'def ' vorhanden?
					if "def " in row:
						# suche erstes Zeichen, das kein Docstring ist
						index = re.search('\S', row).start()
						whitespace = row[:index]
						whitespaceLen = len(whitespace)
						if " " in whitespace:
							blanks = True
						else:
							blanks = False					
						print(whitespaceLen,blanks)	
 
 
						print(">> Funktionsdefinition gefunden")
						print(">> Schreibe Docstring")
						print(">> Whitespaces",index)
						outfile.write('"""\nHallo Welt\n"""\n')
					print(row)
 
Dokumenter.dokumentme("dokme.py")
# Tests, Datei mit und ohne Dokstring,unterschiedliche Einrückungstiefe
# extrahiere die Parameter

Output:

class HalloWelt:
 
	def Hallo(welt):
"""
Hallo Welt
"""
		return welt
 
 
print(HalloWelt.Hallo("Welt"))

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Mit Python rekursiv Verzeichnisse auswerten

Hier ein kurzer Code-Schnipsel (basierend auf https://www.tutorialspoint.com/python/os_walk.htm), der Verzeichnisse rekursiv durchläuft und jeweils den kompletten Pfad in einem pandas DataFrame speichert. Dateien werden ignoriert, dies kann durch die Überarbeitung des „pass“ Teils angepasst werden.

import os
import sys
import pandas as pd
 
paths = pd.DataFrame(columns={'Path'})
 
rootdir = 'somepath’
 
for root, directories, filenames in os.walk(rootdir):
    for directory in directories:
        paths = paths.append({'Path':(os.path.join(root, directory)).replace('\\','/')},ignore_index=True)
    for filename in filenames:
        pass
 
paths.to_clipboard()

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Time in Python

A short summary on Python’s timestamps:

import datetime
 
now = datetime.datetime.now()
 
print(now.strftime('%Y-%m-%d %H:%M'))
print(now.isoformat())

From the module’s documentation:

Directive Meaning
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time
representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number
[00,23].
%I Hour (12-hour clock) as a decimal number
[01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first
day of the week) as a decimal number [00,53].
All days in a new year preceding the first
Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first
day of the week) as a decimal number [00,53].
All days in a new year preceding the first
Monday are considered to be in week 0.
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number
[00,99].
%Y Year with century as a decimal number.
%z Time zone offset indicating a positive or
negative time difference from UTC/GMT of the
form +HHMM or -HHMM, where H represents decimal
hour digits and M represents decimal minute
digits [-23:59, +23:59].
%Z Time zone name (no characters if no time zone
exists).
%% A literal '%' character.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Slides from my 2016 Froscon Presentation „Using Python for Scientific Research“

Here are my slides from the Froscon 2016 presentation „Using Python for Scientific Research“.

Slides: Froscon_Slides_2016

Video: Video Recording (The screen was flickering most of the time, pretty annoying and distracting)

I will continously update and expand this presentation during the next months, if you want to receive updates follow the GitHub repository: https://github.com/UweZiegenhagen/2016-Python-Data-Analysis-Slides/

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Parsing Emacs Orgmode files with Python

Here’s some experimental (alpha) code to parse Emacs Orgmode files. It’s far from complete, I only aim at parsing basic TODO strings with level (**), status (TODO, DONE), priority (#A, #B, #C), task and tags.

2016-09-03: It takes my actual orgmode file, so it’s working fine.

2016-09-04: I created a github repo, code updates will be added there, only: https://github.com/UweZiegenhagen/python-orgmode-parser

# -*- coding: utf-8 -*-
import re
 
def parseEmaceOrgmode(s):
    r = '^([\*]+)?\s?(TODO|PROGRESSING|FEEDBACK|VERIFY|POSTPONED|DELEGATED|CANCELLED|DONE)?\s?(\[#[A|B|C]\])?\s?(.*?)\s*(:(.*):)?$'    
    m = re.search(r,s)
    level = m.group(1)
    if (level is not None):
        level = len(level)
    prio = m.group(3)
    if (prio is not None):
        prio = prio[2:3]
    tags = []
    a = m.group(5)
    if a != None:
        b = len(a)-1
        a= a[1:b]
        a = a.split(':')
    tags.append(a)
    return(level, m.group(2), prio, m.group(4), tags)
 
with open("../orgmode.org", "r") as ins:
    for line in ins:
        level, status, priority, task, tags = parseEmaceOrgmode(line)
        if level is not None:        
            print('Level:', level)
            print('Status:', status)
            print('Priority:', priority)
            print('Task:', task)
            print('Tags:',tags,'\n\n')

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Ein einfaches Python-Beispiel für Klassen und Funktionen

Hier noch ein einfaches Python-Beispiel für Klassen und Funktionen, das ich vor ein paar Tagen geschrieben habe. Die Punkt-Klasse erhält eine entsprechende Funktion, um die Euklidische Distanz zu einem anderen Punkt zu bestimmen.

# -*- coding: utf-8 -*-
import math as m
 
class Point:
 
    def __init__(self,x,y):
        self.x = x
        self.y = y
 
    def calcEuclidDistanceToPoint(self,x,y):
        return m.sqrt(m.pow(self.x-x,2) + m.pow(self.y-y,2))
 
p1 = Point(0,0)
p2 = Point(1,1)
print(p2.calcEuclidDistanceToPoint(p1.x,p1.y))
runfile('euclidDistance.py', wdir='E:/Python')
1.4142135623730951

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Lineare Gleichungen lösen mit numpy

Hier ein kurzes Beispiel aus der numpy-Dokumentation, wie man mit Hilfe von numpy lineare Gleichungssysteme lösen kann:

Zu lösen sind folgende Gleichungen:

  • 3 * x0 + 1 * x1 = 9
  • 1 * x0 + 2 * x1 = 8

Die Koeffizienten kommen in die entsprechenden numpy-Arrays, dann ruft man linalg.solve auf:

import numpy as np
 
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(a, b)
print(x) # gibt [ 2.  3.]

pff

Den Plot habe ich mit LaTeX erstellt, siehe http://uweziegenhagen.de/?p=3516.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Parallel LaTeXing with Python Threads

Based on an example from stackexchange I have created a small example on parallel TeX compilation.

# -*- coding: utf-8 -*-
"""
Created on 2016-07-06
Uwe Ziegenhagen
based on http://stackoverflow.com/questions/16181121/python-very-simple-multithreading-parallel-url-fetching-without-queue
"""
 
from multiprocessing.pool import ThreadPool
from time import time as timer
import os
 
files = ['test-01.tex','test-02.tex','test-03.tex','test-04.tex','test-05.tex',
'test-06.tex','test-07.tex','test-08.tex','test-09.tex','test-10.tex']
 
def compile_file(cfile):
	try:
		result = os.system('pdflatex -interaction=batchmode ' + cfile)
		return cfile, None
	except Exception as e:
		return cfile, e	
 
start = timer()
results = ThreadPool(8).imap_unordered(compile_file, files)
for cfile, error in results:
	if error is None:
		print("%r compiled in %ss" % (cfile, timer() - start))
	else:
		print("Error compiling %r: %s" % (cfile, error))
		print("Elapsed Time: %s" % (timer() - start,))
 
print('Gesamtzeit',timer() - start)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Fokussiertes Arbeiten mit Emacs / Distraction-free Emacs

Editoren, die minimales Design statt Mengen von Menüs und Buttons aufweisen, sind in den letzten Jahren sehr modern geworden. IA Writer für Mac OS X und iOS, Writemonkey für Windows sind nur einige Beispiele. Mit Emacs geht das natürlich auch… Hier ein paar Codeschnipsel mit den entsprechenden URLs.

;; distraction-free
;;  https://nickhigham.wordpress.com/2016/01/14/distraction-free-editing-with-emacs/
(scroll-bar-mode 0)    ; Turn off scrollbars.
(tool-bar-mode 0)      ; Turn off toolbars.
(fringe-mode 0)        ; Turn off left and right fringe cols.
(menu-bar-mode 0)      ; Turn off menus.
;; bind fullscreen toggle to f9 key
(global-set-key (kbd "") 'toggle-frame-fullscreen)

;; http://emacs.stackexchange.com/questions/2999/how-to-maximize-my-emacs-frame-on-start-up
;; Start fullscreen (cross-platf)
(add-hook 'window-setup-hook 'toggle-frame-fullscreen t)
; emacs-doctor.com/emacs-strip-tease.html
;; Prevent the cursor from blinking
(blink-cursor-mode 0)
;; Don't use messages that you don't read
(setq initial-scratch-message "")
(setq inhibit-startup-message t)
;; Don't let Emacs hurt your ears
(setq visible-bell t)
(custom-set-faces
  '(default ((t (:background "black" :foreground "darkgrey"))))
  '(fringe ((t (:background "black")))))

distrfree_emacs

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Excel: Formel nur auf die x-te Zeile anwenden

Hier ein kurzes Beispiel für die Nutzung der Rest() Funktion, um Formeln in Excel nur auf jede x-te Zeile anzuwenden.

  1. Mit zeile() erhält man die Zeilennummer des aktuellen Bezugs
  2. Rest() gibt den Rest bei der ganzzahligen Teilung zurück
  3. Wenn() prüft einfach die Bedingung, ob Rest() einen bestimmten Wert hat

Man kann nicht nur gerade/ungerade prüfen (oberes Beispiel), auch bei anderen Zeilensprüngen klappt das.

excel

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website