Category Archives: Discussion

Geocache idea.

So recently, I’ve been doing geocaching.  This is a lot of fun and great to do with children.  As I find caches, I get the feeling I should add one and I’ve thought it’d be fun to make it more nerdy than the sport already is.  The device I’m thinking of would incorporate using electronics in a waterproof box.  Obviously, as I build this, I’ll post it but the concept is simple…  A bit of PIC programming, some buttons and LED’s should be all that’s needed.  Then create a lock that will open with the right combination.  So press button A and a red light is on.  This should signal the next button and make about 4 stages of this and the lock is open.  Any geocachers have input on this?

An Idea.

Okay, this may be a rather dull post but here’s an idea and input would be helpful from those who’ve done this type of thing. So, a few years ago I did a lot with rocketry. A move to a less open area and the addition of kids caused a slow down, to a point. The kids love it but I don’t have the time to build the big ones until they get a little older. Anyhow, in that time I dabbled a bit with electronics.

My idea is a fun project my kids (6 and 7 years old) may have fun helping with. I’m sure it’s been done many times but make a radio that is controlled by a serial interface. I am constantly in work environments that block streaming radio, but I thought it’d be fun to make a device that will plug into a serial interface and it can receive the sound data as well as be able to control the channel and such through a program.

Anyone with experience in serial devices is welcome to contribute an opinion. Like most projects that seem simple, I’m sure this is not but thank you for your comments!

VBA – User Defined Type

As much as I do not like VBA, I do like the “User Defined Types” which, from a C/C++ programmer’s prospective, this is a lot like using structs.  And for data management, which is probably 90% of what VBA is used for, it makes a lot of since.  How do we define a User Defined Type?

Private Type dict
    a As Integer
    b As String
    c As String
    d As Integer
End Type

Once Defined, we need an initialization function to store the struct.

Private Function defineDict() As dict
    defineDict.a = 1
    defineDict.b = "two"
    defineDict.c = "three"
    defineDict.d = 4
End Function

At this point, we can use the same calling to to that ‘struct’ to change the variables as needed.

Sub testType()
    Dim t As dict       ' Set the variable
    t = defineDict      ' Initialize
    Debug.Print t.b     ' Prints >> "two"
    t.b = "no more"     ' Change a variable
    Debug.Print t.b     ' Prints >> "no more"
End Sub

Minesweeper Guide

So the classic game of Minesweeper is a great waste of my time.  I’ve found though, the secret to being successful is understanding the 2’s.  I’ll demonstrate with a series of screenshots.  I’ll remind my readers that the Minesweeper I use is Linux based, and Windows’ Minesweeper is somewhat different.  For example, the version I’m using will always have the upper left corner free and there is always a solution through logic.  Unfortunately, in Windows, there are times when no logic will fix it.

Now, I’ve created a program to solve the puzzles, but it’s no where near as fun.  For the cheat program (for Windows XP version) check out my tutorial.  It’s a good read on using C in Windows to pull information about a program, or hooking, as it is better known.

The key for all the graphics is:

  • RED = MINE
  • YELLOW = MAYBE
  • GREEN = CLEAR

The first three graphics will show a common pattern with a 5 and some a row including 2’s.  When 2’s are in a row, you can start eliminating.

EDIT: I plan to continue updating this, but for now I’ll post as is.

GZip with ZLib

In an effort to use zlib in VBA, I had to first learn to use it.  I’m looking to gunzip the XFDL files to use the data as an MS  Office plugin.  In tinkering with zlib’s GZip functions, I found them to be very much like normal file handling in C.  Here’s a link to the official zlib reference manual, GZip is the tenth section.  So, to test it, I made a “micro-gunzip” which does work well.  When compiling, don’t forget to link to libz.a using gcc -o out -i in.c -lz.   Other than that, enjoy!  The basics are covered in the comments.

#include <stdio.h>
#include <zlib.h>
/* gcc filename.c -o outname -lz */

int main(int argc, char *argv[]) {
	// variables
	gzFile gFile;           // gzip file object
	FILE *pFile;            // out file object
	char *filen = argv[1];  // get the name of the file
	char buffer[100];       // buffer for reading

	// open files
	gFile = gzopen(filen, "rb");        // same as file
	pFile = fopen("example.out","wb");
	if(pFile == NULL || gFile == NULL)
		perror("Error opening file");
	else {
	    // write
		while(!gzeof(gFile)) {
			gzgets(gFile,buffer,100);   // file object first
			fputs(buffer,pFile);        // write to plain tex
		}
		// close
		fclose(pFile);
		gzclose(gFile);
	}
	return 0;
}

NCOER Spreadsheet – Done

Okay, so I’ve updated my code and I’m ready to release to the world my NCOER speardsheet.  Here’s a quick tutorial on how to use it.

  1. Download the Excel 2007 or Excel 2003 version. (Right Click and Save As)
  2. Ensure that you have enabled macros [ Office 2007 ] or [ Office 2003 ] for your MS Excel.
  3. Open the file you downloaded.
  4. Enter the unit you need the report for in the textbox on the left.
  5. Click Update
  6. It will prompt you for your AKO Username/Password to access the data.
  7. Wait a short time and it will automatically load and filter.
  8. Print or export the data as needed.

And that’s it.  I know military types read this blog (proven through the Open XFDL project) so please comment and let me know your opinion!

NCOER Spreadsheet

Last week, I complained about how bulky VBA (Visual Basic for Applications) can be.  My current project is to create a spreadsheet to keep track of upcoming NCOERs.  This is an easy task in anything but the most used and abused application the admin personnel in the Army use, Microsoft Excel.  Now, the data is easy enough to pull once you get an SSL connection with this website (to access you need to use an AKO Username/Password.)  The Interactive Web Response System will allow you to pull data on any past, due or current NCOERS (Evaluations).  This is great as I can track our evaluations as they move up the chain and will see when they are late.  Unfortunately, the web designers have only sorted the information by last name.

So, my basic program is complete.  I can make a connection (fortunately, MSXML6.0 makes an easy post request to an SSL website… something that if using Python, is not an easy task.)  It would appear that it is utilizing Internet Explorer’s library for the connection.  Once the connection is made and the data is loaded, then I parse.  Here is where VBA gets bulky.  Fortunately, I can use a reference to VBScript’s RegEx object, but it is far from being as complete as say, any other regex engine in any other language.  On top of that, parsing text through splits and such is an amazing pain.  Here’s an example.

Python:

import re
test = 'A simple "test of the languages" will show how bad VBA is!'
a = re.findall(re.compile(r'".*"',re.I),test)
print "Result = %s" % a[0]
## Result = "test of the languages"

VBA:

Private Sub CommandButton1_Click()
    ' must include Microsoft VBScript Regular Expressions 5.5 in references
    Dim re As New RegExp
    Dim testing As Variant
    Dim test As String
    ' to escape quotes "" can be used or chr(34).
    ' unbelievably, chr(34) is easier to read than ""
    test = "A simple " & Chr(34) & "test of the languages" & Chr(34) & " will show how bad VBA is!"
    re.Pattern = Chr(34) & ".*" & Chr(34)
    re.IgnoreCase = True
    Set testing = re.Execute(test)
    Range("A1").Value = "Result = " & testing(0)
    ' Result = "test of the languages" in "A1"
End Sub

See the difference?  I know it’s pretty close but keep in mind, this is a single line of text.  Multiple lines, large text files, etc. can be horrendous.  What in the world is left, mid and right anyhow?  I know 90% of this is that I refuse to touch this language if I can avoid it but still, this is ridiculous!!

Fern Screensaver : Part 4

I’ve now completed the Fern Screensaver in Objective-C for the Mac!  Surprisingly, using Objective-C was not that far from C/C++.  In fact, much of my code could be pasted directly in.  That includes the variables, math functions, etc.  Also, Mac has done a good job of documenting it’s libraries so using the NSObjects was not that difficult between Google and a quick reference search along with the example screensaver code.  I’m going to hit a few key differences and then post the entire file I edited.  XCode does the templating pretty well.

First, all the variables are at the top of the code so they don’t change as the program advances frames.

// VARIABLES
float mat[4][7] = {
//...

@implementation ZackScreenSaverView

Secondly, I had to use implement my NSObjects at the start of the -(void)animateOneFrame method.  The size = [self bounds].size; calls the screensize.  It’ll take some time to get used to the method calls in Objective-C!

- (void)animateOneFrame
{
	NSRect dot;
	NSSize size;
	NSColor *color;
	NSBezierPath *path;
	float red,green,blue,alpha;

	size = [self bounds].size;

The framework has some good methods for getting random floats, or any integer type!

	// random number
	p = SSRandomFloatBetween(0.0,1.0);

Finally, it took some new methods to draw my dots to the screen.

	// set dot
	dot = NSMakeRect(jx,jy,1.0,1.0);

	// make dot
	path = [NSBezierPath bezierPathWithRect:dot];

	// draw dot
	[path stroke];

Other than that, the rest is pretty much the same.  I encourage those more used to Objective-C and programming for Mac products to comment about the use of this code and correct any bad assumptions!  Here is the code in it’s entirety (note that I’ve taken out the redraw at this time)…

//
//  ZackScreenSaverView.m
//  ZackScreenSaver
//
//  Created by Zachary D. Skelton on 5/30/10.
//  Copyright (c) 2010, Skelton Networks. All rights reserved.
//

#import "ZackScreenSaverView.h"

// VARIABLES
float mat[4][7] = {
	{0.0,0.0,0.0,0.16,0.0,0.0,0.01},
	{0.85,0.04,-0.04,0.85,0.0,1.6,0.85},
	{0.2,-0.25,0.23,0.22,0.0,1.6,0.07},
	{-0.15,0.28,0.26,0.24,0.0,0.44,0.07}
};
// constant sets
float xa = -5.5;
float xb = 6.5;
float ya = -0.5;
float yb = 10.5;
// x and y to be altered
float x = 0.0;
float y = 0.0;
// screen/image size
int ix = 512;
int iy = 512;
// floats for math fulction
float p = 0.0;
float x0 = 0;
float jx = 0;
float jy = 0;
// variables to control function
int i = 0;
int k = 1;
int end = 10000;

@implementation ZackScreenSaverView

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview
{
    self = [super initWithFrame:frame isPreview:isPreview];
    if (self) {
        [self setAnimationTimeInterval:1/30.0];
    }
    return self;
}

- (void)startAnimation
{
    [super startAnimation];
}

- (void)stopAnimation
{
    [super stopAnimation];
}

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];
}

- (void)animateOneFrame
{
	NSRect dot;
	NSSize size;
	NSColor *color;
	NSBezierPath *path;
	float red,green,blue,alpha;

	size = [self bounds].size;

	ix = size.width;
	iy = size.height;
	dot = NSMakeRect(ix/2,iy/2,1.0,1.0);

	red = 255.0;
	green = 255.0;
	blue = 255.0;
	alpha = 255.0;
	color = [NSColor colorWithCalibratedRed: red
									  green: green
									   blue: blue
									  alpha: alpha];

	[color set];

	// random number
	p = SSRandomFloatBetween(0.0,1.0);

	// find random i
	if(p <= mat[0][6])
		i = 0;
	else if(p <= (mat[0][6] + mat[1][6]))
		i = 1;
	else if(p <= (mat[0][6] + mat[1][6] + mat[2][6]))
		i = 2;
	else
		i = 3;

	// super math function
	x0 = ((x*mat[i][0])+(y*mat[i][1])+mat[i][4]);
	y = (x*mat[i][2]+y*mat[i][3]+mat[i][5]);
	x = x0;
	jx = ((x-xa)/(xb-xa)*(ix-1));
	jy = (iy-1)-(y-ya)/(yb-ya)*iy-1;

	// set dot
	dot = NSMakeRect(jx,jy,1.0,1.0);

	// make dot
	path = [NSBezierPath bezierPathWithRect:dot];

	// draw dot
	[path stroke];

	// CLEANUP
	/*
	if(k == end) {
		k = 0;
		//sleep(5);
	} else
		k += 1;
	*/
	return;
}

- (BOOL)hasConfigureSheet
{
    return NO;
}

- (NSWindow*)configureSheet
{
    return nil;
}

@end

Microsoft Access : XFDL Viewer – Introduction

I know, I said it yesterday that it is rare that I develop on Windows, but this is a long promised application.  In 2007, my unit administrator (in the U.S. Army Reserves) suggested code that would allow batch loading XFDL forms from MS Access.  Due to the scope of the Apps 4 The Army project, I was limited to using a web application.  Now that the project is submitted and done, I am free to do my original plan, which is code to do the same process in MS Access.

Starting this today, I realized how much I hate doing Visual Basic.  Particularly, VBA is very painful!!  It’s not that the language is bad but it just always feels bulky and pieced together to me.  It seems to lack the professionalism of C/C++ and the flow of Python.  But, I may be alone in that.

I have a question for my readers though. Would anyone have an interest in seeing this project on SourceForge?  The Apps 4 the Army project is no longer my intellectual right, but a desktop application, a MS Office Plugin, etc… that’s all good to make public.  So let me know, if I get readers saying we’d like to help; then I will happily move this project to SourceForge!

Fern Screensaver : Part 3

Today, I had no Mac with me to work on my screensaver in Objective-C.  As you can see in my previous post, I used my python program and wrote it in C for SDL that works on either Windows or Linux.  Now, the basic principle is the same, I just need to output that location to the correct pixel plot method to use other systems.  I thought, since I was on Windows all day, I might as well use that to make the screensaver using Windows API.

I’ve had some use of Window’s API before to make a Breakout game for my children.  It is rustic at times but works.  I decided to not mess with OpenGL today and just use Win32 API and GDI methods.  Below you will find my complete source code and a link to download this screensaver.  Once downloaded, save it in C:\WINDOWS\System32\ and it will appear on your personalization menu.

A quick note before the code, for those unfamiliar with Windows API… there’s a lot of goobly gook here that looks scary.  It’s really not that bad but here’s the meat of the project:

  • Lines 8-34 are the same variables we’ve seen before.
  • Lines 36-40 are a ‘dot()’ method I made to clean the code (slightly).
  • After Line 42:
    • WM_CREATE is called on the start of the program.
    • WM_DESTROY is called on the completion of the program.
    • WM_PAINT is used to paint to the screen.
      • Here you see the same math as before until lines 78-82.
      • At Lines 78-82, I’m using Win32 API to create a color brush and paint it with the dot method.
    • WM_TIMER is called every millisecond in this program, it keeps the loop going.
      • InvalidateRect() will force a WM_PAINT message.
  • Everything that follows is not really applicable as it just meets the demands of the Screensaver library.

If you would like to try out this screen saver, download from this link and save the file to your C:/WINDOWS/system32/ folder.  Let me know how it works for you!

#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#include <scrnsave.h>

#define TIMER 1

// VARIABLES
float mat[4][7] = {
    {0.0,0.0,0.0,0.16,0.0,0.0,0.01},
    {0.85,0.04,-0.04,0.85,0.0,1.6,0.85},
    {0.2,-0.25,0.23,0.22,0.0,1.6,0.07},
    {-0.15,0.28,0.26,0.24,0.0,0.44,0.07}
};
// constant sets
float xa = -5.5;
float xb = 6.5;
float ya = -0.5;
float yb = 10.5;
// x and y to be altered
float x = 0.0;
float y = 0.0;
// screen/image size
int imgx = 128;
int imgy = 128;
// floats for math fulction
float p = 0.0;
float x0 = 0;
float jx = 0;
float jy = 0;
// variables to control function
int i = 0;
int k = 1;
int end = imgx*imgy;
int done = 0;

void dot(HDC hdc, HBRUSH whtBr, int x, int y) {
        SelectObject(hdc, whtBr);
            Rectangle(hdc, x-2, y-2, x+1, y+1);
        DeleteObject(whtBr);
}

LRESULT WINAPI ScreenSaverProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
    static HDC hdc;
    //static HGLRC hrc;
    PAINTSTRUCT ps;
    HBRUSH whtBr;
    static RECT rect;
    switch(message) {
        case WM_CREATE:
            GetClientRect(hwnd,&rect);
            imgx = rect.right;
            imgy = rect.bottom;
            int ret = SetTimer(hwnd, TIMER, 1, NULL);
            if(ret == 0)
                MessageBox(hwnd, "Could not set Timer", "ERROR", MB_OK);
            break;
        case WM_DESTROY:
            KillTimer(hwnd,TIMER);
            PostQuitMessage(0);
            break;
        case WM_PAINT:
            k++;
            p = (float) rand()/RAND_MAX;
            if(p <= mat[0][6])
                i = 0;
            else if(p <= (mat[0][6]+mat[1][6]))
                i = 1;
            else if(p <= (mat[0][6]+mat[1][6]+mat[2][6]))
                i = 2;
            else
                i = 3;
            x0 = ((x*mat[i][0])+(y*mat[i][1])+mat[i][4]);
            y = (x*mat[i][2]+y*mat[i][3]+mat[i][5]);
            x = x0;
            jx = ((x-xa)/(xb-xa)*(imgx-1));
            jy = (imgy-1)-(y-ya)/(yb-ya)*imgy-1;
            // Paint it
            whtBr = CreateSolidBrush(RGB(255,255,255));
            hdc = BeginPaint(hwnd, &ps);
                dot(hdc, whtBr, (int)jx, (int)jy);
            EndPaint(hwnd, &ps);
            ReleaseDC(hwnd, hdc);
            if(k == end) {
                Sleep(5);
                done = 1;
            }
            break;
        case WM_TIMER:
            if(done == 0)
                InvalidateRect(hwnd, NULL, FALSE);
            else {
                InvalidateRect(hwnd, NULL, TRUE);
                k = 0;
                done = 0;
            }
            break;
        default:
            return DefScreenSaverProc(hwnd, message, wParam, lParam);
        }
    return 0;
}

BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
    //return FALSE;}
    switch(message) {
        case WM_INITDIALOG:
            //get configuration from the registry
            return TRUE;
        case WM_COMMAND:
            switch(LOWORD(wParam)) {
                case IDOK:
                    //write configuration
                    EndDialog(hDlg, LOWORD(wParam) == IDOK);
                    return TRUE;
                case IDCANCEL:
                    EndDialog(hDlg, LOWORD(wParam) == IDOK);
                    return TRUE;
            }
    }
    return FALSE;
}

BOOL WINAPI RegisterDialogClasses(HANDLE hInst) {
    return TRUE;
}

Just a note, this is the rare time you will find me messing with Windows.

Fern Screensaver : Part 2

For those interested, here is roughly the same code in C for use with SDL. This first block are standard variables that are not by default when CodeBlocks produces an SDL template.

#include <time.h>
#include <unistd.h>

    // START RANDOM NUMBERS
    srand((unsigned)(time(0)));

    // VARIABLES
    float mat[4][7] = {
        {0.0,0.0,0.0,0.16,0.0,0.0,0.01},
        {0.85,0.04,-0.04,0.85,0.0,1.6,0.85},
        {0.2,-0.25,0.23,0.22,0.0,1.6,0.07},
        {-0.15,0.28,0.26,0.24,0.0,0.44,0.07}
    };
    // constant sets
    float xa = -5.5;
    float xb = 6.5;
    float ya = -0.5;
    float yb = 10.5;
    // x and y to be altered
    float x = 0.0;
    float y = 0.0;
    // screen/image size
    int imgx = 512;
    int imgy = 512;
    // floats for math fulction
    float p = 0.0;
    float x0 = 0;
    float jx = 0;
    float jy = 0;
    // variables to control function
    int i = 0;
    int k = 1;
    int end = imgx*imgy;

    // dot rect
    SDL_Rect dot;
    dot.x = screen->w/2;
    dot.y = screen->h/2;
    dot.h = 1;
    dot.w = 1;

This next block is the heart of the program. You’ll see this is very close to the Python code, but be aware that in C, you’re needing to be careful about your defined types.

        // DRAWING STARTS HERE

        // random number
        p = (float) rand()/RAND_MAX;
        // find random i
        if(p <= mat[0][6])
            i = 0;
        else if(p <= (mat[0][6] + mat[1][6]))
            i = 1;
        else if(p <= (mat[0][6] + mat[1][6] + mat[2][6]))
            i = 2;
        else
            i = 3;
        // super math function
        x0 = ((x*mat[i][0])+(y*mat[i][1])+mat[i][4]);
        y = (x*mat[i][2]+y*mat[i][3]+mat[i][5]);
        x = x0;
        jx = ((x-xa)/(xb-xa)*(imgx-1));
        jy = (imgy-1)-(y-ya)/(yb-ya)*imgy-1;
        // set dot
        dot.x = (int) jx;
        dot.y = (int) jy;
        // draw bitmap
        SDL_FillRect(screen, &dot, SDL_MapRGB(screen->format, 255, 255, 255));

        // DRAWING ENDS HERE

Finally, we control the program flow. I found that it looks like nothing is happend once the drawing is a quarter complete. So instead of running through every pixel, we’ll just do a quarter of them. This speeds up the program a bit. I’m thinking I may let them go but start a new one when each is a quarter done.

        // CLEANUP
        if(k == end) {
            k = 0;
            printf("Out of dots.\n");
            sleep(5);
            SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
        } else {
            k += 1;
            printf("\r%i out of %i",k,end);
            fflush(stdout);
        }

        SDL_Flip(screen);

Edit: For Windows users, you’ll need to have #include <Windows.h> and change sleep() to Sleep().

Fern Screensaver : Part 1

So my brother has asked me to help in making some iPhone/iPad applications.  Sounds like a great idea, I just need to get used to Objective-C.  If you already know C/C++, it’s not a huge leap to produce some iPhone code.  But I’m short of ideas to write and since most of the Mac is using Objective-C, I’ve decided practicing that language with something else, a screen saver!

I have done a simple screen saver using this excellent article to draw shapes.  I’ve decided to go from utilizing already produced code to doing something of my own.  My wife, who is a botanist at Iowa State was kind enough to loan me a Mac with Snow Leopard loaded, as school is out for the summer and they do not need this for their classes.  I asked her what she would like, and of course, it’s ferns (that’s the plant she studies).  Some quick thinking and googling lead me to the idea to use fractals!  In particular, Barnsley’s Fern.  To learn more, use google and this link.

Math drew this with a fractal equation, not by hand.

Now, as I have shown previously, I’m much better with Python, so to prototype the mathematical equation and code idea, I’ve developed a sample using pygame.  I found the math through this excellent code snippet, which saved me a lot of time in testing.  The use of the code is explained in the comments:

#!/usr/bin/python
import random, pygame, time
from PIL import Image
from pygame.locals import *
from pygame.color import THECOLORS as color

# VARIABLES TO INCLUDE MATH
mat = [[0.0,0.0,0.0,0.16,0.0,0.0,0.01],
	[0.85,0.04,-0.04,0.85,0.0,1.6,0.85],
	[0.2,-0.25,0.23,0.22,0.0,1.6,0.07],
	[-0.15,0.28,0.26,0.24,0.0,0.44,0.07]]

xa = -5.5
xb = 6.5
ya = -0.5
yb = 10.5

x = 0.0
y = 0.0

imgx = 700
imgy = 700

# VARIABLES FOR CONTROL
k = 1
end = imgx*imgy / 10 * 4 # Looks like nothing is happening after this point.

# START PYGAME AND SETUP
pygame.init()
screen = pygame.display.set_mode((imgx, imgy), 0, 8 )
pygame.display.set_caption('Fern Screensaver')
screen.fill(color['black'])

# START LOOP
done = False
while not done:
    # DETECT END OF DRAWING
    if k == end:
        # ENJOY AND RESET
        time.sleep(3)
        k = 0
        screen.fill(color['black'])
    else:
        # MATH FOR THE FRACTAL
        p = random.random()
        if p <= mat[0][6]:
            i = 0
        elif p <= mat[0][6] + mat[1][6]:
            i = 1
        elif p <= mat[0][6] + mat[1][6] + mat[2][6]:
            i = 2
        else:
            i = 3
        x0 = x * mat[i][0] + y * mat[i][1] + mat[i][4]
        y = x * mat[i][2] + y * mat[i][3] + mat[i][5]
        x = x0
        jx = int((x-xa)/(xb-xa)*(imgx-1))
        jy = int(imgy-1)-int((y-ya)/(yb-ya)*imgy-1)
        # AFTER PLAYING WITH SEVERAL COLORS, WHITE ON BLACK IS THE BEST
        c = color['white']
        screen.set_at((jx, jy), c)
        pygame.display.update()
    # DETECT EVENTS TO END PYGAME
    events = pygame.event.get()
    for e in events:
        if e.type == KEYDOWN and e.key == K_ESCAPE or e.type == QUIT:
            done = True
    # CYCLE AGAIN
    k += 1

# DONE
pygame.quit()

So, the next step is to code this for the Mac… keep posted for that code/tutorial.

To the authors of Hamster.

I found your project listed on this blog (which is a great read for Linux users)!  I will not rewrite that author’s excellent post, if you’re curious what Hamster is, go read the blog!  This tool is great for anyone obsessed with data and time tracking.  Essentially, it will show you what you do during the day.  For those who are bad at time management (me), then this tool can help increase performance.  But in using it, I found that I wanted something more.  Specifically, I didn’t want to tell it what I was doing.  I mean, I switched from coding my wardriver to blogging five minutes ago and I still haven’t updated.  Even worse, what happens when I’m multitasking between work, programming, army, etc.  I would like this application to update what is happening as I change it, rather than take the five seconds to update my current task.  I know, I’m lazy.

So what do I think should happen?  Well, I’ve commented on the post that I found this program that I would like it to be automated.  Take a ‘picture’ every minute of active processes and then use that data to associate that program with your current activity!  For example, the browser is open (you can even catch the website name) and you have a setting that associates that program/page with an activity, Hamster then updates what you are doing.  You could even go so far as to use what window is in front, the next behind, the next behind, etc to rank the amount of work you are doing with that task.

With my Army project done, my wardriver being worked on at a steady pace, I think this would be a fun program.  Anyone else interested in this?  Let me know through your comments…

Garmin Wardriver – Prototype Released

This project went together smoother than I thought it would.  The source code and application are available on it’s SourceForge page.  I’m still working to create a range for the networks and then use circles as points.  I’m thinking if I factor in strength, I can come up with an approximate (no where near exact) range.  Unfortunately, without the right antenna, it’s not likely to come up with a direction but I can get the entry and exit and create a circle around it from that.  Unfortunately, to convert the minute data to feet will take some fancy math due to variations in minutes with the longitude.  More on that in a future post.

For those wanting to use the application, here are the steps to get it working.

  1. Ensure you have iwlist, gpsbabel and Google Earth installed.
    • sudo apt-get install wireless-tools gpsbabel googleearth-package
  2. Plug in your gps.
  3. Test with ‘sudo gpsbabel -T -i garmin -f /dev/ttyUSB0
  4. If that pulls data, run ‘sudo ./garminwardriver.py
  5. Open your ‘out.kml’ in Google Earth (Start Google Earth->File->Open)

And there you go, data that can be drawn on any wifi card with any GPS device (if you change the code for your device).  Try it out and let me know if it works or what errors you come up with.  This is just a prototype, so expect v1.01 to be out soon with updates.

Update:

I wrote this post and completely forgot to add the screen shots!

apprunning
Gathering Data
googleearth
Google Earth Data

Garmin Wardriver – Part 2

I’m very happy to say, this is a simple project, to get working in its most basic form.  Note, I said it’s most basic form so no hate mail on the fact that this is nothing more than a quick script!  There are plans to actually go deeper, make this open to more than my device, not use already existing programs, etc.  But for the basic concept and starter, I’ve made this program use gpsbabel to get the gps information and iwlist to get the network information.  I had started with pywifi but found this to be a problem because there was an overbound error.  This bug will be reported, it seems it has a problem with converting an integer to a float on a 64bit machine.

So with no futher ado, here is the script:

#!/usr/bin/env python
import os, re, time

# DEATH FUNCTION
def die(msg):
	print ' [*] ERROR: %s' % msg
	exit(1)

# ENSURE WE ARE ROOT
def checkroot():
	if os.getuid() != 0:
		die('Run this program as root.')
	return

# GET NETWORK INFO
def getessid(dev):
	nets = os.popen('iwlist %s scan' % dev).read()
	pat  = re.compile(r'ESSID:".*"')
	mess = re.findall(pat, nets)
	found= []
	for find in mess:
		found.append(find.split('"')[1].split('"')[0])
	return found

# GET GPS INFO
def getposition(dev):
	pos = os.popen('gpsbabel -i garmin,get_posn -f %s' % dev).read()
	pos = pos.splitlines()[1].split(' ')
	return [pos[1],pos[2]]

# RUN IT
def main():
	checkroot()
	found = getessid('eth1')
	pos   = getposition('/dev/ttyUSB0')
	for find in found:
		print 'ESSID: %s @ %s | %s' % (find,pos[0],pos[1])
	exit(0)

if __name__ == '__main__':
	main()

So what you see here is that I’m using os.popen() to call my programs to draw data.  Unfortunately, iwlist is painfully slow, to the point there’d be a five second delay on some slower machines between the call and having the data ready.  This is why I want to develop the application to not be dependent on other programs, but for the time being, this works as proof of concept in the data gathering stage.  It’s now just a matter of adjusting the code to run this constantly and load data to an overlay when entering and leaving an ESSID’s area.

Any comments for improvements?  Don’t forget, you can join this project any time on SourceForge!

Garmin Wardriver

For my birthday, my wife got me a GPS (Garmin Venture HC).  I have been disappointed in it’s integration with Linux, most particularly it’s ability to communicate with gpsd (usb input, not serial).  I had high hopes of doing some wardriving and kismet does not gather any of the data despite it’s configuration.  I can get gpsd to get some cryptic messages from the device but I found that this command: `gpsbabel -T -t garmin -f /dev/ttyUSB0` will generate the current coordinates.  So instead of getting frustrated, I’ve decided to open my first SourceForge project.  You can find it listed as Garmin Wardriver.

The concept seems simple enough, generate location through direct communication with the GPS device or through the gpsbabel command above and then gather a list of local ESSID’s with their strength.  With this data, updated each second, one could generate a location for entering an ESSID’s area, it’s strength as you move through and when out.  Output this to an overlay for a program such as Google Earth and that is a wardriver!  I can see this branching to more advanced uses but for the basic proof of concept, a command line program should suffice.  This will be written in Python and I’ve looked into utilizing the pygarmin and pywifi modules instead of generating information from preexisting programs.

DONE!!!

It is done!  The XFDL Loader is completed and it is functional.  It came down to the wire, with less than an hour left in submission time to complete but it did get done.  Here is a sample XFDL form and a sample CSV data file (RIGHT CLICK BOTH TO SAVE) to use.  The process to use the web application is (each step is a different page):

  1. Load the two sample files by file type.
  2. Set up data to merge to the form.
    • Use the drop down box on the right to select data by the header
    • Write data in the middle column input boxes to have default data for all forms.
  3. It’ll take awhile to generate the forms, be patient.  When completed, there will be a link to download a zipped archive of your forms.

And that’s it.  Be aware, because the project changed from PHP to Python, we had 10 days to generate the web application.  Therefore, there is no styling (it’s not pretty) and it might not work on all forms.  Also, it only selects text inputs.  Check boxes, more options, etc are yet to come, but this was needed to be functional by May 15th, and with only minutes to spare, it was done!

Approaching the final hours!

The project is due tomorrow!  I have a lot of work to do, but it finally appears possible to have this all done.  Thank you to my team member who contributed the code to correct the xml.dom.minidom’s output to be read correctly by PureEdge and Lotus Forms Viewer.  This will enable me to save, although I’m a bit sad that I spent so much time  this week working on that.  At this point, I need to complete the parsing scheme, develop a function to save the data to forms per the CSV file and then send back those files in a zipped archive.  All small steps, and assuming no road blocks, able to get done today.  A quick bit of documentation and packaging and this barely beta, functional web application will be ready for submission.  This may require an all-nighter and it’s down to the wire, but I think it will work.  Keep your eyes on the XFDL Loader as it will be updated through the day!

XFDL Viewer Update…

As I dig through miles of XML, I realize I have not posted lately. I’ve been a bit busy meeting the May 15th deadline for my project. But here’s a quick update. First, don’t forget to view the update viewer. It’s not pretty, but it works to the point I’ve set it. I’ve changed from PHP to using Python CGI (a language I’m more comfortable with) and I’ve done what took two weeks in two days. Too bad this wasn’t thought of before!! Anyhow, I figured I’d pass along this bit of code from Neil Funk that shows a better method for decompression of an XFDL in Python:

#!/usr/bin/python
from base64 import *
import zlib

# OPEN FILES
inp = open('example.xfdl','rb').read()
out = open('example.xml,'wb')

# TAKE OUT THE MIME DATA
magic = inp.splitlines()[0]
data   = inp.split(magic)

# THE TRICKY PART -- Look to the python manual for explanation.
wbits = 15+32
newData = zlib.decompress(b64decode(data),wbits)

out.write(newData)
out.close()

And drumroll please, for Chris Hutton contributed this PHP code for recompressing an XFDL from XML.  I’m working to translate this to Python, but for the time being, an XML with an XFDL extension works.

// Export XML, gzip, and base64 encode. Append XFDL header information and output to user.
// XML is the raw data to be saved.
$newxml = $xml->asXML();
// chunk_split is new to me!
$output = chunk_split(base64_encode(gzencode($newxml)));
// Add the header!
$output = "application/vnd.xfdl;content-encoding=\"base64-gzip\"\n". $output;

header("Content-disposition: attachment; filename=\"{$filename}\"");
header("Content-type: application/vnd.xfdl");

echo $output;

So thank you all for your contributions!  I’ll try to keep this blog more up-to-date.

Ubuntu 10.04 – Fixing Title Bar Buttons (Place on the right)

After downloading Ubuntu 10.04 Lucid Lynx, I noticed that the biggest user interface change is the title bar buttons.  Unlike Windows or Mac, the buttons are located on the left side.  This is not too bad if you can get used to it, but I found several complaints online.  So, for those who are not used to gconf-editor, here are instructions to fixing the title bar.

  1. Open a terminal or use Alt+F2 and type ‘gconf-editor’.
  2. In the tree menu on the left side go to: apps -> metacity -> general
  3. On the options menu (right side of the editor) find the option midway down for ‘button_layout’.
  4. Editing these options can let you customize the menu, here’s how:
    • The colon ‘ : ‘ sets the middle, so anything on the left of the colon is on the left of the title bar.
    • Settings are comma separated values of menu, minimize, maximize, close, separator
      • Duplicates and unknown values are silently ignored.
    • Example #1: menu:minimize,maximize,close
    • Example #2: close,minimize,maximize:
    • Example #3: minimize,maximize,close:

See, one of the great things with Linux is that these configurations are available.  If you take a moment to look around your gconf-editor, you’ll see how powerful this tool is to your user interface customization.  Feel free to contact me or comment here with questions regarding this process.

Ubuntu 10.04 Alpha 2 – Review

So I decided to update my laptop to Ubuntu 10.04.  This process got off to a rough start because a pesky dog ran into my laptop, shutting the lid and causing a sleep halfway through the upgrade.  The problem came in that the computer was not set to be able to resume and so I only had half the updates done.  So when I rebooted, there was no graphical display, and for awhile, not even the ability to use a terminal.  Thankful, grub had been updated and I was able to boot into the recovery counsel, compile a wireless driver, get an internet connection and download and install the rest of the updates manually rather than through ‘sudo upgrade-manager -d’.  Once that was done, I was amazed at the new Ubuntu.

Improvements that I noticed:

  1. Better Graphical Display (Finally away from the orange/brown theme!)
  2. Applets, as per the past four releases, are better in bothe appearance and use.
  3. Ubuntu is keeping with its integration of web based applications and social networking through the Desktop.

There are many more improvements but these are the ones that I’ve noticed first.  I’ve also seen through Launchpad that bugs are being addressed, which in this pre-review from last year, it would appear the the integration of fixes for the bugs in Linux has improved quite aways in the past year, and this release appears to be continuing the quality product of Ubuntu Linux!

XFDL in Linux :: Update

So, after talking with the Army’s G6 (essential the IT Department), the competition I’m entering (which because I’m not an active duty Reservist, I cannot receive prize money) is focused on web applications, not desktop applications.  The changes you can expect to see in my coding is that there will be quite a bit of php, perl and python that I’ll be using rather than the application side.  At the same time though, I’ll take what I do in this web application and use it for developing a desktop application and a Microsoft Office plugin that can be used to batch load files.  Just figured I’d acknowledge the reason for changes.  On the plus side of all of this, perl has a specific Mime module and php has a great and simple interface to xml parsing, so this may end up easier as a web application.

Complaint

“I’m a PC and Windows 7 was my idea.”

This has been annoying me for the past several months, and since I have a blog, I’m going to complain.  First of all, Windows is proprietary and if it was your idea and they didn’t pay you for it, oh well, that’s business.  Secondly, the crap in Windows 7 isn’t that great; I bought my wife a Dell Mini-10 for her birthday and it came with Windows 7.  I immediately installed Ubuntu 9.10 Netbook Remix and the comparison without even numbers, just general usage, screen real estate and speed, Ubuntu is far superior.  And finally, Ubuntu and Linux itself are open source which means that I can truly say, as a contributer (bug triage):

“”I’m a PC and Ubuntu truly is partly my idea.”

Update.

So for anyone reading this blog, I am still here, just have not added anything this week.  I’m working and have not been able to update the blog but I will soon have links and information to my linux Cribbage game.  This is near completion and I have written it using pygtk.  It is using card and game modules that I had designed for a text based run of the program and figuring no one would want to use the text based, I’ve switched to a GTK interface, which is obviously, much better.

Just a starter…

So, to start off, hello and thanks for visiting!  This blog has a purpose to demonstrate code examples that refers primarily to the languages of python, c/c++ and others.  Just a quick introduction, I’m a hobby programmer from Ames, Iowa.  Recently, I’ve attempted to start offering computer services to the local community and have created this site: http://www.skeltonnetworks.com/ which is in it’s intial stages but is functional.  My interests in programming relate mostly to computer security and linux.  For any comments, please feel free to write through either this blog or the contact form on my home page.