Tag Archives: custom

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

Python Curses – Custom Menu

Continuing on the same project as the previous post, I came to wanting to make a custom menu with curses in Python.  Realizing that there are functions to create menus in curses already, I wanted to build this fro m the bottom up.  The concept was to produce a menu that would highlight the selection change on the arrow keys or direct input, and then on a press of the Enter key the menu would return that selection.

Now, while writing this, you’ll see in my code that I took probable the least efficient way of building this menu, but it helps in making itself explanatory for the person learning curses.  As for the context of this coding, I built it as a function in my XFDL viewer, so there are 5 options in the menu.  I used win.keypad(0) to enable the use of the arrow keys but for some reason, the curses.KEY_UP was not being detected so the arrow key up and arrow key down are 259 and 258, respectively.  This does work though, I also have the menu catch numbers 1-5 and set the highlighted line accordingly.

def menu():
    curses.init_pair(1,curses.COLOR_RED, curses.COLOR_WHITE)
    screen.keypad(1)
    pos = 1
    x = None
    # I'm going to be lazy and save some typing here.
    h = curses.color_pair(1)
    n = curses.A_NORMAL
    while x != ord('\n'):
        # Gotta reset the screen from the root or lose the border, window, etc.
        screen.clear()
        screen.border(0)
        screen.addstr(2,2, "XFDL VIEWER", curses.A_STANDOUT)
        screen.addstr(4,2, "Please select an option...", curses.A_BOLD)
        # Detect what is highlighted by the 'pos' variable.
        if pos == 1:
            screen.addstr(5,4, "1 - XFDL -> XML",h)
        else:
            screen.addstr(5,4, "1 - XFDL -> XML",n)
        if pos == 2:
            screen.addstr(6,4, "2 - XML  -> XFDL",h)
        else:
            screen.addstr(6,4, "2 - XML  -> XFDL",n)
        if pos == 3:
            screen.addstr(7,4, "3 - Show XML",h)
        else:
            screen.addstr(7,4, "3 - Show XML",n)
        if pos == 4:
            screen.addstr(8,4, "4 - Exit",h)
        else:
            screen.addstr(8,4, "4 - Exit",n)
        if pos == 5:
            screen.addstr(9,4, "5 - DEBUG", h)
        else:
            screen.addstr(9,4, "5 - DEBUG", n)
        screen.refresh()
        x = screen.getch()
        # Is 'x' 1-5 or arrow up, arrow down?
        if x == ord('1'):
            pos = 1
        elif x == ord('2'):
            pos = 2
        elif x == ord('3'):
            pos = 3
        elif x == ord('4'):
            pos = 4
        elif x == ord('5'):
            pos = 5
        # It was a pain in the ass trying to get the arrows working.
        elif x == 258:
            if pos < 5:
                pos += 1
            else:
                pos = 1
        # Since the curses.KEY_* did not work, I used the raw return value.
        elif x == 259:
            if pos > 1:
                pos += -1
            else:
                pos = 5
        elif x != ord('\n'):
            curses.flash()
            # show_error() is my custom function for displaying a message:
            # show_error(str:message, int:line#, int:seconds_to_display)
            show_error('Invalid Key',11,1)

    return ord(str(pos))

I’ve highlighted the lines pertaining to my work around for the key pad.  This function will return the menu option and then that is processed for a reaction.  Reminder: the ‘screen’ object for my curses window is a global variable. I’m quite thrilled at the simplicity of this and the curses library, although I am disappointed in the lack of tutorials on the web deeper than typical ‘Hello World’ tutorials, but I hope these posts go to help others exploring this library!

Here’s a nice picture of the library in action:

Customize menu in action...
Be sure to comment on these tutorials and let me know if there is more detail needed or if they are helpful!!

Python Curses – Custom Progress Bar

Custom Progress BarIn making a visual editor for my XFDL project, I’ve decided to do the basic start in curses.  This is a module of python/library of C that I have not been able to utilize much at this point despite interest.  Unfortunately, there seems to be limiteexid documentation beyond the standard ‘Hello World’ type of program.  I’ll write this short tutorial with the assumption you can get through those tutorials and utilize this object.

The concept here is to create a progress bar in curses.  This example does not have any data but a basic understanding of python would allow you to create the refreshes on percentage of completion rather than time based as I have here.

def show_progress():
    #Create a window object.
    win = curses.newwin(3,32,14,10)
    # Add the Border
    win.border(0)
    # Current text: Progress
    win.addstr(1,1,"Progress ")
    # This is to move the progress bar per iteration.
    pos = 10
    # Random number I chose for demonstration.
    for i in range(15):
        # Add '.' for each iteration.
        win.addstr(1,pos,".")
        # Refresh or we'll never see it.
        win.refresh()
        # Here is where you can customize for data/percentage.
        time.sleep(0.05)
        # Need to move up or we'll just redraw the same cell!
        pos += 1
    # Current text: Progress ............... Done!
    win.addstr(1,26,"Done!")
    # Gotta show our changes.
    win.refresh()
    # Without this the bar fades too quickly for this example.
    time.sleep(0.5)

See, nothing to it.  The first line creates a new window object for and the next line adds its border.  I mapped out the relative positions for text, and you’ll want to customize this to what you need to use in your program, but for the sake of demonstration, it will show a period for each iteration.  As previously stated, you can customize this to be data or percentage driven in your program.  Don’t forget to call win.refresh() for each iteration you want to show on the screen!

Custom Brush for SyntaxHighlighter Evolved

Okay, before I get started let me just say that I realize there are several already set-up plugins for the WordPress Plugin, SyntaxHighlighter Evolved to include a brush for the *.batch language.  Also, there is a great article by the Plugin’s author that will guide you through developing a brush.  The reason I am posting mine is to pass a long a few things that went unsaid for the less experienced WordPress Plugin developer, but let me just say that this was much easier both in the plugin development and brush development than I thought it would be.  The reason I made my own brush, it’s just more fun to make my own!

Now, that being said, here we go!   My post for “Violating IT Policy” included a batch script for Cygwin to be portable.  since there was no brush in SyntaxHighlighter Evolved To develop a brush, you will need to set-up a new plugin for word press.  The plugin will be adopted by SyntaxHighlighter Evolved as you will see in a moment.  The structure for this plugin will be:

<root folder>/wp-content/plugins/
                        /plugins/<javascript brush>.js
                        /plugins/<php plugin>.php

For the javascript brush, this does have some tricky elements. but I’ve commented what I’m doing below.

/** shBrushBatch.js **/
/* Declare a new brush with SyntaxHighlighter.brushes.<your name for the brush> */
SyntaxHighlighter.brushes.Batch = function()
{
	/* Declare words that you need highlighted */
	var variable = 'clear cls goto set';
	var constants = 'if or';

	/* This is the heart of your brush, you can use the *.
	/* SyntaxHighlighter.regexLib.* brushes when applicapble. */
	this.regexList = [
		/* You may notice that my comments are looking for a css that does not match. */
		/* I'll explain below the script. */
		// comments
		{ regex: /(^::|rem).*$/gmi,                             css: 'string'},
		// stings
		{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'comments'},
		{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'comments'},
		{ regex: /echo.*$/gmi,                                  css: 'keyword'},
		// variables
		{ regex: /%w+\1/gmi,                                    css: 'keyword'},
		{ regex: /%\*|%%?~?[fdpnxsatz]*[0-9a-z]\b/gmi,          css: 'keyword'},
		// clear cls keywords
		{ regex: new RegExp(this.getKeywords(variable), 'gmi'), css: 'variable'},
		// if and key words
		{ regex: new RegExp(this.getKeywords(constants), 'gmi'),css: 'constants'},
		// labels
		{ regex: /^:.+$/gmi,                                    css: 'script'}
	];
};

/* Create the highlighter object. */
SyntaxHighlighter.brushes.Batch.prototype = new SyntaxHighlighter.Highlighter();
/* Set the Aliases */
SyntaxHighlighter.brushes.Batch.aliases = ['bat','batch'];

So the reason that my css does not match the actual of what it is would be because the theme does not match my preference.  I perfer comments to be green, so since the string for the RDark format is green, I had to assing my comments to the string.  This was pretty confusing but the way I figured out my color scheme was simple enough.  In <root>/wp-content/plugins/syntaxhighlighter/styles/ you will find all of the css files to coordinate with the theme.  Half way down, you will see “Actual Syntax Highlighter Colors” and it is at this point that you will want to see what all of your options are.  Rather than converting #5CE63B to green, I went and made a sample script once my plugin was complete, I then went and set up a color tester like this, in place of my normal brush file:

/** shBrushBatch.js  - color test version **/
SyntaxHighlighter.brushes.Batch = function()
{
	/* 	set your wordpress to:
			1
			string
			comments
			... continue until the last keyword ...
			color3
			1 I dropped the correct closing in the example for formatting. */
	var string = 'string';
	var comments = 'comments';
	// ... continue to the last keyword ...
	var keyword = 'color3';

	this.regexList = [
		{ regex: new RegExp(this.getKeywords(string), 'gmi'), 	 css: 'string'},
		{ regex: new RegExp(this.getKeywords(comments), 'gmi'),  css: 'comments'},
		// ... continue to the last keyword ...
		{ regex: new RegExp(this.getKeywords(color3), 'gmi'), 	 css: 'color3'}
	];
};

SyntaxHighlighter.brushes.Batch.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Batch.aliases = ['bat','batch'];

After doing this and seeing the colors, I could then associate which color I wanted for which sets of syntax.

Now, onto making the plugin work.  Obviously, you’ll need both of these files to have any results.  What this does is when you activate this plugin (yes, it does show in your plugins) then SyntaxHighlighter adopts it.  This script is pretty standard from what I saw online and is almost exactly out of the author’s blog post.  The comments at the front are what will appear in your WordPress under Plugins.  I’ve kept the comments mostly the same as the author, as he is describing it better than I could.

<?php
/*
Plugin Name: Batch Brush - SyntaxHighlighter Evolved
Descriptionn:  Adds support for the Batch language to SyntaxHighlighter Evolved.
Author: Zachary D. Skelton
Version: 1.0.2
Author URI: http://www.skeltonnetworks.com/
*/

// SyntaxHighlighter doesn't do anything until early in the "init" hook.
add_action('init','syntaxhighlighter_batch_regscript');

// Tell SyntaxHighlighter about this new brush.
add_filter('syntaxhighlighter_brushes','syntaxhighlighter_batch_addlang');

// Register the brush with WordPress.
function syntaxhighlighter_batch_regscript() {
	wp_register_script('syntaxhighlighter-brush-batch',
		plugins_url('shBrushBatch.js',__FILE__),
		array('syntaxhighlighter-core'),'1.0.2');
	}
// Add alternative names for your brush.
function syntaxhighlighter_batch_addlang($brushes) {
	$brushes['batch'] = 'batch';
	$brushes['bat'] = 'batch';

	return $brushes;
	}
?>

At this point you should be able to load your page.  If it cannot find the brush (you’ll get a dialog to let you know), you could replace plugins_url() in line 19 with a string of a direct path to the file, but there should be no need for it.  The most common reason for this is an error in your javascript brush, so make sure to check that before going to insane.  After this is all done, you may have problems seeing the results.  It took me 5 loads of the correct format before I saw the change, in that case, deactivate the plugin, clear the cache, change the plugin version number in line 6 and re-activate the plugin.  Should not need all of that but some browsers are fussy, and that takes care of any problem with the cache. As I said before, this is well documented and relatively easy to make.  You can see that I made my plugin only apply to my script but it would be easy to add more things to it.  I used a lot of my regex directly from this plugin because that is a skill I’m still working on.  But this was surprisingly simple, and you can find lots of good information on making plugins of your own.  It is surprisingly not too tough!