Wednesday, 3 December 2014

Auxiliary Input for Toyota Caldina 2003

It took a while to figure out how to get this working so I thought I'd write it up in case it saves anyone else the trouble.

My car is a Toyota Caldina 2003, and it has a Multi AV Station II that looks like this:





To get auxiliary input for both sound and video, you need one of these cables:


I bought mine off Ebay from here where it was listed as a "Audio Video cable for Toyota car audio parts Blue 6pin connector to 3 RCA female". I also saw them called VTR cables.

Once you've got one, you need to get to the back of the stereo and plug it in. Luckily the Caldina's are fairly easy to access. I followed these steps on Answers.com and found them very good. Once you get to the back it should look like this:


The blue six-pin plug is the one you want.



Plug the cable into that. Personally, I then used a 3.5mm to RCA cable for the sound (Red/White) and a single RCA cable for the video (Yellow) and fed them into the glove compartment.

Once you've got the stereo back into place. You need to get the stereo into Video mode to use the new connector. This can be tricky to figure out as it is all in Japanese but here's what you do.
  1. Press the TV button.
  2. Press the button just above the AM FM button that's in Japanese, I think it's the Tuning button.
  3. Press the VIDEO button on the touchscreen. If it doesn't show, play something into the RCA inputs, I had to play some music from my phone in before the button appeared.


Once you've pressed VIDEO with any luck you should have the music playing through the car stereo.

Before I put it all back together I checked the video functionality by plugging in a Raspberry Pi, which worked no problem.


That's all there is to it, hope it helps.

Monday, 16 September 2013

My Go Tour Web Crawler Solution

I recently followed through the Tour of Go, it's a really great introduction to the language with some interesting exercises.

The final exercise is to rewrite a simple web crawler function, making it concurrent and stopping it from retrieving duplicate URLs. It took me a couple of attempts to find a solution I was happy with.

The original crawl function
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    // TODO: Fetch URLs in parallel.
    // TODO: Don't fetch the same URL twice.
    // This implementation doesn't do either:
    if depth <= 0 {
        return
    }
    body, urls, err := fetcher.Fetch(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("found: %s %q\n", url, body)
    for _, u := range urls {
        Crawl(u, depth-1, fetcher)
    }
    return
}

My crawl function
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    // the number of outstanding URLs being fetched
    count := 1
    // a list of URLs that have been fetched
    fetched := map[string]bool{url: true}

    // a channel for the go routines to report completion of a fetch
    complete := make(chan bool)

    // a function to recurse through the urls to the required depth
    var fetch func(url string, depth int, fetcher Fetcher)
    fetch = func(url string, depth int, fetcher Fetcher) {
        defer func() {
            complete <- true
        }()

        body, urls, err := fetcher.Fetch(url)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Printf("found: %s %q\n", url, body)

        for _, u := range urls {
            if fetched[u] != true && depth-1 > 0 {
                fetched[u] = true
                count++
                go fetch(u, depth-1, fetcher)
            }
        }
        return
    }
    // start the crawl
    go fetch(url, depth, fetcher)

    // wait for all outstanding fetches to complete
    for i := 0; i < count; i++ {
        <-complete
    }
}

Monday, 13 February 2012

List Processes using libproc

To learn a little more about processes on a Linux system and to try writing some code in C I adapted some code from this blogpost and wrote a super basic version of the ps command.

On Debian based Linux systems first install libproc.
$ sudo apt-get install libproc-dev

The code:
#include <stdio.h>
#include <string.h>
#include <proc/readproc.h>

int main(int argc, char** argv)
{
 // fillarg used for cmdline
 // fillstat used for cmd
 PROCTAB* proc = openproc(PROC_FILLARG | PROC_FILLSTAT);

 proc_t proc_info;

 // zero out the allocated proc_info memory
 memset(&proc_info, 0, sizeof(proc_info));

 while (readproc(proc, &proc_info) != NULL) {
  printf("%-10d %-10d ", proc_info.tid, proc_info.ppid);
  if (proc_info.cmdline != NULL) {
   // print full cmd line if available
   printf("%s\n", *proc_info.cmdline);
  } else {
   // if no cmd line use executable filename 
   printf("[%s]\n", proc_info.cmd);
  }
 }

 closeproc(proc);
}

To compile:
$ gcc -o myps myps.c -lproc

The command output. The first column is process ID, the second is the parent process ID, and the third is the process command (if in square brackets the command isn't available and the filename of the executable is shown).
$ ./myps
1          0          /sbin/init
2          0          [kthreadd]
3          2          [ksoftirqd/0]
6          2          [migration/0]
29         2          [cpuset]
30         2          [khelper]
31         2          [netns]
33         2          [sync_supers]

... manually deleted output here so it's not too long

14531      12456      /usr/lib/chromium-browser/chromium-browser --type=renderer --lang=en-GB --force-fieldtest=CacheListSize/CacheListSize_12/ConnCountImpact/conn_count_6/ConnnectBackupJobs/ConnectBackupJobsEnabled/DnsImpact/default_enabled_prefetch/DnsParallelism/parallel_default/GlobalSdch/global_enable_sdch/IdleSktToImpact/idle_timeout_10/Instant/HiddenControlB/Prefetch/ContentPrefetchPrerender1/PrerenderFromOmniboxHeuristic/ConservativeAlgorithm/ProxyConnectionImpact/proxy_connections_32/SpdyCwnd/cwndDynamic/SpdyImpact/npn_with_spdy/WarmSocketImpact/warmest_socket/ --channel=12451.0x7f10f46cde00.1990687626
14557      2          [kworker/7:1]
14562      2          [kworker/3:0]
14574      12901      ./myps

To add more columns, take a look at the proc_t struct in the header file /usr/include/proc/readproc.h.

Sunday, 22 January 2012

Converting PHP variables to Javascript variables

Here are some techniques for safely passing PHP variables to Javascript.

Ints and Floats
This one's pretty obvious.
var js_num = <?php echo $php_num; ?>;

Strings
Note that json_encode will take care of the Javascript string quoting delimiters.
var js_str = <?php echo json_encode($php_str); ?>;

Arrays and Associative Arrays
Arrays and associative arrays require that the type first gets encoded to JSON (the first call to json_encode) and then into a string (second call to json_encode) which can be parsed by a Javascript JSON parse function. JSON.parse is included in all recent browsers but to be sure of support use Douglas Crockford's json2.js file which will add it to any browser missing it. jQuery also provides a JSON parsing function.
var js_arr = JSON.parse(<?php echo json_encode(json_encode($php_arr)); ?>);
var js_obj = JSON.parse(<?php echo json_encode(json_encode($php_assoc)); ?>);

Objects
Objects are handled like associative arrays as if get_object_vars had been called upon the object first.

Monday, 14 November 2011

RGB Hex and Int Conversions in PHP

Convert Hex to an Integer
hexdec("FFDDAA"); // returns 16768426

Convert an Integer to Hex
sprintf("%06X", 65280); // returns 00FF00
Can be used as a random color generator:
// get a random color (between 000000 and ffffff)
function randomColor() {
    return sprintf("%06X", rand(0, 16777215));
}

Get RGB Decimal values from Hex
$color = "34BB21";
$r = hexdec(substr($color, 0, 2)); // 52
$g = hexdec(substr($color, 2, 2)); // 187
$b = hexdec(substr($color, 4, 2)); // 33

And as a bonus.... RGB Hex validation
preg_match('/^[[:xdigit:]]{6}$/', $color);
For example:
function validate($color) {
    return (bool)preg_match('/^[[:xdigit:]]{6}$/', $color);
}

$tests = array(
    'asdfee',
    '123455',
    'DEAD12',
    'fde888',
    'gde888',
    'ffee',
    'blaarg'
);

foreach ($tests as $test) {
    print $test . "\t" . (validate($test) ? 'valid' : 'invalid') . "\n";
}

/*
Outputs

asdfee  invalid
123455  valid
DEAD12  valid
fde888  valid
gde888  invalid
ffee    invalid
blaarg  invalid
*/

Tuesday, 4 October 2011

Conway's Game of Life in JavaScript with Cloud9

As a small project to learn about a few new technologies I was interested in I built Conway's Game of Life using JavaScript and HTML5's canvas element.

Server Side
The server side is written in node.js, using the express framework with jade as the templating engine.

Client Side
The client side uses jQuery and the jQuery UI.

The most interesting aspect of the development for me was the use of the Cloud9 IDE, a browser based development environment. Cloud9 provides an editor, file browser, debugging tools, and easy access to Github projects. In addition, as I was useing node.js I could even run and test the application all from the browser without requiring any local environment setup. Cloud9 provides a shell with which you can install node.js dependencies (using 'npm' the node.js package manager) and perform git commands.

The Cloud9 shell, showing the auto-complete coolness.

The editor is much better than you'd expect from a browser based IDE and does provide many useful features such as syntax error-checking as you type. I ran into a few bugs with the IDE as I was using it but on the whole it was surprisingly good.

An example of the real-time code analysis, picking up coding errors as you type.

The very best thing about the whole setup was that I could switch to my laptop, open a browser, and continue working on it without the need for ANY local changes.

Cloud9 also provides an easy deployment mechanism if you use online hosting services Heroku or Joyent.

Cloud9 deployment setup

I signed up for Heroku and tested the deployment. So you can now see the app at http://blooming-mist-4344.herokuapp.com/.

Game of Life in action on Heroku

All in all, I would definitely recommend Cloud9 for node.js development. I'm hoping to add a few more features at some point to the app, such as saving and reloading Game of Life boards. The code is on my GitHub page for anyone interested - https://github.com/ewen/game_of_life.

Tuesday, 30 August 2011

PHP Anonymous Functions

I had to write a simple function in PHP to generate an id of the format dd-dd-dd-dd-dd-dd (where d is a digit). I thought I'd use it to try PHP's Anonymous functions with more of a functional programming approach, this is what I came up with:

$id = implode('-', array_map(function($n) { return sprintf('%02d', mt_rand(0, 99)); }, array_fill(0, 6, 0)));

It works fine and can be put all on one line (although a 109 char line) but realistically should be split for readability as I find it quite incomprehensible. Maybe:

$id = implode('-', array_map(
    function($n) { return sprintf('%02d', mt_rand(0, 99)); },
    array_fill(0, 6, 0)
));

Whilst that was interesting, in the end I used a more conventional approach (for readability and maintainability):

$numbers = array();
while (count($numbers) < 6) {
    $numbers[] = sprintf('%02d', mt_rand(0, 99));
}
$id = implode('-', $numbers);