PHP – switch statement vs. function dispatching

When you start having too many cases in your switch statement, it might be worth looking into using a function lookup. This is possible in all languages where functions are first class citizens…

<?php
$post = "hello";
$info = "3.1415";
//-----------------------------------------------------------
// Version 1 - using a switch statement
//-----------------------------------------------------------

switch ($post) {
    case "hey": {
        print("I've been called with $info\n");
        break;
    }

    case "there": {
        print("I've been called with $info\n");
        break;
    }

    case "hello": {
        print("I've been called with $info\n");
        break;
    }

    default: {
        print("shouldn't have gotten here\n");
    }
}

//-----------------------------------------------------------
// version 2 - same thing using a dictionary of functions
//-----------------------------------------------------------

$funcArray = Array(
    "hey" => function ($param) {
        print("I've been called with $param\n");
    },
    "there" => function ($param) {
        print("I've been called with $param\n");
    },
    "hello" => function ($param) {
        print("I've been called with $param\n");
    }
);

// The data driven invocation of the correct function:

if (isset($funcArray[$post])) {
    // Invoke the relevant function if the string is found
    $funcArray[$post]($info);
}
else {
    print("shouldn't have gotten here\n");
}
?>

Virtual Box – Shared folders on Ubuntu Guest

Well, the first thing to make sure is that Guest Additions are correctly installed. For example, on Ubuntu 16.04 guest on VirtualBox 5.0.32 r112930 I received a message that the kernel headers were not found (even though they did exist). This was fixed with:
sudo apt-get install dkms

Next problem was constantly receiving a protocol error when trying to mount the host’s directory that I named hostfs in the VirtualBox shared folders dialog. This however, was my fault – the correct syntax to do this is:

sudo mount -t vboxsf -o uid=1000,gid=1000 <name-given-in-virtualbox-dialog> <empty-directory-path-in-guest>

Creating an iOS push certificate PEM file

in the Apple developer console:

  • Create a development iOS certificate of type “APNs Development iOS” – this is a certificate used to connect between your entity that sends the push (e.g a php script on a server or some other app) and the APN development (sandbox) gateway that delivers the push to the remove iOS device.

Creating a APMs push certificate is done by following the steps in adding a certificate in the development console, which includes selecting the certificate type, selecting the App ID it should be associated with (e.g. com.naturongo.mypush) downloading the certificate request, double-clicking the request file and using the KeyChain Access application to fill out the request, uploading the resulting file and the signed certificate will be generated.

  • Click the download button for this certificate – this will download a .cer file to your local drive

  • Double click this .cer file – this should add it to your keychain via the Keychain Access application

  • Once you’ve identified it in your Keychain Access application, ctrl-click it and select the export option.

  • Export it to a .p12 file. You will be requested for a password to be used for accessing the private key in this file – lets suppose the password is “pass”

  • Once you have the .p12 file on your drive – lets call it cert_push_dev.p12 then convert it to a pem file via:
    openssl pkcs12 -in APN_push_dev.p12 -out APN_push_dev.pem -nodes -clcerts

  • The assumption is that at this point you have the following:
  1. An APN token from an iOS application that registered with an APN Server
  2. The pem file created in the previous step
  3. The password to this pem file

    Given all this, you can now use the following php script to send a push notification to the remote iOS device associated with the APN token:

    <?php
    
    // This is the APN token received by the iOS device when registering with the APN server
    $deviceToken = "aba3213b06b13d33b881058bfe8c88478a1d1d07fbed6d3303afc904fe874e7d";
    
    $message = 'You have recieved new notification!';
    
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'APN_push_dev.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', 'pass');
    
    // Open a connection to the APNS server
    //$APNS = 'ssl://gateway.push.apple.com:2195'; // production server
    $APNS = 'ssl://gateway.sandbox.push.apple.com:2195'; // development
    $fp = stream_socket_client( $APNS, $err, $errstr, 60,
                                STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
    
    if (!$fp) {
        exit("Failed to connect: $err $errstr" . PHP_EOL);
    }
    
    echo 'Connected to APNS' . PHP_EOL;
    
    // Create the payload body
    $body['aps'] = array(
        'alert' => $message,
        'sound' => 'default',
        'data' => 'test data'
    );
    
    // Encode the payload as JSON
    $payload = json_encode($body);
    
    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
    
    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));
    //echo "send result=$resultn";
    if (!$result) {
        echo 'Message not delivered' . PHP_EOL;
    }
    else {
        echo 'Message successfully delivered' . PHP_EOL;
    }
    
    // Close the connection to the server
    fclose($fp);
    ?>

If the above file is named push_ios.php then
Sending a push notification can now be done by running php from the command line:
php -f push_ios.php

Quick ReactJS native environment setup on OS/X

First, install XCode
Also install brew (brew.sh)

Then, from the command line

brew install node
brew install watchman
npm install -g react-native-cli

to generate a new project, from the command line

react-native init myproj

The above will create a basic React native template (it can take a few minutes, lots of megabytes involved…). When complete it will create a folder named myproj containing the following:

index.ios.js (main file for the application javascript/JSX code for iOS devices)
index.androis.js (main file for the application javascript/JSX code for Android devices)
ios – (directory containing XCode project and related files)
android – (directory containing gradle project and related files)
node_modules – modules used by the application

You might want to look at the official React native tutorial

To quickly run an iOS app, open the XCode project (in this case myproj.xcodeproj) in the ios directory. After it completes indexing and doing it’s thing, run it (click the play button in XCode). This will start the react packager, and launch the basic compiled application in the simulator. The packager enables you to make changes in the code and immediately view them in the react application by pressing +R. You can check this very cool feature of React native development by making a small change in index.ios.js , saving, switching to the simulator running the application and pressing +R

Should you add new resources (e.g source code files) you’ll need to relaunch the react packager. You do this from the command line in the project directory by:

npm start

Ubuntu 14.04 not seeing Wifi Networks

I installed a fresh Ubuntu 14.04 on an old MacAir (how to do that is explained here) and took me hours to get it to see the Wifi networks. There were many suggestions on many sites but the solution that finally worked for me was Hadaka’s answer from ubuntuforums

Just for information, check your pci id via

lspci -n | grep 0280

Then some cleaning up

sudo apt-get autoremove
sudo apt-get remove --purge bcmwl-kernel-source  #for good measure
sudo apt-get remove --purge b43-fwcutter firmware-b43-installer

sudo rm /var/lib/apt/lists/*
sudo rm /var/lib/dpkg/lock
sudo rm /var/cache/apt/archives/lock
sudo dpkg --configure -a

sudo apt-get update # I didn't do this as I didn't have a network

Now the important part is:

sudo apt-get install linux-firmware-nonfree

however, as I didn’t have a network I downloaded linux-firmware-nonfree_1.14ubuntu1_all.deb to a USB stick (you might want to get a newer version) from here to a connected computer and then

sudo dpkg -i linux-firmware-nonfree_1.14ubuntu1_all.deb

and then

sudo modprobe b43

Finally, rebooted and was able to see and connect to WiFi networks

Cordova – update all plugins in project

A quick hack to update all the Cordova plugins used in a Cordova project. Next hack will be updating all Cordova platforms…

From the Cordova project run the following (unix shell required):

cordova plugins | grep -Eo '^[^ ]+' | while read line
do
    echo "cordova plugin remove $line"
    echo "cordova plugin add $line"
done

Generating call graphs with Doxygen

Obviously you should first download and install Doxygen

Next, you should download and install Graphviz which will install the dot tool

in a nutshell, you create the documentation by running:

doxygen my_conf_file

Where my_conf_file contains all the required parameters for the generated documentation. If you use the doxygen wizard from the UI, a configuration file will be generated with some default parameters, however you need to change the following parameters in the generated configuration file if you want caller and/or called function graphs to be generated:

HAVE_DOT               = YES
EXTRACT_ALL            = YES
EXTRACT_STATIC         = YES
CALL_GRAPH             = YES
CALLER_GRAPH           = YES
MAX_DOT_GRAPH_DEPTH    = 10

Note that if you use the above parameters on a non-trivial code base then the documentation generation might take a long time. Read the doxygen documentation to better understand the implications.