Write Your Own Listener Interface (you know you want to)

I’ve used Listeners a lot in Java. The standard listeners have always been sufficiently flexible for my needs.

Until today.

This tutorial was all I needed to quickly implement my listener: Listeners in Java

It’s clear, succinct and comprehensive. When you need to implement your custom listener interface, check it out.

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback

Java: repaint() Waking Nightmare

You know those times, while coding, when it feels like you’ve drifted into a horrible nightmare where nothing you do works?

This happened to me today.

I wanted the little app I’m making to display a green tick or a red cross depending on whether the user had entered valid credentials. Simple? Yeah. Everything went really well, I extended a JPanel to handle the tick/cross display area (tickCross), got the POST code going, strung together the rest of the GUI elements.

The problem was that tickCross.repaint() wasn’t reliably repainting. about 30% of the time the image wouldn’t be painted. The method was being called, but nothing was happening. I tried Google, re-read the related Sun Java docs and was reminded that: “repaint() does not actually paint. It calls the peer repaint which enqueues a request in some platform-dependent way inside the native GUI for a repaint.” – MindProd. Great. My OS was deciding when I was allowed to draw.

Somewhat more irritated, I then had to resort to every programmer’s backup tool: trial and error.

After much frustration, I struck a solution. It’s not elegant, I’d even say it’s hacksih, but it works.

1
2
3
tickCross.repaint();
tickCross.setVisible(false);
tickCross.setVisible(true);

Cross or tick when I damn well want them, every time.

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback

Auto-Notification of Broken Links, Fantastic Pre-Written Anti-Spam .htaccess File!

Recently I’ve been learning a bit about .htaccess, redirecting visitors who come via now-broken links.

To help with this, I inserted a little mailer script into my error 404 page that sends me an email containing the referring URI, the URI the visitor was trying to reach and various other tidbits of information. It works well, allowing me to quickly fix broken links that I would otherwise be unaware of.

It also writes the beginning of a rewrite rule, as if I wasn’t lazy enough.

Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<? php 
	//mail me about this error...
	$to = "mike(@)pagesofinterest(.)net";
	$base = "http://pagesofinterest.net";
 
	$referrer = $_SERVER['HTTP_REFERER'];
	$requested_page = $_SERVER['REQUEST_URI'];
	$agent = $_SERVER['HTTP_USER_AGENT'];
	$ip = $_SERVER['REMOTE_ADDR'];
	$subject = "Error 404 - $requested_page";
	$body = "The page: $requested_page, referred to by $referrer does not exist.  Fix this or add a rewrite.\n\nAgent: $agent\n\n";
	$body .= "IP: $ip \n\n";
	mail($to, $subject, $body, $headers);
 
	//append to file:
	$redirect = "Redirect 301 $requested_page http://pagesofinterest.net/\n";
	$filename = "redirects.txt";
	$fh = fopen($filename, 'a');
	fwrite($fh, $redirect);
	fclose($fh);
?>

Use:

sort redirects.txt | uniq > unique_redirects.txt

In a terminal to get a smaller file containing only unique broken links.

One problem was the sheer volume of messages I was getting. I did some research, and it seems this site has become the target of spammers. After a bit of googling on how to discourage this, I came across the best thing a newb could hope for: a perfect, commented example. Aaron Logan has graciously made his .htaccess file available to the world. It handles bad user agents, known bad IP’s, and keywords in referrer URI’s. It is gold.

You can get your own copy of it here: best anti spam .htaccess file.

Thanks Aaron!

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback

Find and Replace Text Within Multiple Files in Linux – Avoid RSI

After updating 100+ pages manually, I realized that I had neglected to add “index.php” to the end of certain links. Usually this would be fine, but the links in question are opened in Shadowbox, which will fail on pretty, “index.php”-less links.

I was able to fix this on the server in 5 seconds with find+perl:

find . -name 'FILE_NAME.EXTENSION' | xargs perl -pi -e 's/FIND/REPLACE/g'

Where FILE_NAME is the name of the files to be searched in (can be ‘*’) and EXTENSION is the filetype (can be ‘*’). FIND is the text to be searched, and REPLACE is a replacement string.

Phew!

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

Comments (1)Trackback

Using PNG Transparency + the jQuery Colour Change Plugin

See the cute little pictures on the left? The ones below the site menu? Go ahead and run the mouse over them a few times – a faded circle behind the animals changes colour each time, doesn’t it? Yep.

The idea for this came from Artemy Lebedev’s Mandership. Go there and hover the cursor over the bar-code in the top right, notice that it changes colour as you do so.

I really like this effect, and wanted to implement on this site, as I needed something to distract me from important work.

The effect is accomplished with jQuery, a colour generation function and a transparent PNG.

I thought I’d share this effect, and variations, with the world with this tutorial.

Below are four variations, each adding an additional function/plugin to achieve the different effects:

Vanilla

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Colour Animation

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Hover Intent

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Brightness/Darkness Modification (darkness shown here)

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Vanilla

First, the library:

You’ll need to include jQuery in your page. First download the jQuery library, then upload it to your server. To include the library in your page, you need to modify then paste this code somewhere in your page’s header (the bit between the … tags):

<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>

Change src to reflect the location of the jQuery file you uploaded to your server.

Second, the functions:

This code needs to be pasted just below the jQuery library link, also in the header.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<script type="text/javascript">/* generate random colour http://www.therustybarrel.com/david/experiments/randhex.html */
function genHex(){
	colors = new Array(14);
	colors[0]="0";
	colors[1]="1";
	colors[2]="2";
	colors[3]="3";
	colors[4]="4";
	colors[5]="5";
	colors[5]="6";
	colors[6]="7";
	colors[7]="8";
	colors[8]="9";
	colors[9]="a";
	colors[10]="b";
	colors[11]="c";
	colors[12]="d";
	colors[13]="e";
	colors[14]="f";
 
	digit = new Array(5);
	color="";
	for (i=0;i<6;i++){
		digit[i]=colors[Math.round(Math.random()*14)];
		color = color+digit[i];
	}
	return "#"+color;
}
 
jQuery(document).ready(function(){
jQuery(".colour-change").hover(function(){
jQuery(this).parent().css("background-color", genHex());
});
});
</script>

The genHex() function is from The Rusty Barrel, but the site seems to be down. It strings together some random hex values, returning them in a string suitable for use in CSS.

jQuery code that is to be triggered by some event needs to be placed between jQuery(document).ready(function(){…}); In this case we have some code that will be executed when when the visitor hovers the cursor over any element with the class ‘colour-change’. The next line selects the anchor, then gets its parent. It then asks genHex() for a random colour, uses this to change the parent’s background colour. Simple! jQuery makes Javascript much simpler, fun even. It also alleviates many issues related to browser incompatibility.

Note that this code must be pasted below the line calling the jQuery library. Why? Because the colourChange() function needs jQuery to run, and javascript code only knows about libraries included above themselves.

Third, the HTML:

1
2
3
4
5
<div style="width:600px; height: 188px; background-color: #333333; margin: 0px auto;">
<a href="http://pagesofinterest.net/blog/2009/06/using-png-transparency-the-jquery-colour-change-plugin" class="colour-change"
<img src="http://pagesofinterest.net/images/post/dizi.png" alt="Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples."/>
</a>
</div>

The HTML required for this effect consists of three elements: an outer div, an anchor and an image. The styling for the div is very important. It must be given width and height values equal to the width and height of the image it is wrapping, and it must be given a background colour.

The anchor is given the class “colour-change”, which is required for jQuery to handle the cursor hover event.

The image should be whatever image you want to use – with at least a little transparency!

You can use this effect as many times as you want on any page – as long as whatever page you’re using it on has 1) the jQuery library link in the header, 2) the functions below the jQuery link in the header, and 3) the anchors must be given the class ‘colour-change’.

Colour Animation

Follow the vanilla section of this tutorial first.

Any of the variations can be combined with the excellent colour animation plugin for jQuery. This results in a smooth transition between colours, which is desirable in some cases. Here is our example + colour animations:

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

To integrate the colour animation plugin with this example:

Download the colour animation plugin, upload it to your sever.

Link to it in the header of your page, between the jQuery link and the functions code, e.g:

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.colouranimations.js"></script>
<script type="text/javascript">
function genHex(){
[...]
}
jQuery(document).ready(function(){
[...]
});
</script>

Swap the line “jQuery(this).parent().css(”background-color”, genHex());” with:

jQuery(this).parent().animate({backgroundColor: genHex()},500);

the ‘500′ value tells the function how long you want the transition to take, in milliseconds. Change this to whatever you like!

Hover-Intent

Any of the effect variations can be combined with hover-intent. If you plan on applying this colour-change effect to multiple items on a page, you should seriously consider this plugin. If will prevent the crazy “piano key” behaviour that can occur when a visitor hovers over multiple items in quick succession.

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Follow the vanilla section of this tutorial first.

Download the hover-intent jQuery plugin, upload it to your server.

Link to it in the header of your page, between the jQuery link and the functions code, e.g:

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.hoverintent.js"></script>
<script type="text/javascript">
function genHex(){
[...]
}
jQuery(document).ready(function(){
[...]
});
</script>

Replace the jQuery code with:

1
2
3
4
5
jQuery(document).ready(function(){
jQuery(".colour-change").hoverIntent(function(){
jQuery(this).parent().animate({backgroundColor: genHex()},500);
}, function(){});
});

You’ll notice that I’ve combined the hover intent plugin with the colour animation plugin in the code above. If you’d like to do this, make sure you include both plugins! Your jQuery, hover-intent and colour animation links should look like:

<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.color.animation.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.hover.intent.js"></script>

Remember that the jQuery link must be first! In this case the order of the following two doesn’t matter. The rule is this: if javascript X requires functions within javascript Y, then javascript Y must be included before javascript X.

Brightness/Darkness Manipulation

Any of the effects can be combined with this to produce a random colour change of a consistently darker/lighter brightness level. This can be good in situations where you want the randomized colour change to be more subtle.

Brightness:

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Darkness:

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Follow the vanilla section of this tutorial first.

I include this section in case you want to use only light/dark colours. Maybe the full range is too garish for you?

You’ll need to include the following two functions. Copy them just above the genHex() function. The functions are modified from code found in this post this post on the Experts Exchange.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function LightenColor(h, d) {
 
	var r, g, b, txt;
 
	h = (h.charAt(0) == "#") ? h.substring(1,7) : h;
 
	r = parseInt(h.substring(0,2),16);
	g = parseInt(h.substring(2,4),16);
	b = parseInt(h.substring(4,6),16);
 
	r = (r+d > 255) ? 255 : (r+d < 0) ? 0 : r+d;
	g = (g+d > 255) ? 255 : (g+d < 0) ? 0 : g+d;
	b = (b+d > 255) ? 255 : (b+d < 0) ? 0 : b+d;
 
	txt = b.toString(16);        if (txt.length< 2) txt = "0"+ txt;
	txt = g.toString(16) + txt;  if (txt.length< 4) txt = "0"+ txt;
	txt = r.toString(16) + txt;  if (txt.length< 6) txt = "0"+ txt;
 
	return "#"+ txt;
}
function DarkenColor(h, d) {
	return LightenColor(h, d* -1);
}

To get a random light colour, swap the jQuery(this).parent().css(”background-color”, genHex()); for:

jQuery(this).parent().css("background-color", LightenColor(genHex(),100));

To darken:

jQuery(this).parent().css("background-color", DarkenColor(genHex(),100));

There you go! I hope you found this tutorial helpful – please let me know if you spot any errors :)

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback

Unboxing the Bamboo

WacomBambooMy Wacom Bamboo arrived earlier today: hooray!

I’ve been wanting a device like this for a long time, but it wasn’t until recently that I actually needed one. I’ve started using the online Chinese character learning service, Skritter, and have found that it really helps me learn (and remember) new words. One learns/practises characters by writing them, which I’ve been using a mouse for. Not really ideal – I find it quite difficult to draw/write with a mouse, and even though I’ve become proficient at writing characters this way, I don’t think it’s as helpful in terms of increasing my ability to write Chinese characters as say, using a Wacom tablet would be. Don’t get me wrong – I’m confident that Skritter with a mouse is still by far the best way to learn/remember characters. I just think practising the characters WITH A PEN is more helpful when one’s goal is not only to be able to read Chinese, but also write it. Most probably with a pen.

So, I asked for one and it was given. Thanks Parental bodies 1 and 2 :)

Parental body 1 managed to fool me during the grant application process, which is no mean feat. Scroll to this sub-story.

The Bamboo was purchased from Ascent, a (NZ) online computer store. It is hands down the best online store I’ve ever seen – backed by impressive customer service. There was a slight hiccup in ordering: we tried to use a credit card, but Ascent has had cases where Person X buys a product with Person Y’s credit card, without Y’s knowledge, and now verify card ownership by looking the given details up in the phone book – bad luck if you’re unlisted! A phone call later, and we had a bank account number. Another phone call, this time to phone banking, and the money was transferred. Phone banking transfers are faster than online transfers here.

Delivery was quick.

Ubuntu 9.04 recognised it as soon as I plugged it in – there was no delay. Although I had read that this was the case, I was quite surprised. Thanks to WINE, the windows tutorial program, included on one of the CDs worked perfectly, and I was able to quickly go through the basic usage tutorials.

Then it was straight to Skritter.

[...]

I’ve used it for about an hour, and all I can say is: whoa. It’s a joy to use. In fact, I’m going to go and use it some more now.

[...]

This thing is … responsive, natural, it really is like I’m writing! It is awesome to able to practice the same motions as I would use when writing with a real pen + paper with Skritter. Wacom + Skritter = heaven. Also it’s matte black, and the pen comes with a little holder, that is reminiscent of an old inkpot.

Here are some pictures of the grand unboxing:

The package arrive about a day and a half later.

The package arrived about a day and a half later.

Ripping open the outer padding reveals some plastic padding

Ripping open the outer padding reveals some plastic padding

There it is!

There it is!

Another box!

Another box!

Some text... I have no time for reading!

Some text... I have no time for reading!


Finally!

Finally!

Skritter is the best, bar none. This coming from a guy with (seriously) 6 1E5 exercise books filled with handwritten characters + 3 at varying stages of completion, stacks of flash cards, Rosetta Stone, ProVoc… Compared to all methods of learning Chinese characters I’ve tried, Skritter is the best. Writing characters over and over in an exercise book, flashing cards in front of my face, sitting in front of Rosetta Stone, none of them were working very well anymore. It’s as if the efficacy of these methods is reduced in proportion to the number of characters learned. Skritter gets around this problem by rotating the characters according to a proven repetition strategy that in most cases will give a retention rate of ~95%.

Obviously it’s not a 1-stop-shop for Chinese language learning, but it definitely takes care of the character recognition/reproduction learning side. With gusto and style. Not to mention in less time than the aforementioned methods require!

Go there, prove these sentiments to yourself: write some Chinese characters.

Back to top

Tricked! I’m one of those annoying people that just loves to trick people. I’ve always been this way. I like to defend this “feature” of my personality by claiming that my tricks are aimed at helping my nearest & dearest develop a strong sense of logic and critical faculties, but the honest truth is that I just like to confuse people. A joke is anything that I find funny.

The earliest “encouragement” I remember administering was to my brother. While watching TV, if any text came up on screen he would ask me what it said. To which I would reply: “Learn-to-read-“. He loved it. Another favourite was the old “137″ home-phone trick with babysitters. That’s where one hides a portable phone somewhere and secretly dials 137, then hangs up. In NZ this results in a callback, which is when the phone rings but no-one is there (phone: “ring ring”, babysitter: “hello? hello?…”). Oh and another one: the invincible arcaroc dinner plate: while drying dishes, ask the babysitter: “Do you think this would break if I dropped it on the floor?”. Without waiting for a reply, drop it. Heh.

Anyway, all this has made my mother (and brother, wife, Garry, etc…) determined to trick me in a similar way. The day she ordered the Bamboo she succeeded. After emailing her to ask whether I could have the tablet, I received this reply:

Ascent products: Grant Application

Ascent products: Grant Application

I thought, maybe Ascent had some process by which parents could state an amount their offspring were allowed, and send these messages if the products the offspring wanted fell below this amount. At which point this email would be sent out. Dur dur dur.

Well done Mum!

Back to top

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback