newspaint

Documenting Problems That Were Difficult To Find The Answer To

Monthly Archives: March 2013

How to Upload a File over SSH Using Node.JS

The pure-JavaScript SSH2 Node.JS library available at https://github.com/mscdex/ssh2 allows a variety of SSH protocol client operations to be performed within a Node.JS script.

Specifically I wanted to know how to upload a file. Essentially, after creating a SSH connection to a server, it is a matter of opening a read stream from the local file system and opening a write stream to the SSH connection and then piping the two together.

The example code may provide illustration:

var fs = require('fs');
var ssh2 = require('/usr/local/node/node_modules/ssh2');

var conn = new ssh2();

conn.on(
    'connect',
    function () {
        console.log( "- connected" );
    }
);

conn.on(
    'ready',
    function () {
        console.log( "- ready" );

        conn.sftp(
            function (err, sftp) {
                if ( err ) {
                    console.log( "Error, problem starting SFTP: %s", err );
                    process.exit( 2 );
                }

                console.log( "- SFTP started" );

                // upload file
                var readStream = fs.createReadStream( "/proc/meminfo" );
                var writeStream = sftp.createWriteStream( "/tmp/meminfo.txt" );

                // what to do when transfer finishes
                writeStream.on(
                    'close',
                    function () {
                        console.log( "- file transferred" );
                        sftp.end();
                        process.exit( 0 );
                    }
                );

                // initiate transfer of file
                readStream.pipe( writeStream );
            }
        );
    }
);

conn.on(
    'error',
    function (err) {
        console.log( "- connection error: %s", err );
        process.exit( 1 );
    }
);

conn.on(
    'end',
    function () {
        process.exit( 0 );
    }
);

conn.connect(
    {
        "host": "10.0.0.1",
        "port": 22,
        "username": "root",
        "privateKey": "/home/root/.ssh/id_root"
    }
);

Beware JavaScript parseInt and Leading Zeros

I had some JavaScript code for breaking apart a timestamp (e.g. 11:07) into hours (11) and minutes (07).

function minutes_past_midnight( timestring ) {
  var result = /(\d+):(\d+)/.exec( timestring );
  if ( result == null )
    return null;

  var hours = parseInt( result[1] );
  var minutes = parseInt( result[2] );

  return( (hours * 60) + minutes );
}

But this function failed to correctly calculate when minutes were 08 or 09. That’s because parseInt, by default, treats numbers leading with zero as octal.

To fix this I changed my parseInt call to specify a radix parameter to force it to interpret in base-10.

  var hours = parseInt( result[1], 10 );
  var minutes = parseInt( result[2], 10 );

This strips out (skips) a leading zero in the hours and minutes so parseInt() will not see any leading zeros.

GIMP Crashes When Run On A Non-32-Bit-Per-Pixel Display

I had remote desktop’d into my Windows 7 PC and trying to start up the graphical editing program GIMP v2.8.4 when I saw the following error window:

GIMP crash notification

GIMP crash notification

This message read (from Microsoft Visual C++ Runtime Library):

This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.

The cause? GIMP doesn’t like being run on any display with less than 32 bits per pixel.

The problem was that, by default, rdesktop on Linux uses a lower quantisation of pixels. To fix it add the -a 32 option to your rdesktop command line, e.g.:

rdesktop
  10.0.0.9      # host to connect to
  -a 32         # ensure 32 bits per pixel to be displayed
  -g 1200x1024  # make the desktop window 1200 wide by 1024 deep
  -5            # use protocol version 5

How to Click on a Div or Span Using PhantomJS

What is PhantomJS?

PhantomJS is the V8 javascript engine combined with some JS (like Node.JS) to make a headless browser that is extremely useful for testing.

One of the best features is the ability to output the virtual display at any time to a PNG graphic file.

The Problem

I was struggling with how to click on a div or span element using PhantomJS.

Other elements could be clicked on by code not unlike the following (from imagebin.js included in the examples provided with the PhantomJS distribution):

page.open("http://imagebin.org/index.php?page=add", function () {
    page.evaluate( function () {
        document.querySelector('input[name=nickname]').value = 'phantom';
        document.querySelector('input[name=disclaimer_agree]').click()
        document.querySelector('form').submit();
    });
});

The problem is that the element returned by the document.querySelector() function for a div or span does not have a click() method.

The Solution

The solution was found this blog post and the following example should make this clear:

page.evaluate( function() {
    // find element to send click to
    var element = document.querySelector( 'span.control.critical.closer' );

    // create a mouse click event
    var event = document.createEvent( 'MouseEvents' );
    event.initMouseEvent( 'click', true, true, window, 1, 0, 0 );

    // send click to element
    element.dispatchEvent( event );
});

You might ask where I got “span.control.critical.closer” from. Well I use Google Chrome and manually load up the web page with the element I want to click. Then I click on the menu and select tools -> developer tools (alternatively press shift+ctrl+I). Then I click on the magnifying glass icon on the bottom of the screen and then click on the div or span element I want to click – and copy down the name.

Example Usage

I would use code like the following:

function mouseclick( element ) {
    // create a mouse click event
    var event = document.createEvent( 'MouseEvents' );
    event.initMouseEvent( 'click', true, true, window, 1, 0, 0 );

    // send click to element
    element.dispatchEvent( event );
}

function handle_page( page ) {
    page.evaluate(
        function( mouseclick_fn ) {
            var element = document.querySelector( "input#payConf" );
            mouseclick_fn( element );
        },
        mouseclick
    );

    window.setTimeout(
        function () {
            handle_click_reaction( page );
        },
        5000 // give page 5 seconds to process click
    );
}

Important!

Many users new to PhantomJS seem oblivious to the need to wait some time to allow the virtual browser to do whatever action the click intended to do. After you dispatch your mouse event you will either want to call window.setTimeout or implement a waitFor() type function (you can find such a function elsewhere on this blog).

If you expect to get results from your click instantly you will most likely be disappointed!

The Disadvantages of Apartment Living

Sydney Apartment Block

Sydney Apartment Block

Apartments. They are widely marketed as a preferable alternative to the traditional house and garden. And there are many advantages. But the reality is there are many, many disadvantages, too. The disadvantages will be the primary focus of this article.

Advantages of Apartment Living

Let’s start with the advantages of apartment living to keep the article, to some extent, balanced.

Firstly many apartments are quite modern being a modern phenomena in many places. It is quite appealing to be living in a new place with fresh paint and new appliances.

Because apartment blocks can be quite densely populated they can often afford to be positioned near amenities such as public transport or shopping centres.

Disadvantages

Noise

Apartment blocks are noisy. You cannot escape this. Ever. Why? Because you will always get a neighbour, either upstairs, or downstairs, or to your left, or to your right, that has their powerful sub-woofer pumping away, or does the vacuuming or washing at 11pm at night, or has super-noisy coitus.

Modern apartments have thick walls – and even concrete floors – but they are not always thick enough – especially for modern powerful sub-woofers.

Older apartments or maisonettes – as are popular in overcrowded London – have notoriously thin wooden floors and you can hear everything going on below and above.

Garbage

In the UK, at least, unwanted material can be separated into recycling and garbage. In an individual household that is not really a problem. But in an apartment block you are typically given one large garbage bin and one large recycling bin for the entire block.

This shouldn’t be a problem: however apartment blocks are often full of renters – many of whom are from cultures somewhat incompatible with the local. These people flat don’t understand or care about the rules for recycling that are plastered all over the bin. They throw dirty nappies, plastic bags, and other unrecyclable items into the recycling bin.

And then the council refuses to empty the overflowing garbage tip the recycling bin has become. And the council then writes to all the apartment residents blaming them for failing to obey the recycling rules.

Apartment blocks allow a level of anonymity when it comes to garbage and this lack of accountability means everybody in the block suffers.

Parking and Access

If your apartment block is gated you can expect to be harassed by people you never met pressing your buzzer hoping you’ll let them in. Tradesmen will just press any old button in an attempt to turn up for an appointment for someone else.

Often you will have an allocated space. But you can have fun dealing with a neighbour that parks badly leaving you with little room in your own space.

In the UK one has to watch out for apartment blocks that have no visitor parking. Expecting your friends to pay for parking nearby? Doesn’t seem fair, now, does it.

Quality with Age

Some apartment blocks are built very poorly. I had experience living in a Sydney apartment block that was a 30 story tower. I was on the 6th floor but, at only 7 years old, had cracks in the concrete walls and the floor was sloping. In Australia, especially, one must be vary careful with build quality as many large apartment-makers in that country have a reputation for poor quality.

Very Basic Introduction to VOIP

I was recently overseas and wanted a cheap way of making phone calls internationally while appearing as if I was still home. Now a mobile phone lets you do this because you retain your number no matter where you are in the world – but when you’re paying £1.50 per minute to make and receive calls it is time to look at other options.

Voice over IP is a service provided by many companies. One such company I signed up with was Voipfone but I’ve got friends that use PennyTel in Australia.

I pay a small fee, £2/month, to “hire” a local number in the town of my choice in the UK. Then I run a VoIP client on my mobile phone which logs into my SIP account in the UK and when I make or receive phone calls they are transmitted over the Internet to the UK where my Voipfone company then turns them into normal phone calls that go through the local phone provider.

Here is a rough diagram of the operation:

Calls go over the Internet to the SIP provider that then turns them into normal phone calls

Calls go over the Internet to the SIP provider that then turns them into normal phone calls

The advantage of a VoIP account is that you can have multiple phones registered on that SIP account. One could be at home. The other could be on your mobile phone (as a VoIP or SIP app). Then when somebody dials your ordinary phone number your VoIP provider then sends a ringing signal to all your logged in phones until one of you picks up.

Changing the Time on the Panasonic Air-Conditioner Remote Control

This is for a remote control from a brand new Panasonic air conditioning wall unit installed in March 2013 in Australia.

Here is a picture of the remote control:

Panasonic Air Conditioner Remote Control

Panasonic Air Conditioner Remote Control

To set the time press the “clock” button at the centre of the bottom of the control (see the position of the finger in the following picture):

Set the Time by Pressing the Clock Button

Set the Time by Pressing the Clock Button

The time should be slowly blinking on the control after pressing the clock button. Now you can press the up and down arrows to set the time as desired (see the position of the finger in the next picture):

Press the Up and Down Arrows to Set The Time

Press the Up and Down Arrows to Set The Time

When you are finished press the “clock” button once more and the time should stop flashing. Now the time on the control is set!

Sydney and Melbourne Domestic Airports Have Free Wifi

Sydney Airport

Well at least from the Jetstar/Virgin terminal. As can be seen from the selection menu on my mobile phone:

Choose FREE WIFI by SYD

Choose FREE WIFI by SYD

Select “FREE WIFI by Syd” and the first time you try and browse using a web browser you’ll be given a menu asking for your e-mail address (though you can give it any address you like) and provide your age (over or under 18) and gender (male or female).

Once you click to proceed you’ll be shown another page on which you click “proceed” and then you’ve got access!

By default it takes you to http://www.sydneyairport.com.au/ which is useful because you can look up departure and arrival times.

Melbourne Airport

Select “MELAIR FREE” as evidenced by the mobile phone:

Select MELAIR FREE

Select MELAIR FREE

The first web page you view will be a HTTPS with an invalid certificate so you will just have to click “continue”:

Continue when warned about an invalid HTTPS certificate

Continue when warned about an invalid HTTPS certificate

Then you will be served a web page that requires you to accept the terms and conditions.

Accept the Terms and Conditions

Accept the Terms and Conditions

By default it takes you to http://melbourneairport.com.au/ but you can access any site you want.