Here is the pickling and cookie webserver example using webpy that I presented in tutorial:
#!/usr/bin/env python
import os
import web
from pickle import load, dump
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
# global session store & session id
SESSION_COUNT = 0
SESSIONS = {}
# methods to save & load data to files to persist
# session changes across restarts & crashes
data_fn = 'data.pkl'
def save_data():
fp = open(data_fn, 'w')
dump( (SESSIONS, SESSION_COUNT) , fp)
fp.close()
def load_data():
if not os.path.isfile(data_fn): return
global SESSIONS, SESSION_COUNT
fp = open(data_fn, 'r')
SESSIONS, SESSION_COUNT = load(fp)
fp.close()
# restore our session data
load_data()
def parse_cookies():
cookies_str = web.ctx.env['HTTP_COOKIE']
return dict([ c.strip().split('=')
for c in cookies_str.split(';')])
class Index(object):
def GET(self):
web.header('Content-Type','text/html')
session = {}
# see if the user has our cookie already
if 'HTTP_COOKIE' in web.ctx.env:
cookies = parse_cookies()
for name, val in cookies.items():
web.debug('got cookie: %s = %s' % (name, val))
# grab the session based on the user's cookie
if 'session_id' in cookies:
web.debug('got session id')
session = SESSIONS[cookies['session_id']]
# check if we got a session, if not create a new one
if not session:
web.debug('missing session, creating new session')
global SESSION_COUNT
expires_date = 'Fri, 11-Dec-2010 11:59:59 GMT'
web.header('Set-Cookie', 'session_id=%s;'
' expires=%s;'
% (expires_date, SESSION_COUNT))
SESSIONS[str(SESSION_COUNT)] = session
SESSION_COUNT += 1
# update the session
session['visits'] = session.setdefault('visits', 0)+1
save_data()
return (str(web.ctx.env) +
" You've visited %s times!"
% session['visits'])
def POST(self):
self.GET()
if __name__ == "__main__":
# run the webserver
app.run()
And here is the example of using cookies in Javascript:
// Cookies in Javascript
// The manual (tedious) way to set a cookie
document.cookie = ‘ppkcookie1=testcookie;' +
' expires=Thu, 2 Aug 2010 20:47:11 UTC; path=/’;
// The easy way
// from http://www.quirksmode.org/js/cookies.html
// if days == 0, the cookie expires when
// the user closes their browser
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = “; expires=”+date.toGMTString();
} else var expires = “”;
document.cookie = name+”=”+value+expires+”; path=/”;
}
function readCookie(name) {
var nameEQ = name + “=”;
var ca = document.cookie.split(‘;’);
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==’ ‘) c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,”“,-1);
}
I finally upgraded Ubuntu on my IBM T43 laptop. I was waiting for 9.04 because I heard lots of problems about the 8.04 to 8.10 upgrade process but then I found out I had to upgrade to 8.10 before I could get to 9.04 - so it goes.
The upgrade went smoother than my previous one though.
Sound:
sound stopped working but I was expecting this because PulseAudio caused this in the previous upgrade, luckily I found this tutorial on keeping the PulseAudio beast at bay which worked like a charm. Sadly, I no longer have on screen volume indicators when I change the volume using the extra keyboard keys but apparently this is a known issue and its a very minor annoyance.
Graphics:
All my Compiz settings seem to have been reset but that should only take a minute to re-configure. Also my text rendering settings were reset and everything looked too sharp and pixelated until I re-activated sub-pixel smoothing. On the plus side, I’m getting all the fancy effects without the proprietary ATI driver warning (I think they open-sourced their driver some time ago).
Networking:
Wireless didn’t work at first because apparently madwifi is a restricted driver now that I had to activate manually. This took me a minute to figure out since there was not auto-notification of this.
Firefox:
Firefox went from 3.0.8 to 3.0.10 and all my sessions and extensions seemed to survive perfectly except Tabkit which now won’t do its awesome hierarchical tab display or event the multi-row tab display. This is by far the most annoying issue since I’ve become addicted to hierarchical tabs. I also had to re-install Flash player and I couldn’t get the auto-prompted installer to work so I had to download the debian package direct from Adobe and run it.
Hibernation & Sleeping are finally working again.
Some simple programming examples of XSL & AJAX:
XSL (eXtensible Stylesheet Language) (see http://www.w3schools.com/xsl/ )
XSL is a style sheet language for XML documents. It describes how to display an XML document of a given type, so in a way it is similar to CSS but it adds a transformation language for XML documents called XSLT which is most often used to transform XML data into HTML but can transform between any two XML representations.
Example XML Data:
<?xml version=”1.0” encoding=”ISO-8859-1”?>
<?xml-stylesheet type=”text/xsl” href=”cdcatalog.xsl”?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
</catalog>
Example XSL Template (XSLT):
<?xml version=”1.0” encoding=”ISO-8859-1”?>
<xsl:stylesheet version=”1.0”
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>
<xsl:template match=”/”>
<html>
<body>
<h2>My CD Collection</h2>
<table border=”1”>
<tr bgcolor=”#9acd32”>
<th align=”left”>Title</th>
<th align=”left”>Artist</th>
</tr>
<xsl:for-each select=”catalog/cd”>
<tr>
<td><xsl:value-of select=”title”/></td>
<td><xsl:value-of select=”artist”/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Example Output: http://www.w3schools.com/xsl/cdcatalog_with_xsl.xml
(examples from http://www.w3schools.com/xsl/cdcatalog_with_xsl.xml )
In the exapmle above, the browser automatically converts xml into html. Typically, you would convert it yourself on the server side in Java or on the client side with Javascript.
on client: http://www.w3schools.com/xsl/xsl_client.asp
on server: http://www.w3schools.com/xsl/xsl_server.asp
AJAX (Asynchronous Javascript And Xml) (see http://www.w3schools.com/Ajax/default.asp )
AJAX allows you to get responses from the webserver without reloading the page. It can be used asynchronously or synchronously (asynch is best, define a handler function). Useful for form submission, live updates, changing page content on actions. It is quicker than page reloads because you send less data over the wire, you only have to load some parts of the page once and the rest can be fetched via AJAX. But be wary of breaking browser history and the back button which work by default with page reloads but require extra effort to work properly with AJAX.
AJAX Example:
<html>
<body>
<script type=”text/javascript”>
function ajaxFunction() {
// cross browser compatible XMLHttpRequest creation
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e) {
alert(“Your browser does not support AJAX!”);
return false;
}
}
}
// setup handler on success
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
document.myForm.time.value = xmlHttp.responseText;
}
}
// set request parameters (similar to form tag parameters)
xmlHttp.open(“GET”,”time.asp”,true); // 3rd is asynch
xmlHttp.send(null); // null because we aren’t using POST data
}
</script>
<form name=”myForm”>
Name: <input type=”text”
onkeyup=”ajaxFunction();” name=”username” />
Time: <input type=”text” name=”time” />
</form>
</body>
</html>
Or if you use jQuery: http://docs.jquery.com/Ajax/jQuery.ajax
function ajaxFunction() {
$.ajax({
type:’GET’,
url:’time.asp’,
success: function(responseText) {
document.myForm.time.value = responseText;
}
});
}
# Using Tomcat
# the following are commands to run on cdf
# download Tomcat
wget http://apache.sunsite.ualberta.ca/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.tar.gz
tar xzf apache-tomcat-6.0.18.tar.gz
# configure Tomcat
cd apache-tomcat-6.0.18
pico conf/server.xml
# change 8080’s to your assigned port number
# run Tomcat
bash
export JAVA_HOME=/local/packages/jdk1.6.0_07/
bin/startup.sh
# view http://localhost:PORT_NUMBER/ in your browser on cdf to test that it works
# get a sample application
cd webapps
wget http://tomcat.apache.org/tomcat-6.0-doc/appdev/sample/sample.war
# view http://localhost:PORT_NUMBER/sample in your browser on cdf to test that the sample app works
cd ../
# stop Tomcat
bin/shutdown.sh
// Cookies in Javascript
// The manual (tedious) way to set a cookie
document.cookie = ‘ppkcookie1=testcookie; expires=Thu, 2 Aug 2010 20:47:11 UTC; path=/’;
// The easy way
// from http://www.quirksmode.org/js/cookies.html
// if days == 0, cookie expires when the user closes their browser
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = “; expires=”+date.toGMTString();
} else var expires = “”;
document.cookie = name+”=”+value+expires+”; path=/”;
}
function readCookie(name) {
var nameEQ = name + “=”;
var ca = document.cookie.split(‘;’);
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==’ ‘) c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,”“,-1);
}
Running Apache
see my last tutorial post for instructions on running Apache
Google Alerts - get notified as Google updates its search index
TweetBeep - get notified as people tweet about you
BackType - get notified about comments on blogs and websites
might be useful for other wsgi projects
but are these Django specific..?
went through the Wikipedia Category on functional languages the other week and I found a bunch of interesting languages I want to check out
Scala JVM-based, java with less syntax + functional aspects
F# Microsoft’s .NET functional language (only interesting to me if the Mono implementation is complete)
Clojure JVM-based, may be good for concurrent programming
Boo python-like .NET language with Mono support
also stumbled upon some projects to build operating systems with functional languages: Kinetic, House, Singularity (found a Squeak one too: SqueakNOS)
maybe someday we’ll be running operating systems without side effects :P
to setup apache on cdf:
- grab the apache.tar.gz file from the Student Guide on the course site (there is also an apache.htm page which has instructions similar to these)
- extract apache.tar.gz to your home directory on cdf which creates a folder called apache
- run the apache/bin/start.sh file to start apache (and apache/bin/stop.sh to stop apache before you logout of cdf)
- when prompted use the port you have been assigned, see the CSC309-ports.txt file in the Student Guide
and voila! your personal apache server should be running, you can view it in a browser running on cdf at the address: http://localhost:[your port]/
the start.sh file you ran set up your apache environment in your home directory, not to be confused with the directories in the apache folder
so your html/css/js/xml/etc go in the htdocs folder in your home directory
also, here is the DHTMLX example page i showed in tutorial for your reference
(check out my DOM & Javascript post in case you missed that tutorial)
thought i might try to expand my horizons by following what famous researchers/professors in CS are thinking and doing via their blogs. you know Turing Award winners and such
alas, i could find practically none of them blogging… sad, the profession that creates the web isn’t fully utilizing it
in the end i’ve subscribed to Mark Guzdial’s Amazon blog and i found a number of natural language processing blogs but they didn’t spark my interest
anyone know of some blogs that i missed?