Monthly Archives: September 2014

You are here: Home . Archive

How to court an ex-Prime Minister

I’m publishing this a day late; Mondays lately are pretty heavy. I hope you enjoy the read nonetheless

In a rather curt fashion, we got a new Prime Minister last week. If the letter announcing the change were a tweet, it’d have said, “It’s been real. No offense, it’s not you.” If it were a Facebook relationship status, it would be “It’s now very complicated”. Not to miss a beat, the opposition rode in on a unicorn, carrying promises of donor funds, a bouquet and a box of chocolates to court the ex-Prime Minister.

Opposition Courting Amama Mbabazi

Reports say they immediately asked him to join them to work together to oust the current government. “Here here, don’t look back. Come to us,” they seemed to say. You’d have expected courtesy to dictate that they give him at least some time to let it sink in before they try to sink their teeth in. Our members of the opposition, a determined lot, are having none of that though; they want to be the rebound guy here and now, no time to waste. Kinda like that person who immediately offers to buy the deceased’s clothes while you are at the funeral. Not cool. That said, seeing as you, dear opposition, are bent on the courtship and won’t listen to wise counsel, here are a few ways you can do the courting tactfully; dropping hints in newspapers and in radio interviews won’t quite cut it.

The ex-premier is one of the biggest African politicians on Twitter. Fill his Twitter feed with praises of his statesmanship. Then, start a hashtag encouraging him to make the big move. Make sure the hashtag trends. Follow this up closely with a burst of direct messages to him from different members in the opposition, all stating a different reason why your side of the bread is buttered better. You do have an uphill task here since in as much as you have slices of bread, the man you are courting is among the bakers.

Charter a jet to fly overhead as he arrives for parliamentary proceedings. We’ve seen at various Independence day celebrations that our pilots are capable of performing those fancy aerial gymnastics that Tom Cruise wanted us to believe were only a reserve for top American guns. Get the jet to spell-out in the air a few words inviting the ex-premier to your side of the house. “Come to the opposition”, “The F in FDC is for FLY”, “Make a movement towards the opposition”.

Run a Java Application as a linux service

I needed to run a Java program as a service on a server running RHEL. I used the script below to get it working. I got direction from

1. http://stackoverflow.com/questions/11203483/run-a-java-application-as-a-service-on-linux

2. http://www.apexninjas.com/blog/2011/02/start-java-program-as-linux-daemon/ and

3. http://fedoraproject.org/wiki/Packaging:SysVInitScript#Initscript_template

The third link provides a detailed explanation on init scripts; I recommend that, at the very least, you skim through it. I needed a cleaner implementation than link 1 and a less verbose implementation than link 2. This is what I eventually used:

#!/bin/sh
#
# myprogram Startup script for my Java program
#
# chkconfig: <startlevellist> <startpriority> <endpriority> e.g. chkconfig: 2345 85 15 Explained #http://fedoraproject.org/wiki/Packaging:SysVInitScript#.23_chkconfig:_line. Run levels are here. http://en.wikipedia.org/wiki/Runlevel
#
# description: My Java program that......\
#				mows the Linux lawn

### BEGIN INIT INFO
# Provides:
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop:
# Short-Description: Start and Stop my java program
# Description: 	My Java program does this and that
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

exec=/path/to/the/jarfile.jar
prog=myprogram
#config="<path to your config file>" #Add a config file if you need one. Usually put in /etc/
pidfile=${PIDFILE-/var/run/myprogram.pid}
logfile=/var/log/myprogram/myprogram.log
errorlog=/var/log/myprogram/error.log	

[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

lockfile=${LOCKFILE-/var/lock/subsys/$prog}

start() {
    #[ -f $config ] || exit 6 #No config for now. You can add it here & uncomment
    #The check for if the service is already running is done prior to this in rh_status_q()
     echo -n $"Starting $prog: "
    # Start the service
	nohup java -jar $exec >>$logfile 2>>$errorlog & echo $! >$pidfile
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    # stop it here 
	kill $(<$pidfile)
	rm -f $pidfile
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    restart
}

force_reload() {
    restart
}

rh_status() {
    # run checks to determine if the service is running or use generic status
    if [  -f $pidfile ]
    then
	if [  -e /proc/$(<$pidfile) ]
	then
		echo -ne "$prog (pid $(<$pidfile)) is running...\n"
	fi
    else
	echo -ne "$prog is stopped\n"
    fi
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q || exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
exit $?

Place the script here: /etc/init.d/

Also, mkdir /var/log/myprogram

Now to start your service:

service myprogram start

To stop it:

service myprogram stop

To check status:

service myprogram status

Look through other init scripts in /etc/init.d/ for other ways to do this

Add WordPress Related Posts without a plugin

There are several articles out there on how to add WordPress related posts without using a plugin. I’m adding one more to the fray only because all the other posts do one thing; they match related posts based on those posts being in the same category or having the same tag as the current post. If you’d like to match posts based on that criteria (same category, same tag), these are well-written articles:

By Darren, on Hongkiat here http://www.hongkiat.com/blog/wordpress-related-posts-without-plugins/

By the staff at WpBeginner http://www.wpbeginner.com/wp-tutorials/how-to-display-related-posts-in-wordpress/

If you’d like to do more than that, I share here how to match against title and post content and provide a fallback that matches against category. On to the code:

First off, your theme will need to have thumbnail support. Add this to your functions.php (most themes already have this )

add_theme_support( 'post-thumbnails' );  //Important
//set_post_thumbnail_size( 100, 50, true );  //If the default WordPress thumbnail dimensions of 150 x 150 won't cut it for you, use this to change them

Then, add these three functions to, well, functions.php

/**
* Append related posts to the bottom of the post
* currently being displayed
* @since 1.x.x
*/
function yourthemename_get_related_posts($content){
global $wpdb,$post;
$related_posts_title = __("Highly Recommended:");
$number_of_related_posts = 3;

//First, we match content based on post title and post content
$matchContent = addslashes($post->post_title. ' ' . $post->post_content);

//Query your Database to pick the related posts. Note that we don't use SELECT *, which is inefficient
$sql = "SELECT ID,post_title FROM ".$wpdb->posts." WHERE MATCH(post_title,post_content) AGAINST ('".$matchContent."') AND post_status = 'publish' AND ID != '".$post->ID."' LIMIT ".$number_of_related_posts.";";
$related_posts = $wpdb->get_results($sql);

$content .= '
<div class="related_posts">';
$content .= '
<h3>'.$related_posts_title.'</h3>
';
$content .= '
<ul>';</ul>
//If matching title/content didn't pick-up a thing, we fall-back to querying based on same category
if( empty( $related_posts ) ){
$category = get_the_category();
$cat=$category[0]->cat_ID;
$args = array( 'posts_per_page' => $number_of_related_posts, 'cat' => $cat, 'post__not_in' => array($post->ID) );
$related_posts = new WP_Query ( $args );

if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
$content.=yourthemename_wrap_related_post_item(get_the_ID(),get_permalink(),get_the_title());
endwhile;
}
}
else {
foreach ( $related_posts as $relatedPost ) {
$content.=yourthemename_wrap_related_post_item($relatedPost->ID,get_permalink($relatedPost->ID),$relatedPost->post_title);
}
}
$content .= '

';
$content .= '

</div>
<!--.related_posts-->';
wp_reset_postdata();//Important to allow the comments template to show comments. Without this, comments won't display
//The comments template relies on the global $wp_query object to be set for it to work; We call this function to set the post data back up
return $content;
}

/**
* The layout for an item in related posts. We create this separately since
* the items are populated using two different approaches [matching against post title/content and
* matching against same category
*
* @param $id The post ID
* @param $the_permalink The post permalink
* @param $post_title The post title
* @return An HTML li element
* @since 1.x.x
*/
function yourthemename_wrap_related_post_item($post_id,$the_permalink,$post_title){
$content='';
$content .='
<ul>
	<li class="related-post">';
$content .= '<a title="Permanent Link to '.$post_title.'" href="'.$the_permalink.'">';
$content .= yourthemename_the_post_thumbnail();
$content .= '</a>';
$content .= '<a title="Permanent Link to '.$post_title.'" href="'.$the_permalink.'">';
$content .= '
</a>
<h4>'.$post_title.'</h4>
';
$content .= '

';
$content .='</li>
</ul>
&nbsp;

';
return $content;
}

/**
* Returns a string containing an HTML image element for the post currently being displayed
* or a default image if no thumbnail is defined (Which happens when the post doesn't have a 'Featured image'
* @since 1.x.x
*/
function yourthemename_the_post_thumbnail(){
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
return get_the_post_thumbnail($post_id,'thumbnail');
}
else{
return '<img class="attachment-thumbnail wp-post-image" src="'.get_stylesheet_directory_uri().'/images/yourtheme_default_thumbnail.jpg'.'" alt="yourtheme_changeThis" width="150" height="150" />'; /*Your theme's default thumbnail*/
}
}

The code has quite a number of comments for you to follow what’s going on. WordPress has coding standards; all efforts are made to ensure that the code conforms to them.

When you copy the code, replace all instances of yourthemename with your theme’s actual name.
Particular spots you need to customize:
Change $related_posts_title = __(“Highly Recommended:”) and $number_of_related_posts = 3 to suit your needs

Very important: Change yourtheme_default_thumbnail.jpg to the name of an actual image in your theme’s image directory. Make sure its dimensions are the same as the thumbnail dimensions (re-sizing by CSS is bad, very bad)

Then, the CSS:

.related_posts{ width: 100%; }
.related_posts ul { margin: 0; padding: 0;}
.related_posts ul li {list-style-type: none; float: left; padding: 1em;}
.related_posts ul li:hover { background-color: #CCC;}

Watch out for the mafia in Uganda

A few weeks back, a minister declared that the mafia were out to have him sacked. As a fearless writer, I immediately reached for my overcoat and a magnifying glass and headed out to “the field” to gather all kinds of information about this clandestine criminal gang. It’s not the first time that these Mafioso are mentioned; back in 2006, the then vice president spoke of them, alleging they were going about investigating his wealth.

The mafia have since been mentioned a number of times in one conversation or another. On all occasions that they’ve made it into the newspapers, the image that comes to mind is of burly individuals smoking cigars and with big, gold rings on their pinky fingers. This image is uncomfortable for everyone. How can we as a nation, who are free-spirited at heart, enjoy every day with mafia breathing down our necks? We need to unearth this scum so that they can be prosecuted and put away. Their ring needs to be busted, like in the movies, and the mafia lords brought to their fat knees (without the gunfire that movies associate with these arrests). In an effort to contribute to this national effort to bring these men to justice, I’ll share information leading to their arrest. I’ve decided against going ahead with investigations in the field; I’ve put the magnifying glass down and will proceed to make informed speculations based very loosely on a few movies I’ve watched on the subject.

They wear brightly-colored suits. Purple, yellow, pink and colors invented to dumbfound men – aquamarine, beige, turquoise and the like.

mafia_in_ug

You hit me, we hit you

They hold walking sticks and walk with a characteristic limp, one an uniformed person would describe as similar to that of a dog with an injured leg

They love cigars but because they are Ugandan (that’s the mafia, not the cigars), they smoke sportsman instead

They wear knock-off shades and fake moustaches that slide off often

Every evening, they cluster around a big table with their huge families and have spaghetti and mukene

They communicate with each other in a potent mix of Swahili, Italian and a few local languages

They sleep with one eye open, switching which eye’s open in four-hour intervals

WordPress Multiple Excerpt Lengths

There are times you need to have multiple excerpt lengths. You might have a page (usually the homepage) that in one section displays more text that it does in another section. As all things WordPress, there are a number of ways to do this. There might even be a number of plugins for this. You can achieve this easily using some code in your theme’s functions.php. To functions.php, add this:


/**
* Change the excerpt length. Returns a different excerpt length
* for use in any template file. For this example, we return a different
* excerpt length for two categories, 3 and 4
*/
function themename_excerpt_length ($length) {
if ( in_category( 3 )) { /*If the category has ID 3*/
return 10; //10 is how long the excerpt will be for this category
}
else if ( in_category( 4 ) ) { /*A different category ID*/
return 40;
}
else{
return 55; //The default excerpt length
}
}
add_filter('excerpt_length', 'themename_excerpt_length');

To use this function, while in the loop in your template file, call themename_excerpt_length(). I use this on my homepage to have different excerpt lengths in the different sections

Why did the President’s car cross the border?

Last week, we all gasped in disbelief when we heard that Kenya’s President’s car had sneaked out of Kenya with the aid of some uncouth individuals. The vehicle sauntered across the border and was found parting, popping Uganda waragi bottles and living it large in Uganda.

All requests for an interview with it were turned down, perhaps because its inebriated state wouldn’t let it string together anything coherent. I was bitter about losing so much money in getting someone who speaks fluent car to conduct the interview only for the aides to violently turn us down.

We were turned down so violently, at one moment in the phone call we were yelling in Luganda and the aides on the other end were hurling huge Swahili pop sounds at us- it’s a wonder that the phone line managed to faithfully carry everything across.

Since they won’t let us hear it from the car’s mouth, we’ve decided to compile a list of possible reasons it chose to make the huge leap across the border; we all know that, “Once you go Ugandan, it can’t be undone”. The car crossed:
To learn Luganda
It was afraid of being hijacked
It wanted to bond with the owners of Migingo
It didn’t know Sheng
As an MP, it didn’t want to be grilled anymore
It wanted a Ugandan woman
It wanted its debt to be cleared by President Museveni
When it grew up, it wanted its number plate to begin with U
It had a thing for matooke
It wanted to be counted in the census
As a star long distance runner, it was training. It run the entire journey and had plans to run back
It wanted women to kneel for it


It wanted to teach Ugandans how to run long distances
It heard that Museveni was giving out #sacksofmoney
It thought taxis were still on strike so it could make a quick buck transporting people
It wanted to work less and live a slower life
It wanted to stand for President in 2016
It wanted to start a side business and use company resources for it
The cold was driving its tyres nuts
It hoped to join the Miss Uganda beauty contest and be judged by army men
It wanted to use boda boda
It wanted to fall asleep in parliament.

Let’s invest in foreign ghosts

We were thrilled when news broke that the Uganda National Roads Authority (UNRA) allegedly paid about 24 billion to a ghost company from outside countries to do the Mukono-Katosi Road. It was hard for us to hide our excitement as a nation; UNRA had finally broken free of the grip local ghosts had on us. We’ve seen ghosts in the police force, we’ve listened to ghost teachers, we’ve heard of ghost pensioners and we’ve even seen what ghosts do to our poor MPs’ money. Never in even our wildest dreams did we think that in our lifetime, we’d see ghosts from abroad. We’d shelved that dream right next to the one where Uganda goes to the moon and discovers a rare form of gold that sends off mental vibes that only a Ugandan who isn’t a politician can pick up. UNRA wasn’t going to let us go down like that; they looked at our little faith and said “Countrymen, we will heal you still. We will bring you ghosts from lands far faraway”

foreign_ghosts

To easily repeat this huge advance, we need to learn from it as much as possible. Here’s where UNRA needs to share insights. What do the foreign ghosts look like UNRA? Do they eat money in shillings too? Do they disappear when a local committee is setup to probe them? Do they understand our accent? Do I need a translator to communicate with them?

These are such exciting times. UNRA, we hope that other entities will follow your bold example – in a global village, we can’t stick to only investing locally. Bring in expatriates! In case you aren’t as excited about this as you ought to be, here’s a small fact to get you there-because of the ghosts being foreign, the Federal Bureau of Investigation, the FBI, has joined in the exorcism. Imagine that. The FBI! This means we can ditch our counterfeit copies of CSI, Bones, Castle and all those investigative series and tune into NTV news to follow this case. Agent Miller will be there, furrowed brow and all, doing forensics, running after local villains, villains whose last names roll off our tongues very easily, and tackling them. The car chases wouldn’t be in New York, they’d be right here in Bwaiise. Though knowing Bwaiise, the car chase would quickly progress into a swim chase and eventually a boat chase.

Fix for jQuery selector not working

I stopped short of giving my PC a bath when for some strange reason, the jQuery selectors I was using weren’t working. Thing is when doing basic testing for jQuery, you’ll write something to console.log (either that or you’ll put an alert and wait for it to annoyingly pop-up ). Things were so bad, I did both! Many, many hoops later, I realised that the selector worked for all content not loaded by AJAX. Lightbulb! Quick fix:

For content that’s being loaded dynamically, you need to use a technique known as event-delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

e.g.

jQuery("#TheParentSelector").on('click',"#dynamicallyLoadedSelector",function(){
/*Go on, do your thing*/
console.log("Just doing ma thing");
});

Note:

#TheParentSelector is a selector that’s already on the page. It isn’t loaded dynamically

“on” is supported in Jquery 1.7+

But my content isn’t dynamic

Are you targeting them correctly? Sure?

Is your script wrapped in an ‘onLoad’?


$( document ).ready(function() {
// You, doing your thing
});

Do you have any special characters in your selector? You need to escape them with \\ {jQuery(“#Selector\\~”)}

[WordPress Plugin Development] Handling Forms

There are some great resources on how best to add a form to your plugin. Notably, there’s this from Tutsplus (They write very solid tutorials; Love them):

http://code.tutsplus.com/tutorials/create-a-custom-wordpress-plugin-from-scratch–net-2668

In it, Cristian proposes that you use this for your form’s action

<form action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>" method="post" name="oscimp_form"><input name="oscimp_hidden" type="hidden" value="Y" /></form>
and use this to handle the submission:
if($_POST['oscimp_hidden'] == 'Y') {
//Form data sent
} else {
//Normal page display
}
This is fine if you aren’t using OOP in your plugin; if you are (and you really should be IMHO), there are a number of ways to go about it. One is to point the action to a plugin menu item and then in the handler function, check whether the request came in from your form. *stop talking already, give us the code!!*
One tiny other thing: Using REQUEST_URI for your action doesn’t cater for the fact that it could contain several other query arguments which you’d be passing on
Ok, now, the code: Point your form’s action to a plugin menu page:
<form action="<?php echo admin_url('admin.php?page=my-plugin-page');?>" method="POST">
<!--The rest of your input fields-->
<input type="submit" value="Submit" name="my-submit" />
NB: I found that my form defaults to GET hence the need to explicitly define method=”POST”
Then to handle the form submission, put this in the constructor of the class that’s going to handle your data:
add_menu_page($page_title, $menu_title, $capability, "my-plugin-page", array($this,handle_form_submission));
public function handle_form_submission(){
 if ( isset($_POST['my-submit']) ) {
            //Handle your form's data
   } else{ 
     //Output the my-plugin page HTML
}
}
Note that you don’t necessarily have to define a new plugin menu page just to handle your form submission; you can re-use one you’ve already defined-all you need is to add the if ( isset($_POST[‘my-submit’]) )  to pick-up your data and proceed with processing.
Don’t forget to add a nonce to your form.