Thursday, April 30, 2009

The Obvious Hidden

One problem with things that are obvious is that.. they're not ALWAYS obvious to everyone, but when it comes down to finding documentation for the obvious, it's.. well... obvious so nobody WILL document it.

Here's one obvious thing in Flex 3. The combo box is very versitile and great to use. Here's one way to load it up with complex data.


private function bindAddress(data:XML):void
{
var obj:Object;
var collect:ArrayCollection = new ArrayCollection();

for each(var props:XML in data)
{
obj = new Object();
obj.Unique_ID = props.Item_Index_ID;
obj.First_Name = props.First_Name;
obj.Last_Name = props.Last_Name;
obj.Address = props.Address1 + " " + props.Address2;
obj.City = props.City;
obj.State = props.State;
obj.ZipCode = props.Zip_Code;

collect.addItem(obj);
}

cbPersons.dataProvider = collect;
}


now this will allow the user to access all of the data from the combo box by using the "selectedItem" property. For instance, you can get the Address by using.

cbPersons.selectedItem.Address

This isn't the only way to do this, but it is at least one obvious way, well documented.

Sunday, February 01, 2009

Needles And Haystacks

Sometimes, programming is a matter of finding out the right sample or note that explains what you need to do in the right way or even just out right gives you the code you need. Having google at the tip of my fingers has given me quite the reputation of figuring out things quickly. (Of course, google isn't the only search engine out there, but I really like it)

So what I would like to do is to periodically put in what I did, how I did it, and sometimes where I figured things out. Of course, giving credit is hard sometimes, since the last thing on a body's mind is authorship when it comes to deadlines.

One example of which was the whole concept of RSS Feeds. It turns out that RSS feeds are simply XML documents sitting out there on web servers, being either recreated manually, or by services, or being generated on the fly by dynamic web pages.

So how do you get an RSS feed? Well, in ActionScript, you setup an HTTP Service. Here is how you setup a connection to the yahoo weather RSS service.




<mx:HTTPService
id="weatherService"
url="
http://weather.yahooapis.com/forecastrss"
resultFormat="e4x"
result="resultHandler(event);"/>




Basically, the service goes out and reads that URL and returns the XML data. Once the result returns, we can parse the data out as we need to.

In C#, it is a very quick matter of using an XmlTextReader and an XmlDocument. You create the XmlTextReader by passing in the URL of the XML document. Then load the XML document itself by using the XmlDocument's "Load" method.

So... we'll see what I come accross next and I'll post what I find.

Wednesday, January 28, 2009

Formulae Redux

Okay, I suggested a useful project where you create a program to parse out a formulae. Now I'd like to share an implimentation I made in ActionScript using Flex 3.










In my sample, I've decided to create a flash calculator. This calculator will take a formulae, and once the user presses the equal sign, will show the results.

Well, like in about everything programming, there can be arguments about how the "best" way to do this sort of thing, but I'll just go with the way that I think was a good way to go.


I think the best way to start is with your basic stack; a stack of "formula tokens." Think of what makes up a formula: numbers, operators, and parentheses. So we use the stack to build them. Normally, I would like to use a stack object, but since I couldn't find one already made, I decided to use an "ArrayCollection" as my stack object.

Tokenizing

However, there are some user interface considerations. While the operators are individual characters, the numbers themselves are built one digit at a time, and might include a period. So we need an intermediate stack of characters, with digits and operators. Therefore, as the user presses each button, a value would be "pushed" onto the top of the stack (in my case, added to the end of the array) one character at a time. Once the formula is complete, we will work on the evaluation of the formula itself.

Now, evaluating the formula must start with converting the array of characters that we have into a group of the tokens. This mostly involves combining the digits into numbers, and seperating out the operators. Here's the code that I used to seperate things out:



for (var x:int=0;x<formulae.length;x++)
{
if (isNaN(formulae[x]) && formulae[x] != ".")
{
if (tmpStr.length > 0)
{
LastNumber = Number(tmpStr);
tmpStr = "";
sc.addItem(LastNumber);
}
sc.addItem(formulae[x]);
}
else
{
tmpStr += formulae[x];
}
}
if (tmpStr.length > 0)
{
LastNumber = Number(tmpStr);
sc.addItem(LastNumber);
}






The key point to this idea is the function "is not a number" or isNaN. We are assuming that each token is seperated by an operator, and therefore, we will tack each digit together until we run into an operator, with the exception of a dot that can appear in a number. (Special Note: Obviously, this is a perfect spot to check the number to see if there isn't already a dot in the number to prevent a duplicate. However, in my application we are going to assume a valid input. In other words, "garbage in garbage out; diamonds in diamonds out"). If the digit is a number or a dot, we add it to a temporary string. Otherwise, it's an operator, so we convert the temporary string to a number, and add it to the stack (assuming it isn't blank, which could happen), and then add the operator to the stack. In the end, we result with a proper tokenized stack, and we're ready to start processing.

RPN

The next thing that I've decided to do is to process the formula as a postfix reverse polish notation. Don't ask me why it's called that. But I will say it is much easier to evaluate than most other ways you might want to resovle something like a formula. The process even makes it easier to get "priority" done correctly, where multiplication takes place before addition.

So here is the code for this portion of the code which creates a new stack in reverse polish notiation:



for(x=0;x<sc.length;x++)
{
if (!isNaN(sc[x]))
{
stack.addItem(sc[x]);
}
else
{
switch(sc[x])
{
case "(": tmpStack.addItem(sc[x]);
break;
case ")":
while (tmpStack.length > 0 && (tmpStack[tmpStack.length-1] != "("))
{
stack.addItem(tmpStack[tmpStack.length-1]);
tmpStack.removeItemAt(tmpStack.length-1);
}
tmpStack.removeItemAt(tmpStack.length-1);
break;
case "-":
if (tmpStack.length > 0 && (tmpStack[tmpStack.length-1] == "+" tmpStack[tmpStack.length-1] == "*" tmpStack[tmpStack.length-1] == "^" tmpStack[tmpStack.length-1] == "/" tmpStack[tmpStack.length-1] == "%"))
{
stack.addItem(tmpStack[tmpStack.length-1]);
tmpStack.removeItemAt(tmpStack.length-1);
}
tmpStack.addItem(sc[x]);
break;
case "+":
if (tmpStack.length > 0 && (tmpStack[tmpStack.length-1] == "-" tmpStack[tmpStack.length-1] == "*" tmpStack[tmpStack.length-1] == "^" tmpStack[tmpStack.length-1] == "/" tmpStack[tmpStack.length-1] == "%"))
{
stack.addItem(tmpStack[tmpStack.length-1]);
tmpStack.removeItemAt(tmpStack.length-1);
}
tmpStack.addItem(sc[x]);
break;
case "^": tmpStack.addItem(sc[x]);
break;
case "*":
if (tmpStack.length > 0 && (tmpStack[tmpStack.length-1] == "^" tmpStack[tmpStack.length-1] == "/" tmpStack[tmpStack.length-1] == "%"))
{
stack.addItem(tmpStack[tmpStack.length-1]);
tmpStack.removeItemAt(tmpStack.length-1);
}
tmpStack.addItem(sc[x]);
break;
case "%":
if (tmpStack.length > 0 && (tmpStack[tmpStack.length-1] == "^" tmpStack[tmpStack.length-1] == "/" tmpStack[tmpStack.length-1] == "*"))
{
stack.addItem(tmpStack[tmpStack.length-1]);
tmpStack.removeItemAt(tmpStack.length-1);
}
tmpStack.addItem(sc[x]);
break;
case "/":
if (tmpStack.length > 0 && (tmpStack[tmpStack.length-1] == "^" tmpStack[tmpStack.length-1] == "*" tmpStack[tmpStack.length-1] == "%"))
{
stack.addItem(tmpStack[tmpStack.length-1]);
tmpStack.removeItemAt(tmpStack.length-1);
}
tmpStack.addItem(sc[x]);
break;

}
}
}

if (tmpStack.length > 0)
{
for(x=tmpStack.length-1;x>=0;x--)
stack.addItem(tmpStack[x]);
}






This part takes some getting used to. Think about our three different stacks. The first stack has the formulae in the "infix" notation. The second one will contain the operators temporarily. The last will hold the actual reulting RPN formula.

So, if we run into a number, we automatically push that to the end of the results stack. If we find an operator, we have to work through do we push it to the results or push it to the operator stack. (This part is the one you need to pay attention to, cause it is hard to wrap around into words) Notice that we push things to the temporary stack mainly to hold them in order to allow the "priority" operators to be pushed on the stack before the lower "priority" operator. This is done with the check to see what operator appeared prior to it. This sifting naturally turns 3+6*2 into 362*+.

Evaluation

So lets take a look at that last formula. 3 6 2 * +. We first take the 3 and push it onto the stack. Next we take the 6 and push it onto the stack. Next we put the 2 onto the stack. No actions yet. NOW... we have an operator, the multiplication. So we pop off two values from the stack and execute that operator, pushing the result of that operation back onto the stack.

Here's the code:



for(x=0;x<stack.length;x++)
{
if (!isNaN(stack[x]))
tmpStack.addItem(stack[x]);
else
{
LastNumber = tmpStack[tmpStack.length-1];
tmpStack.removeItemAt(tmpStack.length-1);
ThisNumber = tmpStack[tmpStack.length-1];
tmpStack.removeItemAt(tmpStack.length-1);
switch(stack[x])
{
case "+":
tmpStack.addItem(ThisNumber + LastNumber);
break;
case "-":
tmpStack.addItem(ThisNumber - LastNumber);
break;
case "*":
tmpStack.addItem(ThisNumber * LastNumber);
break;
case "/":
if (LastNumber != 0)
tmpStack.addItem(ThisNumber / LastNumber);
else
tmpStack.addItem(0);
break;
case "%":
if (LastNumber != 0)
tmpStack.addItem(ThisNumber % LastNumber);
else
tmpStack.addItem(0);
break;
case "^":
tmpStack.addItem(Math.pow(ThisNumber, LastNumber));
break;
}
}
}

Result
= tmpStack[tmpStack.length-1];





Other Ideas
Oviously there are ways to improve this app. Most glaring is the idea of filtering the input to prevent garbage functions. Another idea is to check stack underflow's (too few operators) or overflows (too many operators not enough values).

Feel free to comment on this app. I'll post the full source code if I can feel confident enough about it.

Kitty Polyglot Choice

I'm the first to admit that I'm a polyglot: I know many different language. That might sound more impressive than it actually is, considering after so far, they all seem the same. But I've been working a lot lately with Adobe's "Flex" which is used to create Flash movies.

First, here's a couple links:

Adobe Flex SDK
Adobe Flex 3 Builder
Adobe Flash Player
Adobe Air

This will get you everything you need to make Rich Internet Applications or Flash movies, ready for business. And one of the best parts is that the engine behind everything is the SDK which is FREE! You can save a lot of time, and have a much easier job of things, if you have Flex 3 Builder, but you don't need it.

So, I will go over what I've learned about Flex continue on from there. I haven't given up on C/C++ or any other of the many languages, but I wanted to share what's at the top of my head first.

Stay tuned.

Monday, February 12, 2007

Formulae Solver

One very useful exercise--as well as one with practical application--is to create a program that reads in a formulae, and then solves it. This can be applied to creating a calculator all the way down to creating a preparser for a SQL statement. Because of time, I will break this over several days and over several possible approaches.

Problem:

You have an input of several characters, made up of symbols and numbers. Create a program to reduce the formulae down to a single solution.

Example:

5+3-(10 % 5)
(50-30)*3

Knowns:

The possible sets of input will be as follows: numbers between 0-9, at least one "period" for known floating point numbers, opening and closing parenthesis, and the operands.

Possible Operands:
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulous
^: Exponent
@: Square Root (yes, I know, I made that up)

The final known is, of course, the order of evaluation. Parenthesis first, then multiplication/division/exponential/modulous, addition/subtraction and finally our new "Square Root" function.

Application:

The way that I would approach this problem is the creation of a "First-In-First-Out" list of the characters in the file. This can be accomplished with any number of ways, including list objects or just an array of characters. But the first thing to do is to seperate the whole of the formulae into seperate "tokens" that can then be sorted into proper priority.

Tuesday, October 24, 2006

File Streams and Text Files

Files are simply a long stream of binary bits of data. The use of files depends on what the file is made up of; more or less, each file is written with a sort of pattern to make it possible to read it again and write it again.

The most common form of file is the "Text" file. The text file is basically filled with binary values from the ASCII character set (see previous graphic for more details on that). The pattern for the average text file is that for one, it will not hold any data other than the first 127 bites of the ASCII table (yes, there are exceptions, but this is the "basic" text file), there will be "End of Line" markers that will tell programs when to stick in a carriage return, and then there might be an end of file marker.

In a moment of non sequiter theatre, lets point out that the "End of Line" marker is different based upon the operating system involved. In Windows, the end of line is marked with a "Carrage Return" plus a "Line Feed" character, where as many unix systems only use "Carriage Return." Knowing what your text file is made up of is important before you commit to one method or another.

The methods of reading these files are so common and so often used, that just about every compiler has ways to read them. "Getline()" method will read from the first of the file, to the end of line marker, and return what it finds. "Writeline()" will write out a text line and include the end of line marker automatically. "eof()" will test if the text file is at the end of the file.

If you would consider a text file like a paragraph made up of rows and columns. Each row and column has a letter that fits inside that paragraph. Consider this picture:

[{tab}][I][{space}][a][m][{space}][a][{carriage return}][{line feed}]
[s][i][m][p][l][e][{space}][t][e][x][t][{carriage return}][{line feed}]
[f][i][l][e][{end of file}]

As you read from the text file, a cursor is advancing through each column and row as you pull data out. Once it reaches the end, no more data can be pulled.

Wednesday, October 18, 2006

Arrays Again


Memory on computers are a structured, ordered system. A spreadsheet is a wonderful way to represent it; if you look at the diagram, you see two aspects. One is the Address of the memory and the other is the contents of the memory. In general the memory is a certain uniform size: 8 bites. Things like characters can fit in a single address. Others, like Long Integers, have to fit in two memory addresses.

Arrays and pointers are addresses that contain addresses to other areas. This allows you to write programs dynamically instead of having to have set memory sets.

One array living at 0x0002 can possibly point to an array over in 0x0016 (this is a simplified view; its more complicated than that, but dont worry about it). The array starts at 0x0016 and keeps going until 0x0022.

Monday, October 09, 2006

File Streams Again



I would like to throw out some extra information about files. The above diagrams are two bits of important information. One is the general accepted heiarchy for the file streams. The second is one of the ASCII character sets. Knowing these numbers are important for dealing with files.

Consider the following file as an input example:

1,"Indionapolis, IN",$22.33,A1C
2,"Phoenix, AZ",$12.53,A3C
3,"Los Angeles, CA",$26.03,A5C
4,"Huston, TX",$2.83,A3C
5,"Fargo, MN",$42.33,A1C

Try out the following source code; this is the start of an idea to read in such a file. What are the limitations? What are the strengths? How can this work better?



Created with colorer-take5 library. Type 'cpp'

#include <iostream.h>
#include <fstream.h>

int main( )
{
char filename[255];
char tmpStr[300];
char qr;
int tmpint=0;
int x;

cout << "\n\n\nCSV FILE TESTER\n\n\n";
cout << "Enter the name for the CSV File: ";
cin >> filename;

if ( strlen( filename ) == 0 ) {
cerr << "Blank filename" << endl;
exit( 1 );
}

ifstream inFile( filename, ios::in );

qr = ' ';
while ( !inFile.eof() )
{
inFile.getline(tmpStr, 299);

x = 0;
while ( x < strlen(tmpStr) ){
qr = tmpStr[x];
if (qr == ',')
cout << " \n";
else if (qr == '"')
{
cout << '"';
x++;
qr = tmpStr[x];
while ( ( !inFile.eof() ) && ( qr != '"' ) )
{
qr = tmpStr[x];
cout << qr;
x++;
}
cout << '"' << endl;
}
else
cout << qr;
x++;
}
cout << endl;
}
cin.ignore();
return 0;
}