R2DeltaSquared

    • Long Division in Common Lisp

      • 10/14/12
      • 3:55PM
      ;Here is my version in Common Lisp
        ;Supply your own flatten function
        ;or borrow one from let-over-lambda or something
        ;http://letoverlambda.com/lol.lisp
      
        (defun long-div (dividend divisor depth)
          (cond
           ((> depth 0)
            (flatten (list
                      (truncate (/ dividend divisor))
                      (long-div (* 10 (mod dividend divisor))     
                       divisor (- depth 1)))))
           (t ())))
      
    • Getting Started with OpenCV

      • 07/08/12
      • 5:59AM

      I started working through the examples for OpenCV. So far I am impressed at how fun, easy and fast it is. To install openCV on my mac I typed:

      SystemName% brew install opencv
      

      This time hombrew just worked and installed the library for me. Then I made a simple image viewer example. The first step was to make a cmake package that looks like this:

      PROJECT( imageView_proj )
      FIND_PACKAGE( OpenCV REQUIRED )
      ADD_EXECUTABLE( imageView imageView.cxx )
      TARGET_LINK_LIBRARIES( imageView ${OpenCV_LIBS} )
      

      It is important to name this file CMakeLists.txt. Next I write the code for imageView.cxx:

      #include 
      
      int main( int argc, char** argv ){
        IplImage* img = cvLoadImage( argv[1] );
        cvNamedWindow( argv[1], CV_WINDOW_AUTOSIZE );
        cvShowImage( argv[1], img );
        cvWaitKey(0);
        cvReleaseImage( &img );
        cvDestroyWindow( argv[1] );
      }
      

      I build with cmake then make like normal and I have a nicely fast native looking image viewing program.

    • inPulse Internet time

      • 06/30/12
      • 7:10AM

      I made a watch face for the inPulse programmable watch. The watch SDK is c based and nice. All I do is get the local time, and compute the swatch internet time based on it. The base firmware is pretty smart and handles updates, and time-setting, and handling communications for me, so I can concentrate on making a nice simple display. I based my program on some of the example code provided by the SDK. The code I used is here:

      /**
       * Copyright (C) 2011, Allerta Inc.
       * Author: Jon Bennett (jon@allerta.ca)
       *
       * Permission to use, copy, modify, and/or distribute this software for  
       * any purpose with or without fee is hereby granted, provided that the  
       * above copyright notice and this permission notice appear in all copies.  
       *  
       * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL  
       * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED  
       * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR  
       * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES  
       * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,  
       * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,  
       * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS  
       * SOFTWARE.
       * 
       * Modifed by David Rosenfeld June 2012
       **/
      
      #include 
      #include 
      #include 
      #include 
      
      // It is daylight savings time so do this
      #define TIMEZONE_OFFSET -1
      
      // Forward Declaration
      void handle_button_causing_wakeup();
      
      // Ask the clock for the internet time
      int get_internet_time()
      {
          int hour;
          int min;
          int sec;
          int beat;
      
          struct pulse_time_tm now;
          pulse_get_time_date(&now);
          hour = now.tm_hour;
          min = now.tm_min;
          sec = now.tm_sec;
      
          beat = ((sec + (60 * min) + ((hour + 1 + TIMEZONE_OFFSET) * 3600)) / 86.4);
          if(beat > 1000){
              beat = beat - 1000;
          }
          return beat;
      }
      
      // This function is called once after the watch has booted up
      // and the OS has loaded
      void main_app_init()
      {
          draw();
          // Schedule the processor to go to sleep in 5 seconds
          pulse_update_power_down_timer(10000);
      
          // Register a callback for the woke_from_button event
          pulse_register_callback(ACTION_WOKE_FROM_BUTTON, &handle_button_causing_wakeup);
      }
      
      void handle_draw_event(int timeout)
      {
        draw();
        pulse_register_timer(timeout, &handle_draw_event, timeout);
      }
      
      // Now Draw!
      void draw()
      {
          int hour;
          int min;
          int sec;
      
          struct pulse_time_tm now;
          pulse_get_time_date(&now);
          hour = now.tm_hour;
          min = now.tm_min;
          sec = now.tm_sec;
      
          pulse_oled_set_brightness(100);
          pulse_blank_canvas();
          int beat;
          beat = get_internet_time();
          printf("\n\n    @%d\n", beat);
          printf("\n\n    %d:%d", hour, min);
      
      }
      
      // This function is called when the button is used to wake the processor
      void handle_button_causing_wakeup()
      {
          // Set the screen brightness to full
          pulse_oled_set_brightness(100);
      
          // Schedule the processor to go to sleep in 9 seconds
          pulse_update_power_down_timer(9000);
          draw();
      }
      
      void main_app_handle_button_down()
      {
      
      }
      
      void main_app_handle_button_up()
      {
      
      }
      
      // Main loop. This function is called frequently.
      // No blocking calls are allowed in this function or else the watch will reset.
      // The inPulse watchdog timer will kick in after 5 seconds if a blocking
      // call is made.
      void main_app_loop()
      {
      
      }
      
      // This function is called whenever the processor is about to sleep (to conserve power)
      // The sleep functionality is scheduled with pulse_update_power_down_timer(uint32_t)
      void main_app_handle_doz()
      {
          isAlive = false;
          // Gradually turn down the screen brightness, creating a fade effect
          for (int i = 100; i >= 0; i-=6) {
              pulse_oled_set_brightness(i);
              pulse_mdelay(60);
          }
      }
      
      // Prints a status message to the screen when bluetooth is connected or disconnected
      void main_app_handle_hardware_update(enum PulseHardwareEvent event)
      {
      
      }
      
    • Vaguely Remembering C

      • 06/10/12
      • 7:05AM

      I used to program in C and enjoy it. It has been quite a while. Yesterday I found the book Practical C by Steve Oualline. It is a good read so far, it is nice to see clarity and style emphasised in a book. So far the material is pretty standard. I flew through to chapter 4 where things started to get interesting. C strings and Malloc are always a good way to spend a Sunday. The point of the code is to print out HELLO in large friendly letters made with the * character. Here is my solution:

      
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      /*****************************************************
       * scanline.c by David Rosenfeld
       * A solution to problem 4-2 and 4-4 of 
       * Practical C found on page 62
       * This program breaks up each character into a 
       * "Scanline" I loop over 7 scanlines and print out
       * the "string" for each character.
       *****************************************************/
      
      /*****************************************************
       * block_H prints out scanline of a block h
       * Input: int scanline, the row number to display 
       *****************************************************/
      char* block_H(int scanline){
        scanline = scanline % 7;
        char *output = malloc(7);
      
        if(scanline == 3){
          strcpy(output,"***** ");
            } else {
          strcpy(output, "*   * ");
        }
        return output;
      }
      
      /*****************************************************
       * block_E prints out a block e
       *****************************************************/
      char* block_E(int scanline){
        scanline = scanline % 7;
        char *output = malloc(7);
      
        if(scanline == 0 || scanline == 3 || scanline == 6){
          strcpy(output,"***** ");
        }else {
          strcpy(output,"*     ");
        }
        return output;
      }
      
      /*****************************************************
       * block_L prints out a block L
       *****************************************************/
      char* block_L(int scanline){
        scanline = scanline % 7;
        char *output = malloc(7);
      
        if(scanline == 6){
          strcpy(output,"***** ");
        }else {
          strcpy(output,"*     ");
        }
        return output;
      }
      
      /*****************************************************
       * block_O prints out a block O
       *****************************************************/
      char* block_O(int scanline){
        scanline = scanline % 7;
        char *output = malloc(7);
      
        if(scanline == 6 || scanline == 0){
          strcpy(output," ***  ");
        }else {
          strcpy(output,"*   * ");
        }
        return output;
      }
      
      /*****************************************************
       * The Main Entry point
       *****************************************************/
      int main()
      {
        int lcv = 0;
        for (lcv = 0; lcv < 7; lcv++) {
          printf("%s%s%s%s%s\n", 
             block_H(lcv), 
             block_E(lcv), 
             block_L(lcv), 
             block_L(lcv), 
             block_O(lcv));
        }
      }
      

      The output looks like this:

      *   * ***** *     *      ***  
      *   * *     *     *     *   * 
      *   * *     *     *     *   * 
      ***** ***** *     *     *   * 
      *   * *     *     *     *   * 
      *   * *     *     *     *   * 
      *   * ***** ***** *****  ***  
      

      So in not to long a time I wound up re-learning about allocating memory from the stack and passing around references. I should really store those variables and free all the memory later, but the program exits before that would be relevant.

    • Building an Application Indicator clock in Python

      • 06/09/12
      • 5:07AM

      So I build an app for Ubuntu that displays the current Swatch Internet time. The code is pretty short so I figured I would share it here.

      every application needs an icon. I made a SVG that looks like this:

      
      
       
        
         
          image/svg+xml
          
          
         
        
       
       
          @
        
       
      

      I stored this in ~/bin where I keep custom tools and the like.

      Next I made a very short python app that looks like this:

      #!/usr/bin/env python
      import sys
      import gtk
      import appindicator
      import time
      
      PING_FREQUENCY = 1 # seconds
      
      class Clock:
          def __init__(self):
              self.ind = appindicator.Indicator("new-swatch-indicator",
                                                 "~/bin/at.svg",
                                  appindicator.CATEGORY_APPLICATION_STATUS)
      
              self.ind.set_status(appindicator.STATUS_ACTIVE)
              self.ind.set_attention_icon("new-messages-red")
              self.menu_setup()
              self.ind.set_menu(self.menu)
      
          def menu_setup(self):
              self.menu = gtk.Menu()
      
              self.quit_item = gtk.MenuItem("Quit")
              self.quit_item.connect("activate", self.quit)
              self.quit_item.show()
              self.menu.append(self.quit_item)
      
          def main(self):
              gtk.timeout_add(PING_FREQUENCY * 1000, self.check_time)
              gtk.main()
      
          def check_time(self):
              now = time.gmtime()
              hour = now.tm_hour
              mn = now.tm_min
              sec = now.tm_sec
              update = "%d" % (((sec + (60 * mn) + ((hour + 1) * 3600)) / 86.4) % 1000)
              self.ind.set_label(update)
              gtk.timeout_add(PING_FREQUENCY * 1000, self.check_time)
      
          def quit(self, widget):
              sys.exit(0)
      
      if __name__ == "__main__":
          indicator = Clock()
          indicator.main()
      

      The code sets a 1 second timeout, pulls the current UTC and then displays it in a label. I added some boilerplate code to handle exiting the application via a menu, and was done. Easy!

    • Gentoo |- Arch

      • 05/31/12
      • 7:19PM

      I moved this site to a new host and operating system. Hello Arch Linux!

    • Probability and Non-Transitive Dice

      • 03/01/12
      • 6:34PM

      Today I wrote a program to analyse the properties of a set of "Non-Transitive" dice.

      Cross makes a list of lists of all the possible combinations of elements of those lists. Left Side Wins takes two lists representing sides of dice, or sums of sides of dice, and counts the number of times the left side wins.

      The code looks like:

      import collections
      
      blue = [2,2,2,7,7,7]
      magenta = [1,1,6,6,6,6]
      olive = [0,5,5,5,5,5]
      red = [9,4,4,4,4,4]
      yellow = [3,3,3,3,8,8]
      d6 = [1,2,3,4,5,6]
      
      t1 = [1,2]
      t2 = [3,4]
      
      def iterablep(x):
          return isinstance(x, collections.Iterable)
      
      def wrap(lst):
          return [[x] if not iterablep(x) else x for x in lst]
      
      def flat(x):
          return [item for sublist in x for item in sublist]
      
      def flatten(x):
          return flat(wrap(x))
      
      def cross(a, b):
          return [[x, y] for x in a for y in b]
      
      def left_side_wins(left, right):
          return len([x for x,y in cross(left, right) if x > y])
      
      def debug(left, right):
          return [[x,y] for x,y in cross(left, right) if x > y]
      
      def twice(x):
          return map(sum, cross(x,x))
      
      def triple(x):
          return map(sum, map(flatten,cross(cross(x,x),x)))
      
      def quad(x):
          return twice(twice(x))
      
      def report(x,y):
          games = len(cross(x,y))
          wins = left_side_wins(x,y)
          pwins = float(wins) / float(games) * 100
          print "The left side won %i times out of %i matches" % (wins,games)
          print "That is %f4 percent" % pwins
      
    • More Functional Python Tricks

      • 02/01/12
      • 5:25PM

      I finally finished chapter two of Think Stats. I found some more functional sytax in python. The reduce function is quite handy. Say you have a dictionary pmf that maps a key x to a probability px and you want to find the mean of the set stored in pmf. The calculation would be:

      
      mu = reduce(lambda x_0, x_1: x_0 + x_1, [px * x for x, px in pmf.items()])
      
      

      Now python has a built in sum function, so the lambda is not the clearest way to express this. The lambda notation gives us the flexibility to reduce using a different aggregate function like x*y for instance. In this case better way to do the calculation would be say:

      
      mu = sum([x * px for x,px in pmf.items()])
      
      

      That is getting pretty close to the TeX notation for the actual formula:

      
      \mu=\sum_{i}p_ix_i
      
      
    • More Thinking about Statistics

      • 01/31/12
      • 4:13PM

      Tonight I made it further into Think Stats. The best thing I learned about that it is possible to use a lambda to tell sorted what field to sort by.

      If you have a dictionary d and you want to order it by value the python code to get the sorted list is:

      import operator
      sorted(d.items(), key=lambda value: value[1])
      


      If you want the largest value first the code would be:

      sorted(d.items(), key=lambda value: value[1], reverse=True)
      


      I used this to find the mode of a provided histogram.

      What I like about this syntax is that it allows me to compose sorts into a list comprehension, removing unwanted free variables and loop constructs from my code.

    • Installing Matplotlib on OS X Lion — the Homebrew Challenge

      • 01/30/12
      • 5:29PM

      I learned a lot about the default python installs on OSX, more about the homebrew package manager, and the intricacies of building matplotlib under OSX.

      The problem stems from some incompatibility between gcc 4.2 and LLVM. The libraires that matplotlib need compile under gcc 4.2, sadly they don't compile under LLVM yet. Apple switched to using LLVM exclusively which makes building all the prerequisites for mathplotlib interesting.

      So at the moment if you are wanting to get all the code from Think Stats working on your shiney new Macbook, be sure get a working copy of GCC 4.2 first. Then build the Github version of matplotlib.