Lars Wiegman

  • Home
  • Skills
  • Contact
  • Blog

Shell history expansion

posted on November 13, 2018 #

Shells like Bash and Zsh support all kinds of expansions. One I use on a daily basis is the history expansion which expands to the last word of previous command in history. The next example would open my editor with ‘new.txt’ file.

% cp old.txt new.txt
% vim !$

Deploy and serve assets from a zip archive

posted on August 4, 2015 #

When going through the sourcecode of the godoc.org service I came upon this gem called the zipfs package. From the docs:

Package zipfs file provides an implementation of the FileSystem interface based on the contents of a .zip file.

Combine this with the FileServer handler from the net/http package and you’ll be able to serve your assets from a single zip archive.

I wouldn’t recommend this strategy in production but it beats embedding your HTML templates, CSS files and your API docs in your Go code.

The following is an example of a HTTP service which serves the contents of the given archive from the /assets/ path:

package main

import (
    "archive/zip"
    "flag"
    "log"
    "net/http"

    "golang.org/x/tools/godoc/vfs/httpfs"
    "golang.org/x/tools/godoc/vfs/zipfs"
)

func main() {
    zipPath := flag.String("zip", "assets.zip", "zip file containing assets")
    httpAddr := flag.String("http", "localhost:6011", "http address")
    flag.Parse()

    r, err := zip.OpenReader(*zipPath)
    if err != nil {
        log.Fatal(err)
    }
    fs := zipfs.New(r, *zipPath)

    m := http.NewServeMux()
    m.Handle("/assets/", http.FileServer(httpfs.New(fs)))

    log.Print("Listening on ", *httpAddr)
    if err := http.ListenAndServe(*httpAddr, m); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

Random password generator

posted on March 18, 2014 #

I was updating a random password generator for a project, thought I’d share the resulting code. Also availabe as a gist.

Using a default length of 14 characters this should generate passwords with 84 bits of entropy.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, string

def random_password(length=14):
    """
    Random password generator.

    Default generated password will have an entropy of 84 bits.

    For each character in the password, generate a random byte, reduce
    the integer value to modulo 64 and use the result as an index on
    the character pool.

    In a 64 character pool, each character will have an entropy of 6
    bits. With a lenght of 14 characters the total entropy is 84 bits:

        log2(64) * 14 = 84 bits

    The difference between 13 and 14 characters can be several years
    to brute force. """

    characters = string.ascii_letters + string.digits + '+/'

    l = list()
    for x in xrange(length):
        i = ord(os.urandom(1)) % len(characters)
        c = characters[i]
        l.append(c)
    return ''.join(l)

if __name__ == '__main__':
    print(random_password())

Generating passwords is easy, storing them safely seems to be more of a challenge.

Do more with the Caps lock key in OS X

posted on March 17, 2014 #

To most of us, the Caps Lock key is useless and even annoying; waiting to be accidentally turned on and litter your input with caps. Which is a pity because considering its location and size it’s a convenient key to tap.

By disabling the Caps lock functionality in OS X and using a third party app, the Caps lock key can become quite useful.

For example, control tmux, on OS X version 10.9.

Disable the Caps lock key in OS X

  1. Launch the System Preferences app
  2. Navigate to the Keyboard panel, from the Keyboard tab click the “Modifier Keys…” button
  3. Choose the “No Action” option for the Caps Lock Key

Tapping the Caps lock key will now be ignored by OS X.

Remap the Caps lock key

Because the Caps lock key isn’t a regular key, it can’t be configured by applications or OS X, we’ll need to remap it to a regular key, preferably one you rarely use, like F19. PCKeyboardHack allows us to do just that.

  1. Download and install PCKeyboardHack matching your OS X version
  2. After installing PCKeyboardHack you’ll need to restart OS X or load the kext manually:

    $ sudo kextload /Applications/PCKeyboardHack.app/Contents/Library/PCKeyboardHack.10.9.signed.kext
    

    Note! Load the kext matching your OS X version.

  3. Launch the PCKeyboardHack app

  4. Change the keycode of the Caps Lock key to a key you don’t regularly use, like F19 which has keycode 80.

Tapping the Caps lock key will now invoke the F19 keycode.

Configure tmux to use Caps lock

To use the remapped Caps lock key as a prefix for tmux, you’ll need to bind the F19.

Add the following to your ~/.tmux.conf:

unbind C-b
set-option -g prefix F19

If tmux was already running, reload its configuration file:

$ tmux source-file ~/.tmux.conf

Tapping Caps lock will be less of a strain on your finger than tapping Ctrl-b.

Dennis the DNS menace

posted on March 7, 2014 #

Just pushed a new project to Github, it’s just a small piece of a live project as I’m usually not at liberty to open-source production code.

The project is called Dennis. It’s a nameserver which can serve customised DNS responses on a per user basis. It’s written in the Go programming language and uses Redis as a fast datastore.

On its own Dennis isn’t very useful but by adding a DNS recursor and a HTTP(S) proxy, Dennis can bypass geo-blocking for thousands of users. It works by identifying users by their IP address, and each user can setup an unlimited number of custom DNS responses.

For a more elaborate description see the project on Github, github.com/namsral/dennis.

Tag cached responses with uWSGI

posted on March 4, 2014 #

uWSGI is a powerful application server but the documentation can be light on some subjects like caching.

If you want distinguish cache hits from misses you can use the incache:key= condition. Using the following uWSGI configuration will add a X-Cache header to each response.

[uwsgi]

...

; Enable caching
mime-file = /etc/mime.types
cache2 = name=%n-cache,items=100

; Check if URI is cached
route-if = incache:key=${REQUEST_URI},name=%n-cache goto:cache_hit

; Cache MISS
route-label = cache_miss
route-run = addheader:X-Cache: MISS
route-run = cachestore:key=${REQUEST_URI},name=%n-cache,expires=172800
route-run = last:

; Cache HIT
route-label = cache_hit
route-run = addheader:X-Cache: HIT
route-run = cache:key=${REQUEST_URI},name=%n-cache,mime=1

Requesting the same URI twice in a row will tag the response accordingly and add an additional Expires header.

$ curl -I -X GET http://namsral.com/
    HTTP/1.1 200 OK
    ...
    X-Cache: MISS

$ curl -I -X GET http://namsral.com/
    HTTP/1.1 200 OK
    ...
    Expires: Thu, 06 Mar 2014 11:11:14 GMT
    X-Cache: HIT

Apple, Drinks And Mad Men

posted on April 4, 2012 #

Three great things captured in a single picture, I added the drinks myself: Having drinks and ideas worth sharing.

Credit goes to James Minchin III for his awesome behind the scenes at Mad Men photo collection.

Enable Copy-Paste in iTunes Connect

posted on April 3, 2012 #

Got fed up with typing my password in iTunes Connect every time because the form won’t let me copy/paste it. Not sure why Apple is making this more difficult than it has to be.

To circumvent the annoyance you can either disable Javascript or override the onpaste function in the password input field and have it return true instead of false:

document.getElementsByName('theAccountPW')[0].onpaste = function() {
    return true
};

Now you can turn that script in a bookmarklet by prepending it with “javascript:“.

A Scene With Ashton Kutcher As Steve Jobs

posted on April 2, 2012 #

Ashton Kutcher as Steve Jobs in a board meeting, August 1997:

Ed Woolard, Gareth Chang, you can stay, everyone else is getting punk’d!

The iPad Mini Would Have the PPI Of An Older iPhone

posted on March 29, 2012 #

Following the rumors of the iPad Mini, A.T. Faust at AppAdvice makes a good argument why 7.85 inch would be a good size for an iPad.

But keeping the same resolution of 1024 x 768 and shrinking the screen size by 20% would have a negative effect on the effective touch surface area. Interface elements like buttons would become to small to touch. Apple’s Human Interface Guidelines recommends a minimum touch surface area of 44 x 44 points, 88 x 88 points for the newer generation iOS devices with a higher pixel density.

But how many inches of the screen should your finger cover to interact with the interface? The math says, 0.33 inches for iPads:

iPad 1st/2nd generation: 44 points / 132 ppi = 0.33 inch
iPad 3rd generation: 88 points / 264 ppi = 0.33 inch

And 0.27 inches for the iPhones, regardless of the higher pixel density on the newer models:

iPhone 4/4S: 88 points / 326 ppi = 0.27 inch
iPhone 2G/3G/3GS: 44 points / 163 ppi = 0.27 inch

So if the iPad Mini would have a 7.85 inch screen with a resolution of 1024 x 768 pixels it would have a touch surface area equivalent to an iPhone 3GS:

iPad Mini: 44 points / 163 ppi = 0.27 inch

This makes the rumored iPad size at least more plausible because it follows Apple’s Human Interface Guidelines.

But I’m still sceptical. Apple has been upgrading all of its iOS devices with higher ppi displays since the iPhone 4, followed by the iPod Touch and now the 3rd generation iPad. Even OS X, with Mountain Lion, is headed to support high ppi displays.

Releasing a new iPad with old technology doesn’t make a whole lot of sense to me. Apple is notorious for moving forwards regarding technology, not backwards, but who knows.

Apple's And Proview's iPad Dispute

posted on February 28, 2012 #

Interesting turn of events in Apple’s and Proview’s iPad dispute.

  • 1998, May: Apple unveils the iMac
  • 1999, Jul: Apple unveils the iBook
  • 2000, Aug: Proview releases the iPad
  • 2009, Dec: Apple acquires worldwide iPad trademark from Proview for $55k through a shell company called IP Application Development, IPAD Ltd for short
  • 2010, Jan: Apple announces the iPad
  • 2011, Oct: Proview demands $800M from Apple to use the iPad trademark in China
  • 2011, Dec: Apple loses right to use the iPad trademark in China
  • 2012, Jan: Proview loses battle to ban iPad in China
  • 2012, Feb: Proview charges Apple with fraud and unfair competition in iPad trademark acquisition

Notice that Apple’s iMac and iBook preceded Proview’s iPad and how Proview’s iPad looks awfully similar to Apple’s iMac.

The New Ubuntu HUD

posted on January 26, 2012 #

The new Ubuntu HUD resembles a product Aza Raskin developed a while back for Windows. It’s called Enso Launcher and has similar functionality. Besides launching apps it could control apps, manipulate text and do simple calculations as is shown in this screenshot.

A similar feature exists in Mac OS X and it’s especially helpful when controlling a Mac with a keyboard. It works and looks similar to spotlight. To use it, hit the following key combo and start typing:

Command + Shift + /

Google Needs to Prioritize Native Apps

posted on December 14, 2011 #

Most popular online services find their way to a mobile platform via iOS and eventually add support for Android. Some online services even start out as an iOS app like Instagram or remain entirely iOS exclusive like Path.

As the Android platform grows and has recently surpassed the iOS platform in marketshare, 45% vs 27% in the US according to a Comscore report, developers remain to prefer iOS as a first release platform.

This to dismay of Eric Schmidt which has recently called developers to prioritize Android:

Whether you like ICS or not, and again I like it a great deal, you will want to develop for that platform, and perhaps even first.

What is keeping developers from prioritizing Android is what many already have speculated. And now has been backed up by numbers from analytics firm Flurry Analytics. Their revenue analysis prove iOS to be roughly 4x more profitable per app. This is despite the larger market share of the Android platform.

It’s up for speculation what makes the iOS platform more profitable but Google’s stance towards apps and selling them through an app store is certainly not improving the matter. Google’s own priority lies with the Web and not with native apps. An excerpt from an article posted by CNET in February to prove my point:

Google’s philosophy of pushing Web development over native software development when possible, a strategy that isn’t always practical on smartphones but is starting to make more sense as computing power grows in tablets.

Google’s quest in this world is to one day replace software developed for specific machines with software developed on and for the Web.

And for most mobile users the web is something that is free to use, albeit paid by ads or your privacy. Contrary to native apps for which users pay for in an app store.

If Eric Schmidt really wants developers to prioritize the Android platform, Google itself has to prioritize native apps.

As a developer you have limited resources and need to prioritize in order to succeed and starting to develop for the most profitable platform makes a lot of sense.

How Steve Jobs Will Be Remembered

posted on October 6, 2011 #

Barack Obama, via AllThinsD:

And there may be no greater tribute to Steve’s success than the fact that much of the world learned of his passing on a device he invented.

Larry Page, CEO at Google, via Goolge+:

He was very kind to reach out to me as I became CEO of Google and spend time offering his advice and knowledge even though he was not at all well.

Lakshan Perera, via LakTEK

Steve’s life was not bed of roses. As a child he was adopted, he had to drop-out from the University, was kicked out from his own company and lived the best years of his life battling with Pancreatic cancer. Yet he managed to “put a ding in the universe”.

Steve Jobs himself, in a speech at Stanford University:

…death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life’s change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true.

He will be missed.

Personal URL Shortener In Three Lines Of Code

posted on April 23, 2011 #

Having your own URL shortener service has some benefits over using a third party service. To name two: more exposure for your personal domain and full access to web traffic data. But if, for whatever reason, you don’t want to host your own here is a quick hack using the Nginx webserver.

Choose a reliable URL shortener service. I’m betting on Google’s service at http://goo.gl/. Add the following three lines to the server section of your Nginx configuration:

location ~ /u/(.*)$ {
    rewrite ^/u/(.*)/?$ http://goo.gl/$1 redirect;
}

Generate a shortened URL at http://goo.gl/ and replace the goo.gl domain with your own. In my case:

http://goo.gl/nlthH > http://namsral.com/u/nlthH

When users click on your shortened URL they will be redirected to Google’s shortened URL which in turn will redirect users to their final destination. This all happens in a flash, try it .

By adding a unique path to your shortened URLs you’ll be able to differentiate them from other content on your site. Now using grep you can quickly scan through the Nginx logs for clicks:

grep '/u/' /var/log/nginx/namsral.com.access.log

Lost In App Store Limbo

posted on April 20, 2011 #

The “Release soon, release often” and “Incremental improvements” mantras often spoken of by web application publishers do not apply to iOS apps. iOS apps need to be washed and groomed to perfection before they are released to the App Store horde.

The majority of apps released in the App Store get one chance at making a splash. If it fails to generate enough downloads or develop a large enough user base to get picked up by the general public the app is forever lost in limbo.

I Don't Always Test My Code

posted on April 14, 2011 #

I Don’t Always Test My Code But When I Do, I Do It In Production

This would make a great quote for the most interesting man in the world.

Hold Off Spammers with Nginx

posted on February 18, 2011 #

If you run your own webserver, Nginx in my case, you can easily hide mailto links from spammers with the HTTP rewrite module.

Add the following three lines of code to your Nginx server config and replace any “mailto:user@example.com” links with “/mail/user/”.

location ~ /mail/(.*)$ {
        rewrite ^/mail/(.*)/$ mailto:$1@$host redirect;
    }

The same can be done for other schemes like for making telephone calls. Again, add the code below and replace any “tel:555-1234” links with “/call/55512345/”.

location ~ /call/(.*)$ {
        rewrite ^/call/(.*)/$ tel:$1 redirect;
    }

These are examples using Nginx but I bet the same can be accomplished with other webservers.

Apple's 30 Percent Cut

posted on February 17, 2011 #

It’s not a bad deal. If you were going down the “Sell it Yourself” road and use PayPal to collect money with say a one dollar app, it would cost you 32¢. This is sans the hosting & exposure, which is more than Apple charges its developers on the App Store.

  • Home
  • Skills
  • Blog
  • Contact
  • •
  • Archive
  • Feed
  • GitHub

Copyright © 2007-2018 Lars Wiegman, lars@ at namsral.com