Rob Murrer

Euclid’s GCD

In my Discrete Mathematics course we spent a lot of time with the RSA encryption scheme and modulo arithmetic. This is an implementation of an essential part of RSA which is the calculation of the modulo multiplicative inverse. I originally wrote this function to use the long long data type in C, but the precision wasn’t great enough to work with a large key size. I rewrote my original code with the GNU Multiple Precision Arithmetic Library (GMP). This library actually includes a multiplicative inverse look up so this function I wrote is redundant.

The algorithm for finding the multiplicative inverse is Euclid’s Greatest Common Divisor Algorithm. It is recursive and this implementation outputs a table similar to how a person would perform it with a pencil and paper manually.

EuclidsGCD.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// This is an old function that was used before the port to GMP
// It is here to show how the GCD function below used to look. 
// Unfortunately I lost the original version of it after the port.
// The GMP really makes the code alot harder to read
long long powmod(long long base, long long power, long long mod) {

    //2^7 = 2^2 * 2^2 * 2^2 * 2^1
    long long result = 1;

    long long i;
    for(i=0; i < power/2; i++) {
        result *= base*base%mod;
    }

    //odd power?
    if (power%2 != 0)
        result *= base;

    return result%mod;
}

//GMP Port:
//data structures
typedef struct gcdNode {
    mpz_t j;
    mpz_t k;
    mpz_t q;
    mpz_t r;
    mpz_t x;
    mpz_t y;
    struct gcdNode* next;
} gcdNode;

typedef struct gcdReturn {
    mpz_t mult_inv;
    mpz_t gcd;
} gcdReturn;

//function
gcdReturn* gcdCalc(mpz_t j, mpz_t k) {

    gcdNode* help_ptr = (gcdNode*)malloc(sizeof(gcdNode));
    mpz_init_set(help_ptr->j, j);
    mpz_init_set(help_ptr->k, k);
    mpz_inits(help_ptr->q, help_ptr->r, help_ptr->x, help_ptr->y, NULL);
    help_ptr->next = NULL;

    //calculate gcd by using euclids division algorithm
    while (1) {

        //multiplier and remainder
        mpz_divexact(help_ptr->q, help_ptr->k, help_ptr->j);
        mpz_mod(help_ptr->r, help_ptr->k, help_ptr->j);

        //remainder 0? 
        if (mpz_cmp_ui(help_ptr->r, 0) == 0) break;

        //create next row
        gcdNode* new_ptr = (gcdNode*)malloc(sizeof(gcdNode));
        mpz_inits(new_ptr->j, new_ptr->k, new_ptr->q, new_ptr->r, new_ptr->x, new_ptr->y, NULL);
        mpz_set(new_ptr->j, help_ptr->r);
        mpz_set(new_ptr->k, help_ptr->j);

        //link and traverse
        new_ptr->next = help_ptr;
        help_ptr = new_ptr;

    }//gcd calc loop

    //save gcd
    gcdReturn* returnVal = (gcdReturn*) malloc(sizeof(gcdReturn));
    mpz_init_set(gcdReturn->gcd, help_ptr->j);

    //set intial x & y values for last row in table
    mpz_set_ui(help_ptr->x, 1);
    mpz_set_ui(help_ptr->y, 0);

    //column headings
    dbg("j\tk\tq\tr\tx\ty");

    //fill in the x & y columns of the table
    while (help_ptr->next != NULL) {

        gmp_printf("%Zd\t%Zd\t%Zd\t%Zd\t%Zd\t%Zd\n", help_ptr->j, help_ptr->k, help_ptr->q, help_ptr->r, help_ptr->x, help_ptr->y);

        gcdNode* next_ptr = help_ptr->next;

        mpz_t numerator, kx, one;
        mpz_inits(numerator, kx, one, NULL);
        mpz_set_ui(one, 1);
        mpz_mul(kx, next_ptr->k, help_ptr->x);
        mpz_sub(numerator, one, kx);
        mpz_divexact(next_ptr->x, numerator, next_ptr->j);
        mpz_set(next_ptr->y, help_ptr->x);

        //cleanup
        mpz_clears(numerator, kx, one, help_ptr->j, help_ptr->k, help_ptr->q, help_ptr->r, help_ptr->x, help_ptr->y, NULL);
        free(help_ptr);

        help_ptr = next_ptr;
    }

    gmp_printf("%Zd\t%Zd\t%Zd\t%Zd\t%Zd\t%Zd\n", help_ptr->j, help_ptr->k, help_ptr->q, help_ptr->r, help_ptr->x, help_ptr->y);

    //set gcd
    //take care of negative multiplicative inverse
    mpz_init(returnVal->mult_inv);
    if (mpz_sgn (help_ptr->x) < 0)
        mpz_add(returnVal->mult_inv, help_ptr->x, help_ptr->k);
    else
        mpz_set(returnVal->mult_inv, help_ptr->x);

    return returnVal;
}

KnightsDepot

This was part of a recursion assignment in Computer Science I taught by Dr. Cazalas at UCF.

Assignment Specification

You are working on an engineering project with other students and are in need of 2x4s (2 by 4’s) of various lengths. Thankfully, UCF has its very own “Depot” store: KnightsDepot…so you don’t have to drive far. Unfortunately, KnightsDepot only carries 2x4s in fixed lengths. So your team will have to purchase the 2x4s and then cut them as needed. Because of your tight college student budget, you want to buy the least number of 2x4s in order to cover the lengths requested by your team.

The recursive function you are designing will return the minimum number of 2x4s you need to purchase, in order to cover the lengths requested by your team. Example:

Array of 2x4 lengths requested by your team: { 6, 4, 3, 4, 1, 3 } Fixed length of 2x4s at KnightsDepot: 6 (so each purchased 2x4 has a length of 6) A possible arrangement of of 2x4s: { 6 } { 3, 3 } { 4, 1 } { 4 } Minimum number of 2x4s needed to purchase: 4

Approach to solving
-------------------
My initial thought to solve this was to use a "greedy" algorithm which simply makes the best possible choice for the next board so that no scrap is wasted.
This method of solving is certainly faster than the final solution, but it is possible for this method not to be the most efficient use of boards.
The correct solution was to permutate the order in which you bought the boards and do a simple in-order purchase and calculate if this order performed better than the previous.

``` c KnightsDepot.c
/*  precondition:   fin/fout are pointers to the input/output file
    postcondition:  calculates the minimum amount of boards needed for project
*/
void KnightsDepot(FILE *fin, FILE *fout) {

    //read in args
    int size, whole;
    fscanf(fin, "%d %d", &whole, &size);

    if (DEBUG) printf("Read in argument size: %d, whole: %d\n", size, whole);

    //need to DAM for board array
    int * boards = (int *) malloc(sizeof(int)*size);

    //read in boards
    int i;
    for (i=0; i < size; i++)
        fscanf(fin, "%d", &boards[i]);

    //begin solving
    if (DEBUG) printf("KnightsDepot:  \n");
    fprintf(fout, "KnightsDepot:  ");    

    //edgecase: if boards to be bought are zero then just print 0 and get out
    if (size == 0) { 
        fprintf(fout, "%d\n\n", 0);
        if (DEBUG) printf("\ntotal boards: %d\n\n", 0);
        return;
    }

    //for passing by reference into DepotPermuteAndCalc
    //setting value to -1 indicates no boards have been counted yet.
    int runningCount = -1;

    //recurse
    int total = DepotPermuteAndCalc(boards, size, 0, whole, &runningCount);

    fprintf(fout, "%d\n\n", total);
    if (DEBUG) printf("\ntotal boards: %d\n\n", total);

    //cleanup
    free(boards);

    return;
}


/*  precondition:   boards is the array of our board lengths of size size.  fixed is the range we are holding            
                    in place [0-fixed] while we permute. whole is the dimension of the boards at the store and
                    runningCount is a pointer which holds the value of the least amount of boards we purchased 
                    through all the permutations.
    postcondition:  returns the minimum number of boards needed for the project.
*/
int DepotPermuteAndCalc(int boards[], int size, int fixed, int whole, int *runningCount) {

    if (DEBUG) {
        printf("PermutateAndCalc() size:%d, fixed:%d, whole:%d, runningCount:%d\n", size, fixed, whole, *runningCount);
        int i;
        for (i=0; i<size; i++)
            printf("%d ", boards[i]);
        printf("\n");
    }

    //basecase 
    if (fixed == size) {
        //calculate number of boards needed for this permutation
        int count = DepotCalcBoards(boards, size-1, whole);

        //compare to past permuations or just set it to runningCount if this is first permutation (-1)
        if (*runningCount == -1 || count < *runningCount)
            *runningCount = count;
    }

    //permutate
    int i;
    for (i=fixed; i < size; i++) {

        swap(boards, fixed, i);
        DepotPermuteAndCalc(boards, size, fixed+1, whole, runningCount);
        swap(boards, fixed, i);
    }

    //return our lowest count
    return *runningCount;
}


/*  precondition:   boards is the array of our board lengths of size size.  whole is the dimension of the boards 
                    at the store.
    postcondition:  returns the number of boards needed doing a 'dumb' linear addition
*/
int DepotCalcBoards(int boards[], int size, int whole) {

    int i;
    int working = 0;

    //start at the end of the array and figure out how many boards we can get
    for(i=size; i >= 0; i--) {

        working += boards[i];

        //the boards divide evenly into the whole dimension
        if (working == whole) {

            //are we at the end of array?
            if (i == 0) return 1;

            //no so recurse
            else return 1 + DepotCalcBoards(boards, i-1, whole);
        }

        //we have to waste the rest of the board and recurse with current i as new size
        if (working > whole) return 1 + DepotCalcBoards(boards, i, whole);

    }

    //if we get this far then we have a stray cut that needs to be made
    return 1;
}


/*  precondition:   a is the position that will be put into b and vice-versa
    postcondition:  switches the values at index a and index b in the array
*/
void swap(int array[], int a, int b) {
    int temp = array[a];
    array[a] = array[b];
    array[b] = temp;
    return;
}
```

Loku

This project was born out of the desire to stream local content recorded over-the-air via my HD Homerun to my Roku devices in my home. There are a large number of components to this system and It was very interesting how they all could work together. It is an ongoing project and still requires some serious work, but it does work and my wife and I use it daily.

The project includes several pieces:

  • Ubuntu Linux Server
  • MythTV Backend for scheduling and recording of over the air TV
  • HandBrakeCLI for transcoding file to work on the Roku player
  • Django based local web application that keeps track of files for the Roku devices and serves XML data
  • Python script that exports metadata from MythTV and injects them into the Django application
  • Roku application written in Brightscript for selecting and viewing videos

Pictures

Server Closet

"Server Closet"

No house is complete without a server closet right?

Roku Channel

Roku Icon

Code

The bulk of this project is boiler plate code from the Roku SDK. The backend uses the Django Admin to add cover photos. The following script was the most labor intensive.

File /Users/rob/Desktop/blog/octopress/source/downloads/code/rokuimport.py could not be found

Orbit Simulator

This was a Physics I extra credit assignment that displays a system of objects in motion reacting to each others presence in accordance to Netwon’s Third Law. The algorithm was developed in a single function at first and used a spreadsheet to plot the path of the planet. After confirming that the method worked, I built a PyGame interface to display the graphics. The challenging part of this program was to display what was happening with the models in the simulation.

By developing a simple camera model that allows the user to change the position of the view and zoom. I also included a feature to keep a specific body in the center of the camera’s view port so that one could simulate our understanding of the solar system before the Copernican Revolution.

Videos

3 Bodies

Screenshots

Prototype

"Pyhon and excel prototype"

Application

Soure Code

The source is available on GitHub

TK Tile & Stone

This project is a brochure website that allows the business owner to display samples of its work and create an online presence. This project included several design iterations and a complete branding of the business. The scope of my involvement with this project included the website design, copy writing, logo design, and the programming of the website. By building the website to adhere to web standards and providing a semantic markup, the content is search engine friendly.

Screenshot

"Homepage Screenshot"

Live Version

View the completed website at http://tktilestone.com/

Problems With Type Submit in IE6/7

The goal was to build a search form that would appear to be one input element, but would include a small submit button on the end for accessibility reasons. I developed a something and started to test it in Internet Explorer. I ran into some issues.

Goal

Code

HTML
1
2
3
4
5
6
<form action="#">
    <div id="search">
        <input type="text">
        <button type="submit">Search</button>
    </div>
</form>
CSS
1
2
3
4
5
#search input   { float:left; width: 202px; height:18px; padding:2px;}
#search button  { float:left; overflow:hidden; text-indent:-9999em; height:24px; width: 17px; }
#search input   { border: 1px solid black; border-width: 1px 0 1px 1px; }
#search button  { border: 1px solid black; border-width: 1px 1px 1px 0;
                  background: #FFF url(mag.png) no-repeat center center; }

Result in IE6/7

This is because when you use a border on an input with the type=submit, it adds an extra border when the form is active. After struggling with several outline and border definitions with :focus, :active, :hover, as mentioned by a StackOverflow post, I decided to look around to see how other people solved this problem.

Twitter

Facebook

First I looked at Twitter. They simply use an anchor and is in my opinion a bad solution because it is completely worthless without javascript enabled. Facebook simply didn’t define a border on its submit and that seemed to work. Alas, that means I must add an extra element or hard-code it into my image. or I could use the input type image.

Final Solution

HTML
1
2
3
4
5
6
<form action="#">
    <div id="search">
        <input type="text">
        <input type="image" src="mag.png" id="search-submit" value="Search">
    </div>
</form>
CSS
1
2
3
4
#search input   { float:left; width: 202px; height:16px; padding:2px;}
#search input   { border: 1px solid black; border-width: 1px 0 1px 1px; }
#search #search-submit
                { border: 1px solid black; border-width: 1px 1px 1px 0; width:16px; height:16px;  }

This requires you to set the image inside the HTML which might be undesirable. Alternatively you could use a 1px transparent gif and set the background with CSS. I also solved the problem by adding an extra div and eliminating the border on the type=submit. I did not like that extra markup and I think the input type=image is a better solution.

Inline-Block vs Float for Vertical Alignment in Forms

This test examines the most consistent way to vertically align labels with input elements. The screen shots were done on Windows XP. Any feedback on this test would be appreciated.

Code

HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div class="container">

    <form action=#" class="formstest">
      <fieldset class="inlineblockforms">
          <legend>display:inline-block;</legend>
          <ul>
            <li><label>test</label><input type="text"></li>
            <li><label>test</label><input type="text"></li>
          </ul>
      </fieldset>

      <fieldset class="floatforms">
          <legend>float:left;</legend>
          <ul>
            <li><label>test</label><input type="text"></li>
            <li><label>test</label><input type="text"></li>
          </ul>
      </fieldset>
    </form>

  </div><!-- container -->
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.formstest fieldset
            { width: 350px; margin-bottom: 21px; float:left; margin-right:21px; }
.formstest ul
            { padding: 21px 21px 0px 21px; }
.formstest li
            { list-style-type: none; background-color:#EEE; border: 1px solid #000; margin-bottom:21px;}
.formstest input
            { width: 200px; padding:5px; }
.formstest label
            { width:50px; padding:5px; }
.inlineblockforms label
            { display:inline-block; vertical-align:middle; }
.inlineblockforms input
            { display:inline-block; }
.floatforms li
            { overflow:hidden;  width:100% /* ie6 haslayout fix */;}
.floatforms label, .floatforms input
            { display:inline; float:left; }

Renderings

Internet Explorer 6

Float method looks superior. But float method needs width:100%; to fix a haslayout bug. inline-block method looks terrible (it looks fine if you eliminate padding on label and input though)

Internet Explorer 7

Float method looks superior. inline-block has an excessive amount of spacing above the label.

Internet Explorer 8

Float method looks superior. Nearly identical except for a small amount of spacing above label.

Firefox 3.5

The rendering seems to be identical. Although when I run Firefox on Ubuntu, inline-block method renders superior.

Safari 4

Float method looks superior. Nearly identical except for a small amount of spacing above label.

Conclusion

For the most consistent rendering, use the float method for vertical alignment of labels in forms.

Sliding Door Inputs

Forms look different on every browser & operating system. To make a form input appear exactly the same across browsers, everything rendered by default by browser must be replaced. This example takes the common sliding doors technique and applies it to an input widget. This enables us to add a rounded border to the input.

HTML
1
2
3
4
5
6
7
<form class="sliding">
  <fieldset><legend>Sliding door inputs</legend>
    <ul>
      <li><label>One</label><span></span><input type="text"></li>
    </ul>
  </fieldset>
</form>
CSS
1
2
3
4
.sliding label   { float:left; width: 75px; height:21px; }
.sliding input   { float:left; width: 150px; height:21px; font-size:14px; padding-top:3px; border:0;                 outline:0; background: #FFF url('images/sliding-input.png') no-repeat top right; }
.sliding span    { float:left; height: 21px; width: 5px;
                   background: #FFF url('images/sliding-input.png') no-repeat top left;}

Rendering

Admin Theme

In my technical writing class the final project was to create a fictitious real world problem and solve it with what we had learned in the class. I chose to solicit a current client to switch from a WordPress based website to a custom Content Management System (CMS). I created a mock-up of what the Admin Panel would look like in the new CMS.

Screenshots

Dashboard

"Dashboard Screenshot" "Dashboard Screenshot w/ grid overlay" This is the overlay of a 960 grid and a 21px typsetting guide.

Subnavigation

"Subnavigation Screenshot"

Manage Table

"Browse Table Screenshot"

Create Product

"Create Product Screenshot"

Live version

A semi-working version of the theme is available here.

JQuery Scroller

In one of the previous iterations of this site I had a User Interface (UI) element that had a scrollable element that was using this code.

jquery.vscroll.plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
(function($){

$.fn.vscroll = function(options) {
  var opts = $.extend({}, $.fn.vscroll.defaults, options);
  
  return this.each(function() {

      var $scroll_item = $(this).find(opts.vscroll_toscroll);
      var $scroll_up = $(this).find(opts.vscroll_up);
      var $scroll_down = $(this).find(opts.vscroll_down);
      var vscroll_pos = 0;
      
      //hide DOWN  if the element if we don't need it 
      if ($scroll_item.height() <= $scroll_item.parent().height() ) { $scroll_down.css("visibility", "hidden"); }
                              
      $scroll_up.click(function(event) {
          if (vscroll_pos >= 0) { $scroll_up.css("visibility", "hidden"); }
          else { vscroll_pos += opts.vscroll_size; }
          $scroll_item.animate({top: vscroll_pos},"normal")
          if ($scroll_down.css("visibility") == "hidden") { $scroll_down.css("visibility", "visible"); }  //if hidden show DOWN element
          if (vscroll_pos >= 0) { $scroll_up.css("visibility", "hidden"); } // if visible hide UP element
           event.preventDefault();
          });
          
      $scroll_down.click(function(event) {
          vscroll_pos -=  opts.vscroll_size;
          $scroll_item.animate({top: vscroll_pos},"normal")
          if ($scroll_up.css("visibility") == "hidden") { $scroll_up.css("visibility", "visible"); }  //if hidden show UP element
          if ($scroll_item.height() <= ( Math.abs(vscroll_pos) + $scroll_item.parent().height() ) ) { $scroll_down.css("visibility", "hidden"); }  //hide DOWN - make sure don't scroll to far also checking containers height
          event.preventDefault();
      });
          
  });
};


$.fn.vscroll.defaults = {
   vscroll_toscroll: ".vscroll_toscroll",
   vscroll_up: ".vscroll_up",
   vscroll_down: ".vscroll_down",
   vscroll_size: 84
};

})(jQuery);

Usage

Scrollable Div
1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="vscroll">
    <div class="footer_scroller">
      <ul class="vscroll_toscroll">
            <li><a href="#">Lorem ipsum</a></li>
            <li><a href="#">Lorem ipsum</a></li>
            <li><a href="#">Lorem ipsum</a></li>
            <li><a href="#">Lorem ipsum</a></li>
            <li><a href="#">Lorem ipsum</a></li>
      </ul>
    </div>
    <a class="vscroll_up" href="#">Less</a>
    <a class="vscroll_down" href="#">More</a>
</div>

Then in your $(document).ready(function()) place $("#vscroll").vscroll();.

A live version soon.