Categorized

Spotted my son Joris doing his “Nom Nom Nom Nom” :)

0

The one with the cool Spider-man t-shirt (blue), so proud! We also bought an enormous amount of Lego last weekend, finally a good excuse to spend lot of cash on toys again. For the non-geeks: “Nom Nom Nom”. What we bought:
- http://starwars.lego.com/en-us/Products/7868.aspx#7913 Thanks to my nephew for making him enthusiastic about Star Wars Lego

- http://herofactory.lego.com/en-us/Products/Default.aspx#2063 and http://herofactory.lego.com/en-us/Products/Default.aspx#2142 which can be combined to create: http://herofactory.lego.com/en-us/BuildingInstructions/2063-2142/combi1.aspx (okay, I had to buy both of course, otherwise we’d only have half of the puzzle and I wouldn’t be able to sleep at night)

Testing the Euro in Oracle with Zend_Db – PHP, Character Encoding Mayhem.

0

Just a little code snippet to test inserting and reading special characters (in this case the €) with Oracle and Zend Framework.

References:
ISO/IEC 8859-15
http://en.wikipedia.org/wiki/ISO/IEC_8859-15

Unicode Character ‘EURO SIGN’ (U+20AC)
http://www.fileformat.info/info/unicode/char/20ac/index.htm

CREATE TABLE "EURO_TEST" ( "EURO" VARCHAR2(50 CHAR) )

Zend Framework Controller Action …

   /*
    * http://en.wikipedia.org/wiki/ISO/IEC_8859-15
    * EURO = Hex A4 (Dec 164)
    *
    * Unicode Character 'EURO SIGN' (U+20AC)
    * http://www.fileformat.info/info/unicode/char/20ac/index.htm
    * EURO = UTF-8(hex) 0xE2 0x82 0xAC (e282ac)
    *
    * Oracle Adapter Configuration:
      resources.db.adapter = "Oracle"
      resources.db.params.host = ""
      resources.db.params.username = ""
      resources.db.params.password = ""
      resources.db.params.charset = "AL32UTF8" !!IMPORTANT!!
      resources.db.params.dbname = "..."
      resources.db.isDefaultTableAdapter = true

    * Get Oracle NLS Settings:
    * SELECT * FROM NLS_DATABASE_PARAMETERS;
    */
    public function euroAction ()
    {
        $this->_helper->viewRenderer->setNoRender(true);

        $db = Bootstrap::getDatabase();
        // cleanup a previous test
        $db->delete('EURO_TEST');
        $db->insert('EURO_TEST',array('EURO'=>'€'));

        echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>Euro Test</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>';

        /* @var $db Zend_Db_Adapter_Oracle */
        $result = $db->fetchAll("select euro from euro_test");
        // Shows the €
        foreach ($result as $r) {
            echo htmlentities($r['EURO'], ENT_QUOTES, 'UTF-8'); // !!IMPORTANT!!
            echo '<br/>';
        }

        // http://www.techonthenet.com/oracle/functions/dump.php
        $result = $db->fetchAll("select dump(euro, 1016) as eurocode from euro_test");
        // Should show something like Typ=1 Len=3 CharacterSet=AL32UTF8: e2,82,ac.
        foreach ($result as $r) {
            echo $r['EUROCODE'];
            echo '<br/>';
        }

        echo '€';
        echo '</body></head></html>';
    }

See also:

A solution to set various PHP UTF-8 encoding settings for PHP through a .htaccess file can be found in this stack overflow post:

.htaccess settings for UTF-8 encoding support example:

########################################
# Locale settings
########################################

# See: http://php.net/manual/en/timezones.php
php_value date.timezone "Europe/Amsterdam"

SetEnv   LC_ALL  nl_NL.UTF-8

########################################
# Set up UTF-8 encoding
########################################

AddDefaultCharset UTF-8
AddCharset UTF-8 .php

php_value default_charset "UTF-8"

php_value iconv.input_encoding "UTF-8"
php_value iconv.internal_encoding "UTF-8"
php_value iconv.output_encoding "UTF-8"

php_value mbstring.internal_encoding UTF-8
php_value mbstring.http_output UTF-8
php_value mbstring.encoding_translation On
php_value mbstring.func_overload 6

# See also php functions:
# mysql_set_charset
# mysql_client_encoding

# database settings
#CREATE DATABASE db_name
#   CHARACTER SET utf8
#   DEFAULT CHARACTER SET utf8
#   COLLATE utf8_general_ci
#   DEFAULT COLLATE utf8_general_ci
#   ;
#
#ALTER DATABASE db_name
#   CHARACTER SET utf8
#   DEFAULT CHARACTER SET utf8
#   COLLATE utf8_general_ci
#   DEFAULT COLLATE utf8_general_ci
#   ;

#ALTER TABLE tbl_name
#   DEFAULT CHARACTER SET utf8
#   COLLATE utf8_general_ci
#   ;

Firefox 4 Gets a Seal of Approval XD

0

Now lets hope the extensions catch up with this version. Still waiting for Selenium, Pencil, Delicious, etc.

Nice Fresh Retro Implementation of <blink> to Drive People Insane, Enjoy!

0

We needed a nice “test environment” banner on a page and yes, we had the nostalgic idea to put a “under construction” picture with it. Instead I put in a blink, but to adjust the blinking speed we took the jQuery implementation. As a practical joke I “enhanced” the blink code a bit, to really spice it up, code below, enjoy :)

(function($) {
	$.fn.blink = function(options) {
		var defaults = {
			delay : 500
		};
		var options = $.extend(defaults, options);

		return this.each(function() {
			var obj = $(this);
			setInterval(function() {
				var color = "#";
				var hex = '0123456789ABCDEF';
				for (var i = 0; i<6; i++) {
					var r =  Math.round(Math.random() * 16);
					color += hex[r];
				}				

				var color2 = "#";
				for (var i = 0; i<6; i++) {
					var r =  Math.round(Math.random() * 16);
					color2 += hex[r];
				}

				var size =  Math.round(Math.random() * 20) + 10;				

				var aran = Math.round(Math.random() * 3);
				var a = ['left','right','center'];

				$(obj).css({'text-align':a[aran],'background-color':color2,'color':color, 'font-size': size+'px'});
				if ($(obj).css("visibility") == "visible") {
					$(obj).css('visibility', 'hidden');
				} else {
					$(obj).css('visibility', 'visible');
				}
			}, options.delay);
		});
	};
}(jQuery));

$('#blink').blink({delay:400});

Posting Form Data via jQuery Ajax, a Code Snippet

0

You can test the code below in jsFiddle.

</pre>
<form id="myform"><input type="text" name="ok" value="cute" />
 <input type="submit" /></form>
<pre>
$(function(){
    $('#myform').submit(function(){
        var values = {};
        $.each($(this).serializeArray(), function(i, field) {
            values[ field.name ] = field.value;
        });

        values['custom-param'] = 'value';

        $.ajax({
            // mimeType: 'application/json',
            // contentType: 'application/json',
            type: "POST",
            async : false, // 'false' if I want code behind this call to handle response data
            url: 'myurl',
            data: values,
            dataType: 'json',
            success: function(response, textStatus) {
                if (response) {
                    // ^_^
                    console.debug(response);
                } else {
                    // x_x
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // x_x
            }
        });

        // do more useful stuff

        return false;
    });
});

If you happen to use Zend_Rest_Route (like me often) be careful when using “PUT” because the parameters will not be found in the request, you would probably need to serialize the “values” array with the json2.js library like:

data: JSON.stringify(values),
contentType: 'application/json; charset=utf-8',

which should be JSON decoded server side. Or just perform a POST at the REST path with an ID included in the path because that call will actually trigger the PUT action (which in my opinion is kinda weird, would rather have it fail but I can understand the logic). Don’t know why ZF doesn’t just parse the parameters on a PUT request if the content type is ‘application/x-www-form-urlencoded’.

Sublime Text Per Type File Preferences

0

I’ve been using Sublime Text for a while now on Windows and I sometimes forget to change the file type preferences to the following to ensure indentation (e.g. important for Python!) and to remove trailing white space.

My basic options for Python (Python.sublime-options) and Javascript.

# Settings in here override the defaults in:
# Packages/Default/Options/Default File Type.sublime-options
# See there for the available options and their description.

tabSize 4
translateTabsToSpaces true
trimTrailingWhiteSpaceOnSave true
wordWrap false

Zend Framework JSON based REST/RPC Controller Code Snippet

2

It’s a start towards a standard controller snippet I can re-use, will evolve over time.


<?php

class <ModuleName>_<ControllerName>Controller extends Zend_Controller_Action {
 public function <ActionName>Action() {
 // Making sure the date gets refreshed.
 $this->_response->setHeader('Cache-Control', 'no-cache, must-revalidate');
 $this->_response->setHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');

 /*
 Already performed by sendJson()
 $this->_helper->layout()->disableLayout();
 $this->_helper->viewRenderer->setNoRender(true);
 */

 $this->_helper->json->sendJson(<DATA>);
 }

 public function init() { }
 public function indexAction() {}
 public function getAction() {}
 public function postAction() {}
 public function putAction() {}
 public function deleteAction() {}
}

// Optional base class to inherit from, adds authentication and/or context switching.
class Default_Service_BaseRestController extends Zend_Controller_Action {
 public $requireAuthentication = false;

 public function init() {
 /* @var $contextSwitch Zend_Controller_Action_Helper_ContextSwitch */
 $contextSwitch = $this->_helper->getHelper ( 'contextSwitch' );

 /*
 $contextSwitch->addContext('csv', array());
 $contextSwitch->addActionContext ( 'index', 'csv' )->initContext ();
 $contextSwitch->addActionContext ( 'index', 'xml' )->initContext ();
 */

 $contextSwitch->addActionContext ( 'index', 'json' )
 ->setAutoJsonSerialization ( false )->initContext ();

 if ($this->requireAuthentication) {
 $this->authorize();
 }
 }

 // Just a helper ...
 public static function isAuthenticated() {
 $auth = Zend_Auth::getInstance();
 return $auth->hasIdentity();
 }

 public function authorize() {
 $auth = Zend_Auth::getInstance();
 if (!$auth->hasIdentity()) {
 /*  Not authenticated, could additionally also check for authorization ...
 $this->_helper->json->sendJson('error');
 exit;
 */
 }
 }
}

Minify and Merge JavaScript Project Files in Aptana (2.0) with Ant

1

Based on:
Minify JavaScript and CSS files in IDE
but added merging the files.

<?xml version="1.0" encoding="UTF-8"?>
<project name="YUICompression" basedir=".">
    <target name="default" description="Minifiy a set of files">
        <taskdef name="yuicompress" classname="com.yahoo.platform.yui.compressor.YUICompressTask">
            <classpath>
                <pathelement path="${basedir}/lib/yuicompressor-2.4.2.jar"/>
                <pathelement path="${basedir}/lib/yuiant.jar"/>
            </classpath>
        </taskdef>
		<delete>
			<fileset dir="${basedir}/output" includes="*.js"/>
		</delete>
        <concat destfile="${basedir}/output/javascript.js" append="true">
            <fileset dir="${basedir}/src" includes="*.js"/>
        </concat>
        <yuicompress linebreak="16000" warn="false" munge="no" preserveallsemicolons="true" outputfolder="${basedir}/minified">
            <fileset dir="${basedir}/output">
                <include name="**/*.js"/>
            </fileset>
        </yuicompress>
    </target>
</project>

Aptana Project Structure

Go to Top