Welcome to
Linux&
OpenSource
Despite heavy competition from other operating systems, Linux has not only
managed to survive but it has thrived. The recent success of the Raspberry
Pi has provided an added impetus for coders, developers and everyday
users to take advantage of the many customisable services and utilities that
the platform offers. Linux & Open Source Genius Guide Volume 5 is
guaranteed to keep any ardent Linux user busy for weeks with the number of
useful tutorials, masterclasses and guides on offer. Weve covered a wide
range of fun and useful tips & tricks from creaing your own Windows 8.1 VM
to taking pictures and video with the Raspberry Pi Camera. Youll nd tons of
useful guides that include dual-booting Linux on any device and an ultimate
Qt masterclass. Weve even featured the essential Linux software for your
everyday needs. So, re up your machine, turn the page, and follow our
experts as they guide you through all areas of using and developing Linux.
Linux&
OpenSource
Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
+44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines
Publishing Director
Aaron Asadi
Head of Design
Ross Andrews
Production Editor
Hannah Kelly
Senior Art Editor
Greg Whitaker
Designer
Abbi Denney
Photographer
James Sheppard
Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT
Distributed in the UK, Eire & the Rest of the World by:
Marketforce, Blue Fin Building, 110 Southwark Street, London, SE1 0SU
Tel 0203 148 3300 www.marketforce.co.uk
Distributed in Australia by:
Network Services (a division of Bauer Media Group), Level 21 Civic Tower, 66-68 Goulburn Street,
Sydney, New South Wales 2000, Australia Tel +61 2 8667 5288
Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.
Linux & Open Source Genius Guide Volume 5 2014 Imagine Publishing Ltd
Part of the
bookazine series
Contents
Page 8r
Build you
own distro
Masterclass
78 Dual-boot Linux on any device
88 Get started with Android
Studio
96 Get to grips with Go Program!
100 Qt masterclass
112 Program with Erlang
Genius Guide
Developer guide
Essential software
Page
78
D
ual-b
Linux oot
on a
devic ny
e
r creating
fo
e
bl
la
ai
av
ds
ho
et
m
nt
re
ffe
di
e
Discover th
everything
ve
ha
d
an
ro
st
di
d
ise
om
st
cu
n
ow
your
working your way in no time
Genius Guide
Remastersys
Remastersys is a tool that extracts the
conguration from a running Ubuntu
or Debian installation and then turns
this into an installable ISO image. This
means that you carry out the customisation using
the standard tools that you normally use, such
as the package management system and GUI
conguration tools. When you have everything set
up the way you want it, you can clone the system and
deploy it. Additionally, you can use Remastersys to
make a clone of a working system.
Pros
You can use the
standard tools
to congure a
distribution
Cons
Needs the
expertise to
carry out the
customisations,
doesn't work on
all distros, has an
uncertain future
Fetch Remastersys
The development status of Remastersys is currently
in transition. At time of writing, the best policy is to
visit the Remastersys website and to cut and paste
the repository details from there. For example, if you
are using Ubuntu 13.10, download the GPG key and
add it from the command line with:
Tip
wget -O - http://www.remastersys.com/ubuntu/
remastersys.gpg.key
sudo apt-key add remastersys.gpg.key
then add
deb http://www.remastersys.com/ubuntu
precise main
to the end of /etc/apt/sources.lst by invoking a text
editor as root.
Following that, type sudo apt-get install
remastersys remastersys-gui in order to install
Remastersys and its GUI.
Using Remastersys
you skip this stage, new users will simply have the
default settings for the distribution.
Finally, build the installation ISO simply by clicking
on the Distribution button on the main menu page.
The ISO is deposited into the /home/remastersys/
folder. Use networking to transfer the ISO le to the
outside of the VM. We usually install Filezilla and
transfer to a local FTP server. You can now boot the
ISO on the target machine and carry out a regular
Ubuntu installation.
The future of
Remastersys
The long-time developer of Remastersys
recently decided to give up development.
Fortunately, he has chosen to release the
source code so that other developers can
take up the mantle. The future of the GUI
portion of the project seems less certain,
but Remastersys is also fully functional
from the command line. For the moment,
the binaries of Remastersys are still freely
available from the developer's web site
(www.remastersys.com).
The situation is constantly in ux,
so search around for the latest forks.
The System Imager project, which uses
Remastersys, is a good source of up-todate information, and can be found here:
http://system-imaging.blogspot.co.uk.
SUSE Studio
SUSE Studio allows you to build a
customised SUSE Linux installation
using a web interface. Although it's
easy to use, that doesn't mean it has
compromised on options.
Initially, you choose a base template such as
KDE Desktop or Server. From this point, you begin
the conguration properly. The rst tab is labelled
Software, which is where you choose software
packages with an interface that is categorised and
searchable.
Pros
Could hardly
be easier to
use, sharing of
appliances is built
into the site
Cons
Build speed varies,
you might hit a wall
with really complex
customisations
Tip
Example deployment:
Business desktop
Here we're going to put together an example
appliance. In this case, the appliance will be a
business desktop that based around GNOME. We'll
add a few customisations as we go along, and we
want to nish up with an installable ISO that we can
use for deployment.
Begin by setting up an account on the SUSE Studio
website (http://susestudio.com). You do this by
following the 'Sign In Or Create An Account' link on the
front page, and it is possible to use one of your existing
social networking accounts such as Facebook or
OpenID if you prefer.
Once you have an account, click on 'Create New
Appliance...'. On the next screen, choose the GNOME
Desktop base template, making sure that you are
selecting from the templates that relate to the latest
version of SUSE Linux. Scroll down to the bottom of
the window to choose your architecture and then
give your appliance a meaningful name. Click OK, and
after a short delay, we can start honing the appliance
to match our own requirements.
Start customising
As this is a business desktop, let's add LibreOfce
to it. To do this, select the Software tab and type
the word 'libre' into the search box. The search
is real-time, so you should soon be presented
with a list of matches. Note that they are sorted
by popularity and the package called LibreOfce
should be at the top of the list. Click the '+add'
button to add this package. For a big software suite
such as LibreOfce, it may take a few moments
for the interface to register all of the needed
dependencies. Add Firefox too. Staying in the
Software tab for moment, it's worth noting that you
are able to add extra repositories and even custom
RPM packages.
We'll select the localisation options next.
Proceed to the Conguration tab and select the
General sub-tab. In here, select the English (UK)
option as the language and keyboard layout and
Europe and United Kingdom as the region and time
zone respectively.
Note that you could also have selected Ask on
rst boot for any of these options as well.
Genius Guide
Tip
Q This screen shows us conguring details such as the users and network settings in the Conguration>General page
Ubuntu minimal
installation
Canonical provides a minimal Ubuntu
install CD. It's smaller than the regular
installation ISO and it installs a minimal
version of the distribution. At its most
basic, it gives the user a command line, network
connectivity and not much else. From this barebones beginning, it's possible to selectively add
components while leaving out most of the cruft that
tends to come with a standard distribution.
We're going to work from within a virtual machine
for safety and convenience. In our case, we're
going to use Oracle VirtualBox but any of the major
virtualisers will work. Once we have it set up the way
we want it, we can use Remastersys to turn it into an
ISO that can be distributed. We can then transfer this
ISO from within the VM to an FTP server.
Pros
Excellent way of
keeping the distro
standard yet
minimal too
Cons
Time consuming
to carry out from
start to nish
Example deployment:
Minimal Openbox Desktop
Fetch the installation media from http://tinyurl.com/
ygawub and create a new virtual machine. 512MB is a
sensible minimum when allocating memory, but more
memory can also help greatly with speeding things
up. An 8GB hard disk file should be adequate for most
people's requirements. It's usually worth allocating as
many CPU cores to the VM as you can.
Tip
Clonezilla
Q Fetching the initial set of base packages
Genius Guide
Tip
Using a minimal
install
CD like this will cr
eate
quite a lot of netw
ork
traffic while it is
pulling packages
through
Q Use automatic partitioning
Customisation decisions
When the base installation is complete, you will
be presented with the Software selection menu.
At this point you have to make a decision. If you
want to, you can select one or more of the provided
templates. For example, you could select Kubuntu
desktop option and have a fairly complete desktop
system from the beginning.
There are other options available to establish
a LAMP web server or a Mythbuntu media
system, and many others too. Most of the rest
of this tutorial assumes that you don't select
any of these options so that we can customise
completelyfrom scratch.
More downloading and installation follows.
Conrm that you want GRUB installed to the MBR
when asked. This brings us to the end of the initial
installation phase. Next, eject the ISO and reboot
the VM when prompted.
Tasksel
First reboot
Upon booting the minimal installation for the rst
time, you should be prompted for your username and
password. We can now start to customise the system.
Install X.org server and Openbox window manager
(feel free to substitute another WM/DE if you prefer)
by typing sudo apt-get install xorg openbox.
When this has completed, type startx to test the GUI.
Click on the backdrop to bring up a menu that will
allow you to launch a terminal window.
Now you can begin customising the system. Make
things as comfortable as you like, but remember that
anything that is installed on this system will end up on
the target system. sudo apt-get install firefox
synaptic lxterminal mousepad lxdm will install
and set up the Firefox web browser, Synaptic (GUI
Ubuntu Builder
Ubuntu Builder is a GUI application that
allows you to take the contents of a
standard Ubuntu installation ISO and
modify it to create a new, customised
ISO for redistribution. It's a fairly simple application,
however, and not designed for deep modications of
the type that some of the other methods allow.
Ubuntu Builder is a standalone application
that runs on your desktop, and it even runs on
distributions other than Ubuntu. It works by
modifying a standard Ubuntu installation ISO,
downloading and inserting or removing packages
for you.
Tip
Pros
This is a nice,
simple tool there's little you
can do to make this
all go wrong
Cons
Not a huge amount
of customisation
depth. Lacked
polish and felt a bit
buggy in use. ISO
build process is
also a bit slow
Q The end result: Ubuntu 13.10 with MATE, a more traditional desktop
01
The installation
02
03
Fetch ISO
04
You can fetch the current ISO by clicking on the 'Get Ubuntu' button in the main interface. However,
it's worth mentioning that we actually found manually fetching the latest standard install ISO from the Ubuntu
website to be more reliable.
05
Genius Guide
Tip
06
07
08
48
60
Genius Guide
Thepreviewcanbemadefullscreeninthesame
window,insteadofopeningadifferentpageor
tab this reduces server load
Resources
Rainloop:
http://rainloop.net/downloads
A server
Cutoutthemiddlemanbymanagingyourown
webmail for personal accounts and avoid any
unnecessary downtime
Genius Guide
01
Server
ready
01
Server ready
$ wget http://repository.rainloop.net/
v1/rainloop-[current version].zip
And then unzip it to proceed.
04
07
Log in
08
Add domains
09
Domain ports
Elevate permissions
02
Set up directories
05
Final permissions
03
Download Rainloop
06
Access Rainloop
10
Contacts database
15
Log in to
your email
11
exit;
12
Enable Contacts
13
14
15
http://[IP or domain]/webmail
And use your normal login details for the mail address
16
Add a signature
Genius Guide
16
17
Manager folders
19
22
More on social
23
More to come
20
18
Add a
signature
21
Scanning an
iPad
Scanning a
Linux machine
About
Nmap
Scanning an
HP printer
Resources
Nmap: www.nmap.org
WireShark site: www.wireshark.org
RFCs: www.ietf.org/rfc.html
Internetworking with TCP/IP, Volume
I, Douglas E. Comer, Prentice Hall
DiscoverNmapandlearnhowtousetsharkto
examine Nmap trafc
Nmap is an open source tool created by
Gordon Fyodor Lyon that supports port
scanning, operating system detection
and version detection and is very famous
it has even been seen in movies, including The
Matrix Reloaded and Elysium.
Nmap stands for Network Mapper and supports
more than 15 scanning techniques. Nmap can
be useful to network administrators as well as
advanced users and hackers. It can be used for
securing your own network, but it can be also used
for hacking (or cracking) purposes.
Genius Guide
03
01
Get Nmap
02
A simple
scan
04
05
06
07
$ nmap V
Nmap version 6.00 ( http://nmap.org )
Platform: x86_64-unknown-linux-gnu
Compiled with: liblua-5.1.5 openssl1.0.1e libpcre-8.30 libpcap-1.3.0 nmaplibdnet-1.12 ipv6
Compiled without:
$
03
A simple scan
$ nmap localhost
The output gives you information about the open
08
Nmap output
options
$ nmap 192.168.2.0/24
09
$ nmap -sU
10
iL LUD
Exclude hosts
$ nmap
ex_IPs
sP 192.168.0.0/16 --excludefile
11
Randomise hosts
nmap --randomize-hosts
12
13
Scan scanme.nmap.org
14
Genius Guide
22
Capture
the trafc
21
22
$ sudo nmap
sU 192.168.2.10
$ sudo tshark
17
18
19
20
Scan an HP printer
23
w UDPscan.tcpdump
15
16
Scan an iPhone 5
24
Resources
VirtualBox:
www.virtualbox.org
Sometimes
using
Windows
is
a necessary evil. A lot of ofce
environments still use Windows, and
sometimes youll need Windows-specic
applications and software if you want to work from
home. Theres also the problem of developing crossplatform apps constantly switching between
operating systems is time-consuming and can,
frankly, get exhausting. The solution to a lot of these
issues is to never dual-boot your machinein the rst
place, but instead to virtualise Windows, in particular
Windows 8.1, on your computer.
Genius Guide
01
01
Install VirtualBox
02
03
Volatile memory
Install
VirtualBox
04
Storage space
05
Storage type
06
System settings
07
Windows disc
08
First boot
15
09
VirtualBox
additions
Install preparation
10
Storage
Unless you plan to do any crazy dualbooting, you will only need to select the empty
space on your hard drive. Otherwise, Windows
gives you tools that lets you create partitions
so that you can install a Linux distro or other
Windows version elsewhere.
12
Personalise
13
Microsoft account
11
Wait for it
Youll need to log into, or set up, a Microsoftbased account to use the latest versions of Windows.
If you already have one, you can enter it here and log
in. Otherwise, youll need to link an email address to a
new account.
14
Final setup
15
VirtualBox additions
Genius Guide
17
16
Shared folders
17
Share settings
19
Host USB
Share
settings
20
18
VirtualBox setup
21
22
Boot to desktop
23
Finish up
Understand regular
expressions
Advisor
Richard Smedley
started using computers long before
WYSIWYG, and still maintains that
the command-line, and Emacs,
is the most productive working
environment
Resources
Server like LAMP/WAMP/MAMP
ownCloud plug-ins:
apps.owncloud.com
Genius Guide
09
01
Word up!
02
Reserved character
POSIX
classes
05
Mmmmm, cooooool
03
Atlantic crossing
08
A to Z Guide
09
POSIX classes
06
No number
07
Start to nish
04
Colourful?
10
ASCII style
11
Beyond grep
12
Bye bye,
IPv4
15
13
Ranging repeat
Validation
Genius Guide
23
A regexp
too far
21
Perl -pie
22
Perl one-liner
23
24
Tagged offender
18
Boundary guard
19
Literally meta
20
Lazy = good
16
Back to basics
17
Why vi?
Resources
TexLive:
www.tug.org/texlive/
Genius Guide
06
01
02
TeX Live
03
Right-to-left
08
WYSIWYM formatting
09
05
Just a fraction
06
Right-to-left
07
Booked up
04
e=mc2
10
Macro power
15
Draught preview
16
Special character
11
12
Boilerplate
17
18
Error messages
13
Make a date
14
Desktop calculator
Genius Guide
19
Pretty pictures
20
txt2tex
21
23
TeXnicians
and TeXperts
22
En passant
\fenboard{r5k1/1b1p1ppp/p7/1p1Q4/2p1r3/
PP4Pq/BBP2b1P/R4R1K}
With TeXmate you dont need the numbers to end
lines.
23
24
Try it out
Resources
n Latest Raspbian Image
raspberrypi.org/downloads
A router or switch
A USB wireless dongle that
supports Access Point mode
A Wi-Fi device to test with
Genius Guide
01
02
03
04
Congure hostapd
DAEMON_CONF="/etc/hostapd/hostapd.
conf"
We then need to create the hostapd cong le at the
path specied above. It should have the following
contents:
interface=wlan0
bridge=br0
driver=nl80211
country_code=UK
ssid=pinet
hw_mode=g
channel=1
wpa=2
wpa_passphrase=super_secret
wpa_key_mgmt=WPA-PSK
ieee80211n=1
wmm_enabled=1
Note that if you dont have a wireless N capable
device, or are having stability issues, youll want
to leave out the last two lines. You may also need
to change the wireless channel if you are having
stability issues. Once youve done this, you can
start the hostapd daemon with sudo /etc/init.d/
hostapd start.
Bridge interfaces
auto lo br0
05
06
07
interface=br0
dhcp-range=192.168.0.2,192.168.0.254,
255.255.255.0,12h
Reboot for the changes to take effect. Youll want to
disconnect the Raspberry Pi from your existing network
at this point, otherwise there will be two DHCP servers
on the network.
08
Try it out
Michael Reed is
a technology journalist
and hes been hacking
away at Linux for over
15 years
Resources
Client computer running Linux
Remote computer running Linux
LAN
Genius Guide
01
02
Install SSH
07
05
Copy key
06
Test SSH
03
04
Generate keys
08
12
Connect to VNC
13
Install Webmin
09
10
11
Genius Guide
14
Test Webmin
16
15
18
19
Set up ddclient
You can ask the person who runs the remote system
to simply visit whatismyip.com and email their
current IP address to you, but setting up dynamic
DNS is a more robust solution. Go to the No-IP
website (www.noip.com) and set up a free account.
Now install the ddclient package.
17
Port forwarding
protocol=dyndns2
use=web, web=checkip.dyndns.com/, webskip='IP Address'
server=dynupdate.no-ip.com
login=user name
password='password'
[hostname].no-ip.biz
run_daemon=true
Now restart it by typing sudo service ddclient
restart.
Resources
Server like LAMP/WAMP/MAMP
ownCloud plug-ins:
apps.owncloud.com
Genius Guide
01
Introduction
02
03
Installing ownCloud
04
05
07
credentials. The client then connects to the server
seamlessly and starts syncing. The app is highly
congurable and lets you change many settings,
including bandwidth usage and multiple sync folder
support. Also, it is available for all the major platforms:
Windows, Linux and Mac OS X.
06
Genius Guide
08
09
10
Journal plug-in
Displaying statistics on
the captured data
Resources
tshark:
www.wireshark.org/docs/man-pages/tshark.html
Wireshark:
www.wireshark.org
www.ietf.org/rfc/rfc2131.txt
Python script
avaliable online:
http://bit.
ly/1gH6W0S
Genius Guide
01
$ tshark -v
02
Capturing network
data using tshark
03
04
05
Applying lters
after network capturing
06
07
08
Genius Guide
09
10
11
if ( ! is_ipv4($sourceIP) )
{
print "Packet number $frameNumber
contains a bogus source IP!\n";
}
You can alter the script in order to catch the type of
errors you want, such as trafc from unwanted hosts
or trafc to specic TCP or UDP ports.
12
Android-powered devices
such as phones and tablets
can also connect
Resources
A Linux box
A second Linux box on a LAN (optional)
An Android phone (optional)
A Microsoft Windows box (optional)
Genius Guide
chmod 400
/etc/openvpn/{server.key,server.
crt,ca.crt,ta.key}.
01
02
06
07
08
03
04
05
12
09
11
10
13
Genius Guide
14
17
15
20
18
16
19
Gnuplot can do
3D too
Resources
Gnuplot homepage:
www.gnuplot.info
Genius Guide
01
Install gnuplot
02
First run
$ gnuplot -V
gnuplot 4.6 patchlevel 0
If you run the gnuplot command without any
arguments you will enter the gnuplot shell, as shown
in the screen above.
Type quit at the gnuplot prompt to leave the gnuplot
shell and return to the UNIX shell.
03
04
07
$ ./LUD.py
gnuplot> set term png size 2048, 2048
gnuplot> set output "LUD.png"
gnuplot> plot cos(x)/x title "Using the
Gnuplot Python module"
05
09
08
06
#!/usr/bin/python
import Gnuplot
gp = Gnuplot.Gnuplot(debug=1)
gp('set term png size 2048, 2048')
gp('set output "LUD.png"')
g5 = Gnuplot.Func(cos(x)/x', title= 'Plotting a
function with py-gnuplot')
gp.plot(g5)
The import Gnuplot command loads the correct
Python module, whereas the gp.plot(g5) command
plots a graph that is called g5. The gp(set term png size
2048, 2048) command defines the output file format
and its dimensions, whereas the gp('set output "LUD.
png"') command dictates the filename that will be used
for saving the output.
Going 3D!
Genius Guide
10
11
12
$ gnuplot test.script
If youre inside gnuplot, run the following command:
Resources
Secure Shell:
goo.gl/RYHiK
FireSSH:
ressh.net
Shellinabox:
https://code.google.com/p/shellinabox
MindTerm:
www.cryptzone.com/products/mindterm/
DropPages:
droppages.com
Pancake:
pancake.io
Genius Guide
01
04
02
Installation
03
Closing connections
07
Saving connections
08
Terminal options
05
06
Working in SSH
09
Installation
11
Connection options
Closing connections
14
Saving connections
15
10
13
12
Working in SSH
Genius Guide
18
16
Installation
17
20
22
Closing connections
23
Saving connections
24
Where to now?
19
21
Connection options
Because this is the leanest of the webbased SSH clients available, you simply dont have
the same level of conguration options. Right-
Resources
Git:
git-scm.com/
A GitHub account:
https://github.com
Genius Guide
01
git init
A .git directory is created: you now have a working
tree, and youre now ready to commit changes to
your repository. Initialisation is only done once per
repository.
02
Installation
05
Staging post
07
Where was I?
08
Undone by stages
03
04
A tree, initially
06
Status
09
10
Commit objects
12
Branch line
14
Releasable code
11
HEAD master
13
Committed to change
15
Git manages projects in the form of files
so not just code
66 Linux & Open Source Genius Guide
Genius Guide
git diff
21
Pushing code
22
Time-saving aliases
18
Ignorance is bliss
16
Branch log
17
Conicting code
19
20
Fetch
23
24
Go use Git
Resources
Raspberry Pi
Raspbian:
www.raspberrypi.org/downloads
Pi Camera
Ashtons picam module:
https://github.com/ashtons/picam
Genius Guide
01
Attach Camera
02
Pi preparation
05
Record video
followed by:
$ sudo apt-get upgrade
03
$ raspistill -o image.png
import picam
i = picam.takePhoto()
i.save(/home/pi/test.jpg)
Advanced photos
$ sudo raspi-config
04
Picam photos
08
Take pictures
07
Pi cong
06
Picam
import picam
import time
ii = picam.takePhotoWithDetails(640,480, 85)
filename = /tmp/picam-%s.jpg % time.
strftime(%Y%m%d-%H%M%S)
ii.save(filename)
09
01
Genius Guide
04
Camera setup
Just
in
case
you're
using
a
new install of Raspbian, you'll need to
make sure that the camera module is
enabled.
Make
sure
that
you've
plugged
in
the
camera
while
it's off, and then in the LXTerminal use:
$ sudo raspi-config
Go to the Enable Camera option and select to
enable it. You may need to restart in order for it to
actually take effect.
05
First tests
We can now do a quick test of the slowmotion capabilities by entering the following:
02
Updating
the
rmware
is
very
straightforward; back in the terminal just type in the
following:
$ sudo rpi-update
Alternate updating
Problems
have
been
known
to
occur with the rmware update and there
are two main ways you can try and x
them. First of all, try updating Raspbian
with apt-get update followed by apt-get
upgrade. If that method doesn't work,
try using the rmware updater like so:
Playing it back
08
Other uses
09
Final warnings
03
07
06
As
well
as
being
able
to
record
video
at
90
frames
per second, you can also go down to
60. You cannot increase the resolution
though, so it's stuck to 640 x 480 for both
90 fps and 60 fps video for the time being.
This isnt a
hardware hack a
spare SD card can
be used for the Tor
router, and other
SD cards can be
used for different
functions without
any problems
Connect
everything over a
wireless network
no need to
directly connect
to the Pi with a
cable
Resources
A Raspberry Pi
Raspbian:
www.raspberrypi.org/downloads
Genius Guide
06
Set up DHCP
07
Server address
01
Install Raspbian
04
SSH connection
02
Set up Raspbian
03
Pi IP
subnet
192.168.42.0
netmask
255.255.255.0 {
range 192.168.42.10 192.168.42.50;
option
broadcast-address
192.168.42.255;
option routers 192.168.42.1;
default-lease-time 600;
max-lease-time 7200;
option domain-name "local";
option
domain-name-servers
8.8.8.8,
8.8.4.4;
}
Save and exit.
05
Install DHCP
08
DHCP server
$ sudo
server
nano
/etc/default/isc-dhcp-
INTERFACES="wlan0"
14
Incoming Wi-Fi
Network addressing
net.ipv4.ip_forward=1
Save this, and then nish by running:
12
10
Static IP
WLAN conguration
interface=wlan0
driver=rtl871xdrv
ssid=[access point name]
hw_mode=g
channel=1
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=[password]
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
13
Hostapd
15
IP tables
16
Apply conguration
So that this still works after a reboot, type:
DAEMON_CONF="/etc/hostapd/hostapd.conf"
11
WLAN creation
up iptables-restore
ipv4.nat
<
/etc/iptables.
Genius Guide
17
Wi-Fi nal
sudo
sudo
sudo
sudo
18
Install Tor
19
Tor congure
Put this below the FAQ comment:
21
Reroute
Route all DNS trafc rst, using:
23
Logging
$ ls -l /var/log/tor
24
20
Table ush
$ sudo iptables -F
$ sudo iptables -t nat -F
22
Masterclass
Become a Linux power user
78 Dual-boot Linux on any device
Give yourself more choice with your computers
as we attempt to dual-boot anything and
everything from Windows to Macs
78
88
100 Qt masterclass
Get your head around event-driven
programming, responsive development, and
reading and writing files, all with Qt
100
Dual-booting
a PC is fairly
simple, but what
about other
devices that
we use or carry
around with us?
76 Linux & Open Source Genius Guide
Genius Guide
Masterclass
Dual-booting
a PC is fairly
simple and
inifinitely
useful but
what about
computer-like
devices that
we use?
Genius Guide
Dual-boot
Linux on any device
Give yourself more choice with your computers as we
attempt to dual-boot anything and everything
Dual booting is not quite one of the dark
computing arts its not like youre
compiling Gentoo or anything but theres
still an element of risk and reward in
the process. Dual-booting a PC is fairly simple, and
innitely useful, but what about computer-like devices
that we use or carry around with us? We decided to see
if we could bring the convenience and power of dual
booting to a range of other everyday devices and give
Warning!
It should go without saying that everything were attempting
in this feature carries some risk of losing all your data. While
you should always have a backup solution in place, we know
it can sometimes slip your mind. This is your reminder
to make sure everything you need is backed up, saved
elsewhere or ghosted in case of any problems.
Masterclass
Dual-boot your PC
Get more out of your PC by adding a second Linux distro
Linux distros are basically designed
these days to work well with each other in
multi-boot situations. Modern GRUB will
automatically detect other bootable distros
during an install and add them to the list. Even if it
doesnt, its fairly simple to add them. Going deeper,
you can mount partitions across multiple distros
for sharing les, proles and space. To get started,
though, youll have to create some space on your hard
drive. If you used the standard installation tools with
your main distro, youre likely using up all the space.
Making space
The most efcient way to set up a hard drive and
share multiple distros
Reclaim space
New partitions
At the very least, your system will already have a root partition for
your distro, plus a swap partition. This swap can be shared by both
distros, so all you need to do is trim the storage partition for the
main distro. Most live discs and installers will include partitioning
tools. However, dedicated rescue and admin distros such as
SystemRescueCD also include them.
Genius Guide
Recover
If you do decide to reorder the entries, youll then need
to run:
$ sudo update-grub
Proper order
One of the first customisations youll usually want to
make to a new boot menu is the default selection and
perhaps the timeout. To do this, enter the terminal and
open the grub.cfg file with:
#!/bin/sh -e
cat << EOF
menuentry "Linux distro" {
set root=(hdX,Y)
linux /boot/vmlinuz
initrd /boot/initrd.img
}
EOF
chainloader (hdX,Y)+1
}
EOF
GRUB
GRUB 1, while simpler looking, needs more
information to boot into Linux properly:
Which GRUB?
There are two versions of GRUB: the older
GRUB 1 (or GRUB Legacy) and the newer
GRUB 2. Some prefer GRUB Legacy as
parts of it are easier to use; however,
GRUB 2 can be customised a lot more with
themes and images and smarter boot
ordering. Generally though, if your main
or primary distro comes with one version
of GRUB, you should continue using that
rather than installing a different version
over it.
#!/bin/sh -e
cat << EOF
menuentry "Windows" {
set root=(hdX,Y)
title Windows
rootnoverify (hd0,0)
makeactive
chainloader +1
Masterclass
Fragmentation
Windows Vista and later has
automatic defragmentation tools
built in to cut down on the issues
previous Windows systems used
to encounter. Its not perfect,
though, and NTFS is still prone to
fragmenting more than Linux journal
le systems as les are updated
or changed over time. We suggest
invoking the Defrag tool from within
Windows by going to Start>All
Programs>Accessories>System
Tools>Disk Defragmenter in Windows
7 and later.
Secure boot
Secure Boot and how it affects
UEFI and dual booting is still an
issue not all distros work with
it. However, Ubuntu, Fedora and
their derivatives all work just ne on
systems with Secure Boot without much ore than
disabling it in the UEFI menu at startup.
Genius Guide
01
Make space
03
Choose wisely
05
02
Install Windows
04
Live booting
Restoring GRUB
$ update-grub
Masterclass
01
Create swap
02
Room to share
03
First roots
05
GRUB reinstall
04
Second distro
06
GRUB update
$ sudo update-grub
It will automatically detect the other install and
update the boot menu next time you boot from the
hard drive.
Genius Guide
Adding ROMs
Find the .zip le of your preferred alternate ROM
and download it to the storage of your Nexus
device. Do not extract it. Reboot the device
to recovery with adb reboot bootloader (on a
connected PC), or turn it on by holding down
volume-up and power and select recovery from
the fastboot menu. Youll be sent to the TWRP
recovery, which now has a new option under
Advanced called MultiROM. Select this, then
Add ROM and hit Next to then locate the zip le
we just put on the device. Swipe to install.
Compatible
devices
Nexus 4
Q
QNexus 7
(2012)
Nexus 7 (2013)
Q
QMultiROM Manager handles all the flashing and
advanced installing for you
Masterclass
Dual-boot a Mac
Apple products can still get a bit of open
source love you just need the right tools
While the quality of Apple software
is debatable on a number of levels,
the hardware inside the rms Mac
computers is often extremely good.
Since the switch to Intel-based architecture
a few years ago, more Linux distros have
technically been able to work on Macs, albeit
with some restricted drivers installed to make
the most of them. Its not as straightforward as
the other setups weve tried in this guide, though,
and involves installing a custom bootloader to
allow us to chainload into live discs and GRUB.
Once this is done, however, you can enjoy a lot
more freedom from your Mac and make full use
of its powerful, high-quality hardware.
01
02
04
Live boot
05
Restricted drivers
06
Boot order
Some rEFInement
03
Genius Guide
Dual-booting a Raspberry Pi
Short of SD cards for Pi projects?
Put two Pi images on one card
The Raspberry Pi, with access to only
a limited SD card, may not be the most
obvious dual-bootable device. However,
due to the recent release of the New Out
Of Box Software (NOOBS), multiple Pi distros can be
installed onto one card. The catch is that you need
to have used NOOBS in the rst place to get the
dual-booting setup to work.
If you havent already done this, installing NOOBS
onto an SD card is easier than copying an image
directly to it. Using the same kind of partitioning
tools weve used to shrink space and create new
structures, wipe an SD card you wish to use on
the Pi and create a FAT32 partition that lls up the
card. Preferably, as were dual-booting, you should
use as large a card as possible, with at least 2GB
for each distro. Once the formatting is complete,
download NOOBS from the Raspberry Pi website
and extract the les onto the SD card, then plug it
into the Raspberry Pi and turn it on. You can then
select which distros you want to install and it will
automatically install them all to the disc, and create
a bootloader to use at system startup.
Raspberry distros
Home & Projects
Raspbian is the preferred distro of the
Raspberry Pi, with tons of learning
software and easier access to some
of the more interesting Pi projects and
hardware. Its easy to set up and can be
used as a standard desktop OS.
HTPC
Its a tough call between OpenELEC and
Raspbmc both run on the excellent
XBMC. However, OpenELEC has been
around for longer and has some very
special speed optimisations that put it
just ahead of Raspbmc.
QIf you've previously used NOOBs to install a distro, you can get back to the OS selector by holding down
shift as you turn it on
Customisability
Arch Linux on Raspberry Pi allows you to
build it from the ground up, only coming
with a command-line interface and a
basic Linux setup to start with. This allows
you to totally customise it and only use the
packages and software you wish.
Genius Guide
Android
Studio
Get your head around the early access
preview of the next stage in Android
development
Masterclass
Introducing Android Studio
The new Android Studio is based on IntelliJ IDEA, a much smaller and streamlined
IDE than Eclipse. Android Studio utilises its features to create an all-in-one Android
development environment with a smart visual view that is great for people just
getting into app development, and the standard text editor for those who know
their way around Java and the Android API.
Installation is very simple as well the les contain both the IDE and the
SDK youll need to create your apps, so you wont need to install the SDK via ADT
separately like you will have done with Eclipse if youve developed for Android in
the past. The Studio allows you to edit how the SDKs are utilised, how imports and
exports work, and even has a plug-in manager.
Recent Projects
The recent
projects view
allows you to go
straight into any
project you wish
to work on without
having to look in
the Open Project
prompt
New Project
Start a new project
by going through
the handy Android
new project wizard,
selecting API levels
and setting the icon
Installation
01
Download
02
Runtime
Use cd in the terminal to navigate to
$ ./studio.sh
If it asks about your Java settings, for now
press Enter, as we can x that later if it becomes
a problem.
03
First run
Genius Guide
Key features
Helpful shortcuts
Development views
Command look-up
(autocomplete command name)
Ctrl
Shift
Project quick x
Alt
Enter
Reformat code
Ctrl
Alt
Virtual devices
Test your apps on a virtual
device that you dene, either
by using settings for the main
Nexus devices, or by using
generic settings for differentsized Android phones or
tablets. You can edit the
system settings to limit or
increase RAM, and even allow
it to use the system GPU if you
need it to. Its not perfect, but
its a great way to quickly test
functionality.
Ctrl
Ctrl
Generate method
Alt
Insert
+
+
Alt
Alt
Jump to source
F4
Delete line
Ctrl
Ctrl
Alt
Shift
Build
Debugging
Eclipse migration
For existing Android developers, its easy to migrate
from Eclipse and the ADT to Android Studio. The
tools are already in place to export the necessary
les from Eclipse, and Android Studio includes a
handy feature that allows you to then import them,
and any other Studio le. This is helpful now and
will be essential when it replaces Eclipse.
Ctrl
F9
Shift
F10
Alt
Masterclass
FAQ
Since Android Studio is still under some
development, there are some bugs that still
need to be ironed out. Here are a couple of
known issues with Android Studio that you
can work around.
01
02
Set image
03
Activity selector
04
Activity name
05
Project structure
06
Views
Migration
Its quite easy to export existing projects from
Eclipse and then import them into Android
Studio. First of all, make sure your ADT plug-in
is up to date, then select File and Export. Open
Android from there and select Generate Gradle
les, then your projects to export before clicking
Finish. In the basic Android Studio window, click
on Import project, nd the build.gradle le and
then press OK at the pop-up. You should then be
able to start development on the project within
Android Studio.
Genius Guide
A view to develop
The two views for Android Studio serve different purposes and people. The
default visual view allows you to drag and drop functions onto the interface, with
guidelines to make sure you keep them aligned with other UI elements. This then
adds the elements to the code, so you can edit them further in there.
Live preview
See a live
preview of the
way your app
will look, even
while using the
text mode
The text view works like any good IDE, with a hierarchical view of code, code
navigation tools, autocomplete and, of course, proper syntax highlighting.
Whichever view you use is up to you however, you will ultimately have more
control with the text view.
Toolbar
Quick access to
preview and debugging
tools, along with the
ability to change the
theme, activity type
and the device preview
Component tree
Even in the visual
view, you can break
down the code
in the individual
components to see
how they work
Useful resources
There are plenty of online resources that you can
use to help you with your development whether
you need to gure out a more elegant method to
create a specic function, or need to wrestle with
some bugs. Heres a list of some of the places you
should visit:
Android Developer Site
developer.android.com
As well as the place to get Android Studio, the
Developer site has regular posts on interesting
Masterclass
Make your rst application
Creating your rst application in Android Studio is really very easy,
and well start by showing you the simplest one of all the classic
Hello World app. All basic apps, when created, have Hello World
01
Visually
02
Relative text
<TextView
android:layout_height=wrap_content
android:text=Hello World!
android:id=@+id/textView/>
The layout variables can also be set as xed pixel
width/height.
04
Quit button
05
Imported
Hello code
android:layout_width=wrap_content
06
Coded actions
03
import android.widget.Button;
This allows us to use some extra Android functions to
press and use the Quit button.
code:
import android.view.View;
import android.view.View.OnClickListener;
Code listing
Package name
The name of your package
according to the Android
system
import functions
Import the various functions
we need to get the code to
work on an Android device
MainActivity class
The MainActivity class includes
all the functions in our main
activity that we created
Main layout
This sets what the main
layout, and displays it
Quit button
The section containing
the code to make sure our
button (with id button)
properly quits the app
with System.exit
Settings menu
This creates the Android settings
menu that appears at the top of
the app
package com.linuxuser.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Genius Guide
Home screen
Emulate a list of
Android devices,
from Nexus
phones and
tablets to generic
phones dened by
screen resolution
Physical buttons
Theres a range of
physical buttons you
can use that work on
certain devices, with
power and volume
working on all
Hardware specs
Edit specic
hardware variables
to better emulate
certain aspects of
a device, or give it
more power via your
host system
Android buttons
Software buttons
are included on
the virtual device,
as they are part of
modern Android
01
02
New device
03
Virtual reality
Debugging
Android Studio includes tools to debug
the apps you create. To use them, rst
make sure a device is running to emulate
the app. Then, click the Debug button
in the shape of a green bug and the le
will rebuild and launch on the device. This
time, though, it will bring up a full logging
window, a console and a debugger with
full tools to gure out where problems
may be occurring in your apps.
QUse
Android
Studios
debugging
tools to
analyse your
code
Masterclass
Sean M Tracey is a
creative technologist at a
leading digital agency. He
spends a lot of his time living
inside of Node.js, Python
and Arduino
Assigning variables
in Go is very
straightforward
and exible
Setting constants
is much stricter, for
obvious reasons
Function denitions
are very user-friendly
in design and
implementation
Installing Go
If youre quite lucky, you might be able to install Go
with one swift command of the terminal:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//Example 1:
a = 1
b = 2
//Example 2:
a, b := 1, 2
//or
var a, b int = 1, 2
//Example 3:
var a, b, c = 1, true, "Hello"
//Constants can only be set like this
const x = 12
//##### Functions
//Example 4:
func example(x int, y int){
fmt.Println(x + y)
}
//Shorthand
func example(x, y int){
fmt.Println(x + y)
}
//With return
func timesTwo(x, y int)(int, int){
return x * 2, y * 2
}
func main(){
h, i := timesTwo(2, 6)
fmt.Prtinln(h, i) // h == 4, i == 12
}
//Alternative way with namesd variable return
func timesTwo(a, b int) (x, y int) {
x = 1 * 2
y = b * 2
return
}
Genius Guide
sudo ./all.bash
And then go and make yourself a cup of tea. Like most
source builds, this can take a little while. Just before
the Bash script exits, you should see something along
the lines of:
Wheres it going?
New languages pop up all the time. So what makes
Go different?
Go is a really exciting language: its quick to
learn, fun to write and really fast at running.
Its true, new languages appear all the time.
Anybody and their mother can learn how to
write a compiler, but Go has some of the best
software engineers in the world tinkering
away with it. Its got a long way to go before it
can stand to challenge the likes of Python or
Java and its going to take time for people to
acknowledge it as a genuine competitor, but
Single statement:
PATH="$HOME/gosrc/go/bin"
Now, enter go in your terminal and you should see the
help dialog listing all the commands we can invoke
when executing a Go script.
import "fmt"
import "math"
import "path"
Hello world
Lets write a quick Hello world. Create a le called
lets.go. If you execute:
go run lets.go
You should see Hello, world pop up in your terminal.
Lets step through what weve written here. package
main is basically Gos way of creating a namespace
for the code contained in the le. If we were to write,
say, a module for use in other programs then we could
use most any name we like. The general convention
is that the package name is the same as the import
path. import(fmt) simply imports the stand I/O
1
2
3
4
5
6
7
package main
helloWorld.go
code listing
Variables
Variable declaration is a little different in Go than
it is in other languages. There are multiple ways of
achieving the same effect, If you look at Example
1 on the preceding page, it can also be written like
Example 2.
In each of these instances, a == 1 and b == 2.
Youll notice that when we used the var keyword, we
declared the variable type just before we assigned a
value. When we declare the variable type at the end
of this declaration, all of the variables will be that
type. If we are assigning values in this way and the
types vary then Go will assign them based on the
value passed.
In Example 3, a will become an integer, b will be a
Boolean and c will be a string. Go has constants too.
They can be set like so:
import("fmt")
const x = 12
func main(){
fmt.Println("Hello, world")
}
But you cant declare the type like you can with a
variable. Thats inferred from the value.
Functions
Q
Now that we have a working environment, we
Google has
included a handy
Bash script to
install and test
Go for us
Linux & Open Source Genius Guide 97
Masterclass
Slices
Arrays in Go are interesting things. For a start, theyre
known as slices. You can create a slice that has a set
capacity but no length. If we know what were going
to put into a slice right away then we can create one
like this:
numbers := make([]int, 5)
If we assign numbers[0] = 2 it would behave as wed
expect, but if we try to assign numbers greater than
the length of the slice well get an out of range error.
Note that slices can be sliced into smaller slices.
For instance, if we have a slice of numbers, we can
Packages
Structs
Go has structs which are kind of like classes in C or
objects in JavaScript. We can create instances of
structs to store variables. Lets say we wanted a
way of storing map co-ordinates. Lets look at the
example code below.
When we set the variable, the order in which we
pass the variables into the struct is the order that
the properties within will be assigned. Reassigning
a value after its creation is simple:
package Bournemouth
london.longitude = 0.1075
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Genius Guide
requestStore.go
-URL=[ANY
VALID
WEB
Finishing up
Its always hard covering the ins and outs of a new
coding language, since every individual aspect of
the latter could easily take up this space on its own.
Hopefully, this tutorial will have given you enough of a
reason to get excited about using Go in some of your
day-to-day projects.
Arrays in Go are
interesting
1 package main
distance.go
2
code listing
3 import(
4
"fmt"
5
"math"
6
)
7
8
9 var places = [3]Coordinates{ Coordinates{51.5072, 0.1275, "London"},
Coordinates{50.7200, 1.8800, "Bournemouth"}, Coordinates{55.8580, 4.2590,
"Glasgow"} }
10
11 type Coordinates struct{
12
latitude float64
13
longitude float64
14
name string
15 }
16
17 func distance(a,b Coordinates) float64{
18
19
return math.Sqrt( ( a.longitude - b.longitude ) * ( a.longitude b.longitude ) + ( a.latitude - b.latitude ) * ( a.latitude - b.latitude ) )
* 69.174; //69.174 miles = 1 degree of latitude on Earth's surface
20
21 }
22
23 func main(){
24
25
pointA := places[0]
pointB := places[2]
26
27
28
fmt.Println("It is ", distance(pointA, pointB), " miles from ",
pointA.name, " to ", pointB.name)
29
30 }
Q The code for distance.go. Using co-ordinates, we can calculate the distance between two points
Masterclass
MASTERCLASS
Event-driven
programming with Qt
Advisor
Resources
Documentation:
qt-project.org/doc/qt-5.0/qtcore/
signalsandslots.html
QtGui index:
qt-project.org/doc/qt-5.0/qtgui/qtgui-index.
html
QML intro:
qt-project.org/doc/qt-5.1/qtdoc/
qmlrststeps.html
Further reading...
planet.qt-project.org
qt-project.org/doc
qt-project.org/forums
blog.qt.digia.com
Genius Guide
(int
(int
(int
(int
_toWhat);
_toWhat);
_toWhat);
_toWhat);
signals:
void newValue (QString _newVal);
private:
void recalculateValue();
int myVal1;
int myVal2;
int myVal3;
int myVal4;
};
Being based on a QObject-derived class requires the
presence of the Q_OBJECT macro. It is needed for
the moc compiler,.
Slots can be declared publicly or privately. In
practice, private slots are rarely used: some versions
of Qt even permit you to substitute the public slots
declaration with a short form. The actual denition
of the slot takes the form of a void member function,
which receives the parameters that are specied in
the signal.
Declaring signals can prove a bit more difcult.
Signals get emitted by the object, and therefore
have no local representation. Due to that, their
declaration consists of a void function with a
parameter for each bit of data that is to be passed to
the recipient.
Finally, the class needs a few member variables
to track the state of the incoming data.
Masterclass
void ResistorCalculator::recalculateValue()
{
float retval;
retval=myVal1*10+myVal2;
switch(myVal3)
{
case 0:
retval=retval;
break;
case 1:
retval=retval*10;
break;
...
default:
emit newValue("No Multiplyer");
return;
}
emit newValue(QString::number(retval));
}
In this part of the code, the emit call is the only one of
relevance. It is called to fire off the signal in question.
Please note that emit does not act as a return
statement. Method execution continues normally after
the emitting of the signal.
QConnect the signals from the list with your newly created slot
Connecting stuff
With that, it is time to connect the QtGui with the
engine. The four slots you created in the editor must be
integrated by hand into the mainform class along with
corresponding signals the editing of the header is
straightforward; the method body looks like this:
Genius Guide
Creating attractive
user interfaces
with Qt
QtGui framework and QML:
two solutions for a common
problem
When Qt was rst envisioned, JavaScript and
HTML were in their infancy using them to
create complex user interfaces was infeasible.
Furthermore, the then-current computer
systems were unable to cope with the
computational demands raised by animated
GUIs. Instead, developers worried about the
ever-rising screen sizes seen on desktop
workstations.
The QtGui framework (which well use to
create our example application) addresses
these issues. It lets you use native controls
and provides a variety of helpers which handle
resizing and positioning. However, it is not well
suited to animation.
In Version 4.7, Nokia introduced a new GUI
stack called Qt Modeling Language (QML).
This JavaScript- and JSON-based system
offered impressive animation facilities and
initially was intended solely for mobile phones.
In theory, QML elements consist solely of
rectangles, bitmaps and texts which are
rendered using OpenGL.
This approach greatly simplied porting the
framework to new operating systems. Due to
that, Digia decided to make QML available on
all platforms. A set of predened controls will
eventually simplify the creation of commonly
used widgets.
Using QtGui usually leads to quicker results,
as controls do not need to be assembled by
hand. Furthermore, the native integration
ensures that the results look exactly like other
desktop apps.
emit changed1(_newVal);
}
Here, we forward the signal via a slot. Theoretically, we
could also connect signals to one another this special
case is described in the documentation. The signal from
the engine must also be processed. For this, create
another slot with the following code. Also, include the
QMessageBox via an #include:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
myEngine= new ResistorCalculator();
connect(this,SIGNAL(changed1(int)),myEngine,SLOT(ring1Changed(int)));
connect(this,SIGNAL(changed2(int)),myEngine,SLOT(ring2Changed(int)));
connect(this,SIGNAL(changed3(int)),myEngine,SLOT(ring3Changed(int)));
connect(myEngine, SIGNAL(newValue(QString)),this,SLOT(datareceived(QString)));
}
Fig 1
Masterclass
A first layout
It is now time to start applying all of this knowledge
in practice. Our first example will consist of a group
of buttons which are arranged above one another
A well-made
Qt application
looks great on a
large variety of
screen sizes
Genius Guide
More layouts
Forgetting to assign a form layout disables the layout
system in its entirety. Sadly, most cases require
more than one layout per form arranging a group of
buttons horizontally under a list is not possible with
just a horizontal or a vertical layout.
Qt permits nested layouts. A horizontal layout can
contain a vertical layout which then, in turn, contains
another horizontal layout. The high performance
of contemporary computer systems ensures that
complex forms will still be rendered in real-time. In
the last ten years, your advisor has not experienced a
single case of lag caused by overcomplex layouts.
Creating nested layouts is relatively easy. In our
example, add a text widget to the main form by
dragging it in from the toolbar. Qt Creator will display a
blue line in the form. This informs you that the control
will be placed in a layout and provides indication of its
location in the layout hierarchy. Keep in mind that you
Changing the
size of the form
will not affect
this placement
the three buttons
will stay in the
middle
should not affect the size of the elements of a layoutmanaged form this is achieved by more subtle
means discussed later in the article.
For now, it is enough to place the text box above
the buttons. The toolbar on the left side of the
screen contains a group called Layouts. Select a
horizontal layout and drag it onto the form in order to
add it. Initially, the layout will show up only as a slim
red line.
Due to an internal limitation of the editor, layouts
can not be modied while a form layout is in place.
This can be xed by clicking the form and selecting
the option Break layout in order to strip the form of
its layout intelligence. When this is done, the layout
will show up as a small red square drag the three
buttons into the rectangle in order to add them to the
internal HorizontalLayout.
Masterclass
A question of policy
Looking at the text box and the buttons in the example
leads to a puzzling conclusion. The Qt framework
somehow knows that some controls can profit from
extra height, whereas others do not. This information is
used at runtime in order to give additional height to the
textbox, while the buttons remain small.
Each widget has a sizePolicy attribute for the
vertical and the horizontal direction. These properties
can be modified by selecting one of the widgets
and setting up its properties accordingly. The seven
attributes that are supported, as of Qt 5.0, are outlined
in Fig 1.
This, however, is not the only possible way the layout
system can be affected. If controls are intended to
grow at different rates, this can be configured using the
Horizontal and Vertical Stretch properties. By default,
they are set to zero so the controls all grow and
shrink together.
Assigning a value to horizontal stretch and/or
vertical stretch permits you to modify the size-gaining
behaviour. When controls are laid out, each widget is
assigned the minimum required space. If additional
Fig 1
QSizePolicy::Fixed
QSizePolicy::Minimum
QSizePolicy::Maximum
QSizePolicy::Preferred
QSizePolicy::Expanding
QSizePolicy::MinimumExpanding
QSizePolicy::Ignored
QInflating the size of the form does not affect the arrangement of the widgets
Attention,
excessive width
Manufacturers of monitors
have their own agenda
In the last years, the diagonals of screens have
grown considerably. At the same time, the
aspect ratio has become atter and atter:
today, screens tend to be much wider than
they used to be. This new situation provides
considerable challenges to user interface
developers. Very wide texts are difcult to read
it is for good reason that most books and
newspapers are printed in portrait mode. When
creating an application optimised for very wide
displays, try to think about how the additional
horizontal screen real estate can be used.
Android tablet apps tend to provide useful
inspiration thanks to their fragment layouts,
which are used to give additional context.
For example, an email client would display
a hierarchy of folders next to the actual
message.
Genius Guide
Fig 2
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QVBoxLayout *verticalLayout;
QTextEdit *textEdit;
QHBoxLayout *horizontalLayout;
QPushButton *pushButton_3;
QPushButton *pushButton_2;
QPushButton *pushButton;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
Where is the
intelligence?
Conclusion
Due to a long tradition of Visual Basic, Windows users
do not expect their applications to show an overly large
amount of flexibility as forms are resized. Due to the
widespread adoption of Qt, Linux and UNIX users are
far less tolerant of applications which do not resize
themselves intelligently.
Creative use of the layout system provides you with
the aforementioned logic with minimal extra code.
Arranging your controls in layouts can be done in mere
seconds, but leads to significantly better applications.
Practical experience shows that the layout
system can be daunting due to the large amount of
functionality offered. Most developers tend to get
acquainted with the handling within few hours let this
article be your guide to more attractive and responsive
user interfaces.
Font sizes?
As screen densities increase, font sizes eventually
become problematic. Keeping them inline is
currently not possible in the framework. Fortunately,
addressing the issue is easily done in code. Most
controls contain an event handler which will be
invoked whenever the layout engine changes the size
of the elements of the screen.
Analysing and comparing the sizes of the widget to
the base size allows you to compute the ideal font size.
The actual correlation can be done in a linear or in a
stepped fashion advanced information on this can be
found in classic typography literature.
Masterclass
MainWindow::MainWindow(QWidget *parent) :
....
{
....
myDesktopPaths=QStandardPaths::standardLocat
ions(QStandardPaths::DesktopLocation);
myCWD=myDesktopPaths[0];
}
QHead to the Qt project website (http://qt-project.org/) to download the latest version of Qt. On the
website you can also access helpfuflu l forums, development topics and tools
Genius Guide
Fig 1
void MainWindow::enumerateCWD()
{
myDir.setPath(myCWD);
enumContents=myDir.entryInfoList(QDir::NoFilter, QDir::DirsFirst);
for(int i=0;i<enumContents.count();i++)
{
if(enumContents[i].isDir()==true)
{
ui->listWidget->addItem("[" + enumContents[i].fileName() + "]");
}
else
{
ui->listWidget->addItem(enumContents[i].fileName());
}
}
}
void MainWindow::myItemClicked
(QListWidgetItem* _inItem)
{
if(_inItem->text().compare("[..]")==0)
{//Go up
myDir.cdUp();
myCWD=myDir.absolutePath();
ui->listWidget->clear();
enumerateCWD();
}
else if(_inItem->text().compare("[.]")==0)
{//Do nothing
}
else
{//Go down
int targetItem=ui->listWidget>currentRow();
if(enumContents[targetItem].
isDir()==true)
{
myDir.cd(enumContents [targetItem].
fileName());
myCWD=myDir.absolutePath();
ui->listWidget->clear();
enumerateCWD();
}
}
}
Recursion
What goes around tends to
come around
In computer science, many problems can be
solved easily by breaking them down into little
steps. For example, let us compare the strings
aaaaaab and aaaaaac. Even though most
programmers would attack this via a loop, let
us, for now, suggest a different approach. Let
there be a comparison function cmp which
compares two characters and returns a value
indicating whether they match. A program
could then be constructed which compares the
current characters, then reduces the string
by one and passes them on to cmp(). Inside
cmp, the characters are compared again if
they match, the string is reduced again and
cmp() is invoked on the new result. This process
continues until the end of the string (or a
disparity) is reached, in which case the instance
of cmp() would return the corresponding code.
Once the recursion has been broken, the
computer will automatically unwind its call
stack. This means that the value from the
innermost cmp() function will be propagated
out until it nally arrives back at the caller.
When applied right, recursive solutions tend
to be very compact. The overhead caused by
the extra stack frames is insignicant on most
modern computer systems.
Masterclass
void MainWindow::myItemClicked
(QListWidgetItem* _inItem)
{
if(_inItem->text().compare("[..]")==0)
{//Go up
if(myDir.cdUp()==true)
{
myCWD=myDir.absolutePath();
ui->listWidget->clear();
enumerateCWD();
}
else
{//Enumerate drives
enumContents=myDir.drives();
ui->listWidget->clear();
for(int i=0;i<enumContents.
count();i++)
{
ui->listWidget>addItem(enumContents[i].absolutePath
());
}
myDriveListModeActive=true;
}
}
....
Calling drives() returns a data structure listing all
drives found on the current machine. In the case of
UNIX, this usually is just the root, which is denoted by
a slash. Under Windows, the application would instead
receive a group of elements. Either way, the contents
are written into the list using a process similar to the
one outlined above.
In addition to that, the click handler routine also
needs some special logic for handling clicks to drives:
void MainWindow::myItemClicked
(QListWidgetItem* _inItem)
{
if(myDriveListModeActive==true)
{
int targetItem=ui->listWidget>currentRow();
myDir.cd(enumContents[targetItem].
absolutePath());
QSelect what kind of widgets Qt Creator should use to pre-populate your layout file
FileWindow::FileWindow(QString _pathToRead,
QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FileWindow)
{
ui->setupUi(this);
QFile myFile(_pathToRead);
myFile.open(QIODevice::ReadOnly |
QIODevice::Text);
QTextStream in(&myFile);
QString collector = in.readAll();
ui->plainTextEdit->setPlainText(collector);
setWindowTitle(_pathToRead);
}
Integrating the routine into the main window is
straightforward. If the element clicked is not a file, a
new FileWindow is opened with a reference to the full
path to the file in question:
FileWindow* myFileWindow=new
FileWindow(enumContents[targetItem].
Genius Guide
absoluteFilePath(), this);
myFileWindow->show();
Conclusion
Even though our example program is not particularly
complex, it shows all important obstacles faced by
developers creating applications which access the file
system. The procedures outlined here can be used to
realise a wide variety of utilities.
void MainWindow::mySeekClicked()
{
QList<QString> myResultList;
seekThisFolder(myDir,&myResultList);
myResultList=myResultList;
}
void MainWindow::seekThisFolder(QDir _where, QList<QString>* myResultStore)
{
qDebug() << _where.absolutePath();
QFileInfoList localContents=_where.entryInfoList();
for(int i=0;i<localContents.count();i++)
{
if(localContents[i].isDir()==true)
{//Folder, so recurse
QString filePath=localContents[i].absoluteFilePath();
if(localContents[i].fileName().compare("..")==0)continue;
if(localContents[i].fileName().compare(".")==0)continue;
QDir myNewDir;
myNewDir.setPath(filePath);
qDebug() << "Spawning into" << filePath;
seekThisFolder(myNewDir, myResultStore);
}
else
{//File, so scan
if(localContents[i].fileName().contains(ui->lineEdit->text()))
{
myResultStore->append(localContents[i].absoluteFilePath());
}
}
}
}
Fig 2
Our example
program shows
all important
obstacles faced
by developers
creating apps
which access the
le system
File access can and
will fail
Peter Principle applied what
can fail will do so
In this story, our example code did not handle
possible le-system errors in order to be
shorter and more compact. When creating
commercial code, it is highly recommended
that all le-system routines are protected by
error handlers. Users can disconnect memory
cards or just go ofine while using your program
if this causes a crash, a bad rating is almost
guaranteed.
Fortunately, most methods which interact
with the le system tend to provide a relatively
simple error-handling system. Checking return
values and onFail callbacks might be tedious
while coding, but has signicant benets due
to the vastly improved user experience faced by
your clients.
Of course, one can also be overzealous.
However, experience shows that adding too
much error-handling code usually is less
critical than too little.
Masterclass
The nal version of the
sqFile Erlang module
Documentation of an Erlang
module in HTML format
The Erlang
graphical monitor
Resources
Erlang:
www.erlang.org
Try Erlang:
www.tryerlang.org
Mnesia DBMS:
www.erlang.org/doc/apps/mnesia/
MochiWeb:
https://github.com/mochi/MochiWeb
Genius Guide
01
Introducing Erlang
02
The Erlang
shell
02
$ erl
Erlang R15B01 (erts-5.9.1) [source] [64-bit]
[smp:8:8] [async-threads:0] [kernel-poll:false]
Eshell V5.9.1 (abort with ^G)
1> q().
ok
2> mtsouk@mail:~$
As you can see, if you want to exit the Erlang shell,
you will have to type q(). and press the Return/Enter
key. Make sure that you do not forget to put a dot at
the end of the command because Erlang commands
always end with the dot character.
The q() function is the easiest way to exit the
Erlang shell, but keep in mind that the q() function
quits everything Erlang is doing. If you are working
locally then there is no problem, but if you are
working on a remote system its better to quit by
typing Ctrl+G and then q. The reason is that you
may shut down the Erlang runtime on the remote
machine when quitting using q()!
The Erlang shell is perfect to test most of your
stuff before putting your code into a module.
The built-in line editor, erl, is a subset of Emacs.
03
04
1> c(hello).
{ok,hello}
2> hello:helloWorld().
hello, world
ok
3>
The rst command compiles the hello.erl source
le and the second command calls the helloWorld()
function of the hello Erlang module. The output is
shown on screen.
Masterclass
05
$ erlc hello.erl
Similarly, you can run an Erlang function without
entering the Erlang shell:
init
06
An Erlang module
When
creating
programs,
Erlang
programmers put their code in modules. Modules
help you organise, store and share code easily and
efciently and are the preferred way of writing Erlang
programs.
The source code for the square module, which
calculates the perimeter and the area of a square
given its side, is the following:
-module(square).
-export([length/1, area/1]).
length(Side) -> 4 * Side.
area(Side) -> Side * Side.
If you use side instead of Side as the variable name,
1> c(square).
square.erl:8: Warning: this expression
fail with a 'badarith' exception
{ok,square}
will
07
1> square:module_info().
An alternative way of getting information about a
module is the following:
-import(square, [area/1]).
There is no command to import all functions at once
from an existing Erlang module. If a function of a
module is not used inside the module, you will get a
descriptive warning message.
09
10
2> m(square).
{ok, FILE} = file:open("output", write)
08
file:close(FILE)
The actual writing of the output to the output le is
done using the following Erlang code:
Genius Guide
{ok,sqFile}
2> im().
<0.42.0>
3> ii(sqFile).
{module,sqFile}
4> iaa([init]).
true
5> sqFile:readlines("data").
The rst command compiles the Erlang module and
adds some extra debugging information, which is a
common practice in every programming language.
The second command starts a new graphical
monitor that is the main Debugger window. The third
command interprets the code of the Erlang module
that is going to be examined. The fourth command
tells Erlang shell to automatically attach the
Debugger to any process that is executing interpreted
code when that process is started. The last command
executes a module function and makes the Debugger
start running.
12
Fig 01
readlines(FileName) ->
{ok, Device} = file:open(FileName, [read]),
try process_line(Device)
after file:close(Device)
end.
process_line(Device) ->
case io:get_line(Device, "") of
eof -> [];
Line -> save_line(Line),
Line ++ process_line(Device)
end.
save_line(Line) -> io:fwrite("**** ~s~n", [trim_whitespace(Line)]).
trim_whitespace(Input) -> re:replace(Input, "\\s+", "", [global]).
11
The Erlang
Debugger
edoc:files(["sqFile.erl"], [{dir,
"documentation"}]).
Remember that documentation is produced for
the functions that are in the exported list even if
you write documentation code (@doc) for other
functions.
13
Fig 02
%% @doc This function calculates the length of the perimeter of a square.
%% For a square with a side length of A, the length of its perimeter is 4 * A.
mylength(Side) -> 4 * Side.
1> pman:start().
Everything that runs using Erlang, including
the Erlang shell, is a process and has a process
identier (pid) that you can see with the help of
the Process Manager. If you want to see more
Fig 03
%% @author Mihalis Tsoukalos <mihalistsoukalos@gmail.com>
[http://www.mtsoukalos.eu/]
%% @doc A module that calculates the perimeter and the area of a square.
%% It also writes the output to a file called "output".
%% @reference from <a href="http://www.linuxuser.co.uk">Linux User & Developer</a>.
%% 2014, Issue 137
%% @copyright 2014 Mihalis Tsoukalos
%% @version 1.23
%%
Masterclass
14
16
Reading les
in Erlang
Erlang OTP
15
13
If you are not familiar with Erlang code, you are likely
to find the code on both modules difficult to read and
understand.
Line 5 tells Erlang that the module will implement
the gen_server behaviour. A behaviour pre-denes
17
18
Genius Guide
19
20
What to do next?
17
Using TCP
in Erlang
Fig 04
20
What to do
next?
Developer guide
Essential tools for coders
120 Write once, use anywhere with
Qt
Qt is the most flexible cross-platform
framework for C++ and can even create crossplatform GUIs. Learn how
132
146
Genius Guide
Developer guide
Further reading...
planet.qt-project.org
qt-project.org/doc
qt-project.org/forums
QAfter startup, Qt Creator shows a start pane with some instructions for getting started
Genius Guide
Installing Qt
Getting Qt up and running is really easy
IDE la Qt
Digia provides users of the framework with a custom
IDE. Qt Creator works best when run in superuser
mode. Start it by entering the following commands
into a terminal hosted in /opt/Qt/ the soft asserts
emitted are normal and do not point to mistakes in
conguration:
sudo qtcreator
SOFT ASSERT: "i != -1" in
file ../../../../src/plugins/
projectexplorer/taskmodel.cpp, line 172
Qt Creator has a slightly unusual layout, which can
best be understood by looking at the GUI in its default
state. The IDE is subdivided into multiple submodules,
which can be activated via the ribbon on the left-hand
side of the screen. Click any of the icons to activate the
corresponding view it will show up in the remainder
of the GUI. The bar at the bottom allows you to nd
out further information about compile processes and
application status by default, it is hidden to save
screen real estate.
First steps
It is now time for us to start working on a little
Hello world application. Click File>New File or
Project in order to open the Project Creation
wizard. Then, select Applications>Qt Gui
Application and click Choose. In the next step,
the product will ask for a name and a storage
location.
After that, a relatively important dialog shows
up. Qt Creator contains a relatively advanced crosscompilation framework, which permits you to target
multiple different versions and platforms with one
click. For our basic project, just select Desktop we
will use this dialog more in later parts of the tutorial.
The Class Information dialog is not signicant and
can be closed by clicking Next. Then, click Finish to
start the generation of the project skeleton. Then,
click Play to start the program it will display the
project skeleton in Edit mode.
Developer guide
Going
cross-platform
Taking our application to
another operating system
is really easy
QT
+= core gui
greaterThan(QT_MAJOR_VERSION,
widgets
TARGET = untitled
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS
+= mainwindow.ui
4):
QT
+=
Genius Guide
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
class Ui_MainWindow
{
public:
QMenuBar *menuBar;
QToolBar *mainToolBar;
QWidget *centralWidget;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().
isEmpty())
MainWindow->setObjectName(QString
::fromUtf8("MainWindow"));
MainWindow->resize(400, 300);
menuBar = new QMenuBar(MainWindow);
...
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
return a.exec();
}
The form itself is made up of two les. The c++ class
contains a more-or-less default constructor which
invokes the setupUi method of the ui object. Other
than that, it does not contain much of signicance:
compile process
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
The actual intelligence of the form resides in the header
le. Its derived from QMainWindow, and contains a
pointer to the aforementioned ui object. It is created
by uic, and resides in the aformentioned ui_*.h le.
Developer guide
Answer real-world
questions with Qt
Advisor
Tam Hanna has followed the
mobile phone market since the year
2004. His rm Tamoggemon Holding
k.s. uses Qt to maximise code reuse
across different mobile and desktop
operating systems.
Further reading...
planet.qt-project.org
qt-project.org/doc
qt-project.org/forums
blog.qt.digia.com
RNG-Output
Assigned
elements
Well-off computers
Modelling this situation on a computer is
comparatively easy. The collection of each individual
can be represented by an array of 36 booleans: if one
of them is false, the element in question is not yet
found in the users collection.
The actual simulation is performed by using the
random-number generator to pick a domino stone.
Its ID is compared against the collection in order
to determine if the stone is already there if it is
not there yet, the ags state is changed and the
number of missing stones is reduced by one.
A loop is used to keep adding stones until
all stones are found in the collection. Counting
Genius Guide
int MainWindow::runAttempt()
{
//Reset
int missing=36;
int attempts=0;
int whatDoIHave[36];
for(int i=0;i<36;i++)whatDoIHave[i]=0;
Processing begins with the declaration of the
variables needed for storage. Using method-local
storages is helpful when it comes to creating multithreaded simulations, as there is less potential for
race conditions.
In the next step, we commence with the actual
population process. It is implemented in the form of
a while loop, which runs until the amount of missing
stoned reaches zero:
//Start to populate
while(missing!=0)
{
attempts++;
The individual attempts are modelled by invoking the
qrand function. It returns a random integer ranging
from zero to the highest value of the random number
generator. Its value can be found by looking at the
RAND_MAX constant, which is declared in stdlib.h.
For our example, we are satised by knowing that
the highest number returned is much larger than
the number range used for modelling. If the ranges
were to end up being close to one another, you
might nd that mapping difculties could occur.
We process the returned number via the modulo
operator. The resulting value is then used as index to
the array if the element is not yet set, the missing
counter is decreased accordingly:
Increase accuracy by
collating results
Colleges and schools tend to provide mathematical
problems which have one or, in the worst case a
small amount of permissible and correct results. As
our simulation is based on a random process, it can
return a large variety of different and valid results. An
Developer guide
sample of data has been collected. Most softwarebased random number generators need a starting
value, which initialises the numerical processes
contained. It is customary to pass in the current time
in a production environment.
int myBinningArray[27];
for(int i=0;i<27;i++)
myBinningArray[i]=0;
for(int i=0;i<50000;i++)
{
int idx=runAttempt()/10;
if (idx>=27)idx=27;
myBinningArray[idx]++;
}
Finally, data must be normalised in order to simplify
the processing. This is achieved by dividing the
number of iterations seen by each slot of the bin
with the total. The result is then multiplied with 100
to achieve the percentage of iterations that fell in the
bucket in question:
for(int i=0;i<27;i++)
qDebug() << (float)myBinningArray
[i]/(float)50000*100;
Divisions tend to require quite a bit of computing
power. Due to that, C treats all division operations
involving two integers as int the normalisation
process above would not work out, as the result of
the division would be rounded to either zero or one.
Casting the two parameters to oat ensures that the
arithmetical operation will be carried out with oat
data types, thereby preserving accuracy.
The example that we have used dumps the
computed results into the command line. You can
copy them into a spreadsheet such as the one
included in LibreOfce. This method was used to
generate the chart shown in gure ve it is clear
Stockings galore
The methods outlined here can be applied to a
wide range of real-life problems. One amusing
problem solved recently involved stockings.
Purchasing a single pair of expensive stockings
is perceived as a waste of money, as a ladder in
one of the stockings would render the other one
completely useless. Purchasing multiple packs of
...
20-29
10-19
0-9
QA binning array is made up of
Q Customers must expect to purchase a large number of gems to get a complete set
Genius Guide
int MainWindow::modelStockingWearing()
{
int lostStockings=0;
//Left stocking
int myResult= qrand() % ((100 + 1));
if(myResult<=3)lostStockings++;
//Right stocking
myResult= qrand() % ((100+1));
if(myResult<=3)lostStockings++;
return lostStockings;
}
modelStockingWearing is a relatively simple
function. It invokes the random number generator
twice in order to gure out whether the left and/or
the right stocking was damaged during the outing.
This result can then be processed further in a
mother routine. See Fig 01.
In principle, this method is easy. It runs the
modelStockingWearing-Function
until
the
number of remaining stockings falls below two.
The amount of possible iterations is then dumped
into the command line for further processing. See
Fig 02.
The improved version of the harness routine runs
the internal test a thousand times. It then divides the
counter by thousand in order to receive the average
value per iteration.
A chart with the results of our computation (right)
shows that the price per wearing session does
not decrease signicantly when more than four
packages are purchased in one sitting.
Fig 01
Fig 02
Conclusion
While using computers to solve non-virtual
problems by brute force is a process that is not
currently perceived as acceptable and this story
glosses over some mathematical details the
results returned by a modelling system based on the
methods described tend to be accurate enough for
everyday use.
QThe price of each wearing stops to reduce after the fourth package was bought
Developer guide
Handle Twitters
three-legged OAuth process
Building and signing requests according to OAuth can be tricky.
We explain the authentication process for Python and Flask
Advisor
Sean M Tracey is a
creative technologist at a
leading digital agency. He
spends a lot of his time living
inside of Node.js, Python
and Arduino
Resources
Python 2.7+
Flask 0.10.0:
ask.pocoo.org
Flask GitHub:
github.com/mitsuhiko/ask
A Twitter account
Your favourite text editor
QThe OAuth Settings page for your new Twitter app youll fill in various bits as you go
Once upon a time, Twitter was a favourite
API for developers looking to write a
quick weekend hack. Setup was quick,
documentation was plentiful and the
data available was vast. Fun times! But now things
are a little different. With the Twitter API v1.1,
authentication is not quite as easy as it once was
(though the documentation is still plentiful and
the data vast). Twitter now requires adherence
to OAuth protocol v1 for all requests made to its
API. Its tempting to install a library and ignore all
the complicated stuff and entirely appropriate
if youre putting together a quick hack project.
However, understanding whats going on in the
authentication process will help you along when it
comes to debugging problems you may encounter
later if you have to start handling multiple users or
requests. For this tutorial, well be using Flask a
01
Install Flask
02
03
Genius Guide
Full code
avaliable online:
http://bit.
ly/1gH6W0S
04
With the
Twitter API v1.1,
authentication is
not quite as easy
as it once was
05
Assigning a namespace
to the Flask app
06
07
verifyRequest = urllib2.Request(https://api.twitter.com/oauth/access_token,
oauth_verifier= + request.args.get(oauth_verifier))
verifyRequest.add_header(Authorization, create_oauth_
Developer guide
08
09
A little about
oauth_nonce
Most of the values included in the OAuth
headers and signing process are selfexplanatory. However, one isnt so obvious
in its purpose. OAuth_Nonce is a randomly
generated value often alphanumeric
but as there is no dened convention, an
integer between 1 and something large
will serve its purpose. It exists so Twitter
can check that its not been sent the same
request twice.
10
11
12
13
14
15
Genius Guide
Full code
avaliable online:
http://bit.
ly/1gH6W0S
headers(verifyRequestParams))
try:
httpResponse = urllib2.urlopen(verifyRequest)
except urllib2.HTTPError, e:
return e.read()
responseData = getParameters(httpResponse.read())
16
Handling access
17
18
if __name__ == __main__:
app.secret_key =
R4nDOMCRypt0gr4ph1cK3yf0R5355i0N
app.run(host=0.0.0.0, debug=True)
If we didnt include any parameters in the run
function then our server would run and be accessible
at 127.0.0.1: 5000, but it wouldnt be accessible to
external machines that kind of defeats the point of
having a server. By passing host=0,0,0,0, Flask will
listen on any IP address it can for potential requests
with a default port of 5000. debug=True is an error
message beautier that Flask includes.
Rather than crashing our server, an error page will
be delivered detailing what went wrong in place of
our expected return.
session[oauth_token] = responseData[oauth_token]
return Authorised + session[oauth_token]
def getParameters(paramString):
paramString = paramString.split(&)
pDict = {}
for parameter in paramString:
parameter = parameter.split(=)
pDict[parameter[0]] = parameter[1]
return pDict
def sign_request(parameters, method, baseURL):
baseURL = urllib.quote(baseURL, )
p = collections.OrderedDict(sorted(parameters.items(), key=lambda t: t[0]))
requestString = method + & + baseURL + &
parameterString =
for idx, key in enumerate(p.keys()):
paramString = key + = + urllib.quote(str(p[key]), )
if idx < len(p.keys()) - 1:
paramString += &
parameterString += paramString
result = requestString + urllib.quote(parameterString, )
signingKey = consumer_secret + & + session[oauth_secret]
print signingKey
hashed = hmac.new(signingKey, result, sha1)
signature = binascii.b2a_base64(hashed.digest())[:-1]
return signature
def create_oauth_headers(oauthParams):
oauthp = collections.OrderedDict(sorted(oauthParams.items(), key=lambda t: t[0]))
headerString = OAuth
for idx, key in enumerate(oauthp):
hString = key + =\ + urllib.quote(str(oauthp[key]), ) + \
if idx < len(oauthp.keys()) - 1:
hString += ,
headerString += hString
return headerString
if __name__ == __main__:
app.secret_key = R4nDOMCRypt0gr4ph1cK3yf0R5355i0N
app.run(host=0.0.0.0, debug=True)
Developer guide
Resources
Python 2.7+
Flask 0.10.0:
lask.pocoo.org
Flask GitHub:
github.com/mitsuhiko/ask
A Twitter account
Your favourite text editor
01
Genius Guide
02
server.py modules
{% if session[oauth_token] != %}
<h1>Already Authorised</h1>
<div class=dialog>
<p>Hello, Youve authenticated!<br>Lets <a href=/get-tweets>get some tweets</a></p>
</div>
{% else %}
<h1>Authorisation required</h1>
<div class=dialog>
<p>We need to <a href=/authenticate>authenticate</a></p>
</div>
{% endif %}
Fig 01
Full code
avaliable online:
http://bit.
ly/1gH6W0S
03
04
@app.route(/)
def home():
if not oauth_token in session:
session.clear()
session[oauth_secret] =
session[oauth_token] =
return render_template(index.html)
Its a simple function: all we want to do is check
whether or not we have an oauth_token already
Developer guide
05
Template variables
06
Getting lost
(and then found again)
@app.errorhandler(404)
def fourOhFour(error):
return render_template(fourohfour.html)
If a page or endpoint is requested and triggers a 404,
then the fourOhFour function will be red. In this
case, well generate a template that tells the user, but
we could also redirect to another page or dump the
error message.
07
Static les
08
@app.route(/get-tweets)
@app.route(/get-tweets/<count>)
def getTweets(count=0):
Youll notice that unlike our other authentication
endpoints, weve made two declarations. The rst
is a standard route denition: it will intercept and
handle the path get-tweets. The second lets us
dene a parameter that we can use as a value in
our getTweets function. By including count=0 in
our function declaration, we ensure that there
will always be a default value when the function is
executed; this way we dont have to check the value
is present before we access it.
If a value is included in the URL, it will override the
value in the function. The string inside the <variable
name> determines the name of the variable. If you
want the variable passed to the function to have a
specic type, you can include a converter with the
variable name. For example, if we wanted to make
sure that <count> was always an integer instead of a
oat or string, wed dene our route like so:
@app.route(/get-tweets/<int:count>)
09
if session[oauth_token] == or
session[oauth_secret] == :
return redirect(rootURL)
Assuming we have all we need, we can start to
build the parameters for our request (Fig 02).
Youll notice that the nonce value is different
from that in our previous requests. Where the
nonce value in our authenticate and authorise
requests can be any random arrangement of
characters that uniquely identify the request, for
all subsequent requests the nonce needs to be a
32-character hexadecimal string using only the
characters a-f.
10
?count=tweetRequestParams[count] &user_
id=tweetRequestParams[user_id]
11
12
Genius Guide
13
Flask lters
14
Wrapping up
tweetRequestParams = {
oauth_consumer_key : consumer_key,
oauth_nonce : helpers.nonce(32),
oauth_signature_method : HMAC-SHA1,
oauth_timestamp : int(time.time()),
oauth_version : 1.0,
oauth_token : session[oauth_token],
user_id : session[user_id],
count : str(count)
}
Fig 02
Fig 03
tweetRequestParams[oauth_signature] = tweetRequest
makeRequest=urllib2.Request(https://api.twitter.com/1.1/statuses/
user_timeline.json?count= + tweetRequestParams[count] + &user_id=
+ tweetRequestParams[user_id])
del tweetRequestParams[user_id], tweetRequestParams[count]
makeRequest.add_header(Authorization, helpers.create_oauth_
headers(tweetRequestParams))
try:
httpResponse = urllib2.urlopen(makeRequest)
except urllib2.HTTPError, e:
return e.read()
Fig 04
{% if data %}
<ul id=tweets>
{% for tweet in data %}
<li>
<div class=image>
<img src={{ tweet[user][profile_image_url_https]
}} alt=User Profile Picture>
</div>
<div class=text>
<a>{{ tweet[text]|forceescape }}</a>
</div>
</li>
{% endfor %}
</ul>
{% else %}
<p>We didnt get any tweets :(</p>
{% endif %}
Developer guide
Using Django
Admin to create a
new blog post
Mihalis Tsoukalos is
a UNIX system administrator
also procient in programming,
databases and mathematics. He
has been using Linux since 1993
Resources
Django: www.djangoproject.com
Django built-in template tags and
lters: https://docs.djangoproject.com/en/dev/ref/
templates/builtins
SQLite: www.sqlite.org
Apache: www.webforefront.com/django/
setupapachewebserverwsgi.html
Genius Guide
01
Installing Django
django-admin version
If your output prints something like 1.4.5, then
everything is okay. Otherwise check your
PATH settings or look for error messages.
django-admin is the main Python script
for
Django
administrative
tasks.
Run
django-admin without any command-line parameters
to display usage information and a list of all the
available commands.
Although at the time of writing this article the latest
Django version is 1.6.1, Debian uses an older version.
02
03
04
Developer guide
05
photoBlog,
Next, add valid values to the ADMINS eld.
Then, change the TIME_ZONE value to match your
location. Later on in this article, you will learn about
the other changes you need to make to it in order to
support the Django administration interface.
The next step will show you how to use a
database with your Django project.
06
07
08
Using models
09
Dynamic templates
/home/mtsouk/docs/article/working/djangoBlog.
LUD/code/LUD/templates
When your server goes live and is moved to a
different hard disk location, you will need to make
more changes, but this is sufcient for development
purposes.
You can have multiple template paths if needed. To
make your app to use templates, you should add the
following two lines inside your photoBlog/views.py file:
10
Genius Guide
11
Project URLs
url(r'^welcome/$', 'photoBlog.views.welcome'),
12
MEDIA_ROOT = '/home/mtsouk/docs/article/
working/djangoBlog.LUD/code/LUD/photos/'
The MEDIA_URL variable is set to uploaded_photos
so all images are stored inside directory /code/
LUD/photos/uploaded_photos.
Timestamps will be used for making the lename
unique (it is crucial that lenames are unique) using
the following Python module:
13
14
A veiw takes an
HTTP request and
returns an HTTP
response
Developer guide
15
url(r'^welcome/$', 'photoBlog.views.
welcome_template', name='welcome'),
url(r'^about/$', 'photoBlog.views.about_
template', name='about'),
url(r'^list/$', 'photoBlog.views.list_
template', name='list'),
The names are used in the template le templates/
navigation.html, as in Fig 01.
Please note that if you know how to write CSS code,
you can make the look of the Django site better. This
article is about Django programming, not website
design and CSS.
In order to add a new blog post, you will have to
use the admin panel. Alternatively, you can create
a Django form, but we think that the admin panel
is more than enough. Nevertheless, have in mind
that the admin panel is not for end users.
What is still missing is going live, but you are going
to learn more about it in a while!
16
17
url(r'^node/like/(?P<myID>\d+)/$', 'photoBlog.
views.like_blogPost'),
Then, you need to implement the like_blogPost
method inside photoBlog/views.py:
count = a.nLikes
count += 1
a.nLikes = count
a.save()
return HttpResponseRedirect ('/node/%s/' %
myID)
The like_blogPost method updates an SQLite3
database record simply and elegantly. Last, you
should add the following to the templates/display_
blogpost.html le:
{% load base_extras %}
Fig 01
<div id="topbar">
<div class="navbar">
<div class="navbar-side navbar-left"></div>
<div class="navbar-content">
|| <a href="{% url welcome %}">Welcome</a> ||
<a href="{% url list %}"><b>List Posts</b></a> ||
<a href="{% url about %}">About</a> ||
</div>
<div class="navbar-side navbar-right"></div>
</div>
</div>
<VirtualHost *:80>
ServerAdmin mactsouk@gmail.com
ServerName blog.highiso.net
DocumentRoot /srv/www/blog.highiso.net/public_html/
Fig 02
Django logging
import logging
logger = logging.getLogger(__name__)
A logger is the entry point into the logging
system. Each log message that is written to the
logger is a Log Record. Each log record also has
a log level indicating the severity of that specic
message. Each logger sends its log records to a
Handler. The Handler determines what happens
to each message and can display a message on
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
WSGIScriptAlias / /srv/www/blog.highiso.net/public_html/LUD/wsgi.py
Alias /static/ /srv/www/blog.highiso.net/public_html/static/
Alias /uploaded_photos/ /srv/www/blog.highiso.net/public_html/static/uploaded_photos/
ErrorLog /srv/www/blog.highiso.net/logs/error.log
CustomLog /srv/www/blog.highiso.net/logs/access.log combined
</VirtualHost>
[Mon Jan 06
[Mon Jan 06
[Mon Jan 06
[Mon Jan 06
Python/2.7.3
Fig 03
18:07:49 2014] [notice] SIGHUP received. Attempting to restart
18:07:49 2014] [warn] mod_wsgi: Compiled for Python/2.7.2+.
18:07:49 2014] [warn] mod_wsgi: Runtime using Python/2.7.3.
18:07:49 2014] [notice] Apache/2.2.22 (Debian) PHP/5.4.4-14+deb7u7 mod_wsgi/3.3
configured -- resuming normal operations
Genius Guide
18
Setting up Apache
ALLOWED_HOSTS = ['*']
For the admin site to work properly on
the production server, you will need to
run the following command after setting
STATIC_ROOT and STATIC_URL:
19
Examining database
tables and data
20
Last words
21
Developer guide
Sean M Tracey is a
creative technologist at a
leading digital agency. He
spends a lot of his time living
inside of Node.js, Python
and Arduino
Resources
Node.js v0.10.17:
nodejs.org
NPM v1.3.8:
www.npmjs.org/doc/cli/npm-install.html
Duino v0.0.9:
github.com/ecto/duino
Forever.js v0.10.11:
github.com/nodejitsu/forever
Arduino Uno/Duemilanove
5 LEDs
Potentiometer
13 prototyping wires
Your favourite text editor
Arduino IDE 1.0.5
01
02
Genius Guide
How does it
all work?
Full code
avaliable online:
http://bit.
ly/1gH6W0S
03
04
QTo get a stable reading from the potentiometer, it must be connected to the 5V power pin
}, 500);
setInterval(function(){
spawn(echo $[100-$(vmstat|tail -1|awk
{print $15})], function(error, stdout,
stderr){
var percentage = parseInt (stdout);
displayUsage(percentage);
});
Developer guide
05
function displayUsage(percentage){
var ledCount = ((percentage / 100) * 100)
/ (10 * (10 / pins.length));
}
Right now, all display usage will do is calculate
06
Alternative ways of
controlling LEDs
function displayUsage(percentage){
var ledCount = ((percentage / 100) * 100) /
(10 * (10 / pins.length));
for(var z = 0; z < pins.length; z ++){
if(z < ledCount){
board.analogWrite(pins[z],brightness);
} else {
board.analogWrite(pins[z], 0);
}
}
}
Remember the array of pin numbers we
created earlier on? Here were looping
through them and checking if the pin selected
from the array represents a value low enough
that it can be turned on. We can do this in
a variety of ways. If, for example, we only
wanted to toggle the pins on and off then
we could do something like this
QNode aims to offer users an easy way to build scalable network programs
Genius Guide
} else {
leds[z].off();
}
}
}
...But those methods, while really useful, dont
allow us to set the values being sent. They
are HIGH or LOW because we want to be able
to adjust the brightness of our LEDs based
on user input, so were going to address the
board directly with board.analogWrite(pins[z],
brightness). The analogWrite method lets
us send an analog value between 0 and 255,
0 being off (or the analog equivalent of
LOW) and 255 being on full power (or, the analog
equivalent of HIGH).
07
potentiometer.on(read, function
(err,
value) {
value = (value / 1024) * 100;
brightness = Math.round((value / 100) *
255);
node app.js
});
in the command line, assuming everything
is wired correctly, you will now have a fully
functioning CPU meter. To try it out, why not
open a couple of taxing programs at the same
time to see how it affects the measure? As
more of the CPU time is used, the number
of LEDs lit up should increase, and we could
leave it there. But, that does mean that weve
only covered writing values. If we want to read
values, how do we do that?
Head back over to your project le. Immediately
after the variables where we set the board
information, create a new variable called
potentiometer. This will be the object that
we use to listen for events and access data
from the potentiometer.
08
More benefits
The key benet of using something like
Duino is that you can ofoad a lot of the
problem crunching to a beeer machine.
Perhaps even more useful is the ability
for the controlling computer to navigate
the internet on behalf of the Arduino.
Arduino was never actually designed
with the internet in mind, by letting
our computer deal with navigating the
network and sending the result we
dont have to worry about shields, the
amount of bytes available or dropping
connections. It just works.
info:
Forever processes running
data:
uid command
script
forever pid logfile
uptime
data:
[0] fwGv /usr/local/bin/ node
app.js 96489 96490 /Users/ seantracey/.
forever/fwGv.log 0:0:1:13.707
If you want to stop a process, you can enter forever
stop [PROCESS INDEX].
09
Brief recount
Developer guide
def build(self):
return Label(text=Hello World!,
font_size=100,
color=0, 1, 0, 1)) # (r, g, b, a)
The build method is called when the App is run, and
whatever widget is returned automatically becomes
the root widget of that App. In our case thats a Label,
and weve set several properties - the text, font_size
and color. All widgets have different properties
controlling aspects of their behaviour, which can be
dynamically updated to alter their appearance later,
though here we set them just once upon instantiation.
Note that these properties are not just Python
attributes but instead Kivy properties. These are
accessed like normal attributes but provide extra
functionality by hooking into Kivys event system. Well
see examples of creating properties shortly, and you
should do the same if you want to use your variables
with Kivys event or binding functionality.
Thats all you need to show some simple text, so run
the program again to check that this does work. You can
experiment with the parameters if its unclear what any
of them are doing.
Applications
can also run on
Android, iOS, plus 01
Raspberry Pi
Genius Guide
Kivy comes
with all the tools
needed to use kv
language
these events to call our own functions when a user
presses the button, and can set the buttons text
property to display the X or O. We also created a new
Kivy property for our widget, coords well show how
this is useful later on. Its almost identical to making a
normal Python attribute by writing self.coords = [0, 0]
in GridEntry.__init__. As with the TicTacToeGrid, well
style our new class with kv language, but this time we
get to see a more interesting feature.
<GridEntry>:
font_size: self.height
Q
A tic-tac-toe grid now accepting input, adding a O or X alternately
<TicTacToeGrid>:
cols: 3 # Number of columns
This is the basic syntax of kv language; for each
widget type we may write a rule defining its behaviour,
including setting its properties and adding child
widgets. This example demonstrates the former,
creating a rule for the TicTacToeGrid widget by
declaring that every TicTacToeGrid instantiated should
have its cols property set to 3.
Well use some more kv language features later, but
for now lets go back to Python to create the buttons that
will be the entries in our tic-tac-toe grid.
Developer guide
def build(self):
return TicTacToeGrid()
# Replaces the previous label
With this complete you can run your main Python file
again and enjoy your new program. All being well, the
single Label is replaced by a grid of nine buttons, each
of which you can click (it will automatically change
colour) and release (youll see the printed output
information from our binding). We could customise
the appearance by modifying other properties of the
Button, but for now well leave them as they are.
02
(ListProperty,
class TicTacToeGrid(GridLayout):
status = ListProperty([0, 0, 0,
0, 0, 0,
0, 0, 0])
current_player = NumericProperty(1)
This adds an internal status list representing who has
played where, and a number to represent the current
player (1 for O, -1 for X). By placing these numbers in
our status list, well know if somebody wins because
the sum of a row, column or diagonal will be +-3. Now
we can update our graphical grid when a move is
played (Fig. 02).
You can run your app again to see exactly what
this did, and youll nd that clicking each button
now places an O or X as well as a coloured
background depending on whose turn it is to
play. Not only that, but you can only play one
move in each button thanks to our status
array keeping track of existing moves.
This is enough to play the game but theres one vital
element missing... a big pop-up telling you when youve
won! Before we can do that, we need to add some code
to check if the game is over.
Kivy properties have another useful feature
here, whenever they change they automatically
call an on_propertyname method if it exists
and dispatch a corresponding event in Kivys
event system. That makes it very easy to write
code that will run when a property changes,
both in Python and kv language. In our case
we can use it to check the status list every time
QThe game with final additions, making the grid square and extending the interface
winner = None
if -3 in sums:
winner = Xs win!
elif 3 in sums:
winner = Os win!
Genius Guide
03
Time to experiment
Fig 01
Full program
avaliable online:
http://bit.
ly/1gH6W0S
Fig 02
# Note the *args parameter! Its important later when we make a binding
# to reset, which automatically passes an argument that we dont care about
def reset(self, *args):
self.status = [0 for _ in range(9)]
Fig 03
Developer guide
Installing Gulp
01
Install
Node
01
Install Node
02
Install Gulp
03
Save as dependency
04
Ready to gulp
Using a task
runner you
can make the
most of CSS
preprocessors
to streamline
how you write
stylesheets
Genius Guide
Install and
maintain
dependencies
05
06
07
page at github.com/jackfranklin/gulp-load-plugins.
gulpLoadPlugins({
pattern: gulp-*,
config: package.json,
scope: [devDependencies],
replaceString: gulp-,
camelize: true,
lazy: true,
});
Adjust references
gulp.task(lint, function() {
return gulp.src(js/*.js)
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter(default));
});
08
Further options
Set up a project
One thing to be mindful of is to try and not
overload your Gulp conguration le in any
way. This could be through the structure
of your task denitions or the general
formatting of the code within.
Your tasks should be written in a clean
manner that is simple to understand and
maintain or manage should you need to.
Your Gulple may potentially be distributed
amongst a team of developers working on
the same project. Should any one individual
wish to amend or revise the le, it shouldnt
take too much time to do so.
There are a vast amount of plug-ins
available to download, implement and use
within your projects. Thanks to the high
engagement level of the development
community, more are being added on a
Developer guide
Apply Gulp to 12
a project
09
Create gulple.js
10
Reference plug-ins
var
var
var
var
var
jshint = require(gulp-jshint);
concat = require(gulp-concat);
uglify = require(gulp-uglify);
rename = require(gulp-rename);
header = require(gulp-header);
11
Code linting
gulp.task(lint, function()
{
return gulp.src(js/*.js)
.pipe(jshint())
.pipe(jshint.reporter(default));
});
Minication
and concatenation
gulp.task(scripts, function() {
var headerValue = Evaluated by
gulp.\n;
return gulp.src(js/*.js)
.pipe(concat(combined.js))
.pipe(header(headerValue))
.pipe(gulp.dest(dist))
.pipe(rename(combined.min.js))
.pipe(uglify())
.pipe(header(headerValue))
.pipe(gulp.dest(dist));
});
13
gulp.task(watch, function() {
gulp.watch(js/*.js, [lint, scripts]);
});
14
Default tasks
Genius Guide
15
Plug-in
repository
Resources
Here are a selection
of plug-ins that will
add power to your
Gulple tasks
GULP-BUMP
www.npmjs.org/package/gulp-bump
Whether you are working within a team
of developers, committing open source
code for public consumption or building
a task runner for your own projects, this
plug-in allows you to update and bump
version numbers within any Semver
JSON les following any major, minor or
patch changes to the code.
GULP-SASS
www.npmjs.org/package/gulp-sass
This aptly named plug-in will convert
your Syntactically Awesome Style
Sheets into processed productionready CSS les. Combined with the
watch task, your les can be interpreted
as soon as they have been updated or
amended. This includes success and
error callback methods that can be built
into the workow process.
Gulp plug-ins
15
Plug-in repository
16
17
No limits
18
Update plug-ins
GULP-IMAGEMIN
w w w. n p m j s . o r g /p a c k a g e /g u l p imagemin
Images and digital assets can often
be too large network resource hogs,
and the cause of many loading
issues for applications. This handy
plug-in will minify your PNG, JPEG
and GIF images to a more respectable
le size and help alleviate some of these
issues for your production servers.
GULP-LOAD-PLUGINS
www.npmjs.org/package/gulp-loadplugins
This fantastic plug-in removes the
requirement to specically dene
and require each plug-in individually
into your Gulple. The plug-in can
read the package.json le associated
with the project and the scope of
dependencies
contained
within
and
automatically
assign
them
to a global scope on your behalf.
Developer guide
All the examples
presented in this
article are tested for
Vim version 7.3.547
on Ubuntu 13.04
Himanshu Arora is a
Resources
Vim:
www.vim.org/download.php
Genius Guide
01
02
03
04
05
Developer guide
07
08
Genius Guide
09
Manual indenting
Another
important
feature
that
Vim provides is code indentation. Software
programmers are required to indent their code
and Vim provides easy steps for code indentation.
To indent a single line of code, you can use >> or <<
to indent the line to the right or left respectively.
Multiple lines can also be indented using [numberof-lines]>> or [number-of-lines]<<; for example, 10>>
or 10<<. This is a better technique than indenting
each line, but you still need to count the number
of lines to indent. This could prove frustrating,
especially if the number of lines is very large.
Fortunately, there is another trick: to select the
lines by working with Vim in visual mode. In order
to do this, you rst need to bring Vim into visual
mode. This (as mentioned previously) can be done
using va. Once in visual mode, use the arrow keys to
select all the lines that you want to indent in one go.
After this, all you need to do is press > or < and the
whole selected area will be indented accordingly.
For those
programmers
who want
everything
automated, Vim
also provides
auto-indenting
10
Automatic indentation
11
Search words
12
Replace words
Essential software
The best distros and projects
160 Presentation software
Choose the best slideshow software as we look
over a selection of the best Linux presentation
apps on offer
Genius Guide
Essential software
Presentation software
Choose the best slideshow applications
Calligra Stage
Calligra is very impressive, although
it lacks the same kind of community
support and popularity as LibreOffice.
Calligra Stage is the presentation software
bundled with the suite, and is a standard desktop
presentation application in the same vein as
PowerPoint and Impress.
Starting up Stage, youll notice one thing to begin
with clutter. The main interface is just lled with
functions that dont quite t the space unless youre
using a 1080p or higher monitor. Even then, theres a
lot on the screen to deal with, leaving little room for
the preview of the actual presentation. The interface
is somewhat context sensitive at least, changing
out some of the boxes depending on whether youre
editing images, text or animations.
Some of the functions arent straightforward to
use, though, even if you can nd them in the interface.
The pointer function can link between text boxes and
titles, but it requires the use of anchor points on each
SCORES
Ease of use
Q The interface is very cluttered on non-1080p screens, but there are a lot of features to choose from
7
7
Aesthetics
Presentations can
be made to look
good enough for a
business environment
Features
Overall
Genius Guide
EWIPE
A very simple
presentation
application that
does everything
in blocks
SCORES
Ease of use
Q The presentation itself is also limited, and does not have a full-screen option or smart scaling
6
0
Aesthetics
Features
Overall
Essential software
LibreOfce Impress
The slideshow
creator from
our ofce suite
champion is it as
good as the rest of
the suite?
LibreOffice is just an excellent office suite,
and a true open source success story.
One of the strengths of LO is its
compatibility with other software,
especially with Microsofts versions. While Writer
has some of the best compatibility of the lot,
Impress is still pretty great at importing a variety
of different presentation le types with very few Q The layout is clean and simple, giving you access to all the necessary functions
issues none that cant be tweaked to work with
Impress at least.
of course, you can add, remove or reposition
It is an amazing piece of software, well worthy of
The software comes with just about every
functions as you see t. Priority is given to making the LibreOfce name and a place in the full suite.
function youd see in other slideshow creators, sure you can see the preview of the slides, and the Presentations look great when displayed, while it
meaning you wont need to switch between
screen is never overly packed with functions and imports other le types reasonably well and is just
multiple ones. Whether youre doing a very
customisation. This is in stark contrast to the way nice to use.
professional business presentation or something
Calligra Stage is laid out, with everything placed
The only real issue with the software is that
a bit more informal, all the necessary graphs
on the screen at once with very little room to you cant quickly or easily publish presentations
and animations and sounds and interactions are
manoeuvre around them. Due to Impresss layout, online, although such a function will probably
readily available to use in Impress.
we were able to quickly and efciently put together be coming sometime in the future. For now,
The interface to create your presentations is
a presentation without having to hunt down though, Impress is most denitely the best ofine
extremely neat and logically laid out by default anything or wrestle with the interface at all.
presentation application.
SCORES
Ease of use
Q Impress is the only one that supports slide transitions and object animations
9
8
Aesthetics
10
Features
From graphs to
animations and everything
in between, Impress has
just about everything
Overall
LibreOffice is just an
amazing suite, and the
Impress package doesnt
let it down
Genius Guide
Slidier
An online
presentation creator
and sharer that uses
HTML-like code
Although its not open source, even if you
are using it through Chromium, Google
Docs has a very serviceable presentation
tool. It may be a little basic, but it does just
enough for a presentation to look as professional as
anything Stage or Impress can make. Slidier is in
some ways the open source equivalent to this aspect
of Google Docs, allowing you to create and share your
spreadsheets online without needing any specic
software installed. In fact, the Slidier version is
better in that regard, as you dont need an account
for it, and sharing the link is a bit easier than the
Google method.
Unfortunately, thats just about the only thing it
has going for it against Docs. Slidier is an incredibly
simple tool that has you build your presentation as
a piece of code, one with very basic formatting to
signify titles or a break to the next slide. The most
complicated thing is adding an image, which uses
the img tags from standard HTML, while most other
Q Its a very simple way to create a slideshow, almost like editing a wiki page
functions involve a dash, a hashtag or a slash to yet professional, and play on just about any browser.
signify what they represent. Some of these are also Every presentation you make is saved with two URLs
accessible from preset buttons on the interface; one thats read-only, and another that allows you to
however, some functions need to be hunted down in further edit the slideshow.
If you need to create a simple presentation very
the About section.
The presentations you make also have some limits quickly, Slidier may just be what youre looking
due to this construction method. Like EWIPE, you for. However, there just arent enough functions to
can only control the position of items vertically on consider it as a replacement for Impress or Calligra,
the screen. You cannot change the alignment of text especially if you plan to use graphs or need some
or the position of images, or even have two items form of animation. For now, if youre happy using an
side by side. If you are able to play within these rules, ofine app or Google Docs, theres really no reason
though, the presentations you can create are simple to switch.
SCORES
Ease of use
Q There are some interesting features in Slidifier, but it does lack some important ones
7
0
Aesthetics
Features
Overall
Essential software
Music players
We nd out the best way to organise and play your music
Rhythmbox
There was a bit of a kerfuffle a year or
so back with Rhythmbox. Soon after
Ubuntu One started streaming music,
Canonical opted to switch to Banshee for
the next release of Ubuntu. These kinds of changes
happen everyday in Linux. However, what was more
surprising was the instant backtracking by Canonical,
reinstating Rhythmbox as the default music player in
the following release of Ubuntu returning with better
music streaming options.
Rhythmbox is a great default music player for
a number of reasons. It has a straightforward
interface with nice, big, standard buttons that
stand out so anyone can use it. The entire music
library is accessible down the side, along with a
handful of basic streaming services other than
Ubuntu One, and a dedicated Radio and Podcast list.
Playlists are split up from this main Library, although
these only include playlists youve created and
automatic ones such as recently added or played
music, with no smart recognition.
SCORES
Playback
Interface
A nice straightforward
interface with good
OS integration
7
9
8
Online
Overall
Rhythmbox is definitely
good, but its in sore need
of a big update to make it
more relevant in a world of
online music
Genius Guide
Audacious
Lightweight yet with
a surprising number
of features
Audacious is the only media player in
this group test that can be described
as lightweight and in fact like many
lightweight apps, its made that way
in mind. Still though, its a very popular music
player and music manager, thanks in part to a good
selection of features that make it more than just a
basic music player.
Audaciouss interface is simple, with a single
pane to list all available media, listed by album by
default. Music can be easily added, with a standard
folder being used to check regularly for any more
content for Audacious to add to your library of
media. Interestingly, playlists and play queues are
handled in separate tabs from the main library,
keeping the interface a little cleaner and allowing
you to have a specic layout of your favourite
playlists without needing all of them on show.
The search function is a bit odd, though. Instead
of an omnipresent search eld on the interface,
a separate column needs to be opened up from
the menus. The results from the search are
not displayed very well, with what seems to be
a random mash of authors, albums and songs
included in the results. This highlights a small
SCORES
Playback
Interface
Q The search function is not the best, but Audacious is highly customisable
Online
Overall
Audacious is fine as
a lightweight music
player, but for proper
media management and
integration youll need a
bit more
6
0
Essential software
Clementine
A Linux favourite,
how is the latest
Clementine player?
Clementine is based on the KDE
music player, Amarok, but with a few
improvements and a much better
interface. Its quickly become a very
popular media player and the latest version,
1.2, has arrived with a whole host of great new
features. These are sure to attract new users
while appeasing die-hard fans who still want to
use their favourite media player.
First of all, Clementine now has access to a lot
more music streaming services than before, with
new additions such as Dropbox and Ubuntu One
joining the already impressive list of existing ones.
These include Google Drive, Spotify, SoundCloud,
Last.fm and Grooveshark. You can easily search
within the free services using the built-in
Clementine search functions, and you can log in
to do the same with the account-driven services
such as Spotify and the cloud storage ones. These
settings are easily found in the preferences menu
under a different section to the vast wealth of
customisation options that Clementine offers.
Through these options you can change just
about every way Clementine behaves, from simple
Q Clementine has everything but the Kitchen Sink. It even has the Hypno Toad
SCORES
Playback
Interface
Q The Android app offers better control than some HTTP interfaces
Online
Connects to everything
you would probably want
to use bar Pandora and
Google Music
Overall
An amazing piece of
software that lets you
do just about anything
youd want to do with all of
your music
9
10
Genius Guide
Banshee
It may not be
as popular as
Clementine, but is
Banshee better?
Banshee was the one-time default audio
player for Ubuntu, replacing and then
being usurped by Rhythmbox. Due to
this, you would be forgiven in thinking
that they are incredibly similar applications and
in some regards they certainly are. They both
employ a similar three-pane layout for your media,
and they both include a column down the side
for navigating your media, videos, podcasts and
online services. At the core, they also both run off
GStreamer, which is a great media back-end and
allows the two to play just about anything with the
right codecs installed.
The interface for Banshee is nice and easy to use,
and very responsive. Search is instant, bringing up
results as you type, and the way results are listed is
conducive to nding the tracks, album or artist youre
looking for. The album pane on the main interface
has thumbnails of the album art instead of a list
although the grid effect can be disabled if you wish. It
all works very well and, like all the others, integrates
just ne with the desktop environments that allow
for playback options via volume controls.
Customisation wise, theres not a whole lot more
than Rhythmbox. You cant even set a specic
SCORES
Playback
Good playback
options, but lacks
its own dedicated
notication icon
Interface
An easy-to-use interface
that is laid out in a
logical manner
Q The extensions give Banshee a lot of its features, and turning these off is the main way to
Online
Limited online
options, and its only
minimally extendable
Overall
7
9
10
4
Essential software
Ubuntu One
It was a fairly big deal a few years ago
when Canonical announced Ubuntu
One 1GB of storage for all users of Ubuntu,
to be used as they wish to save and sync
their les to and from the cloud. Since then, Ubuntu
One has upgraded to 5GB of free storage and is
available to anyone, not just those using Ubuntu. As
well as offering 5GB for free, you can also add 20GB
of storage for $2.99 a month or $29.99 a year and
this stacks so you can continue to add 20GB to your
account, and add a further $2.99 or $29.99 to your bill
in the process.
The Ubuntu One client is fairly simple to use,
requiring little more than your Ubuntu One login
details and then some basic information on what you
wish to keep synced. As well as its own Ubuntu One
folder that has les that are automatically synced
SCORES
Space
Integration
Features
Rather disappointingly,
only the very basic
customisations are
Customisation available in Ubuntu One
Overall
Genius Guide
Copy
The newcomer
with a lot of
promise
Copy is so named as a little bit of an injoke ofcially, of course, its because
it copies your les to the cloud, like all
cloud storage services do. However, it
also copies other cloud storage services in some of
the way it looks and operates, giving its name a bit
of a double entendre. This is no reason to look past
it, though, as Copy has quickly become a very good
cloud storage solution.
First of all, you get 15GB of storage free, the
most out of any of the services were reviewing in
this feature. It also has the cheapest upgrade path,
offering 250GB for only $9.99 a month/$99.99 a year,
or 500GB for $14.99 a month/$149.99 a year. This is
one of the best prices available on any service and
while you would think there must be a catch, it isnt
quite what youd expect.
The client software for Copy is supplied in three
binaries, although you only need to use one of them
at a time, or ever. The main one is the graphical client,
allowing you to log in and set up your computer to
sync les to your copy account. Similar to Dropbox,
SCORES
Space
Integration
Features
Overall
Essential software
Dropbox
No introductions
necessary for the
king of cloud storage
Dropbox is synonymous with cloud
storage; in fact, when describing other
cloud services to less tech-savvy people,
the conversation usually includes
the phrase its like Dropbox. Popularity doesnt
necessarily mean quality, though, which is why were
comparing it with several other services in this test
to see if it truly deserves its reverence.
Here are the facts then Dropbox is a crossplatform service offering 2GB of free data, with
small increments available for referrals and such,
which is upgradeable for a price. This starts at $9.99
a month for 100GB, which seems to be somewhat of
a standard in the cloud storage space and is cheaper
than Ubuntu Ones 20GB add-on scheme. Dropboxs
Linux client is fairly simple compared to the other
platforms it works on; however, it offers roughly the
same level of functionality without some of the bells
and whistles those versions have.
The client only allows for syncing of the main
Dropbox folder, rather than letting you select
different folders to also sync or back up. However,
you can tell Dropbox to selectively sync specic
folders from the main Dropbox directory, just in
SCORES
Space
Integration
Integrates throughout a
network and has a useful
notication icon
Features
Q Have more control over your files via the web interface
Overall
Genius Guide
SpiderOak
A veteran in Linux
cloud storage
One of the rst commercial cloud
storage services to make its way to
Linux, SpiderOak has been around
for a few years. This means a couple
of things right off the bat rstly, it has the
same 2GB free, $9.99 for 100GB storage deal as
Dropbox. Secondly, it also has probably the best
and most mature client program out of any in
this test, which well shortly go into more detail
about. One of the benets of using SpiderOak is
that the rm behind it is extremely condent in the
security and privacy of your data on its server. It
operates what it calls a Zero Knowledge scheme,
where the server doesnt actually know what you
have stored on it because its encrypted. This is a
good idea and should guard against most types
of intrusion.
As mentioned, the client for SpiderOak is
extremely good on Linux. The main interface
supplies a lot of information on the current status
of backup and syncing, what the current queue
of uploading or downloading les is, a log of any
changes made etc. Like Ubuntu One, you can
select other folders to back up, as well as having
a SpiderOak Hive folder that syncs between all
devices. You can also heavily customise the way the
Q You get complete control over the client and how it syncs
SCORES
Space
Integration
SpiderOak is able to
integrate well with a
number of setups
Features
Overall
SpiderOak is probably
the best commercially
available storage solution
on Linux, and we dont say
that lightly
Essential software
Integrated development
The best IDEs to streamline and enhance your workow
Code::Blocks
A relatively new IDE, Code::Blocks
was released in early 2008 after three
years of release candidates. Although a
C++ IDE by default, it has plug-in support
to extend its functionality to allow for building and
testing of other languages. However, for pure coding,
Code::Blocks can be used to write scripts in various
languages thanks to support for syntax of a variety of
different languages. However, you cannot test these
without add-ons.
Unfortunately, the plug-in scene for Code::Blocks
is fairly immature and there isnt even proper support
for Python and other interpreted programming
languages. Plug-ins are found via the Code::Blocks
wiki and are not particularly well laid out at the
moment. Plug-ins are installed manually, which
would be ne normally, but the other IDEs in the test
have some interesting ways of managing plug-ins
that make this method seem somewhat archaic.
SCORES
Installation
Workflow
Code::Blocks interface
is generally good for
workow, although
it doesnt support all
languages properly
Features
A great selection of
features that can all be
heavily customised
Plug-in
support
Overall
Genius Guide
Geany
A fully featured
IDE thats a little
more lightweight
than most
Geany is sometimes mistaken for a
gloried text editor. In reality, its a full
IDE, albeit a slightly more lightweight IDE
than most.
Geany has multi-language support out of the
box, with easy options to create les that use
different languages as part of the main interface.
Projects are kept in specic folders, like Eclipse,
although there is a le to go with them that Geany
can read to manage the projects. Multiple projects
can be viewed and edited at a time, all in different
languages. There are also debuggers and builders
for the various languages that support them, and
you can run and test stuff like Python that doesnt
need compiling as such.
The rest of the interface for Geany is clean and
well labelled. Code is automatically highlighted
with the correct syntax and theres a smart tab in
the left column that allows you to track and view
the different variables, functions and classes in the
projects and code. Navigation through the code is
fairly simple via context-sensitive menus and nice
options within the rest of the interface, and the
Q Geanys interface is smart and easily breaks down code for workflow purposes
SCORES
Q The native languages are supported quite well with compilers and such
Installation
Readily available in
most repos and requires
minimal dependencies
Workflow
9
9
Features
No proper debugger,
but a great selection
of build and project
management functions
Plug-in
support
Overall
Geany is a great,
lightweight IDE with
good native support for a
variety of languages, but
theres not much room
for expansion
Essential software
Eclipse
Eclipse is an
industry standard
so how does it
fare against
more communityrun efforts?
Eclipse is one of the most popular
development suites around, and at first
glance its easy to see why. While created
mainly for Java development, Eclipse is
highly customisable through plug-ins. Thanks to
its popularity and community, this has resulted in
a great selection of add-ons that enables Eclipse to
work with just about any language. These plug-ins
allow for more than that, with a marketplace full of
interface and behavioural modications alongside
the language elements.
Eclipse has great project management tools as
well, with a smart tabbed interface, and plug-inspecic menu entries for starting projects in
different IDEs if needed. Projects are located in plain
folders in the location of your choice, allowing for
easy access of source code if you need it, instead of
being inside a proprietary le. The function search
ability works well and the interface has plenty of tips
SCORES
Installation
Workflow
Features
Plug-in
support
10
Overall
Genius Guide
Netbeans
The Oracledeveloped Java
dev platform
that multitasks
Netbeans started life as a humble
student project to make a Java IDE in
Prague. Within a few years, a company
had been set up around the IDE, and then
had been bought by Sun Microsystems. The rest
is history and after over 15 years of development,
Netbeans is on version 7.3.
Netbeans has a very similar feature-set to Eclipse,
with debuggers, compilers, unit testers and the
like, although by default Netbeans has support for
PHP and HTML as well as its Java-specic features.
Netbeans also has a huge database of plug-ins
to call from, allowing you to extend its features to
just about any programming language. These plugins are nicely arranged on the Netbeans website,
with simple search functions and a fairly easy way
to install the plug-ins to the system. Theres no
repository function for the plug-ins like Eclipse, but
the database displays enough information to know if
youre getting the latest version of the plug-in.
The interface is a little confusing not very
well streamlined and aesthetically a little dated.
SCORES
Installation
Workflow
Features
A similar feature-set to
Eclipse, but not as much
customisation
Plug-in
support
Overall
Essential software
Xchat
options
SCORES
Installation
Ease of use
Features
Overall
8
8
Genius Guide
Irssi
A functional
command-line
client with a limited
feature set
Irssi is the sole command-line-only IRC
client in this section, and is the preferred
option for a lot of Linux users that forgo
the graphical IRC offerings available.
Even though its a CLI application, it claims to be the
client of the future, and because of this it does have
the highest compatibility among the clients in the
test and wont require any extra graphical packages
such as GTK+ or Qt.
Being a command-line tool means the interface
is extremely limited. Theres no JED-style window
emulation here, requiring a completely manual
setup of Irssi to just about everything. The manual to
make it work is only available on the website which,
ironically, you will need to access via a graphical
web browser. From there you can learn how to
connect to servers and channels, how to start
creating multi-window setups and editing other
display preferences. There is actually not a whole
SCORES
Q Ironically, youll need to look up the website in a graphical browser to make sense of Irssi
Installation
Ease of use
Features
Overall
Essential software
Konversation
Take full control of
your graphical IRC
experience with this
KDE app
Konversation, while a KDE app, is not
directly tied to that desktop environment.
Its development is independent from the
DE and it has its own release schedule
because of this. Its used in some KDE-based distros
as a default, although it doesnt quite have the
ubiquity of Xchat from earlier in this test. This means
that Qt is required for Konversation; however, the
necessary dependencies wont cause a problem in
the vast majority of cases.
First impressions of Konversation are that its a
little more complex than Xchat. The menu system
and startup screens offer a fair few more options,
with some of these displayed in separate windows,
such as a more advanced nickname selector, away
messages etc. However, theres only one server in
the list to begin with, a complete opposite to Xchat.
While this means a little more setup on your rst go,
it does result in a lot less clutter in the server listing.
The same automatic connection settings can be
made, with the ability to add multiple channels to
any server.
The amount of features and customisation
in Konversation is vast. Theres not a single part
SCORES
Installation
Available by default on
some distros, get it with Qt
on others
Ease of use
9
8
10
Features
Overall
Genius Guide
Smuxi
Smuxi is a simpleto-use application
but its interface is
too simplied it
doesnt quite stand
up to its rival IRC
clients
One of the things we werent too keen
with in Irssi was how limited it is as
a command-line application, and
how much extra manual setup you
have to perform to get it to anywhere near the
functionality of the other clients weve tested.
Even then, there was only so close you could get to
that level of functionality.
Smuxi is inspired by Irssi and is a graphical
client with a twist. As well as being a standalone
graphical client, you can also have it as a front-end
client for a back-end IRC server. The back-end can
be connected at all times, with multiple front-end
clients connecting to it at once, allowing for the
client system to use up very few resources. The
standalone mode is still very lightweight, though,
and can be used just ne in that mode. The interface
is a fair bit simpler than the offerings from Xchat
SCORES
Installation
Ease of use
Limited customisation
for the interface
Customisation and behaviour
8
9
6
Features
Overall
Essential software
System recovery
Live-booting system rescue distros you should turn to
the best system recovery tool
Parted Magic Not
but offers other useful tools
Parted Magic gets its name from
two of the partition editors featured
in the software suite, which is
an indicator of its focus. Theres
a lot of partition editing software on the disc, both
in graphical and command-line form, and there are
even tools and packages to help you diagnose the
health of your hard drives. Shufed in with these
apps, though, are a few great tools for other system
recovery and maintenance tasks.
For starters, ddrescue is included with the other
partition and editing tools. This data recovery
tool is very powerful for xing le corruption and
suchlike, with ways to compare it to previous
versions, even if they too are corrupt. Parted
Magic lists all available tools on its website, with
categories and a small description for each, allowing
you to look up the relevant package for the task
you wish to accomplish. While this is great, theres
SCORES
Quick to boot, with some
advanced boot options
Boot
Recovery
Ease of use
Extras
Overall
Genius Guide
Finnix 107
The smallest and
fastest system
recovery distro but
can be tricky to use
A Debian-based distro, Finnix is the
smallest and fastest one in this test. 107
comes in at about 120MB for both x86
and PPC architectures, yet is apparently
able to help you with all your system recovery
needs. It manages this by not including a desktop
environment, something all the others have, and
this also allows it to be incredibly quick due to its
command-line-only nature.
Before you get to the command line, though,
theres a selection of boot options that seems to be
the standard with these rescue discs, with a choice
of 32- or 64-bit. There are also a few extra options to
boot into FreeDOS, use the Smart Boot Manager and
run an iPXE so you can easily install other distros
over the network to the current system. There are
other boot proles as well, for those who want more
control over how Finnix runs.
It loads very quickly into the command-line
interface, proudly announcing how many packages
are installed. You can browse whats available
using dpkg -get-selections to get an idea of whats
SCORES
Great a lot of booting
options, including ones
outside of Linux
Boot
Decent recovery apps, but
not a huge selection
Ease of use
7
3
Extras
Overall
Recovery
Essential software
Knoppix
An all-purpose
portable livebooting distro but
not our rst choice
This all-purpose live distro does have
sheer exibility as a mobile OS. With
multiple versions of every kind of app
youd need on the DVD edition, and a great
selection of core packages on the CD version,
Knoppix is a jack-of-all-trades as a Linux livebooting distro. When it comes to system recovery,
though, there are some very specic features that
need to be included, and Knoppix is clearly not the
most focused distro.
Here are the things it can do, at least. Obviously,
as a live-booting distro, you dont need to be able to
properly boot into your operating system to access
les if theres a problem booting. You can also x
GRUB using the command line if you know what
to do and of course with ample browsers in the
software list, you can easily look that up. There
arent any data recovery or forensic tools, though, so
for corrupt data youll need to look elsewhere.
Knoppix is a great portable distro. Its easy to
put onto a USB stick permanently and can then
have programs and packages added to it from
there. By default, it does come with other system
SCORES
Highly customisable boot
sequence using cheat
sheet
Boot
Recovery
Ease of use
Extras
Overall
As a system recovery
distro, Knoppix doesnt
do so well. All the other
distros here are far
better
9
5
8
10
Genius Guide
SystemRescueCD
An essential
portable distro you
should keep to hand
On rst impressions, SystemRescueCD
seems to tick all the boxes wed want it to
tick as a recovery distro. The live-booting
OS comes in at a fairly small 370MB
and immediately offers up a huge variety of boot
options, with the choice of 32- and 64-bit, languages,
alternate boot methods etc. This then quickly loads
into a command-line interface for the interest of
speed, and it either lets you continue doing work on
the command line or gives you information on how to
boot into a graphical environment. This environment
is fast and gives you some extra graphical tools to do
your recovery tasks.
All in all, thats a great start. Its got plenty
of applications to help you with data recovery,
including ddrescue that we mentioned earlier, which
work mostly on the command line. However, the
SystemRescueCD website has some great guides
to get you going on that. This manual is set as the
homepage of the included web browser (Midori, to
keep it fast and within Xfce) so as long as you have
an internet connection, you can easily access it.
There are other maintenance apps as well,
SCORES
A huge number of boot
options available through
a straightforward menu
Boot
10
Recovery
Ease of use
Extras
Other system
maintenance tools
round out the selection
of apps
Overall
SystemRescueCD is
a fantastic tool for
performing recovery
tasks on your system,
or doing some general
maintenance
Essential software
Video editors
The best tools for creating and editing clips and lms
PiTiVi
SCORES
Installation
Ease of use
Features
Codec
support
Thanks to a GStreamer
base, it has decent
decoding for a variety of
video codecs
Overall
Genius Guide
OpenShot
An allencompassing
video-editing tool
Built upon its own media framework,
OpenShot is a fairly all-encompassing
package that has similar codec support
to FFmpeg. Its one of the newer entries
in this group test, with its rst release just over four
years old now, and its denitely one of the better
editing suites weve come across. Like PiTiVi, the
interface is nice and straightforward; however, unlike
PiTiVi, this interface makes it easier to access a much
deeper library of features and editing options.
The timeline consists of a track hierarchy, with
higher tracks generally having dominance over
the lower tracks in terms of what is previewed
and encoded. Theres no differentiation between
music and video tracks, but its smart enough to
know not to cut off video if an audio track is placed
higher than a video track. These tracks can be
moved between by the use of transitions, which are
visually represented very nicely with an arrow to
determine the direction of play, bridging the tracks
together to give a nice sense of the ow of the video
itself. There are plenty of transitions available,
ranging from dissolves, wipes and fades to either
emulating a specic style or even creating some
impromptu special effects. There are some visual
and audio effects available as well, which are added
SCORES
Q There are a great selection of effects and transitions that are fully customisable
Installation
Widely available in
repos, and has its own
media framework
Ease of use
Features
A great selection of
video editing tools and
tricks, as well as effects
and transitions
Codec
support
Overall
A prosumer-level video
editor that is only slightly
more difficult to use than
your basic video editor
Essential software
Kdenlive
A video editor
suitable for
prosumers
Whereas OpenShot is a straightforward
video editor with a deceptive amount
of depth and large number of features,
Kdenlive could prove a little more
intimidating. With a more utilitarian interface
and workow, Kdenlive is deceptive in its design,
however, and generally just as easy to use as
OpenShot. The KDE video editor has been updated
in recent years to work a lot better on other
desktop environments and is also based on the
popular FFmpeg media framework, giving it a lot of
compatibility with various containers, formats and
codecs.
Like OpenShot, Kdenlive works on a hierarchy of
separate tracks, with higher tracks having priority,
and transitions being used to go between the
clips up and down the tree. However, in Kdenlive
there is a differentiation between video and audio
tracks, allowing you to perform some audiocentric manipulation to the tracks and clips in
your timeline. Effects and transitions are generally
easier to get to as well, with the right-click menu
bringing up a list of both to access. These effects
can also be heavily customised to your exact liking.
Theres a whole host of other video editing
features in Kdenlive to use as well, with a
stabilisation algorithm and the ability to create
SCORES
Installation
Ease of use
Features
Codec
support
Overall
8
8
10
9
Genius Guide
Cinelerra
An out-dated videoediting tool for
professionals
Cinelerra is an interesting program.
Having previously won awards for its video
editing ability, it was a bit confusing to nd
that it was not readily available in all major
distros. Its promoted as an incredible advanced
video editor, with a lot of the tools used in more
professional scenarios, including a compositing
engine and the ability to work in both RGBA and YUV
colour spaces. The website offers links to binaries
and PPAs so you can install it on your system, albeit
only for a small selection of distros.
The interface for Cinelerra really needs an
overhaul. With a lot of low-resolution artwork and
bad colour choice, it can be a little jarring at rst.
At the very least, its comprised of many smaller
windows for the timeline, compositor, preview,
options etc, with a couple more windows you can
add and arrange as you please. The timeline has
the same layout as weve seen in OpenShot and
Kdenlive, and you can also now select sections of
track to manipulate. There are of course effects
and transitions; however, there doesnt seem to
be quite the amount that comes with some other
editors in this test.
Perhaps due to its status as more professional
software, it is unable to import a fair few le formats
we tried to throw at it, such as MKV, MOV and some
AVIs. These are not uncommon le formats and
while it will handle more RAW style formats, thats
SCORES
Installation
Ease of use
Features
Codec
support
Overall
6
5
10
3
Essential software
Photo managers
Discover the very best photo-managing tool on Linux
Shotwell
SCORES
Installation
A lot of dependencies
required; however, its
a default application on
some distros
Ease of use
Editing
Features
Overall
Genius Guide
gThumb
A straight-forward
photo manager to
rival Shotwell
We were actually a little surprised by
gThumb, especially as its a GNOMEmade application. With the recent move
to simplifying all parts of GNOME, we were
wondering whether its popularity was misplaced;
however, it looks like all the changes to the GNOME
Shell havent affected the way gThumb works.
Its not to say that gThumb a super-advanced,
though it features a fairly straightforward
interface that wed want from a photo manager. By
default, its a thumbnail view, displaying the Picture
folder in the home directory. Instead of importing
photos from specic albums, you merely navigate
through the directory structure. This means that
instead of having specic albums to create, youll
need to organise those photos yourself in a le
manager or terminal.
Clicking on the Edit le button in the top right
opens up the image editor, and a sort of limited
lmstrip view as well. You can click between
photos in the stream on the bottom to edit them
individually, although you cant move between them
with arrow keys. The editor is a little more advanced
than what you get with Shotwell, allowing for more
manual colour and balance corrections, as well
SCORES
Installation
Ease of use
Editing
8
8
7
Features
Overall
Essential software
F-Spot
A little out-dated
tool but with some
interesting features
F-Spot was replaced by Shotwell in
Ubuntu a few years ago. However, the
application has stuck around, albeit
without an update in over two years.
This simple image editor actually comes with an
interesting variety of features, although theyre not all
that useful in the long run.
The rst time you start it up, youll need to
import photos from a directory. This is a pretty
straightforward process, although it initially looks
like youll need to change settings on each individual
image in selected folders. It quickly imports into
the library, displaying a thumbnail view, some basic
metadata, a histogram and a sort of timeline for
basic ltering of your photos. The timeline breaks
are used to show a graph of photos taken per month
along the top, allowing you to select each month
from there.
You can also lter by tags and such in the main
view, as well as adding extra tags and dates to the
lters to nd exactly what you need.
The thumbnail view is quite basic, and you can
increase the size of the thumbnails in the view.
Double-clicking a picture enters the edit mode,
which you can also select from the top bar, and this
includes a lmstrip view that you can key between
with arrow keys on the keyboard. The editor is a little
simplistic, with some basic autocorrection tools,
although they seem to do very little to the photos we
tried them on.
The main browsing interface can be a little
confusing as well, especially once you start ltering
images. Its not always clear how youre supposed
to get back to the standard view if you want to, and
SCORES
Q The editor and file strip view are quite nice, but could do more
Installation
Ease of use
Basic navigation is
great, but can get a little
counter-productive with
more advanced searches
Editing
Features
A decent variety of
features, but not all of
them work quite as well as
they should
Overall
Genius Guide
digiKam
A fullycomprehensive
photo manager
The KDE-developed image organiser has
recently released the digiKam Software
Collection version 4.0.0 which has lots of
new features. DigiKam has received a few
upgrades over the past few years since it hit version
2.0 and became one of open sources premier photo
managers. It comes with a full range of functions,
including the standard preview and lmstrip view
were looking for, batch tag and data editing, editing
software, and even a light-table function.
Although built for KDE, digiKam works just ne
with GTK-based desktop environments and has a
more neutral design aesthetic than KDE, allowing
it to not stick out on other desktops. It can also be
found in all major package managers thanks to
its popularity and ties to KDE, although options to
compile from source via a tarball or GitHub are just
as available.
Initial startup involves a quick but thorough setup
wizard, going through basics such as photo library
locations, the manner of importing RAW les and a
few more options. While a lot of people can mostly
ignore these and have a decent default selection,
they are useful for people with more specic needs.
SCORES
Installation
Ease of use
Editing
Features
digiKam is overowing
with a variety of features
to make it easier and
better to use
Overall
A fantastic overall
package that offers
specialised tools to
organise, analyse and edit
your photo library
tri Spe
al ci
of al
fe
r
Enjoyed
this book?
Try
3 issues
for just
* This offer entitles new UK Direct Debit subscribers to receive their first three issues for 5. After these issues, subscribers will then pay 25.15 every
six issues. Subscribers can cancel this subscription at any time. New subscriptions will start from the next available issue. Offer code ZGGZIN must
be quoted to receive this special subscriptions price. Direct Debit guarantee available on request.
** This is a US subscription offer. The USA issue rate is based on an annual subscription price of 65 for 13 issues, which is equivalent to $102 at the
time of writing compared with the newsstand price of $16.99 for 13 issues, being $220.87. Your subscription will start from the next available issue.
About
the
mag
Four of the hottest distros feature every month insert the disc, reboot your PC & test them all!
subscribers to
www.imaginesubs.co.uk/lud
Quote code ZGGZIN
Or telephone UK 0844 249 0282 overseas +44 (0) 1795 418 661
TM
facebook.com/ImagineBookazines
twitter.com/Books_Imagine
VOLUME 5