Flabby Rabbit | The offical home of The Rabbit

External MySQL database with Node.js

Getting node to connect to a local database is a piece of cake, but when trying to connect externally I found very little on the internet … and ended up just guessing until it worked.

First you need to get nodes mysql plugin installed:

npm install mysql

“The mysql module is entirely written in Node.js, and implements an async MySQL client.” – nice introduction and the projects github. Here is my implementation, be warned it is horrible. Use the previous link to see how this should have been done:

var _mysql = require('mysql');
var MYSQL_HOST = '127.0.0.1';
var MYSQL_PORT = '3306';
var MYSQL_USER = 'user';
var MYSQL_PASS = 'pass';
var DATABASE = 'db_name';

var mysql = _mysql.createClient({
    user: MYSQL_USER,
    password: MYSQL_PASS,
    host: MYSQL_HOST,
    port: MYSQL_PORT,
});

mysql.query('use ' + DATABASE);

mysql.query('SELECT value FROM settings WHERE setting = "chan"', function selectCb(error, results, fields) {
  if (error) {
    console.log('Error getting settings: ' + error.message);
    return;
  }

  if(results.length > 0) {
    results.forEach(function(row) {
        console.log('Connecting to: ' + row['value']);
    });
  }
});

Drag and drop targets with jQuery

Multi line strings in Javascript

String concatenation is the most common method of formatting long strings in Javascript, but it isn’t the only or best way. For better performance try using backslashes to split up your lines.

Backslashes

var text = "I am a long string that I would\
like to split up on to multiple lines to keep my code\
nice and neat, which (should be) every developers aim."
;

String Concatenation

var text = "I am a long string that I would like to split "
         + "up on to multiple lines to keep my code nice and "
         + "neat, which (should be) every developers aim.";

Running a function after page execution

“Registers a callback to be executed after script execution finishes or exit() is called.” – php.net

Here is a simple class to show the execution time of a page:

<?php
    class logger {
       
        private $exec_start, $exec_time;
       
        function __construct() {
            $this->exec_start = microtime(true);
       
            register_shutdown_function(array($this, 'basic_log'));
        }
       
        public function basic_log() {
            $exec_time = microtime(true) - $this->exec_start;
            echo $exec_time;
        }
    }
?>

Quick and easy way to avoid CSS hacks

Probably the most incredibly useful snippet I have learnt recently. It’s beautifully simple and unbelievably essential. Creating websites for such a wide variety of platforms is hard enough but then when you throw IE6 and no script into the mix things can become very messy.

Replace the tag with the following code and most of the hard work will be taken care of:

<!--[if lt IE 7]><body class="no-js ie6"><![endif]-->
<!--[if IE 7]><body class="no-js ie7"><![endif]-->
<!--[if IE 8]><body class="no-js ie8"><![endif]-->
<!--[if gt IE 8]><!--><!--<![endif]-->
<script type="text/javascript">document.body.className = document.body.className.replace("no-js","js");</script>

Now you can easily target and correct any of the unique “features” of IE and also gracefully degrade when no javascript is detected.

A much better version of this post: Better conditional classnames for hack-free CSS

Final note: It might be a better idea to have no-js on the html tag instead of the body. The main reason for this is that if you wanted to test for no-js and ie6 you wouldn’t be able to with the above method. This is because IE does not support chained class selectors so you can’t do:

.no-js.ie6 div

Changing inc style permanently in Notepad++

Notepad++ by default interprets .inc files as being pascal source files. This by no means incorrect, it is just not very helpful when the .inc files I mainly work with are related to SSI and therefore are mostly HTML.

Text file containing declarations, headers, functions, or other data referenced by a program’s source code; can be used with C/C++, Pascal, Java, PHP (Web pages), and other languages.

The file you need to be interested in is located at %APPDATA%\Notepad++\langs.xml (e.g. C:\Documents and Settings\<username>\Application Data\Notepad++). In this file you need to remove inc from the ext of the Pascal node and add it to that of the html node.

<Language name="html" ext="html htm shtml shtm xhtml inc" commentLine="" commentStart="&lt;!--" commentEnd="--&gt;">;

Save this file, close Notepad++ and when you open a .inc file it should now be highlighted as if it was a HTML file.

Side note:
The langs.model.xml file in C:\Programs\Notepad++ is the factory default settings, and changing the declaration here will have no effect.

Deleting entire row based on column value

I needed to remove all rows in an excel sheet where column A was blank. With 4000 rows to sort through I thought I would attempt to write my first macro to do the job for me. I have no prior knowledge of VB so didn’t expect to get very far. Boom, done – all I can say is VB is horrible.

Sub deleteRows()
    Dim n As Long, rowCount As Long
    rowCount = Application.WorksheetFunction.CountA(Range("B:B"))
    For n = 1 To rowCount Step 1
        If Range("A" & n).Value = "" Then
            Rows(n).Delete
            If Range("B" & n).Value <> "" Then
                n = n - 1
            End If
        End If
    Next
End Sub

This solution works perfectly but I have just had an idea that might work. If you used a reverse loop from rowCount to 1 then there would be no need for the if statement; as the index of the rows to be processed will not be changed. I may update this post when/if I get a chance to have another look.

Using SSI effectively

Server Side Includes (SSI) is a simple interpreted server-side scripting language. SSI is mainly used to include files inside other files, much like PHP includes.

Simple include:
File: main.html

<!--#set var="inc" value="/inc/header.inc" -->

Using variables to include files:
File: main.html

<!--#set var="inc" value="/inc/header.inc" -->
<!--#include virtual="${inc}"-->

Passing variables to create dynamic includes using SSI and JavaScript:
File: main.html

<!--#set var="inc" value="/inc/header.inc?title=Welcome" -->

File: /inc/header.inc

<script type="text/javscript">
    var title = "<!--#echo var="QUERY_STRING"-->
    alert(title);
</script>

Apache includes can also do a number of other interesting bits and pieces.

Displaying dates:

<!--#echo var="DATE_LOCAL" -->

<!-- See http://gnuplot.sourceforge.net/docs_4.2/node274.html for format specifiers -->
<!--#config timefmt="%A %B %d, %Y" -->
<!--#echo var="DATE_LOCAL" -->

Document last modified: <!--#flastmod file="index.html" -->

I have always used PHP includes in my own work but since starting my new job we do not have access to such technology and therefore have been forced to use SSI. I was wondering how the performance would differ between the two methods. There was some debate on the matter but little in the way of facts and figures. I did find one interesting point which was:

“using PHP is more efficient than using SSI because SSI is still forking a separate CGI process where PHP is not, assuming PHP is integrated as a module on the web server, not run as a CGI.”

This seemed interesting but either way any differences would be negligible and it appears no body has any definitive proof to which is faster.. Never the less there is no doubt that PHP is more powerful and flexible and for this reason I would not consider changing to SSI.

Setting default monitor for Ubuntu

When using dual screen the gnome panels automatically get attached to the default monitor. If you have something like nvidia x-config you can easily change this using their software, but what if you don’t?

Open up a new terminal window and enter:

xrandr --prop | grep "[^dis]connected" | cut --delimiter=" " -f1

This will display which devices are currently connected, now decide which one of these is the monitor you want to set to default. Now enter:

xrandr --output [monitor] --primary

Replacing [monitor] with the device you chose in the first step. Now your panels should magically move to your new default monitor.

Andrew Martin at ubuntuforums wrote a quick bash script to semi-automate this process. Copy the code below and save it with the file extension .sh. Now set this file as executable and away you go.

#!/bin/bash
# Author: Andrew Martin
# Credit: http://ubuntuforums.org/showthread.php?t=1309247
echo "Enter the primary display from the following:"            # prompt for the display
xrandr --prop | grep "[^dis]connected" | cut --delimiter=" " -f1    # query connected monitors
 
read choice                             # read the users's choice of monitor
 
xrandr --output $choice --primary                   # set the primary monitor

Creating JSON Objects with Android

After starting a new project utilizing Android and a server written in C++ I noticed that although Android has a built in JSON library there is little to no information about how to implement anything useful. The majority of responses online point users to using an additional library such as GSON. This is all well and good, but I only needed minimal functionality…converting JSON to HashMaps and vice versa.

Here is the first draft of my JSON class. With static methods to convert Map to JSONObject and the other way around, of any depth.

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONObject;

import android.util.Log;

public class JSON {

    public static JSONObject create(Map<String, Object> params) {
        try {
           
            //Create Json
            Iterator iter = params.entrySet().iterator();
            JSONObject holder = new JSONObject();
            while(iter.hasNext()) {
                Map.Entry pairs = (Map.Entry)iter.next();
                String key = (String)pairs.getKey();
                Object v = pairs.getValue();
                if (v.getClass().equals(HashMap.class)) {
                    Map<String, Object> params2 = (Map<String, Object>)v;
                    v = create(params2);
                }
                holder.put(key, v);
            }
            return holder;
           
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            Log.e("JSON Error", sw.toString());
            return null;
        }
    }
}
 

Essentials