More buffer flush while printing unsorted lists
More buffer flush while printing unsorted lists

--- a/include/common-template.inc.php
+++ b/include/common-template.inc.php
@@ -236,7 +236,7 @@
 }
 function trackEvent($category, $action, $label = "", $value = -1) {
   if (isAnalyticsOn()) {
-    echo "<script> _gaq.push(['_trackEvent', $category, $action".($label != "" ? ", $label" : "").($value != -1 ? ", $value" : "")."]);</script>";
+    echo "\n<script> _gaq.push(['_trackEvent', '$category', '$action'".($label != "" ? ", '$label'" : "").($value != -1 ? ", $value" : "")."]);</script>";
   }
 }
 ?>

--- a/labs/tripPlannerTester.kml.php
+++ b/labs/tripPlannerTester.kml.php
@@ -159,8 +159,7 @@
 					$regionTimes[] = $time;
 				}
 			}
-			flush();
-			ob_flush();
+			flush(); @ob_flush();
 			curl_close($ch);
 		}
 	}

--- a/schedule_viewer.py
+++ b/schedule_viewer.py
@@ -22,6 +22,9 @@
 
 
 import BaseHTTPServer, sys, urlparse
+from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
+from SocketServer import ThreadingMixIn
+import threading
 import bisect
 from gtfsscheduleviewer.marey_graph import MareyGraph
 import gtfsscheduleviewer
@@ -57,34 +60,8 @@
       return list(iterable)
     return simplejson.JSONEncoder.default(self, obj)
 
-# Code taken from
-# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425210/index_txt
-# An alternate approach is shown at
-# http://mail.python.org/pipermail/python-list/2003-July/212751.html
-# but it requires multiple threads. A sqlite object can only be used from one
-# thread.
-class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
-  def server_bind(self):
-    BaseHTTPServer.HTTPServer.server_bind(self)
-    self.socket.settimeout(1)
-    self._run = True
-
-  def get_request(self):
-    while self._run:
-      try:
-        sock, addr = self.socket.accept()
-        sock.settimeout(None)
-        return (sock, addr)
-      except socket.timeout:
-        pass
-
-  def stop(self):
-    self._run = False
-
-  def serve(self):
-    while self._run:
-      self.handle_request()
-
+class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
+    """Handle requests in a separate thread."""
 
 def StopToTuple(stop):
   """Return tuple as expected by javascript function addStopMarkerFromList"""
@@ -254,9 +231,11 @@
       parsed_params['time'] = int(round(float(parsed_params['time']),-2))
     paramkey = tuple(sorted(parsed_params.items()))
     if handler_name in self.cache and paramkey in self.cache[handler_name] :
-      print ("Cache hit for ",handler_name," params ",parsed_params)
+      print ("Cache hit for ",handler_name," params ",parsed_params, 
+		" thread ", threading.currentThread().getName())
     else:
-      print ("Cache miss for ",handler_name," params ",parsed_params)
+      print ("Cache miss for ",handler_name," params ",parsed_params, 
+               	" thread ", threading.currentThread().getName())
       result = handler(parsed_params)
       if not handler_name in self.cache:
         self.cache[handler_name] = {}
@@ -713,14 +692,13 @@
   t0 = datetime.datetime.now()
   schedule.Load(options.feed_filename)
   print ("Loaded in", (datetime.datetime.now() - t0).seconds , "seconds")
-  server = StoppableHTTPServer(server_address=('', options.port),
+  server = ThreadedHTTPServer(server_address=('', options.port),
                                RequestHandlerClass=RequestHandlerClass)
   server.key = options.key
   server.schedule = schedule
   server.file_dir = options.file_dir
   server.host = options.host
-  server.feed_path = options.feed_filename
-  
+  server.feed_path = options.feed_filename  
 
 
   print ("To view, point your browser at http://localhost:%d/" %

file:a/stop.php -> file:b/stop.php
--- a/stop.php
+++ b/stop.php
@@ -95,6 +95,7 @@
 	echo '</p>';
 	echo '<p class="ui-li-aside"><strong>' . midnight_seconds_to_time($row[0]) . '</strong></p>';
 	echo '</a></li>';
+        flush(); @ob_flush();
 }
 if (sizeof($trips) == 0) echo "<li> <center>No trips in the near future.</center> </li>";
 echo '</ul></div>';

--- a/stopList.php
+++ b/stopList.php
@@ -31,6 +31,7 @@
 		foreach ($suburbs as $suburb) {
 			if (startsWith($suburb, $_REQUEST['firstLetter'])) {
 				echo '<li><a href="stopList.php?suburb=' . urlencode($suburb) . '">' . $suburb . '</a></li>';
+				flush(); @ob_flush();
 			}
 		}
 	}
@@ -101,6 +102,7 @@
 					}
 					echo bracketsMeanNewLine(trim(preg_replace("/\(Platform.*/", "", $row[1])) . '(' . sizeof($stopsGrouped["stop_ids"]) . ' stops)');
 					echo "</a></li>\n";
+					flush(); @ob_flush();
 					$stopsGrouped = Array();
 				}
 				else {
@@ -113,6 +115,7 @@
 					}
 					echo bracketsMeanNewLine($row[1]);
 					echo "</a></li>\n";
+					flush(); @ob_flush();
 				}
 			}
 			else {

file:a/trip.php -> file:b/trip.php
--- a/trip.php
+++ b/trip.php
@@ -40,12 +40,14 @@
 foreach ($routetrips as $othertrip) {
 	echo '<a href="trip.php?tripid=' . $othertrip[1] . "&routeid=" . $routeid . '">' . midnight_seconds_to_time($othertrip[0]) . '</a> ';
 }
+flush(); @ob_flush();
 echo '</p><p><h2>Other directions/timing periods:</h2> ';
 $url = $APIurl . "/json/routesearch?routeshortname=" . rawurlencode($trips[1]->route_short_name);
 $json = json_decode(getPage($url));
 foreach ($json as $row) {
 	if ($row[0] != $routeid) echo '<a href="trip.php?routeid=' . $row[0] . '">' . $row[2] . ' (' . ucwords($row[3]) . ')</a> ';
 }
+flush(); @ob_flush();
 echo '  <ul data-role="listview"  data-inset="true">';
 echo '<li data-role="list-divider">' . midnight_seconds_to_time($times[0]) . '-' . midnight_seconds_to_time($times[sizeof($times) - 1]) . ' ' . $trips[1]->route_long_name . '</li>';
 $stopsGrouped = Array();
@@ -62,6 +64,7 @@
 			echo '<p class="ui-li-aside">' . midnight_seconds_to_time($stopsGrouped['startTime']) . ' to ' . midnight_seconds_to_time($stopsGrouped['endTime']) . '</p>';
 			echo bracketsMeanNewLine($row[1]);
 			echo '</a></li>';
+                        flush(); @ob_flush();
 			$stopsGrouped = Array();
 		}
 		else {
@@ -70,6 +73,7 @@
 			echo '<p class="ui-li-aside">' . midnight_seconds_to_time($times[$key]) . '</p>';
 			echo bracketsMeanNewLine($row[1]);
 			echo '</a></li>';
+                        flush(); @ob_flush();
 		}
 	}
 	else {

--- a/tripPlanner.php
+++ b/tripPlanner.php
@@ -62,6 +62,7 @@
 			echo '<li>';
 			processLeg($legNumber, $leg);
 			echo "</li>";
+                        flush(); @ob_flush();
 		}
 		echo "</ul>";
 	}