Journal OSX

Swift Programming Language is open source!

Apple finally adhered to their promise from WWDC 2015 of open sourcing their new programming language, Swift. In addition to the source code to the compiler, Apple also released the very first implementation in Swift of the “Foundation” library that serves as the standard library for all OS X and iOS application. All the source – code and everything else was released under the Apache 2.0 license which grants the user of the software the freedom to use the software for any purpose, to distribute it, modify it, and distribute modified versions of it, under the same terms of the license without concern for any royalties. The great advantage of the Apache License is that it’s a permissive license, so software derived or which makes us of the software does not necessarily need to be licensed under the same license which leaves ample room for commercial closed-source software to use Swift.

So far Swift’s application was fairly limited to Apple’s own platform since no compiler or runtime library was available for other platforms. As fantastic as these platforms are to develop for, heck even I use a Mac as my main desktop machine, they only make up for a fraction of a much larger universe (my servers all run CentOS Linux). Making Swift publicly available provides access to this interesting language to a much larger developer community.

Why is the Open Sourcing for Swift so interesting?

First of all, if you’re interested in or currently are developing for one or more of Apple’s platform and are using Objective-C, then you will need to learn Swift, as soon as you can. In case you are not developing for one Apple’s platforms, which include OS X, iOS, tvOS, watchOS, and who-knows-what in the future, then currently, the applications of Swift are fairly limited to a few proof-of-concepts implementations on non-Apple platforms like Linux.

Still, why is Swift so interesting to me? It’s an extremely modern language with clever design elements, a very elegant syntax, strong safety features and, thanks to being derived from the LLVM compiler project, is extremely fast. A few of the especially interesting features for developers are: a cool error handling / exception system and Swift’s  adherence to a protocol-oriented architecture.

In Swift, no values are allowed to be null. If you declare a value as
Int, you have to assign an integer value; if you declare a
String value, it can’t ever be nil.

var exampleString : String
exampleString = nil                   // error !

Trying to set a variable to nil will result in a compiler error. Variables in Swift are only allowed to be nil, if they’re optional variables which are declared with a question mark after its type:

var exampleOptionalString : String
exampleOptionalString = nil           // allowed

The question mark indicates that a value may be assigned to the variable and it equals to X or there isn’t a value at all. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features. Because a variable’s “nullability” can be determined at compile time, a large number of null checks can be avoided. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

Swift also provides an interesting error-handling system which, in my personal opinion, improves the readability of the code. The system is derived from the older NSError system used in Objective-C APIs. It separates the idea of exceptions into two concepts: errors which are the fault of the programmer, and errors that result from user input or the environment. This distinction is important, because it’s not the user’s fault if the developer failed to check the bounds of an array before attempting to access a value, however the user should be notified if the app failed to save a file because the disk is full.

Based on this, Swift distinguishes between exceptions and errors. Exceptions are thrown by the system and always result in your program exiting with an error. Errors are triggered by problems that the user can at least attempt to deal with. Swift’s syntax requires the developer to be especially cautious about functions that can possibly cause issues.

Consider the following Java-snippet:

try {
            String data = getData();
} catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());

It’s not obvious from the code which of the three lines in the try section may possibly result in an exception being thrown. However, the equivalent code in Swift makes it clear which lines can throw an error:

do {
            try openFile()
            let data = getData()
            try writeToFile(data)
} catch let error {
            println("Error: \(error)")

In Swift, any function that can throw an error is required to be wrapped in a do block, or else their calling method must be marked as throws. In a similar fashion, methods in Java must either be wrapped in a try block or have their calling function list the possible exception that they can re-throw in the signature.
The interesting difference here is that each individual line that can throw an error must be prefixed with try. Anyone reading the code can quickly grasp which line or method might fail; in the given example, openFile and writeToFile are the problematic lines which can cause issues.

Lastly, in Swift, along with many other languages, there is this idea of a data type that contains a list of possible methods that a type respectively a class can implement. Java and C# refer to this as an interface, while C++ refers to it as an abstract base class. In Swift, this is called a protocol.

The following example shows a protocol that defines methods for processing some data:

protocol IntegerProcessing {
                 func processNumber(number : Int) -> Int

Any class can then choose to conform to the protocol like this

class MyNumberProcessor : IntegerProcessing {
                  func processNumber(number : Int) -> Int {
                           return number * 2

Even for a novice developer this might look like very benign stuff. However, the real strength and flexibility comes from the fact that the majority of the Swift standard library and the Swift language itself is largely implemented through protocols. Let’s consider the following simple example of comparing two values. In almost all programming languages, it’s possible to compare to integers to each other using the == operator:

2 == 2    // true

In slightly fewer languages this ability to compare values is extended to Strings (including Swift, but for example not in Java):

"foo" == "bar"  // false

The Equatable protocol in Swift requires that any class that conforms to it (“implements”, in Java/C# parlance) implements a version of the == operator which allows two objects of the same type to be compared against each other.

This philosophy of protocols defining the behaviour of objects, rather than their inheritance tree shapes a larger number of aspects in Swift. It’s an interesting approach to development and I’m eager to see this applied elsewhere.

I believe that these features any most definitely many more are responsible for Swift living up to its designers’ goals of being “fast, modern, safe, and interactive”.

Journal Linux

Laptop Power Saving with powertop on Fedora 22

The most important thing you want from a laptop is long battery life. Ever ounce of power you can get to work, read or simply just entertain on a long jaunt. Therefore, it’s always good to know what is consuming your power.

Intel’s powertop utility shows what’s drawing power when your system’s not plugged in. Use dnf to install powertop:

sudo dnf install powertop

powertop requires direct access to the hardware to measure power usage so you have to run it with root privileges:

sudo powertop

The powertop ouput will look similiar to the screenshot below. The measured power usage as well as system wakeups per second will most likely be different:

Screenshot of Powertop
Powertop 2.7 on Fedora 22

To switch between the multiple tabs use either the Tab or Shift+Tab keys. To quit the application, simply hit the Esc key.

The utility not only shows the power usage for various hardware and drivers but also displays the CPU stepping modes as well as systems wakeups per second. Processors are often so fast that they idle for the majority of the time.

The best way to maximize battery power is to minimize the number of wakeups per second. The best way to achieve that is to use powertops’ Tunable tab to optimise your laptop’s power savings. “Bad” usually indicates a setting that’s not saving power. In contrast, it might actually enhance the performance. “Good” indicates a setting is tuned to save power. Use the Enter key to turn any tunable on/off.

If you like to automatically turn all tunables on, the powertop package also includes a service that automatically sets all tunables to “Good” for optimal power saving. To start the service enter the following command:

sudo systemctl start powertop.service

To automatically start the service on boot time  enter the following command

sudo systemctl enable powertop.service

Probably the only caveat about this service and the tunables in general: Certain tunables may risk your data or result in some odd hardware behavior. For example, the “VM writeback timeout” settings affects how long the system waits before writing any changes of data to the actual disk. So you actually trade off data security for power savings. If the system loses all power for some reason, you might lose all the changes you made in the last 15 seconds, rather than the default 5. Nevertheless, for most laptop users this isn’t an issue since the system should warn you about low running battery.


Reduce the File Size of PDF Documents with Preview on OS X

The PDF file format is ubiquitous for good reason, mostly because it allows for perfect preservation of a documents formatting, text, and other elements. However, sometimes PDF can be quite bloated and a file that should be not more than 200KB can suddenly be 1.5MB for no obvious reason. Adobe’s Acrobat X has functions to reduce/optimise the size of a pdf. On OSX you can achieve the same with Preview.

For PDF files that have not been optimized yet, the Preview app in OS X can often reduce the file size considerably by passing it through an export filter.

While it works great for text heavy files, it’s not a perfect solution for image-heavy slides. The “Reduce File Size” Quartz filter will indeed drastically shrink the file size of a pdf but the great savings in size come at a price. It will also make the slides look thoroughly awful. This is because the filter achieves its file size reduction by scaling all the images down by at least 50% and to no more than 512 pixels on a side, plus it uses aggressive JPEG compression. So not only will the images suffer from compression artifacts, they will also tend to get that lovely up-scaling blur.

Fortunatenly, anyone can create their own Quartz Filter with the ColorSync Utility shipped with OSX. The following zip file: PDF compression filters contains various files that reduce the file size while trying to minimise the amount of artifcats introduced in the images. It’s nowhere near as aggressive as the default Quartz-Filter.

The ColorSync Utility will by default save your own Quartz Filters in the following directory: /Users/YourName/Library/Filters/.

In order for the Filters to appear in the Save AS/Export menu the *.qfilter files need to be moved into the following directory

/Library/PDF Services/ Notice not in home folder (~/) but system-wide.

Afterwards the filters will appear in the dropdown menu of the export function:
Screenshot 2014-11-28 13.43.34


Limiting ssh user to SFTP using restricted shell

This is a follow up to the recent article about restricting ssh login to sftp. Back then I showed you how to restrict an ssh user who can login into a system by configuring openssh to prevent user logins of users associated with a specific group.

To do things differently I will show you an alternative and in my personal opinion easier way of restricting a ssh user to sftp. rSSH is a restricted shell that can be used with OpenSSH to only allow sftp and scp. It also includes support for rsync, rdist and cvs. This enables the creation of shell users without providing them full login access to the server except for transferring files.

First, make sure that the rssh package is installed (can be found in the usual repository). Since Debian is still my favourite distro I use aptitude. Use the equivalent on yours (yum, zypper etc.)

# aptitude install rssh
The following NEW packages will be installed: rssh
0 packages upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 65.8 kB of archives. After unpacking 185 kB will be used.
Get: 1 wheezy/main rssh amd64 2.3.3-6 [65.8 kB]
Fetched 65.8 kB in 0s (752 kB/s)
Preconfiguring packages …
Selecting previously unselected package rssh.
(Reading database … 137643 files and directories currently installed.)
Unpacking rssh (from …/rssh_2.3.3-6_amd64.deb) …
Processing triggers for man-db …
Setting up rssh (2.3.3-6) …

In order to restrict a user to SFTP the rssh shell needs to be configured as the login shell for the user. The following example adds a new user bubu to the system with the shell set to /usr/bin/rssh

# useradd -m -d /home/bubu -s /usr/bin/rssh bubu
# passwd bubu

To change the shell of an existing shell use either usermod or the chsh command. Whichever you prefer.
# usermod -s /usr/bin/rssh <old-user-name>
# usermod -s /usr/bin/rssh chris2

# chsh -s /usr/bin/rssh chris2

Afterwards, if you try logging in via ssh or sftp you will receive a similar response to this since by default rssh locks down the system completely leaving the user without any sort of access.

$ sftp

$ ssh


[bash]’s password: TYPE-THE-PASSWORD
Linux 3.13-0.bpo.1-amd64 #1 SMP Debian 3.13.10-1~bpo70+1 (2014-04-23) x86_64 GNU/Linux
Last login: Sun Nov 16 07:03:04 2014 from localhost
This account is restricted by rssh.
This user is locked out.
If you believe this is in error, please contact your system administrator.
Connection to closed.

The default action for rssh is to lock down any access. To adjust the default setting edit the rssh.conf file. Append or uncomment the following two lines: allowscp, allowsftp:

# vi /etc/rssh.conf

# Leave these all commented out to make the default action for rssh to lock
# users out completely…



The user should be able to login into the system now:

$ sftp
Connecting to…’s password:
sftp> pwd
Remote working directory: /home/bubu