Browsed by
Author: kris

Ajax python “hello server” example

Ajax python “hello server” example

Ajax provides direct messaging between a browser page and the server from where the browser page originated. For example, only a part of a web page may be loaded using Ajax (like google maps).

There are examples of Ajax on the web, but i have not found one of them that used mod_python as a back-end. I thought I would provide a simple “Hello world” example as reference:

I assume you have apache2 and mod_python working. I have Python Version 2.5.2 and Apache2 version 2.2.8 on Ubuntu.

File “test_ajax_helloserver.html” : contains the ajax javascript code that your browser will execute.
File “” : contains the ajax response that mod_python will execute on the server

Copy and paste the text below into your favourite text editor.
Save the two files in the same directory/folder under your Apache mount point.
Load “test_ajax_helloserver.html” through your Apache webserver, and test it by clicking the button.


<html><head><title>AJAX Hello Server mod_python ( Test</title>
<script type="text/javascript">
var req;
function sendServerRequest(){
   req = newXMLHttpRequest(); // register the callback function
   req.onreadystatechange = updateMsgOnBrowser
   //specify url correctly in open(requestMethod,url,isAsync,username,password)"POST", "", true); //or "POST"
   req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   //get the text input element (payload) and send it to server
   var msg_value = (document.getElementById("testmsg")).value;
   req.send("form_send="+msg_value);  //send(payload) send(null)=no parameters
// This is the callback function that called from the server with the XML data
function updateMsgOnBrowser() {
  if (req.readyState == 4) {
     if (req.status == 200) {
        if(req.responseXML == null){
           var msg_display = document.getElementById("display_result");
           msg_display.innerHTML="XML response error<p><b>Content-type:</b>"+
               req.getResponseHeader("Content-type")+"<p><b>Response:</b> "+req.responseText;
        } else {
	   if (!testXML.documentElement && req.responseStream) { // Microsoft hack
	      testXML.load(req.responseStream); // another reason to drop IE
           var stime=(testXML.getElementsByTagName("server")[0]).getAttribute("time");
           var ctype=(testXML.getElementsByTagName("ctype")[0]).firstChild.nodeValue;
           var msgval=" - )" ;
           if (testXML.getElementsByTagName("message")[0].firstChild!=null){
           var version=(testXML.getElementsByTagName("version")[0]).firstChild.nodeValue;
           var msg_display=document.getElementById("display_result");
           msg_display.innerHTML="<p><b>Server received:</b>"+msgval+
             "<p><b>Python Version:</b> "+version+"<p><b>Server Time:</b>"+stime+
             "<p><b>Content-type  server:</b>"+ctype+
             "<p><b>Content-type browser:</b>"+req.getResponseHeader("Content-type");
     } else {
       var msg_display = document.getElementById("display_result");
       msg_display.innerHTML = "ERROR: "+ req.status +" "+ req.statusText;
//helper function to get a XMLHTTPRequest
function newXMLHttpRequest() {
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch (e) {}
   alert("XMLHttpRequest not supported");
   return null;
<body><h1>Simple javascript ajax to server test</h1>
<input id="testmsg" type="text" value="Hello Ajax server">
<button onclick="sendServerRequest()">Send ajax request to Server</button>
<div id="display_result" style="{background:honeydew;}">
Response from "" on the server will go here </div>
<div id="error_msg"></div>

import  sys,time
def index(req):
    req.content_type="Content-Type: application/xml"
    submit = req.form.getfirst("form_send", "no form parameter")
    s= "<?xml version=\"1.0\"?>  <server time=\"%s\">\
        <ctype>%s </ctype> <message>%s </message> <version>%s </version>\
       </server>" % (time.ctime(),req.content_type,submit,sys.version)
    return s

You would need a different javascript pattern/design if you plan to a have web-page that simultaneously sends multiple Ajax request.

If you get the error “405 Method Not Allowed”, the python module is not processing the “POST request. This may be due to the security configuration of the Web server. You could try changing your “POST” to a “GET” in the javascript. If you get a XML response error it may be because mod_python is not running properly.

The housing of domestic bees

The housing of domestic bees

Bees are industrious, organised and intelligent. Instead of explaining this in an article, I submit the following photo to the reader. See how those bees are watching me whilst I was checking out their health by opening their hive.

Like other Fauna and Flora, bees have been domesticated. The environment of domestic bees were changed by the introduction of artificial hives. Most honey bees are managed in in boxes where they store their honey in rectangular combs that are easily harvested. Feral colonies (bee colonies their native habitat) are not the norm. Whilst a lot of feral bees have been decimated by pests like the  Varroa mite, feral colonies have proven to be more resistant to pests than domesticated bees.

Man-made beehives normally adopt the Langstroth design. Bees store their honey and babies in frames. About nine of these frames are placed in boxes. A number of these boxes are stacked on a “bottom board”.

hive structure

Bees normally land on the bottom board and walk into the hive entrance at the bottom.

At the end of spring, bee keepers empty about half the honey out of each hive. Some commercial bee-keepers can be mercenary about the amount of honey they harvest. To ensure that bees make it through winter, bee-keepers feed the bees sugar water or an equivalent. This is like raiding the fruit and veggies and replacing it McDonalds food.

Varroa mites are like big ticks. If you were the size of a bee, a Varroa mite l;arger than a rat would be sucking your blood. A bee with more than one Varroa mite does not last long. Most bee-keepers use insecticides to control the amount of Varroa.

Bees will clean out their hives by removing dead bees, waste, the odd Varroa mite and other debris from the combs. As bottom boards are flat, the debris normally accumulate there. The beehive entry point therefore become the accumulation point of the hive debris.

bee movement pattern

Live mites often end up on the bottom board with the debris, where they can re-attach themselves to bees that walk in and out of the hive.

Some bee colonies spend more effort on hive hygiene by cleaning out their hives. It is well known that bees that are hygienic are more resistant to Varroa mite and pests.

Many scientist say there is no single cause to “colony collapse disorder”. “Colony collapse disorder” seems to be related to infections and Varroa.

The hive can be seen as an ecosystem that include bees and bee pests. The introduction of the artificial hive has changed this ecosystem, allowing pests to evolve their behavior to gain a competitive advantage.
Unhygienic hives are a breeding ground for many illnesses and may be the cause of colony collapse disorder (just like damp, drafty houses cause many illnesses in humans)

One method to improve the hygiene design of bee boxes, is to install a bottom board that allow debris (including live Varroa mites) to fall through onto the ground.

I have made such a bottom board,- as shown in the picture.

better bottom boards

The Purpose of Life

The Purpose of Life

I have told this story (truth) to friends, and I thought it was time to write it down. I still believe in this purpose after all these years.

So, what is the purpose of life? The best way to explain this, is by taking you on a quick route tour of the path I took. I suspect the answer may apply to you as well.

I agonized about this in my youth poring over books, trying to understand philosophers like Jung and Satre.   I didn’t find any answer that I could believe in, so I concluded it was up to me to figure out for myself.

The purpose of Life was too hard to derive analytically, so I decided I needed simple building blocks to derive this truth. Maybe I could build a simple system of truths and extrapolate that to my purpose.

So I looked at my cat and thought, what is the cat’s purpose of life?
I thought for a while and didn’t get very far.   I was not doing very well was I?
So as you do with analysis I moved onto my dog;- what is the dog’s purpose of life?  I thought for a while and didn’t get very far. Shit, I was not doing very well was I?

Then it struck me, the purpose for dog was somehow in being a dog, and the purpose of the cat is somehow in it’s catness. If the cat tried to be a dog, and tried to chase after cars and bark, it would be an unfulfilled silly cat.
And if the dog tried to be a cat by climbing up trees and slink under the house, it would be a pretty unfulfilled dog.

So, the cat’s purpose in life is tied into its catness, and the purpose of the dog is tied into its dogness.

The cat needs to be as much of a cat as it can be, and the dog needs to be as much of a dog as he can be.

Right, so I need to be as much of of a human as I can be – but that does not say enough.

Specifically, I need to as much Kris as I can be. I need to express my Kris-ness as much as I can – In that lies my purpose.

So who-ever you are, your purpose in live is to express your <your name here>-ness.   Be as much yourself as you can be, even if that means you have to march to the beat of a totally different drum.

The terrain of life

The terrain of life

We are unbalanced, as it is difficult to be true to ourselves.

We are taught to live normative lives. In your first years you are taught the difference between right and wrong. If you are allowed to rob a home, others are allowed to rob your home.  So the laws and morals of society protects you.

These norms extend to the rules at work, the quirky directives of your boss, the politics at work. We accept the norms, the laws of the land, the morals of our church and we attempt to live according to these.

This is “life on rails”. A person living on rails can be successful. For example, a politician can attain the powers of office.

To live outside the norms of society, is to invite adversity.   Norms are established because they are enforced. Forget about breaking the law. Try to be strange at work. Your colleagues will be afraid to associate you, lest they may be considered strange as well.

If you do not conform to norms, you lead a “life in the wilderness”.   A life in the wilderness has paths less travelled, so you may often find yourself in the brambles.

This does not mean you cannot be successful in your own way.   Martin Luther King went against the norms of his time.   Vincent van Gogh lead a life in the wilderness. In an act of love Vincent presented his ear to a “lady” he cherished, and he was shunned for that.   A person leading a life in the wilderness is not necessarily a “good” or “bad” person, as they may be living a life outside norms of “good” or “bad”.

You may not want to gift your ear, but you will have private thoughts, fantasies. If you do not express your real self, you may be somewhat on rails.

So by the words of William Shakespeare;- Those who want “to be” choose a life in the wilderness, and those that choose “not to be” are on rails.

It may be refreshing to get off at the stations once in a while, and go tramping into the wilderness a bit …

Intelligence and image processing

Intelligence and image processing

Intelligence is a fascinating topic as we are defined by our thoughts. And it is hard to create an artificial intelligence (if there is artificial intelligence, there must be artificial stupidity, and there is).

To some extent intelligence represent the ability to recognise patterns. Recognition of faces, worldwide trends, and scientific discovery are all underscored by this ability.

Pattern recognition requires the means to abstract a domain into characteristics that are recognisable. So, if we posses many methods to synthesize or abstract, and we can integrate these methods;- can we create artificial intelligence?

I dont know, but I have created a simple pattern abstraction of images. It can be used to stitch panoramic photos. Find it here.

Why the NZ Green party has not grown

Why the NZ Green party has not grown

There has been a revival of the the political left in the last decade.

It seems like everybody, even political parties to the right of the political spectrum are stating that we should take care of our environment.

The American agenda of self-interest and the consequent destructiveness they wreak on worldwide communities has become more apparent.

We have seen increasing coverage on the agendas Global corporations. Global corporations do not have a conscience, or differently stated, their conscience is to make a profit for their shareholders. This profit motive promotes greed, consumerism and materialism. The World trade organisation has also increasingly been exposed as a lobby tool for global corporations.

Many individuals are sharing knowledge, opinions and information to an extent that have never happened before. The thriving Open Source movement is an expression of this sharing and collaboration.

One would have thought that the NZ Green party would thrive in this environment. Yet their growth has been stagnant as they have not been able to capitalise on these trends.

And here is the reason: The NZ Green party is not a true promoter of progressive ideals and as such they do not have a core support base.

On the one hand the Greens buy into the the above ideals and on other hand they buy into divisive ideologies such as bi-culturalism. For those of you not familiar with NZ politics, bi-culturalism is the belief that there are two classes of people in New Zealand (Maori and non-Maori). Bi-culturalism stems from guilt created by the destructiveness during British colonialism. To compensate for the destructiveness during that period, we have invented policies based on ethnicity. These policies have become politically correct, but true progressives are not at ease with discrimination along ethnic lines.