Showing posts with label Open Source. Show all posts
Showing posts with label Open Source. Show all posts

January 18, 2010

SSH Messenger


As a request, I have finished my second full Objective C project. If someone is on a computer wearing headphones and is not in convenient shouting range this app makes it simple to still get their attention.  It would also make a good admin tool, or a awesome way to prank/annoy someone. It is a simple application that will connect to a remote computer via SSH and then use the built in osascript libraries to cause a dialog prompt to appear. However instead of requiring some terminal skills, instead just enter the IP, username and password of the remote computer and then type your message. A handy shell script takes care of all the rest. Click here to check it out. (Universal Binary, Mac OS X 10.5+)

This was an interesting project, not so much on the Objective C side, which I am getting quite good at, instead the shell scripting was a challenge this time. In order to have the SSH command work without setting up key pairs, I needed to delve into the world of Expect. Expect is a handy command set that allows you to set up automation of terminal entry. In short you can have it "expect" some input and then after finding it, send some output to the terminal, which in my case was the password entry for ssh. The ssh command does not have a password argument, so it needed expect to look for the password prompt and then enter a password for the user.  It also led to a nice way to do some general result checking in the case of a prompt with two or more button options.

Expect while a little strange at first was not that hard to figure out and only took about an hour and a half to have down pat and working the way I wanted it to.  Sadly as it is based out of /usr/bin/expect you cannot use echo command, which made it slightly harder to learn when something was not working.

Check out the base script I came up with below...

#!/usr/bin/expect -f
#log_user 0
set addr [lindex $argv 0]
set usr [lindex $argv 1]
set pas [lindex $argv 2]
set message [lindex $argv 3]
set from [lindex $argv 4]
# now connect to remote UNIX box (addr) with given script to execute
spawn ssh $usr@$addr -o StrictHostKeyChecking=no
match_max 100000
# Look for any ssh issue that needs exit
set timeout 4
expect "ssh:" {exit 2}
# Look for password prompt(s)
expect "*?assword:*" {send "$pas\r"}
# Look for password rejection and exit
expect "*?assword:*" {exit 1}
set timeout 10
# send osascript commands for popup
send "osascript -e 'tell application \"Finder\" to activate'\r"
#send "osascript -e 'tell application \"Finder\" to display dialog \"$message\"'\r"
send "osascript -e 'tell app \"Finder\" to display dialog \"$message\" buttons \"Ok\" default button 1 with title \"Message From $from\" with icon caution'\r"
# Look for reply
expect "button returned:Ok" {
 send "logout\r"
 exit 0
}
send "logout\r"
exit;

Another important thing to note is that I was rather annoyed to find out it required the curly braces to be placed how they are, due to it being based on Tcl. However it was only a minor inconvenience until I realized that is why if kept having errors.  The script above takes 5 arguments Address, User, Password, Message and From, and is the general Alert script used in the SSH Messenger.

This makes the first Objective C and Shell combo app that I have done, which is a nice change from the Java Shell combo I am more used to working with.  That and it was a good refresher in shell scripting.

November 30, 2009

Simple HTML Parser in Objective C

For my current project I needed a way to fetch remote html and then parse it into a more accessible data form. So I took my Java XML Parser work and ported it over to Objective C and extended it to work with HTML, which tends to be far more messy and broken... grr. To combat this, unlike a full html parser, this converts it to a psudo xml form, where all character data between > and < and > or /> is appended to the tag string.  The down side to this is that you need to parse out any needed tag attributes separately, but that is a price I am willing to pay in this case.

Check out the files below for the code...
HTMLNode.h
NTMLNode.m


Using the HTMLNode class should be simple enough, just import the HTMLNode.h file and then use the example below to get started. It is good to note that this parser expects clean and valid HTML/XHTML, however most sites have some issue or mistake. This may cause you a few headaches, it did for me. Still the parser should get most if not all the tags, so in this case use the search function "-(HTMLNode*) search:(HTMLNode*) root: (NSString*) term" to find a containing div tag and then use getChildN for traversing the rest.

// Setup and build html node tree in root...
NSString *url = @"http://www.google.com";
HTMLNode *root = [[HTMLNode alloc] init];
[root buildFromURL: url: root];

// Get the head tag which should be root child 0...
HTMLNode *headnode = [root getChildN:0];

// The tag of the head node should be "head"...
NSLog([headnode getTag]);


As usual the code is free to use, but please give me some credit if it is used in a large project, or at least leave a comment about what it was used in.

November 27, 2009

Creating an Array of NSDictonary Objects

I had created an interface for the NSTableView class in InterfaceBuilder and needed a way to update the table with items. The easiest way seemed to be with an array of NSDictionary objects. But as I was not quite fimilar with the NSDictionary class I first had to look up how to create and fill one. Below is a base example I came up with.

// Aloc and Init Array
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:1];

// Setup keys
NSArray *keys = [NSArray arrayWithObjects:@"Name", @"Job", nil];

// Setup values
NSArray *values = [NSArray arrayWithObjects: @"Epic Box", @"running", nil];

// Add new NSDictionary with keys and values
[array addObject:[NSDictionary dictionaryWithObjects: values forKeys: keys]];

To get a value from a NSDictionary object you can do as follows...

//Using the array from the example above
NSInteger index = 0;
NSString *key = @"Name";

// Get value
NSString *result [[array objectAtIndex: index] objectForKey: key];

Remote File Request to NSString in Objective C

A current side project in Obj C that I m working on required a way to fetch a remote HTML file and parse through it to get the url of links and images. The first step required a way to get a remote file and store it as a NSString. The code below is an example of how to so.

NSString *url = @"http://www.google.com";
NSURLRequest *urlrequest = [ [NSURLRequest alloc] initWithURL: [NSURL URLWithString:url] ];
NSData *returnData = [ NSURLConnection sendSynchronousRequest:urlrequest returningResponse: nil error: nil ];
NSString *returnstring = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];

Tested on OS X 10.5+ with GCC 4.2

November 14, 2009

Simple Java XML Parser

To continue my SN Project work I started to convert the simple object to data save format I had been using to save time during the semester into a xml based file system. This way when I update code it will not break saved game file due to class def not found exceptions. However I quickly ran into an issue that Java did not have a "simple" built in class to handle XML parsing and other free libraries where a little more complex then I was looking for, so although I usually try not to reinvent the wheel while programing, this time I wanted to try my hand at writing a simple Java XML parser.

What this basic XML parser does:  It looks for the starting tag < and then starts appending the tag characters to the node tag.  Then it hits > telling that the tag had ended and the data starts finally it looks for < for the next node.  There is also the case that another < is found in the data which indicates that a nested tag was found.  The older node is pushed on a stack and the parser moves up one child node and begins the tag and data read once more. This is repeated until no nodes are left on the stack indicating the root closing tag has been reached.

As a note:  I have removed most of the advanced checking and my custom xml build methods for security reasons, so you are on your own to add try/catch as needed.  Also, as I am not using any attributes in tags, so this parser does not read them.

Overall the code works well for the xml documents I am reading in, though for one class I may still look into a faster c based solution in the future, since I am working with a JNI library anyway.

You can check out the code HERE
As usual the code is free to use, but please give me some credit if it is used in a large project, or leave a comment about what it was used in.

August 4, 2009

JamBot

A while ago I was introduced to the online web game Jam Legend, so I checked out the site. The premiss is the same as any of the music games, you hit the notes as the move on the screen. I played for a while, then got bored and forgot about it till this week. However, after playing it again, and getting bored again, I decided to create my own challenge and finally check out the Robot class in java to see if I could create a program that could play it for me.

The Robot class is a java package that is designed to aid in computer automation. You can have it look at the current screen object and then move the mouse or hit keys. The big challenge for me was getting the bot to be able to recognize what was happening on screen. Like any robotics programing it is easy to say that it will look here and do something, but actually making it happen is quite a bit more challenging. To start off JamBot requires you to drag the transparent window over the game, this sets up a view port for the bot to look at a few different locations, namely in and just above the five note zones. The challenge with this is that when playing not only do the note locations change when you need to hit a key, it also changes the background colors as your multiplier increases. In order to adjust for this, the easiest way is to check the color percent of the note color for that spot, vs just seeing if the color has changed. If you look at the included code, the values have been adjusted to what I though worked best, but you may have better luck with some further adjustments. The next step was to also have the bot look just above the note zone to see if there is a hold note active. Then if a color match is found, instead of unlocking the key, it waits for the hold to finish. After figuring out all this, and a few hours later, I had a working bot, just for the insane tap difficulty which would get around a 90% on most songs. Is it perfect, NO, however it looks and act like a normal person playing with normal skill would.

Now if I was interested in further development I would look into adding separate Robot objects for the different notes, I think this will improve accuracy and timing, by using different threads for each zone. Right now the bot is missing notes due to the main loop not being fast enough to either see the note coming or hit it before it is out of range. I am reasonably sure that a more streamed lined threaded setup will fix this. Also it is missing the ability to select different difficulty setting, and needs an included feature for strum. All which would not be too hard to add, but I will leave that up to some one else, as I have other projects to start.

Quick Instructions for Use
[Only works for Insane Tap]
1. Open JamLegend and get to the point that you can hit play to start the song.
2. Start JamBot and drag window till the lines and circles line up on screen.
3. Click the Setup Button and then drag the window to the side.
4. Once out of the browser window click start.
5. Start your song and watch as it plays its self.

As usual I have uploaded the compiled class (MAC) and the java source code for anyone to develop further, however please credit me if you do. Download Here and enjoy.

June 22, 2009

Crunchyland bot

Quite a while back I was having fun working on a javascript exploit bot for an online game called crunchyland, the game itself was rather simple you create a character give it weapons and fight silly monsters that you encounter. The entire game engine was based on flash files that where embedded in html and where linked through javascript. The problem was that I quickly got bored with the game, you click, that is it, not very entertaining past a level or two. However before I moved on, I decided to try to write a bot for it so I could at least get on the leader board. Because there was no way I was going to sit for weeks of clicking, like some of the obsessive kids on the site apparently do. (Get a job!)

It was not too hard a task and gave me a good refresher in javascript dom manipulation. The bot uses an open window and url testing to change and click elements in the window triggered by timers. I also went a step further and had it watch the size of the health bar to heal the player after a certain point. After a week of testing I quickly had my character self level up on my testing server while I did other more productive things, and after a few more days I was on the leader board, with little effort, past the coding, on my part.

I have been waiting a while before releasing it, one to not get kicked of while I was still on the leader board, and to to prevent hoards of script kiddies from also quickly leveling up with no work. Now it looks like the game it not being worked on, and my script does not work completely anymore, so here it is CL Bot (For Safari 3 maybe 4 only). Anyone with some javascript experience could take it further and fix the parts that do not work with the game updates, however I have better things to be doing. Enjoy...

June 21, 2008

ASP Stock Ticker

Another little ASP script that I had to whip up was a stock ticker. I had searched around for a free javascript version, however they where either way to complicated and ad ridden to use, or they just did not work. So like most situation call for I just gave up on that idea and whipped up my own version.

It is very simple, it just pulls the CVS data on the stock from yahoo finance and prints out a table row, that way I can use single calls in a table row, and just make a new row and call for each different stock. Also I have an up and down arrow image, but you can make your own. This should be a good starter for people looking for a simple stock ticker. I am using an asp include to call the whole page for code simplification, but you can just drop the code in a page and it will work.


<%
function getQuote(name,location)
strURL = location
Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.open "GET",strUrl, false
objXMLHTTP.send
ProcessUrl = objXMLHTTP.ResponseText
Set objXMLHTTP = Nothing
Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")

dim quote
quote = Array()

' Split the string at the comma characters and add each field to a ListBox
quote = Split(ProcessUrl, ",")

if quote(4) >= 0 then
Response.Write "<td>" & name & "</td><td><img src='images/up.gif'></td><td><font color='green'>" & quote(1) & "</font></td><td><font color='green'>" & quote(4) & "</font></td>"
else
Response.Write "<td>" & name & "</td><td><img src='images/down.gif'></td><td><font color='red'>" & quote(1) & "</font></td><td><font color='red'>" & quote(4) & "</font></td>"
end if
end function
%>

<center>
<h3>Stock Ticker</h3>
<table width="190" border="0" cellspacing="1" cellpadding="1">
<tr>
<% getQuote "Dow", "http://download.finance.yahoo.com/d/quotes.csv?s=%5EDJI&f=sl1d1t1c1ohgv&e=.csv" %>
</tr>
<tr>
<% getQuote "Nasdaq", "http://download.finance.yahoo.com/d/quotes.csv?s=%5EIXIC&f=sl1d1t1c1ohgv&e=.csv" %>
</tr>
<tr>
<% getQuote "S&P 500", "http://download.finance.yahoo.com/d/quotes.csv?s=%5EGSPC&f=sl1d1t1c1ohgv&e=.csv" %>
</tr>
<tr>
<% getQuote "10Yr Bond(%)", "http://download.finance.yahoo.com/d/quotes.csv?s=%5ETNX&f=sl1d1t1c1ohgv&e=.csv" %>
</tr>
</table>
</center>

June 12, 2008

ASP Ad Generator

After playing with ASP for a while I figured out what I would need and started off programing with a internet browser open to w3schools asp page. My idea is grab a config file read it in and choose a random ad from it and display. At first I though of using ajax to pull the content, however I would rather avoid using ajax, because if javascript is not turned on then no ads will be displayed. Instead I like that fact that you can include asp pages and then call the function, this also allows you to specify a width, and maybe if needed I will add some other parameters later. So far works quite well, but still is in development.

ASP Generator


<%
'//////////////////////////////////////////////////////////////////////////
'Display ads when function is called
'//////////////////////////////////////////////////////////////////////////
function displayAd(width)
config = Array()
config = ReadConfigFile("///path to config file///")

' Count the elements in the array
dim count
for each arrValue in config
count = count+1
next

'Will give the correct ad count based off of interger division + 1
count = count \ 4 + 1

randomize()
adchoice = 4 * Int(count * Rnd)

Response.Write "<div class='" & config(adchoice+2) & "' style='background-color: " & config(adchoice+1) & "; width: " & width & "'>"
Response.Write "<p>" & config(adchoice) & "</p>"
Response.Write "</div>"
end function

'//////////////////////////////////////////////////////////////////////////
'Read from file and grab contents for ad display
'//////////////////////////////////////////////////////////////////////////
function ReadConfigFile(Filename)
const ForReading = 1, ForWriting = 2, ForAppending = 3
const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
strAllFile = Array()

' Create a filesystem object
dim FSO
set FSO = server.createObject("Scripting.FileSystemObject")

' Map the logical path to the physical system path
dim Filepath
Filepath = Server.MapPath(Filename)

if FSO.FileExists(Filepath) Then

set TextStream = FSO.OpenTextFile(Filepath, ForReading, false, TristateUseDefault)

' Read file in one hit
Counter = 0
do while not (TextStream.AtEndOfStream)
redim preserve strAllFile(Counter)
strAllFile(Counter) = TextStream.ReadLine
Counter = Counter + 1
loop
TextStream.Close
else
Response.Write "<h3><i> Config does not exist </i></h3>"
end if

set FSO = nothing
ReadConfigFile = strAllFile
end function
%>


Include & call

<!--#include file="adgenerator.asp"-->
<% displayAd(300) %>


Config file test

This is a ad in a rounded box...
#999999
adboxround'

This an ad in a box...
#235689
adboxsquare

May 14, 2008

Java Simple Physics



Well with classes over, I wanted to at least do something with the year of University Physics torture I have endured. Thus I present Java Simple Physics. It is just a quick physics example that uses the kinetic and potential relationship to have balls with different gravity constants drop then bounce with no loss of energy. It took a few hours to get right, mostly because I either did not know what I was doing, or was over complicating things. I hope to slowly improve on this concept till I have a VERY simple physics engine. Hey, it can only help to have a physics engine laying around, one day I might actually need one.


import javax.swing.*;
import java.awt.*;

public class Physics extends Thread
{
private int worldx = 200, worldy = 900, worldtime = 15;
private JFrame frame = new JFrame();
private Ball ball,ball1;

public Physics()
{
// Set up frame
frame.setSize(worldx,worldy);
frame.setVisible(true);
// Make new ball
ball = new Ball(400,450,9.8,worldx,worldy,worldtime);
ball1 = new Ball(400,450,3.8,worldx,worldy,worldtime);
}

public void run()
{
while(true)
{
try
{
// Cover old draw with fresh screen
frame.getGraphics().fillRect(0,0,worldx,worldy);

// Move and paint ball
ball.move();
ball.draw(frame.getGraphics());
ball1.move();
ball1.draw(frame.getGraphics());
Thread.sleep(worldtime);

}
catch(Exception e){System.out.print(e);}
}
}

public static void main(String args[])
{
Physics p = new Physics();
p.start();
}
}

class Ball
{
private double gravity = 9.8, t;
private double x,y,v,a,m,dx,dy,dv,k,u;
private int worldx,worldy,dir=-1,width = 90;

public Ball(int xin, int yin, double g, int wx,int wy, int time)
{
// Set Constants
worldx = wx; worldy = wy-width; t = time;
// Reduce gravity to fit with drawing refresh rate
gravity = g * .02;

// Center ba;; on x axis
x = worldx/2 + width/2;

// Set varables
y = yin;
v = 0;
a = 0;
m=.8;

// Preset u and k values based on varables
k = (m * gravity * (worldy - width)) - (m * gravity * y);
if(k < 0){ k = 0; }
u = m * gravity * y;
}

// Catch and reverse
public void move()
{
// Calculate u and k
k += u - (m * gravity * y);
u = m * gravity * y;
//Find dv based on k = .5mv^2
dv = ((2 * k) / m) - v;

// Catch and reverse on k or u < 0
if(k <= 0 && dir == 1)
{
dir = -1;
v = v*(-1);
a = a*(-1);
k = 1;
u = m * gravity * worldy-width/10;
dv = -1;
}
else if(u <= 0 & dir == -1)
{
dir = 1;
v = v*(-1);
a = a*(-1);
u = 0;
k = m * gravity * worldy-width/10;
dv = ((2 * k) / m);
}

// Finalise new movement
y += ((1+dv)*dir)/t;

// Print out values when needed
//System.out.println("x:"+x+" y:"+y+" u:"+u+" k:"+k+" - dv"+dv*dir);
}



public void draw(Graphics g)
{
// Draw to screen
g.setColor(Color.GREEN);
g.fillOval(worldx - (int)x, worldy - (int)y - width/3, width, width);
}

}

April 3, 2008

Fortran 95 BattleShip


Because I want to try taking every programing the CS Department offers this semester was Fortran. Definitely not quite like the other languages I know, but after getting used to it, I can do almost everything I can with C short of graphics and some string manipulation. After some short homework assignments, we where given our first big assignment, two player ascii battleship. Simple enough to complete in the 4 weeks we where given. I decided however to up the ante and add a simple ai system for one player games. Nothing fancy, just a random seek, with a focus on areas when something was hit, sill very easy to beat every-time. Yet it was somewhat impressive and if nothing else made it easier to test the program because I did not have to play against myself everytime.

I have uploaded it here with the Mac and Windows compiled versions plus source.

Fortran was definitely not designed with games in mind, but as with most programing languages with some careful planing and a bit of force you can easily get around such constraints.

March 9, 2008

PHP Thmbnail Function

I had whipped up a online photo album for the AMS website I am working on, however after photos where uploaded I realized that I was not using thumbnails, but instead the huge pictures, which on dial up would take years to load a large album. So I went looking for a good thumbnail function, sadly all the ones I found where way to complex for what I was trying to do. With no other options, I did some research and studied how the other functions worked an came up with my own simple version.


function makeThumb($im,$dest,$thumbwidth,$thumbheight)
{
$resizeResult = TRUE;
$imgResult = TRUE;

list($width, $height) = getimagesize($im);
$exttype = exif_imagetype($im);

$tim = ImageCreateTrueColor($thumbwidth,$thumbheight);

if($exttype == IMAGETYPE_GIF)
{
$image = imagecreatefromgif($im);
imagealphablending($tim, FALSE);
imagesavealpha($tim, TRUE);
$resizeResult = imagecopyresampled($tim, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height);
//header('Content-type: image/gif');
$imgResult = imagegif($tim,$dest);
}
else if($exttype == IMAGETYPE_JPEG)
{
$image = imagecreatefromjpeg($im);
$resizeResult = imagecopyresampled($tim, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height);
//header('Content-type: image/jpeg');
$imgResult = imagejpeg($tim,$dest);
}
else if($exttype == IMAGETYPE_PNG)
{
$image = imagecreatefrompng($im);
imagealphablending($tim, FALSE);
imagesavealpha($tim, TRUE);
$resizeResult = imagecopyresampled($tim, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height);
//header('Content-type: image/png');
$imgResult = imagepng($tim,$dest);
}

if($resizeResult != TRUE || $imgResult != TRUE){ return FALSE; } else return TRUE;
}


To use just call makeThumb("Location of Image", "Place to put thumbnail", width, height); Very simple, also it will return false if something fails inside. Remember to make sure the directory it is writing to has the permission to write set correctly or it will always fail.

December 23, 2007

Running Lejos on Mac OS X


One of the classes I took last semester was Artificial Intelligence, and after a long and horrible 9 weeks of prolog bootcamp, we finally hit the robotics part of the class. There was only one problem, we where using Lejos, which is a java based programing language for the Lego NXT bricks. This was fine because I am quite proficient with Java, the problem was that Lejos does not have native Mac OS support, and all of the forums that relate to it only give partial help or promises of support eventually. This is not good enough so I set off on an adventure to get it running on my MacBook Pro.

The first thing I did was to get the latest update to Lejos, big mistake, the linux Lejos 0.4.0beta would not work for me. I finally got it to force build, but this was only enough to get a broken firmware on the brick. Realizing this I went back to the 0.2.0alpha that we where using in class and this compiled fine. You just download it from the Lejos Site and unzip it. Place the entire lejos_nxj folder in the Applications folder. Then open terminal and cd to the build directory aka /Applications/lejos_nxj/build. Then type and run ANT and it will make a build for the Mac OS based on the build.xml file in the build folder.

The problem I ran into is that in terminal you have to ether set up a tcsh shell with the environmental variables set or set them in a .profile file in your home folder. Both of these worked but where annoying and took quite a bit of research on my part to figure out what needed to be done. Also you then need to use a text editor and run the build, compile and link command in the tcsh shell on the .java file each time you run it. Sadly this was no better than the PC solution, which was essentially doing the same things through Eclipse and batch files.

In lab I had done the basic PC Eclipse Setup, but quite frankly the whole button setup made me want to scream, not that was was that hard, but instead I found it very pointless for all of that work that was required. So after I got Lejos working on my Mac I started to write a small application that would let me code and then run the code in one simple step, and at the same time make the PC users in my class envious of its simplicity.

The final result I was quite proud of, and only took about a week of using/upgrading, plus a bit of unix scripting on the back end to get it to the point where I was happy enough to just bring my laptop to lab and use it instead. Also now that the class is over I spent a little time to clean it up a bit more and make it more usable for people other than me. If you are looking for a quick solution or are planing on doing something similar I have uploaded my application, which I am calling LejosTools. Get it Here I hope it can be as helpful to someone else as it was for me. Also I have included the source with it, because I have no plans to continue development. All I ask is if someone uses the code send some credit my way as a developer. Otherwise enjoy...

As a side note, I have not tested other versions of Lejos, but from what I have seen the unix commands have not changed, so if you can get something greater then the 0.2.0alpha working, LejosTools should still work. If they do change just update the lejosfull sh script in the resources folder.