This is a website by Willem van Zyl

I'm a project manager, software developer, Apple evangelist and geek from South Africa. I'm passionate about web and mobile application development, usability, productivity, physics, astronomy, science fiction and fantasy.

If you would like to contact me, message me on Twitter or send me an email.

How to keep spaces and dashes (hyphens) from breaking to a new line in HTML

28 Jan 2012

In HTML table headers, cells, and other containers spaces or dashes (hyphens) within textual elements could become breakpoints.

This usually happens if the container or page layout is too small to fit all of the text on one line, but can be prevented by using either non-breaking spaces or non-breaking dashes:

Non-breaking spaces

The HTML Entity for a non-breaking space is " ":

<table>
  <tr>
    <td>
      This text could break to a new line.
    </td>
  </tr>
</table>

<table>
  <tr>
    <td>
      This&nbsp;text&nbsp;won't&nbsp;break&nbsp;to&nbsp;a&nbsp;new&nbsp;line.
    </td>
  </tr>
</table>

Non-breaking dashes (hyphens):

The HTML Entity for a non-breaking dash (hyphen) is "&#8209;":

<table>
  <tr>
    <td>
      this-text-could-break-to-a-new-line.
    </td>
  </tr>
</table>

<table>
  <tr>
    <td>
      this&#8209;text&#8209;won't&#8209;break&#8209;to&#8209;a&#8209;new&#8209;line.
    </td>
  </tr>
</table>

Read more...

Why I don't sign Non-Disclosure Agreements

22 Jun 2011

As a freelance software developer, potential clients often ask me to sign NDAs (Non-Disclosure Agreements) before they're willing to discuss the details of a project with me.

Although I understand these clients' concerns about intellectual property, I always refuse to sign.

Trade secrets that would give employees an unfair advantage in their future careers are categorically not the same thing as ideas for websites & web applications. Clients like to think that their ideas are unique, innovative, and ground-breaking, but 10+ years in the industry has unfortunately shown me that they rarely are.

I once made the mistake of signing an NDA, only to discover that the client wanted me to build an application that was, quite simply, an email-like messaging system. The project didn't incorporate any innovative ideas, and it wasn't unlike similar components that I'd previously built for other systems. Even though the idea behind the project was commonplace, ever since then that signed NDA made me feel uncomfortable whenever I had to build messaging components for other projects.

Read more...

Focus on being productive instead of being busy

15 Jun 2011

Somehow the modern world has assigned the meaning of the word "effective" to the word "busy".

For some people being busy is a status symbol – a badge of honor that marks them as important, a go-getter, an achiever. The problem with this mindset is that they never end being busy: to-do lists keep growing, emails pile up, phone calls go unanswered, and they're always rushing towards some imaginary destination.

Being busy doesn't necessarily mean that you're getting work done. To be productive, you have to deliver.

Read more...

How to find text within specific types of files from the command line

09 Sep 2010

Sometimes it's useful to speed up text (or regular expression)-based searches from the command line by only searching through specific types of files.

To find text within specifically-typed files from the command line, open a new Terminal window, switch to the directory containing the files you want to search through, and enter the following command (replacing "js|php|sh" with a pipe-separated list of file extensions and "willem" with your search string):

find . -type f | egrep 'js|php|sh' | sed -e "s@'@\\\'@g" -e "s@ @\\\ @g" | xargs grep "willem"

This command will recursively find all files within the current directory, filter only files with the specified extensions from the list, and search each of these files for the specified search text.

After the command has run, you'll see output similar to the following:

./system/application/config/acl.php:  * @author     Willem van Zyl (willem@geekology.co.za)
./system/application/config/acl.php:  * @version    $Id: acl.php 1030 2010-07-19 09:49:01Z willem $
./system/application/config/autoload.php:  * @author     Willem van Zyl (willem@geekology.co.za)
./system/application/config/autoload.php:  * @version    $Id: autoload.php 930 2010-06-23 13:33:11Z willem $
./system/application/config/config.php:  * @author     Willem van Zyl (willem@geekology.co.za)
./system/application/config/config.php:  * @version    $Id: config.php 1008 2010-07-09 13:55:42Z willem $
./system/application/config/constants.php:  * @author     Willem van Zyl (willem@geekology.co.za)
./system/application/config/constants.php:  * @version    $Id: constants.php 930 2010-06-23 13:33:11Z willem $

Read more...

How to disable auto-formatting of telephone numbers by the Skype Browser Plugin

05 Jul 2010

If your website displays telephone numbers, visitors who have Skype installed might see a broken layout.

This is due to the Skype Browser Plugin functionality that parses each webpage visited to find textual telephone numbers and replace them with "Call via Skype" image links:

To keep the Skype Prowser Plugin from modifying your content or breaking your layout, Skype proposes that web developers add the following metadata tag to their websites' HTML HEAD sections:

<meta name="SKYPE_TOOLBAR" CONTENT="SKYPE_TOOLBAR_PARSER_COMPATIBLE">

This metatag is supposed to instruct the Skype Browser Plugin to only reformat numbers that are "tagged" with the following HTML comment:

<!-- sphoneid telnr="+27210000000" fileas="Willem van Zyl" -->021 000 0000<!-- sphoneid -->

... but unfortunately it won't work at all if you're not using the Transitional XHTML DOCTYPE. Even if you are using Transitional XHTML, you can still expect the metadata tag to only work occasionally so long as you used the exact capitalization, attribute order, and wording above. Lastly, the tag above isn't valid XHTML (it doesn't have a closing slash), so its usage is not ideal.

Read more...

How to manage background tasks in the Bash shell

10 Jun 2010

In the the Bash command line shell the "&" (ampersand) character is a control operator used to fork processes.

According to the man page for Bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

If the ampersand character is added to the end of a command, Bash will execute the command as a background process and assign a Job Number in addition to the usual Process ID (PID) to it:

Willem-Van-Zyls-MacBook-Pro:~ willem$ sleep 60 &
[1] 66984
Willem-Van-Zyls-MacBook-Pro:~ willem$ sleep 30 &
[2] 67001

In the above output, the "[1]" and "[2]" indicate the Job Numbers and the "66984" and "67001" indicate the PIDs.

To see a list of all running jobs, use the "jobs" command:

Willem-Van-Zyls-MacBook-Pro:~ willem$ jobs
[1]-  Running                 sleep 60 &
[2]+  Running                 sleep 30 &

To terminate a job, use the "kill" command and a "%" (percentage sign) with the Job Number appended:

kill %1

Read more...

How to download YouTube videos with Safari

09 Jun 2010

Although there are several free video downloading services available online, videos can easily be downloaded from YouTube by using just Safari and a free video conversion utility.

Open Safari, then browse to the YouTube video you want to download.

Read more...

How to list comments and files changed for a specific Subversion revision on the command line

01 Jun 2010

If you need to check which files changed during a specific Subversion revision, open a new Terminal window, switch to the directory containing the working copy, and enter the following command (replacing "{svn_repository_address}" with the actual URL to your SVN Repository):

svn log -v -r 7447 {svn_repository_address}

The above command will present you with output similar to the following:

------------------------------------------------------------------------
r158 | willem | 2010-01-28 12:54:23 +0200 (Thu, 28 Jan 2010) | 1 line
Changed paths:
   A /trunk/system/application/config/common_passwords.php
   M /trunk/system/application/javascript/general.js
   M /trunk/system/application/javascript/jquery.passwordStrength.js
   M /trunk/system/application/models/ajax_model.php
   M /trunk/system/application/views/administration/administration_users-add_view.php

Working on ticket #59. Added common passwords list.
------------------------------------------------------------------------

The "svn log" command has several additional parameters available, these can be viewed by entering the following in a Terminal window:

svn help log

Read more...

How to import / export comma-separated value (CSV) files to / from MySQL databases

04 Feb 2010

If you need to import data from CSV or other text-based files to a MySQL database or vice-versa, you can use the LOAD DATA or SELECT INTO OUTFILE statements explained below.

Examples - Importing files with "LOAD DATA"

A MySQL LOAD DATA statement can be used to load values from any text-based files (such as comma separated, tab separated, etc.) into database tables.

In the examples below, a CSV file with the following content is imported:

"column1","column2","column3"
1,"foo",10
2,"bar",20
3,"baz",30

... into a table with the following structure:

CREATE TABLE `test_table` (
`column1` INT NOT NULL,
`column2` VARCHAR(100) NOT NULL,
`column3` INT NOT NULL,
PRIMARY KEY (`column1`)
);

A simple import:

LOAD DATA LOCAL INFILE '/Users/willem/Documents/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(column1, column2, column3);

An import with variables and arithmetic:

LOAD DATA LOCAL INFILE '/Users/willem/Documents/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(column1, column2, @variable1)
SET column3 = @variable1 / 100;

Read more...

A list of cPanel and WHM Inbound and Outbound Ports

27 Jan 2010

cPanel in combination with WHM is a Unix-based (usually integrated with CentOS Linux) web hosting control panel that provides a graphical interface and automation tools designed to simplify the process of hosting websites.

In combination with WebHost Manager (WHM), the software offers GUI, command line, and API-based access that allows third-party software vendors, web hosting organizations, and developers to automate standard system administration processes to manage hosting accounts on a web server.

If you have a WHM-based server running behind a firewall, you’ll need to open certain ports on your firewall to enable all services. The following are lists of Inbound and Outbound Ports used by the cPanel and WHM software:

Read more...

How to check kernel, architecture, and release (distribution) information on Linux

10 Jan 2010

Kernel and architecture

The uname command-line utility can be used to check the kernel and architecture of a machine running Linux:

uname -a

... resulting in output like:

Linux ubuntu 2.6.20-16-generic #2 SMP
Tue Feb 12 05:41:34 UTC 2008 i686 GNU/Linux

This output specifies the operating system ("Linux"), nodename on the network ("ubuntu"), kernel version ("2.6.20-16-generic"), and architecture ("i686"), but it doesn't specify the operating system's release information.

Red Hat, Fedora, and CentOS Release Info

To check the release information in Red Hat Enterprise Linux, Fedora, or CentOS, run the following command:

Read more...

How to check which processes are accessing the Internet on Mac OS X or a Linux machine

26 Oct 2010

The "lsof" command line tool can be used to list information about files opened by processes. By adding certain parameters, the tool will list IP Address / Host Name and Port details about all processes' open network files (connections):

lsof -i

The above command will show output like the following:

Willem-MacBook-Pro:~ willem$ lsof -i
COMMAND   PID   USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
SystemUIS 376 willem   10u  IPv4 0x3db2878      0t0  UDP *:*
Finder    377 willem   11u  IPv4 0x4e9a66c      0t0  TCP localhost:49171->localhost:26164 (ESTABLISHED)
Connect36 396 willem    4u  IPv4 0x3db26c8      0t0  UDP *:ssdp
Connect36 396 willem    5u  IPv4 0x3db46d8      0t0  UDP 192.168.1.102:9334->239.255.255.250:ssdp
Connect36 396 willem    6u  IPv4 0x4e9ae64      0t0  TCP *:9335 (LISTEN)
Dropbox   407 willem    7u  IPv4 0x5db9e64      0t0  TCP 192.168.0.48:49169->174.36.30.67-static.reverse.softlayer.com:https (CLOSE_WAIT)
Dropbox   407 willem   15u  IPv4 0x481366c      0t0  TCP 192.168.1.102:55607->174.36.30.66-static.reverse.softlayer.com:https (CLOSE_WAIT)
Dropbox   407 willem   18u  IPv4 0x4e9a270      0t0  TCP localhost:26164 (LISTEN)
Dropbox   407 willem   19u  IPv4 0x5db966c      0t0  TCP localhost:26164->localhost:49171 (ESTABLISHED)
Dropbox   407 willem   20u  IPv4 0xa470e64      0t0  TCP 192.168.0.48:52821->174.36.30.66-static.reverse.softlayer.com:https (CLOSED)
Dropbox   407 willem   21u  IPv4 0x42dea68      0t0  TCP 192.168.0.48:54833->ec2-174-129-27-165.compute-1.amazonaws.com:https (CLOSE_WAIT)
Dropbox   407 willem   24u  IPv4 0xb428270      0t0  TCP 192.168.1.102:54996->208.43.202.30-static.reverse.softlayer.com:http (ESTABLISHED)
Dropbox   407 willem   25u  IPv4 0x505ea68      0t0  TCP 192.168.1.102:55606->174.36.30.66-static.reverse.softlayer.com:https (CLOSE_WAIT)
firefox-b 554 willem   30u  IPv4 0xa498e64      0t0  TCP 192.168.1.102:55670->channel47-09-01-snc1.facebook.com:http (ESTABLISHED)
firefox-b 554 willem   40u  IPv4 0x5243a68      0t0  TCP 192.168.1.102:55668->wy-in-f100.1e100.net:http (ESTABLISHED)
firefox-b 554 willem   44u  IPv4 0xa45fa68      0t0  TCP 192.168.1.102:55669->74.125.100.100:http (ESTABLISHED)
firefox-b 554 willem   79u  IPv4 0xa462e64      0t0  TCP 192.168.0.48:50332->nwk-qtsoftware.apple.com:http (CLOSED)

In the above output the columns from left to right indicate the Process Name, Process ID, User that the process belongs to, Type of Connection, Device Address, Connection Node, and Connection Addresses / Host Names / Ports / Status.

To display the output with IP Addresses instead of Host Names, add the "-n" parameter:

Read more...

How to set up custom voicemail greetings in Asterisk

15 Oct 2009

Asterisk is a popular free and open source software implementation of a telephone private branch exchange (PBX) system available for many versions of Unix.

The software allows attached telephones to make calls to one another, connect to Public Switched Telephone Network (PSTN) systems, and connect to Voice Over Internet Protocol (VoIP) services. Additionally, users can set up voice mailing, conference calling, interactive phone menus, and automatic call distribution.

Asterisk is available in several pre-packaged distributions (including a Linux operating system, Asterisk, all relevant hardware drivers, and a User Interface), the most popular of which is Trixbox.

Voicemail greetings in Trixbox

Although Trixbox offers a lot of Asterisk customization options through its user interface and allows users to easily record / upload / manage custom voice greetings for IVRs (digital receptionists) and Ring Groups, setting up custom voicemail greetings for individual extensions isn't catered for in the UI.

By default, Trixbox uses generic voicemail greetings ("The person at extension 123 is on the phone, please leave your message after the tone. When done, hang up or press the pound key.") for all extensions. There are two ways to change these greetings:

Read more...

An introduction to Regular Expressions

12 Oct 2009

Regular expressions (also known as "regex" or "regexp") are short text strings for describing search patterns. Regex can be used to search for simple or extremely complex patterns through blocks of text, and most programming languages as well as several Unix command-line tools (such as grep, expr, sed, awk, and vi) and Mac OS X desktop applications (such as BBEdit, SubEthaEdit, and TextMate) can interpret and use them. As of version 3, the Bash shell also acquired its own regex-match operator that can be used in Bash Scripts.

The Basics

The most basic type of regular expression consists of a single literal character:

a

A search using this expression will match the first occurrence of the character "a" in a target string, so if the target string was:

This is a sentence

... the regular expression will match the "a" between "is " and " sentence".

This regular expression could match the second (and third, and fourth, etc.) occurrence of "a" too, but will only do so if you tell the regex engine to continue searching through the target string.

A more complex regular expression can contain optional and non-optional characters, repetition, etc., for example:

Read more...

How to claim a replacement Xbox 360 in South Africa after the Red Ring of Death

05 Oct 2009

The South African Xbox 360 Exchange page on xbox.com doesn't provide a lot of information on the replacement procedure, so this post details everything you need to do to perform a claim on your warranty.

In the past faulty Xbox 360s had to be taken to their place of purchase to perform a claim, but this procedure recently changed so you can complete a claim from home.

Xbox 360s purchased in South Africa are covered by three warranties: A 90-day Accessory Warranty, a 1-Year All-Purpose Warranty covering manufacturing defects and faulty parts, and a 3-Year Red Ring of Death (RROD) Warranty covering hardware failures indicated by 3 flashing red lights or an E74 error message.

The two latter warranties are void if:

  • the console has been opened
  • the console has been tampered with in any way
  • any of the seals on the console are broken

Lightning strikes and power surges are not covered by any warranty, power adapters are COD replacements, and claims on international consoles or out-of-warranty units are chargeable.

If you receive a replacement console, your original warranty does not reset. However, it does receive a short extension in most cases depending on where you are in the warranty period:

Read more...

How to use PHP and NuSOAP to connect to web services

02 Oct 2010

NuSOAP is a rewrite of SOAP contained in a set of PHP classes that don't require a PHP Extension (in contrast, SOAP requires that PHP be compiled with the "–enable-soap" option).

The examples below use the NuSOAP library to connect to a WSDL-based (Web Services Description Language) web service hosted on an IIS server:

To perform a function call without parameters or user authentication:

<?php

  //include the NuSOAP class file:
  require 'lib/nusoap.php';

  //instantiate the NuSOAP class and define the web service URL:
  $client = new nusoap_client('http://www.someserver.com/service.svc?wsdl', 'WSDL');

  //check if there were any instantiation errors, and if so stop execution with an error message:
  $error = $client->getError();

  if ($error) {
    die("client construction error: {$error}\n");
  }

  //perform a function call without parameters:
  $answer = $client->call('TestFunction');

  //check if there were any call errors, and if so stop execution with some error messages:
  $error = $client->getError();

  if ($error) {
    print_r($client->response);
    print_r($client->getDebug());
    die();
  }

  //output the response (in the form of a multidimensional array) from the function call:
  print_r($answer);

?>

Read more...

How to purchase an Xbox LIVE Gold Subscription in South Africa

30 Sep 2009

Even though Microsoft's been promising it for years, South Africa still doesn't officially have Xbox LIVE for multiplayer gaming. According to Microsoft this is due to low bandwidth availability, but even so local gamers have been playing on the UK and US Xbox LIVE servers for years.

Playing on Xbox LIVE requires three things:

  • An ADSL Internet connection
  • An Xbox LIVE Gamertag
  • An Xbox LIVE Gold Subscription

A Gamertag is free and can be created on your console, while a Gold Subscription will cost you somewhere between R150 and R500, depending on the supplier and the length of the subscription.

The following instructions assume that you have an Xbox 360 running the NXE (New Xbox Experience) dashboard. If this is the case, the interface you see after you turn on the console will look like this:

If your Xbox 360 is running the older dashboard software, the interface will look like the image below and although the screenshots later in the post will look similar to what your console displays, they won't look exactly the same. You'll be prompted to download the free NXE update after you've set up your Xbox LIVE Gamertag:

Read more...

How to add a Recent Items stack to the Dock on Mac OS X

02 Sep 2009

Mac OS X stacks usually list the contents of specified folders, but the Dock has a hidden Recent Items Stack feature for Applications, Documents, Servers, and Volumes.

To enable the Recent Items Stack, open a new Terminal window and enter the command below:

defaults write com.apple.dock persistent-others -array-add '{ "tile-data" = { "list-type" = 1; }; "tile-type" = "recents-tile"; }'

... then right-click on the new Stack to choose which information to display.

To revert the change, right-click (or control-click) on the Recent Items Stack and choose the "Remove from Dock" option.

Read more...

How to change the Mac OS X Login Screen's background image

26 Aug 2009

Mac OS X has only one background image for its Login Screen by default, but the commands below can be used to change this image.

Your new background image should be a 2560 × 1600 pixels JPEG image. To change the Login Screen's background image, open a new Terminal window and enter the following command (replacing "/path/to/backgroundimage.jpg" with the full path to your preferred background image):

defaults write /Library/Preferences/com.apple.loginwindow
  DesktopPicture "/path/to/background/image.jpg"

To revert the change, open a new Terminal window and enter the following command:

defaults write /Library/Preferences/com.apple.loginwindow
  DesktopPicture "/System/Library/CoreServices/DefaultDesktop.jpg"

Read more...

How to display hidden files and directories in the Finder on Mac OS X

18 Aug 2009

In Mac OS X, the Finder doesn't display hidden files and directories by default (on Unix systems, directories or files are hidden by adding a "." in front of their names). To change this setting, use the commands below:

To make the Finder display hidden files and directories, open a new Terminal window and enter these commands:

Read more...

How to make hidden application icons transparent on Mac OS X

14 Aug 2009

In Mac OS X, clicking on the red button in an application's titlebar or clicking on the application's name in the menubar and choosing "Hide {APPLICATIONNAME}" will hide it from view until you click on its icon in the Dock.

By default the icons for hidden applications look no different than those for visible applications, but you can change this setting using the command below.

To make the icons for hidden applications appear transparent in the Dock, open a new Terminal window and enter these commands:

defaults write com.apple.Dock showhidden -bool YES
killall Dock

To revert the change, open a new Terminal window and enter these commands:

defaults write com.apple.Dock showhidden -bool NO
killall Dock

Read more...

How to get an iPhone out of the Recover Mode Loop

12 Aug 2009

Once an iPhone is put into Recovery Mode, it will be stuck in the Recovery Mode Loop (when the device restarts it'll automatically go back into Recovery Mode).

To get an iPhone out of the Recovery Mode Loop, download the cross-platform iRecovery utility from ihackintosh.com. The instructions below are for using the command-line Macintosh version of iRecovery, but there's also a Windows version included in the download.

Open a new Terminal window and navigate to the directory that the iRecovery for Mac utility was extracted to.

Connect the iPhone to your Mac with the USB cable, wait for iTunes to finish any synchronization, then enter the command below to open a Terminal interface to the device:

./irecovery -s

You will see output similar to this:

iRecovery - Recovery Utility
by westbaer
Thanks to pod2g, tom3q, planetbeing and geohot.

=======================================
::
:: iBoot for m68ap, Copyright 2008, Apple Inc.
::
::  BUILD_TAG: iBoot-385.49
::
::  BUILD_STYLE: RELEASE
::
=======================================

[FTL:MSG] Apple NAND Driver (AND) RO
[NAND] Device ID           0xb614d5ec
[NAND] BANKS_TOTAL         4
[NAND] BLOCKS_PER_BANK     4096
[NAND] PAGES_PER_BANK      524288
[NAND]SECTORS_PER_PAGE    8
[NAND] BYTES_PER_SPARE     128
[FTL:MSG] FIL_Init            [OK]
[FTL:MSG] BUF_Init            [OK]
[FTL:MSG] FPart Init          [OK]
read old style signature 0x43303034 (line:286)
[FTL:MSG] VFL Register    [OK]
[FTL:MSG] VFL Init            [OK]
[FTL:MSG] VFL_Open            [OK]
[FTL:MSG] FTL Register    [OK]
[FTL:MSG] FTL_Open            [OK]
Boot Failure Count: 2   Panic Fail Count: 0
Entering recovery mode, starting command prompt
]

Next, enter these commands in the device's Terminal interface:

setenv auto-boot true
saveenv
/exit

... then reboot the iPhone by holding down the Sleep / Wake and Home buttons for 10 seconds.

Read more...

How to change the Mac OS X Login Screen's welcome message

06 Aug 2009

The Mac OS X Login Screen displays no welcome message by default, but you can add a message such as your company name by using the commands below.

To change the Login Window message, open a new Terminal window and enter this command:

sudo defaults write /Library/Preferences/com.apple.loginwindow
  LoginwindowText "www.geekology.co.za"

To revert the change, open a new Terminal window and enter this command:

sudo defaults write /Library/Preferences/com.apple.loginwindow
  LoginwindowText ""

Read more...

How to change the format of screenshots saved to your Desktop on Mac OS X

03 Aug 2009

Mac OS X has several options for taking screenshots with shortcut keys or taking screenshots from the command line. By default these screenshots are copied to the clipboard or saved to your Desktop as PNG files. You can set these saved screenshots to one of several different filetypes using one of the commands below.

To change the default screenshot filetype, open a new Terminal window and enter a command like this (replacing "{filetype}" with your preferred filetype):

defaults write com.apple.screencapture type {filetype}

... then log out and back in to activate the changes.

Permitted filetypes are "jpg", "png", "bmp", "gif", and "tiff".

Read more...

How to display a text-based file and folder tree on the command line

29 Jul 2009

If you need to see a visual layout of files and directories from the current directory in a tree, you can do so by piping the output from a recursive "ls" command into a "grep" search, then piping those results into "sed" replacements to build the tree view.

Open a new Terminal window, switch to the directory you'd like to list, then enter this command:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g'
  -e 's/^/ /' -e 's/-/|/'

Explanation of the commands

  • ls -R - list all files recursively

  • grep ":$" - find all lines ending in ":" (a colon)

  • sed -e 's/:$//'... - remove all trailing ":" (colons), replace "-" (dashes) with "|" (pipes), and replace "/" (forward slashes) with "–" (double dashes)

Example output

|-Outlook Plugins
|-QuickLook Plugins
|-Quicktime Codecs
|---Perian.component
|-----Contents
|-------MacOS
|-------Resources
|---------English.lproj
|-----------main.nib
|---------French.lproj
|-----------main.nib
|---XviD_Codec-r58 (Intel).component
|-----Contents
|-------MacOS
|-------Resources
|---------English.lproj
|---------XviD_Codec.nib
|---------XviD_Export.nib

Read more...

How to reuse commands with different arguments on a Bash command line

20 Jul 2009

If you'd like to rerun a command on a Bash command line with a different set of arguments without retyping the entire command or manually replacing the arguments one-by-one, you can do so using the "!!:gs" syntax demonstrated below.

Some Unix commands can be lengthy to type and tedious to manually modify, for example:

find . -type f -name "*Mac*" > ~/Desktop/Mac-list.txt

The above command would search the current directory and its subdirectories for files with "Mac" anywhere in their names and write the results to a text file named "Mac-list.txt" on the user's Desktop.

If you wanted to change this command to find all files containing "Ubuntu" anywhere in their names and write the results to a text file named "Ubuntu-list.txt" on the user's Desktop, you could press the "Up Arrow" key to display the last command, use the arrow keys to move the cursor to each instance of the term "Mac", delete it, and replace it with "Ubuntu".

Alternatively, you could use a simple replace statement like the one below:

!!:gs/Mac/Ubuntu/

... to rerun the last command ("!!") after replacing all instances of "Mac" with "Ubuntu".

Read more...

How to find lost ZIP file passwords with "fcrackzip"

17 Jul 2009

fcrackzip is a free ZIP password cracking utility for Linux and OS X that can be used to recover lost ZIP file passwords through brute force or dictionary attacks.

To install fcrackzip on Linux, you can use use apt-get:

sudo apt-get install fcrackzip

... yum:

sudo yum install fcrackzip

... or a similar repository system.

To install fcrackzip on Mac OS X, first install MacPorts then install fcrackzip through MacPorts:

sudo port install fcrackzip

The default brute force starting length is 5-6 characters, so you might want to specify a minimum and maximum password length when you invoke fcrackzip. To use the utility, switch to the directory containing your encrypted ZIP file and run fcrackzip with the "-b" (use a brute force attack), "-u" (use unzip to weed out wrong passwords), and "-l" (specify password length) arguments:

fcrackzip -b -u -l 1-4 geekology.zip

The software will run for some time depending on the complexity of the ZIP file's password and will display a success message once it finds the correct key (in my test the brute force attack took 1 minute to find the correct result for a 4-letter password):

PASSWORD FOUND!!!!: pw == geek

You can find more information on fcrackzip's usage in its help page ("fcrackzip -h"):

fcrackzip version 1.0, a fast/free zip password cracker
written by Marc Lehmann
 You can find more info on
http://www.goof.com/pcg/marc/

USAGE: fcrackzip
          [-b|--brute-force]            use brute force algorithm
          [-D|--dictionary]             use a dictionary
          [-B|--benchmark]              execute a small benchmark
          [-c|--charset characterset]   use characters from charset
          [-h|--help]                   show this message
          [--version]                   show the version of this program
          [-V|--validate]               sanity-check the algortihm
          [-v|--verbose]                be more verbose
          [-p|--init-password string]   use string as initial password/file
          [-l|--length min-max]         check password with length min to max
          [-u|--use-unzip]              use unzip to weed out wrong passwords
          [-m|--method num]             use method number "num" (see below)
          [-2|--modulo r/m]             only calculcate 1/m of the password
          file...                    the zipfiles to crack

methods compiled in (* = default):

 0: cpmask
 1: zip1
*2: zip2, USE_MULT_TAB

Read more...

How to pair or unpair an Apple Remote with an Apple TV or a Mac

09 Jul 2009

The Apple Remotes shipped with Apple TVs, iMacs and MacBooks can be used to play / pause music or skip tracks, toggle your Mac between sleep / wake modes, control Front Row (OS X's built-in media center software), Keynote slideshows, or non-Apple software such as Boxee.

By default any Apple Remote will work on any Apple product, but if you'd like some extra security you can pair a single Apple Remote with your Apple TV or Mac.

Pairing or unpairing an Apple Remote with a Mac

To pair an Apple Remote with a Mac, point the remote at the computer and hold down the Menu and Next / Fast-Forward buttons for a few seconds until a confirmation appears on-screen:

Read more...

How to remove hidden ".svn" directories from the command line

06 Jul 2009

When Working Copies are checked out of a Subversion repository, Subversion creates a hidden ".svn" directory in each directory of the Working Copy to store metadata about your project and any changes you've made.

This metadata increases the total size on disk of your Working Copy, so if you need to send a copy of your project to someone you can remove the metadata by opening a Terminal window, navigating to the top-level directory of the Working Copy, and running this command:

sudo find * -type d -name .svn -exec rm -rf {} \;

In the command above, the "-type d" argument specifies that the "find" utility should only search for directories, the "-name .svn" argument specifies that it should search for results with ".svn" as their name, and the "-exec rm -rf {} \;" argument specifies that it should execute "rm -rf" (remove recursively without asking for permission on individual files) on the results.

Please note that after you've run this command on a Working Copy's directories, you won't be able to use any svn commands (e.g. "svn status", "svn update", "svn commit", etc.) on it anymore.

Read more...

Xcode and Objective-C resources for iPhone Application Developers

02 Jul 2009

If you'd like to become an iPhone Application Developer, there are several resources available online and offline to get you started.

There are two kinds of iPhone applications: Web-based and Native. Web Apps combine the iPhone's Multi-Touch technology with Safari web-based interfaces (built in HTML, JavaScript and CSS with additional functionality provided by your language of choice: PHP, Java, etc.), while Native Apps are designed and developed in Apple's Xcode software using the Objective-C language.

Web Apps can be developed on any platform, but if you do so on a Mac you'll have access to Apple's excellent Dashcode IDE and iPhone Simulator (a full version of the iPhone OS running as a desktop application) to debug your application.

Native Apps can only be developed in the Objective-C language on a Mac using Apple's free Xcode IDE. To debug your Native Apps, you can run them in the iPhone Simulator or configure your actual iPhone as a development device for testing.

Web Apps

Safari is Apple's web browser based on the WebKit engine, and the Safari Dev Center provides Safari Development Videos, a Reference Library, Technical Articles, Coding How-To's and Sample Code to enable iPhone OS integration, visual effects, client-side storage and offline applications for Safari-based Web App development.

Read more...

How to send emails with attachments using PHP's "mail()" function

29 Jun 2009

If you need to send an email with attachments using just PHP's "mail()" function, you can do so by using a multipart/mixed content header and converting the attachments to base64 strings.

First, generate a random hash to serve as a MIME Boundary:

$random_hash = md5(date('r', time()));

Next, set some email headers:

$headers = "From: noreply@geekology.co.za\r\nReply-To: noreply@geekology.co.za";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

... then convert the attachment into a base64 string:

$attachment = chunk_split(base64_encode(file_get_contents("geekology.zip")));

Finally, define the content of the email in a similar manner to the example below, then send it using PHP’s "mail()" function:

<?php

  $to = "someone@somewhere.com";

  $subject = "A test email";

  $random_hash = md5(date('r', time()));

  $headers = "From: noreply@geekology.co.za\r\nReply-To: noreply@geekology.co.za";

  $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

  $attachment = chunk_split(base64_encode(file_get_contents("geekology.zip")));

  $output = "
  --PHP-mixed-$random_hash
  Content-Type: multipart/alternative; boundary='PHP-alt-$random_hash'
  --PHP-alt-$random_hash
  Content-Type: text/plain; charset='iso-8859-1'
  Content-Transfer-Encoding: 7bit

  Hello World!
  This is the simple text version of the email message.

  --PHP-alt-$random_hash
  Content-Type: text/html; charset='iso-8859-1'
  Content-Transfer-Encoding: 7bit

  <h2>Hello World!</h2>
  <p>This is the <b>HTML</b> version of the email message.</p>

  --PHP-alt-$random_hash--

  --PHP-mixed-$random_hash
  Content-Type: application/zip; name=geekology.zip
  Content-Transfer-Encoding: base64
  Content-Disposition: attachment

  $attachment
  --PHP-mixed-$random_hash--";

  echo @mail($to, $subject, $output, $headers);

?>

Read more...

How to check directory sizes on the command line

23 Jun 2009

The Unix "ls" command will display Permission and Ownership settings for directories, but not the total size of their contents:

$ ls -lh
total 0
drwxr-xr-x   6 willem  staff   204B Jun  7 00:47 Anime
drwxr-xr-x+  7 nobody  staff   238B Feb  4 11:17 CoD4 Vids
drwxr-xr-x  15 willem  staff   510B Oct 31  2008 Converted for iPod
drwxr-xr-x  23 willem  staff   782B May  8 10:36 Documentaries
drwxr-xr-x   7 willem  staff   238B Jun 11 00:31 Movies & Series
drwxr-xr-x  25 willem  staff   850B Oct 30  2008 TEDTalks - Favourites
drwxr-xr-x  26 willem  staff   884B May 20 01:38 Unconverted

Displaying directory sizes using "du"

To see the total size for directories, you should rather use the "du" command:

Read more...

How to gain access to a visitor's IP address in PHP

20 Jun 2009

PHP's HTTP_X_FORWARDED_FOR and REMOTE_ADDR server variables store the IP Addresses of a visitor's connection and any proxy server that their connection was forwarded through.

To use these details in your code, write a script similar to this:

<?php

  $addressForwarded = $_SERVER['HTTP_X_FORWARDED_FOR'];
  $addressRemote = $_SERVER['REMOTE_ADDR'];

  echo "Connection forwarded for: {$addressForwarded} " .
       "and originated from {$addressRemote}.";

?>

Read more...

How to recover your iPhone from Safe Mode

18 Jun 2009

Until recently I didn't know that Jailbroken iPhones had a Safe Mode for when SpringBoard crashes, but the other day my iPhone suddenly restarted and presented me with these screens:

When in Safe Mode certain functions are disabled, but you can easily restore your iPhone to normal Operational Mode by either:

Tapping the Restart button in the Safe Mode Notification Dialog

... or:

By holding down the Sleep / Wake Button for a few seconds, dragging your finger along the "slide to power off" slider, waiting until the iPhone turns off, then pressing the Sleep / Wake Button for a few seconds until it turns on again.

Read more...

How to enable remote access to a MySQL database server

16 Jun 2009

By default, remote access to the MySQL database service is disabled. If you need to enable remote access, follow the steps below:

Modify the MySQL configuration file

Log into the server via SSH if you don't have direct access to the machine (replacing USERNAME and SERVER-ADDRESS with your username and Server IP Address or Hostname):

ssh {USERNAME}@{SERVER-ADDRESS}

... then locate the MySQL configuration file:

mysql -? | grep ".cnf"

The above command will list configuration files in the order that they will be read, the file that you should edit will usually be located at "/etc/my.cnf".

Open the configuration file for editing:

Read more...

How to recover from Linux freezes with "Raising Skinny Elephants Is Utterly Boring"

04 Jun 2009

In the rare cases that a Linux machine freezes, it can usually be rebooted with the Ctrl-Alt-Backspace key combination. However, if this doesn’t work you can try raising the elephant:

To be able to use this functionality, your kernel needs to be compiled with the CONFIG_MAGIC_SYSRQ option on. If your kernel was compiled with this option, entering the following command on the command line should cause the same path to be echoed out:

ls /proc/sys/kernel/sysrq

A simple mnemonic to remember the combination of keys to raise the elephant is "Raising Skinny Elephants Is Utterly Boring" (RSEIUB). Hold down the left Alt and the SysRq (sometimes labelled "Print Screen") keys and press the following letters in this order, making sure that you give a few seconds pause between keystrokes:

Read more...

How to reuse the last specified parameter on the command line

03 Jun 2009

If you want to reuse the last parameter you specified for a command in a Bash shell, you can use the "!$" tag.

An example of where this would be useful is if you create a directory with a long path, then want to switch to it:

mkdir /home/willem/some_folder/another_folder/new_folder
cd !$

Read more...

How to configure a Vodafone 3G modem on Ubuntu Linux 9.04 (Jaunty Jackalope)

24 May 2009

In this example I'll use a Huawei E220 USB 3G Modem on a Vodacom prepaid account. To set up your 3G connection you can use the 3G modem drivers available on betavine.net for the majority of Linux distributions (you'll need the relevant usb-modeswitch and vodafone-mobile-connect files for your operating system and architecture).

For Ubuntu Linux the two drivers are Debian package files ("usb-modeswitch0.9.7i386.deb" and "vodafone-mobile-connect2.00.00-1all.deb"). Install the Modeswitch package first, then install Vodafone Mobile Connect by running these commands on the command line:

sudo dpkg -i usb-modeswitch_0.9.7_i386.deb
sudo dpkg -i vodafone-mobile-connect_2.00.00-1_all.deb

If you are notified of unresolved dependency problems after installing Vodafone Mobile Connect, correct them by running this command:

Read more...

How to get a free US iTunes Store account from anywhere in the world

22 May 2009

If you use iTunes, there are several benefits to getting an iTunes Store account, including:

  • Free singles
  • The ability to download album artwork
  • The ability to download iPad / iPhone / iPod Touch apps
  • The ability to get iTunes Genius results (recommendations of music you might like)

Creating an iTunes account normally requires you to enter your credit card details, but if you don't have a credit card (or you live in a country the iTunes Store doesn't support), you can use one of the methods below to get a free account.

Note that if you try to purchase anything that's not free using a free account, you will still be prompted for your credit card details.

Method 1 - Purchase a free iPad / iPhone / iPod Touch Application

To purchase a free app, open iTunes, click the "iTunes Store" item in the menubar on the left side of the application, click the "App Store" link on the left side of the page, find a free application and click on the "Get App" button.

When prompted for your Apple ID and Password, click on the "Create Account" button, then fill in the details iTunes requests (you'll need to fill in a real postal code for the area you select, so check online for valid postal codes). When you get to the Payment Details page you'll see that "None" has been added as an option.

Method 2 - iTunes Redeem Code

You should be able to find websites that offer iTunes Redeem Codes as part of promotions if you Google for them.

Once you have an iTunes Redeem Code you can create a free account by opening iTunes, clicking on the "iTunes Store" item in the menubar on the left side of the application, choosing your country at the bottom of the page, then clicking the "Redeem" link in the "Quick Links" section in the top right corner of the page.

Enter your Redeem Code when prompted for it, then click the "Redeem" button. When prompted for your Apple ID and Password, click the "Create Account" button, then fill in the rest of the details iTunes requests (you'll need to fill in a real postal code for the area you select, so check online for valid postal codes). When you get to the Payment Details page you'll see that "None" has been added as an option.

Read more...

How to search from the Mac OS X command line with Spotlight

20 May 2009

Mac OS X's Spotlight feature automatically indexes files and their metadata on your hard drive and any external drives while you use your Mac.

A simple Spotlight search can be performed by clicking the Spotlight icon in the top-right corner of your Mac's screen while a more advanced search (based on kind, date, name, contents, device make, album, artist, bit rate, city, codec, EXIF data, language, height, width, etc.) can be performed by using the Spotlight search box in the top-right corner of a Finder window.

These simple or advanced searches can also be performed on the command line by using the mdfind utility.

Read more...

How to use ModRewrite and .htaccess to add trailing slashes to all URIs and URLs

11 May 2009

Apache's Rewrite Module allows developers to define extensive URL Rewriting and Redirecting Conditions & Rules, one of which could be to add trailing slashes to Representational State Transfer (RESTful) URLs.

RESTful URLs are Uniform Resource Indicators (URIs) that are more user- and SEO-friendly than standard GET-based URIs. For example (GET vs. REST):

http://www.geekology.co.za/blog/article.php?id=1
http://www.geekology.co.za/blog/index.php/article/1

...or (GET vs. REST):

http://www.geekology.co.za/blog/article.php?slug=this-is-the-article-title
http://www.geekology.co.za/blog/index.php/article/this-is-the-article-title

To use URL Rewriting to add a trailing slash to all RESTful URIs, create a .htaccess file in your website's root folder (if it doesn't exist yet), open it, and add this content:

Read more...

iPod Touch, iPhone, and iPad firmware direct download locations

01 May 2009

If you need up jailbreak or unlock your iPod Touch / iPhone / iPad or reinstall your software, you'll need to download the latest device firmware bundles (.ipsw files) using one of the methods below.

You can let iTunes download the firmware but stop the process before it starts installing, then retrieve the IPSW (firmware) files from your "~/Library/iTunes/Device Support" folder. Alternatively, these two very useful websites will let you download most versions of the firmware (in addition to the firmware for other iPod models):

iClarified (iPod Touch)

iClarified (iPhone)

iClarified (iPad)

Felix Bruns' Website (iPod Touch, iPhone, and other iPod models)

If you're going to jailbreak or unlock your iPod Touch, iPhone or iPad the best software to use is PwnageTool. This package is developed by a group called the iPhone Dev Team, and most other software-based jailbreaking / unlocking systems use their methods and code core.

Read more...

How to mount a Samba (Windows) file share to a folder in Ubuntu Linux

17 Apr 2009

To mount a Samba (Windows) file share to a folder in Ubuntu Linux, you need to have Samba Filesystem Support installed. The easiest way to do this is via apt-get on the command line:

sudo apt-get install smbfs

After the installation has finished, create a directory that the Samba share will be mounted to (e.g. "windows_share" in the "/mnt" directory):

sudo mkdir /mnt/windows_share

Finally, use the mount command to mount the remote shared folder to your newly created directory (change the IP address, paths, username and password in the example below as needed):

sudo mount -t smbfs //10.0.0.100/shared_folder/
  /mnt/windows_share -o username=Guest,password=

To unmount the Samba share, use the umount command (change the path in the example below as needed):

sudo umount /media/windows_share

To automatically mount the Samba share when you boot up your computer, you'll need to edit your "/etc/fstab" file as detailed on this page on the Ubuntu Forums.

For more detailed usage information on the mount and umount commands as well as fstab, see their man pages:

man mount
man umount
man fstab

Read more...

How to check your internal and external IP addresses from the command line

15 Apr 2009

If your computer accesses the Internet via a local network connection, it will have an internal (LAN / WiFi) as well as an external (Internet) IP Address. If you need to reference either of these on a Unix machine, you can do so relatively easily from the command line.

Checking your internal IP address

To check the IP Address of your LAN / WiFi connection, ensure that Perl is installed, then run this command on the command line:

Read more...

How to enable Terminal's directory and file color highlighting in Mac OS X

13 Apr 2009

By default Mac OS X's Terminal application uses the Bash shell (Bourne Again SHell) but doesn't have directory and file color highlighting enabled to indicate resource types and permissions settings.

Enabling directory and file color highlighting requires that you open (or create) "~/.bash_profile" in your favourite text editor, add these contents:

Read more...

How to display MySQL CLI query output vertically

11 Apr 2009

The MySQL CLI (Command Line Interface) is a great tool to test queries and administrate remote (or local) databases.

Unless you have a large widescreen display or dual monitors, however, output from tables with a lot of columns break onto a new line, rendering the results unreadable.

For example, if you have a table called "location_cities" with a definition like this:

+---------------+--------------+------+-----+---------+
| FIELD         | Type         | NULL | KEY | DEFAULT |
+---------------+--------------+------+-----+---------+
| id            | varchar(255) | NO   | PRI |         |
| area_id       | varchar(255) | NO   | MUL |         |
| name          | varchar(255) | NO   |     |         |
| latitude      | varchar(100) | YES  |     | NULL    |
| longitude     | varchar(100) | YES  |     | NULL    |
| date_entered  | timestamp    | NO   |     |         |
| date_modified | timestamp    | YES  |     | NULL    |
+---------------+--------------+------+-----+---------+

... this query will render as follows:

Read more...

How to enable syntax highlighting and other options in vim

10 Mar 2009

Vim is a popular command line text editor with an interface that is based not on menus or icons but on commands given in a text user interface.

Unfortunately the vim that ships with Mac OS X 10.5.* (Leopard) doesn't have an optimized configuration file to allow for syntax highlighting, auto indentation, etc.

To fix this, open a new Terminal window and enter these commands to open vim's configuration file:

cd /usr/share/vim
sudo vim vimrc

Press the "i" key to switch vim to Insertion Mode, then enter these lines below the "set backspace=2" line:

set ai                  " auto indenting
set history=100         " keep 100 lines of history
set ruler               " show the cursor position
syntax on               " syntax highlighting
set hlsearch            " highlight the last searched term
filetype plugin on      " use the file type plugins

" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
\ if ! exists("g:leave_my_cursor_position_alone") |
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal g'\"" |
\ endif |
\ endif

Press the Escape key to take vim out of Insertion Mode, then press ":" (colon) followed by "x" to save the file and exit. Enter this command again:

sudo vim vimrc

... and you'll see that vim now automatically indents code, displays the cursor position, has syntax highlighting, etc.

Read more...

How to see the current Unix timestamp and other date formats on the command line

07 Mar 2009

The UNIX date command can show the current (or a future) date in several different formats. The command’s default output presents a full date string:

date

Sat Mar  7 07:25:51 SAST 2009

... but this output can be modified by specifying certain arguments.

To see the output in a different format:

date "+DATE: %Y-%m-%d%nTIME: %H:%M:%S"

DATE: 2009-03-07
TIME: 07:27:43

To see the last Friday of the month:

date -v1d -v+1m -v-1d -v-fri

Fri Mar 27 07:29:28 SAST 2009

To display the current UNIX Timestamp:

date +%s

1236403850

The date command has several other arguments which can be found by reviewing its man page:

man date

Read more...

How to use a Bash Script to split a CSV file into multiple files with headers

27 Feb 2009

A Bash Script implementing the Unix head, tail, split and cat commands can be used to split a large Comma Separated Values (CSV) or other text file into smaller chunks containing the original file’s header.

In this example, I have a "data.csv" file with the following content:

name,value
item1,20
item2,23
item3,22
item4,12
item5,65
item6,31
item7,43
item8,12
item9,43
item10,12
item11,11
item12,33
item13,33
item14,22
item15,75

Create a new script file (in this example I’ve named it "splitcsv.sh") containing the code below in the above mentioned file’s directory using a plain text editor such as nano, vim or TextEdit:

#!/bin/bash

# check if an input filename was passed as a command
# line argument:
if [ ! $# == 1 ]; then
  echo "Please specify the name of a file to split!"
  exit
fi

# create a directory to store the output:
mkdir output

# create a temporary file containing the header without
# the content:
head -n 1 $1 > header.csv

# create a temporary file containing the content without
# the header:
tail +2 $1 > content.csv

# split the content file into multiple files of 5 lines each:
split -l 5 content.csv output/data_

# loop through the new split files, adding the header
# and a '.csv' extension:
for f in output/*; do cat header.csv $f > $f.csv; rm $f; done;

# remove the temporary files:
rm header.csv
rm content.csv

Browse to the directory containing the script with a Terminal window and enter (replacing "scriptfile" with the name you gave the script file and "datafile" with your CSV file's name):

sh ./{scriptfile} {datafile}

The split command can also break apart files based on a number of bytes or a specific pattern. For more information, see its man page:

man split

Read more...

How to understand and modify Unix file permissions

25 Feb 2009

The Unix "ls -l" command will present a directory listing similar to the one below:

Willem-MacBook-Pro:~ willem$ ls -lh
total 0
drwx------+  39 willem  staff   1.3K Feb 25 15:31 Desktop
drwxr-xr-x   32 willem  staff   1.1K Nov 29 20:55 Development
drwx------+  16 willem  staff   544B Feb 24 16:59 Documents
drwx------+ 168 willem  staff   5.6K Feb 25 15:16 Downloads
drwxrwxrwx@  25 willem  staff   850B Feb 25 13:06 Dropbox
drwx------+  57 willem  staff   1.9K Feb 10 10:23 Library
drwx------+  13 willem  staff   442B Feb 25 11:35 Movies
drwx------+  10 willem  staff   340B Dec  1 13:55 Music
drwx------+  19 willem  staff   646B Feb 22 21:46 Pictures
drwxr-xr-x+   8 willem  staff   272B Feb  7 11:36 Public
drwxr-xr-x   10 willem  staff   340B Feb 12 09:40 Scripts
drwxr-xr-x+  56 willem  staff   1.9K Feb 25 13:31 Sites
drwxr-xr-x    8 willem  staff   272B Nov 12 23:32 Woopra
Willem-MacBook-Pro:~ willem$

In this listing the columns indicate (from left to right): permissions, subitem count, owner, group, size on disk, date modified and item name.

The permissions column will always display a string in the format "rwxrwxrwx" with an optional leading "d" to indicate that the item is a directory. (Some operating systems also add a trailing '+' or '@' to indicate associated ACLs or extended attributes. ACLs can be displayed with 'ls -le' and modified with 'chmod -a').

Explanation of "rwx" permissions

The nine "rwxrwxrwx" characters are divided into three sets to indicate the permissions for the owner of the item, the group that owner belongs to, and any other users on the system:

Read more...

How to define user crontabs (scheduled tasks) on Mac OS X and Linux

22 Feb 2009

Unix systems' cron service runs scheduled tasks at dates and times defined by users in crontab files. A user can check their crontab entries from the command line by entering:

crontab -l

... or check another user's crontab by entering:

sudo crontab -u {username} -l

Crontab entries are defined as follows:

{minute (*-0-59)} {hour (*-0-23)} {monthday (*-1-31)}
  {month (*-1-12)} {weekday (*-0-7)} {path} {script}

For example, to execute a script on the hour on Mondays, you would use:

Read more...

How to change the default MySQL root (or other user) password

20 May 2009

In fresh MySQL installations, the default root password is set to "" (nothing). While this might be acceptable on a development machine, it's a huge security risk on production servers.

To set an initial MySQL root password from the command line

Open a new Terminal window and enter (replacing "{newpassword}" with the new password):

mysqladmin -u root password {newpassword}

To change the password for any user account (including root) that already has a password

Open a new Terminal window and enter the following line, then enter the user's current password when prompted:

Read more...

The performance of popular web browsers on the Acid3 test

19 Feb 2009

The Acid3 test was designed by the Web Standards Project to test browser compatibility with DOM and JavaScript web standards.

When successful, the Acid3 test displays a gradually increasing percentage counter with colored rectangles in the background. The percentage displayed is based on the number of sub-tests passed. In addition to these the browser also has to render the page exactly like the reference page as rendered in the same browser.

The tests below were performed with the latest versions of each browser on a MacBook 2.0GHz with 2GB of RAM running Mac OS X 10.5.* (Leopard).

The Internet Explorer 7 test was run on the same machine in a fresh Sun VirtualBox 2.1.0 Windows XP Service Pack 3 Professional Edition virtual machine. The fact that the browser was running in a virtual machine and not natively might have impacted its speed, but would not have had any effect on its ability to render the page correctly.

Webkit r34604 (100/100)

Read more...

How to find and kill frozen processes in Mac OS X and on the command line

18 Feb 2009

When applications freeze in Mac OS X, they can be forcefully closed by using one of these "Force Quit" methods:

  • Hold down the ⌥ (Option) key, right click on the application’s icon in the Dock, and choose ‘Force Quit‘.
  • Click on the Apple logo in the top left corner of the screen and choose "Force Quit", or press ⌘-⌥-⎋ (Command-Option-Escape), then select the application from the list and click the ‘Force Quit‘ button.
  • Open Activity Monitor from your "/Applications/Utilities/" folder, click on the application in the list of processes, then click the "Quit Process" button in the top left corner of the Activity Monitor window.

If none of these succeed in terminating the application, you’ll need to use Unix's kill command. Open a new Terminal window and enter:

ps aux | grep "{process name}"

Read more...

How to test SMTP servers on the command line

14 Feb 2009

Using the telnet utility, it’s possible to directly connect to and test SMTP servers from the command line.

Encoding authentication details in base64

If your SMTP server requires authentication, you’ll need to use a base64-encoded version of your username and password strings. These can be generated by using an online base64 encoder, using PHP’s ‘base64_encode()‘ function:

<?php

echo base64_encode('some_text_to_encode');

?>

... piping plain text into the command line ‘base64‘ utility (if you’re on a Macintosh, you can install base64 with MacPorts):

echo 'some_text_to_encode' | base64

... or by piping plain text into a perl script:

Read more...

How to launch the Mac OS X screen saver from the command line with an AppleScript

13 Feb 2009

Mac OS X has a built-in command line utility named "osascript" that can read and execute AppleScript files or commands passed as arguments. By using osascript to launch the Screen Saver engine, you can lock your screen from the command line:

osascript -e 'tell application id "com.apple.
  ScreenSaver.Engine" to launch'

To shorten this command, you can save it as a bash script (named "launchss.sh" in this example) in your Home folder:

#!/bin/bash

osascript -e 'tell application id "com.apple.
  ScreenSaver.Engine" to launch'

... and run it by entering:

sh ~/launchss.sh

Alternatively, you can make the script behave like an application by saving it with a ".command" file extension instead of ".sh". To execute it, double-click it in the Finder or drag it to your Dock and launch it from there.

More details about osascript's usage can be found in its man page:

man osascript

Read more...

How to change the OS X network location from the command line or an AppleScript application

12 Feb 2009

In Mac OS X Leopard, Network Locations are defined in System Preferences->Network, and allow users to assign their DHCP, IP, Subnet, Router, DNS, WINS, etc. settings to preconfigured sets. These sets can be activated by simply selecting a different Network Location (e.g. "Home", "Office", "Coffee Shop") on the Network Preferences panel.

The scselect command line utility can be used to list all Network Locations on an OS X system by opening Terminal (from your "/Applications/Utilities" folder), and entering:

scselect

It's also possible to switch your Network Location to a different preconfigured set by entering:

Read more...

How to extract and sort email addresses from text files with Automator on Mac OS X

10 Feb 2009

Automator (Mac OS X's drag & drop batch script-building tool) can be used to create applications that streamline repetitive tasks without any knowledge of programming.

Follow these steps to build an Automator workflow that will search all text files in a specified folder for email addresses, sort these email addresses alphabetically, and remove any duplicates:

Launch Automator from your "/Applications" folder and choose to create a "Custom" workflow.

Read more...

How to reset Mac OS X's Spotlight data cache and re-index your hard drive

09 Feb 2009

Apple's Spotlight technology automatically indexes all content on an OS X system to allow for instant search results based on documents (including their content), pictures, music, applications, emails, calendar entries, system preferences, bookmarks, web history, etc.

Occasionally Spotlight's metadata stores can become corrupted and cause searches to take much longer than necessary. To reset the data cache for your Mac's hard drive, open a Terminal window and enter this command:

sudo mdutil -E /

To force Spotlight to immediately start re-indexing your hard drive (this might take a few hours and is probably best left to run overnight), enter this command:

sudo mdutil -i on /

Further information on mdutil's usage can be found on its man page by entering this command:

man mdutil

Read more...

Startup keyboard shortcuts on Apple Macintosh Intel computers

08 Feb 2009

Intel-based Apple Macintosh computers have several keyboard shortcuts that can be used during the boot process to boot from a different drive, eject a disc, enter Target Disk mode, etc.

After you've turned your Mac on, wait for the Apple logo to appear then hold down one of the key combinations below until the rotating "loading" animation appears below the Apple logo:

X:
Force Mac OS X Startup.

Read more...

How to reset a Mac's PRAM and NVRAM

07 Feb 2009

The information stored in a Mac’s PRAM (Parameter Random Access Memory) and NVRAM (Non-Volatile Random Access Memory) include:

  • Alarm clock setting
  • Autokey rate
  • Display and video settings
  • Disk cache
  • DVD region setting (resetting your PRAM doesn’t change your DVD region)
  • Mouse scaling
  • Recent kernel panic information
  • Serial Port Configuration and Port Definition
  • Speaker volume
  • Startup disk
  • Virtual memory
  • etc.

Resetting the PRAM and NVRAM might solve problems with the above-mentioned hardware (e.g. an iSight camera that is constantly turned on), but if the problems persist you should take the machine to an authorised repair shop.

To reset the PRAM and NVRAM on an Intel-based Mac:

Read more...

How to take screenshots from the command line on Mac OS X

05 Feb 2009

In addition to the default screenshot shortcut keys provided by Mac OS X, the built-in screencapture command line utility allows for a variety of screenshot options:

Capture the screen to the clipboard:

screencapture -c

Capture a selection or window (press spacebar to switch):

screencapture -i ~/Desktop/screenshot.png

Capture a window without its shadow (press spacebar after entering the command to enable Window Selection mode):

screencapture -io ~/Desktop/screenshot.png

Capture the screen and open the image in a new Mail message:

Read more...

"Variable variables" and array syntax ambiguity in PHP

04 Feb 2009

In PHP it's possible to define variable variables, variables with names that are set and used dynamically.

Normal variables are set with statements like:

<?php

  $fruit = 'apple';

?>

Variable variables are set by using two dollar signs in front of a normal variable's name:

<?php

  $fruit = 'apple';
  $$fruit = 'red';

?>

This results in two variables being defined: $fruit with the value 'apple', and $apple with the value 'red', which means that these two echo statements will produce the same results:

Read more...

How to extract audio, video, and subtitle tracks from Matroska (MKV) video files

03 Feb 2009

mkvtoolnix is a set of cross-platform command line tools (mkvmerge, mkvextract, and mkvinfo) for extracting audio, video and subtitle tracks from Matroska Video (.mkv) files. After extracting these tracks you can recombine them into an AVI container with subtitles embedded using a tool such as ffmpegX (a visual interface to mencoder available for OS X only) or mencoder (Linux).

mkvtoolnix can be downloaded here, or installed via MacPorts.

First, use mkvmerge to list the MKV file's contents:

mkvmerge -i MovieFile.mkv

You'll see a listing similar to this:

File 'MovieFile.mkv': container: Matroska
Track ID 1: subtitles (S_TEXT/ASS)
Track ID 2: audio (A_MPEG/L3)
Track ID 3: video (V_MPEG4/ISO/AVC)

Next, use mkvextract to extract certain tracks / attachments based on the output from the above command:

mkvextract tracks MovieFile.mkv 1:thesubtitles.srt
  2:theaudio.mp3 3:thevideo.mp4

mkvextract will extract the tracks you listed and save them to the specified filenames.

Read more...

How to uninstall Google Software Update on Mac OS X

02 Feb 2009

After trying out the Macintosh versions of Picasa and Google Quick Search Box, the Google Software Updater keeps popping up even after I uninstalled both applications.

Usually uninstalling a Mac application is as simple as dragging the relevant app file ('Picasa.app' and 'Quick Search Box.app') into the Trash, but in this case some extra work was needed:

According to Google's support pages, uninstalling Google Software Update involves running one of the commands mentioned below on the command line:

Uninstall Google Software Update for the current user only:

sudo ~/Library/Google/GoogleSoftwareUpdate/
  GoogleSoftwareUpdate.bundle/Contents/Resources/
  GoogleSoftwareUpdateAgent.app/Contents/Resources/
  install.py --uninstall

Uninstall Google Software Update for all users:

sudo /Library/Google/GoogleSoftwareUpdate/
  GoogleSoftwareUpdate.bundle/Contents/Resources/
  GoogleSoftwareUpdateAgent.app/Contents/Resources/
  install.py --uninstall

Read more...

How to compile and install command line tools on Mac OS X with MacPorts

01 Feb 2009

The MacPorts Project provides software installation, updating, and removal functionality to OS X similar to Linux' apt-get or yum. The Project is currently tracking more than 5000 packages including software such as subversion, wget, apache2, php5, etc.

To install the software, first install Apple's Xcode Developer Tools (available on your Mac OS X installation disc) and the X11 windowing environment (included by default in 10.5.* "Leopard", but available on your Mac OS X installation discs for 10.4.* "Tiger" and 10.3.* "Panther"), then download the MacPorts DMG (disk image), mount the disk image and run the installation package.

After the installation has completed, reopen any Terminal windows to reload PATH settings updated by the installation, then run the following command to update the MacPorts package cache:

sudo port -v selfupdate

Detailed usage instructions can be found in the MacPorts Guide, but the basic commands are:

Install a package:

Read more...

How to take screenshots on the iPhone, iPad, and in Mac OS X

29 Jan 2009

On the iPhone / iPad

Taking screenshots on an iPhone running software 2.* (or an iPad) is easy: Simply press the Sleep / Wake and Home buttons simultaneously to save an image of the screen to your Photo Library.

To download the images from your iPhone, you can use iPhoto, Image Capture, or a similar photo management application. Alternatively, you can email them to yourself.

On the Mac

To take screenshots in Mac OS X you can use the "Grab" application in your "/Applications/Utilities" folder, the built-in keyboard shortcuts, or the command line screencapture utility.

Like Grab, the screencapture command line utility gives you the option of taking Selection, Window, Screen, or Timed screenshots, but it expands upon Grab's functionality somewhat by letting you specify a timer interval, mute the screen capture sound effect, specify where the output image should be saved, etc.

Read more...

How to perform segmented downloads on the command line with "aria2c"

26 Jan 2009

aria2 is a Linux / Mac OS X / Windows command line utility that can download files concurrently from multiple HTTP(S) / FTP / BitTorrent sources. While the utility is running, each downloading file is adaptively split into multiple segments with varying segment sizes based on server response times.

It continually trims out slow servers and favors faster ones, and if a file’s sources contain both HTTP(S) / FTP and BitTorrent URIs, content downloaded through HTTP(S) / FTP will be uploaded to the BitTorrent swarm.

Synopsis:

aria2c [OPTIONS] [URL | TORRENT_FILE | METALINK_FILE]…

Usage examples

Download a file via HTTP with the default settings:

Read more...

South African cellphone network data access details

23 Jan 2009

If you occasionally need to configure Internet access for people who want to tether their cellphone to their laptop on a South African network, you might want to keep this list of connection settings for South African mobile providers close by:

Cell-C
APN: internet
Username: guest
Password: guest
DNS: 196.7.0.138, 196.7.142.132
SMTP: -

MTN
APN: internet
Username: guest
Password: guest
DNS: 196.11.240.241
SMTP: mail.mtn.co.za

Vodacom
APN: internet
Username: guest
Password: guest
DNS: 196.207.40.165, 196.43.46.190
SMTP: smtp.vodamail.co.za

Vodacom (VPN)
APN: internetvpn
Username: guest
Password: guest
DNS: 196.207.40.165, 196.43.46.190
SMTP: smtp.vodamail.co.za

Virgin Mobile
APN: vdata
Username: guest
Password: guest
DNS: 196.7.0.138, 196.7.142.132
SMTP: mail.cmobile.co.za

Read more...

Copyright © Geekology 2012. All Rights Reserved.

Built by Code Like Clockwork.