Zawiki Release v0.11-30-g7307413
tschinz
Apr 11, 2020 Contents
i Zawiki, Release v0.11-30-g7307413
Contents 1 Chapter 1
Commandline
1.1 Cheatsheet
• Admin rights • Quit • Mounting • Wipe Disk • Environment variables • User • Alias • Permissions • Threads • General • Find / Which • Grep • Links • Compression – Tar, bz2, gz • RAR
2 Zawiki, Release v0.11-30-g7307413
• In Outputs – Tail – Cat • PGP Pretty Good Privacy & GPG – Files – Create PGP files – GPG Privacy • SSH • SCP
1.1.1 Admin rights
Note: In order to gain administrative rights, for a session or only for a command
Listing 1: admin sudosu sudo "command" sudo-s # Longtimeroot su- # rootpreservedenv sudo!! # executepreviouscommandasroot chsh-s/bin/zsh # changeloginshelltozsh
1.1.2 Quit
Listing 2: quit sudohalt # Sleep sudoreboot # Reboot sudoshutdownnow # Shutdown
1.1.3 Mounting
For permanent mount see: /etc/fstab
Listing 3: mounting sudovim/etc/fstab # Toeditdefaultmountdrives sudofdisk-l # Driveinfo ls-l/dev/disk/by-uuid # getDriveUUID's mkdir-p/media/d # makefolderforHD mount-tvfat-oiocharset-utf8, umask=000 /dev/sda3/media/d mkdir-p/mnt/mountplace mount/dev/sda1/mnt/mountplace unmount/mnt/mountplace
(continues on next page)
1.1. Cheatsheet 3 Zawiki, Release v0.11-30-g7307413
(continued from previous page) mount -U
1.1.4 Wipe Disk
Listing 4: wipe disk # unmount disk sudo umount /dev/sdXY -l
# use /dev/random to write Zeros on entire disk§ sudo dd if=/dev/urandom of=/dev/sdX bs=10M
1.1.5 Environment variables
They can be set permanently system wide /etc/profile or per user shell /etc/.bashrc /etc/.zshrc
Listing 5: environment variables # Licenses export LM_LICENSE_FILE=$LM_LICENSE_FILE:portnumber@serverip
# Print Environmemt variables printenv echo $name_env_var
# Set env var setenv name value
1.1.6 User
Listing 6: user # Access to different PC with unknown Password chroot path/of/new/systemroot # change root of FileSys # Useful for hacking another PC # 1. with LiveUSB / CD login # 2. mount HD # 3. chroot to his filessystem # 4. Change user / password and everything else you want
# User information who # returns all users logged in whoami # return actual username id
# Change to user sudo -u user2 bash # open bash of user2
# Send info write
1.1. Cheatsheet 4 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
# Add user sudo useradd -d /home/
# Add user to group usermod -a -G
# Change user password sudo passwd
1.1.7 Alias
Listing 7: alias # Set up aliases alias
1.1.8 Permissions
Listing 8: permissions chmod xxx file|folder # xxx = rwx|xnumber chmod -x file |folder # add only executable Flag chown -R user:group file|folder # change owner recursively find . -type d -exec chmod 755 {} \; # find dir's and set 755 find . -type f -exec chmod 644 {} \; # find files and set 644
Rights read write execute Abreviation 0 • • •
x 1 • •
x 2 • •
x x 3 •
x 4 • •
x x 5 •
x x 6 •
x x x 7
1.1. Cheatsheet 5 Zawiki, Release v0.11-30-g7307413
1.1.9 Threads
PID = Process ID
Listing 9: threads ps -x # view executed threads ps -ax | grep name # search for specific process name kill
Signal Name Single Value Effect SIGHUP 1 Hangup SIGINT 2 Interrupt from keyboard SIGKILL 9 Kill signal SIGTERM 15 Termination signal SIGSTOP 17, 19, 23 Stop the process
1.1.10 General
Listing 10: general uname -a # Distribution & Kernel informations whereis command # returns location of command mkdir /existing/path/dirname # creates a directory mkdir -p /non/existing/path/name # creates a directory path mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a} # creates a tree structure pwd # print working directory ls # list content ls -la # list flags ll # short list flags cd # change dir rm name # remove file rm -r # remove directory with content rm -R name # remove recursively folder with its content rm !(delete_all_but_this) # delete all except !() cp source/path /dest./path # copy file cp -R source/path dest./path # copy directory with content cp -R --preserve=mode,ownership,timestamp source/path dest/path # copy with preserving owner and permission and␣ ,→time df # show disk sizes df -H # show disk sizes in KB, MB, GB diff path/to/file1 path/to file2 # compare file1<->file2 and shows the difference sdiff path/to/file1 path/to file2 # compare file1<->file2 and merge directly
1.1. Cheatsheet 6 Zawiki, Release v0.11-30-g7307413
1.1.11 Find / Which
Listing 11: find and which # finding and delete all folder with
# Find location of a program which zsh
1.1.12 Grep
Grep let you search for word in files and outputs the line it was found.
Listing 12: grep grep boo /etc/passwd # search boo in for /etc/passwd grep -r "192.168.1.5" /etc/ # search recursivaly in /etc for 192.168.1.5 grep -w "boo" /path/to/file # search for word "boo" only grep is also often uses in pipes to search within the output of an other command
Listing 13: grep pipe cat /proc/cpuinfo | grep -i 'Model' # display CPU Model name ps -x | grep vnc
Note: Flags • -r : search recursively in all files \ • -n : display line number \ • -c : count number of times found \ • --color : colors the word searched in the results
1.1.13 Links
Listing 14: links ln target-filename symbolic-filename # create hardlink ln -s target-filename symbolic-filename # create softlink
Note: Hard Link vs Softlink Symbolic links are different from hard links. Hard links may not normally point todirec- tories, and they cannot link paths on different volumes or file systems. Hard links always
1.1. Cheatsheet 7 Zawiki, Release v0.11-30-g7307413 refer to an existing file.
1.1.14 Compression
Tar, bz2, gz
Listing 15: compress tar cfv name.tar /path/to/folder # Compression tar tar xfv tarfile # Decompression tar tar cfvz name.tar.gz /path/to/folder # Compression tar.gz tar xfvz tarfile # Decompression tar.gz tar cfvj name.tar.bz2 /path/to/folder # Compression tar.bz2 tar xfvj tarfile # Decompression tar.bz2
Note: Flags • c = Compression | x = eXtraction • f = file/folder • v = Verbose • j = bz2 | z = gz • p = Preserve (keep permissions)
1.1.15 RAR
Listing 16: compress rar # compress and split in files of 700MB rar a -m5 -v700m rarname folder_or_file_to_compress
# uncompress, if a split rar uncompress the first rar e rarname
Note: Flags • m5 = highest compression m0 = lowest compression • e = extract in current folder • a = append to rar • v
1.1. Cheatsheet 8 Zawiki, Release v0.11-30-g7307413
1.1.16 In Outputs
Tail
Listing 17: tail tail file|folder # give end of a file ./executable > output.txt # redirect output to a file ./executable > output.txt 2<&1 # redirect output to a file output 2 & 1 # 2 = Error output # 1 = Std output
Cat
Listing 18: cat cat > file1.txt # To Create a new file cat >> file1.txt # To Append data into the file cat file1.txt # To display a file cat file1.txt file2.txt # Concatenate several files and display cat file1.txt file2.txt > file3.txt # To cat several files and transfer output␣ ,→to another file
1.1.17 PGP Pretty Good Privacy & GPG see also GnuPg
Files
Listing 19: pgp files /home/user/.ssh pgp # private key pgp.pub # public key gpg_fingerprint.txt # Infos for the gpg fingerprint
Create PGP files
1.1. Cheatsheet 9 Zawiki, Release v0.11-30-g7307413
Listing 20: create key’s ssh-keygen -t dsa -f filename # Create private and public key gpg --gen-key # Create gpg fingerprint
GPG Privacy
Listing 21: gpg gpg --gen-key # Create a key gpg --export -a "User Name" > public.key# Export a public key gpg --export-secret-key -a "User Name" > private.key# Export private key gpg --import public.key # Import public key gpg --allow-secret-key-import --import private.key# Import private key gpg --delete-key "User Name" # Delete public key gpg --delete-secret-key "User Name" # Delete private key gpg --list-keys # List key in public key ring gpg --list-secret-keys # Lsit key in private key ring gpg --fingerprint > fingerprint # Short list of numbers to verify public key gpg -e -u "Sender User Name" -r "Receiver User Name" somefile # Encrypt data gpg -d mydata.tar.gpg # Decrypt data
1.1.18 SSH
See also the dedicated SSH page
Listing 22: ssh_config # Edit config file sudo vim /etc/ssh/sshd_config
# start, stop, restart SSH sudo /etc/init.d/ssh start sudo /etc/init.d/ssh stop sudo /etc/init.d/ssh restart
Listing 23: ssh ssh-agent bash # start new bash agent ssh-add privatekey # key you want to use for that session # without a given key he search for ~/.ssh/id_rsa
Connect to another station by ssh by default a password is needed or if configured no password but with rsh keys
Listing 24: ssh connection ssh -p
# or ssh -p
# or with port forward and commandline ssh -L
1.1. Cheatsheet 10 Zawiki, Release v0.11-30-g7307413
Note: Options • -p
1.1.19 SCP
Transferring file through SSH For these command you have to use either the PW oralready bash started
Listing 25: scp # Synchronising directories rsync -avr -P --rsh='ssh -p YYYY' /localpath/to/dir user@host:/remotepath/to/dir
# Host -> Remote scp sourceFile user@host:/directory/targetFile scp -R sourceFolder user@host:/directory/targetFolder scp -P port sourceFile user@host:/directory/targetFolder
# Remote -> Host scp user@host:/directory/sourceFile targetFile scp -R user@host:/directory/sourceFolder targetFolder scp -P port user@host:/directory/sourceFolder targetFolder
1.2 Crontab
Cron allows tasks to be automatically run in the background at regular intervals by the cron daemon. These tasks are often termed as cron jobs. Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times. Crontab is used to regularly execute some task e.g. shell scripts
1.2.1 Restrictions
You can execute crontab if your name appears in the file: /usr/lib/cron/cron.allow. If that file does not exist, you can use crontab if your name does not appear inthefile: /usr/ lib/cron/cron.deny. If only cron.deny exists and is empty, all users can use crontab. If neither file exists, only the root user can use crontab. The allow/deny files consist ofone user name per line.
1.2. Crontab 11 Zawiki, Release v0.11-30-g7307413
1.2.2 Crontab Viewer
To define the editor to use write the following inyour ~/.bashrc
Listing 26: ~/.bashrc export VISUAL=vim export EDITOR=vim
Listing 27: crontab crontab -l # List crontab's for current user crontab -r # Del crontab's for current user crontab -e # Edit crontab's for current user
1.2.3 Crontab file
A crontab file has five fields for specifying day, date and time followed by thecommandto be run at that interval.
* * * * * * command to be executed + + + + + + | | | | | | | | | | | +--- Absolute path to script | | | | +------day of week (0 - 6) (Sunday=0) | | | +------month (1 - 12) | | +------day of month (1 - 31) | +------hour (0 - 23) +------min (0 - 59)
* in the value field above means all legal values as in braces for that column. Thevalue column can have a * or a list of elements separated by commas. An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range). Notes • Repeat pattern like /2 for every 2 minutes or /10 for every 10 minutes is not sup- ported by all operating systems. If you try to use it and crontab complains it is prob- ably not supported. • The specification of days can be made in two fields: month day and weekday. Ifboth are specified in an entry, they are cumulative meaning both of the entries willget executed .
1.2.4 Entry Examples
A line in crontab file like below removes the tmp files from /home/someuser/tmp each day at 6:30 PM.
30 18 * * * rm /home/someuser/tmp/*
:caption: crontab entries
0 * * * * /home/user/backupServerA.sh # At Noon each day 0 0 * * * /home/user/backupServerB.sh # At Midnight each day 0 1 * * * /home/user/backupServerC.sh # At 1 o'clock each day 0 * * * 1 /home/user/backupServerD.sh # At Noon each Monday @reboot /home/user/Documents/x11vnc_start.bash (continues on next page)
1.2. Crontab 12 Zawiki, Release v0.11-30-g7307413
(continued from previous page) @reboot nohup airsonos & @weekly /home/user/script.bash > /home/user/scriptoutput.log
Changing the parameter values as below will cause this command to run at different time schedule below:
Frequently used times
min hour day/month month day/week Execution time * * * * * Every Minute 0 * * * * Every Hour 0 0 * * * Every Day 0 0 * * 0 Every Week 0 0 1 * * Every Month 0 0 1 1 * Every Year
More special times
min hour day/month month day/week Execution time 30 0 1 1,6,12 * 00:30 Hrs on 1st of Jan, June & Dec. 0 20 * 10 1-5 8.00 PM every weekday (Mon-Fri) only in Oct. 0 0 1,10,15 * * Midnight on 1st ,10th & 15th of month 5,10 0 10 * 1 At 12.05,12.10 every Monday & on 10th of ev- ery month
1.2.5 Environment
Cron invokes the command from the user’s HOME directory with the shell /usr/bin/sh. Cron supplies a default environment for every shell, defining:
HOME=user’s-home-directory LOGNAME=user’s-login-id PATH=/usr/bin:/usr/sbin:. SHELL=/usr/bin/sh
1.2.6 Disable Email
By default cron jobs sends a email to the user account executing the cronjob. If this is not needed put the following command At the end of the cron job line.
>/dev/null 2>&1
1.2. Crontab 13 Zawiki, Release v0.11-30-g7307413
1.2.7 Generate log file
To collect the cron execution execution log in a file :
30 18 * * * rm /home/someuser/tmp/* > /home/someuser/cronlogs/clean_tmp_dir.log
1.2.8 Execute script as sudo
In order to let a crontab script run as sudo you need to give the script sudo rights without asking for a password. This can be achieved by adding the script to the root crontab instead of the user crontab. the following command will let you edit the root crontab. sudo crontab -e
The Crontab entry will be a simple script call
* * * * * /location/to/script.bash
1.3 dd and ddfldd
• Install • On Linux • On MacOs
Use for creating and copying iso files from and to a medium. The dd command doesn’t has a output during copy but dcfldd does. It gives an output all X blocks written. This means in the commands below you can also just replace dd with dcfldd.
1.3.1 Install
Listing 28: dcfldd install sudo apt-get install dcfldd
1.3.2 On Linux
Listing 29: dd usage # Create usb stick or sdcard => image fdisk -l # get disk info unmount /dev/sdX # unmount disk dd if=/dev/sdX of=/location/for/image.iso bs=1M conv=noerror,sync # copy usb stick␣ ,→to image
# Copy image => usb stick or sdcard fdisk -l # get disk info (continues on next page)
1.3. dd and ddfldd 14 Zawiki, Release v0.11-30-g7307413
(continued from previous page) unmount /dev/sdX # unmount disk dd if=/location/of/image.iso of=/dev/sdX bs=1M conv=noerror,sync # copy image to␣ ,→usb stick dd has no output normally, if you want to watch the status of the copy then open a new Terminal and try one of the following commands
Listing 30: watch dd sudo kill -USR1 $(pgrep '^dd$') # dd will display␣ ,→status once sudo watch -n
1.3.3 On MacOs
Listing 31: dd usage # Create usb stick or sdcard => image diskutil list # get disk info diskutil unmountDisk /dev/diskX # unmount disk dd if=/dev/diskX of=/location/for/image.iso bs=1m # copy usb stick to image
# Copy image => usb stick or sdcard diskutil list # get disk info diskutil unmountDisk /dev/diskX # unmount disk dd if=/location/of/image.iso of=/dev/diskX bs=1m conv=noerror,sync # copy image to␣ ,→usb stick
1.4 General Shell Commands
• Change permissions on type • SSH relia
1.4. General Shell Commands 15 Zawiki, Release v0.11-30-g7307413
1.4.1 Change permissions on type sudo find /var/www -type d -print0 | sudo xargs -0 chmod 0755 sudo find /var/www -type f -print0 | sudo xargs -0 chmod 0644
1.4.2 SSH relia ssh -p 2222 -L 5900:localhost:5900 -L 19999:localhost:19999 [email protected]
1.5 Network
1.5.1 Interfaces
Listing 32: interface ifconfig ifup
1.5.2 NMAP
Find open ports on a ip subnet range
Listing 33: nmap # Finding ssh server in ip range 192.168.0-192.168.0.255 nmap -p 22 --open 192.168.1.0/24
1.5.3 ARP-SCAN
Finding a machine on your local subnet using DHCP.
1.5. Network 16 Zawiki, Release v0.11-30-g7307413
Listing 34: arp-scan # Finding ssh server in ip range 192.168.0-192.168.0.255 sudo apr-scan --interface=eth0 --localnet | grep aa:bb:cc:dd:ee:ff
1.6 RSync
Synchronizing directories local and remotely
Listing 35: rsync # Synchronising directories to distant computer rsync -avzP --rsh='ssh -p YYYY' /localpath/to/dir user@host:/remotepath/to/dir
# Synchronizing local left to right rsync -avP --delete --stats /source/folder/* /destination/folder
# Synchronizing and exclude a folder or file rsync -avP --delete --stats --exclude 'excl_folder' --exclude 'folder/excl_file.txt ,→' /source/folder/* /destination/folder rsync -avP --delete --stats --exclude-from '/home/user/exclude.txt' /source/folder/ ,→* /destination/folder
Listing 36: exclude.txt sources public_html/database.* downloads/test/*
Note: Flags
-a = archive (recursion & preserve rights, time, owner, group)\\ -v = verbose \\ -z = compress during transfer \\ -P = display progress \\ --delete = delete files on destination folder \\ --stats = display some statisics at the end \\ --exclude
1.7 SSH
SSH is a useful and secure tool to connect yourself via the internet or locally with your PC remotely. It is not installed on every distribution by default.
1.6. RSync 17 Zawiki, Release v0.11-30-g7307413
1.7.1 Install sudo apt-get install ssh
1.7.2 Config sudo nano /etc/ssh/sshd_config
Define port to listen, recommend to change the default port 22 If you use FTP Port as SSH Port (21) then you will run into problems with connecting via Windows PC’s because of the Windows Firewall. in order to solve this problem execute the following line on Windows PC’s with Admin privilege. netsh advfirewall set global statefulftp disable
Source your .bashrc
Create or edit the ~/.bash_profile. And add the following line to souce with each SSH Login your .bashrc
Listing 37: .bash_profile source ~/.bashrc
Test
Test you system with via the localhost. ssh -p
Restart SSH sudo /etc/init.d/ssh restart
1.7.3 Connect ssh -p
1.7. SSH 18 Zawiki, Release v0.11-30-g7307413
1.7.4 Port Forwarding
Listing 38: ssh connection ssh -N -T -L
# or with port forward and commandline ssh -L
Note: Options • -p
1.7.5 RSA keys
How to setup ssh with rsa keys
Listing 39: ssh keys # Generating RSA Key pair ssh-keygen -t rsa
# Copy key ssh-copy-id -i ~/.ssh/id_rsa.pub "[email protected] -p
# Append key to file authorized_keys cat ~/.ssh/*.pub | ssh [email protected] -p
1.7. SSH 19 Chapter 2
Scripts
2.1 Config Files
• /etc/profile – Add Program to“PATH“ • ~.bashrc.zshrc – Create a cmd alias • Add custom functions • etc/fstab
• My linux configfiles
2.1.1 /etc/profile
/etc/profile contains Linux system wide environment and startup programs. It is used by all users with bash, zsh, sh shell. Usually used to set PATH variable, user limits, and other settings for user. It only runs for login shell. If you wanted to make large changes or application specific changes use /etc/profile.d directory. My profile
20 Zawiki, Release v0.11-30-g7307413
Add Program to“PATH“
export PATH=$PATH:/opt/sublime_text
2.1.2 ~.bashrc .zshrc
Execute commands at start of a shell instance for a given users only .bashrc .zshrc
Create a cmd alias
Listing 1: alias
1 # Common home locations 2 alias home='cd ~' 3 alias root='cd /' 4 alias dtop='cd ~/Desktop' 5 alias dwld='cd ~/Downloads' 6 alias docs='cd ~/Documents' 7 alias www='cd /var/www/html' 8 # Common data directories 9 # Common commands 10 alias o=open 11 alias ..='cd ..' 12 alias ...='cd ..; cd ..' 13 alias ....='cd ..; cd ..; cd ..' 14 # Common command shortcuts 15 alias cls=clear 16 alias ll='ls -la' 17 alias owner-wwwdata='sudo chown -R www-data:www-data ./' 18 alias permission-file='sudo find . -type f -exec chmod 644 {} \;' 19 alias permission-folder='sudo find . -type d -exec chmod 755 {} \;' 20 # commands 21 alias backup='~/Documents/backup.bash'
2.1.3 Add custom functions
Listing 2: function
1 # Draw Mandelbrot Factral 2 function mandelbrot_zsh { 3 local lines columns colour a b p q i pnew 4 ((columns=COLUMNS-1, lines=LINES-1, colour=0)) 5 for ((b=-1.5; b<=1.5; b+=3.0/lines)) do 6 for ((a=-2.0; a<=1; a+=3.0/columns)) do 7 for ((p=0.0, q=0.0, i=0; p*p+q*q < 4 && i < 32; i++)) do 8 ((pnew=p*p-q*q+a, q=2*p*q+b, p=pnew)) 9 done 10 ((colour=(i/4)%8)) 11 echo -n "\\e[4${colour}m " 12 done 13 echo 14 done 15 }
2.1. Config Files 21 Zawiki, Release v0.11-30-g7307413
2.1.4 etc/fstab
There’s a file called /etc/fstab in your Linux system. Learn what its contents meanand how it’s used in conjunction with the mount command. When you learn to understand the fstab file, you’ll be able to edit its contents yourself, too. My fstab 1. column - Device • UUID=... • /dev/hda2 2. column - Default mount point • / • mnt/data • media/disk 3. column - Filesystem type • ext2 • ext4 • ntfs • vfat • auto 4. column - Mount options • auto and noauto - mounted automatically at bootup • user and nouser - allows normal user to mount the device • exec and noexec - lets execute binaries from that partition • ro and rw - R ead- O nly and R ead- W rite • sync and async - data can be writte synchron or asynchron • default - means rw,suid,dev,exec,auto,nouser,async 5. column - Dump options • In most cases 0 6. column - fck options • In most cases 0
Listing 3: fstab
1 UUID=3d3920bb-91c7-4632-8fd0-1d87b110a496 / ext4 errors=remount- ,→ro 0 1 2 /swapfile none swap sw ␣ ,→ 0 0
3
4 # internal WD 1TB Harddisk on /dev/sda1 5 #UUID=377d6d5c-3d62-4155-b7f1-3f07fe09a0c2 /mnt/data2 ext4 defaults ␣ ,→ 0 0
6
7
8 # external Lacie Rugged 2TB Harddisk on /dev/sda1 9 UUID=0c6f2eed-3ec0-493e-9ab8-e954a9e3a25d /media/zas_backup ext3 nofail, ,→nobootwait 0 0 (continues on next page)
2.1. Config Files 22 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
10
11 # external WD Passport 1TB Harddisk on /dev/sde1 12 UUID=20F605D47F5FE7AC /media/zas_media ntfs nofail, ,→nobootwait 0 0
2.2 Scripts
• Shell Bang • Script End • Variables • Command line arguments • Functions • Console prints • User Inputs • Check and create folder • Lockfile • Samples
Here you can dowload some example files for Linux. It can be neither Scripts or Linksor config files A lot of scripts and configurations can be found in my config repo: • Shell Scripts
2.2.1 Shell Bang
At the beginning of a file there need to be a line to indentify the program orthefile. #!
#!/bin/sh
#!/bin/bash
#!/usr/bin/env python
2.2.2 Script End
exit 0
2.2. Scripts 23 Zawiki, Release v0.11-30-g7307413
2.2.3 Variables
Listing 4: variables
1 # Var 2 SEPARATOR='------,→------' 3 INDENT=''
4
5 # Array 6 MOUNT_POINTS=( 'elem1' 'elem2')
7
8 # Use Env var 9 Linux_user="$USER"
2.2.4 Command line arguments
Listing 5: cli arguments
1 usage='Usage: script.bash [-v] [-h]' 2 usage="$usage\n\t[-n input_n] [-u input_u]"
3
4 while getopts "n:u:vh" options; do 5 case $options in 6 n ) var_n=$OPTARG;; 7 u ) var_u=$OPTARG;; 8 v ) verbose=1;; 9 h ) echo -e $usage 10 exit 1;; 11 * ) echo -e $usage 12 exit 1;; 13 esac 14 done
15
16 if [ -n "$verbose" ] ; then 17 echo "Verbose" 18 fi
2.2.5 Functions
2.2. Scripts 24 Zawiki, Release v0.11-30-g7307413
Listing 6: functions
1 # Define function 2 function test () { 3 local arg1=$1 ; local arg2=$2
4
5 $result = $arg1 + $arg2
6
7 return 1 8 }
9
10 # Usage function 11 test 1 2
2.2.6 Console prints
Display message welcome on screen
Listing 7: echo
1 # Console print 2 echo 'Welcome'
3
4 # Write message File deleted to /tmp/log.txt 5 echo 'File has been deleted' > /tmp/log.txt
6
7 # Append message File deleted /tmp/log.txt 8 echo 'File has been deleted' >> /tmp/log.txt
9
10 # Append message and command output on screen, print variable 11 echo "Today's date is $(date)"
2.2.7 User Inputs
Listing 8: user inputs 1
1 echo -n "Please enter: "
2
3 stty -echo 4 read user_text 5 stty echo
6
7 echo "" # force a carriage return to be output
Listing 9: user inputs 1
1 read -n1 -r -p "Press space to continue..." key 2 if [ "$key" = '' ]; then 3 # Space pressed, do something 4 # echo [$key] is empty when SPACE is pressed # uncomment to trace 5 else 6 # Anything else pressed, do whatever else. 7 # echo [$key] not empty 8 fi
2.2. Scripts 25 Zawiki, Release v0.11-30-g7307413
2.2.8 Check and create folder
Listing 10: check and create folder
1 if [ ! -d "/folder/location" ]; then 2 sudo mkdir /folder/location 3 fi
2.2.9 Lockfile
Lockfiles you can wait until another process is finished.
Listing 11: check and create folder
1 # Define path and lockfile 2 lockDir="/path/to/lock_files" 3 lockFilePath="$lockDir/lockfile.lock" 4 # Loop until file no longer exist 5 while [ -e "$lockFilePath" ] 6 do 7 exit 8 done
9
10 # Create new lockfile 11 touch $lockFilePath
12
13 TO SOMETHING THE LOCK IS YOURS
14
15 # Remove lockfile 16 rm -f $lockFilePath
2.2.10 Samples
DIR="$( cd "$( dirname "$0" )" && pwd )" # get dir of executed file
2.2. Scripts 26 Chapter 3
Tools
3.1 Apache
• Password Protect Apache Pages – Install Apache Packages – Create the Password File
27 Zawiki, Release v0.11-30-g7307413
– Configure Apache Password Authentication – Access Control in Virtual Host
3.1.1 Password Protect Apache Pages
When setting up a web server, there are often sections of the site that you wish to re- strict access to. Web applications often provide their own authentication and authorization methods, but the web server itself can be used to restrict access if these are inadequate or unavailable. In order to create the file that will store the passwords needed to access our restricted content, we will use a utility called htpasswd. This is found in the apache2-utils package within the Ubuntu repositories.
Install Apache Packages
Update the local package cache and install the package by typing this command. We will take this opportunity to also grab the Apache2 server in case it is not yet installed on the server:
sudo apt-get update sudo apt-get install apache2 apache2-utils
Create the Password File
We now have access to the htpasswd command. We can use this to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd within our /etc/apache2 configuration directory. The first time we use this utility, we need to addthe -c option to create the specified file. We specify a username (test in this example) at the end of the command to create a new entry within the file:
sudo htpasswd -c /etc/apache2/.htpasswd test
You will be asked to supply and confirm a password for the user. Leave out the -c argument for any additional users you wish to add:
sudo htpasswd /etc/apache2/.htpasswd another_user
If we view the contents of the file, we can see the username and the encrypted password for each record:
cat /etc/apache2/.htpasswd
Output
test:$apr1$lzxsIfXG$tmCvCfb49vpPFwKGVsuYz. another_user:$apr1$p1E9MeAf$kiAhneUwr.MhAE2kKGYHK.
3.1. Apache 28 Zawiki, Release v0.11-30-g7307413
Configure Apache Password Authentication
Now that we have a file with our users and passwords in a format that Apache canread, we need to configure Apache to check this file before serving our protected content. We can do this in two different ways. The first option is to edit the Apache configuration and add our password protection to the virtual host file. This will generally give better performance because it avoids the expense of reading distributed configuration files. If you have this option, this methodis recommended. If you do not have the ability to modify the virtual host file (or if you are already using .htaccess files for other purposes), you can restrict access usingan .htaccess file. Apache uses .htaccess files in order to allow certain configuration items to be set withinafilein a content directory. The disadvantage is that Apache has to re-read these files on every request that involves the directory, which can impact performance. Choose the option that best suits your needs below.
Access Control in Virtual Host
Configuring Access Control within the Virtual Host Definition Begin by opening up the virtual host file that you wish to add a restriction to. For ourexam- ple, we’ll be using the 000-default.conf file that holds the default virtual host installed through Ubuntu’s apache package: Inside, with the comments stripped, the file should look similar to this:
Listing 1: /etc/apache2/sites-enabled/000-default.conf
1
Authentication is done on a per-directory basis. To set up authentication, you will need to target the directory you wish to restrict with a
Listing 2: /etc/apache2/sites-enabled/000-default.conf
1
6
7
3.1. Apache 29 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
12 13
Save and close the file when you are finished. Restart Apache to implement your password policy:
sudo service apache2 restart
The directory you specified should now be password protected. Configuring Access Control with .htaccess Files If you wish to set up password protection using .htaccess files instead, you should begin by editing the main Apache configuration file to allow .htaccess files: Find the
Listing 3: /etc/apache2/apache2.conf
1 ... 2
Next, we need to add an .htaccess file to the directory we wish to restrict. In ourdemon- stration, we’ll restrict the entire document root (the entire website) which is based at /var/www/html, but you can place this file in any directory you wish to restrict accessto /var/www/html/.htaccess. Within this file, specify that we wish to setup Basic authentication. For the AuthName, choose a realm name that will be displayed to the user when prompting for credentials. Use the AuthUserFile directive to point Apache to the password file we created. Finally, we will require a valid-user to access this resource, which means anyone who can verify their identity with a password will be allowed in:
Listing 4: /var/www/html/.htaccess
1 AuthType Basic 2 AuthName "Restricted Content" 3 AuthUserFile /etc/apache2/.htpasswd 4 Require valid-user
Save and close the file. Restart the web server to password protect all content inorbelow the directory with the .htaccess file:
sudo service apache2 restart
To confirm that your content is protected, try to access your restricted content inaweb browser. You should be presented with a username and password prompt. If you enter the correct credentials, you will be allowed to access the content. If you enter the wrong credentials or hit “Cancel”, you will see the “Unauthorized” error page:
3.1. Apache 30 Zawiki, Release v0.11-30-g7307413
3.2 Hardware Sensors
• Installation • Setup • Loading modules • Monitoring
3.2.1 Installation sudo apt-get install lm-sensors hddtemp
• lm-sensors reads the mainboard sensors • hddtemp reads the S.M.A.R.T. enables harddisk sensors
3.2.2 Setup
Running sensors-detect sudo sensors-detect
Answer to ALL questions with YES, especially to the last one “Do you want to add these lines to /etc/modules automatically.
3.2.3 Loading modules
Since we don’t want to restart; load the modules manually. Therefore load the modules displayed at the end of the previous command.
#----cut here---- # Chip drivers coretemp #----cut here----
Run command sudo modprobe [modulename]
3.2.4 Monitoring
To read the sensors by coimmandline enter: sensors
There are also gui available for all desktop environments. • Gnome: sudo apt-get install sensors-applet • KDE: Build in Widget
3.2. Hardware Sensors 31 Zawiki, Release v0.11-30-g7307413
3.3 Let’s Encrypt
• Version • Renew Certificates
3.3.1 Version
certbot --version
3.3.2 Renew Certificates
# Stop Webserver Service sudo service apache2 stop
# Update Certificates sudo certbot renew sudo certbot renew --dry-run
# Restart Webserver Service sudo service apache2 start
3.4 Raid
• Types – Raid types – Non-Raid types • mdadm Commands – Check Raid Status – Create Raid Array – Change Raid Array ∗ Grow ∗ Delete Raid Array • Links
Raid ( R edundant A rray of I ndependent D isks) is a system to connect multiple harddisks together to increase the size, the performance or the security of those drives. Raid can be done via a specific hardware implementation, which is expensive; or a software implementation, which adds overhead and decreases your CPU performance. On this page only the software implementation using the mdadm ( M ulti D rive Adm inistration) is covered.
3.3. Let’s Encrypt 32 Zawiki, Release v0.11-30-g7307413
3.4.1 Types
Raid types
Type ^ Description Image
RAID Block level striping. MD can handle devices 0 of different lengths, the extra space onthe larger device is then not striped
RAID Mirror 1
RAID Like RAID 0, but with an extra device for par- 4 ity
RAID Like RAID 4, but with the parity distributed 5 across all devices
RAID Like RAID 5, but with two parity segments 6 per stripe RAID Take a number of RAID 1 mirrorsets and 10 stripe across them RAID 0 style
3.4. Raid 33 Zawiki, Release v0.11-30-g7307413
Non-Raid types
• LINEAR – Concatenate a number of devices into a single large MD device. • MULTIPATH – Provide multiple paths with failover to a single device. • FAULTY – A single device which emulates a number of disk fault scenarios for testing and development. • CONTAINER – A group of devices managed as one, in which RAID systems can be built.
3.4.2 mdadm Commands
Check Raid Status cat /proc/mdstat sudo mdadm --query --detail /dev/md* # * = md number e.g. md0
Create Raid Array
Create a RAID 1 (mirror) array from two partitions. If the partitions differ in size, the array is the size of the smallest partition. mdadm --create /dev/md0 --level=mirror --raid-devices=2 /dev/sda1 /dev/sdb1
Create a RAID 5 volume from three partitions. If the partitions used in your RAID array are not the same size, mdadm will use the size of the smallest from each partition. If you receive an error, such as: mdadm: RUN_ARRAY failed: Invalid argument, make sure your kernel supports (either via a module or by being directly compiled in) the raid mode you are trying to use. Most modern kernels do, but you never know… mdadm --create /dev/md1 --level=5 --raid-devices=3 /dev/sda2 /dev/sdb2 /dev/sdc2
Change Raid Array
Grow
This adds the new device to the array then grows the array to use its space. mdadm --add /dev/md1 /dev/sdd1 mdadm --grow /dev/md1 --raid-devices=4
Delete Raid Array mdadm --stop /dev/md0 # to halt the array mdadm --remove /dev/md0 # to remove the array mdadm --zero-superblock /dev/sd[abc]1 # delete the superblock from all drives in␣ ,→the array vim /etc/mdadm/mdadm.conf # delete any rows related to deleted array
3.4. Raid 34 Zawiki, Release v0.11-30-g7307413
3.4.3 Links
• MDADM Wikipedia article • Official mdadm webpage
3.5 Samba
• Server – Installation Server – Configuration – User – Creating Share – Restart Samba – Test • Client – Installation Client – Create shared folder – Set Up FSTAB
Samba is useful for a creating a Network directory and share it with other PC, especially Windows.
3.5. Samba 35 Zawiki, Release v0.11-30-g7307413
3.5.1 Server
For creating a server who shares a drive
Installation Server
sudo apt-get install samba
Configuration
Under global add the following lines or uncomment them in your file etc/samba/smb. conf
Listing 5: /etc/samba/smb.conf
1 [global] 2 # Permission on newly created files and folders 3 create mask = 0644 4 directory mask = 0755
5
6 # add user security 7 security = user 8 encrypt passwords = true 9 map to guest = bad user
User
# Create User sudo smbpasswd -a username
New SMB password: Retype new SMB password: Added user username.
# Activate User sudo smbpasswd -e username Enabled user username.
Creating Share
Add the end of the file /etc/samba/smb.conf add your shares
Listing 6: /etc/samba/smb.conf [multimedia] comment = multimedia path = /mnt/multimedia browseable = yes read only = no
3.5. Samba 36 Zawiki, Release v0.11-30-g7307413
Restart Samba
# Linux in general sudo /etc/init.d/samba restart # Ubuntu >10.04 sudo initctl restart smbd
Test
To test samba and display all available shares for the current user type: smbclient -L
3.5.2 Client
For mounting a shared drive
Installation Client
Install samba tools. sudo apt-get install samba smbfs
Create shared folder
Create before an empty folder where you want to mount your samba drive. sudo mkdir /mnt/shared_folder_name
Set Up FSTAB
Open etc/fstab file and add a new entry . See also etc/fstab
3.5. Samba 37 Zawiki, Release v0.11-30-g7307413
Listing 7: /etc/fstab # only read access //SERVER/shares /MOUNTPOINT smbfs username=samba_user,password=samba_pass 0 0
# read / write access //SERVER/shares /MOUNTPOINT smbfs username=samba_user,password=samba_pass,uid=this_ ,→user,gid=this_group 0 0
3.6 Shairport
• Install • Run Shairport • Autostart
Linux can receive AirPlay audio using a program called Shairport. Shairport tries to em- ulate the Airport system of Apple. This version allows to stream music from a device e.g. Smartphone, Tablet, PC to the Airport Server which then play the music. The device need to be in the same Network.
3.6.1 Install
Download AirPlay (Shairport)
cd /tmp sudo git clone https://github.com/abrasive/shairport.git shairport
Install dependencies
sudo apt-get install libssl-dev libavahi-client-dev libasound2-dev build-essential
Configure the Shairport build
cd shairport ./configure
Make & install Shairport
sudo make sudo make install
Identify your audio output device
1 x@z:~$ aplay -l 2 **** List of PLAYBACK Hardware Devices **** 3 card 0: PCH [HDA Intel PCH], device 0: ALC892 Analog [ALC892 Analog] 4 Subdevices: 1/1 5 Subdevice #0: subdevice #0 6 card 0: PCH [HDA Intel PCH], device 1: ALC892 Digital [ALC892 Digital] 7 Subdevices: 1/1 8 Subdevice #0: subdevice #0 9 card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0] 10 Subdevices: 1/1 (continues on next page)
3.6. Shairport 38 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
11 Subdevice #0: subdevice #0 12 card 0: PCH [HDA Intel PCH], device 7: HDMI 1 [HDMI 1] 13 Subdevices: 1/1 14 Subdevice #0: subdevice #0
Setup the firewall I use ufw to do this:
1 sudo ufw allow from 192.168.1.1/16 to any port 3689 proto tcp 2 sudo ufw allow from 192.168.1.1/16 to any port 5353 3 sudo ufw allow from 192.168.1.1/16 to any port 5000:5005 proto tcp 4 sudo ufw allow from 192.168.1.1/16 to any port 6000:6005 proto udp 5 sudo ufw allow from 192.168.1.1/16 to any port 35000:65535 proto udp
3.6.2 Run Shairport
shairport -v -a 'Airplay receiver name' -o alsa-- -d hw:1,1
Add -v to the above for debugging info, -vv for more debug info and -vvv for even more debug info!
3.6.3 Autostart
For automatically start shairport you can use the script that comes with the source. Just copy the script you need to the init.d directory.
sudo cp scripts/debian/init.d/shairport /etc/init.d/
3.7 Subsonic
• Installation – Install Java – Install Madsonic • Configuration and Service – Add Transcoding – If somethings goes wrong • Jukebox – Selecting the Soundcard
(Sub)Madsonic is a free, web-based media streamer, providing ubiquitous access to your music. Use it to share your music with friends, or to listen to your own music while at work. You can stream to multiple players simultaneously, for instance to one player in your kitchen and another in your living room. (Sub)Madsonic is designed to handle very large music collections (hundreds of giga- bytes). Although optimized for MP3 streaming, it works for any audio or video format that can stream over HTTP, for instance AAC and OGG. By using transcoder plug-ins,
3.7. Subsonic 39 Zawiki, Release v0.11-30-g7307413
(Sub)Madsonic supports on-the-fly conversion and streaming of virtually any audio for- mat, including WMA, FLAC, APE, Musepack, WavPack and Shorten. If you have constrained bandwidth, you may set an upper limit for the bitrate of the music streams. (Sub)Madsonic will then automatically resample the music to a suitable bitrate.
Figure1: Madsonic Webinterface
3.7.1 Installation
For installation instructions see also here. My madsonic configuration can be see in the config repo: madsonic config
Install Java sudo apt-get install openjdk-8-jre
Install Madsonic
There are 2 good Subsonic versions. The official subsonic version, very stable, fast and reliable and the MadSonic Mod from MadEvil. It has several improvements and feature additions. • Download the Subsonic .deb package and install it: sudo dpkg -i subsonic-x.x.deb
• Download the MadSonic .deb package and install it:
3.7. Subsonic 40 Zawiki, Release v0.11-30-g7307413
sudo dpkg -i Madsonic-x.x.xxxx.deb
• Test the system on a local browser with the address http://localhost:4040
3.7.2 Configuration and Service
• Log into change the admin password first • Recommended to change advanced settings as well, like Java Memory, Port Number, Startup Settings – Edit the SUBSONIC_ARGS variable in /etc/default/subsonic or /etc/ default/madsonic • Restart the service
sudo service subsonic restart # or sudo service madsonic restart
Add Transcoding
In order that Subsonic can use the powerful transcoding feature you need to install some third-party transcoders:
sudo apt-get install lame flac faad vorbis-tools
If somethings goes wrong
Check the logs in /var/madsonic.
3.7.3 Jukebox
In order to get the Jukebox to work, the soundcard needs to be set up first. The user that is running (Sub)Madsonic needs to have access to the soundcard. For Ubuntu this means adding that user to the audio group in /etc/group.
useradd -G audio username
Selecting the Soundcard
First you need to find out what your soundcards are named in the sound library usedin Java. Create the following file
Listing 8: audioDevList.java
1 import java.io.*; 2 import javax.sound.sampled.*;
3
4 public class audioDevList{ 5 public static void main(String args[]){ (continues on next page)
3.7. Subsonic 41 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
6
7 // Get and display a list of available mixers.
8
9 Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); 10 System.out.println("Available mixers:"); 11 for(int cnt = 0; cnt < mixerInfo.length;cnt++){ 12 System.out.println(mixerInfo[cnt].getName()); 13 } 14 } 15 }
And then run
javac audioDevList.java java audioDevList
If you get an error about javac not found, you need to install the JDK (e.g. openjdk-8-jdk).
sudo apt-get install openjdk-8-jdk
Here is a sample output of the script:
Available mixers: NVidia [plughw:0,3] NVidia [plughw:0,7] NVidia [plughw:0,8] NVidia [plughw:0,9] Intel [plughw:1,0] CX8801 [plughw:2,0] Port NVidia [hw:0] Port Intel [hw:1] Port CX8801 [hw:2]
Linux / Mac : Modify your /usr/bin/subsonic/subsonic_run.sh (for Ubuntu package install) and add the following line. Note the single quotes and the hash mark # before the sound card name. Those are required.
'-Djavax.sound.sampled.SourceDataLine=#PCH [plughw:0,0]' \
Restart the subsonic service
sudo service subsonic restart # or sudo service madsonic restart
Once Music is played in jukebox mode the audio is not available anymore to other pro- grams. To cut this restart sub/madsonic as above shown.
3.8 Systemd
• List services • Status service • Start Stop Service • Add Service
3.8. Systemd 42 Zawiki, Release v0.11-30-g7307413
• Add in vim file • Start Service manually • Start Service on boot
3.8.1 List services systemctl --type=service
3.8.2 Status service systemctl status firewalld.service
3.8.3 Start Stop Service systemctl stop firewalld.service systemctl status firewalld.service
3.8.4 Add Service cd /etc/systemd/system sudo vim jupyterlab.service
3.8.5 Add in vim file
[Unit] Description = Jupyterlab service After = network.target StartLimitIntervalSec=0
[Service] Type=simple User=zas ExecStart=/home/zas/Documents/jupyterlab_start.bash
[Install] WantedBy = multi-user.target
3.8. Systemd 43 Zawiki, Release v0.11-30-g7307413
3.8.6 Start Service manually systemctl start jupyterlab
3.8.7 Start Service on boot systemctl enable jupyterlab
3.9 VIM
• Cheat Sheet • SWP Files • Commands – Edit & Save & Quit – File – Tab – Split screen – Search – Replace – Modes – Edit – Macro – Console • .vimrc
Vim is a text editor written by Bram Moolenaar and first released publicly in 1991. Based on the vi editor common to Unix-like systems, Vim is designed for use both from a command line interface and as a standalone application in a graphical user interface.
3.9. VIM 44 Zawiki, Release v0.11-30-g7307413
3.9.1 Cheat Sheet
The Vim Cheat Sheet was done by http://michael.peopleofhonoronly.com/vim/.
Figure2: Vim Cheatsheet
3.9.2 SWP Files
If working remotely Vim generated swap file. If you’re sure that your work is safely storey you can get rid of the swapfiles with the follwing commands: find . -name ".*.swp" # find swap files find . -name ".*.swp" | xargs rm -f # find and delete
3.9. VIM 45 Zawiki, Release v0.11-30-g7307413
3.9.3 Commands
Edit & Save & Quit
Command Description :e
File
Command Description :ls l i s t current buffers & files :e Open integrated File e xplorer :Sex S plit windows and open integrated File ex plorer
Tab open multiple files as tabs in vim >7.0 vim -p file1 file2 file3
Command Description :tabe
Split screen
Command Description :sb
3.9. VIM 46 Zawiki, Release v0.11-30-g7307413
Search
Regex
Command Description /
Replace
Command Description :%s/
Modes
Command Description i I nsert Mode R R eplace Mode a A ppend Mode v V isual Mode V V isual Line Mode Ctrl + v V isual Block Mode u U ndo
Edit
Command Description d D elete (also used as Cut) D D elete to eol (also used as Cut to eol) y Y ank (copy) Y Y ank (copy) line < shift left (marked lines) > shift right (marked lines)
3.9. VIM 47 Zawiki, Release v0.11-30-g7307413
Macro
Command Description q
Console
Execute a console command. Vim will be halted and the console from within Vim was opened will execute the program and go back to Vim after execution is complete.
Command Description :!
3.9.4 .vimrc
Listing 9: .vimrc
1 set nocp
2
3 set autoindent 4 set backspace=2 5 set backup 6 set hidden 7 set history=500 8 set hlsearch 9 set incsearch 10 set listchars=precedes:$,extends:$,tab:>-,trail:.,eol:< 11 " Line numbers " 12 set number 13 set printheader=%<%F%=Seite\ %N 14 set ruler 15 set shiftwidth=2 16 set showcmd 17 set showmatch 18 set showmode 19 set sidescroll=5 20 set smartcase 21 set smartindent 22 set softtabstop=2 23 set spelllang=de,en 24 set spellsuggest=double,10 25 set statusline=%<%f\ %h%m%r%=%([%{Tlist_Get_Tagname_By_Line()}]%)\ #%n\ %-14.(%l/ ,→%L,%c%V%)\ %P 26 set tabstop=2 27 " set textwidth=75 " 28 set title 29 set wildmenu 30 set wildmode=list:longest,full
31
32 " Use Windows Clipboard " (continues on next page)
3.9. VIM 48 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
33 if has("win32") 34 set clipboard=unnamed 35 endif
36
37 " Syntax Highlighting " 38 syntax on
39
40 " Filename Detection 41 filetype on 42 filetype indent on 43 filetype plugin on
44
45 " Folding 46 "syntax sync fromstart 47 set foldmethod=indent 48 set nofoldenable
Download my .vimrc
3.10 VNC Remote Control
• x11vnc – Install – Config – Start – Autostart • VNC over SSH – Linux ∗ Open SSH Tunnel ∗ Launch VNC Viewer in Linux – Windows ∗ Putty Config ∗ Start VNC ∗ Troubleshooting – Macintosh ∗ Install Tools ∗ Set up SSH Tunnel ∗ Launch VNC Viewer in Mac • Putty
VNC is a protocol to let you connect and view the screen of your remote controlled PC. But this isn’t very secure and should not be enabled over the internet but only locally. VNC is often used to hack Linux PC. Therefore you should use VNC over SSH where the data is encrypted and very secure.
3.10. VNC Remote Control 49 Zawiki, Release v0.11-30-g7307413
3.10.1 x11vnc
Perfect fast and configurable solution for almost all Linux distributions. x11vnc does not create an extra display (or X desktop) for remote control. Instead, it uses the existing X11 display shown on the monitor of a Unix-like computer in real time.
Install sudo apt-get install x11vnc
Config
Generate password file x11vnc -storepasswd Enter VNC password: Verify VNC password:
The password in now store by default in the file ~/.vnc/passwd
Start x11vnc -usepw -forever -display :0 -safer -bg -o /home/user/Documents/log/vnc/ ,→x11vnc.log -localhost
• -forever : listen forever to input connections • -display :
Autostart
In Lubuntu with LXDE add the following line to the file : /etc/xdg/lxsession/Lubuntu/ autostart
Listing 10: /etc/xdg/lxsession/Lubuntu/autostart @x11vnc -usepw -forever -display :0 -safer -bg -o /home/user/Documents/log/vnc/ ,→x11vnc.log -localhost
In Lubuntu with lightdm add the following line to the file : /etc/xdg/lxsession/Lubuntu/ autostart
Listing 11: /etc/xdg/lxsession/Lubuntu/autostart @x11vnc -usepw -forever -safer -bg -o /home/user/Documents/log/vnc/x11vnc.log - ,→localhost -auth /var/run/lightdm/root/:0 -display :0
In Gnome add the following line to the file: /etc/gdm/Init/Default
3.10. VNC Remote Control 50 Zawiki, Release v0.11-30-g7307413
Listing 12: /etc/gdm/Init/Default x11vnc -usepw -forever -display :0 -safer -bg -o /home/zas/Documents/log/vnc/ ,→x11vnc.log -localhost
3.10.2 VNC over SSH
Linux
Open SSH Tunnel
ssh -N -T -L 5900:localhost:5900
This forwards our local port 5900 to the host computers port 5900, just replace 5900 with the port you normally use for VNC connections, i.e if you use display 20 then it would read ssh -N -T -L 5920:
Launch VNC Viewer in Linux
vncviewer localhost:5900
Windows
To connect to VNC over SSH in Linux you need a VNC Viewer like UltraVNC and Putty
Putty Config
see: Putty
Start VNC
• Start Putty with the above configuration • Enter password • Open a VNC Viewer • Connect to 127.0.0.1
3.10. VNC Remote Control 51 Zawiki, Release v0.11-30-g7307413
Troubleshooting
If you have problems connecting to the remote machine, and if the connection gets rejected then you should quit your local VNC Server. Because you are connecting via localhost he might respond to your request.
Macintosh
Install Tools
Tightvnc is a great vncviewer and is installable through Macport, as well as Putty: sudo port install tightvnc sudo port install putty
Set up SSH Tunnel
Terminal ssh -p
Putty see: Putty
Launch VNC Viewer in Mac vncviewer localhost:5900 or use the program “Chicken Of VNC”
3.10.3 Putty
• Create a new putty session • goto Session -> Add hostname and port • goto SSH -> Enable compression • goto SSH -> Tunnels -> Add tunnel – Source Port: 5900 – Destination : 127.0.0.1:5900 – Click Add
3.10. VNC Remote Control 52 Zawiki, Release v0.11-30-g7307413
Figure5: Putty Tunnel con- Figure3: Putty Session Figure4: Putty SHH Config fig
3.11 VPN Virtual Private Network
• VPN Server Outgoing (Linux) – Install – Config – Start VPN – Enable Forwarding • VPN client Incoming (Win 7)
A virtual private network (VPN) extends a private network across a public network, such as the Internet. It enables a computer to send and receive data across shared or public networks as if it were directly connected to the private network, while benefiting from the functionality, security and management policies of the private network. This is done by establishing a virtual point-to-point connection through the use of dedicated connections, encryption, or a combination of the two. There exist many different VPN protocols such as PPTP, OpenVPN, L2TP, SSTP. Inthis section We will set-up and connect a VPN connection using the PPTP protocol.
3.11. VPN Virtual Private Network 53 Zawiki, Release v0.11-30-g7307413
3.11.1 VPN Server Outgoing (Linux)
Install sudo apt-get install pptpd
Config
Add the following lines in your etc/pptpd.conf
Listing 13: /etc/pptpd.conf localip 192.168.1.5 # IP of your server hosting VPN remoteip 192.168.1.234-1.238 # Range of IP to use for connected machines
Add the following lines to configure pptpd in /etc/ppp/pptpd-options
Listing 14: /etc/ppp/pptpd-options ms-dns 192.168.1.1 # IP of your DNS Server nobsdcomp noipx mtu 1490 mru 1490 add users to the /etc/ppp/chap-secrets file, you can add as many users as you like
Listing 15: /etc/ppp/chap-secrets username * users-password *
Start VPN
Start / Restart the VPN Deamon to activate the config sudo /etc/init.d/pptpd restart
Important: Note that the connection can only access the server itself and not beyond it. Enable forwarding to avoid this.
Enable Forwarding
This step is optional. It is needed to give the connected machine access beyond the server. By enable forwarding the entire network will be available to the connected machine not just the VPN server itself. Edit the /etc/sysctl.conf and change to following parameter from 0 to to 1
3.11. VPN Virtual Private Network 54 Zawiki, Release v0.11-30-g7307413
Listing 16: /etc/sysctl.conf net.ipv4.ip_forward=1
To active the setting either restart the server or run the command: sudo sysctl -p
3.11.2 VPN client Incoming (Win 7)
See the print screens to how to setup the VPN incoming connection on Windows 7.
Note: If VPN is setup by default to relay all traffic through the VPN connection. To avoid this you need to uncheck.
Figure6: Start VPN setup
3.11. VPN Virtual Private Network 55 Zawiki, Release v0.11-30-g7307413
Figure7: Configure machine to connect to
Figure8: Configure user credentials
3.11. VPN Virtual Private Network 56 Zawiki, Release v0.11-30-g7307413
Figure9: Change IPv4 and ipv6 properties
Figure10: Goto advanced properties
3.11. VPN Virtual Private Network 57 Zawiki, Release v0.11-30-g7307413
Figure11: Uncheck user default gateway
3.11. VPN Virtual Private Network 58 Chapter 4
Ubuntu
4.1 Installation and Config
• Installation – Default Tools – ZSH – Oh My ZSH – SublimeText 3 – SublimeMerge – Krusader – Yakuake – FSearch – Anaconda – QT-Creator – Visual Studio Code • Configuration – Oh My ZSH Config – SublimeText 3 Config – SublimeMerge Config
59 Zawiki, Release v0.11-30-g7307413
• How To Use Ubuntu Tools – SSH ∗ SSH connection without password ∗ Open SSH Connection – VNC ∗ Create password ∗ Launch x11vnc – QView
4.1.1 Installation
This installation is based on Ubuntu 18.4 LTS and ROS Melodic Morenia.
Default Tools sudo apt-get install git curl vim openssh-server krename rar unrar kget diffutils␣ ,→kate x11vnc echo "Configure Firewall and Port for ssh" sudo ufw allow ssh sudo ufw enable sudo ufw status sudo service ssh restart
ZSH sudo apt-get install zsh sudo chsh -s /bin/zsh $USER
Oh My ZSH cd ~/Downloads sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/ ,→install.sh)"
SublimeText 3 wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add - sudo apt-get install apt-transport-https echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/ ,→sources.list.d/sublime-text.list sudo apt-get update sudo apt-get install sublime-text
4.1. Installation and Config 60 Zawiki, Release v0.11-30-g7307413
SublimeMerge wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add - sudo apt-get install apt-transport-https echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/ ,→sources.list.d/sublime-text.list sudo apt-get update sudo apt-get install sublime-merge
Krusader sudo apt-get install krusader
Yakuake sudo apt-get install yakuake
FSearch sudo add-apt-repository ppa:christian-boxdoerfer/fsearch-daily sudo apt update sudo apt-get install fsearch-trunk
Anaconda cd ~/Downloads wget https://repo.anaconda.com/archive/Anaconda3-2019.10-Linux-x86_64.sh bash Anaconda3-2019.10-Linux-x86_64.sh
QT-Creator cd ~/Downloads wget http://download.qt.io/official_releases/qt/5.13/5.13.1/qt-opensource-linux- ,→x64-5.13.1.run chmod +x qt-opensource-linux-x64-5.13.1.run ./qt-opensource-linux-x64-5.13.1.run sudo apt-get install build-essential sudo apt-get install libfontconfig1 sudo apt-get install mesa-common-dev sudo apt-get install libglu1-mesa-dev -y
4.1. Installation and Config 61 Zawiki, Release v0.11-30-g7307413
Visual Studio Code curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages. ,→microsoft.gpg sudo install -o root -g root -m 644 packages.microsoft.gpg /usr/share/keyrings/ sudo sh -c 'echo "deb [arch=amd64 signed-by=/usr/share/keyrings/packages.microsoft. ,→gpg] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources. ,→list.d/vscode.list' sudo apt-get install apt-transport-https sudo apt-get update sudo apt-get install code # or code-insiders
4.1.2 Configuration
Oh My ZSH Config
Listing 1: ~/.zshrc additions echo"#------,→-" >> ~/.zshrc echo "# Program in Path" >> ~/.zshrc echo "#" >> ~/.zshrc echo "#------,→--" >> ~/.zshrc echo "# Special zsh config" >> ~/.zshrc echo "# Show hidden files and folders" >> ~/.zshrc echo "setopt globdots" >> ~/.zshrc echo "#------,→--" >> ~/.zshrc echo "# Goto Alias" >> ~/.zshrc echo "# Common home locations" >> ~/.zshrc echo "alias home='cd ~'" >> ~/.zshrc echo "alias root='cd /'" >> ~/.zshrc echo "alias dtop='cd ~/Desktop'" >> ~/.zshrc echo "alias dwld='cd ~/Downloads'" >> ~/.zshrc echo "alias docs='cd ~/Documents'" >> ~/.zshrc echo "alias www='cd /var/www/html'" >> ~/.zshrc echo "alias workspace='cd ~/Workspace'" >> ~/.zshrc echo "alias aptlock-rm='sudo rm /var/lib/dpkg/lock && sudo rm /var/lib/dpkg/lock- ,→frontend'" >> ~/.zshrc echo "# Common commands" >> ~/.zshrc echo "alias o=open" >> ~/.zshrc echo "alias ..='cd ..'" >> ~/.zshrc echo "alias ...='cd ..; cd ..'" >> ~/.zshrc echo "alias ....='cd ..; cd ..; cd ..'" >> ~/.zshrc echo "# Common command shortcuts" >> ~/.zshrc echo "alias cls=clear" >> ~/.zshrc echo "alias ll='ls -la'" >> ~/.zshrc
4.1. Installation and Config 62 Zawiki, Release v0.11-30-g7307413
SublimeText 3 Config
Listing 2: ~/.zshrc additions echo "# Sublime Text" >> ~/.zshrc echo "export PATH=$PATH:/opt/sublime_text" >> ~/.zshrc echo "# Sublime Text" >> ~/.bashrc echo "export PATH=$PATH:/opt/sublime_text" >> ~/.bashrc cp ./../config/sublimetext/Package Control.sublime-settings ~/.config/sublime-text- ,→3/Packages/User/
SublimeMerge Config
Listing 3: ~/.zshrc additions echo "#Sublime Merge" >> ~/.zshrc echo "export PATH=$PATH:/opt/sublime_merge" >> ~/.zshrc echo "#Sublime Merge" >> ~/.bashrc echo "export PATH=$PATH:/opt/sublime_merge" >> ~/.bashrc
4.1.3 How To Use Ubuntu Tools
SSH
SSH connection without password
# On your local machine generate a RSA Key pair ssh-keygen -t rsa
# Copy your local public key to the remote machine safely ssh-copy-id -i ~/.ssh/id_rsa.pub "
# Append key to file authorized_keys cat ~/.ssh/*.pub | ssh
Open SSH Connection
# Just ssh ssh
# ssh with portforwarding ssh -L
4.1. Installation and Config 63 Zawiki, Release v0.11-30-g7307413
VNC
On remote PC x11vnc needs to be installed and launched. Prefereable add to startup commands
Create password
Only needed if not only localhost used. x11vnc -storepasswd
Launch x11vnc
# Command with all options x11vnc -usepw -forever -display :0 -safer -bg -o ~/Documents/log/vnc/x11vnc.log - ,→localhost
# Minimal command but still restricted to localhost x11vnc -forever -display :0 -safer -bg -localhost
QView
Lightweight Image Viewer sudo add-apt-repository ppa:jurplel/qview sudo apt-get update sudo apt-get install qview
4.2 Introduction
• Additional Informations
4.2.1 Additional Informations
• https://ubuntu.com/ - Ubuntu Webpage – https://ubuntu.com/#download - Ubuntu Download • https://www.osboxes.org/ubuntu/ - Virtual Box images • Additional Tools – ZSH ∗ Oh My ZSH – Sublime Text – Sublime Merge – Krusader – Yakuake
4.2. Introduction 64 Zawiki, Release v0.11-30-g7307413
– FSearch – Anaconda – QT Creator – Visual Studio Code – Hitachi SDK ∗ Hitachi LiDaR SDK ∗ Hitachi LiDaR ROS Driver – ROS Installation
4.2. Introduction 65 Chapter 5
Raspberry Pi
5.1 Rune Audio
• Commandline Tricks • Hifiberry Amp+
66 Zawiki, Release v0.11-30-g7307413
Rune Audio is a based on an Archlinux distribution. It is intended to be easy to setup and offers a wide variety of audio tools and supports many different DAC’s. For the Raspberry Pi A+/B+ and 2 a preconfigured image is available with out of the box support formany DAC’s. Features are: • Webserver • MPD • Shairport (Airplay) • Webradio • USB • Samba • Jamendo • Spotify • DLNA
5.1.1 Commandline Tricks
Listing 1: soundcards and attached boards aplay -l # Display's available sound cards aplay -L # Display's all PCM's
Listing 2: volume mixer amixer sset Master 100 # ~0% Volume amixer sset Master 200 # ~100% Volume
5.1.2 Hifiberry Amp+
Add HiFiberry Amp+ to the system. First you need to add the devicetree overlay.
Listing 3: /boot/config.txt> device_tree_overlay=hifiberry-amp
Afterwards you need to change the mpd configuration.
Listing 4: /etc/mpd.conf audio_output { name "snd_rpi_hifiberry_amp" type "alsa" device "hw:1,0" mixer_type "hardware" mixer_control "Master" mixer_device "hw:1" mixer_index "0" auto_resample "no" auto_format "no" enabled "yes" }
5.1. Rune Audio 67 Zawiki, Release v0.11-30-g7307413
Perhaps the file /etc/mpd.conf will be overwritten on each restart. As a bad fix this can be avoided making the file immutable
chattr +i /etc/mpd.conf
5.2 Setup Rpi
• Raspi-conf • Wifi Dongle – Setup – For static IP address • Disable Power saving mode • SSH – Set up Hostname – SSH Connect ∗ Resolve ssh lang issue ∗ Source .bashrc file upon ssh logon • GUI • Important stuff • Interconectivity • Python modules – General – GPIO – I2C
5.2.1 Raspi-conf
The integrated Rpi config tool for many things.
raspi-config
5.2.2 Wifi Dongle
Setup
Listing 5: /etc/network/interfaces
1 auto lo
2
3 iface lo inet loopback 4 iface eth0 inet dhcp
5 (continues on next page)
5.2. Setup Rpi 68 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
6 allow-hotplug wlan0 7 auto wlan0
8
9
10 iface wlan0 inet dhcp 11 wpa-ssid "ssid" 12 wpa-psk "password"
For static IP address
Listing 6: /etc/network/interfaces
1 iface eth0 inet static 2 address
5.2.3 Disable Power saving mode
Listing 7: /etc/modprobe.d/8192cu.conf # Disable power saving options 8192cu rtw_power_mgnt=0 rtw_enusbss=1 rtw_ips_mode=1
5.2.4 SSH
See also SSH
Set up Hostname
Setting up your Raspberry with a hostname can be very useful if it is connected to a network with DHCP Server. Instead of searching for the IP of the RPi you can find it by it’s hostname. • install samba and the samba tools
sudo apt-get install samba samba-common-bin sudo apt-get install netatalk # for avahi setup for mac
• change the hostname in the following files
sudo vim /etc/hostname sudo vim /etc/hosts # or sudo hostname
• restart hostname service
sudo service hostname.sh start
Now you can connect to your RPi with your hostname
5.2. Setup Rpi 69 Zawiki, Release v0.11-30-g7307413
SSH Connect
Regenerate ssh keys to be safe rm /etc/ssh/ssh_host_* && dpkg-reconfigure openssh-server
Connect via remote PC ssh pi@
Resolve ssh lang issue
Listing 8: /etc/ssh/ssh_config # Comment the following line # SendEnv LANG LC...
Add the following environment variables into your ~/.bash_profile
Listing 9: ~/.bash_profile export LANG="en_US" export LANGUAGE=$LANG export LC_ALL=$LANG
Source .bashrc file upon ssh logon
Add the following line to the ~/.bash_profile
Listing 10: ~/.bash_profile source $HOME/.bashrc
5.2.5 GUI
Launch GUI startx
5.2.6 Important stuff sudo apt-get install vim git tightvncserver
5.2. Setup Rpi 70 Zawiki, Release v0.11-30-g7307413
5.2.7 Interconectivity
Enable i2c
Listing 11: /etc/modules i2c-bcm2708 i2c-dev
Remove SPI and I2C from the blacklist
Listing 12: /etc/modprobe.d/raspi.blacklist.conf # Comment out both line to remove from blacklist # blacklist spi-bcm2708 # blacklist i2c-bcm2708
5.2.8 Python modules
General sudo apt-get install python-dev
GPIO sudo apt-get install python-rpi.gpio # GPIO Module
I2C sudo apt-get install python-smbus # SMBus support sudo apt-get install i2c-tools # I2C support sudo i2cdetect -y 0 # Detect I2C on RPi v2
5.2. Setup Rpi 71 Chapter 6
Filesystem
6.1 Important Files
/boot/grub # Grub files /etc/fstab # Drive mounts /etc/profile # EnvVar for all users /etc/group # All groups available /home/username/.bashrc # User-script @startup /etc/init.d/ # Global start-scripts /etc/ssh/sshd.config # SSH config file ~.bashrc # bash shell init scripts ~.zshrc # zsh shell init scripts
6.2 Folders
6.2.1 Foreword
Like UNIX, Linux chooses to have a single hierarchical directory structure. Everything starts from the root directory, represented by /, and then expands into sub- directories instead of having so-called ‘drives’. In the Windows environment, one may put one’s files almost anywhere: on C drive, D drive, E drive etc. Such a file system iscalleda hierarchical structure and is managed by the programs themselves (program directories), not by the operating system. On the other hand, Linux sorts directories descending from the root directory / according to their importance to the boot process.
72 Zawiki, Release v0.11-30-g7307413
6.2.2 Root directory /
As we all know Linux file system starts with /, the root directory. All other directories are ‘children’ of this directory. The partition which the root file system resides on is mounted first during boot and the system will not boot if it doesn’t find it. On our reference system, the root directory contains the following sub-directories:
Figure1: https://www.blackmoreops.com/
Folder Description /bin Essential command binaries /boot Static files of the boot loader /dev Device files /etc Host-specific system configuration /root Home directory for the root user (optional) /home User home directories (optional) /lib Essential shared libraries and kernel modules /lib
6.2. Folders 73 Zawiki, Release v0.11-30-g7307413
/bin
The bin directory contains several useful commands that are of use to both the system administrator as well as non-privileged users. It usually contains the shells like bash, csh, etc. and commonly used commands like cp, mv, rm, cat, ls. For this reason and in contrast to /usr/bin, the binaries in this directory are considered to be essential. The reason for this is that it contains essential system programs that must be available even if only the partition containing / is mounted. This situation may arise should you need to repair other partitions but have no access to shared directories (ie. you are in single user mode and hence have no network access). It also contains programs which boot scripts may depend on.
/boot
This directory contains everything required for the boot process except for configuration files not needed at boot time (the most notable of those being those that belong tothe GRUB boot-loader) and the map installer. Thus, the /boot directory stores data that is used before the kernel begins executing user-mode programs. This may include redundant (back-up) master boot records, sector/system map files, the kernel and other important boot files and data that is not directly edited by hand. Programs necessary to arrangefor the boot loader to be able to boot a file are placed in /sbin. Configuration files for boot loaders are placed in /etc. The system kernel is located in either / or /boot (or as under Debian in /boot but is actually a symbolically linked at /.
/boot/map
Contains the location of the kernel.
/boot/vmlinuz /boot/vmlinuz-kernel-version
Normally the kernel or symbolic link to the kernel.
/boot/grub
This subdirectory contains the GRUB configuration files including boot-up images and sounds. GRUB is the GNU GRand Unified Bootloader, a project which intends to solve all bootup problems once and for all. One of the most interesting features, is that you don’t have to install a new partition or kernel, you can change all parameters at boot time via the GRUB Console, since it knows about the filesystems.
/boot/grub/grub.conf /boot/grub/menu.lst
Grub configuration file.
6.2. Folders 74 Zawiki, Release v0.11-30-g7307413
/dev
/dev is the location of special or device files. It is a very interesting directory that high- lights one important aspect of the Linux filesystem - everything is a file or a directory. Look through this directory and you should hopefully see hda1, hda2 etc…. which rep- resent the various partitions on the first master drive of the system. /dev/cdrom and /dev/fd0 represent your CD-ROM drive and your floppy drive. This may seem strange but it will make sense if you compare the characteristics of files to that of your hardware. Both can be read from and written to. Take /dev/dsp, for instance. This file represents your speaker device. Any data written to this file will be re-directed to your speaker. Ifyou try cat /boot/vmlinuz > /dev/dsp (on a properly configured system) you should hear some sound on the speaker. That’s the sound of your kernel! A file sent to /dev/lp0 gets printed. Sending data to and reading from /dev/ttyS0 will allow you to communicate with a device attached there - for instance, your modem. 3 Informations are relevant: • Kind of the Access – bloc oriented (b) - buffered access e.g. Harddisks – characteroriented (c) - non buffered access e.g. Screen, Printer • Major device number – Specify the driver to be used. • Minor device number – To describe the actual instance of a device. In case multiple devices of the same driver are used Some common device files as well as their equivalent counterparts under Windows that you may wish to remember are:
Listing 1: deviceslist.txt /dev/ttyS0 (First communications port, COM1) First serial port (mice, modems).
/dev/psaux (PS/2) PS/2 mouse connection (mice, keyboards).
/dev/lp0 (First printer port, LPT1) First parallel port (printers, scanners, etc).
/dev/dsp (First audio device) The name DSP comes from the term digital signal processor, a specialized␣ ,→processor chip optimized for digital signal analysis. Sound cards may use a␣ ,→dedicated DSP chip, or may implement the functions with a number of discrete␣ ,→devices. Other terms that may be used for this device are digitized voice and␣ ,→PCM.
/dev/usb (USB Devices) This subdirectory contains most of the USB device nodes. Device name␣ ,→allocations are fairly simplistic so no elaboration is be necessary.
/dev/sda (C:\, SCSI device) First SCSI device (HDD, Memory Sticks, external mass storage devices such as␣ ,→CD-ROM drives on laptops, etc).
/dev/scd (D:\, SCSI CD-ROM device) First SCSI CD-ROM device.
(continues on next page)
6.2. Folders 75 Zawiki, Release v0.11-30-g7307413
(continued from previous page) /dev/js0 (Standard gameport joystick) First joystick device.
/dev/hd* Mounted Harddisk Partitions
/etc
Contains all local configurationfiles.
/root
Home folder for the root user. In most systems it was eliminated
/home
Home folder for all system users. Each user has a own RWX folder with his name inside /home/
/lib
Needed systemlibraries and kernelmodules
/lib
Needed systemlibraries and kernelmodules
/media
Debian automatic mountpoint for Plug&Play programms
/mnt
Temporary mountpoint
/opt
Place for optional Software installed be the user.
6.2. Folders 76 Zawiki, Release v0.11-30-g7307413
/sbin
Important systemprogramms. They are used for the startup of the system. Only executable by root user.
/tmp
All users can use this foder to store temporary files
/usr
User Data
/var
Variable data
6.2. Folders 77 Chapter 7
Mac
7.1 Geektool
Geektool is a wonderful program to display information on your desktop. Here you can see my “Control Center”.
7.1.1 Date & Time
All command geeklets date +%d # Day number date +%B # Month date +%A # Weekday date "+%H" # Hour date "+%M" # Minutes
78 Zawiki, Release v0.11-30-g7307413
Figure1: Geektool Example
7.1.2 Location & Weather
Actual Weather
All command geeklets Get the weather of a certain location from Yahoo weather.
WEATHER=`curl --silent "http://weather.yahooapis.com/forecastrss?p=SZXX0035&u=c" |␣ ,→grep -E '(Current Conditions:|C
//' -e 's/ C$/ ,→˚C/'` echo "Sion " $WEATHER
Moonphase
Get the image for the actual Moonphase from lexiyoga. Directly the image will be fetch, therefore a image geeklet is needed. http://www.lexiyoga.com/images/moon/moon16.png
7.1. Geektool 79 Zawiki, Release v0.11-30-g7307413
7.1.3 System information
Uptime uptime | awk '{sub(/[0-9]|user\,|users\,|load/, "", $6); sub(/mins,|min,/, "min", ,→$6); sub(/user\,|users\,/, "", $5); sub(",", "min", $5); sub(":", "h ", $5);␣ ,→sub(/[0-9]/, "", $4); sub(/day,/, " day ", $4); sub(/days,/, " days ", $4); sub(/ ,→mins,|min,/, "min", $4); sub("hrs,", "h", $4); sub(":", "h ", $3); sub(",", "min ,→", $3); print "Uptime: " $3$4$5$6}'
Networking
# Internal Wireless IP myen0=`ifconfig en0 | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}'` if [ "$myen0" != "" ] then echo "Wireless: $myen0" else echo "Wireless INACTIVE" fi
# Internal Ethernet IP myen1=`ifconfig en1 | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}'` if [ "$myen1" != "" ] then echo "Ethernet: $myen1" else echo "Ethernet INACTIVE" fi
# External IP wip=`curl --silent http://checkip.dyndns.org | awk '{print $6}' | cut -f 1 -d "<"` echo "External IP: $wip"
Battery status
BATTERY=`ioreg -l | awk '$3~/Capacity/{c[$3]=$5}END{OFMT="%.f %%";max=c["\ ,→"MaxCapacity\""];print(max>0?100*c["\"CurrentCapacity\""]/max:"?")}'` echo $BATTERY '\n\n\n'
HDD usage
DISK=`df -hl | grep 'disk0s2' | awk '{print $5 " ("$4"/"$2")"}'` echo $DISK '\n\n\n'
7.1. Geektool 80 Zawiki, Release v0.11-30-g7307413
Ram usage
MEM=`top -l 1 | grep PhysMem: | awk '{print int($2/($2+$6)*100)}'` echo $MEM'%\n\n\n'
CPU load
SYSTEM=`top -l3 | grep "CPU usage" | tail -1 | awk '{print int(($3+$5))}' | sed 's/ ,→\%//'` echo $SYSTEM '%\n\n\n'
Process manager ps -amcwwwxo "command %mem %cpu" | grep -v grep | head -13
7.2 Keyboard Layout
All Mac have a keyboard were many symbols are missing. In programming this is very unpractical, so either you know on the tip of your head where which symbol is; or you look at the layout below ;-). The layout is accordingly to the Mac Retina Book Swiss keyboard.
7.3 Macport https://www.macports.org sudo port install
7.3.1 Useful Macports
• Krusader • kdiff3 • md5deep • unrar • pzip • putty • tightvnc • …
7.2. Keyboard Layout 81 Zawiki, Release v0.11-30-g7307413
Figure2: Mac keyboard swiss layout
7.3. Macport 82 Chapter 8
Windows
8.1 Commandline
• Get Win License Key • Bat Script – Start - End Script – Run other script – Delete – Directory – Remove trailing \ – Commandline Arguments – Forcing ownership
Sample scripts can be found in the config repo
83 Zawiki, Release v0.11-30-g7307413
8.1.1 Get Win License Key wmic path softwarelicensingservice get OA3xOriginalProductKey
8.1.2 Bat Script
Start - End Script
Listing 1: skeleton.bat :start @echo off setlocal set cmd_location="%~dp0" pushd %cmd_location% set SEPARATOR="------,→------" set INDENT=" "
echo %SEPARATOR% echo "-- %~nx0 Started!" echo.
:script
:end echo. echo "-- %~nx0 Finished!" echo %SEPARATOR% popd endlocal goto:eof
Run other script
Listing 2: delete.bat :: Runs scripts and comes back call "./script.bat"
Delete
Listing 3: delete.bat set base_directory="%cmd_location:"=%.." echo "Delete files in: %base_directory%" del /f /s /a %base_directory%\*cache.dat echo "Delete intermediate directories in: %base_directory%" for /d /r "%base_directory:"=%\" %%a in (.xrf\) do if exist "%%a" rmdir /s /q "%%a"
8.1. Commandline 84 Zawiki, Release v0.11-30-g7307413
Directory
Listing 4: dir.bat echo Delete directory %dir% if exist %dir% ( echo %dir% found ) else ( echo %dir% not found! ) echo Create %dir% if not exist if not exist "%dir%" ( mkdir "%dir:"=%" )
Remove trailing \
Listing 5: string_manipulation.bat if %cmd_location:~-1%==\ set design_directory=%design_directory:~0,-1%
Commandline Arguments
Listing 6: cmnd_args.bat ::------:: Parse command line options :: :parse set usage1="Usage: hdl_designer.bat [-v] [-h]" set usage2=" [-n designName]" set usage3=" [-d designDirectory]" echo "Search Commandline Parameters" :parseloop if not "%1"=="" ( if "%1"=="-v" ( set VERBOSE=1 echo "%INDENT:"=%verbose enabled" shift ) if "%1"=="-h" ( goto :HELP shift ) if "%1"=="-n" ( set design_name=%2 echo "%INDENT:"=%design_name=!design_name:"=! " shift & shift ) if "%1"=="-d" ( set design_directory=%2 echo "%INDENT:"=%design_directory=!design_directory:"=! " shift & shift ) goto :parseloop (continues on next page)
8.1. Commandline 85 Zawiki, Release v0.11-30-g7307413
(continued from previous page) ) echo.
::------:: Helper Functions :: :HELP echo. echo %usage1:"=% echo %usage2:"=% echo %usage3:"=% echo.&pause&goto:eof
Forcing ownership
German Version
Listing 7: force_ownership_de.bat SET DIRECTORY_NAME="C:\Folder\You\Want\Rights\To" TAKEOWN /f %DIRECTORY_NAME% /r /d J ICACLS %DIRECTORY_NAME% /grant administratoren:F /t pause
English Version
Listing 8: force_ownership_en.bat SET DIRECTORY_NAME="C:\Folder\You\Want\Rights\To" TAKEOWN /f %DIRECTORY_NAME% /r /d Y ICACLS %DIRECTORY_NAME% /grant administrators:F /t pause
General
8.1. Commandline 86 Zawiki, Release v0.11-30-g7307413
Listing 9: force_ownership.bat pushd . takeown /f * /r /a icacls *.* /grant:r everyone:f /t /c /q popd
8.2 Firewall
• SSH Over FTP Port
8.2.1 SSH Over FTP Port
Ff FTP Port is used for SSH connections disable Statefulftp in the Windows firewall netsh advfirewall set global statefulftp disable
8.3 Group Policies
• Modify Policies • See all modified Group Policies
8.3.1 Modify Policies
Search for Edit group policy
8.3.2 See all modified Group Policies
Search for rsop.msc
8.4 Power
• powercfg • ´´dumppo´´
8.2. Firewall 87 Zawiki, Release v0.11-30-g7307413
8.4.1 powercfg
:: List available powerstates powercfg /devicequery /?
:: Lists devices be able to wake up the pc from sleep powercfg /devicequery wake_programmable
:: Generates energy report powercfg energy
:: Lists all available powerstates powercfg -a
:: Last wakeup device powercfg -lastwake
:: Turn of Hibernation (in admin console) powercfg -H off
8.4.2 ´´dumppo´´
Basically there are 2 sleep states in Windows, S1 and S3. Most of the time all you have to do is set your BIOS sleep mode to “S3 only” and it should always use S3 sleep state. However you could also configure Windows to force S3 sleep state to ensure that your system saves maximum power. While I don’t have exact figures because each PC is different, I cantell you that S1 sleep state only saves a couple of watts of power but S3 on the other hand only uses a couple watts of power and thus saves quite alot more. Enter ´´dumppo admin´´ in a console to show th current state
$dumppo admin Admin policy overrides Min sleep state...... : S1 Max sleep state...... : S4 - hibernate Min video timeout....: 0 Max video timeout....: -1 Min spindown timeout.: 0 Max spindown timeout.: -1
Notice the minimum sleep state is S1 by default. Type the following command and press enter, “dumppo admin minsleep=S3”. You should now get the following information on the screen.
>dumppo admin minsleep=S3 Admin policy overrides Min sleep state...... : S3 Max sleep state...... : S4 - hibernate Min video timeout....: 0 Max video timeout....: -1 Min spindown timeout.: 0 Max spindown timeout.: -1
8.4. Power 88 Zawiki, Release v0.11-30-g7307413
8.5 Registry
• Login • DateTime • Shell Overlay Icons • Context Menu • New Context Menu • SAP Shortcut Password • PowerPoint Options • Power Settings • Taskbar Transparency
8.5.1 Login
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
8.5.2 DateTime
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\DateTime\Servers
8.5.3 Shell Overlay Icons
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ ,→ShellIconOverlayIdentifiers
8.5.4 Context Menu
Computer\HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers
8.5.5 New Context Menu
Computer\HKEY_CLASSES_ROOT\
8.5. Registry 89 Zawiki, Release v0.11-30-g7307413
8.5.6 SAP Shortcut Password
Computer\HKEY_CURRENT_USER\Software\SAP\SAPShortcut\Security
8.5.7 PowerPoint Options
Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\PowerPoint\Options :: ExportBitmapResolution => DWORD 32bit => 300 (ppi) :: AutomaticPicturesCompressionDefault => DWORD => 0
8.5.8 Power Settings
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power :: HibernateEnabledDefault = 0
8.5.9 Taskbar Transparency
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ ,→Advanced :: UseOLEDTaskbarTransparency => DWORD 32bit => 1
8.5. Registry 90 Chapter 9
Useful Tools
Quick unfinished List of useful tools
9.1 Multimedia
• VLC - Video Player
• Gimp - Image Editor
• Inkscape - Vector Graphic Editor
91 Zawiki, Release v0.11-30-g7307413
• pdftk
• Pantuml Wiki and Official
• Graphviz
• Wavedrom Wiki and Official
• Latex Wiki
9.2 Internet
• Madsonic Wiki and Official
• X11VNC Wiki
• qBitTorrent Wiki
9.2. Internet 92 Zawiki, Release v0.11-30-g7307413
9.3 Commandline
• Yakuake
• Total Terminal
• Cmder • nmap Wiki
9.4 Management
• Total Commander
• Krusader
• DCommander
• Hyperdock
9.3. Commandline 93 Zawiki, Release v0.11-30-g7307413
• iStat Menu
• Virtualbox Wiki
• Keepass
9.5 Programming
• Sublime Text Wiki
• Sublime Merge
• git Wiki
• Anaconda Wiki
• Jupyterlab Wiki
9.5. Programming 94 Zawiki, Release v0.11-30-g7307413
• Sphinx Wiki
• Pandoc Wiki
• Mentor HDL Designer
• Mentor Modelsim
• Xilinx ISE
• Intel Quartus
• Intellij IDEA Wiki
• Intellij PyCharm
9.5. Programming 95 Zawiki, Release v0.11-30-g7307413
• SpinalHDL Wiki
9.5. Programming 96 Chapter 10
Git
10.1 Git Commands
• Start a working area • Work on the current change • Examine the history and state • Grow, mark and tweak your common history • Collaborate
10.1.1 Start a working area
Command Description clone Clone a repository into a new directory init Create an empty Git repository or reinitialize an existing one
97 Zawiki, Release v0.11-30-g7307413
Figure1: Git Cheatsheet
10.1. Git Commands 98 Zawiki, Release v0.11-30-g7307413
10.1.2 Work on the current change
Command Description add Add file contents to the index mv Move or rename a file, a directory, or a symlink reset Reset current HEAD to the specified state rm Remove files from the working tree and from the index
10.1.3 Examine the history and state
Command Description log Show commit logs show Show various types of objects status Show the working tree status
10.1.4 Grow, mark and tweak your common history
Command Description branch List, create, or delete branches checkout Switch branches or restore working tree files commit Record changes to the repository diff Show changes between commits, commit and working tree, etc merge Join two or more development histories together rebase Reapply commits on top of another base tip tag Create, list, delete or verify a tag object signed with GPG
10.1.5 Collaborate
Command Description fetch Download objects and refs from another repository pull Fetch from and integrate with another repository or a local branch push Update remote refs along with associated objects
10.2 Git Flow
• Branches
10.2. Git Flow 99 Zawiki, Release v0.11-30-g7307413
10.2.1 Branches
• master - protected branch - Production releases • develop - protected branch - main developement merge of all feature branches • feature/* - for each feature a separate feature branch is created fork from develop • release - preparing development branch for release on master branch, mainly for bugfixes • hotfix - quick and dirty hotfix directly into develop and master branch
Figure2: Git Flow
10.3 Git General
• Links • Global setup – Check setup – Save Credentials
10.3. Git General 100 Zawiki, Release v0.11-30-g7307413
– Not verify https Certificates – Set commandline colors – Set commandline editor • Git Repo Creation / Cloning – Create new repo – Status of repo – Settings of repo – Clone existing repo – Revert to last commit state – Existing folder – Switch to new Remote – Get Remote Information – Change Push Remote URL • Git Repo information • Add Files • Checkout • Push • Branch – Merge
Figure3: Git Tansport
10.3. Git General 101 Zawiki, Release v0.11-30-g7307413
10.3.1 Links
• Bitbucket • Github • Gitlab • Official Git Webpage • Tutorial Git Branching
10.3.2 Global setup git config --global user.name "username" git config --global user.email "[email protected]"
Check setup git config --list
Save Credentials git config credential.helper store
Not verify https Certificates git config --global http.sslVerify false
Set commandline colors git config color.status.added "green bold" git config color.status.changed "yellow bold" git config color.status.untracked "red bold"
Set commandline editor git config --global core.editor "nano -w"
10.3. Git General 102 Zawiki, Release v0.11-30-g7307413
10.3.3 Git Repo Creation / Cloning
Create new repo git init
Status of repo git status
Settings of repo git remote -v
Clone existing repo git clone [email protected]:course/ElN/eln_labs.git cd eln_labs touch README.md git add README.md git commit -m "add README" git push -u origin master
Revert to last commit state go back to last committed servers state (can’t be undone) git reset --hard
Existing folder cd existing_folder git init git remote add origin [email protected]:course/ElN/eln_labs.git git add . git commit -m "Initial commit" git push -u origin master
Switch to new Remote cd existing_repo git remote rename origin old-origin git remote add origin [email protected]:course/ElN/eln_labs.git git push -u origin --all git push -u origin --tags
10.3. Git General 103 Zawiki, Release v0.11-30-g7307413
Get Remote Information git remote show origin
Change Push Remote URL git remote set-url --push
10.3.4 Git Repo information
# Status about current files ion folder git status
# Status about last commits git log --oneline
10.3.5 Add Files
# Stage a File git add README.md
# Commit file git commit –m "Initial commit, add README file"
10.3.6 Checkout
# Checkout certain commit git checkout e006db0 -b inspectingPrev
# Checkout given branch git chekout master
10.3.7 Push git push origin master
10.3.8 Branch
# Create new branch git branch dev_branch_1
# List all existing branches git branch
# Checkout certain branch git branch dev_branch_1
(continues on next page)
10.3. Git General 104 Zawiki, Release v0.11-30-g7307413
(continued from previous page) # Delete certain branch git branch -d dev_branch_1
Merge
# Checkout branch you want to merge into git checkout master # Merge the two branches git merge dev_branch_1
10.4 Github
• Advanced Search – General – Files – Date Time – Language – Repo Options
10.4.1 Advanced Search
General user:
Files filename:
10.4. Github 105 Zawiki, Release v0.11-30-g7307413
Date Time created:>2019-12-01 created:2019-12-01
Language
Languages start with a big letter C, Python, Perl, C++, Tcl, TeX lang:
Repo Options stars:0..100 stars:200 stars:>200 forks:0..100 forks:200 forks:>200 size:
10.5 .gitignore
Get useful gitignore at gitignore.io Gitignore entries
*.bak # all files with a given ending DS_Store # specific files ._* # all ._ files build/ # folder build/out # subfolder build/* # all files in folder build/out/* # all files in subfolder
!build/file.txt # except the given file
**/Entity/*~ # some subfolder name
10.5. .gitignore 106 Zawiki, Release v0.11-30-g7307413
10.6 Git Submodules
• Clone Repo with submodules • Pull changes – Pull all changes in the repo including changes in the submodules – Pull all changes for the submodules • Add submodule and define the master branch as the one you want totrack • Move Submodule
10.6.1 Clone Repo with submodules git clone --recursive [URL to Git repo]
10.6.2 Pull changes
Pull all changes in the repo including changes in the submodules git pull --recurse-submodules
Pull all changes for the submodules git submodule update --remote
10.6.3 Add submodule and define the master branch as the oneyou want to track git submodule add -b master [URL to Git repo] git submodule init
10.6.4 Move Submodule git mv a b
10.6. Git Submodules 107 Chapter 11
Anaconda
11.1 Additional Install
After installing anaconda other things have to be installed
11.1.1 Jupyter
See the dedicated jupyter pages for more informations: Jupyter
11.1.2 Sphinx pip install -I sphinx==2.3.1 pip install sphinx-rtd-theme pip install sphinxcontrib-wavedrom pip install sphinxcontrib-plantuml pip install recommonmark pip install sphinxemoji pip install sphinx-copybutton
108 Zawiki, Release v0.11-30-g7307413
11.2 Introduction
Anaconda is a complete python package with comes with many features: • Jupyter • PIP • Environments • Support Win / Linux / Mac • Anaconda Download • Conda Docs
11.2.1 Anaconda / Conda Update
# Update all Conda packages conda update --all
# Update Anaconda only conda update conda conda update anaconda
11.2.2 Config File
Create Config file jupyter notebook --generate-config
The Config file is located at: ~/.jupyter/jupyter_notebook_config.json
11.2.3 Change Password jupyter notebook password
11.2.4 Jupyter
See the dedicated jupyter pages for more informations: Jupyter
11.2. Introduction 109 Chapter 12
Jupyter
12.1 Common Functions
• Common Jupyterlab and Nodejs functions – install nvm – Install nodejs via conda – update npm – Rebuild Jupyterlab – Remove nodejs and npm • Auto import of Libraries • Check
110 Zawiki, Release v0.11-30-g7307413
12.1.1 Common Jupyterlab and Nodejs functions
install nvm
https://github.com/creationix/nvm curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | zsh ### Install latest nodejs nvm install node # "node" is an alias for the latest version
Install nodejs via conda
conda install -c conda-forge nodejs
update npm
sudo npm install -g npm
Rebuild Jupyterlab
jupyter lab build
Remove nodejs and npm
conda remove nodejs npm
12.1.2 Auto import of Libraries
• Navigate to ~/.ipython/profile_default • Create a folder called startup if it’s not already there • Add a new Python file called start.py • Put your favorite imports in this file • Launch IPython or a Jupyter Notebook and your favorite libraries will be automati- cally loaded every time! Example start.py
1 import pandas as pd 2 import numpy as np
3
4 # Pandas options 5 pd.options.display.max_columns = 30 6 pd.options.display.max_rows = 20
7
8 from IPython import get_ipython 9 ipython = get_ipython()
10
11 # If in ipython, load autoreload extension 12 if 'ipython' in globals(): (continues on next page)
12.1. Common Functions 111 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
13 print('\nWelcome to IPython!') 14 ipython.magic('load_ext autoreload') 15 ipython.magic('autoreload 2')
16
17 # Display all cell outputs in notebook 18 from IPython.core.interactiveshell import InteractiveShell 19 InteractiveShell.ast_node_interactivity = 'all'
20
21 # Visualization 22 import plotly.plotly as py 23 import plotly.graph_objs as go 24 from plotly.offline import iplot, init_notebook_mode 25 init_notebook_mode(connected=True) 26 import cufflinks as cf 27 cf.go_offline(connected=True) 28 cf.set_config_file(theme='pearl')
29
30 print('Your favorite libraries have been loaded.')
12.1.3 Check
Confirm that Libraries are loaded with
globals()
12.2 Extensions
• Installed extensions
12.2.1 Installed extensions
jupyter labextension list
12.3 General
• Extentions • Kernels • Troubleshoot • nbconvert – Convert to python for linting – Convert to html – Convert to pdf
12.2. Extensions 112 Zawiki, Release v0.11-30-g7307413
12.3.1 Extentions
jupyter labextension list
jupyter labextension install
For Matplotlib see: https://github.com/matplotlib/jupyter-matplotlib See all Jupyterlab Extensions: https://www.npmjs.com/search?q=keywords: jupyterlab-extension
12.3.2 Kernels
Inspect available Kernels
jupyter kernelspec list
12.3.3 Troubleshoot
jupyter troubleshoot
12.3.4 nbconvert
Converts jupyter notebook to other formats
jupyter nbconvert --to
formats are: • --to html - HTML – --template full (default) – --template basic • --to latex - LaTeX – --template article (default) – --template report – --template basic • --to pdf - PDF – --template article (default) – --template report – --template basic • --to sildes - Reveal.js HTML slideshow • --to markdown - Markdown • --to rst - reStructuredText • --to script - executable script (.py) • --to notebook -
12.3. General 113 Zawiki, Release v0.11-30-g7307413
Convert to python for linting jupyter nbconvert --to script test.ipynb
Convert to html jupyter nbconvert --to html test.ipynb
Convert to pdf needs Latex installed see: LaTeX jupyter nbconvert --to latex test.ipynb
12.4 Plotly Dash
• Install Plotly Dash – Checking Versions – Getting help – Jupyter integration install – To rebuild the package and the JupyterLab app – Additional Packages – Install Dash DAQ
12.4.1 Install Plotly Dash
# The core dash backend pip install dash==0.43.0 # DAQ components (newly open-sourced!) pip install dash-daq==0.1.0
Checking Versions import dash_core_components print(dash_core_components.__version__)
12.4. Plotly Dash 114 Zawiki, Release v0.11-30-g7307413
Getting help help(dcc.Dropdown)
Jupyter integration install git clone https://github.com/plotly/jupyterlab-dash cd jupyterlab-dash npm install npm run build jupyter labextension link . ~/anaconda3/bin/./python -m pip install -e .
To rebuild the package and the JupyterLab app npm run build jupyter lab build
Additional Packages pip install aiohttp pip install django_plotly_dash pip install jupyter_plotly_dash
Install Dash DAQ pip install dash_daq
12.5 Installation
• My Extension list – IDE Features – All in one install – Add install R to jupyter – Add install pandoc and inkscape to conda • Install Python Additional Stuff – Graphviz – Install python Libraries • Problems – Anaconda Navigator not starting • Install Plotly and Plotly Express
12.5. Installation 115 Zawiki, Release v0.11-30-g7307413
• Better PDF Export • Enable HTTPS
see also jupyter config
12.5.1 My Extension list
1 jupyter labextension install @jupyter-widgets/jupyterlab-manager 2 jupyter labextension install @jupyterlab/statusbar-extension 3 jupyter labextension install @jupyterlab/plotly-extension 4 jupyter labextension install @jupyterlab/toc 5 jupyter labextension install @deathbeds/jupyterlab_graphviz 6 jupyter labextension install @ryantam626/jupyterlab_sublime 7 jupyter labextension install jupyter-matplotlib 8 jupyter labextension install @mflevine/jupyterlab_html 9 jupyter labextension install jupyterlab-drawio 10 jupyter labextension install jupyterlab-flake8 11 jupyter labextension install jupyterlab_hidecode 12 jupyter labextension install @lckr/jupyterlab_variableinspector 13 jupyter labextension install @jupyter-widgets/jupyterlab-manager
One Liner
IDE Features
nbdev adds jupyter with the follwoing features: • a variable explorer, a list of breakpoints and a source preview • the possibility to navigate the call stack (next line, step in, step out etc.) • the ability to set breakpoints intuitively, next to the line of interest • flags to indicate where the current execution has stopped
1 pip install nbdev 2 conda install xeus-python -c conda-forge 3 pip install jupyter_server 4 jupyter labextension install @jupyterlab/debugger
All in one install
1 jupyter labextension install @jupyter-widgets/jupyterlab-manager @jupyterlab/ ,→statusbar-extension @jupyterlab/plotly-extension @jupyterlab/toc @deathbeds/ ,→jupyterlab_graphviz @ryantam626/jupyterlab_sublime jupyter-matplotlib @mflevine/ ,→jupyterlab_html jupyterlab-drawio jupyterlab-flake8 jupyterlab_hidecode @lckr/ ,→jupyterlab_variableinspector @jupyter-widgets/jupyterlab-manager
12.5. Installation 116 Zawiki, Release v0.11-30-g7307413
Add install R to jupyter
conda install -c r r-essentials
Add install pandoc and inkscape to conda
1 conda install -c conda-forge pandoc 2 conda install -c conda-forge inkscape
12.5.2 Install Python Additional Stuff
Graphviz
Install Graphviz from https://graphviz.gitlab.io/download/ put Graphviz/bin in your PATH
pip install graphviz
Install python Libraries
1 pip install pixiedust 2 pip install SchemDraw 3 pip install nbwavedrom 4 pip install flake8 5 pip install pyflakes 6 pip install nbconvert 7 pip install watermark 8 pip install sty
oneline
pip install pixiedust SchemDraw nbwavedrom flake8 pyflakes nbconvert graphviz␣ ,→watermark
12.5.3 Problems
Anaconda Navigator not starting
When starting anaconda-navigator produces the follwowing error.
1 $ anaconda-navigator.exe 2 Traceback (most recent call last): 3 File "c:\Users\silvan.zahno\AppData\Local\Continuum\anaconda3\lib\site-packages\ ,→qtpy\__init__.py", line 202, in
6
7 During handling of the above exception, another exception occurred:
8
9 Traceback (most recent call last): 10 File "c:\Users\silvan.zahno\AppData\Local\Continuum\anaconda3\Scripts\anaconda- ,→navigator-script.py", line 6, in
12.5. Installation 117 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
12 File "c:\Users\silvan.zahno\AppData\Local\Continuum\anaconda3\lib\site-packages\ ,→anaconda_navigator\app\main.py", line 22, in
1 pip uninstall PyQt5 2 conda update conda 3 conda update anaconda-navigator 4 anaconda-navigator.exe
12.5.4 Install Plotly and Plotly Express
conda install -c plotly plotly_express plotly-orca
12.5.5 Better PDF Export
1 sudo apt-get install texlive-xetex 2 pip install jupyter_contrib_nbextensions 3 pip install cite2c
12.5.6 Enable HTTPS
See: https://juno.sh/ssl-self-signed-cert/
#!/bin/bash # Create Directory Structure mkdir ca ca/certs ca/crl ca/newcerts ca/private chmod 700 ca/private touch ca/index.txt echo 1000 > ca/serial
# Generate CA root key openssl genrsa -aes256 -out ca/private/ca.key.pem 4096 chmod 400 ca/private/ca.key.pem
# Use the root key (ca.key.pem) to create a root certificate (ca.cert.pem) openssl req -config openssl.cnf -key ca/private/ca.key.pem -new -x509 -days 7300 - ,→sha256 -extensions v3_ca -out ca/certs/ca.cert.pem chmod 444 ca/certs/ca.cert.pem
# Generate SSL certificate mkdir jupyter jupyter/csr jupyter/certs jupyter/private chmod 700 jupyter/private openssl genrsa -out jupyter/private/ssl.key.pem 2048 chmod 400 jupyter/private/ssl.key.pem
# Request certificate for your server openssl req -config openssl.cnf -key jupyter/private/ssl.key.pem -new -sha256 -out␣ ,→jupyter/csr/ssl.csr.pem (continues on next page)
12.5. Installation 118 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
# Finally, issue your server SSL certificate openssl ca -config openssl.cnf -extensions server_cert -days 2048 -notext -md␣ ,→sha256 -in jupyter/csr/ssl.csr.pem -out jupyter/certs/ssl.cert.pem chmod 444 jupyter/certs/ssl.cert.pem
Install the CA certificate on your device, located at ca/certs/ca.cert.pem As of iOS 10.3 you must manually turn on trust for SSL when you install a certificate. In order to turn on SSL trust for CA certificate, go to Settings > General > About > Certificate Trust Settings. Under Enable full trust for root certificates, turn on trust for the certificate. Once CA certificate is trusted on the device, all certificates signed with it will betrusted too, including the one we generated for SSL, located at jupyter/certs/ssl.cert.pem. You can now use it when launching Jupyter Notebook by providing absolute paths to both key and certificate. If you generate all your certificate and keysin ~/.ssh/ folder, your paths will be:
jupyter notebook --certfile ~/.ssh/jupyter/certs/ssl.cert.pem --keyfile ~/.ssh/ ,→jupyter/private/ssl.key.pem
Alternatively, you can specify paths to key and certificate in Jupyter configuration file.
12.5. Installation 119 Chapter 13
Pandoc
13.1 Pandoc
• Additional Arguments – Highlight Styles – PDF Output ∗ For my template needed packages – Template ∗ Windows ∗ Linux
If you need to convert files from one markup format into another, pandoc is your swiss- army knife. • Pandoc Online • Pandoc Download
120 Zawiki, Release v0.11-30-g7307413
13.1.1 Additional Arguments
Highlight Styles
# List all Highlight Styles pandoc --list-highlight-styles pygments tango espresso zenburn kate monochrome breezedark haddock
## Pandoc Argument --highlight-style breezedark
PDF Output
--pdf-engine=xelatex
For my template needed packages
• cm-super – Error no Scalable font • koma-script – ! LaTeX Error: File scrartcl.cls not found.
Template
Latex Template needs to be in the following folders
Windows
C:\\Users\\
Linux
~/.pandoc/templates/
--template=.latex
13.1. Pandoc 121 Chapter 14
Sphinx Documentation
14.1 Introduction
Python has a build in Documentation system called DocString. Sphinx is building on top of that, to automatically create a documentation of your python code. You can then later create different output file formats of your documentation. Addintionally a Sphinx docu- mentation source can also be a plain .rst or .md filesystem. This page and subpages are only a small CheatSheet references for installing, writing and building SPHINX documentation.
14.1.1 Installation
Linux
14.1.2 Check installation which sphinx-quickstart
14.1.3 Configuration see zawiki conf.py
122 Zawiki, Release v0.11-30-g7307413
14.2 Syntax
This is a small cheat sheet with the most used syntax either ReST or SPHINX especially for within python files. For more information see also: • RST and Sphinx Cheatsheet • Python Docstrings
14.2.1 Module Documentation
.. moduleauthor:: Autor ([email protected])
Description of the module.
Reference to modules It is the :mod:`TestClass.TestClass`
Reference to class It is the :class:`TestClass.TestClass`
Reference to function It is the :func:`TestClass.TestClass`
Include usage examples for the module. With or without linenumbers
*Example:*
.. literalinclude:: ../examples/example_1.py :linenos:
.. literalinclude:: ../examples/example_2.py
This afterwards is some code block::
import TestClass
"""
14.2.2 Class Documentation class TestClass: """ Test class description, needs an empty line afterwards
:param arg1: first argument description :type arg1: unknown :param int arg2: second aargument description including type :param str arg3: third argument description including type :param arg4: fourth argument description :type arg4: 2 dimensional list of int """ def __init__(self, arg1=None, arg2=1, arg3="str", arg4=[[1,2]]): # Constructor stuff #...
14.2. Syntax 123 Zawiki, Release v0.11-30-g7307413
14.2.3 Function Documentation def exampleFunction(self, arg1, arg2): """ example Function description, needs an empty line afterwards
:param arg1: first argument description :type arg1: longer type description :param string arg2: second argument description including type
:raises: TypeError
:return: True or False, depending if found or not :rtype: bool
*Example:*
.. literalinclude:: ../examples/functionexample.py """
14.2.4 References
Modules
:mod:`matplotlib.backend_bases`
Classes
:class:`~matplotlib.backend_bases.LocationEvent`
Methods
:meth:`~matplotlib.backend_bases.FigureCanvasBase.mpl_connect`
14.2. Syntax 124 Chapter 15
SublimeText
15.1 Introduction
• Useful Links • Console • Settings
125 Zawiki, Release v0.11-30-g7307413
15.1.1 Useful Links
• Shortcut Cheatsheet • My Settings Backup
15.1.2 Console
If you have problem figuring out what shortcut command is active, Then open the console Ctrl + Alt + c or and type the following command. Then your will see all executed commands in the console. sublime.log_commands(True)
15.1.3 Settings
My sublimetext settings can be found in the Config Repo my settings backup. • SublimeText Settings Wiki
15.2 Packages
• Usage • Useful packages – Alignment
Packages are the plugins or extensions from SublimeText. On the webpage https:// packagecontrol.io/ all available packages can be seen.
15.2.1 Usage
Ctrl + Shift + p • Package Control: Install • Package Control: Remove • Package Control: Add Repository • Package Control: List Packages
15.2. Packages 126 Zawiki, Release v0.11-30-g7307413
15.2.2 Useful packages
• AlignTab • AutoHotkey • Gist • Jedi - Python Autocompletion • LaTeXTools • Markdown Extended • MarkdownEditing • MarkdownLivePreview • MarkdownPreview • MarkdownTOC • Markmon • Origami • Pandoc • PlainTasks • RestructuredText Improved • Smart VHDL • sublimetext_moonburst • Text Pastry • SublimeLinter-flake8 • PackageResourceViewer • Alignment • Kite
Alignment
Listing 1: alignemnt settings { // The mid-line characters to align in a multi-line selection, changing // this to an empty array will disable mid-line alignment "alignment_chars": [ "^", "|", ":", ":=", "<=", "=>" ] }
Ctrl + Alt + a
15.2. Packages 127 Zawiki, Release v0.11-30-g7307413
15.3 Settings
• Preferences Settings • Preferences Key Bindings • Custom Plugin Run Multiple commands
• Config Repo M< Settings Backup.
15.3.1 Preferences Settings
Listing 2: Preferences.sublime-settings
1 { 2 "always_show_minimap_viewport": true, 3 "bold_folder_labels": true, 4 "caret_style": "blink", 5 "close_windows_when_empty": false, 6 "color_scheme": "Packages/sublimetext_moonburst/moonburst.tmTheme", 7 "draw_minimap_border": true, 8 "draw_white_space": "all", 9 "fade_fold_buttons": false, 10 "font_face": "Operator Mono Book", 11 "font_size": 15, 12 "highlight_line": true, 13 "highlight_modified_tabs": true, 14 "ignore_vcs_packages": true, 15 "ignored_packages": 16 [ 17 "Markdown", 18 "RestructuredText", 19 "Vintage" 20 ], 21 "indent_guide_options": 22 [ 23 "draw_normal", 24 "draw_active" 25 ], 26 "line_numbers": true, 27 "overlay_scroll_bars": "enabled", 28 "rulers": 29 [ 30 80, 31 160 32 ], 33 "scroll_past_end": true, 34 "show_encoding": true, 35 "show_line_endings": true, 36 "show_tab_close_buttons": true, 37 "tab_size": 4, 38 "theme": "Adaptive.sublime-theme", 39 "translate_tabs_to_spaces": true, 40 "trim_automatic_white_space": true, 41 "trim_trailing_white_space_on_save": true, 42 "word_wrap": true 43 }
15.3. Settings 128 Zawiki, Release v0.11-30-g7307413
15.3.2 Preferences Key Bindings
Listing 3: Default (Windows).sublime-keymap
1 [ 2 { "keys": ["alt+up"], "command": "select_lines", "args": {"forward": false} }, 3 { "keys": ["alt+down"], "command": "select_lines", "args": {"forward": true} },
4
5 { "keys": ["ctrl+alt+c"], "command": "show_panel", "args": {"panel": "console", ,→ "toggle": true} }, 6 { "keys": ["ctrl+alt+m"], "command": "toggle_menu" }, 7 { "keys": ["ctrl+alt+t"], "command": "toggle_tabs" },
8
9 { "keys": ["ctrl+tab"], "command": "next_view" }, 10 { "keys": ["ctrl+shift+tab"], "command": "prev_view" },
11
12 { "keys": ["ctrl+alt+q"], "command": "alignment" },
13
14 // Change view split to left in a 2 Column mode 15 { 16 "keys": ["super+alt+right"], 17 "command": "run_multiple", 18 "args": 19 { 20 "commands": [ 21 { 22 "command": "set_layout", 23 "args": 24 { 25 "cols": [0.0, 0.90, 1.0], 26 "rows": [0.0, 1.0], 27 "cells": [[0, 0, 1, 1], [1, 0, 2, 1]] 28 }, 29 "context": "window" 30 }, 31 { 32 "command": "focus_group", 33 "args": { "group": 0 }, 34 "context": "window" 35 } 36 ] 37 } 38 }, 39 // Change view split to right in a 2 Column mode 40 { 41 "keys": ["super+alt+left"], 42 "command": "run_multiple", 43 "args": 44 { 45 "commands": [ 46 { 47 "command": "set_layout", 48 "args": 49 { 50 "cols": [0.0, 0.10, 1.0], 51 "rows": [0.0, 1.0], 52 "cells": [[0, 0, 1, 1], [1, 0, 2, 1]] 53 }, 54 "context": "window" 55 }, 56 { 57 "command": "focus_group", (continues on next page)
15.3. Settings 129 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
58 "args": { "group": 1 }, 59 "context": "window" 60 } 61 ] 62 } 63 }, 64 // Change view split to the middle in a 2 Column mode 65 { 66 "keys": ["super+alt+up"], 67 "command": "run_multiple", 68 "args": 69 { 70 "commands": [ 71 { 72 "command": "set_layout", 73 "args": 74 { 75 "cols": [0.0, 0.50, 1.0], 76 "rows": [0.0, 1.0], 77 "cells": [[0, 0, 1, 1], [1, 0, 2, 1]] 78 }, 79 "context": "window" 80 }, 81 { 82 "command": "focus_group", 83 "args": { "group": 1 }, 84 "context": "window" 85 } 86 ] 87 } 88 }, 89 ]
15.3.3 Custom Plugin Run Multiple commands
• Goto Tool -> Developer -> New Plugin • Create a new plugin called run_multiple
Listing 4: run_multiple.py
1 import sublime, sublime_plugin
2
3 # Takes an array of commands (same as those you'd provide to a key binding) with 4 # an optional context (defaults to view commands) & runs each command in order. 5 # Valid contexts are 'text', 'window', and 'app' for running a TextCommand, 6 # WindowCommands, or ApplicationCommand respectively.
7
8 class RunMultipleCommand(sublime_plugin.TextCommand): 9 def exec_command(self, command): 10 if not 'command' in command: 11 raise Exception('No command name provided.')
12
13 args = None 14 if 'args' in command: 15 args = command['args']
16
17 # default context is the view since it's easiest to get the other contexts 18 # from the view (continues on next page)
15.3. Settings 130 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
19 context = self.view 20 if 'context' in command: 21 context_name = command['context'] 22 if context_name == 'window': 23 context = context.window() 24 elif context_name == 'app': 25 context = sublime 26 elif context_name == 'text': 27 pass 28 else: 29 raise Exception('Invalid command context "'+context_name+'".')
30
31 # skip args if not needed 32 if args is None: 33 context.run_command(command['command']) 34 else: 35 context.run_command(command['command'], args)
36
37 def run(self, edit, commands = None): 38 if commands is None: 39 return # not an error
40
41 for command in commands: 42 self.exec_command(command)
15.3. Settings 131 Chapter 16
VirtualBox
16.1 Introduction
• Links • Useful Commands – Change UUID of a VirtualDisk – Clone VirtualDisk – Shrink dynamic image – Resize VirtualDisk
Oracle VM VirtualBox is an x86 virtualization software package. VirtualBox is installed on an existing host operating system as an application; this host application allows addi- tional guest operating systems, each known as a Guest OS, to be loaded and run, each with its own virtual environment. Supported host operating systems include Linux, Mac OS X, Windows XP, Windows Vista, Windows 7, Solaris, and OpenSolaris; there is also a
132 Zawiki, Release v0.11-30-g7307413 port to FreeBSD. Supported guest operating systems include versions and derivations of Windows, Linux, BSD, OS/2, Solaris and others.
16.1.1 Links
• Virtualbox Official Webpage
16.1.2 Useful Commands
Change UUID of a VirtualDisk
VBoxManage internalcommands sethduuid copiedfile.vdi
Clone VirtualDisk
VBoxManage clonevdi /path/to/existing.vdi new.vdi
Shrink dynamic image
VBoxManage modifyvdi vm_hd.vdi compact
Resize VirtualDisk
After resizing the harddisk file it, the partition needs to be resized to in gparted forLinux of Disk Management in Windows
VBoxManage modifyhd YOUR_HARD_DISK.vdi --resize SIZE_IN_MB VBoxManage modifyhd pentaho_vm.vdi --resize 40000 # resize to 40GB
16.1. Introduction 133 Chapter 17
Bittorrent
17.1 Introduction
BitTorrent (abbreviated to BT) is a communication protocol for peer-to-peer file sharing (P2P) which is used to distribute data and electronic files over the Internet. The downlaod can be of any size and can be started and restarted as wanted. A checksum verifies the data after the finished download. Per default all clients who downloads a file become automatic Seeders (means uploaders). Be aware of its implications.
17.1.1 Bittorrent clients
There are many Bittorrent clients out there. The most common in my case are
• uTorrent
• qBittorrent
134 Zawiki, Release v0.11-30-g7307413
I prefer uTorrent for downlaods only and qBittorrent for creating Bittorrent because it has an integrated Bittorrent Tracker.
17.1.2 Creating a Torrent
17.1.3 Enable Local Tracker
The local tracker lets find your Client by others but you have to enable it and forwardthe tracker port. In addition your also need to forward the listening port. By default in qBitTorrent these values are: • Listening Port: 8999 • Tracker Port: 9000
Figure2: qBitTorrent Embedded Figure1: Listening Port Settings Tracker Settings
Important: These two ports needs to be forwarded by your router, adjust the settings accordingly Verify these settings with the openport checker
17.1.4 Creating a Public Torrent
Public Torrents can be find by anyone and be downloaded by anyone. Depending onyour tracker selection they cn be find on popular torrent sites such as ThePirateBay.
Warning: Be careful what you offer to be downloaded.
Create a new Torrent file with the following settings. Add public trackers to your tracker list. To find the latest active public trackers goto tinytorrent.net You can also add your personal tracker if you like.
17.1. Introduction 135 Zawiki, Release v0.11-30-g7307413
17.1. Introduction 136 Zawiki, Release v0.11-30-g7307413
17.1.5 Creating a Private Torrent
Hereafter a semi-private torrent is created. Which means only people having the torrent file can download the file. But it is not per-se private. You have to create the sameTorrent file except add only your own tracker to the tracker list. To find your external ip address goto: https://www.ip-adress.com/ http://your.external.url:9000/announce http://external-ip-address:9000/announce http://localhost:9000/announce
17.1. Introduction 137 Chapter 18
AutoHotKey AHK
18.1 Introduction
• My Scripts • Links
AutoHotkey is a free, open source macro-creation and automation software utility which allows users to automate repetitive tasks. Any application user interface can be modified by AutoHotkey. It is driven by a custom scripting language called AHK that is aimed specifically at providing keyboard shortcuts or hotkeys.
18.1.1 My Scripts
My ahk scripts can be found in the config repo
18.1.2 Links
• AHK Official Webpage • AHK Tutorial
138 Zawiki, Release v0.11-30-g7307413
18.2 Key Definitions
• Raw Keys • Double Keypress Detection
18.2.1 Raw Keys
^ ; Ctrl # ; Win <# ; Left Win ># ; Right Win ! ; Alt >! ; Right Altt + ; Right Shift <+ ; Left Shift ^ ; Control <^ ; Left Control >^ ; Right Control ; Multimedia {Volume_Up} {Volume_Down} {Volume_Mute}
18.2.2 Double Keypress Detection
Alt Key in the example
~Alt:: DoubleAlt := A_PriorHotkey ="~Alt" AND A_TimeSincePriorHotkey < 400 Sleep 0 KeyWait Alt ; This prevents the keyboard's auto-repeat feature from interfering. return
18.3 Tips & Tricks
• Comment • Performance and Compatility • Warnings • Enable Regex for Title mach Mode • Tray Icon and ToolTip • Examples – For Win10 Hibernate – For Win10 Sleep
18.2. Key Definitions 139 Zawiki, Release v0.11-30-g7307413
– Home and End Hotkey • Check for AHK Version and output message • Supend a script via Hotkey
My ahk scripts cna be found in the config repo
18.3.1 Comment
;------;-- Comment ;--
18.3.2 Performance and Compatility
; Recommended for performance and compatibility with future AutoHotkey releases #NoEnv
18.3.3 Warnings
; Enable warnings to assist with detecting common errors #Warn
18.3.4 Enable Regex for Title mach Mode
SetTitleMatchMode,RegEx ; then IfWinExist, Total Commander.*
18.3.5 Tray Icon and ToolTip
Menu, TRAY, Icon, Favicon.ico Menu, TRAY, Tip, Tooltip Text
18.3.6 Examples
For Win10 Hibernate
; Wait for Hotkey ; Ctrl + Win + Alt + l ; Send Hotkey ; Ctrl + Win + x + u + s ^#
18.3. Tips & Tricks 140 Zawiki, Release v0.11-30-g7307413
For Win10 Sleep
; Wait for Hotkey ; Ctrl + Win + l ; Send Hotkey ; Win + x + u + s ^#l::Send #xus
Home and End Hotkey
; Ctrl + Left ^Left::Send {Home} ; Ctrl + Right ^Right::Send {End}
18.3.7 Check for AHK Version and output message
If (A_AhkVersion < "1.0.39.00") { MsgBox,20,,This script may not work properly with your version of AutoHotkey.␣ ,→Continue? IfMsgBox,No ExitApp }
18.3.8 Supend a script via Hotkey f1::suspend
18.3. Tips & Tricks 141 Chapter 19
Python
19.1 Docstring
• Python begin file • Variables • Functions – Function with types – Function with pep484 type annotations – Function modules level – Function - other examples • Class
19.1.1 Python begin file
#!/usr/bin/python3 # -*- coding: utf-8 -*-
"""Example NumPy style docstrings.
This module demonstrates documentation as specified by the `NumPy Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections are created with a section header followed by an underline of equal length. (continues on next page)
142 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
Example ------Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks::
$ python example_numpy.py
Section breaks are created with two blank lines. Section breaks are also implicitly created anytime a new section starts. Section bodies *may* be indented:
Notes ----- This is an example of an indented section. It's like any other section, but the body is indented to help it stand out from surrounding text.
If a section is indented, then a section break is created by resuming unindented text.
Attributes ------module_level_variable1 : int Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an inline docstring immediately following the variable.
Either form is acceptable, but the two should not be mixed. Choose one convention to document module level variables and be consistent with it.
.. _NumPy Documentation HOWTO: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
"""
19.1.2 Variables module_level_variable1 = 12345 module_level_variable2 = 98765 """int: Module level variable documented inline.
The docstring may span multiple lines. The type may optionally be specified on the first line, separated by a colon. """
19.1. Docstring 143 Zawiki, Release v0.11-30-g7307413
19.1.3 Functions
Function with types def function_with_types_in_docstring(param1, param2): """Example function with types documented in the docstring.
`PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring:
Parameters ------param1 : int The first parameter. param2 : str The second parameter.
Returns ------bool True if successful, False otherwise.
.. _PEP 484: https://www.python.org/dev/peps/pep-0484/
"""
Function with pep484 type annotations def function_with_pep484_type_annotations(param1: int, param2: str) -> bool: """Example function with PEP 484 type annotations.
The return type must be duplicated in the docstring to comply with the NumPy docstring style.
Parameters ------param1 The first parameter. param2 The second parameter.
Returns ------bool True if successful, False otherwise.
"""
19.1. Docstring 144 Zawiki, Release v0.11-30-g7307413
Function modules level def module_level_function(param1, param2=None, *args, **kwargs): """This is an example of a module level function.
Function parameters should be documented in the ``Parameters`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not obvious.
If \*args or \*\*kwargs are accepted, they should be listed as ``*args`` and ``**kwargs``.
The format for a parameter is::
name : type description
The description may span multiple lines. Following lines should be indented to match the first line of the description. The ": type" is optional.
Multiple paragraphs are supported in parameter descriptions.
Parameters ------param1 : int The first parameter. param2 : :obj:`str`, optional The second parameter. *args Variable length argument list. **kwargs Arbitrary keyword arguments.
Returns ------bool True if successful, False otherwise.
The return type is not optional. The ``Returns`` section may span multiple lines and paragraphs. Following lines should be indented to match the first line of the description.
The ``Returns`` section supports any reStructuredText formatting, including literal blocks::
{ 'param1': param1, 'param2': param2 }
Raises ------AttributeError The ``Raises`` section is a list of all exceptions that are relevant to the interface. ValueError If `param2` is equal to `param1`.
""" if param1 == param2: (continues on next page)
19.1. Docstring 145 Zawiki, Release v0.11-30-g7307413
(continued from previous page) raise ValueError('param1 may not be equal to param2') return True
Function - other examples def example_generator(n): """Generators have a ``Yields`` section instead of a ``Returns`` section.
Parameters ------n : int The upper limit of the range to generate, from 0 to `n` - 1.
Yields ------int The next number in the range of 0 to `n` - 1.
Examples ------Examples should be written in doctest format, and should illustrate how to use the function.
>>> print([i for i in example_generator(4)]) [0, 1, 2, 3]
""" for i in range(n): yield i class ExampleError(Exception): """Exceptions are documented in the same way as classes.
The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself.
Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.
Note ---- Do not include the `self` parameter in the ``Parameters`` section.
Parameters ------msg : str Human readable string describing the exception. code : :obj:`int`, optional Numeric error code.
Attributes ------msg : str Human readable string describing the exception. code : int Numeric error code.
""" (continues on next page)
19.1. Docstring 146 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
def __init__(self, msg, code): self.msg = msg self.code = code
19.1.4 Class class ExampleClass(object): """The summary line for a class docstring should fit on one line.
If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below).
Properties created with the ``@property`` decorator should be documented in the property's getter method.
Attributes ------attr1 : str Description of `attr1`. attr2 : :obj:`int`, optional Description of `attr2`.
"""
def __init__(self, param1, param2, param3): """Example of docstring on the __init__ method.
The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself.
Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.
Note ---- Do not include the `self` parameter in the ``Parameters`` section.
Parameters ------param1 : str Description of `param1`. param2 : :obj:`list` of :obj:`str` Description of `param2`. Multiple lines are supported. param3 : :obj:`int`, optional Description of `param3`.
""" self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute
#: list of str: Doc comment *before* attribute, with type specified self.attr4 = ["attr4"]
self.attr5 = None (continues on next page)
19.1. Docstring 147 Zawiki, Release v0.11-30-g7307413
(continued from previous page) """str: Docstring *after* attribute, with type specified."""
@property def readonly_property(self): """str: Properties should be documented in their getter method.""" return "readonly_property"
@property def readwrite_property(self): """:obj:`list` of :obj:`str`: Properties with both a getter and setter should only be documented in their getter method.
If the setter method contains notable behavior, it should be mentioned here. """ return ["readwrite_property"]
@readwrite_property.setter def readwrite_property(self, value): value
def example_method(self, param1, param2): """Class methods are similar to regular functions.
Note ---- Do not include the `self` parameter in the ``Parameters`` section.
Parameters ------param1 The first parameter. param2 The second parameter.
Returns ------bool True if successful, False otherwise.
""" return True
def __special__(self): """By default special members with docstrings are not included.
Special members are any methods or attributes that start with and end with a double underscore. Any special member with a docstring will be included in the output, if ``napoleon_include_special_with_doc`` is set to True.
This behavior can be enabled by changing the following setting in Sphinx's conf.py::
napoleon_include_special_with_doc = True
""" pass
def __special_without_docstring__(self): pass (continues on next page)
19.1. Docstring 148 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
def _private(self): """By default private members are not included.
Private members are any methods or attributes that start with an underscore and are *not* special. By default they are not included in the output.
This behavior can be changed such that private members *are* included by changing the following setting in Sphinx's conf.py::
napoleon_include_private_with_doc = True
""" pass
def _private_without_docstring(self): pass
19.2 Examples
Python examples can be found in the https://github.com/tschinz/config// • https://github.com/tschinz/config/tree/master/scripts/python/ • https://github.com/tschinz/config/tree/master/scripts/python/codequality • https://github.com/tschinz/config/tree/master/scripts/python/fuzzy_search • https://github.com/tschinz/config/tree/master/scripts/python/smallstuff • https://github.com/tschinz/config/tree/master/scripts/python/xkcd
19.3 General
• flake8 – .flake8
Python samples
19.3.1 flake8 python -m flake8 test.py
19.2. Examples 149 Zawiki, Release v0.11-30-g7307413
.flake8
Flake8 configuration file is formated at ini File. and located at: • Linux - ~/.config/flake8 • Windows - %userprofile%\.flake8 see my config .flake8
[flake8] max-line-length = 200 ignore = #E501: Line too long E501
#E722 do not use bare 'except' E722
#W504 line break after binary operator (one has to disable one of the W503/W504␣ ,→pair) W504
#W391 blank line at end of file W391 exclude = .git, __pycache__, docs/source/conf.py, old, build, dist
19.4 Flake 8
• .flake8
Python samples python -m flake8 test.py
19.4.1 .flake8
Flake8 configuration file is formated at ini File. and located at: • Linux - ~/.config/flake8 • Windows - %userprofile%\.flake8 see my config .flake8
[flake8] max-line-length = 200 ignore = (continues on next page)
19.4. Flake 8 150 Zawiki, Release v0.11-30-g7307413
(continued from previous page) #E501: Line too long E501
#E722 do not use bare 'except' E722
#W504 line break after binary operator (one has to disable one of the W503/W504␣ ,→pair) W504
#W391 blank line at end of file W391 exclude = .git, __pycache__, docs/source/conf.py, old, build, dist
19.5 Some Methods
• Raw Input • Range • Convert • Dir • Print • String Methods – format – Len – Concatenation – find(sub[, start[, end]]) – strip([chars]) – lstrip([chars]), rstrip([chars]) – split([sep[, maxsplit]]) – partition(sep) – lower(), upper()
19.5. Some Methods 151 Zawiki, Release v0.11-30-g7307413
19.5.1 Raw Input
Wait for until the input is finished by pressing Enter.
Listing 1: raw_input() # raw_input(string) raw_input('Enter something:')
19.5.2 Range
Listing 2: range() # range(arg1, arg2, ...) range(1,5) # = [1, 2, 3, 4] range(1,5,2) # = [1, 3]
19.5.3 Convert
Listing 3: convert ## Convert int() float() complex() long()
19.5.4 Dir
Shows a list of names in the actual scope. Names can be functions, classes, variables of a module
Listing 4: dir() $ python >>> import sys >>> dir(sys) # List all attribute of the sys-modul ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions'] >>> dir() # List all attributes of the actual module ['__builtins__', '__doc__', '__name__', 'sys'] >>> >>> a = 5 # create new variable 'a' >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'sys'] (continues on next page)
19.5. Some Methods 152 Zawiki, Release v0.11-30-g7307413
(continued from previous page) >>> >>> del a # delete a name >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'sys'] >>>
19.5.5 Print
Listing 5: print() age = 25 name = 'tschinz' print '%s is %d Years old.' % (name, age) print 'Why plays %s with this Python?' % name
Overwrite last print output .. code-block:: python :caption: raw_input() import time for i in range(100): print("\rProgress {}%".format(i),end="") time.sleep(0.1)
19.5.6 String Methods format
Listing 6: format() "string {1} {1:03d} {2:04X} {2:08b}".format(42, 7) # output string 42 042 0007 00000111
Len
Listing 7: len() len("Hello World!") # returns 12
Concatenation
Listing 8: concatenation "Hello " + "World" # = "Hello World" "Hello " + "World" + 3*"!" # = "Hello World!!!" s = "Hello World" s[0] # = 'H' s[1] # = 'e' s[10] # = 'd' (continues on next page)
19.5. Some Methods 153 Zawiki, Release v0.11-30-g7307413
(continued from previous page) s[11] # = IndexError : we cannot read past the end of the string s[0:5] # = "Hello" s[6:11] # = "World" s[6:20] # = "World" (no IndexError although 20 is past the end of the string) s[10:6] # = "" (starting from a larger ending at a smaller index is always the␣ ,→empty string)
find(sub[, start[, end]])
Listing 9: find() "Hello world, hello".find("ell") # 1 "Hello world, hello".find("ell", 3,10) # -1 "Hello world, hello".find("ell", 3,20) # 14
strip([chars])
Listing 10: strip() " hello world ".strip() # 'hello world'
lstrip([chars]), rstrip([chars])
Listing 11: lstrip() rstrip() " \tHello there".lstrip() # 'Hello there' " \tHello there".lstrip("H") # ' \tHello there' " \tHello there".lstrip("\t H") # 'ello there' " \tHello there".rstrip() # 'Hello there' " \tHello there".rstrip("e") # ' \tHello ther' " \tHello there".rstrip("erh") # ' \tHello t'
split([sep[, maxsplit]])
Listing 12: split() "apples, peaches, oranges, bananas".split(', ', 2) # ['apples', 'peaches', 'oranges, bananas']
partition(sep)
Listing 13: partition() "Hello World".partition(" ") # ('Hello', ' ', 'World') "Hello World".partition(" Wo") # ('Hello', ' Wo', 'rld')
19.5. Some Methods 154 Zawiki, Release v0.11-30-g7307413 lower(), upper()
Listing 14: lower() upper() "Hello World!".lower() # 'hello world!' "Hello World!".upper() # 'HELLO WORLD!'
Listing 15: string name = 'abcdef' if name.startswith('abc'): print 'Yes, starts with "abc".' if 'a' in name: print 'Yes, contains "a".' if name.find('cde') != -1: print 'Yes, contains "cde".' separator = '_*_' mylist = ['Swiss', 'Germany', 'France', 'Italy'] print separator.join(mylist)
19.6 PIP
• Admin • Package • Create requirements.txt
19.6.1 Admin
# Show pip help pip --help
# Show installed pip version pip --version
# Update pip (Linux) pip install --upgrade pip
# Update pip (Windows) python -m pip install --upgrade pip
19.6.2 Package
# Search a package pip search
# See package version pip show
# See all installed packages pip list (continues on next page)
19.6. PIP 155 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
# Install pip install
# Uninstall pip uninstall
19.6.3 Create requirements.txt pip freeze > requirements.txt
19.7 PyQt4
• Links • Import PyQt4 module • Class • Signal Slot • Toolbar • Taskbar • Widgets • Progressbar • Layout • Statusbar • Center window
19.7.1 Links
• Riverbank PyQt4 Download • PyQt4 Reference Guide • PyQt4 Class Reference • PyQT4 CustomSerialProgramm CSP Example
19.7. PyQt4 156 Zawiki, Release v0.11-30-g7307413
19.7.2 Import PyQt4 module
Python tutorial can be found at: ZetCode Tutorial
Listing 16: import import PyQt4 from PyQt4 import QtGui, Qt from PyQt4 import QtCore
19.7.3 Class
Define the class to generate a Window
Listing 17: class windowsize = (700,600) class MainUI(QtGui.QMainWindow):
def __init__(self, win_parent = None): # Init the base class QtGui.QMainWindow.__init__(self, win_parent) self.init_UI()
def init_UI(self): #... code ... self.setWindowTitle('Python Script GUI - Main') #self.setWindowIcon(QtGui.QIcon('icons/zas.png')) self.resize(windowsize[0], windowsize[1]) self.setCentralWidget(main_widget) #### # Launch Window # if __name__ == "__main__": # Someone is launching this directly # Create the QApplication #app = QtGui.QApplication(sys.argv) app = QtGui.QApplication() # The Main window main_window = MainUI() main_window.show() # Enter the main loop app.exec_()
19.7.4 Signal Slot
Especially if you have a multithreaded application all information between the threads should be exchanged with the signal slot mechanism. Connect a signal to a function (slot).
Listing 18: connect signal slot self.connect(self, QtCore.SIGNAL('signalName'),self.receiving_functionName)
Emit a signal with certain parameters, the parameters will be given to the function argu- ments.
19.7. PyQt4 157 Zawiki, Release v0.11-30-g7307413
Listing 19: emit signal self.emit(SIGNAL("signalName"), "param_string", 10, False) # String, int and bool␣ ,→parameter
Listing 20: signal slot example import sys import time from PyQt4.QtCore import * from PyQt4.QtGui import * class WindowEx(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) self.connect(self, SIGNAL("signalName"), self.receiving_functionName) self.someFunction()
def someFunction(self): self.emit(SIGNAL("signalName"), "string", 10, False)
def receiving_functionName(self, string_param, int_param, bool_param): print("%s %i %b" % (string_param, int_param, bool_param)) if __name__ == "__main__": app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_())
19.7.5 Toolbar
Listing 21: toolbar # Create Buttons and Shortcuts self.run = QtGui.QAction(QtGui.QIcon('icons/run.png'), 'Run Script', self) self.run.setShortcut('Ctrl+R') self.connect(self.run, QtCore.SIGNAL('triggered()'), self.exe) self.rst = QtGui.QAction(QtGui.QIcon('icons/reset.png'), 'Reset Fields', self) self.rst.setShortcut('Ctrl+Shift+R') self.connect(self.rst, QtCore.SIGNAL('triggered()'), self.reset) self.info = QtGui.QAction(QtGui.QIcon('icons/info.png'), 'Info', self) self.info.setShortcut('Ctrl+Q') self.connect(self.info, QtCore.SIGNAL('triggered()'), self.displayInfo) self.exit = QtGui.QAction(QtGui.QIcon('icons/exit.png'), 'Exit', self) self.exit.setShortcut('Ctrl+Q') self.connect(self.exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))
# Create Toolbar self.toolbar = self.addToolBar('Actions') self.toolbar.addAction(self.run) self.toolbar.addAction(self.rst) self.toolbar.addAction(self.info) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(self.exit)
19.7. PyQt4 158 Zawiki, Release v0.11-30-g7307413
19.7.6 Taskbar trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("icons/simulate.png"), self) trayIcon.show()
For Windows 7 and newer, the Taskbar uses heuristic algorithm to define groupable ap- plications. Therefore your Python application is always grouped with the pythonw.exe application. To change that, you need to enter a specific AppUserModelID. import ctypes myappid = 'mycompany.myproduct.subproduct.version' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
The Code need to be executed before and GUI is started.
19.7.7 Widgets
Listing 22: widgets # Title label self.script_label = QtGui.QLabel("Launcher for script: " + script)
# Input widgets self.input_label = QtGui.QLabel("Input File:") self.input_edit = QtGui.QLineEdit() self.input_button = QtGui.QPushButton("Browse")
# Output widgets self.output_label = QtGui.QLabel("Output Directory:") self.output_edit = QtGui.QLineEdit() self.output_button = QtGui.QPushButton("Browse")
# Verbose Radiobutton self.verbose_rb = QtGui.QRadioButton('Verbosity', self) self.clear_button = QtGui.QPushButton("Clear")
# Textbox for output self.textBox = QtGui.QTextEdit("Script Output") self.textBox.setMaximumHeight(windowsize[0]-200)
# Connect signal # Browse File button QtCore.QObject.connect(self.input_button, QtCore.SIGNAL("clicked()"), self.browseFile) # Browse Directory button QtCore.QObject.connect(self.output_button, QtCore.SIGNAL("clicked()"), self.browseDir)
# Browse Directory button QtCore.QObject.connect(self.clear_button, QtCore.SIGNAL("clicked()"), self.clear)
#---- # browse File # def browseFile(self): (continues on next page)
19.7. PyQt4 159 Zawiki, Release v0.11-30-g7307413
(continued from previous page) #filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 'Path', ,→"filters") filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '', "XML files␣ ,→(*.xml);;All files (*)") self.input_edit.setText(filename) if not(filename == ''): self.statusBar().showMessage('Ready: File OK') else: self.statusBar().showMessage('Error: File NOK') # END browseFile
#---- # browse Directory # def browseDir(self): dirname = QtGui.QFileDialog.getExistingDirectory(self, 'Open directory', '') self.output_edit.setText(dirname) if not(dirname == ''): self.statusBar().showMessage('Ready: Directory OK') else: self.statusBar().showMessage('Error: Directory NOK') # END browseDir
#---- # clear terminal # def clear(self): self.textBox.setText('') self.statusBar().showMessage('Ready: terminal cleared') # END clear
19.7.8 Progressbar
The Progressbar allows to represent the % done of the program or simply to display that a process is working
19.7. PyQt4 160 Zawiki, Release v0.11-30-g7307413
Listing 23: progressbar # Create progressbar self.pbar = QtGui.QProgressBar(self)
# 0% of 100% self.pbar.setValue(0) self.pbar.setMaximum(100) self.pbar.setMinimum(0)
# In progress, bouncing back and forth self.pbar.setMaximum(0) self.pbar.setMinimum(0)
# 33% of 100% self.pbar.setValue(33) self.pbar.setMaximum(100) self.pbar.setMinimum(0)
19.7.9 Layout
Listing 24: layout # Layout grid1 = QtGui.QGridLayout() grid1.addWidget(self.input_label, 0, 0) grid1.addWidget(self.input_edit, 0, 1) grid1.addWidget(self.input_button, 0, 2) grid1.addWidget(self.output_label, 1, 0) grid1.addWidget(self.output_edit, 1, 1) grid1.addWidget(self.output_button, 1, 2) grid1.addWidget(self.verbose_rb, 2, 0) grid1.addWidget(QtGui.QLabel(''), 2, 2) grid1.addWidget(self.clear_button, 2, 2) hboxCmd = QtGui.QHBoxLayout() hboxCmd.addWidget(self.script_label) hboxCmd.addStretch(1) hboxTextBox = QtGui.QHBoxLayout() hboxTextBox.addWidget(self.textBox) main_layout = QtGui.QVBoxLayout() main_layout.addLayout(hboxCmd) main_layout.addLayout(grid1) main_layout.addLayout(hboxTextBox) main_layout.addWidget(self.pbar)
# Create central widget, add layout and set main_widget = QtGui.QWidget() main_widget.setLayout(main_layout)
19.7. PyQt4 161 Zawiki, Release v0.11-30-g7307413
19.7.10 Statusbar
Listing 25: statusbar # Write statusbar message self.statusBar().showMessage('Ready')
# Add widget into statusbar self.statusBar().addPermanentWidget(self.pbar,0)
19.7.11 Center window
Listing 26: center self.winCenter() def winCenter(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) # END win_center
19.8 Standart libraries
• Module Content • sys – sys Variables – Arguments • os – os Variables • re & RegExp • time • random
19.8.1 Module Content
If you want to know the functions available of a module, import it and dir(
19.8. Standart libraries 162 Zawiki, Release v0.11-30-g7307413
19.8.2 sys sys Variables sys.
Variable name Description argv Command line args builtin_module_names Linked C modules byteorder Native byte order exec prefix Root directory executable Name of executable modules Loaded modules path Search path platform Current platform (Windows, Linux, Darwin (Mac)) stdin, stdout, stderr File Objects for I/O
Arguments
Listing 27: sys args sys.argv for $python foo.py bar -c qux --h sys.argv[0] = foo.py sys.argv[1] = bar sys.argv[2] = -c sys.argv[3] = qux sys.argv[4] = --h
19.8.3 os os Variables os.
Variable name Description altsep Alternative separator curdir Current dir string defpath Default search path devnull Path of null device extsep Extension separator linesep Line separator name Name of os (posix, nt, mac, os2, ce, java, riscos) pardir Parent dir string pathsep Patch separator sep Path seperator
These functions are platform indepentend and should work on Linux, Windows und Mac.
19.8. Standart libraries 163 Zawiki, Release v0.11-30-g7307413
Listing 28: os os.getcwd() # Return actual working directory os.listdir() # Return NAmes of all files and folders from the given␣ ,→loction os.getenv() # Read environment variables os.putenv() # Write environment variables os.remove(file) # delete file os.sysrtem() # put the command into the Terminal os.path.split(filepath) # Returns location and filename os.path.isfile(filepath) # Check if location is a file os.path.isdir(path) # Check if location is a folder os.path.exist(path|file) # Check if location exists os.path.splitext(file) # Splits filename and extention file, ext = os.path. ,→splitext(f) os.path.dirname(path) #
For searching wihtin a folder root use the os.walk() for dirpath, dirnames, filenames in os.walk(folder_location): # dirpath = root dir of file # dirnames = [] list of dirs in dirpath # filenames = [] list of files in dirpath pass path_win = "C://user/file.txt" path_lin = "/home/user/file.txt" os.path.basename(path_win) # 'file.txt' os.path.dirname(path_win) # 'C://user' os.path.basename(path_lin) # 'file.txt' os.path.dirname(path_lin) # '/home/user' os.path.split(path_win) # ('C://user', 'file.txt') os.path.split(path_lin) # ('/home/user', 'file.txt') os.path.splitext(path_lin) # ('/home/user/file', '.txt')
19.8.4 re & RegExp import re def myRegEx_Checker(expression,data): reg=re.compile(expression); if reg.match(data): return True return False
# replace multiple space with one re.sub("\s+"," ", " Python Regexpr ") # " Python Regexpr "
# remove front and leading spaces re.sub("^\s+|\s+$","", " Regexpr ") # "Regexpr"
# remove comment (# or -- or //) and all after it re.sub("(--|#|//).*","", "Regexpr --comment") # "Regexpr "
# search only re.findall("(\d{1,2}\/\d{1,2}\/\d{4})", "asdfsadf31/02/2012dsfsdf") # Date (e.g.␣ ,→31/3/2006)) # returns a list of found strings
19.8. Standart libraries 164 Zawiki, Release v0.11-30-g7307413
19.8.5 time
Listing 29: time import time strftime("%Y-%m-%d %H:%M:%S", gmtime()) # 2009-01-05 22:14:39 strftime("%Y-%m-%d %H:%M:%S", localtime()) # 2009-01-05 22:14:39 strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) # Tue, 06 Jan 2009 04:54:56 +0000
Listing 30: sleep import time time.sleep(6) # Sleep in seconds
19.8.6 random
Listing 31: random import random
# Random number between 0.0 and 1.0 random.random() # e.g. 0.28396990573542813
# Uniform random number between a and b (a <= x < b) uniform(a, b) random.uniform(1, 10) # e.g. 6.3970639899381769
# Gauss random number of mean value "mu" and standard deviation "sigma" gauss(mu, sigma) random.gauss(5, 2) # e.g. 6.3865365546439046
# Other functions betavariate(alpha, beta) # Beta deviation expovariate(lambd) # Exponential deviation gammavariate(alpha, beta) # Gamma-deviation lognormvariate(mu, sigma) # logarithmische deviation vonmisesvariate(mu, kappa) # Von-Mises-deviation paretovariate(alpha) # Pareto-deviation weibullvariate(alpha, beta) # Weibull-deviation
# Random integer between a and b (a <= x <= b) like throw dice randint(a, b) random.randint(1, 6) # e.g. 4
# Random picked number of a list randrange( [start,] stop[, step]) range(0, 21, 2) # e.g. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] random.randrange(0, 21, 2) # e.g. 10
19.8. Standart libraries 165 Zawiki, Release v0.11-30-g7307413
19.9 Syntax
• General – Sourcefile – Help informations • Import – import
19.9. Syntax 166 Zawiki, Release v0.11-30-g7307413
– Dictionaries – Sequence – References and Objects • Oriented Objects Programming – __init__-Method – Klassen und Objekt variablen – inherit • Input & Output – File – Freeze and Unfreeze • Exceptions – try .. except – throw exception – try .. finally • Buildin Methods – __init__() – __del__() – __str__() – __it__() – __getitem__() – __len__()
19.9.1 General
Sourcefile
19.9. Syntax 167 Zawiki, Release v0.11-30-g7307413
Listing 32: sourcefile #!/usr/bin/python # -*- coding: utf-8 -*- # -*- coding: latin1 -*- # -*- coding: iso-8859-1 -*- # durch coding auch umlaut möglich print 'Hello Wörld'
Help informations help(command or object) q => Exit help
19.9.2 Import
There are two ways to import modules. import
You import the module. you have to call each time modulname.function to access each function import
from
In the second way you import one one or with * all functions of a module. But if you import the same function of two different modules, or if you import * from two modules which has common function names the interpreter won’t know which one you are calling. from
Example
# First way import math math.sqrt(25)
# Second way from math import sqrt sqrt(25)
# Second way but import everything (need for math. anymore) from math import * sqrt(25) log(10)
19.9. Syntax 168 Zawiki, Release v0.11-30-g7307413
19.9.3 Strings and Numbers
'' => Spaces and symbols will be taken "" => Same as Strings with '' ''' ''' or """ """ Multiline Strings, inside '' and "" can be used 'This is a String.' / "This too!" ''' This is a Multiline String. Frist Line And this is the "Second Line" '''
Escape Characters
\' # = ' \" # = " \\ # = \ \n # = New Line \t # = Tabulator \ # = Line feed
Types
Type Example int 5 long 1.23 float 9.25e-3 complex 5.3+3j
19.9.4 Convertions int() # to int float() # to float complex() # to complex long() # to long unichr() # int to 1 char ord() # 1 element string to int str() # int to string
String Bin Hex convertions hex_bin = binascii.unhexlify(hex_string) hex_string = binascii.hexlify(hex_bin) def hex2bin(self, str): bin = ['0000','0001','0010','0011', '0100','0101','0110','0111', '1000','1001','1010','1011', '1100','1101','1110','1111'] aa = '' for i in range(len(str)): aa += bin[int(str[i],base=16)] return aa (continues on next page)
19.9. Syntax 169 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
# END hex2bin bin_string = hex2bin(hex_string) hex_string = hex(int_number) int_number = int(hex_string,16)
# 2 digit hex string hex_string = "0x%0.2X" % 255 # = 0xFF hex_string = "%0.2X" % 255 # = FF
# Format strings the easy way string = "{0} {1}".format(firstReplacer , secondReplacer)) print("{:03} {:3}".format(nbr1 , nbr2)) # {:03} = right aligned 3 numbers filled with 0 e.g. 005 or 015 # {:3} = right aligned 3 numbers e.g. 5 15
# More examples print("{0: >6,.4}".format(nbr0, nbr1) # print nbr0, align right, fill with " ", 6 places width, 4 digits precision
19.9.5 String Format Mini Language format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::=
"{" [field_name] ["!" conversion] [":" format_spec] "}" / "r"|"s" \ / (r)epr (s)tr \ arg_name \ | ("." attribute_name | "[" element_index "]")* \ | | | \ | identifier integer | index_string | | (quotes | [identifier not required) | |integer] | | ______/ \______/ \ ":" [[fill]align][sign][#][0][width][,][.precision][type] [default]--> < left + | | (int) (int) b base 2 [default --> > right [-] | | c character for ^ center " " | \ d base 10 numbers] = | `zero padding e exponent (e) | E exponent (E) use 0b,0o,0x f fixed point for 2 8 16 F ^^(same)^^ b base 2 c character [default]--> g general (???) o base 8 s string G general 2 (?) d base 10 n number (general 3) x base 16 o base 8 (continues on next page)
19.9. Syntax 170 Zawiki, Release v0.11-30-g7307413
(continued from previous page) X base 16 s string e, E exponent (lower case) x base 16 f, F, % fixed point (upper case) X base 16 g, G, n (general numbers) (x100, f) % percentage print("{:>6.5}".format(var)) # right aligned to 6 digits, precision 5 (5␣ ,→numbers including point e.g. 0.123) print("{:08}".format(var)) # filled up with 0 to 8 digits, 00001234 print("0x{:0x}".format(int(var))) # in hex small case, 0x4d2 print("0x{:0X}".format(int(var))) # in hex small case, 0x4D2 print("{:04x}".format(int(var))) # in hex small case, 0x04d2 print("{:04X}".format(int(var))) # in hex small case, 0x04D2
19.9.6 Operator
+ # Plus 3 + 5 = 8 'a' + 'b' = 'ab' - # Minus -5.2 order 5 - 2 * # Multiplcation 2 * 3 = 6 ** # Power 3 ** 4 = 3 * 3 * 3 * 3 = 81 / # Division 4 / 3 = 1 oder 4.0/3 = 1.3333... // # Integer Division 4 // 3.0 = 1.0 % # Modulo 8 % 3 = 2 << # Bitwise left 2 << 2 = 8 (in binary) >> # Bitwise right 11 >> 1 = 5 (in binary) & # Bitwise AND 5 & 3 = 1 (in binary) ¦ # Bitwise OR 5 | 3 = 7 (in binary) ^ # Bitwise XOR 5 ^ 3 = 6 (in binary) ~ # Bitwise NOT ~5 = -6 < # Smaller as > # Bigger as <= # Smaller Equal >= # Bigger Equal == # Equal != # Not Equal not # log NOT and # log AND or # log OR
Priority
A Line will be evaluated from left to right
## High priority lambda # lambda function or # log OR and # log AND not x # log NOT in, not in # Part of test (in Sequences) is, is not # Identity test <,<=,>,>=,!=,== # Comparison | # Bitwise OR ^ # Bitwise XOR & # Bitwise AND (continues on next page)
19.9. Syntax 171 Zawiki, Release v0.11-30-g7307413
(continued from previous page) <<,>> # Bitwise Shift +,- # Add, Sub *,/,% # Mul, Div, Mod +x,-x # pos-, neg-sign ~x # Bitwise NOT ** # Pow x.attribut # Attribut reference x[index] # Index x[index:index] # range of a sequence f(param ...) # function call (ausdruck, ...) # brackets [ausdruck, ...] # List {key:value, ...} # Dictionaries 'ausdruck, ...' # Umwandlung in Stringdarstellung ## Low priority
19.9.7 Statement if elif else number = 23 guess = int(raw_input('Enter a number: ')) if guess == zahl: print 'YES' elif guess < number: print 'Higher' else: print 'Lower'
while number = 23 nostop = True while nostop: guess = int(raw_input('Enter a number: ')) if number == guess: print 'Yes' nostop = False # End of while elif guess < number: print 'Higher' else: print 'Lower' else: print 'End of while loop'
19.9. Syntax 172 Zawiki, Release v0.11-30-g7307413 for for i in range(1, 5): print i else: print 'End of for loop'
break while True: s = raw_input('Enter something: ') if s == 'end': break print 'The length of the string is', len(s)
continue continue use for while and for while True: s = raw_input('Enter something: ') if s == 'end': break if len(s) < 3: continue print 'Sufficient long' # Treat input here
pass
# pass is used to create an empty block def function(): pass
19.9.8 Functions
General Functions def hello_world(): print 'hello cruel world!' # End of function hello_world() # function call def printMax(a, b): if a > b: print a, 'is max value' else: print b, 'is max value' printMax(3, 4) # function call with number x = 5 y = 7 printMax(x, y) # function call with arguments
19.9. Syntax 173 Zawiki, Release v0.11-30-g7307413
Global variable def func(): global x print 'x ist', x x = 2 print 'global x is now', x x = 50 func() print 'The value of x is', x # x = 2 because of global var
Predefined Arguments
If a function parameter is not given, the default value will be used. All parameter with default values need to be at the end of the parameter list. def sag(message, loops = 1): print message * loops sag('Hello') sag('World', 5)
Keywords with param def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', c func(3, 7) func(25, c=24) func(c=50, a=100)
Return def maximum(x, y): if x > y: return x else: return y print maximum(2, 3)
19.9.9 Modules
Definition of a Module
Everything in Python is a module (almost) def hello(): print 'Hello, this is a module' version = '0.1'
19.9. Syntax 174 Zawiki, Release v0.11-30-g7307413
Usage of a Module
The Module need to be in the same folder import myModule myModule.hello() print 'Version', mmyModule.version
from .. import from myModule import hello, version # OR: from myModule import * hello() print 'Version', version
19.9.10 Data structures
List
# This is a list list = ['Book', 'Pencil', 'Apple', 'Glass'] print 'I have ', len(list), ' to buy.' print 'These things are:', # Don't forget the comma at the end for thing in list: print thing, print '\nI also have to buy Bananas' list.append('Banans') print 'My list is now', list print 'Sort My list' list.sort() print 'The sorted list is ', list print 'First I'll buy', list[0] oldthing =list[0] del list[0] print 'I did buy ', oldthing print 'My list is now', list
Tuple zoo = ('Wolf', 'Elefant', 'Pinguin') print 'The number of animals in the Zoo is: ', len(zoo) new_zoo = ('Ape', 'Delfin', zoo) print 'The number of animals in the new Zoo is: ', len(new_zoo) print 'All animals in the new Zoo are: ', new_zoo print 'The animals from the old Zoo are', new_zoo[2] print 'The last animal is a: ', new_zoo[2][2]
19.9. Syntax 175 Zawiki, Release v0.11-30-g7307413
Dictionaries ab = { 'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]' } print "Swaroops Adresse ist %s" % ab['Swaroop'] # Ein Schluessel/Wert-Paar hinzufuegen ab['Guido'] = '[email protected]' # Ein Schluessel/Wert-Paar loeschen del ab['Spammer'] print '\nEs gibt %d Kontakte im Adressbuch\n' % len(ab) for name, adresse in ab.items(): print '%s hat die Adresse %s' % (name, adresse) if 'Guido' in ab: # oder: ab.has_key('Guido') print "\nGuidos Adresse ist %s" % ab['Guido']
Sequence list = ['Book', 'Pencil', 'Apple', 'Glass'] # Index print 'Pos 0 is', list[0] # Book print 'Pos 1 is', list[1] # Pencil print 'Pos 2 is', list[2] # Apple print 'Pos 3 is', list[3] # Glass print 'Pos -1 is', list[-1] # Glass print 'Pos -2 is', list[-2] # Apple # List range print 'Pos 1 to 3 is', list[1:3] # ['Pencil', 'Apple'] print 'Pos 2 to End is', list[2:] # ['Apple', 'Glass'] print 'Pos 1 to -1 is', list[1:-1] # ['Pencil', 'Apple'] print 'Pos begin to is', list[:] # ['Book', 'Pencil', 'Apple', 'Glass'] # List range on a string name = '1234567' print 'Chars 1 bis 3 ist', name[1:3] # 23 print 'Chars 2 bis Ende ist', name[2:] # 34567 print 'Chars 1 bis -1 ist', name[1:-1] # 3456 print 'Chars Begin to End', name[:] # 1234567
References and Objects list = ['Book', 'Pencil', 'Apple', 'Glass'] mylist = list
“mylist” is another name pointing to the same object. Delete one item del list[0] print 'list is', list print 'mylist is', mylist
Both list return it’s items without the deleted item “Book”. This shows that both point to the same object
19.9. Syntax 176 Zawiki, Release v0.11-30-g7307413
print 'Copy with range' mylist = list[:] # this copies the whole list del mylist[0] print 'list is', list print 'mylist is', mylist
Both lists are different now, will the copy created a new list.
19.9.11 Oriented Objects Programming self == this == addr des Objektes
__init__-Method class Person: def __init__(self, name): self.name = name def sagHallo(self): print 'Hallo, mein Name ist', self.name p = Person('Swaroop') p.sagHallo() # Dieses kurze Beispiel kann auch als # Person('Swaroop').sagHallo() geschrieben werden.
Klassen und Objekt variablen class Person: '''Stellt eine Person dar.''' bevoelkerung = 0 def __init__(self, name): '''Initialisiert die Daten der Person.''' self.name = name print '(Initialisiere %s)' % self.name # Wenn diese Person erzeugt wird, Person.bevoelkerung += 1 def __del__(self): '''Ich sterbe.''' print '%s verabschiedet sich.' % self.name Person.bevoelkerung -= 1 if Person.bevoelkerung == 0: print 'Ich bin der letzte.' else: print 'Es gibt noch %d Leute.' % Person.bevoelkerung def sagHallo(self): '''Begruessung durch die Person. Das ist wirklich alles, was hier geschieht.''' print 'Hallo, mein Name ist %s.' % self.name def wieViele(self): '''Gibt die aktuelle Bevoelkerungszahl aus.''' if Person.bevoelkerung == 1: print 'Ich bin ganz allein hier.' else: print 'Es gibt hier %d Leute.' % Person.bevoelkerung
• Alle Variablen sind normalerweise public • Mit __privatvar wird es zu einer Privaten Variable
19.9. Syntax 177 Zawiki, Release v0.11-30-g7307413
• Mit __doc__ kann auf die ''' Infos zugegriffen werden Person.__doc__ or Person. sagHallo.__doc__ • __init__ wird immer bei der erzeugung eines Objektes ausgeführt • __del__ wird automatisch aufgerufen falls das Objekt nicht mehr gebraucht wird inherit class SchulMitglied: '''Repraesentiert ein beliebiges Mitglied der Hochschule.''' def __init__(self, name, alter): self.name = name self.alter = alter print '(SchulMitglied %s initialisiert)' % self.name def auskunft(self): '''Gib Auskunft ueber das Mitglied.''' print 'Name: "%s" Alter: "%s"' % (self.name, self.alter), class Dozent(SchulMitglied): '''Repraesentiert einen Dozenten der Hochschule.''' def __init__(self, name, alter, gehalt): SchulMitglied.__init__(self, name, alter) self.gehalt = gehalt print '(Dozent %s initialisiert)' % self.name def auskunft(self): SchulMitglied.auskunft(self) print 'Gehalt: "%d Euro"' % self.gehalt class Student(SchulMitglied): '''Repraesentiert einen Studenten der Hochschule.''' def __init__(self, name, alter, note): SchulMitglied.__init__(self, name, alter) self.note = note print '(Student %s initialisiert)' % self.name def auskunft(self): SchulMitglied.auskunft(self) print 'Letzte Pruefungsnote: "%1.1f"' % self.note d = Dozent('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 1.7) mitglieder = [d, s] for mitglied in mitglieder: mitglied.auskunft() # geht bei Dozenten und Studenten
19.9.12 Input & Output
File text = 'sein oder nicht sein'
# Write f = file('gedicht.txt', 'w') # "w" = Schreiben f.write(text) # schreibe den Text in die Datei f.close() # schliesse die Datei
# Read f = file('gedicht.txt') # kein Modus bedeutet "r" = Lesen while True: line = f.readline() if len(line) == 0: # eine leere Zeile = Dateiende (EOF) (continues on next page)
19.9. Syntax 178 Zawiki, Release v0.11-30-g7307413
(continued from previous page) break print line, # das , für Zeilenvorschub Unterdrückung f.close() # schliesse die Datei
Freeze and Unfreeze import cPickle as p # Datei, in der das Objekt speichert wird einkaufsdatei = 'einkaufsliste.data' einkaufsliste = ['Aepfel', 'Mangos', 'Karotten']
# Schreibe in die Datei f = file(einkaufsdatei, 'w')
#Einfrieren p.dump(einkaufsliste, f) # speichere das Objekt in der Datei f.close() del einkaufsliste # loesche die einkaufsliste # Lies die Einkaufsliste aus der Datei wieder ein f = file(einkaufsdatei)
#Auftauen gespeicherteliste = p.load(f) print gespeicherteliste
19.9.13 Exceptions try .. except
Each try needs to have at least one except try: s = raw_input('Geben Sie etwas ein --> ') except EOFError: print '\nWarum haben Sie die Eingabe abgebrochen?' sys.exit() # beendet das Programm except: print '\nIrgendein Fehler hat eine Ausnahme ausgeloest.' print 'Fertig'
throw exception class KurzeEingabeAusnahme(Exception): '''Eine benutzerdefinierte Ausnahmeklasse.''' def __init__(self, laenge, mindestens): Exception.__init__(self) self.laenge = laenge self.mindestens = mindestens try: s = raw_input('Geben Sie etwas ein --> ') if len(s) < 3: raise KurzeEingabeAusnahme(len(s), 3) # Hier kann man ganz normal mit der Arbeit fortfahren except EOFError: (continues on next page)
19.9. Syntax 179 Zawiki, Release v0.11-30-g7307413
(continued from previous page) print '\nWarum haben Sie die Eingabe abgebrochen?' except KurzeEingabeAusnahme, x: print 'KurzeEingabeAusnahme: Eingabe hatte die Laenge %d,' \ ' gefordert war mindestens %d.' % (x.laenge, x.mindestens else: print 'Es wurde keine Ausnahme ausgeloest.'
try .. finally
If an exception is raised in the program, e.g. Ctrl + c Keyboard interrupt, the finally clause is raised before the program is closed import time try: f = file('gedicht.txt') while True: # unsere uebliche Weise, Dateien zu lesen zeile = f.readline() if len(zeile) == 0: break time.sleep(2) print zeile, finally: f.close() print 'Raeume auf... Datei geschlossen.'
19.9.14 Buildin Methods
__init__()
Is executed before an object is returned
__init__(self, ...)
__del__()
Is called before an object is destroyed
__del__(self)
__str__()
Is called if print or str() is used
__str__(self)
19.9. Syntax 180 Zawiki, Release v0.11-30-g7307413
__it__()
Is called if < is used lt == less than There are also such methods for other operators
__it__(self, other)
__getitem__()
Is called if an indexing operator is used x[key]
__getitem__(self, key)
__len__()
Is called if the len() function is used
__len__(self)
19.9. Syntax 181 Chapter 20
RegEx
• RegEx Cheatsheet - from Added Bytes • Test your regex with Regexr
20.1 Anchors
^ # Start of line \A # Start of string $ # End of line \Z # End of string \b # Word boundary \B # Not word boundary \< # Start of word \> # End of word
20.2 Character Classes
\c # Control character \s # White space \S # Not whit space \d # Digit \D # Not digit \w # Word \W # Not word \xhh # Hexadecimal character hh \Oxxx # Octal character xxx
182 Zawiki, Release v0.11-30-g7307413
20.3 POSIX Character Classes
[:upper:] # Upper case letters [:lower:] # Lower case letters [:alpha:] # All letters [:alnum:] # Digits and letters [:digit:] # Digits [:xdigit:] # Hexadecimal digits [:punct:] # Punctuation [:blank:] # Space and tab [:space:] # Blank characters [:cntrl:] # Control characters [:print:] # Printed characters and spaces [:word:] # Digits, letter and underscore
20.4 Assertions
?= # Lookahead assertion ?! # Negative lookahead ?<= # Lookbehind assertion ?!= or ? # Once-only Subexpression ?() # Condition [if then] ?()| # Condition [if then else] ?# # Comment
20.5 Quantifiers
* # 0 or more *? # 0 or more, ungreedy + # 1 or more +? # 1 or more, ungreedy ? # 0 or 1 ?? # 0 or 1, ungreedy {3} # Exactly 3 {3,5} # 3, 4 or 5 {3,5}? # 3, 5 or 5 ungreedy
20.6 Special Characters
\ # Escape Character \n # New line \r # Carriage return \t # Tab \v # Vertical tab \f # Form feed \a # Alarm [\b] # Backspace \e # Escape \N{name} # Named Character
20.3. POSIX Character Classes 183 Zawiki, Release v0.11-30-g7307413
20.7 String replacement
$n # nth non passive group $2 # "xyz" in /^(abc(xyz))$/ $1 # "xyz" in /^(?:abc(xyz))$/ $` # Before matched string $' # After machted string $+ # Last machted string $& # Entire matched string $_ # Entire input string $$ # Literal $
20.8 Ranges
. # Any character except new line (\n) (a|b) # a or b (...) # Group (?:...) # Passive Group [abc] # Range (a or b or c) [^abc] # Not (a or b or c) [a-q] # Letter between a and q [A-Q] # Upper case letter between A and Q [0-7] # Digit between 0 and 7 \n # nth group/subpattern
20.9 Pattern Modifiers g # Global match i # Case-insensitive m # Multiple lines s # Treat string as single line x # Allow comments and white space in pattern e # Evaluate replacement U # Ungreedy pattern
20.10 Metacharacters
These Characters must be escaped with \
^ < > * $ { ] + | ( ) \?.
20.7. String replacement 184 Zawiki, Release v0.11-30-g7307413
20.11 Patter Modifiers
([A-Za-Z0-9-]+) # Letter, numbers and hyphens (\d{1,2}\/\d{1,2}\/\d{4}) # Date (e.g. 31/3/2006) ([^\s]+(?=\.(jpg|gif|png))\.\2) # jpg, gif or png image
20.11. Patter Modifiers 185 Chapter 21
VHDL
21.1 Introduction
• PDF • Links
VHDL (VHSIC hardware description language) is a hardware description language used in electronic design automation to describe digital and mixed-signal systems such as field- programmable gate arrays and integrated circuits. VHDL is commonly used to write text models that describe a logic circuit. Such a model is processed by a synthesis program. A simulation program is used to test the logic design using simulation models to represent the logic circuits that interface to the design. This collection of simulation models is commonly called a testbench. VHDL has constructs to handle the parallelism inherent in hardware designs. VHDL is strongly typed and is not case sensitive. A final point is that when a VHDL model is translated into the “gates and wires”thatare mapped onto a programmable logic device such as a CPLD or FPGA, then it is the actual hardware being configured, rather than the VHDL code being “executed” as if onsome form of a processor chip. As last remark I want to thank Corthay Francois for his VHDL Summary and HTML files.
186 Zawiki, Release v0.11-30-g7307413
21.1.1 PDF
• ESA VHDL Modelling Guide • Synth Works Fixed & Float • Synth Works Math Tricks • Synth Works Verification • Synth Works VHDL 2008 End of Verbosity • Short Guide CoF • EPFL VHDL Script
21.1.2 Links
• Wikibook VHDL Programmable Logic • Wikibook VHDL for FPGA Design • Wikibook VHDL • VHDL Guide • Compact Summary of VHDL • Open cores - Free VHDL/Verilog IP’s • VHDL Guru Blog • Synth Works
21.2 Attributes
• Predefined attributes – Value kind attributes ∗ 'left ∗ 'right ∗ 'high ∗ 'low ∗ 'length ∗ 'ascending ∗ 'structure & 'behaviour ∗ 'simple_name & 'instance_name & 'path_name – Function kind attributes 1 ∗ 'pos(value) ∗ 'val(value) ∗ 'succ(value) ∗ 'pred(value)
21.2. Attributes 187 Zawiki, Release v0.11-30-g7307413
∗ 'leftof(value) ∗ 'rightof(value) – Function kind array attributes ∗ 'left() ∗ 'right() ∗ 'high() ∗ 'low() ∗ 'event ∗ 'active ∗ 'last_event ∗ 'last_value ∗ 'last_active – Function kind attributes 2 ∗ 'image ∗ 'value – Signal kind attributes ∗ 'delayed(time) ∗ 'stable(time) ∗ 'quite(time) ∗ 'transaction – Type kind attributes ∗ 'base – Range kind attributes ∗ 'range ∗ 'reverse_range • Custom attributes
Attributes are a feature of VHDL that allow you to extract additional information about an object (such as a signal, variable or type) that may not be directly related to the value that the object carries. Attributes also allow you to assign additional information (such as data related to synthesis) to objects in your design description.
21.2.1 Predefined attributes
The VHDL specification describes five fundamental kinds of attributes. • a value • a function • a signal • a type • a range.
21.2. Attributes 188 Zawiki, Release v0.11-30-g7307413
Predefined attributes are always applied to a prefix (such as a signal or variable name,or a type or subtype name), as in the statement: wait until Clk = '1' and Clk'event and Clk'last_value = ‘0’;
Some attributes also include parameters, so they are written in much the same way you would write a call to a function: variable V: state_type := state_type'val(2); -- V has the value of Strobe
In this case, the attribute ‘val has been applied to the prefix state_type (which is a type name) and has been given an attribute parameter, the integer value 2.
Value kind attributes
'Left, 'Right, 'High, 'Low, 'Length, 'Ascending The value kind attributes that return an explicit value and are applied to a type or subtype include the following:
'left
'Left This attribute returns the left-most element index (the bound) of a given type or subtype. type bit_array is array (1 to 5) of bit; variable L: integer := bit_array'left; -- L has a value of 1
'right
'Right Returns the right-most bound of a given type or subtype. type bit_array is array (1 to 5) of bit; variable R: integer := bit_array'right; -- R has a value of 5
'high
'High returns the upper bound of a given scalar type or subtype. type bit_array is array(-15 to +15) of bit; variable H: integer := bit_array'high; -- H has a value of 15
21.2. Attributes 189 Zawiki, Release v0.11-30-g7307413
'low
'Low returns the upper bound of a given scalar type or subtype.
type bit_array is array(15 downto 0) of bit;
variable L: integer := bit_array'low; -- L has a value of 0
'length
'Length returns the length (number of elements) of an array.
type bit_array is array (0 to 31) of bit;
variable LEN: integer := bit_array'length; -- LEN has a value of 32
'ascending
'Ascending (VHDL ‘93 attribute) returns a boolean true value of the type or subtype is declared with an ascending range.
type asc_array is array (0 to 31) of bit;
type desc_array is array (36 downto 4) of bit; variable A1: boolean := asc_array'ascending; -- A1 has a value of true variable A2: boolean := desc_array'ascending; -- A2 has a value of false
'structure & 'behaviour
There are two additional value kind attributes that can be used to determine information about blocks or attributes in a design. These attributes, ‘structure and ‘behavior, return true or false values depending on whether the block or architecture being referenced includes references to lower-level components. The ‘structure attribute returns true if there are references to lower-level components, and false if there are no references to lower-level components. The ‘behavior attribute returns false if there are references to lower-level components, and true if there are no references to lower-level components. 'Structure returns a true value if the prefix (which must be an architecture name) in- cludes references to lower-level components. 'Behavior returns a true value if the prefix (which must be an architecture name) does not include references to lower-level components.
'simple_name & 'instance_name & 'path_name
VHDL 1076-1993 added three attributes that can be used to determine the precise con- figuration of entities in a design description. These attributes return information about named entities, which are various items that become associated with identifiers, character literals or operator symbols as the result of a declaration. 'Simple_name returns a string value corresponding to the prefix, which must be a named entity. 'Instance_name returns a string value corresponding to the complete path (from the de- sign hierarchy root) to the named entity specified in the prefix, including the names ofall
21.2. Attributes 190 Zawiki, Release v0.11-30-g7307413 instantiated design entities. The string returned by this attribute has a fixed format that is defined in the IEEE VHDL Language Reference Manual. 'Path_name returns a string value corresponding to the complete path (from the design hierarchy root) to the named entity specified in the prefix. The string returned bythis attribute has a fixed format that is defined in the IEEE VHDL Language Reference Manual.
Function kind attributes 1
'Pos, 'Val, 'Succ, 'Pred, 'Leftof, 'Rightof Attributes that return information about a given type, signal, or array value are called function kind attributes. VHDL defines the following function kind attributes that canbe applied to types:
'pos(value)
'Pos(value) returns the position number of a type value. type state_type is (Init, Hold, Strobe, Read, Idle); variable P: integer := state_type'pos(Read); -- P has the value of 3
'val(value)
'Val(value) returns the value corresponding to a position number of a type value. type state_type is (Init, Hold, Strobe, Read, Idle); variable V: state_type := state_type'val(2); -- V has the value of Strobe
'succ(value)
'Succ(value) returns the value corresponding to position number after a given type value. type state_type is (Init, Hold, Strobe, Read, Idle); variable V: state_type := state_type'succ(Init); -- V has the value of Hold
'pred(value)
'Pred(value) returns the value corresponding to position number preceding a given type value. type state_type is (Init, Hold, Strobe, Read, Idle); variable V: state_type := state_type'pred(Hold); -- V has the value of Init
21.2. Attributes 191 Zawiki, Release v0.11-30-g7307413
'leftof(value)
'Leftof(value) returns the value corresponding to position number to the left of a given type value. type state_type is (Init, Hold, Strobe, Read, Idle); variable V: state_type := state_type'leftof(Idle); -- V has the value of Read
'rightof(value)
'Rightof(value) returns the value corresponding to position number to the right of a given type value. type state_type is (Init, Hold, Strobe, Read, Idle); variable V: state_type := state_type'rightof(Read); -- V has the value of Idle
From the above descriptions, it might appear that the 'val and 'succ attributes are equiv- alent to the attributes ‘leftof and ‘rightof. One case where they would be different is the case where a subtype is defined that changes the ordering of the base type: type state_type is (Init, Hold, Strobe, Read, Idle); subtype reverse_state_type is state_type range Idle downto Init; variable V1: reverse_state_type := reverse_state_type'leftof(Hold); -- V1 has the value of Strobe variable V2: reverse_state_type := reverse_state_type'pred(Hold); -- V2 has the value of Init
Function kind array attributes
'Left, 'Right, 'High, 'Low The function kind attributes that can be applied to array objects include:
'left()
'Left(value) returns the index value corresponding to the left bound of a given array range. Example: type bit_array is array (15 downto 0) of bit; variable I: integer := bit_array'left(bit_array'range); -- I has the value of 15
21.2. Attributes 192 Zawiki, Release v0.11-30-g7307413
'right()
'Right(value) returns the index value corresponding to the right bound of a given array range. type bit_array is array (15 downto 0) of bit; variable I: integer := bit_array'right(bit_array'range); -- I has the value of 0
'high()
'High(value) returns the index value corresponding to the upper-most bound of a given array range. type bit_array is array (15 downto 0) of bit; variable I: integer := bit_array'high(bit_array'range); -- I has the value of 15
'low()
'Low(value) returns the index value corresponding to the lower bound of a given array range. type bit_array is array (15 downto 0) of bit; variable I: integer := bit_array'low(bit_array'range); -- I has the value of 0
'Event, 'Active, 'Last_event, 'Last_value, 'Last_active Function kind attributes that return information about signals (such as whether that signal has changed its value or its previous value) include:
'event
'Event returns a true value of the signal had an event (changed its value) in the current simulation delta cycle. process(Rst,Clk) begin if Rst = '1' then Q <= '0'; elsif Clk = '1' and Clk'event then -- Look for clock edge Q <= D; end if; end process;
21.2. Attributes 193 Zawiki, Release v0.11-30-g7307413
'active
Active—returns true if any transaction (scheduled event) occurred on this signal in the current simulation delta cycle. process variable A,E: boolean; begin Q <= D after 10 ns; A := Q'active; -- A gets a value of True E := Q'event; -- E gets a value of False . . . end process;
'last_event
'Last_event returns the time elapsed since the previous event occurring on this signal. process variable T: time; begin Q <= D after 5 ns; wait 10 ns; T := Q'last_event; -- T gets a value of 5 ns . . . end process;
'last_value
'Last_value returns the value of the signal prior to the last event. process variable V: bit; begin Q <= '1'; wait 10 ns; Q <= '0'; wait 10 ns; V := Q'last_value; -- V gets a value of '1' . . . end process;
'last_active
'Last_active returns the time elapsed since the last transaction (scheduled event) of the signal. process variable T: time; begin Q <= D after 30 ns; wait 10 ns; T := Q'last_active; -- T gets a value of 10 ns . . . end process;
21.2. Attributes 194 Zawiki, Release v0.11-30-g7307413
Note: the 'active, 'last_event, 'last_value and 'last_active attributes are not gen- erally supported in synthesis tools. Of the preceding five attributes, only ‘event should be used when describing synthesizable registered circuits. The ‘active, ‘last_event, ‘last_value and ‘last_active attributes should only be used to describe circuits for test purposes (such as for setup and hold checking). If they are encountered by a syn- thesis program, they will either be ignored, or the program will return an error and halt operation.
Function kind attributes 2
'Image, 'Value The 'image and 'value attributes were added in the 1993 specification to simplify the reporting of information through Text I/O. These attributes both return string results cor- responding to their parameter values.
'image
'Image(expression) (VHDL ‘93 attribute) returns a string representation of the expres- sion parameter, which must be of a type corresponding to the attribute prefix.
assert (Data.Q = '1') report "Test failed on vector " & integer’image(vector_idx) severity WARNING;
string_signal <= std_logic'image(sl_signal);
'value
'Value(string) (VHDL ‘93 attribute) returns a value, of a type specified by the prefix, corresponding to the parameter string.
write(a_outbuf,string'("Enter desired state e.g.: S1")); writeline(OUTPUT,a_outbuf); readline(INPUT,a_inbuf); read(a_inbuf,instate); -- instate is a string type
-- convert string to type state_type next_state <= state_type'value(instate);
write(a_outbuf,string'("Enter duration (e.g.: 15)")); writeline(OUTPUT,a_outbuf); readline(INPUT,a_inbuf); read(a_inbuf,induration); -- induration is a string type
-- convert string to type integer duration <= integer'value(induration);
21.2. Attributes 195 Zawiki, Release v0.11-30-g7307413
Signal kind attributes
'Delayed, 'Stable, 'Quiet, 'Transaction The signal kind attributes are attributes that, when invoked, create special signals that have values and types based on other signals. These special signals can then be used anywhere in the design description that a normally declared signal could be used. One example of where you might use such an attribute is to create a series of delayed clock signals that are all based on the waveform of a base clock signal. Signal kind attributes include the following:
'delayed(time)
'Delayed(time) creates a delayed signal that is identical in waveform to the signal the attribute is applied to. (The time parameter is optional, and may be omitted.) process(Clk'delayed(hold)) -- Hold time check for input Data begin if Clk = '1' and Clk'stable(hold) then assert(Data’stable(hold)) report "Data input failed hold time check!" severity warning; end if; end process;
'stable(time)
'Stable(time) creates a signal of type boolean that becomes true when the signal is stable (has no event) for some given period of time. process variable A: Boolean; begin wait for 30 ns; Q <= D after 30 ns; wait 10 ns; A := Q'stable(20 ns); -- A gets a value of true (event has not yet occurred) wait 30 ns; A := Q'stable(20 ns); -- A gets a value of false (only 10 ns since event) . . . end process;
'quite(time)
'Quiet(time) creates a signal of type boolean that becomes true when the signal has no transactions (scheduled events) or actual events for some given period of time. process variable A: Boolean; begin wait for 30 ns; Q <= D after 30 ns; (continues on next page)
21.2. Attributes 196 Zawiki, Release v0.11-30-g7307413
(continued from previous page) wait 10 ns; A := Q'quiet(20 ns); -- A gets a value of false (10 ns since transaction) wait 40 ns; A := Q'quiet(20 ns); -- A finally gets a value of true (20 ns since event) . . . end process;
'transaction
'Transaction creates a signal of type bit that toggles its value whenever a transaction or actual event occurs on the signal the attribute is applied to.
Type kind attributes
'base
'Base returns the base type for a given type or subtype. type mlv7 is ('0','1','X','Z','H','L','W'); subtype mlv4 is mlv7 range '0' to 'Z'; variable V1: mlv4 := mlv4'right; -- V1 has the value of 'Z' variable V2: mlv7 := mlv4'base'right; -- V2 has the value of 'W' variable I1: integer := mlv4'width; -- I1 has the value of 4 variable I2: integer := mlv4'base'width; -- I2 has the value of 7
Range kind attributes
'Range, 'Reverse_range The range kind attributes return a special value that is a range, such as you might use in a declaration or looping scheme.
'range
'Range returns the range value for a constrained array. function parity(D: std_logic_vector) return std_logic is variable result: std_logic := '0'; begin for i in D'range loop result := result xor D(i); end loop; return result; end parity;
21.2. Attributes 197 Zawiki, Release v0.11-30-g7307413
'reverse_range
'Reverse_range returns the reverse of the range value for a constrained array.
STRIPX: for i in D'reverse_range loop if D(i) = 'X' then D(i) = '0'; else exit; -- only strip the terminating Xs end if; end loop;
21.2.2 Custom attributes
Custom attributes are those attributes that are not defined in the IEEE specifications, but that you (or your simulation or synthesis tool vendor) define for your own use. A good example is the attribute enum_encoding, which is provided by a number of synthesis tool vendors (most notably Synopsys) to allow specific binary encodings to be attached to objects of enumerated types. An attribute such as enum_encoding is declared using the following method: attribute enum_encoding: string;
Once the attribute has been declared and given a name, it can be referenced as needed in the design description: type statevalue is (INIT, IDLE, READ, WRITE, ERROR); attribute enum_encoding of statevalue: type is "000 001 011 010 110";
Custom attributes are a convenient “back door” feature of VHDL, and design tool vendors have created many such attributes to give you more control over the synthesis and simu- lation process. For detailed information about custom attributes, refer to your design tool documentation.
21.3 Conversion
• Overview – Name declaration • Numeric_STD Library • STD_logic_arith Library • Conversions – std_logic & std_ulogic – std_logic_vector & std_ulogic_vector – Integer ∗ Integer <=> Real – Unsigned – Signed
21.3. Conversion 198 Zawiki, Release v0.11-30-g7307413
• Resize – Resize Unsigned – Resize Signed
21.3.1 Overview
21.3. Conversion 199 Zawiki, Release v0.11-30-g7307413
Name declaration signal sl : std_logic; signal sul : std_ulogic: signal slv : std_logic_vector(7 downto 0); signal sulv : std_ulogic_vector(7 downto 0); signal uv : unsigned(7 downto 0); signal sv : signed(7 downto 0); signal int : integer range -128 to 127;
21.3.2 Numeric_STD Library
To From Command std_logic_vectorunsigned std_logic_vector(uv) std_logic_vectorsigned std_logic_vector(sv) std_logic_vectorinteger std_logic_vector(to_unsigned(int, length)) std_logic_vector(to_signed(int, length)) unsigned std_logic_vectorunsigned(slv) unsigned signed unsigned(sv) unsigned integer to_unsigned(int, length) signed std_logic_vectorsigned(slv) signed unsigned signed(uv) signed integer to_signed(int, length) integer std_logic_vectorto_integer(unsigned(slv)) to_integer(signed(slv)) integer unsigned to_integer(uv) integer signed to_integer(sv)
21.3.3 STD_logic_arith Library
To From Command std_logic_vectorunsigned conv_std_logic_vector(uv, length) std_logic_vectorsigned conv_std_logic_vector(sv, length) std_logic_vectorinteger conv_std_logic_vector(int, length) unsigned std_logic_vectorunsigned(slv) unsigned signed conv_unsigned(sv, length) unsigned integer conv_unsigned(int, length) signed std_logic_vectorsigned(slv) signed unsigned conv_signed(uv, length) signed integer conv_signed(int, length) integer std_logic_vectorconv_integer(unsigned(slv)) conv_integer(signed(slv)) integer unsigned conv_integer(uv) integer signed conv_integer(sv)
21.3. Conversion 200 Zawiki, Release v0.11-30-g7307413
21.3.4 Conversions std_logic & std_ulogic std_logic and std_ulogic are compatible and can be assigned without cast. The same for an element of a subtype of std_logic or std_ulogic sl <= sul; sl <= slv(0); sl <= sulv(1); sl <= uv(2); sl <= sv(3); sul <= sl; sul <= slv(0); sul <= sulv(1); sul <= uv(2); sul <= sv(3);
std_logic_vector & std_ulogic_vector std_logic_vector and std_ulogic_vector are compatible and can be assigned without cast. slv(1 downto 0) <= std_logic_vector(sulv(1 downto 0)); sulv(1 downto 0) <= std_ulogic_vector(slv(1 downto 0)); slv(0) <= sl; slv(1) <= sul; slv(2) <= sv(2); slv(3) <= uv(3); slv <= std_logic_vector(uv); slv <= std_logic_vector(sv); slv <= std_logic_vector(to_unsigned(int, slv'length)); slv <= std_logic_vector(to_signed(int, slv'length));
Integer
-- Numeric_Std Conversions int <= to_integer(unsigned(slv)); int <= to_integer(signed(slv)); int <= to_integer(uv); int <= to_integer(sv);
-- Std_Logic_Arith Conversions int <= conv_integer(unsigned(slv)); int <= conv_integer(signed(slv)); int <= conv_integer(uv); int <= conv_integer(sv);
21.3. Conversion 201 Zawiki, Release v0.11-30-g7307413
Integer <=> Real int <= integer(real_s); real_s <= real(int);
Unsigned uv(0) <= sl; uv(0) <= sul; uv <= unsigned(slv); uv <= unsigned(sv);
-- Numeric_Std Conversions uv <= to_unsigned(int, uv'length); -- Std_Logic_Arith Conversions uv <= conv_unsigned(int, uv'length); uv <= conv_unsigned(sv, uv'length);
-- Conversion without modification -- Signed => Unsigned -- 15 => 15 -- 0 => 0 -- - 1 => 31 -- -16 => 16 uv <= unsigned(sv);
-- Conversion with MSB inverting -- Signed => Unsigned -- 15 => 31 -- 0 => 16 -- - 1 => 15 -- -16 => 0 uv <= unsigned( not(sv(sv'high)) & sv(sv'high-1 downto 0);
Signed sv <= signed(slv); sv <= signed(uv);
-- Numeric_Std Conversions sv <= to_signed(int, sv'length); -- Std_Logic_Arith Conversions sv <= conv_signed(int, sv'length); sv <= conv_signed(uv, sv'length);
21.3. Conversion 202 Zawiki, Release v0.11-30-g7307413
21.3.5 Resize
Resize Unsigned
Listing 1: ieee unsigned resize library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; ... signal uv_1 : unsigned(2 downto 0); signal uv_2 : unsigned(4 downto 0); ... uv_1 <= resize(uv_2,uv_1'length);
Listing 2: synopsys unsigned resize library ieee ; use ieee.std_logic_1164.all ; use ieee.std_logic_arith.all ; use ieee.std_logic_unsigned.all ; ... signal uv_1 : unsigned(2 downto 0); signal uv_2 : unsigned(4 downto 0); ... uv_1 <= conv_unsigned(uv_2,uv_1'length);
Resize Signed
Listing 3: ieee signed resize library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; ... signal sv_1 : signed(2 downto 0); signal sv_2 : signed(4 downto 0); ... sv_1 <= resize(sv_2,sv_1'length);
21.3. Conversion 203 Zawiki, Release v0.11-30-g7307413
Listing 4: synposys signed resize library ieee ; use ieee.std_logic_1164.all ; use ieee.std_logic_arith.all ; use ieee.std_logic_unsigned.all ; ... signal sv_1 : signed(2 downto 0); signal sv_2 : signed(4 downto 0); ... sv_1 <= conv_signed(sv_2,sv_1'length);
21.4 Examples
• Blinker – Settings • BRAM – Definition ∗ ROM Definition ∗ RAM Definition – Initialisation ∗ MIF-File ∗ HEX-File · Format · Example ∗ Binary-File ∗ In VHDL ∗ Syntesis Tool limitation · Port limitation · Initialisation limitation • Debounce • Reset Input • Pseudo Random Number Generator – Background – Generics
21.4. Examples 204 Zawiki, Release v0.11-30-g7307413
21.4.1 Blinker
Many time you want to implement a Led blinking at a given event. The problem is that the available signal is either tool long or (mostly) too short to be seen for a led. Therefore this bloc was created to let a led blink on an event of a signal.
Settings
• Set your clockFrequency , according to that a blink of 500ms will be calculated. • Choose your mode – mode 0: rising edge reaction – mode 1: falling edge reaction
Mode = 0 (reactive on rising edge) ______input ____/ ______output ____/ \______time 0s 0.5s 1s
_ input ____/ \______output ____/ \______time 0s 0.5s 1s
Mode = 1 (reactive on falling edge) _____ input \______output ______/ \______time 0s 0.5s 1s
_ input ____/ \______output ______/ \______time 0s 0.5s 1s
See also: config repo blink
21.4.2 BRAM
See also: config repo bram To generate RAM and ROM using the BRAM’s available in the FPGA, several methods can be used. • For Xilinx you can use the CoreGen Program and for Actel the Libero IDE • Write VHDL code which the synthesis tool can understand The advantage of the second method is that it’s target independent, but however it de- pends on the functionalities of the Synthesis tool.
21.4. Examples 205 Zawiki, Release v0.11-30-g7307413
Figure1: BRAM
Definition
ROM Definition
Single Port ROM with VHDL initialisation See also: config repo rom.vhd
RAM Definition
Dual-Port RAM with synchronous Read (Read Through) with no initialisation See also: config repo dp_ram_1.vhd Generic Dual-Port RAM (Write First) with two clocks, enables and write enables and initialisation with a binary file See also: config repo dp_ram_2.vhd
Initialisation
MIF-File
An ASCII text file (with the extension .mif) that specifies the initial content of a memory block (CAM, RAM, or ROM), that is, the initial values for each address. A MIF contains the initial values for each address in the memory. A separate file is required for each memory block. In a MIF, you are also required to specify the memory depth and width values. In addition, you can specify the radixes used to display and interpret addresses and data values.
21.4. Examples 206 Zawiki, Release v0.11-30-g7307413
HEX-File
Intel HEX is a file format for conveying binary information for applications like program- ming microcontrollers, EPROMs, and other kinds of chips. It is one of the oldest file formats available for this purpose, having been in use since the 1970s.
Format
Start code The Start code exist only once per line at it’s beginning. The Start code is : Byte count The Byte count indicates the number n of Raw Data bytes there are in the Data field. Address 16bit Address of the Data. If more Address bits are needed see Record Type 04. Record type There are six possible Record type: • 00: data record, contains data and 16-bit address. • 01: End Of File record. Must occur exactly once per file in the last line of the file. The byte count is 00 and the data field is empty. Usually the address field is also 0000,in which case the complete line is :00000001FF. Originally the End Of File record could contain a start address for the program being loaded, e.g. :00AB2F0125 would cause a jump to address AB2F.
:00000001FF
or
:020000010000FD
• 02: Extended Segment Address Record, segment-base address (two hex digit pairs in big endian order). Used when 16 bits are not enough, identical to 80x86 real mode addressing. The address specified by the data field of the most recent 02 recordis multiplied by 16 (shifted 4 bits left) and added to the subsequent 00 record addresses. This allows addressing of up to a megabyte of address space. The address field of this record has to be 0000, the byte count is 02 (the segment is 16-bit). The least significant hex digit of the segment address is always0. • 03: Start Segment Address Record. For 80x86 processors, it specifies the initial content of the CS:IP registers. The address field is 0000, the byte count is 04, the first two bytes are the CS value, the latter two are the IP value. • 04: Extended Linear Address Record, allowing for fully 32 bit addressing (up to 4GiB). The address field is 0000, the byte count is 02. The two data bytes (twohex digit pairs in big endian order) represent the upper 16 bits of the 32 bit address for all subsequent 00 type records until the next 04 type record comes. If there is not a 04 type record, the upper 16 bits default to 0000. To get the absolute address for subsequent 00 type records, the address specified by the data field of the most recent 04 record is added to the 00 record addresses. • 05: Start Linear Address Record. The address field is 0000, the byte count is 04. The 4 data bytes represent the 32-bit value loaded into the EIP register of the 80386 and higher CPU.
21.4. Examples 207 Zawiki, Release v0.11-30-g7307413
Data Raw Data of n bytes (n = Bytecount) at the given address in Hexadecimal format. Checksum The Checksum is two hex digits - the least significant byte of the two’s complement of the sum of the values of all fields except fields 1 and 6 (Start code “:” byte and twohex digits of the Checksum). It is calculated by adding together the hex-encoded bytes (hex digit pairs), then leaving only the least significant byte of the result, and making a2’s complement (either by subtracting the byte from 0x100, or inverting it by XOR-ing with 0xFF and adding 0x01).
Example
: 10 0100 00 214601360121470136007EFE09D21901 40 : 10 0110 00 2146017EB7C20001FF5F160021480119 88 : 10 0120 00 194E79234623965778239EDA3F01B2CA A7 : 10 0130 00 3F0156702B5E712B722B732146013421 C7 : 00 0000 01 FF
Binary-File
An ASCII text file (with the extension .bin) that specifies the initial content of a memory block (CAM, RAM, or ROM), that is, the initial values for each address. This is the ini- tialisation file used in the BRAM-VHDL examples. The file location has to be given inthe generic called initFile. The file is witten in ASCII-binary format and one line hastobe one line of the BRAM with the exact number of databits. Also each BRAM address has to be initialised in this file. An example of an 16 databit and 3 addressbit RAM
0000000000000000 0000000000000001 0000000000000010 0000000000000011 0000000000000100 0000000000000101 0000000000000110 0000000000000111
In VHDL
In order to initialise the BRAM you can also edit the VHDL code directly and initialise your Memory signal.
signal ROM : rom_type := (X"0200A",X"00300",X"08101",X"04000",X"08601",X"0233A", X"00300",X"08602",X"02310",X"0203B",X"08300",X"04002", X"08201",X"00500",X"04001",X"02500",X"00340",X"00241", X"04002",X"08300",X"08201",X"00500",X"08101",X"00602", X"04003",X"0241E",X"00301",X"00102",X"02122",X"02021", X"00301",X"00102",X"02222",X"04001",X"00342",X"0232B", X"00900",X"00302",X"00102",X"04002",X"00900",X"08201", X"02023",X"00303",X"02433",X"00301",X"04004",X"00301", X"00102",X"02137",X"02036",X"00301",X"00102",X"02237", X"04004",X"00304",X"04040",X"02500",X"02500",X"02500", X"0030D",X"02341",X"08201",X"0400D"); (continues on next page)
21.4. Examples 208 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
Restrictions
There are cetain restriction if you write BRAM’s in VHDL
Syntesis Tool limitation
The VHDL Code for creating BRAM is read and understood by the synthesis tool. The mentioned code was tested in Xilinx XST Syntesis Tool. It has to be verified for other Synthesis tools like Simplify or Leonardo. The following limitaions are due the use of Xilinx XST.
Port limitation
The BRAM’s defined in VHDL can have multiple Read ports, but only ONE Write port.
Initialisation limitation
The BRAM can only with the described Binary file format be initialised. The Synthesis tools doesn’t support read and parsing files. Therefore a hex or mif file format cannotbe used.
21.4.3 Debounce
Each button can bounce while pushing or releasing. This can’t completely eliminated. but to avoid button bouncing. The following two thing can be done. • Buy high quality buttons • Implement a button debouncing Settings First the max bounce time should be measured and according to that value and your used clock, the counterBitNb can be choosen accordingly. The following implemen- tation has two different modes. Mode 0 is reactive on rising edge and mode 1 is reactive on falling edge.
Mode 0 ______input ____/ \ / \ / \_/ \ / \______output ____/ \_
Mode 1 ______input ____/ \ / \ / \_/ \ / \______output ______/ \______
See also: config repo debounce
21.4. Examples 209 Zawiki, Release v0.11-30-g7307413
21.4.4 Reset Input
For having a stable system first you need a proper reset. Just using an input as reset isn’t enough. Here’s how to poperly synchronize your reset.
--pad_rst----+------+------+ +--+--+ +--+--+ +--+--+ +-. --'1'-----|D Q|----|D Q|----|D Q|----| >O-----rst | | | | | | +-´ +--|> | +--|> | +--|> | | +-----+ | +-----+ | +-----+ --clk--+------+------+
Listing 5: blink LIBRARY ieee; USE ieee.std_logic_1164.all; USE ieee.numeric_std.all;
ENTITY rst_synchronizer IS PORT( pad_rst_n : IN std_logic; clock : IN std_ulogic; reset : OUT std_ulogic ); END rst_synchronizer ;
ARCHITECTURE rtl OF rst_synchronizer IS
signal lvec_rst_n : std_ulogic_vector(2 downto 0);
BEGIN
process(pad_rst_n , clock) begin if pad_rst_n = '1' then lvec_rst_n <= (others => '0'); elsif rising_edge(clock) then lvec_rst_n <= lvec_rst_n(1 downto 0) & '1'; end if; end process; rst <= not lvec_rst_n(2); END ARCHITECTURE rtl;
21.4.5 Pseudo Random Number Generator
See also: config repo blink This VHDL module uses 2 Linear Feedback Shift Registers (LFSR) with polynomials for maximal sequence length, one of which is scalable to output word size (4bit - 24bit) and one to operate as a non-uniform duty cycle clock. The module gives the user 4 op- tions for output distribution types, Gaussian unimodal, bimodal, uniform, and non-uniform distributions. These distributions are created by altering a scalable LFSR output by clock- ing the output irregularly with a non-uniform clock, shifting scaled outputs into a buffer- adder-tree to effectively use the central limit theorem to create a normal distribution, and a feedback loop to further shape the distributions. Sample histograms are included in the figures following. The prng.vhd module is verified in a test bench by writing outthe pseudo-random values to a file. This data can be entered into one’s favorite statistical analysis software package for verification.
21.4. Examples 210 Zawiki, Release v0.11-30-g7307413
Background
The LFSR is a shift register of arbitrary length that takes its input based off a linear func- tion derived from the previous state. This function is chosen to provide a maximally long sequence. As the output-width is scaled, a different LFSR is built with a polynomial to provide maximal length. The polynomials used are commented in the VHDL module.
Generics
Generic Type Range Description g_W Integer 28 - 4 Number of output vector bits g_V Integer 24 - 18 Non uniforming clocking bits g_G_TYPE Integer Gaussion Distri- bution Type for 0 = uniform o_g_noise 1 = bimodal
g_U_TYPE Integer Uniform Distri- bution Type for 0 = uniform o_u_noise 1 = ave-uniform
Signal Size Description iCLK_clk 1 input clock signal iGRS_reset_n 1 input reset signal i_enable 1 enable prn generation o_g_noise [g_W-1:0] gaussian distibution output o_u_noise [g_W-1:0] uniform distribution output
21.5 File
• Reading File • Writing File type file_open_kind is ( read_mode, write_mode, append_mode );
21.5. File 211 Zawiki, Release v0.11-30-g7307413
21.5.1 Reading File
The below code reads a set of binary numbers from the file named read.txt and put them into a 4 bit std_logic_vector signal.
Listing 6: read file LIBRARY ieee; use ieee.std_logic_1164.ALL; use STD.textio.all;
------Declare empty entity -- ENTITY read_file IS END read_file;
------Declare architecture -- ARCHITECTURE behaviour OF read_file IS
constant FILE_NAME : string := "C:\read.txt"; signal bin_value : std_logic_vector(3 downto 0):="0000";
BEGIN
------Read Process -- process file file_pointer : text; variable line_content : string(1 to 4); variable line_num : line; variable j : integer := 0; variable char : character:='0'; begin -- Open the file read.txt from the specified location for reading(READ_MODE) file_open(file_pointer,FILE_NAME,READ_MODE);
-- Continue reading until EOF while not endfile(file_pointer) loop -- Read the whole line from the file readline (file_pointer,line_num); -- Read the contents of the line from the file into a variable READ(line_num,line_content); -- For each character in the line convert it to binary value -- And then store it in a signal named 'bin_value' for j in 1 to 4 loop char := line_content(j); if(char = '0') then bin_value(4-j) <= '0'; else bin_value(4-j) <= '1'; end if; end loop; -- After reading each line wait for 10ns wait for 10 ns; end loop;
-- After reading all the lines close the file file_close(file_pointer); (continues on next page)
21.5. File 212 Zawiki, Release v0.11-30-g7307413
(continued from previous page) wait; end process; end behaviour;
A simulation of the reading:
read_file.vhd
21.5.2 Writing File
The code below writes is used to writing a file. It writes binary values from 0000 to 1111.
Listing 7: write file LIBRARY ieee; use ieee.std_logic_1164.ALL; use ieee.std_logic_arith.ALL; use STD.textio.all;
------Declare empty entity -- ENTITY write_file IS END write_file;
------Declare architecture -- ARCHITECTURE behaviour OF write_file IS
constant FILE_NAME : string := "C:\write.txt";
BEGIN
------Write Process -- process file file_pointer : text; variable line_content : string(1 to 4); variable bin_value : std_logic_vector(3 downto 0); variable line_num : line; variable i,j : integer := 0; variable char : character:='0'; begin -- Open the file write.txt from the specified location for writing(WRITE_MODE) file_open(file_pointer, FILE_NAME, WRITE_MODE);
-- We want to store binary values from 0000 to 1111 in the file for i in 0 to 15 loop bin_value := conv_std_logic_vector(i,4); -- convert each bit value to character for writing to file for j in 0 to 3 loop if(bin_value(j) = '0') then line_content(4-j) := '0'; else (continues on next page)
21.5. File 213 Zawiki, Release v0.11-30-g7307413
(continued from previous page) line_content(4-j) := '1'; end if; end loop;
-- write the line write(line_num,line_content);
-- write the contents into the file writeline (file_pointer,line_num); -- wait for 10ns after writing the current line wait for 10 ns; end loop;
-- Close the file after writing file_close(file_pointer); wait; end process; end behaviour; write_file.vhd
21.6 Programming Guidelines
21.6.1 Rules
Entity ports
• Use only modes IN and OUT in the port of sub-blocks, INOUT mode too only in the port of the top-level entity • Use only signal types STD_LOGIC and STD_LOGIC_VECTOR, INTEGER, UNSIGNED, SIGNED • Signals in the port of the entity should be grouped as follows: • Resets • Clocks • Signals of group A • Signals of group B • Signals of group C • … • Signals inside a group should be further grouped as follows: – Control inputs – Data inputs – Outputs
21.6. Programming Guidelines 214 Zawiki, Release v0.11-30-g7307413
Architecture
Architecture name should be one of following rules:
Architecture Name Description behavioral Implies physical logic, does not compile with RTL tool rtl Implies physical logic, compiles with RTL tools struct Implies physical connections, but not any logic gate Gate level netlist simulation Simulation mode testbench Test bench
Signals
• Direction of bits in STD_LOGIC_VECTOR, UNSIGNED and SIGNED is always DOWNTO • Size of the vector should be parameterized • Usually the least significant bit is numbered as zero • Use package numeric_std for arithmetic operations
Important: Never mix these libraries library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; library ieee ; use ieee.std_logic_1164.all ; use ieee.std_logic_arith.all ; use ieee.std_logic_unsigned.all;
Processes
Label every process
Listing 8: async_process.vhd processname: process(all) begin Do something here; end process;
Synchronous process
Synchronous process is sensitive only to reset and clock • Clock event is always to the rising edge • All control registers must be initialized in reset
21.6. Programming Guidelines 215 Zawiki, Release v0.11-30-g7307413
Listing 9: sync_process.vhd processname: process(reset, clock) begin if reset = '1' then reset <= assignemts; elsif rising_edge(clock) then rising_edge_clock <= assigments; end if; end process;
Asynchronous process
• Include all process input signals in the sensitivity list • Complete if-clauses must be used, all cases defined • Signals are assigned in every branch
Listing 10: async_process.vhd processname: process(all) begin async_logic <= assignment; end process;
21.6.2 Naming Conventions
Constant
This convention applies to all constants. The names must be in capital letter,are com- posed as follows:
Type Convention Example Generic g_
Constant c_
21.6. Programming Guidelines 216 Zawiki, Release v0.11-30-g7307413
Global Signals
This convention must be applied to physical ports of components or function blocks and global variables in QSYS components and pin names at top-level. The names are composed as follows: __[_n][_#] Examples: • avs_JetMapping_data • pad_Ethernet2_reset_n Valid Values for Interface Types
Value Meaning Apply to avs Avalon-MM Slave QSys components avm Avalon-MM Maser QSys components aso Avalon-ST Source QSys components asi Avalon-ST Sink QSys components cso Clock output QSys components csi Clock input QSys components coe Conduit QSys components inr Interrupt receiver QSys components ins Interrupt sender QSys components ncm Nios II custom instruction master QSys components ncs Nios II custom instruction slave QSys components rsi Reset sink QSys components rso Reset source QSys components tcm Avalon-TC master QSys components tcs Avalon-TC slave QSys components pad Physical pad Top-level entity
Ports Signals
This convention applies to internal ports (signals across the hierarchy). The names are composed as follows:
21.6. Programming Guidelines 217 Zawiki, Release v0.11-30-g7307413
Value Meaning Example [i]GCK Global Clock signal iGCK_clk_in_100 : in std_ ,→logic; [i]GRS Global Reset signal iGRS_reset_n : in std_ ,→logic; [i,o]CLK Internal Clock signal iCLK_pll_clk_25 : in std_ ,→logic; [i,o]RST Internal Reset signal oRST_enet_reset_n: out␣ ,→std_logic; [i,o]
Local Signals
This convention applies to local signals only. The names are composed as follows: l_[_n][_#] Valid Values for Interface Types
21.6. Programming Guidelines 218 Zawiki, Release v0.11-30-g7307413
Value Meaning Example sig Local signal lsig_cnt_en : std_logic
vec Local vector lvec_cnt : std_logic_ ,→vector(1 DOWNTO 0); lvec_cnt : unsigned(1␣ ,→DOWNTO 0); lvec_cnt : signed(1␣ ,→DOWNTO 0); ary Local Array type logic_array is␣ ,→array (0 to 1) of std_ ,→logic; signal lary_logics :␣ ,→logic_array; int Local integer signal lint_pixel_pos_ ,→cnt : integer range 0␣ ,→to 2; var Local variable variable lvar_load_new_ ,→pix_data_set : std_ ,→logic;
Alias
An alias creates an alternative name for an existing object. It does not create a new object. For these reasons no specific naming conventions are established so far. Example: signal instruction : std_logic_vector(15 downto 0); alias opcode : std_logic_vector(3 downto 0) is instruction(15 downto 12);
21.6.3 IP Reusability
• The IP specification lists the requirements and details the feature set, performance expectations, size, usage model, etc. Not all design blocks need to be reusable, the specification must state whether a design is being architected as a reusable block. • The specification has been officially reviewed by all interested parties. This increases the likelihood that the design block can be reused elsewhere in the company. • Existing libraries of components have been reviewed to identify if existing IP with similar functionality already exists, i.e. practice reuse in the development process. • The IP core name follows your company’s naming conventions. The name of the core should be description of designs function, e.g. AXI4 Clock Crossing Bridge. • Signal and parameter naming conventions are followed. Signal and parameter names should be descriptive of the functionality. This makes it easier for end users to un- derstand the impact of these parameters and signals on the design block.
21.6. Programming Guidelines 219 Zawiki, Release v0.11-30-g7307413
• The IP core has default parameter values. Parameters provide the simplest way to create reusable design blocks. IP features, ports and functionality can all be parame- terized for maximum flexibility. The default values should be the most common usage model for the design block. • The IP uses standard interfaces. Adopt a common interface protocol on all of IP. The use of standard interfaces simplifies the interconnection and management of functional blocks that make up a design. It ensures compatibility between IP blocks from different design teams, simplifies the integration of individual design blocksinto a full system design and enables “plug and play” interoperability of IP. • The IP core meets the timing specification and all timing violations have been ad- dressed. The IP core includes a full set of timing constraints. • The IP passes LINT tests per your company’s established coding rules. It is recom- mended that you invest in a LINT to enforce coding guidelines and that it is fully integrated with version control/design check in process. • The verification of the IP meets the functional, assertion, and line coverage goalsas specified in the test plan. Note that the test plan should be developed atthesame time as the functional specification for the design. • The IP is adequately tested to cover the parameterization space and both expected and unexpected data patterns. Users of IP tend to be suspicious of other peoples design. There’s nothing gained in debugging someone else’s code. • Provide a user interface and/or script for end users to instantiate the IP in their de- sign. The interface should make it easy for the user to understand any applicable constraints. At a minimum, the IP should come with a documented command-line script that enables users to pass values to the parameters in the IP. Ideally it should come with a simple graphical user interface (GUI) to help users get started (see Fig- ure 1). • Design files and all packaging files adhere to your company’s standard version-control directory structure. If users know where the applicable files are located, it provides the user with confidence that the designer of the IP has thought through the process of reuse. • Testbench and reference designs are available for use with the core. This is a “nice to have” feature that provides new users an easy way to get started with a design. • IP cores, example designs and test benches can be simulated in company simulators. Users should be able to run the scripts and see the basic functionality of the design. • Release notes detail all supported devices, FPGA device families, and versions of the EDA tools used on the design.
21.7 SDC Constraints
• Intel SDC Constraint Manual
21.7. SDC Constraints 220 Zawiki, Release v0.11-30-g7307413
21.7.1 Comment
# This is a comment
21.7.2 New line
No character allowed after newline \\ command_part_1 \\ command_part_2
21.7.3 Netlist Terminology
Term Definition Cell Device building block Pin I/O of cells (not FPGA I/O) Net Connection between Ports Port Top-level I/O
21.8 SDC Theory
• Path & Analysis Times • Timing Analysis – Launch edge & Latch edge – Setup & Hold – Data Arrival Time – Clock Arrival Time – Data Required Time (Setup) – Data Required Time (Hold) – Setup Slack – Hold Slack – Recovery & Removal ∗ Analyse Recovery & Removal
21.8. SDC Theory 221 Zawiki, Release v0.11-30-g7307413
21.8.1 Path & Analysis Times
3 types of paths: • Clock Paths • Data Paths • Asynchronous Path 2 types of analysis: • Synchronous : clock & data paths • Asynchronous : clock & async paths
Figure2: Paths
21.8. SDC Theory 222 Zawiki, Release v0.11-30-g7307413
21.8.2 Timing Analysis
Launch edge & Latch edge
• Launch Edge = edge which launches the data from the source register • Latch Edge = edge which latches the data from the destination register
Figure3: Launch & Latch Edge
Setup & Hold
• Setup Tsu = Minimum time data signal must be stable BEFORE clock edge
• Hold Th = Minimum time data signal must be stable AFTER clock edge
21.8. SDC Theory 223 Zawiki, Release v0.11-30-g7307413
Figure4: Setup & Hold
21.8. SDC Theory 224 Zawiki, Release v0.11-30-g7307413
Data Arrival Time
The time for data to arrive at destination register
Clock Arrival Time
The time for clock to arrive at destination registers clock input
Data Required Time (Setup)
Minimum time required before the latch edge, for the data to get latched into the desti- nation register
Setup_T ime = Clock_Arrival_T ime − tsu − Clock_Jitter
Data Required Time (Hold)
Minimum time required after the latch edge for the data to remain valid for successful latching into the destination register
Hold_T ime = Clock_Arrival_T ime + th + Clock_Jitter
Setup Slack
Margin by which the setup timing requirement is met.
Setup_Slack = Setup_T imemin − Data_Arrival_T imemax
Must always be positive
Hold Slack
Margin by which the hold timing requirement is met.
Hold_Slack = Data_Arrival_T imemin − Maximum_Hold_T imemax
Must always be positive
Recovery & Removal
• Recovery trec : Minimum time an asynchronous signal must be de-asserted BEFORE clock edge.
• Removal trem : Minimum time an asynchronous signal must be de-asserted AFTER clock edge.
21.8. SDC Theory 225 Zawiki, Release v0.11-30-g7307413
Figure5: Setup & Hold Time & Slack
21.8. SDC Theory 226 Zawiki, Release v0.11-30-g7307413
Analyse Recovery & Removal
In case of the Reset it should be synchron to the clock even when its use asynchronous. if rst = 1 then -- async rst, but still synch to clk q <= '0'; elsif rising_edge(clk) then q <= d; end if;
21.9 SDC Usage
• General – Collections – Priorities • Clock Constraints – Clock – Generated Clock – Derive PLL clocks – Automatic Clock Detection & Creation – FPGA Uncertainties (jitter, clock networks) – Virtual Clock example – Gated Clock • Input Constraints – Combinatorial (without FF) – Synchronous Inputs • Source Synchronous – SDR ∗ Center Aligned Clock ∗ Direct Clocking ∗ PLL Clocking ∗ Edge Aligned Clock – Data Input Constraints
21.9. SDC Usage 227 Zawiki, Release v0.11-30-g7307413
∗ Tco relative to data
∗ Tco relative to input clock • Output Constraints – Synchronous Outputs ∗ SO Calculations – Source Synchronous Outputs ∗ SSO Calculations • False Path – Asynchronous I/O constraints – Timing exceptions between clock domains – Synchronisation done through a dual-clock DC_FIFO – Clock groups • Multicycle Paths
21.9.1 General
Collections
To find certain Cells, Pins, Nets or Ports Collections, there are Wildcard enabled search commands. get_clocks get_registers get_ports get_pins all_clocks all_registers all_input all_output
Priorities
• Priority Order – set_false_path & set_clock_groups High Priority – set_max_delay & set_min_delay – set_multicycle_path – create_clock & create_generated_clock Low Priority • Sequential execution, last command will be executed if same priority • set_input_delay and set_output_delay are in addition and will not be overwritten be other sdc commands
21.9. SDC Usage 228 Zawiki, Release v0.11-30-g7307413
21.9.2 Clock Constraints
Two possible clocks: Clocks & Generated Clocks
Clock
Absolute or base clock (from Quartz internal or external) create_clock [-name
Generated Clock
Clocks derived from another clock (all other clocks) (PLL, clock divider, output clocks, ripple clocks) create_generated_clock [-name
21.9. SDC Usage 229 Zawiki, Release v0.11-30-g7307413
Derive PLL clocks derived_pll_clocks \\ # Altera specific for all PLL␣ ,→generated clocks [-create_base_clocks] \\ # generate create_clock constants for␣ ,→PLL input clocks [-use_net_name] # use net names as clock names # Substitute would be to create all generated clocks manually
Quartus can do the substitution automatically with the expand option enabled. No Altera specific commands used. tcl: write_sdc -expand
Automatic Clock Detection & Creation
Not to use for final design. Default clock used = 1GHz. derive_clocks [-period
FPGA Uncertainties (jitter, clock networks)
3 Types of uncertainties: • Intra-clock transfer : Transfer within single clock domain within FPGA • Inter-clock transfer : Transfer within different clock domains within FPGA • I/O interface clock transfer : Transfer between I/O port and internal design registers derive_clock_uncertainty # Altera specific [-overwrite] # overwrites any existing uncertainty␣ ,→constraints [-add] # adds derived uncertainty to existing␣ ,→constraints
# For Feedback clock, (feedback_clk_pcb = data_clk_pcb + data_pcb + $T_{co}\_ASSP$ set_clock_latency [-late] # max clock latency in case of feedback clock [-early] # min clock latency in case of feedback clock
21.9. SDC Usage 230 Zawiki, Release v0.11-30-g7307413
Virtual Clock example create_clock -period 10 -name clk_in [get_ports {clk_in}] create_clock -period 10 -name virt_clk_in set_input_delay -clock [get_clocks {virt_clk_in}] -max 2 [get_ports {data_in}] set_input_delay -clock [get_clocks {virt_clk_in}] -min 2 [get_ports {data_in}]
Gated Clock
An AND enable on the clock can serve to eliminate power consumption. All flip-flops use no energy without clock. But it violates synchronous design rules. It also uses a new Global Clock path for the Gated Clock.
21.9.3 Input Constraints
2 Types of Combinatorial Interfaces and Synchronous Inputs.
Combinatorial (without FF)
Absolute maximum and minimum time between points. Signals traversing FPGA and in- ternal signals set_max_delay [-from
Synchronous Inputs
Synchronous Inputs where one external clock is used between multiple devices. set_input_delay [-max] \\ # max time to arrive and still meet Tsu (input setup␣ ,→time) [-min] # min time to stay active and still meet Th (input hold␣ ,→time)
Calculations − input_delay_max = Data_tracemax Board_clock_skewmin + Tcomax − input_delay_min = Data_tracemin Boardclockskewmax + Tcomin
21.9. SDC Usage 231 Zawiki, Release v0.11-30-g7307413
set_input_delay -clock
21.9.4 Source Synchronous
Source Synchronous Interfaces where the FPGA reads a clock which is used created by an other device. Clock and Data send at the same time. • Single Data Rate (SDR) • Doube Data Rate (DDR) • Quatriple Data Rate (QDR) • High Speed SPI4.2
SDR e.g. MII, SPI
Center Aligned Clock
Data transitions not in phase with clock, clock is in the middle of the data change. Can directly be used without shift.
Direct Clocking
# Virtual Clock which create the data on other device create_clock -name virt_clk_in -period 8.000
# Received Clock but Center aligned which means 180° shifted (no phase command␣ ,→only waveform). # Allows to shift clock by half a period create_clock -name clk_in period 8.000 -waveform {4.0 8.0} [get_ports clk_in]
PLL Clocking
Add PLL clocking or DLL to add shift to have the same input delay between data and clock. Needed for High speed (>125MHz)
# Virtual Clock which create the data on other device create_clock -name virt_clk_in -period 8.000
# Received Clock but Center aligned which means 180° shifted (no phase command␣ ,→only waveform). # Allows to shift clock by half a period (continues on next page)
21.9. SDC Usage 232 Zawiki, Release v0.11-30-g7307413
(continued from previous page) create_clock -name clk_in -period 8.000 -waveform {4.0 8.0} [get_ports clk_in] derive_pll_clocks # or create_generated_clocks -name int_clk -source [get_pins PLL|clk[0]]
Edge Aligned Clock
Data transitions at the same time at the clock. Clock need to be shifted 180° ** PLL Clocking ** Add PLL clocking or DLL to add shift to have the same input delay between data and clock. Needed for High speed (>125MHz)
# Virtual Clock which create the data on other device create_clock -name virt_clk_in -period 8.000
# Received Clock Edge Aligned therefor no need to shift create_clock -name clk_in -period 8.000 [get_ports clk_in] derive_pll_clocks # or create_generated_clocks -name int_clk -source [get_pins PLL|clk[0]] -phase 180␣ ,→[get_pins PLL_clk[0]]
Data Input Constraints
Tco relative to data
# create input delays set in_max_dly [expr $data_tracemax + $tcomax - $clk_tracemin] set in_max_dly [expr $data_tracemin + $tcomin - $clk_tracemax]
# input constraints set_input_delay -max $in_max_dly -clock virt_clk_in [get_ports data_in] set_input_delay -min $in_min_dly -clock virt_clk_in [get_ports data_in]
Tco relative to input clock
# create input delays set in_max_dly [expr $data_tracemax + $tco_datamax - $tco_clkmin - $clk_tracemin] set in_max_dly [expr $data_tracemin + $tco_datamin - $tco_clkmax - $clk_tracemax]
# input constraints set_input_delay -max $in_max_dly -clock virt_clk_in [get_ports data_in] set_input_delay -min $in_min_dly -clock virt_clk_in [get_ports data_in]
21.9. SDC Usage 233 Zawiki, Release v0.11-30-g7307413
21.9.5 Output Constraints
Synchronous Outputs
Synchronous Outputs where one external clock is used between multiple devices. set_output_delay [-max] \\ # max time to arrive and still meet other devices Tsu␣ ,→(input setup time) [-min] # min time to stay active and still meet other devices␣ ,→Th (input hold time)
SO Calculations output_delay_max = Data_trace_{max} - Board_clock_skew_{min} + T_{su} output_delay_max = (T_{data_pcb_{max}} + T_{cl}) - (T_{clk2_{min}} - T_{clk1_ext_{max}}) + T_{su} output_delay_min = Data_trace_{min} - Board_clock_skew_{max} + T_{h} output_delay_min = (T_{data_pcb_{min}} + T_{cl}) - (T_{clk2_{max}} - T_{clk1_ext{min}}) + T_{h} set_output_delay -clock
Source Synchronous Outputs
Source Synchronous Outputs where the FPGA generates a clock which is used further in an other device. Clock and Data send at the same time. • Single Data Rate (SDR) • Doube Data Rate (DDR) • Quatriple Data Rate (QDR) • High Speed SPI4.2 set_output_delay [-max] \\ # max time to arrive and still meet other devices Tsu␣ ,→(input setup time) [-min] # min time to stay active and still meet other devices␣ ,→Th (input hold time)
21.9. SDC Usage 234 Zawiki, Release v0.11-30-g7307413
SSO Calculations output_delay_max = Data_trace_{max} - Clock_trace_{min} + T_{su} output_delay_min = Data_trace_{min} - Clock_trace_{max} + T_{h} set_output_delay -clock
21.9.6 False Path
2 Types of False Path: • Logic-based: Not relevant circuit operation (static, quasi-static) • Timing-based: Path intentionally not analysed (bridging async clock domain using synchronizer circuits) 2 Methods: • set_false_path: disable timing analysation for a certain path or collection • set_clock_group: don’t look at clock domain crossing between one, or mor clocks set_false_path [-fall_from
Asynchronous I/O constraints
Path to ignore by the Timing Analyzer. set_false_path -from [get_ports ext_rst_n] # input set_false_path -from [get_ports button*] # input set_false_path -to [get_ports led*] # output
21.9. SDC Usage 235 Zawiki, Release v0.11-30-g7307413
Timing exceptions between clock domains
Path to ignore by the Timing Analyzer. Clock domain crossing if double FF synchronisation. set_false_path -from [get_pins reg1|clk] -to [get_pins reg2|d]
Synchronisation done through a dual-clock DC_FIFO
Path to ignore by the Timing Analyzer. set_false_path -from [get_clocks ext_clk50mhz] -to [get_clocks {i_PLL|altpll_ ,→component|auto_generated|pll1| clk[0]}]
Clock groups
Muxed clocks
# clocks are separate, no cross domain analyzation set_clock_groups -exclusive -group {clk_100} -group {clk_66}
# same as set_false_path -from {get_clocks clk_100} -to {get_clocks clk_66 set_false_path -from {get_clocks clk_66} -to {get_clocks clk_100}
21.9.7 Multicycle Paths
If a signal is slow and not sampled every clock edge. 2 Types possible: • Clock enable signal not every time – Should be avoided and replaced by pipeline FlipFlops to cut logic path. • 2 shifted clocks between 2 registers – TimeQuest can used the false Latch edge, Multicycle for correct this setting How To: • Determine Launch to Latch relationship – With help of the TimeQuest Waveforms • Fix Setup (because Hold changes with setup) • Fix Hold Open Window • start setup increment = edges before on source clock • end setup increment = edge after on destination clock • start hold increment = edges after on source clock • end hold increment = edge before on destination clock set_multicycle_path [-start | -end] # start = change launch clock | end =␣ ,→change latch clock [-setup | -hold] # setup hold edge [-fall_from
21.9. SDC Usage 236 Zawiki, Release v0.11-30-g7307413
(continued from previous page) [-from
# 2 cycles for signal (case clock enable) set_multicycle_path -from {get_pins reg1|clk} -to {get_pins reg2|d} -setup 2 set_multicycle_path -from {get_pins reg1|clk} -to {get_pins reg2|d} -hold 1 # 1 +␣ ,→**1** clock before setup
# default 1 cycle signal (case clock enable) set_multicycle_path -from {get_pins reg1|clk} -to {get_pins reg2|d} -setup 1 set_multicycle_path -from {get_pins reg1|clk} -to {get_pins reg2|d} -hold 0
# 2 cycles for signal (case shifted clock) set_multicycle_path -from {get_pins reg1|clk} -to {get_pins reg2|d} -setup 2 set_multicycle_path -from {get_pins reg1|clk} -to {get_pins reg2|d} -hold 0 # 1␣ ,→clock before setup
21.10 Libraries
• Numeric Operations • IEEE • STD • Synopsys
21.10.1 Numeric Operations
Important: Never mix these Libraries!!! Use numeric_std - it’s the proper IEEE standard and is more recent. library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all;
-- Never mix these libraries library ieee ; use ieee.std_logic_1164.all ; use ieee.std_logic_arith.all ; use ieee.std_logic_unsigned.all ;
21.10. Libraries 237 Zawiki, Release v0.11-30-g7307413
21.10.2 IEEE
Standart IEEE Libraries can not be found in every tool because of their copyright notice. Nevertheless they can be downloaded from the IEE Webpage https://github.com/tschinz/config/tree/master/scripts/vhdl/libraries/ieee • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/math_ complex.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/math_real. vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/numeric_ bit.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/numeric_ std.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/std_logic_ 1164.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/std_logic_ arith.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/std_logic_ misc.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/std_logic_ signed.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/std_logic_ textio.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/ieee/std_logic_ unsigned.vhd
21.10.3 STD https://github.com/tschinz/config/tree/master/scripts/vhdl/libraries/std • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/std/standard. vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/std/textio.vhd
21.10.4 Synopsys https://github.com/tschinz/config/tree/master/scripts/vhdl/libraries/synopsys • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/synopsys/ arithmetic.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/synopsys/ attributes.vhd • https://github.com/tschinz/config/blob/master/scripts/vhdl/libraries/synopsys/types. vhd
21.10. Libraries 238 Zawiki, Release v0.11-30-g7307413
21.11 OSVVM
• Additional Documents
Stands for Open Source VHDL Verification Methodology.
21.11. OSVVM 239 Zawiki, Release v0.11-30-g7307413
21.11.1 Additional Documents
• Synth Works OSVVM • OSVVM at github • OSVVM Files • Doulos Guide
21.12 Simulation
• Configuring – Testbench – sim_main.do
21.12. Simulation 240 Zawiki, Release v0.11-30-g7307413
– Example – sim_wave.do – Launch simulation
Proposal of a simulation script system. All simulation files of a certain bloc can be found besides the src directory in the sim directory. It needs to have at least 4 files
Filename Description
21.12.1 Configuring
Testbench
First configure the testbench accordingly to your simulation. • Constants • Generics • Sequence • etc… sim_main.do
The sim_main.do contains a user defined part and the rest will be the same for ever test- bench. You only need to change the user changable part (see below).
21.12. Simulation 241 Zawiki, Release v0.11-30-g7307413
Variable Description Example work_path Path for all intermediate C:/temp files. Can be anywhere, best is in a temporary folder sim_path Path of the project sim C:/Projects/Calmar/... folder you want to simulate /.../.../sim wave_file wave file to load after com- sim_wave_all.do pilation sim_time simulation time 10 ms, 10 us, 10 sec, -all file_list see below list of all files to compile. Relative to the sim directory Libraries Subfiles Mainfiles Testbenchfiles
toplevel Name of toplevel bloc interpolator_tb (Main Testbench bloc)
Example
Listing 11: sim_main.do
1 #------2 # User changable parameters 3 # -- 4 set work_path C:/temp/ricoh/ri_gen5/interpolator/work 5 set sim_path c:/Projects/CALMAR/Ricoh/2_FPGA/RI_GEN5/ip/interpolator/sim 6 set wave_file sim_wave.do 7 set sim_time "5 ms"
8
9 # filelist according to $simpath 10 set file_list { 11 ../Interpolator_defs_pkg.vhd
12
13 ../PulseGenerator.vhd 14 ../RampCounter.vhd 15 ../HwEncoder.vhd 16 ../Interpolator.vhd
17
18 Interpolator_tb.vhd 19 }
20
21 # Set toplevel entity 22 set toplevel interpolator_tb 23 # -- 24 # END User changable parameters 25 #------
21.12. Simulation 242 Zawiki, Release v0.11-30-g7307413 sim_wave.do
There can be a lot of different wvaeform files. In the sim_main.do you need to specify which one should be used. The waveform file needs to be created with modelsim. • Add all the waves you want • Configure the for each signal and it’s display parameters • Save the waveform file in the sim directory
Launch simulation
• Open Modelsim and enter the following
do C:/Projects/Calmar/location/to/you/folder/sim/sim_script.do
• After compilation there will be a question in modelsim console to start the simulation.
# Launch Simulation
21.13 Syntax
• Types – Records ∗ Multiple record example – Integer – Time – STD_(U)logic – STD_(U)logic_vector – Unsigned – Signed • Operators – Resulting size • Functions – Edge finding – Conversion – Resize • Procedure • Signal – Attributes • Statements – If – Case
21.13. Syntax 243 Zawiki, Release v0.11-30-g7307413
– With Select – When – For • Fixed & Floating Point Types • Fixed Point Types • Floating Point Types
You can also find nice comprehensive VHDL papers and courses at: http://www. synthworks.com
21.13.1 Types
Typename Possible Value(s) Package boolean true, false standard std_ulogic U, X, 0, 1, Z, W, L, H, - std_logic_1164 std_ulogic_vector array of std_ulogic std_logic_1164 std_logic resolved std_ulogic std_logic_1164 std_logic_vector array of std_logic std_logic_1164 unsigned 1 to 22(n) − 1 numeric_std std_logic_arith signed −2(n−1) to2(n−1) −1 (2nd Complement) numeric_std std_logic_arith integer −2147483648 to 2147483647 (32bit) standard real −1.0E38 to 1.0E38 standard time 1 fs to 1 hr standard character 191 / 256 characters standard string array of character standard
Records
21.13. Syntax 244 Zawiki, Release v0.11-30-g7307413
Listing 12: record -- record declaration type reg_type is record irq : std_logic; pend : std_logic_vector(0 to 7); mask : std_logic_vector(0 to 7); end record;
-- signal of declared record signal r, rin : reg_type;
Multiple record example
Listing 13: m_record type value_type is record holdtime : time; filename : string(1 to 100); value : integer; end record; type command_type is record action : std_logic_vector(1 downto 0); value : value_type; busy : std_logic; end record; constant init_value_type : value_type := (1 ps, (others => ' '), 0); constant init_command_type : command_type := ((others => '0'), init_value_type, '0 ,→');
Integer
Listing 14: type integer type integer is range -2147483648 to 2147483647 -- max 32bit subtype natural is range 0 to integer'high -- max 32bit subtype positive is range 1 to integer'high -- max 32bit signal int_free : integer; -- 32bit wide integer signal int_5bit : integer range -16 to 15; -- 5bit integer
Time
21.13. Syntax 245 Zawiki, Release v0.11-30-g7307413
Listing 15: type time type time is range -2147483648 to 2147483647 -- neg also possible
STD_(U)logic
Listing 16: type std -- std_ulogic -- only one driver per signal type std_ulogic is ('U', -- Unitialized 'X', -- Forcing Unknown '0', -- Forcing 0 '1', -- Forcing 1 'Z', -- High Impedance 'W', -- Weak Unknown 'L', -- Weak 0 'H', -- Weak 1 '-', -- Don't care -- std_logic = resolved std_ulogic -- allows more than one driver for Bidirectional busses subtype std_logic is resolved std_ulogic;
STD_(U)logic_vector
Listing 17: type std_vector type std_ulogic_vector is array (natural range <>) of std_ulogic; type std_logic_vector is array (natural range <>) of std_logic; std_logic_vector_sig <= "11"; -- 3
Unsigned
Listing 18: type unsigned type unsigned is array (natural range <>) of std_logic; unsigned_sig <= "11"; -- 3 unsigned_sig <= unsigned_sig + unsigned_sig; + integer_sig;
Signed
Listing 19: type signed type signed is array (natural range <>) of std_logic; signed_sig <= "11"; -- -1 signed_sig <= signed_sig + signed_sig; + integer_sig
21.13. Syntax 246 Zawiki, Release v0.11-30-g7307413
21.13.2 Operators
Operator Description Example Arithmetic + Addition y <= x + 1 - Substraction y <= x - 1 * Multiplication y <= x * 1 / Division y <= x / 1 ** Power / Potenz (2* *x'high DOWNTO 0) abs absolute Value mod Module rem rest of Division Just for vector types sla Arith shift left SHIFT_LEFT(BUS,nbr) sra Arith shift right SHIFT_RIGHT(Bus,nbr) sll Logic shift left (x sll 2) srl Logic shift right (x srl 2) Comparison = equal x = y /= inequal x /= y < smaller x < y > larger x > y <= smaller equal x <= y >= larger equal x >= y Logic Operation on std_logic and & x and y nand !& x nand y or or x or y nor not or x nor y xor (+) x xor y not ~ not(x) Else & Concatenation y = x & z
Resulting size
The result size of an operation
21.13. Syntax 247 Zawiki, Release v0.11-30-g7307413
Figure6: Operator usage
21.13. Syntax 248 Zawiki, Release v0.11-30-g7307413
Listing 20: operation result size -- Binary vector_sig <= "1001"; -- 4 bits binary value -- Hexadecimal vector_sig <= X"F"; -- 1 Hexadigit = 4 binary bits -- Assignation vector_sig <= a; -- a'length = Length of array A vector_sig <= a and b; -- a'length = b'Length boolean_sig <= a > b; -- Boolean vector_sig <= a + b; -- Maximum (A'Length, B'Length) vector_sig <= a * b; -- A'Length + B'Length
21.13.3 Functions
Functions are reusable pieces of code. A function cannot consume simulation time and has only one return parameter. See also Procedure
Listing 21: parity function parity_generator( din : std_ulogic_vector ) return std_ulogic is variable t : std_ulogic := '0'; begin for i in din'range loop t := t xor din(i); end loop; return t; end parity_generator;
... sig_par <= paritiy_generator(data_bus);
Edge finding
Listing 22: edge rising_edge(clk) (clk'event & clk = '1') falling_edge(clk) (clk'event & clk = '1')
Conversion
Listing 23: conversion functions to_integer() -- signed,unsigned return int to_unsigned() -- int return unsigned to_signed() -- int return signed signed() -- slv return signed unsigned() -- slv return unsigned std_logic_vector() -- signed,unsigned return slv std_match(arg1, arg2) -- return bool
21.13. Syntax 249 Zawiki, Release v0.11-30-g7307413
Resize
Listing 24: resize functions resize(sig, length) -- unsigned return unsigned resize(sig, length) -- signed return signed
21.13.4 Procedure
A procedure allows to reuse a piece of code. It has to be written in a package or between the process and it’s beginning. A procedure can consume simulation time and can have as many in, out or inout signals/variables as wished. See also Functions If in the parameter list is a parameter without signal in front, it means that it has to assigned to a direct value or a variable. Mostly signals are used if as the interface and variables are used to give input- or output data.
Listing 25: parity generator procedure parity_generator( signal din : in std_ulogic_vector; signal par : out std_ulogic; par_init : in std_ulogic ) is variable t : std_ulogic := par_init; begin for i in 0 to din'range loop t := t xor din(i); end loop; par <= t; end parity_generator; signal databus : std_logic_vector(31 downto 0) := x"3210" signal par_bit : std_logic;
... parity_generator(databus,par_bit, "0");
21.13.5 Signal
21.13. Syntax 250 Zawiki, Release v0.11-30-g7307413
Listing 26: signal assign DataOut <= ( 7 downto 4 => x"A", 3 downto 2 => "01", 1 => '1', others =>'0');
Attributes
More Attributes can be found at: Attributes
Attribute Decription Example Type based (10 DOWNTO 0) T'base Base type of type T 10 T'left Element left of type T 0 T'right Element right of type T 10 T'high Highest element of type T 0 T'low Lowest element of type T T'pos(x) Place x in type T T'val(n) Value of element at place n in T T'succ(x) Element after x in T T'pred(x) Element before x in T T'leftOf(x) Element left of x in T T'rightOf(x) Element right of x in T Vector based V'left Element most left in vector V 10 V'right Element most right in vector V 0 V'high Highest element in vector V 10 V'low Lowest element in vector V 0 V'range range of vector V 10 downto 0 V'reverse_range inversed range of vector V 0 downto 10 V'length length of vector V 11
21.13.6 Statements
If
Listing 27: if if s0 = '0' and s1 = '0' then output <= in0; elsif s0 = '1' and s1 = '0' then output <= in1; elsif s0 = '0' and s1 = '1' then output <= in2; elsif s0 = '1' and s1 = '1' then output <= in3; else output <= 'X'; end if;
21.13. Syntax 251 Zawiki, Release v0.11-30-g7307413
Case
Listing 28: case case sel is when "00" => output <= in0; when "01" => output <= in1; when "10" => output <= in2; when "11" => output <= in3; when others => output <= 'X'; end case;
With Select
Listing 29: with with sel select output <= in0 when "00", in1 when "01", in2 when "10", in3 when "11", 'X' when others;
When
Listing 30: when output <= in0 when sel = "00" else in1 when sel = "01" else in2 when sel = "10" else in3 when sel = "11" else 'X';
For
21.13. Syntax 252 Zawiki, Release v0.11-30-g7307413
Listing 31: for loop for i in 1 to 8 loop output(i) <= input(i + 8); end loop; for i in input'range loop output(i) <= input(i); end loop;
21.13.7 Fixed & Floating Point Types
TODO
21.13.8 Fixed Point Types
TODO
21.13.9 Floating Point Types
TODO
21.14 RTL Synthesis
• Additional Documents
21.14.1 Additional Documents
• Synth Works RTL Synthesis • Synth Works RTL Standard
21.15 Testbench
• Additional Documents • Tests & Severity – Stop Simulation • Clock generation • Reset • Wait statement • Strings
21.14. RTL Synthesis 253 Zawiki, Release v0.11-30-g7307413
21.15. Testbench 254 Zawiki, Release v0.11-30-g7307413
– Simple and messy – Complicated and pretty ∗ Put String into Line ∗ Get String from Line • Shared Variables
21.15.1 Additional Documents
• Synth Works Subbloc Verification • Synth Works Testbench Techniques
21.15.2 Tests & Severity
Listing 32: severity signal sev_lvl : severity_level := note -- note | warning | error | failure assert ( a = b ) report “a is not equal to b” severity severity_lvl;
Stop Simulation
Listing 33: testbench stop assert false report "End of simulation" severity failure;
21.15.3 Clock generation
Listing 34: clock constant sys_CLK_freq : real := 150.00E6; constant sys_CLK_period : time := (1.0/sys_CLK_freq) * 1 sec; signal sys_CLK_int : std_logic; signal sys_CLK : std_logic; ------Only signal sys_CLK_int <= not sys_CLK_int after sys_CLK_period / 2; sys_CLK <= transport sys_CLK_int after sys_CLK_period * 9 / 10;
-- In a process process begin sys_CLK_int <= '0'; wait for sys_CLK_period / 2; sys_CLK_int <= '1'; wait for sys_CLK_period / 2; end process; sys_CLK <= transport sys_CLK_int after sys_CLK_period * 9 / 10;
21.15. Testbench 255 Zawiki, Release v0.11-30-g7307413
21.15.4 Reset
Listing 35: reset tb_RESETn <= '0' after 0 ns, '1' after 4 * sys_CLK_period;
21.15.5 Wait statement
• Has to be in process without List of sensitivity • Every process without a list of sensitivity need at least on wait statement.
Listing 36: wait wait_PROC: process -- wait for a given TIME wait for
-- wait for an EVENT wait on
-- wait until CONDITON (on event triggered) wait until
-- wait if signal hasn't the whished value if not
-- wait FOREVER wait; end wait_PROC;
21.15.6 Strings
21.15. Testbench 256 Zawiki, Release v0.11-30-g7307413
Listing 37: string -- Integer => String string_sig <= integer'image(integer_sig);
-- String => Interger integer_sig <= integer'value(string_sig);
-- String => Std_logic_vector slv_sig <= to_std_logic_vector(string_sig);
Characters lf - linefeed ht - tabluator
Simple and messy
Make a string plenty wide enough. Then you can store each string in the appropriate slice of it.
Listing 38: string simple variable toto: string(1 to 80) := (others => ' '); -- plenty wide enough, and full of spaces
... if a = 0 then toto(t1'range) := t1; else toto(t2'range) := t2; end if;
This is quite horrible, though, because you have no easy way to find out how many char- acters of toto are in use at any given time.
Complicated and pretty
Make the string a variable of type LINE, from package STD.TEXTIO. Then you can copy any string into it using the WRITE procedure: WRITE procedure adds things to the end of the string stored in toto, so that it grows ever longer. The DEALLOCATE procedure eliminates the spaces used by the line variable.
Important: Each line variable need to be deallocated at the end, otherwise the memory space will not be released.
Listing 39: string pretty 1 variable toto: line; -- initialised to empty! ... if a=0 then write(toto, t1); else write(toto, t2); end if;
21.15. Testbench 257 Zawiki, Release v0.11-30-g7307413
To reset it back to “empty” and free the memory, simply:
Listing 40: string pretty 2 deallocate(toto);
Put String into Line
Copying any string into a line variable, having first cleared that variable:
Listing 41: string pretty 3 procedure put(l: inout line; s: in string) is begin deallocate(l); write(l, s); end;
Get String from Line
Given a variable.
Listing 42: string pretty 4 variable l: line; variable c: character; variable s: string(1 to 80) := (others => ' ');
-- put something into l ...
-- take the whole string content report "Message is " & l.all;
-- take a slice of it, just like a string: c := l(1); s := l.all; (whole line to string)
-- find its length: if l'length > 50 then ... end if;
-- write it to a file (such as the console): writeline(output, l); -- also clears l to empty
21.15.7 Shared Variables
Listing 43: shared variables architecture non_determinist of example is
shared variable count : integer; begin
(continues on next page)
21.15. Testbench 258 Zawiki, Release v0.11-30-g7307413
(continued from previous page) p1 : process begin count := 1; wait; end process p1;
p2: process begin wait 1 ps; count := 2; wait; end process p2; end architecture non_determinist;
21.16 Time
• Time Type – Is a 32bit integer sufficient – Simulator use 64bit integer • Time Conversions – Integer => Time – Real => Time – Time => Real, Integer • Clock generation
21.16.1 Time Type
21.16. Time 259 Zawiki, Release v0.11-30-g7307413
Listing 44: time type type time is range -2147483647 to 2147483647 units fs; ps = 1000 fs; ns = 1000 ps; us = 1000 ns; ms = 1000 us; sec = 1000 ms; min = 60 sec; hr = 60 min; end units;
Is a 32bit integer sufficient
Maxvalue = 232 − 1 = 2.15 ∗ 109 = 2.15us < hour
Note: How many femtosecond has an hour? 1hour = 3.6 ∗ 1010fs
Simulator use 64bit integer
Maxvalue = 264 − 1 = 9.22 ∗ 1018 = 2.56hour
Note: VHDL Simulators use 64bit integer for time representaton Time range is = 1fs − 2.56hour
21.16.2 Time Conversions
Integer => Time
Listing 45: int 2 time -- Time_value := Int_value * Time_unit; timeout := intmax * 1 ns;
Real => Time
Listing 46: real 2 time -- Time_value := integer(real_value) * Time_unit; timeout := integer(realmax) * 1 ns;
21.16. Time 260 Zawiki, Release v0.11-30-g7307413
Time => Real, Integer
Listing 47: time 2 time int_pico := curr_time/ 1 ns * 1000; real_pico := real(curr_time/ 1 ns) * 1000.0; -- Time_value := integer(real_value) * Time_unit; timeout := integer(realmax) * 1 ns;
21.16.3 Clock generation
Listing 48: clock generation architecture test of DUT_tester is -- 100MHz clock constant clkFreq : real := 100.0E6; constant clkPeriod : time := (1.0/clkFreq) * 1 sec; -- Initialising with 1 signal clk_int : std_ulogic := '1'; begin clk_int <= not clk_int after clkPeriod/2; clk <= transport clk_int after clkPeriod*9/10; end test;
21.17 Xilinx UCF Constraints
• How to Guide – Problem A : false paths – Problem B : reading data from outside the FPGA – Problem C: outputting synchronous data correctly with an FPGA • Syntax – Comment – I/O Pad Assigments • Timing constraints – Clock constraint (PERIOD) – Time Group
21.17. Xilinx UCF Constraints 261 Zawiki, Release v0.11-30-g7307413
– OFFSET ∗ OFFSET with TimeGroup ∗ OFFSET with Valid data – False paths – Multicycle paths
21.17.1 How to Guide
This small guide indicates how to resolve most timing problems / constraints inside an FPGA. In fact, most problems with an FPGA timing occur because of three reasons: • False paths • Timing issues due to reading data from outside the FPGA with a clock • Timing issues due to outputting data to another component from the FPGA with a clock.
Problem A : false paths
A simple example for the first case is when you generate the TX line of an UART orwhen you consider interrupt lines in a uBlaze (for instance). In both cases, those signals arenot synchronous with respect to your clock. You must then indicate that those netsare to be ignored by timing checks. In order to do it, for Xilinx FPGA you must use the TIGcon- straint (which stands for Timing IGnore). The only problem here is that you can’t putthat constraint in your VHDL file but you have to put it in the UCF file. When you haveinternal signals, you require to use the complete path of the net (which can be found forexample by displaying the schematic of your design or with the report of the timing analyser). An example of such a constraint for a UCF file is given here :
INST "broadenc_cpu_i/axi_intc_0/axi_intc_0/INTC_CORE_I/hw_intr_1" TNM = UBlaze_ ,→Interrupts; INST "broadenc_cpu_i/axi_intc_0/axi_intc_0/INTC_CORE_I/hw_intr_2" TNM = UBlaze_ ,→Interrupts; TIMESPEC TS_UBlaze_Interrupts = TO "UBlaze_Interrupts" TIG; # We don't care of␣ ,→timing for interrupts
This creates a< group for two signals and then use the TIG constraint to it. If your instance name is incorrect, the synthesis tool will complaint.
Problem B : reading data from outside the FPGA
When you read synchronous data (i.e. with an incoming clock) in an FPGA, you must be sure that you respect setup and hold times in your input register. In order to do, a simple constraint like
OFFSET = IN 4 ns VALID 8 ns BEFORE "mb_vclk"; indicate that the data that are registered with the signal mb_vclk (which must be a con- strained clock) must comply with a setup of 4 ns and a hold time of 4 ns. By doing it like this, you won’t have any problem with source synchronous systems (in which the clock are transmitted from another device with the data).
21.17. Xilinx UCF Constraints 262 Zawiki, Release v0.11-30-g7307413
Problem C: outputting synchronous data correctly with an FPGA
When you generate data for another system in your FPGA and you also generate the clock for that system ( a global clock is not shared between all elements of the system (FPGA and device) for that bus), making sure that the data are aligned with the clock and are output with correct setup and hold times consist in putting the following constraint : net "ve_vclk" TNM_NET = "vdata_out"; net "ve_vy<0>" TNM_NET = "vdata_out"; net "ve_vy<1>" TNM_NET = "vdata_out"; net "ve_vy<2>" TNM_NET = "vdata_out"; net "ve_vy<3>" TNM_NET = "vdata_out"; net "ve_vy<4>" TNM_NET = "vdata_out"; TIMEGRP "vdata_out" OFFSET = OUT AFTER "mb_vclk" REFERENCE_PIN "ve_vclk";
Those constraints have the following meaning : we group all the signals in a group “vdata_out”. This group is generated with a clock (here mb_vclk, which remains inside the FPGA) and the clock for the whole group (which is output and constitues the refer- ence for all the other signals) is ve_vclk. Note that this pin must be included in the group.
21.17.2 Syntax
Comment
# This is a comment
I/O Pad Assigments
NET "out_sig_slow" LOC = "S1" | SLEW = SLOW; NET "out_sig_fast" LOC = "S2" | SLEW = FAST; NET "out_sig33" LOC = "V1" | IOSTANDARD = LVCMOS33 NET "in_sig18" LOC = "V2" | IOSTANDARD = LVCMOS18 NET "reset_n" LOC = "P1" | PULLUP; NET "button_Pullup" LOC = "P2" | PULLUP; NET "button_Pulldown" LOC = "P3" | PULLDOWN;
21.17.3 Timing constraints
Clock constraint (PERIOD)
Definition of a clock with a 50% duty cycle and it’s frequency (40MHz)
NET "SYS_CLK" TNM_NET = "SYS_CLK"; TIMESPEC "tnm_name" = PERIOD "sig_name"
21.17. Xilinx UCF Constraints 263 Zawiki, Release v0.11-30-g7307413
Figure7: Duty Cycle
Time Group
Create timing group with particular net. This code defines a clk_net timing group associ- ated with the CLK clock net and including all synchronous elements controlled by this net (since no qualifier has been specified).
NET "net_name" TNM_NET = qualifier "tnm_name"; NET "CLK" TNM_NET = "clk_net"; NET "ve_vc<0>" TNM_NET = ve_data; NET "ve_vc<1>" TNM_NET = ve_data;
Create timing group by specify the name of the instance (module)
INST "inst_name" TNM = qualifier "tnm_name";
OFFSET
OFFSET constraint is used to specify external setup time for input pads or necessary hold time for output pads. For input pads, OFFSET specifies a time before the (external) clock edge when the related data signals are set.
OFFSET = IN 5 ns AFTER "CLK"; OFFSET = IN 5 ns BEFORE "CLK";
For output pads, OFFSET specifies a minimum time after the clock edge when the related data signals can be deasserted.
21.17. Xilinx UCF Constraints 264 Zawiki, Release v0.11-30-g7307413
Figure8: Offset Example
21.17. Xilinx UCF Constraints 265 Zawiki, Release v0.11-30-g7307413
Figure9: Offset in
OFFSET = OUT 2 ns AFTER "CLK"; OFFSET = OUT 2 ns BEFORE "CLK";
OFFSET with TimeGroup
Set Offset after rising edge of clock constraint for all signals in Timegroup
TIMEGRP "ve_data" OFFSET = OUT 10.333 ns AFTER "mb_vclk" RISING; TIMEGRP "ve_data" OFFSET = OUT 10.333 ns AFTER "mb_vclk" FALLING;
OFFSET with Valid data
The VALID keyword is used in conjunction with the requirement to create a hold time requirement. The VALID keyword specifies the duration of the incoming data valid window. By default, the VALID value is equal to the OFFSET time requirement, which specifies a zero hold time requirement
21.17. Xilinx UCF Constraints 266 Zawiki, Release v0.11-30-g7307413
Figure10: Offset Out
Figure11: Offset Valid
21.17. Xilinx UCF Constraints 267 Zawiki, Release v0.11-30-g7307413
TIMEGRP DATA_IN OFFSET IN = 2ns VALID 3ns BEFORE CLK RISING;
False paths
In some cases, you may want to remove a set of paths from timing analysis if you are sure that these paths do not affect timing performance. For example a processor interrupt line or a UART TX Line. In both cases, those signals are not synchronous with respect to your clock. You must then indicate that those nets are to be ignored by timing checks. In order to do it, for Xilinx FPGA you must use the TIG constraint (which stands for T iming IG nore). One common way to specify the set of paths to be removed from timing analysis is to use the FROM-TO constraint with the timing ignore (TIG) keyword. This allows you to: • Specify a set of registers in a source time group • Secify a set of registers in a destination time group • Automatically remove all paths between those time groups from analysis. To specify the timing ignore (TIG) constraint for this method, define: • A set of registers for the source time group • A set of registers for the destination time group • A FROM-TO constraint with a TIG keyword to remove the paths between the groups
TIMESPEC "TSid" = FROM "SRC_GRP" TO "DST_GRP" TIG;
NET "CLK1" TNM_NET = FFS "GRP_1"; (continues on next page)
21.17. Xilinx UCF Constraints 268 Zawiki, Release v0.11-30-g7307413
(continued from previous page) NET "CLK2" TNM_NET = FFS "GRP_2"; TIMESPEC TS_Example = FROM "GRP_1" TO "GRP_2" TIG;
Figure12: False Path
Multicycle paths
In a multi-cycle path, data is transferred from source to destination synchronous elements at a rate less than the clock frequency defined in the PERIOD specification. This occurs most often when the synchronous elements are gated with a common clock enable signal. By defining a multi-cycle path, the timing constraints for these synchronous elements are relaxed over the default PERIOD constraint. The implementation tools are then able to appropriately prioritize the implementation of these paths. One common way to specify the set of multi-cycle paths is to define a time group using the clock enable signal. This allows you to: • Define one time group containing both the source and destination synchronous ele- ments using a common clock enable signal • Automatically apply the multi-cycle constraint to all paths between these synchronous elements To specify the FROM:TO (multi-cycle) constraint for this method, define: • A PERIOD constraint for the common clock domain • A set of registers based on a common clock enable signal • A FROM:TO (multi-cycle) constraint describing the new timing requirement
21.17. Xilinx UCF Constraints 269 Zawiki, Release v0.11-30-g7307413
TIMESPEC "TSid" = FROM "MC_GRP" TO "MC_GRP"
NET "CLK1" TNM_NET = "CLK1"; TIMESPEC "TS_CLK1" = PERIOD "CLK1" 5 ns HIGH 50%; NET "Enable" TNM_NET = FFS "MC_GRP"; TIMESPEC TS_Example = FROM "MC_GRP" TO "MC_GRP" TS_CLK1*2;
Figure13: Multi-Cycle Path
21.17. Xilinx UCF Constraints 270 Chapter 22
Tcl-Tk
22.1 Introduction
• Links
Tcl originally from “Tool Command Language” is a scripting language. It is commonly used for rapid prototyping, scripted applications, GUIs and testing. Tcl is used on embedded systems platforms. Tcl is also used for CGI scripting. Tcl is popularly used today in many automated test har- nesses, both for software and hardware, and has a loyal following in the Network Testing and SQA communities.
• TCL Tk Manual pdf or online
271 Zawiki, Release v0.11-30-g7307413
22.1.1 Links
• Wikibook Tcl Programming
• Tcl Developper eXchange - Documentation
22.2 Examples
22.2.1 Run simulation run_sim.do This scripts performs the following operations: 1. Quit previous simulation if in action 2. Specify variables #.Get PWD #.Project path variables #.compPath form environmentvar #.work- Path #.ModelsimPath 1. Creating working library 1. Change to working directory 2. Create work lib 3. Change back to modelsim execution directory 4. Mapping work lib 1. Compile Design 1. Execute comp.do files 1. Compile Testbench 2. Loading the design 3. Load do files for simulation 4. Restart and Simulate
22.2. Examples 272 Zawiki, Release v0.11-30-g7307413
22.2.2 Compilation run_sim.do This scripts performs the following operations: 1. Specify variables of component 2. Specify VHDL source Paths 3. Specify Subcomponent Paths 4. Compile additional Libraries 5. Compile the Design
22.2.3 Calculate Simulation time run_sim.do This scripts allows to measure the simulation time
22.3 FPGA Scripting
Every FPGA Manufacturer has its own libraries for scripting their tools with tcl-tk scripts. • Xillinx Vivado • Intel Quartus II
22.4 Syntax
• General – Comments – Console output – Concatenate commands – Sleep – Variables ∗ Local variables ∗ Environment variables • Statements – if – Loop • Filesystem – Check if folder exist – Check if file exist – Make dir
22.3. FPGA Scripting 273 Zawiki, Release v0.11-30-g7307413
– Change directory – Create list – Calculation – foreach_in_collection – get_collection_size • Quartus specific – Post messages • Modelsim specific – Quit Sim – Creating library – Mapping library • Execute .do files – Compilation – Loading design – Wave – Restart & Simulate – Read Signals
22.4.1 General
Comments
Listing 1: comment # this is a comment
Console output
To do a print in the console, the special variable “text” has to be used
Listing 2: console output puts "This text will be displayed in the console"
Concatenate commands
It is possible to concatenate commands with the [] braces.
Listing 3: concatenation set pwd_path [eval pwd] if {[file exists $filename)]} { } if {[file isdirectory $filename)]} { } (continues on next page)
22.4. Syntax 274 Zawiki, Release v0.11-30-g7307413
(continued from previous page) set var [examine /block/signalname]
Sleep
Listing 4: sleep after [expr {int(10*1000)}] # Wait for 10*1000ms = 10sec
Variables
Local variables
Listing 5: local variable # Writing Variables set variableName stringValue set exampleVar /home/user
# Reading Variables $variableName set exampleVar2 $exampleVar/file.do
# Reading Signal Value and store in Variable set exampleVar3 [examine /block/signalname]
Environment variables
Listing 6: environment variable # Current working directory set pwd_path [eval pwd]
# Reading environment variable set compPath $env(modelsim_complib)
22.4.2 Statements if
Listing 7: if if { [$string == "string"] || [$int >= 50] && [string equal -nocase $string ,→"compare"] } { Do stuff here }
22.4. Syntax 275 Zawiki, Release v0.11-30-g7307413
Loop
Listing 8: loops set file_list { file_1.vhd file_2.vhd } foreach file $file_list { puts "File $file" } set library_file_list { design_library {counter.vhd} test_library {counter_tb.vhd counter_tester.vhd} } foreach {library file_list} $library_file_list { puts "Library name $library" foreach file $file_list { puts "file $file" }
22.4.3 Filesystem
Check if folder exist
Listing 9: check folder if {[file isdirectory $env(modelsim_complib)]} { # folder exist } else { # create folder file mkdir $env(modelsim_complib) }
Check if file exist
22.4. Syntax 276 Zawiki, Release v0.11-30-g7307413
Listing 10: check folder if {[file exists $env(modelsim_complib)]} { # file exist } else { # create folder file mkdir $env(modelsim_complib) }
Make dir
Listing 11: mkdir file mkdir $env(modelsim_complib)
Change directory
Listing 12: cd cd $compPath
Create list
Listing 13: cd [list item1 item2]
Calculation
Listing 14: calculations [expr 1.0 * 3.0 / 4.0]
foreach_in_collection
22.4. Syntax 277 Zawiki, Release v0.11-30-g7307413
Listing 15: collection foreach_in_collection op [get_available_operating_conditions] { set operating_conditions $op update_timing_netlist set oc_name [get_operating_conditions_info $op -display_name] puts "Operating Condition Set to: $oc_name" report_timing -setup -npath 10 -detail summary -append -file top_setup.txt
get_collection_size
Listing 16: collection set num_ports [get_collection_size [get_ports *]]
22.4.4 Quartus specific
Post messages
Post messages on Console. postmessage -type info -submsgs {"Submessage 1" "Submessage 2"} "Main info message" postmessage -type extra_info "Extra info message" postmessage -type warning "Warning message" postmessage -type critical_warning "Critical warning message" postmessage -type error -submsgs "Error submessage" "Main error message"
22.4.5 Modelsim specific
Quit Sim
Quit previous simulation if in action
Listing 17: quit vsim quit -sim
Creating library
Change to working folder and create working lib. Note: variable have to created before.
Listing 18: create workdir # change to working directory cd $compPath
# Create work lib vlib $workPath
22.4. Syntax 278 Zawiki, Release v0.11-30-g7307413
Mapping library
Mapping working library to to folder. Note: Variables have to created before.
Listing 19: map workdir # Change to Modelsim execution directory cd $ModelsimPath
# Mapping work lib vmap work $workPath
22.4.6 Execute .do files
In order to execute another do file in from this one
Listing 20: do.do do .path/to/do_file/filename.do
Compilation
Compilation of vhdl files in a certain library. Note: Variables have to created before.
Listing 21: compilation.do # compilation into before created working library vcom -work $workPath path/to/vhdl_file/filename.vhd
Loading design
Loading of the design. See also vsim -help toplevelbloc = testbenc
Listing 22: load_design.do vsim -t ps work.toplevelbloc -l path/to/transcript.txt
Wave
Display wave window and load waveform
22.4. Syntax 279 Zawiki, Release v0.11-30-g7307413
Listing 23: wave.do view wave do path/to/wave.do
Restart & Simulate
Restart simulation and simulate
Listing 24: restart_and_sim.do # Force restart restart -f
# Run until something finish (or until sun burns down) run -all
# Run given time run 50 us
Read Signals
Listing 25: signals.do examine /bloc/signal_name
22.4. Syntax 280 Chapter 23
Spinal HDL
23.1 Introduction
• Some helppages • Spinal Projects • Community
23.1.1 Some helppages
• Offical Spinal HDL Documentation • Cheatsheet Spinal HDL Core • Cheatsheet Spinal HDL Lib • Cheatsheet Spinal HDL Symbolic • Cheatsheet Spinal HDL Cheatsheet • Cheatsheet Spinal HDL Presentation • Cheatsheet Spinal HDL Presentation Fast • Cheatsheet Spinal HDL Presentation Very Fast
281 Zawiki, Release v0.11-30-g7307413
23.1.2 Spinal Projects
• SaxonSoC (RiscV Framework) • Spinal HDL Core and Lib • Spinal Workshop • Vex RiscV Processor
23.1.3 Community
• Gitter Channel • Issues • Email
23.2 Installation
• Tools • Linux – Base Tools Linux – IDE Linux – Simulation Linux – Hardware Debug Tools Linux – RiscV Development Tools – Optional Dev Tools Linux • Windows – Base Tools Windows – IDE Windows – Simulation Windows – Hardware Debug Tools Windows
23.2.1 Tools
The following tools are needed: • tools intro • intellij_idea
23.2. Installation 282 Zawiki, Release v0.11-30-g7307413
23.2.2 Linux
For Linux there is also a complete install-spinal.bash script available.
chmod +x install-spinal.bash ./install-spinal.bash
Base Tools Linux
1 sudo apt-get install -y git make autoconf g++ flex bison 2 sudo apt-get install -y openjdk-8-jdk 3 sudo apt-get install -y scala 4 echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list. ,→d/sbt.list 5 sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823 6 sudo apt-get update -y 7 sudo apt-get install -y sbt
IDE Linux
sudo snap install intellij-idea-community --classic
Simulation Linux
1 cd ~ 2 git clone http://git.veripool.org/git/verilator 3 unset VERILATOR_ROOT 4 cd verilator 5 git pull # Make sure we're up-to-date 6 git checkout verilator_3_916 7 autoconf # Create ./configure script 8 ./configure 9 make -j$(nproc) 10 sudo make install 11 sudo apt-get install -y gconf2 gtkwave
Hardware Debug Tools Linux
sudo apt-get install -y openocd
RiscV Development Tools
wget https://static.dev.sifive.com/dev-tools/riscv64-unknown-elf-gcc-20171231-x86_ ,→64-linux-centos6.tar.gz tar -xzvf riscv64-unknown-elf-gcc-20171231-x86_64-linux-centos6.tar.gz sudo mv riscv64-unknown-elf-gcc-20171231-x86_64-linux-centos6 /opt/riscv64-unknown- ,→elf-gcc-20171231-x86_64-linux-centos6 sudo mv /opt/riscv64-unknown-elf-gcc-20171231-x86_64-linux-centos6 /opt/riscv echo 'export PATH=/opt/riscv/bin:$PATH' >> ~/.bashrc echo 'export PATH=/opt/riscv/bin:$PATH' >> ~/.zshrc
23.2. Installation 283 Zawiki, Release v0.11-30-g7307413
Optional Dev Tools Linux
1 echo "Install default tools" 2 sudo apt-get install -y zsh 3 sudo chsh -s /bin/zsh $USER 4 cd ~/Downloads 5 sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/ ,→install.sh)"
6
7 sudo apt-get install -y yakuake krusader
8
9 wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add - 10 sudo apt-get install apt-transport-https 11 echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/ ,→sources.list.d/sublime-text.list 12 sudo apt-get update 13 sudo apt-get install -y sublime-text sublime-merge
14
15 sudo add-apt-repository ppa:christian-boxdoerfer/fsearch-daily 16 sudo apt update 17 sudo apt-get install -y fsearch-trunk
23.2.3 Windows
Base Tools Windows
• Install Java • Install Scala Build Tool SBT
IDE Windows
• Install IntelliJ IDEA – Within IntelliJ install Scala Plugin – Remove settings for Code Checking
Simulation Windows
• Install MSYS2 64bit • Install verilator from minGW packet manager
Listing 1: Verilator Installation
1 pacman -Syuu
2
3 # Close the MSYS2 shell once you're asked to 4 pacman -Syuu 5 pacman -S --needed base-devel mingw-w64-x86_64-toolchain \ 6 git flex\ 7 mingw-w64-x86_64-cmake
8
9 pacman -S mingw-w64-x86_64-verilator
• ADD MSYS2 C:\msys64\usr\bin;C:\msys64\mingw64\bin to your Environment Variable Path.
23.2. Installation 284 Zawiki, Release v0.11-30-g7307413
Hardware Debug Tools Windows
• Install OpenOCD for JTAG debugging.
23.3 Project Files
• Project Structure – General Project Structure – My Project Structure • Create your first Project • Sample build.sbt • SBT Commands • Add Submodule to Project
23.3.1 Project Structure
Every SpinalHDL Project is created as a Scala Project This means the Scala folder defini- tion applies, of course this can be changes if needed.
General Project Structure
• etc/ - external project libraries for example VexRISCV • project/ - sbt project configuration – build.properties - contains only sbt version to be used for this project – plugins.sbt - contains only sbt plugins to be used for this project • src/ - contains all source files synthesizable or not – main/ - contains a folder for each programming language ∗
23.3. Project Files 285 Zawiki, Release v0.11-30-g7307413
My Project Structure
+-- (.idea/) # temp intellij settings folder +-- ext/ # folder for external IP imported normally via␣ ,→submodules +-- img/ # project images +-- project/ # sbt project folder +-- scripts/ # general scripts for the project +-- sim/ # temp folder for simulation files +-- scr/ # folder for all project source files | +-- hardware/ # folder for all hw related stuff | | +-- netlist/ # spinalHDL generated VHDL and Verilog Code ready␣ ,→for synthesis | | +-- scala/ | | | +--
23.3.2 Create your first Project
Clone the https://github.com/SpinalHDL/SpinalTemplateSbt sample project and get started. git clone https://github.com/SpinalHDL/SpinalTemplateSbt.git cd SpinalBaseProject/ sbt run ls MyTopLevel.vhd
23.3.3 Sample build.sbt
Listing 2: build.sbt example // project name & version name := "eln-chrono-spinal" version := "0.1"
// scala version scalaVersion := "2.11.12"
EclipseKeys.withSource := true
// scala plugins dependencies libraryDependencies ++= Seq( "com.github.spinalhdl" % "spinalhdl-core_2.11" % "1.3.8", "com.github.spinalhdl" % "spinalhdl-lib_2.11" % "1.3.8" )
// changing the src folder for compile and test code (continues on next page)
23.3. Project Files 286 Zawiki, Release v0.11-30-g7307413
(continued from previous page) scalaSource in Compile := baseDirectory.value / "src"/ "hardware" / "scala" scalaSource in Test := baseDirectory.value / "src" / "test" / "scala"
// For allowing Simulation fork tasks fork := true
23.3.4 SBT Commands sbt # enter sbt shell sbt clean # clean repo from sbt generated files sbt compile # compiles all code in hardware/scala sbt run # run all compiled code
23.3.5 Add Submodule to Project
Need to be in the ext/ folder git submodule add -b
23.4 Data Types
• Spinal – Bool – Bits – UInt & SInt – Vec • Conversions – Spinal <-> Spinal – Scala <-> Scala – Scala <- Spinal – Spinal <- Scala • Input & Outputs • Internal Signals
For scala types see Introduction
23.4. Data Types 287 Zawiki, Release v0.11-30-g7307413
23.4.1 Spinal
The language provides 5 base types and 2 composite types that can be used. • Base types: Bool , Bits , UInt for unsigned integers, SInt for signed integers and Enum. • Composite types: Bundle and Vec.
Data
Bundle Vec BaseType
Enum Bool BitVector
Bits UInt SInt
Bool
Spinal Bool as True or False
// Instances val x = Bool val y = Bool(True)
// Assignments x := False
// Operators !x // not x & y // and x | y // or x ^ y // xor x ## y // concatenate x is high xy is low x.set x.clear x.setWhen(cond) x.clearWhen(cond) (continues on next page)
23.4. Data Types 288 Zawiki, Release v0.11-30-g7307413
(continued from previous page)
// Edge detection x.edge // True if state change x.rise // True if rising edge x.fall // True if falling edge x.edges // returns a bundle (rise, fall, toggle) x === y // comparison True equality x =/= y // comparison True Inequality
// Typecast x.asBits // Bits(w(x) bits) x.asUInt // UInt(w(x) bits) x.asUInt(bitCount) // SInt(w(x) bits) x.asSInt // UInt(bitCount bits) x.asSInt(bitCount) // Bits(bitCount bits)
Bits
// Instances val x = Bits() val y = Bits(32 Bits) val x = B(25, 8 Bits) val x = B(8 bits, default -> True) val x = B(8 bits, (7 downto 5) -> B"101", 4 -> true, 3 -> True, default -> false)
// Assignments x := B"8'0xFF" x := B"8'dhFF" x := B"8'0d255" x := B"8'0o377" x := B"8'0b11111111" x := B"8'0b1111_1111" x := (7 -> true, default -> false)
// Operators ~x // bitwise not x & y // bitwise and x | y // bitwise or x ^ y // bitwise xor x.xorR // xor of all bits of x x.orR // or of all bits of x x.andR // and of all bits of x x >> y // Logical shift right x << y // Logical shift left x.rotateLeft(y) // Logical left rotation x.rotateRight(y) // Logical right rotation x.clearAll // clear all bits x.setAll // set all bits x ## y // concatenate x high y low x === y // comparison True equality x =/= y // comparison True Inequality
// Typecast x.asBits // Binary cast to Bits x.asUInt // Binary cast to UInt x.asSInt // Binary cast to SInt x.asBools // Cast to an array of Bools (continues on next page)
23.4. Data Types 289 Zawiki, Release v0.11-30-g7307413
(continued from previous page) B(x) // Cast Data to Bits
// Bit Access x(y) // R/W one bit x(hi,lo) // R/W range x(2 downto 1) // R/W range
// Misc x.getWidth // return bitsize if bus x.range // return (x.high downto 0) x.high // return upper bound x.low // return lower bound x.msb // return msb bits x.lsb // return lsb bits x.getWidth // return number of bites x.resize(y) // return a resized copy (filled with Zero if needed) x.resized // return a version of x which can be resized as needed x.resizeLeft(x) // resize keeping MSB as MSB
UInt & SInt
// Instances val x = UInt(32 Bits) val y = SInt(32 Bits) val x = U(25, 8 Bits) val y = S(25, 8 Bits)
// Assignments x := U(2, 8 Bits) y := S(2, 8 Bits) x := U(2) y := S(2) x := U"8'0xFF" y := S"8'0xFF" x := U"8'0d255" y := S"8'0d255" x := U"8'0o377" y := S"8'0o0000_0001" x := 2 // scala types can be used y := -2 // scala types can be used x := (default -> true) x := (x.range -> true) x := (7 -> true, default -> false) x := ((4 downto 1) -> true, default -> false)
// Operators ~x // bitwise not x & y // bitwise and x | y // bitwise or x ^ y // bitwise xor x.xorR // xor of all bits of x x.orR // or of all bits of x x.andR // and of all bits of x x >> y // Logical shift right x << y // Logical shift left x.rotateLeft(y) // Logical left rotation x.rotateRight(y) // Logical right rotation x.clearAll // clear all bits (continues on next page)
23.4. Data Types 290 Zawiki, Release v0.11-30-g7307413
(continued from previous page) x.setAll // set all bits x ## y // concatenate x high and low y
// Arithmetic x + y // Addition x +^ y // Addition with carry, return +1 bit x +| y // Addition with sat carry x - y // Substraction x -^ y // Substraction with carry, return +1 bit x -| y // Substraction with sat carry x * y // Multiplication, return x+y bits x / y // Division x % y // Modulo
// Comparison x === y // True by equality x =/= y // True by inequality x > y // True by greater than x >= y // True by greater than or equal x < y // True by less than x <= y // True by less than or equal
// Typecast x.asBits // Binary cast to Bits x.asUInt // Binary cast to UInt x.asSInt // Binary cast to SInt x.asBools // Cast to an array of Bools S(x) // Cast Data to SInt U(x) // Cast Data to UInt
// Bit Access x(y) // R/W one bit x(offset, width) // R/W bitfield x(2 downto 1) // R/W range
// Misc x.getWidth // return bitsize if bus x.range // return (x.high downto 0) x.high // return upper bound x.msb // return msb bits x.lsb // return lsb bits x.getWidth // return number of bites x.resize(y) // return a resized copy (filled with Zero if needed) x.resized // return a version of x which can be resized as needed x.resizeLeft(x) // resize keeping MSB as MSB x.expand // return x with 1 bit expanded
// UInt Special x.twoComplement(True) //enable, disable 2-complement
// SInt Special y.abs // return UInt is SInt y.sign // return most significant bit
23.4. Data Types 291 Zawiki, Release v0.11-30-g7307413
Vec
Vector are scala array like
// Instances val w = Vec(SInt(8 bits),2) val x = Vec(Bool,2) val y = Vec(Reg(Bool) init(False), 2) val z = Vec(Reg(SInt(8 bits)) init(0), 10)
// Assignments x(0) := 2 x.head := 2 // x(0) x.last := 2 // x(size-1) x.map(_ := 0) // map on a vector (assign all elements with value 0)
// Comparison x === y // True by equality x =/= y // True by inequality boolvar := x === y // Compare all elements
// Typecast x.asBits // Combines all elements to a big bits val x = Vec(SInt(8bits,2) myBits_16bits := vec.asBits
// Misc x.getBitsWidth // Get width of all elements combined println(x.getBitsWidth) // 16
23.4.2 Conversions
Spinal <-> Spinal val intVar : Int = 1 val intVar : Long = 1 val intVar : Int = 1.0.toInt val doubleVar : Floa tscala types= 1.0 val doubleVar : Double = 1.0 val doubleVar : Double = 1.0e6 val doubleVar : Double = 100e6 val BigDecimal : BigDecimal = BigDecimal(1.0e6) val BigDecimal : BigInt = BigDecimal(1.0e6).toBigInt
BigDecimal().toBigInt BigDecimal(10e6).toBigInt
23.4. Data Types 292 Zawiki, Release v0.11-30-g7307413
Scala <-> Scala
// Can be done with any type x.toByte x.toShort x.toInt x.toLong x.toFloat x.toDouble x.toChar x.toString()
// Spinal uses BigInt many times BigDecimal(2e42).toBigInt BigDecimal(x_Int).toBigInt BigDecimal(x_Double).toBigInt
Scala <- Spinal
Spinal <- Scala x_UInt := U(2, 2 bits) x_UInt := 2 x_UInt := BigInt(2) x_UInt := BigDecimal(10e42).toBigInt
23.4.3 Input & Outputs val io = new Bundle { val testMode = in Bool() default(False) val inValue = in UInt(4 bits) default(0) val loadValue = in Bool() default(False) val en = in Bool() default(False) val step = in UInt(8 bits) default(1) val reset = in Bool() default(False) val up_nDown = in Bool() default(True) val overflowValue = in UInt(width bits) val count = out UInt(width bits) val trigger = out Bool }
23.4. Data Types 293 Zawiki, Release v0.11-30-g7307413
23.4.4 Internal Signals
// Access internal signals in simulation val register = Reg(UInt(width bits)) init(0) simPublic() // or dut.counter.simPublic()
23.5 Tools
23.5.1 Introduction
• Programming Language • Execution • IDE • Simulator • Additional
There are additional Tools needed for Spinal HDL to work. hereafter are named the most common with references for further studies.
Programming Language
• Scala
23.5. Tools 294 Zawiki, Release v0.11-30-g7307413
Execution
• Java SDK
• Scala Build Tool SBT
IDE
For writing and executing the scala code • Intellij IDEA
Simulator
Behind the scene SpinalHDL is generating a C++ cycle accurate model of your hardware by generating the equivalent Verilog and asking Verilator to convert it into a C++ model. • Verilator * Verilator Wiki • GTKWave
23.5. Tools 295 Zawiki, Release v0.11-30-g7307413
Additional
• MYSYS2 for windows only
23.5.2 GtkWave
• Manual Reload
• Cheatsheet https://nbviewer.jupyter.org/GTKWave 3.3 Wave Analyzer User’s Guide Manual Reload If you want to manually via command-line reload the file the gconf2 tool needs to bein- stalled sudo apt-get install gconf2 Afterwards the reload command can be executed gconftool-2 --type string --set /com.geda.gtkwave/0/reload 0 23.5. Tools 296 Zawiki, Release v0.11-30-g7307413 23.5.3 Intellij IDEA IDE • Shortcuts • Rebuild all sbt projects • Cheatsheet https://nbviewer.jupyter.org/IntelliJIDEA_ReferenceCard.pdf Shortcuts Shortcut Action Shift + Shift Global Fuzzy Search Alt + Arrow Right Forward Alt + Arrow Left Backward Ctrl + Left Click Go to Definition Ctrl + Space Autocomplete Ctrl + / Comment Lines of Selection Alt + F12 Open Terminal Ctrl + Ctrl-hold + Arrow Up Add Cursor above Ctrl + Ctrl-hold + Arrow Down Add Cursor below Shift + Alt + Left Click Add Cursor at pointer location Rebuild all sbt projects When external IP change or libraries change you need to force a reimport of all svbt project. View -> Tool Window -> sbt -> Reimport all sbt projects. 23.5. Tools 297 Chapter 24 Scala 24.1 Introduction • Basics – Types – Variables – Constants – Functions ∗ Return ∗ Return type inferation ∗ Function that returns nothing Unit ∗ Arguements default value ∗ Apply – Object – Entry point (main) – Class ∗ Inheritance extends ∗ Case class – Templates / Type parameterization 298 Zawiki, Release v0.11-30-g7307413 • Scala Cheatsheet 24.1.1 Basics Types Type Description Range Byte 8 bit signed value -128 to 127 Short 16 bit signed value -32768 to 32767 Int 32 bit signed value -2147483648 to 2147483647 Long 64 bit signed value -9223372036854775808 to 9223372036854775807 Float 32 bit IEEE 754 single-precision float Double 64 bit IEEE 754 double- precision float Char 16 bit unsigned Unicode charac- U+0000 to U+FFFF ter String A sequence of Chars Boolean Either the literal true or the literal true, false false Unit Corresponds to no value Null null or empty reference Variables In scala, you can define a variable by using the var keyword: var number : Int = 0 number = 6 number += 4 println(number) // 10 Scala is able to infer the type automatically. You don’t need to specify it if the variable is assigned at declaration: var number = 0 //The type of 'number' is inferred as a Int during the␣ ,→compilation. Constants But, in fact, it’s not very common to use var in Scala. Instead, constant values defined by val are often used: val two = 2 val three = 3 val six = two * three 24.1. Introduction 299 Zawiki, Release v0.11-30-g7307413 Functions For example, if you want to define a function which returns true if the sum of its two arguments is bigger than zero, you can do as follows: def sumBiggerThanZero(a: Float, b: Float): Boolean = { return (a + b) > 0 } Then, to call this function, you can just write: sumBiggerThanZero(2.3f, 5.4f) You can also specify arguements by name, which is useful if you have many arguements: sumBiggerThanZero( a = 2.3f, b = 5.4f ) Return The return keyword is not necessary. In absence of it, Scala takes the last statement of your function as the returned value. def sumBiggerThanZero(a: Float, b: Float): Boolean = { (a + b) > 0 } Return type inferation Scala is able to automatically infer the return type. You don’t need to specify it: def sumBiggerThanZero(a: Float, b: Float) = { (a + b) > 0 } Function that returns nothing Unit If you want a function to return nothing, the return type should be set to Unit. It’s equiv- alent to the C/C++ void. def printer(): Unit = { println("1234") println("5678") } 24.1. Introduction 300 Zawiki, Release v0.11-30-g7307413 Arguements default value You can specify a default value for each arguement of a function: def sumBiggerThanZero(a: Float, b: Float = 0.0f) = { (a + b) > 0 } Apply Functions named apply are special because you can call them without having to type their name: class Array(){ def apply(index: Int): Int = index + 3 } val array = new Array() val value = array(4) //array(4) is interpreted as array.apply(4) and will return␣ ,→7 This concept is also applicable for scala object (static) object MajorityVote{ def apply(value: Int): Int = ... } val value = MajorityVote(4) // Will call MajorityVote.apply(4) Object In scala, there is no static keyword. In place of that, there is object. Everything defined into an object is static. The following example defines a static function named pow2 which takes a floating point value as parameter and returns a floating point as well. object MathUtils{ def pow2(value: Float): Float = value*value } Then you can call it by writing: MathUtils.pow2(42.0f) Entry point (main) The entry point of a Scala program (the main function) should be defined inside an object as a function named main. object MyTopLevelMain{ def main(args: Array[String]) { println("Hello world") } } 24.1. Introduction 301 Zawiki, Release v0.11-30-g7307413 Class The class syntax is very similar to Java. Imagine that you want to define a Color class which takes as construction parameters three Float values (r,g,b) : class Color(r: Float, g: Float, b: Float){ def getGrayLevel(): Float = r * 0.3f + g * 0.4f + b *0.4f } Then, to instantiate the class from the previous example and use its getGrayLevel func- tion: val blue = new Color(0, 0, 1) val grayLevelOfBlue = blue.getGrayLevel() Be careful, if you want to access a construction parameter of the class from the outside, this construction parameter should be defined as a val: class Color(val r: Float, val g: Float, val b: Float){ ... } ... val blue = new Color(0, 0, 1) val redLevelOfBlue = blue.r Inheritance extends As an example, suppose that you want to define two classes, Rectangle and Square, which extend the class Shape: class Shape{ def getArea(): Float } class Square(sideLength: Float) extends Shape { override def getArea() = sideLength * sideLength } class Rectangle(width: Float, height: Float) extends Shape { override def getArea() = width * height } Case class Case class is an alternative way of declaring classes. case class Rectangle(width: Float, height: Float) extends Shape { override def getArea() = width * height } Then there are some differences between case class and class : • case classes don’t need the new keyword to be instantiated • construction parameters are accessible from outside, you don’t need to define them as val. In SpinalHDL, this explains the reasoning behind the coding conventions: it’s in general recommended to use case class instead of class in order to have less typing and more coherency. 24.1. Introduction 302 Zawiki, Release v0.11-30-g7307413 Templates / Type parameterization Imagine you want to design a class which is a queue of a given datatype, in that case you need to provide a type parameter to the class: class Queue[T](){ def push(that: T) : Unit = ... def pop(): T = ... } If you want to restrict the T type to be a sub class of a given type (for example Shape), you can use the <: Shape syntax : class Shape() { def getArea(): Float } class Rectangle() extends Shape { ... } class Queue[T <: Shape](){ def push(that: T): Unit = ... def pop(): T = ... } The same is possible for functions: def doSomething[T <: Shape](shape: T): Something = { shape.getArea() } 24.2 Coding Convention • Introduction • class vs case class – [case] class – companion object – function – instances – if / when – switch – Parameters 24.2.1 Introduction The coding conventions used in SpinalHDL are the same as the ones documented in the scala doc. Some additional practical details and cases are explained in next chapters. 24.2. Coding Convention 303 Zawiki, Release v0.11-30-g7307413 24.2.2 class vs case class When you define a Bundle or a Component, have a preference to declare them as case class. The reasons are: • It avoids the use of new keywords. Never having to use it is better than sometimes under some conditions. • A case class provides an clone function. This is useful in SpinalHDL where there is a need to clone one Bundle. For example, when you define a new Reg or a new Stream of some kind. • Construction parameters are directly visible from outside. [case] class All classes names should start with a upper case letter class Fifo extends Component { } class Counter extends Area { } case class Color extends Bundle { } companion object A companion object should start with a upper case letter. object Fifo { def apply(that: Stream[Bits]): Stream[Bits] = {...} } object MajorityVote { def apply(that: Bits): UInt = {...} } An exception to this rule is when the companion object is used as a function (only apply inside), and these apply functions don’t generate hardware: object log2{ def apply(value: Int): Int = {...} } 24.2. Coding Convention 304 Zawiki, Release v0.11-30-g7307413 function A function should always start with a lower case letter: def sinTable = (0 until sampleCount).map(sampleIndex => { val sinValue = Math.sin(2 * Math.PI * sampleIndex / sampleCount) S((sinValue * ((1 << resolutionWidth) / 2 - 1)).toInt, resolutionWidth bits) }) val rom = Mem(SInt(resolutionWidth bit),initialContent = sinTable) instances Instances of classes should always start with a lower case letter: val fifo = new Fifo() val buffer = Reg(Bits(8 bits)) if / when Scala if and SpinalHDL when should normally be written in the following way: if(cond){ ... } else if(cond){ } else { } when(cond){ }.elseWhen(cond){ }.otherwise{ } switch SpinalHDL switch should normally be written in the following way: switch(value){ is(key){ } is(key){ } default{ } } 24.2. Coding Convention 305 Zawiki, Release v0.11-30-g7307413 Parameters Grouping parameters of a component/bundle inside a case class is in general welcome: • Easier to carry/manipulate to configure the design • Better maintainability case class RgbConfig(rWidth: Int, gWidth: Int, bWidth: Int){ def getWidth = rWidth + gWidth + bWidth } case class Rgb(c: RgbConfig) extends Bundle { val r = UInt(c.rWidth bit) val g = UInt(c.gWidth bit) val b = UInt(c.bWidth bit) } But this should not be applied in all cases. For example: in a Fifo, it doesn’t make sense to group the dataType parameter with the depth of the fifo because, in general, the dataType is something related to the design, while the depth is something related to the configura- tion of the design. class Fifo[T <: Data](dataType: T, depth: Int) extends Component { } 24.3 Libraries • scala.math._ • scala.sys.process._ • java.util.Calendar 24.3.1 scala.math._ import scala.math._ pow(2,16-1) // 2^(16-1) Pi // 3.1415 atan() sin() 24.3. Libraries 306 Zawiki, Release v0.11-30-g7307413 24.3.2 scala.sys.process._ import scala.sys.process._ cmd = "ls -la" cmd! 24.3.3 java.util.Calendar import java.util.Calendar println(s"Start cordicPipelinedSim Simulation: ${Calendar.getInstance().getTime()} ,→") println(s"End cordicPipelinedSim Simulation: ${Calendar.getInstance().getTime()}") 24.3. Libraries 307