Saturday, June 5, 2010

Moving to wordpress...

I'm in the middle of moving my blog over to http://scottdowne.wordpress.com/. I will be spending the next few weeks fiddling with the smaller details of design, the sort of detail that can get someone like me wrapped up for days doing, but not accomplishing anything :).

I was impressed that I was able to just export all my old posts over to wordpress, by clicking a "magic button", literally, that's what it was labeled as. It's all automated, and a really painless process.

The reason for the move was for more robust visitor tracking.

I have some pretty cool ideas in mind for my new blog, as far as design goes, so we'll see how far wordpress allows me to hack it. I would like to get some processing.js sketches in my design, maybe in the background, or the banner, or both! if it's possible. If not, I might consider writing something myself, and hosting it myself, but I'm not there yet.

Friday, May 21, 2010

JavaScript is not Java

Just how deep does this rabbit hole go?

Saturday, May 15, 2010

Make one to throw it away

The title of this blog becomes more and more true the more I work in open source, but if you don't know what the title means, let me describe to you something about open source before i tell you what it means.

Open source development differs from school, and I can only assume, propriety jobs like a bank because in open source, if something has been written before, why are you going to write it again? At school, you spend so much time writing code that has been written hundreds of times before, by hundreds of students before you, these assignments are possible, have been proven, and if they were not possible, and they asked you to do it, you would be pretty ticket off spending days trying to figure it out, and you would probably think you accomplished nothing, and wasted time. You are wrong. When you are working on something that has never been done before, you have to try different things, there is no one to tell you what works, only ideas, because no one has done it. You have to think for yourself, make decisions for yourself, and be prepared to be wrong most of the time, until you get it right. You can be wrong hundreds of times, but only be right once... per problem that is.

To "make one to throw it away" means, before you get code that is working, and doing what you want, you have to make one or more versions that fail. This isn't too bad when dealing with a couple hundred lines of code, but something like 8000+ well, that bring me to my next story.

I've been spending the last week, trying to figure out a way to remove the final with() function call from Processing.js. In order to remove the with() function call, I had to rewrite a lot of the code... 8000+ lines of code, which also meant I had to understand (more or less) 8000 lines of code. If you are curious, here is the source in all it's glory. When you "make one to throw it away", you have just written and thrown away 8000 lines of code... if you think that's a waste of time, you are again wrong. This was 8000 lines more educational for me than rewriting 500 lines. It's simple math, really.


lines written * rewrites = productivity score :P

Thursday, May 6, 2010

Processing.js casting bug

I have been working on processing.js bug #625.

What's happening is there is some Java like code, that's being converted into JavaScript, so it can be run in a browser, and this bug deals with converting cast like syntax in java, into something usable in JavaScript.

JavaScript is typeless, what is important about this is the types between variables don't matter (for the most part) so when I create a variable of an int, I just create a variable, and make it an int, and if I need to know the type of the variable, I can check the type of what's in the variable, which would be an int. Looking at p5 append(), is what the cast is being used for in this bug.

"When using an array of objects, the data returned from the function must be cast to the object array's data type. For example: SomeClass[] items = (SomeClass[]) append(originalArray, element)."

In pjs, I don't think the cast is even needed, as append just returns an array, this is the pjs append code:


p.append = function(array, element) {
array[array.length] = element;
return array;
};


Maybe p5 (the Java version of processing) has append returning an array list, which would require the cast.

Either way, JavaScript does not need the cast.

I removed the cast in the example, and it works, but the problem still remains with parsing the cast, as it's valid code. In p5 the cast still needs to be handled by the parser, cannot just remove it. There is a way to do this currently in the parser, but it will only parse out classes inside a list.

One thing I could do is add "PVector" to the list of classes, which currently looks like this:


var classes = ["int", "float", "boolean", "String", "byte", "double", "long", "ArrayList"];


then in this code:


// Remove Casting
aCode = aCode.replace(new RegExp("\\((" + classes.join("|") + ")(\\[\\])*\\)", "g"), "");


It would find PVector, and remove the cast, without hurting anything else. Only problem I see in this is we'll have to add each and every pjs class to the list of classes, and if a new class is added to pjs, someone will have to remember to add the class to the list of classes. There must be a more dynamic way to accomplish this, which is what I want.

I thought about possibly parsing any instance of \(/w+\) and check that the match in w+ is "typeof Object" or something along those lines. Then I could remove the list of classes all together. Yes, I will try that. Thanks for the help blog.

Wednesday, May 5, 2010

Building Firefox on Fedora

Today I went to set up a working Firefox build environment ON Linux Fedora. It was actually easier than I first felt. When I would run into an error message, I would google it, and get an answer usually saying to add modifications in the config file to pass over, or to include, or change the version of various products.

Some of the problems:

  • Something called necko-wifi was not compatible, researching it I found I could just disable it in the mozconfig file by appending a line "ac_add_options --disable-necko-wifi". Solved, next error!

  • Something called maemo was causing an error message, and researching that I found a similar solution that didn't work, to append "ac_add_options --with-maemo-version=5", fixed, but this caused other issues.

  • I then found out, I could do a search for the missing files Firefox was complaining about using Fedora's "yum search 'name of file'" looking for something that looked like what was missing, and then "yum install 'file you found'" and crossed my fingers, would sometimes take a couple hits and misses before it would build, but after that each and every error was solved in that manner, including maemo.


I have to say I'm liking Fedora a lot. I also found a neat trick using vim, where you can do ctrl-p while typing a word to finish it, or scroll through words kinda like auto-complete. Linux can pretty much do anything I would need now.

Sunday, April 25, 2010

Solution to my last post.

In my last post I was trying to create a function that receives a multidimensional array inside parameters like (2, 4, 5) but with an infinite amount that could be passed in, and I was having problems with pass by reference, instead of pass by value.

I fixed it, and came up with a very simple solution:

p.ArrayList = function() {
var createArrayList = function(args){
var array = new Array();
for (var i = 0; i < args[0]; i++){
array[i] = (args.length !== 1 ? createArrayList(args.slice(1)) : 0 );
}

return array;
};
return createArrayList(Array.prototype.slice.call(arguments));
};

I came across the problem of arguments only acting like an array, but not having access to many array like functions, like slice(). Solution.

Array.prototype.slice.call(arguments)

Array.prototype.slice gets the slice method from the Array object.
call() allows you to call an object's function from the context of another object.
and the slice method would be called, using the function definition attached to Array, like it was part of arguments, and just return a copy of the array's values, as an array. :D

copy a multidimensional array in js.

I'm working on ticket #587, for processing.js.

What I have to do is convert a custom ArrayList function to create a multidimensional array based on parameters passed in. For example:

var array = new ArrayList(4, 5, 6);

would create a 3D array, similar to:

int[][][] array = new int[4][5][6]

This is what I've put together:

p.ArrayList = function() {
var array = [],
tempArray = [];

for (var i = 0, aLength = arguments[arguments.length-1]; i < aLength; i++){
array[i] = 0;
}

for (var i = arguments.length-2; i >= 0; i--){
tempArray = array.slice();
array = [];
for (var j = 0, aLength = arguments[i]; j < aLength; j++){
array[j] = tempArray.slice();
}
}
return array;
};

It starts at the back of the arguments, and copies the array recursively until it's done arguments[0], then returns the array.

In JavaScript arrays are copied by reference, and not by value, but if you use array.slice() it creates a copy of the array's values, but not a copy of the array inside the array, those are still passed by reference. In other words, it only works for single, and 2D arrays, anything larger and you start getting arrays containing references to the same data, which is not good.

I'm going to have to find a better way to do this, it must be recursive, and must be based on the number of arguments.

Wednesday, April 21, 2010

OSD600 is over

After tomorrow, I'm done this semester, and the real test begins: will I continue blogging between OSD600 and OSD700. It's already been a week since my last post, but not because of being almost finished, but because of English assignments and exams, and right now I have a breather (I never study hard the night before the exam, I just make sure I didn't miss anything). I would like to say I'll continue blogging for as long as the internet lives, but time is a better test. I really do feel like I've found a great spot in open source, and I'll enjoy it while it lasts.

Anyway, I've been trying to do at least one push to processing.js a day, while I study, big or small, at least one contribution.

Over the last week though, I've really got into irc, and branched into a few of the other channels, which have a totally different atmosphere than the processing.js channel. I got involved in the open source vs proprietary argument, which despite being educational and funny, really is never solved. I've tried to get some to at least try it before they slag it, but I guess for some programming is for money *shrugs*. I've told them to at least take the osd600 class in the fall, because they are quite promising students, just bias and not willing to try certain things. I tried explaining that open source is a good way to get work experience to get those jobs that make all the money they keep talking about. For them to take OSD600, they wouldn't be programming for free, but for marks, and that's what they do in all their other classes.

Wednesday, April 14, 2010

JavaScript this keyword

I know this this keyword's (in JavaScript) meaning changes depending on how it's called, considering this class:

function Obj() {
this.item = "contents";
}

and using it like this:

var obj = new Obj();
obj.item += " of this.item"; // item now contains "contents of this.item"

the this. keyword means the object only when it's called with new keyword, which declares it as an object.

Now, if I am to change the object slightly, like so:

function Obj() {
this.item = "contents";
var funct = this.funct = function(){
return this.item;
};
}

I have two functions that should return the item inside the object. var funct should be usable inside the object, and this.funct should be usable outside the object, and do the same thing. Cept, when a function is created with var funct, the meaning of this. changes again. I'm not sure what it changes into, but in the above example, when I call funct() from inside the class, it returns "undefined". Everything makes sense, I'm just not sure what happens to this. in that crazy example. There is a way to fix this. You need to put the function inside of a closure, sending this, and using it as another word. For example:

function Obj() {
this.item = "contents";
var funct = this.funct = (function(obj) { return function(){
return this.item;
};})(this);
}

What this does is, instead of sending a function using the this. keyword inside, it creates an anonymous function, sending the object this, RENAMING it to obj, and returning a new function where this is changed to obj, hiding the double meaning of the this keyword, making it refer to the same thing no matter when and how it's called.

I've been learning the meaning of this, and I thought I had it figured out. This just shows you can never know you know everything, only that you don't know everything, by learning something you didn't know :P

Monday, April 12, 2010

with(this) { ... } // no more

Here is the source, and an example for processing.js with "with(this) { ... }" removed.

I was having issues using the new getters and setters. What was happening was considering this JavaScrpt class.

function Foo() {
this.value = 0;
__defineGetter__('value', function() { return this.value; });
__defineSetter__('value', function(x) { this.value = x; });

this.getValue = function(){ return value; };
this.setValue = function(x) { value = x; };
}

The this. keywords scope wasn't as intended. It was actually referring to the getter or setters, and not the object that uses it. I solved this by putting it into a closure, and passing the object I wanted the getters and setters to be added to, like so:

function Foo() {
this.value = 0;
__defineGetter__('value', (function(obj) { return function() { return obj.value; };})(this));
__defineSetter__('value', (function(obj) { return function(x) { obj.value = x; };})(this));

this.getValue = function(){ return value; };
this.setValue = function(x) { value = x; };
}

OSD600 release 0.3

I guess technically I'm late on this release, but these things happen when you're doing stuff with this ;)

I have been back and forth on this private ticket for while, trying different things, doing research, and then finally worked with Dave to get it perfect. I did get lots done on it, even thought it's not all going to be used, I consider the research and work I did to be part of my 0.3. Here is a post on what me and Dave worked on, and this is a better foundation for future work in the class parser.

I also worked with Andor Salga. One of his 3D examples had a silly parser error, so I filed a ticket and fixed it. It was up for review, but I had to back up because it was relying on code from a previous fix that's not going in. It was a simple parser fix, so it won't be hard for me to re implement it when the time comes. Also, Andor has a way around it, so his 3D example does work now. This is the example he was working with, if anyone is interested.

I was able to fix, and not have to back up ticket #536 and it's awaiting review.

I have learned one very important lesson; if two, or more bugs reside in the same spot in the code, I should consider keeping them in the same ticket, then I wouldn't of had the problems I'm having with ticket #133, mainly, having to revert a bunch of my "peer review requested". Really though, with the getters and setter, these are all going to be easy to refix (also, because I've already fixed them).

Friday, April 9, 2010

processing.js private and public finally working, I think

I think I have finally finished processing.js ticket #133.

A simple test to see it.

And a cool example that uses public variables. This particular test program was giving me the most difficulties while I was coding. It seemed whenever I would run the automated tests, this one would always have a new problem, and it also happens to be a long test, so it's harder to debug, so to be able to edit it and change the example is satisfying.

I just need to write some clear, simple, and thorough test cases for private and public use, and I'll be done.

Thursday, April 8, 2010

I love you word boundary.

A word boundary is, other than my savior, a regular expression match that matches the tiny, invisible space between a word character (a-zA-Z0-9_) and a non-word character.

You use it with \b and \B (\B matching a non-word boundary, same as [^\b])

Example: "this is some text" with the regular expression \bs. This would only match the "s" in "some" because there is a non word character before the s. Also, if you did s\b it would match the "s" in "this" because it's before a non word character. Finally, \Bs would match "this" and "is" and s\B would match "some". I hope that all made sense.

I needed this in a particular problem where I had to parse some code, and catch any specific words, globally. The problem was, when I checked for a match (previously) I was checking for (\W) which is a non word character, then check for my matching word, so if I was looking for all instances of "scott" I would not want to catch "scotty" as in this case, would be a different variable. So, /(\W)(scott){\W)/g, problem with this is, it would "eat" the leading and trailing characters, making any other matches in the string not check the leading and trailing characters again.

By using \b, I was able to check what I needed, without "eating" the leading and trailing characters.

If anyone is curious, the final product looks like so:

// add this. to public variables used inside member functions, and constructors
if (publicVars) {
// Search functions for public variables
for (var i = 0; i < methodsArray.length; i++) {
methods += methodsArray[i].replace(/(addMethod.*?\{)([\s|\S]*\}\);)/g, function(all, header, body) {
return header + body.replace(new RegExp("(\\.)?\\b(" + publicVars.substr(0, publicVars.length-1) + ")\\b", "g"), function (all, first, variable) {
if (first === ".") {
return all;
} else {
return "this." + variable;
}
});
});
}
// Search constructors for public variables
constructors = constructors.replace(new RegExp("(var\\s*?|\\.)?\\b(" + publicVars.substr(0, publicVars.length-1) + ")\\b", "g"), function (all, first, variable) {
if (/var\s*?$/.test(first) || first === ".") {
return all;
} else {
return "this." + variable;
}
});
}

Obviously, there is code before and after, with declared variables, but just use your imagination ;) and I'm still looking for bug, but feel free to scrutinize my code.

Wednesday, April 7, 2010

Stuck on Processing.js private and public variables

It's been awhile since I posted, but I needed to create some time, which meant moving things around.

Warning, this may seem more like a rant, or crazy ramblings than a normal blog post. I'm just going to write it all down, in hopes that it helps me better understand all that I'm dealing with.

Alright, to start off I'm working on processing,js, specifically ticket #133 (still). It didn't seem hard at first, and I had a lot of initial success, but as I went deeper, I kept finding more and more. This has really taken a lot to get right.

What I'm trying to accomplish, is to grab a class, so I can work with, and parse just the class, as to not parse non class related code. Once I'm in the class, I want to grab and remove the class functions, and constructors for later use, I don't want to be parsing "var i" that is contained in a function, into a private variable. Outside the function, anything that's private, is private, and public is public, but by default, it should be public. This is why I cannot be parsing functions and constructors, but I also have to know what's public, and what's private by the time I work with the functions and constructors, because when a public variable is used in a function or constructor, I need to add a "this." in front of it.

I think some day, hopefully soon, all this class parsing code should have a major overhaul, as I keep coming to code that I don't see any use for, but I'm not comfortable removing it yet. I'm starting to fix things, and as I do, other areas should be removed. I think that would be better suited for a separate bug once I got private and public working.

I did take an attempt at overhauling the class parsing, but I'm conflicted if I should just redo it, and go from there, or if I should use what's already there. I believe most would say not to redo it, but it's still tempting.

Right now, I'm dealing with some code that's being "left behind" as I move parts of the class up, and other parts down. I know that classes with a constructor is parsed separately than a class without a constructor, but I don't think we should be doing this. What we should do is, open the class up, from top brace to bottom brace, and deal with any constructors contained within, as we get to them. This also has the advantage of not needing constructors to be declared first thing, and any member variables can also be declared anywhere. I've made a work around for this, but now I think it's causing my "code left behind" problem, as the code left behind is either the class declaration, or a constructor declaration. For example, imagine a class called Place, when I parse it, I'm left with a line of code like this "processing.Place = function" I think it's a case of a regex somewhere just working with what's between the {} and not what's also in front of it.

Another issue that was solved about a day ago, is private and public functions, being declared with a custom "addMethod()" function, which for the longest time made no sense to me, and I hated it. I have since understood it, and although I still don't like it much, I see the need and don't want to remove it. This function wants an object, a String, and a function as it's parameters, and it will then create a function, with that name, and add it to the object you send, also allowing for overloading (the reason why it's there, is for overloading) I was stuck figuring out how to add a function to this. without making it public. I would send "this" as the object, into addMethod, I thought about intercepting it, and making private functions separately, but then we would be left with separate code for public functions, and private functions, not very ideal. I decided on adding a private object called private to the scope of the class, then when I want to add a function to the private scope, instead of sending "this" I would send my "private" object. The caveat with this is I now have to parse the functions and constructors in the class for any use of a private function, and add "private." in front of it, much like how I add "this." to public variables.

The other option would be to add a "with(this){with(private){ .. }}" around all the code. This would check all variable and function calls if it's inside private (which I would create as "var private = {}"), if not, it would then check if it exists inside this, the problem is, if it doesn't exist inside private, or this, it would be created as a global variable, I think, possibly overwritting any global instances of that variable already defined. Processing.js already uses "with(this) { .. }", and I'm trying to remove it, with moderate success, but it's extremely helpful in this case, and is the difference between 2 lines of code, vs 50 lines of code (I may be exaggerating, as I have not counted which lines are new, and which are being left, or modified, but it's a lot). I plan on talking to David Humphrey in person about possibly, continuing the use of "with()" even with the dangers involved.

I have to admit, this has been quite challenging, and I'm getting kinda frustrated with it, but I guess that's a good thing? *shrugs*

Tuesday, March 30, 2010

public and private in JavaScript

In order to enjoy programming in JavaScript you have to be at least a little crazy. Take this for example:

function Obj() {
var private = {};

this.publicVar = "inside";
private.privateVar = "inside";
this.getPublic = function() {with(this){with(private){
return publicVar;
}}};
this.getPrivate = function() {with(this){with(private){
return privateVar;
}}};
}

This is, I think, the complete way to emulate Java objects with private and public usage. All other ways are close, but always lack some little oddity that makes it less than pure. Another good thing about this method is it's easily created after parsing Java-like code.

Take this usage for the above object:

var obj = new Obj();
alert(obj.getPublic()); // should alert inside
alert(obj.publicVar); // should alert inside
obj.publicVar = "outside";
alert(obj.publicVar); // should alert outside
alert(obj.getPublic()); // should alert outside

alert(obj.getPrivate()); // should alert inside
alert(obj.privateVar); // should alert undefined
obj.privateVar = "outside";
alert(obj.privateVar); // should alert outside
alert(obj.getPrivate()); // should alert inside

Now, I think I've thought of everything, and everything else, but if anyone out there can break this, or find a shortcut, or challenge it in another means, I would be very grateful. Note, if you want to try breaking it, you don't have to understand the class itself, just how to use it, like I did in the second example.

Monday, March 29, 2010

blog post patch

Ok, I wasn't 100% correct in my last post. There was something I didn't consider.

Where I said:

Considering this class:


class Obj {
private String item;
public void setItem(String str) {
item = str;
}
public String getItem() {
return item;
}
}


and consider this usage:


Obj thing = new Obj();
thing.setItem("this has been set");
println(thing.getItem()); // prints "this has been set"
println(thing.item); // prints undefined, as it's not been used yet


Everything working as intended, until I try this:


thing.item = "if you see this, it's broken";
println(thing.getItem()) // prints "if you see this, it's broken" :(

I was wrong, that should work as I originally had hoped, but what was happening was processing.js would wrap it inside a with(this){...} function, which I'm still looking into, but it was doing things that I figured was just normal JavaScript, so I over looked it.

Here are some comparing classes, to illustrate what I mean:

// What should, and does work as intended.
function Obj() {
var privateMember = "hidden";
this.getMember = function() {
return privateMember;
}
}
var obj = new Obj();
alert(obj.getMember()); // alerts "hidden"
obj.privateMember = "not hidden";
alert(obj.getMember()); // alerts "hidden" :D

Now, what processing.js does:

// Does not work as intended.
function Obj() { with (this) { // This is the only change
var privateMember = "hidden";
this.getMember = function() {
return privateMember;
}
}}
var obj = new Obj();
alert(obj.getMember()); // alerts "hidden"
obj.privateMember = "not hidden";
alert(obj.getMember()); // alerts "not hidden" :(

Now, why not yank "with(this){...}" right out of there? I don't know what it's doing, yet. More on that later. But I'm hopeful to say I have a pretty solid direction.

processing.js public members public to everyone but itself

Ok, here's what I'm doing. I'm trying to implement the private/public keywords for processing.js

And here are the problems. First attempt was ages ago, and that was to, inside a class, use this.variable; for public, and var variable; for private. This sort of worked, as it allowed me to use public members freely inside and outside the object, and I could not access private members, until they were set from outside the object.

Considering this class:

class Obj {
private String item;
public void setItem(String str) {
item = str;
}
public String getItem() {
return item;
}
}

and consider this usage:

Obj thing = new Obj();
thing.setItem("this has been set");
println(thing.getItem()); // prints "this has been set"
println(thing.item); // prints undefined, as it's not been used yet

Everything working as intended, until I try this:

thing.item = "if you see this, it's broken";
println(thing.getItem()) // prints "if you see this, it's broken" :(

It's not very useful if private is restrictive but not protective. I thought the whole purpose was to protect you, the person using the object, from themselves, and not just restrict them from, themselves.

Anyway, I wasn't done there. I spent this weekend rewriting the way processing.js translates a class. I was changing it so when you created an object, instead of returning an object, I would call a function that would set all the private members and functions, then return an object literal that would contain all the public variables and functions, which had access to the members in the preceding function, but those members no longer existed, and it worked! Here is an example of what I mean:

function Obj() {
var privateVariable = "It's a secret to everybody";
function privateFunction() {
...
}
return {
publicVariable: "...",
publicFunction: function() { return privateVariable; }
};
}

Usage of this is like so:

var obj = new Obj();
alert(obj.publicVariable); // alertss "..."
alert(obj.publicFunction()); // alerts "It's a secret to everybody"

Everything as expected until I try this... Consider this modified class:

function Obj() {
return {
publicVariable: "...",
publicFunction: function() { return publicVariable; }
};
}

and this usage:

var obj = new Obj();
alert(obj.publicFunction()); // crashes

So now, a private member is private to everyone but itself, which is good, and a public member is public to everyone... but itself. Two solutions, with two completely opposite caveats.

Final though: while writing this, I was thinking, and organizing my thoughts (kinda the point of blogging, for me) and I have two options I need to explore.

  • Change the public functions to use public variables with a "this." before it. Example:

    return {
    publicVariable: "...",
    publicFunction: function() { return this.publicVariable; }
    };

    This works, but isn't very practical as I'm translating Java-like class syntax into the javascript you see now, and I don't want to go through all the code, just the structure; this method would require looking for the usage of all public variables, once I have a list of public variables, and add "this.". Not ideal.

  • Another option, which I'll try, is to add a list of public variables at the top of the code inside a function, like this:

    return {
    publicVariable: "...",
    publicFunction: function() { var publicVariable = this.publicVariable; return publicVariable; }
    };

    Passes the public variable inside this, into a new variable with said name, so I don't have to touch the code inside the function, just add a header of sorts. I would have to do this with functions too.

Sunday, March 28, 2010

JavaScript and multiline regular expressions

Just something I would like to share, because it was causing me grief :P.

While working on parsing a Java-like class into a JavaScript class, for processing.js. I needed to grab all member variables that are marked as public, using a regular expression, and return them as an object literal. Given this as an example:

public String thingOne;
public String thingTwo;

Into this:

{
thingOne: null,
thingTwo: null
}

This is what I ended up doing:

middle = middle.replace(/(?:(private|public)\s+)?(var[\s|\S]*?;)/g, function(all, access, variable) {
if (access === "private") {
return variable;
} else {
variable = variable.replace(/,\s*/g, ";\nvar ");
publicVars += variable.replace(/(?:var\s+)?(\w+)\s*=?\s*([^;,]*)(?:;)?/g, function(all, name, value) {
if (value) {
return "\n" + name + ": " + value + ",";
} else {
return "\n" + name + ": null,";
}
});
return "";
}
});

Now don't worry too much about that, just a short background of what I was doing to bring me to the problem. Multiline regular expressions in Javascript.

From my favourite Javascript regex resource "Multiline Input 'm' This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively.". It does NOT do what you would expect, it simply allows code like this:

String one;
String two;

to match both lines with this /^String/gm. Without m, String two; would not match as it does not start at the beginning of the line, but after a \n. Another way to look at it is, m changes the meaning of ^ and $ to also match \n and \r (\r being carriage return). JavaScript regular expression is already multiline, in a way, as all lines are actually one long line with newline characters.

What I wanted to do was match any instance of "var (bunch of stuff) ;" spanning multiple lines. To grab examples like this:

public String thingOne,
thingTwo;

What I was using was something like this /var.*?;/g grabbing anything between var and ;, including whitespace and newlines? right? Nope, apparently not.

There was a trick I found to solve this. /var[\s|\S]*?;/ This uses \s which is any whitespace, including newline, OR \S which is anything NOT a white space, this is the TRUE anything, and a neat little trick.

Wednesday, March 24, 2010

morning train ride tangent

This morning, on the train, I wanted to open up processing.js and get back to working on ticket #237. I got into it, earlier and reproduced all the problems that the ticket entails. We have empty classes with no methods or constructors not working, we have constructors following methods working, but the methods above the constructor not working, and we have the hardest problem in overloading only working in terms of number of arguments, and not types of arguments. What I mean is:

void addItem(int item){...}
void addItem(String item){...}

This is valid processing, because the two methods are different, but, in JavaScript, variable types are not important, and the above code will be translated into:

var addItem = function(var item){...};
var addItem = function(var item){...};

The methods are translated into the same method, this also does not work with constructors either, which is a different problem because the way processing.js handles consturctors. What processing.js does is, because you can send any number of arguments into a method or constructor, and access the variable by using arguments[n], in a for loop less than arguments.length. This is how constructor overloading is handled in processing.js. There is only one real constructor, it just has if statements checking how many arguments there are. Here is an example for how processing.js translates a class:

class Obj{
Obj(String item){
item = "in constructor one";
}
Obj(int item, String item2){
item = "in constructor two";
}
}

into this:

function Obj() {with(this){
if ( arguments.length === 1 ) {
var item = arguments[0];


item = "in constructor one";

}

if ( arguments.length === 2 ) {
var item = arguments[0];
var item2 = arguments[1];


item = "in constructor two";

}


}}

If you notice, it's just one method that filters out the contents of the constructor into various if statements, but it's only the length of the arguments, and not the types. What I would need to do is grab the types before the types are lost, and then add a type check for all variables at the same time I check the argument length, but methods are not like this.

Funny thing is, while researching this, I came across this blog post, and as soon as I saw the code, I recognized it. This is John Resig's blog, and he is the creator of processing.js, and his post helped me a lot with how to understand the addMethod, method, and the caveats involved.

Ah shoot, I got off on another tangent. Ok, While I was planning on doing this ticket I have been talking about up to this point on the train, I ended up seeing something in code that made me go back to my last ticke on array initialization. I noticed, later in the code, the use of ArrayList() for more than just creating an array, but initializing. I still cannot get it to initialize the array, but I've spend an unexpected morning on this. The idea of ArrayList is to send a size for the array, to create it, but all the values will be empty. Like so:

new ArrayList(2); // creates an arraylist with 2 empty items
new ArrayList(2, 2); // creates a 2D arraylist with an array of two, with two empty items

I saw later in the code something like this

new ArrayList(["Thing 1", "Thing 2"]); // apparently, this is creating and initializing an arraylist

Like I said, I didn't (yet) get this to work, but I think it would improve the way it's already being done, with just the array like this:

var things = ["Thing 1", "Thing 2"];

I should get this wrapped up into:

var things = new ArrayList(["Thing 1", "Thing 2"]); // this would be ideal

My train ride tests did not work, but I'm going to reduce it more and see why. First I should get arraylist initialization to work. period. Then I will attempt to add it into processing.js. Anyway, that's all for today.

Tuesday, March 23, 2010

Processing.js array initialization

Just the other day I fixed a bug for processing.js, where creating an array and initializing it at the same time would crash the parser. What was happening was, code like this:

float[] baz;
baz = new float[] {1.0, 2.5};

when parsed, "new float[]" would be converted to "new ArrayList[]" then "{1.0, 2.5};" would get tacked onto the end, and it shouldn't. "new ArrayList[]" is only for creating an empty array, without initializing it. If you want to initialize, you want the JavaScript to look like this:

baz = [1.0, 2.5];

notice how I no longer use new ArrayList. ArrayList just isn't setup for initialization that I could see, but the above method works.

Anyway, I got all this working fine and dandy here.

When the parser came across something with the word "new\s(\w)" which translates to "new" + whitespace + any word, it would package it all up, what I did was added a check for the array contents, ie. everything inside {} it even worked for 2D arrays and beyond. I would then simply replace the whole thing with the array initialization, and later in the parser it would be changed from {} to []. So, whatever the array was, {{1.2, 2.1}, {7.6, 8.8}} for a 2D array, would just replace all {}'s with []. The problem was, and I didn't notice this until after the patch was submitted, noticed it on the train ride home, was that two arrays can be declared on one line. Sometimes things like this just slip everyone's minds, there are so many ins and outs of a language, and to translate one language to another you have to have good attention to detail. So, something like this:

baz = new float[][] {{1.0, 2.0}, {3.0, 4.0}}; baz2 = new float[][] {{1.0, 2.0}, {3.0, 4.5}};

would break my fix. It would gobble up the whooole thing into one, and the second "new" would get lost, and cause a syntax error. the fix was pretty easy, and I fixed it one the same train I thought of it on. All I had to do was eat all {}'s and everything inside of them until I hit the semi-colon, then stop! the stop is important, and the part I was lacking before. Before I would gobble it all up until I hit the last semi-colon, so, it was greedy.

Here is the fix. Also, I'll be fitting this work into my 0.2 release as it's so very close.

Something else I noticed today (hijacking my own blog post here) working in Processing.js has a pretty big advantage over working in other open source projects. We are a community of developers, so when someone finds a bug, half the time, most of the work in finding the bug is done for us, because the person that found the bug can read the code, and reduce it to a acceptable level of code. But, in a project like Firefox, when a user finds a bug, it might just be a description of what they were doing at the time, and that it crashed. Which is an interesting aspect maybe some of the other members of the processing.js team might not of considered, yet.

Friday, March 19, 2010

0.2

Intro


This release has been weird. My main, original tickets 230 and 133 for this release were not as expected.

Problems and Challenges


230 already existed, but just didn't have any life, I just needed to breathe some life into it by writing some code to show it works, it was more of a documentation issue. The ticket is still awaiting review. I felt out of place with this one, and still do. I had a lot of fun writing it, and even more fun creating this example, but the fact that my code isn't really going to be added, just, feels weird. What I think would be best, and I'll push for this when the time comes. In the original processing there is a place on their website for hacks, basically, lists features, and shows examples, of things that can be done with processing through the use of java, that was not intended. What could happen in processing.js is sort of the same thing, a place on the website, that documents all the hacks that can be used, through the use of JavaScript inside the processing.js code, and this would be a big job, but something that should probably be done much later, maybe even after 1.0 of processing.js has been released. Until then, I feel like my 230 creation is a lost soul.

My other main ticket, ticket #133 also had issues. In the past I struggled with getting the private keyword to work on member functions, but the way processing.js created member functions, through using an addMember function, caused me issues. I would have to intercept the the addMember function, and create it my way. Although, Dave, was showing a trick in JavaScript, on how to make classes, with members, and it seemed to make a lot of sense. This is the code.


var counter = (function (){
var c = arguments[0];
var i = arguments[1];

return {
increase: function(){c+=i;},
getValue: function(){return c;}
};
})(1, 2);

counter.increase();
alert(counter.getValue());

counter.increase();
alert(counter.getValue());


Also, I have mentioned before, that Corban Brook is working on ticket #237 and talked about restructuring the way classes are parsed. I've been holding off working on ticket #133 prviate keyword because of possible changes.

Specifications


What I did do for 0.2:
The main one, was the example used for 230, and the ticket itself.

I also did three little ones to to supplement this release.
Tickets:

I've done some review of other tickets, and found a ticket that was fixed from my 0.1 that I didn't see. All easy stuff, but it adds up, and still must be done right.

Conclusion


This release has been very different than my last in terms of the work done, and I spent a lot less time trouble shooting, and more time creating tests and examples. I am still finding my groove. Finally, Corban said I could take a stab at ticket #237, I will probably do that and my private keyword at the same time, for my 0.3, and still try to get my regex parser fit in somehow, it shouldn't be a problem as it's really only two tickets, and all related to parsing, stuff I've been doing since the beginning of my stay here :)

Tuesday, March 16, 2010

Quick little fix

Yesterday, while cruising the processing.js bug tracking website lightouse looking at the open tickets, and seeing what was happening I can across ticket #382.

It was small so I figured I might as well do it. Throw it in with my 0.2.

I've also started thinking about doing what I did here for string parsing to regular expressions. The first thing that comes to mind is the order in which I must do this. I can mask all strings first, then mask all regular expressions, or vice versa. I would have to replace them in the opposite order in which I mask them, that's a given. I also have to now modify my as I now have to check if a string contains OR , as an example. I think it would be easiest to mask regex first, as I already have the code to check that it's not in a string. So, use that code, find all regex's not in a string, mask them, and any string like code inside the regex will already be gone, so I wouldn't have to check for regex when I mask the strings, and replace again, but in reverse.

Sunday, March 14, 2010

Tabs break nothing!

I mentioned in my last post that I would be taking something on to add to my 0.2, so I did processing.js ticket #351 and wrapped it up the same day. Not bad, but it was easy.

In my last post I talked about how I was able to reproduce the bug, and the next step was to find, where in the code, variables are changed to var. This is what the code in question looked like before I got to it.

// float foo = 5;
aCode = aCode.replace(/(?:static\s+)?(?:final\s+)?(\w+)((?:\[\])+| ) *(\w+)\[?\]?(\s*[=,;])/g, function (all, type, arr, name, sep) {
if (type === "return") {
return all;
} else {
return "var " + name + sep;
}
});

What is happening, is it's matching a regular expression to the code to be parsed, sending the matched groups into a function in the order of (all, type, arr, name, sep) the first parameter is always the whole matching string, and each one that follows is the next match group and so on. The function will do something with the sent values, in this case, swapping the variable type for "var " and removing any array brackets. this new string is then replaced with the original matching string.

The problem was, it was only doing this if there was a space between "int i" this is a closer look at the culprit "(\w+)((?:\[\])+| ) *(\w+)" first it matches a word, something like int, char, anything like that, then it look for any number of [] OR a space, then 0 or more spaces, then another word. I simply changed the spaces to \s, which included all whitespace, including tab, and not just a space, resulting in this.

// float foo = 5;
aCode = aCode.replace(/(?:static\s+)?(?:final\s+)?(\w+)((?:\[\])+|\s)\s*(\w+)\[?\]?(\s*[=,;])/g, function (all, type, arr, name, sep) {
if (type === "return") {
return all;
} else {
return "var " + name + sep;
}
});

Now when a tab is found between int i; it's not ignored, the parsing of int i; is not ignored.

Saturday, March 13, 2010

Back!

It's been a week since I blogged, but I've been all over the place doing small stuff and getting organized, and there wasn't much to say :P

My 0.2 is due next week and I've got my mouse scroll awaiting review, and here is my post covering that, but I would like to get one more thing pushed out before next week is over.

I have the private keyword that I've been working on in the past, and kinda pushed it to the side in favour of string parsing. I figured I would go back to the private keyword but I noticed Corban Brook was working on this ticket, which may include an overhauling for the way processing.js handles the parsing of classes, which would make the way it handles the private keyword too, hopefully making it easier for me later. This excites me and I'm going to be following it, and pushing the private key word back to 0.3 along with another planned ticket to parse regex content much like I parsed string content.

Anyway, for now, I've decided to take on this one tabs break code. This is a bug that causes the code to crash if a tab is used in a certain place instead of a space. I have reproduced the bug and it seems to only work (the bug works, not the code:P) when there is a tab after a variable type, but before the variable name, like so:

int anInt = 0;

This does not work, but oddly enough, these example DO work:

int anInt = 0;
println (anInt);

The only place this causes the error (that I have found) is after the variable type and before the variable name. I printed off the translated code, after it's been turned into javascript to see what's going on, and this is the result of the above error:

int anInt = 0;

and if I take out the tab, I get:

var anInt = 0;

Which works, so obviously, the tab is stopping the conversion of variable names in java like int, to var in javascript. The solution is probably pretty easy, just need to look through the parser, look for the regex that converts variables to vars, and add in a condition for tabs

Thursday, March 4, 2010

Study week day 4: something to show

My five day mission is coming to an end, and I have something to show for it.

In order to view this experiment, you must have a capable browser. I use Minefield. Click this link for more information.

Once inside, you can use the arrow keys to rotate the cubes up and down. Not much else to tell, so here are the examples: example 1 and example 2

A screen shot of example 2 for those currently not with a capable browser.


This gives me an idea though. Have a player that can be moved with the arrow keys, and he moves along this giant cube. You can rotate the cube with the mouse, and there is a 3D randomly generated maze on the cube. As the cube moves gravity would change, so the player (and the maze) wrap around the cube. Finally, add multiplayer.

Wednesday, March 3, 2010

Study week day 3: Vectors Matrices and Vertices

In this post, I blindly set out on a mission, a mission that may or may not change, and has changed.

I was going through these tutorials and as helpful as they are, it's just syntax at this point. I am able to modify, through trial and error, and create and move things, the problem is I don't fully understand what's going down. In these three things: Vectors Matrices and Vertices, are giant question marks.

So I've decided to back it up, and get an understanding of how to represent, modify, and move 3D objects.

What I know and understand.

A vertices is a set of three x, y and z axis that create one point (or corner) of a 3D object. x and y axis is left right, top and down, 2D stuff, the z axis is the third dimension.

These are stored in a matrix, which is just a grid of numbers, rows and columns, that hold these vertices, kinda like an array of vertices. example:

1, 0, 0, 0
0, 1, 0, 0
0, 0, 1, 0
0, 0, 0, 1

This is called the identity matrix (correct me if I'm wrong). It's like a null matrix as anything you try to translate it into would end up being the same thing as it was before the translation. I cannot explain it much more as the technical concepts of translation still escapes me, but I know it's used to move the objects axis in a uniform manner, keeping the integrity of the shape, I get the concepts, I just don't know how it all works (yet).

Not sure what the fourth axis is for; I know it should always be a one, and "is needed to transform points this way" I read that it was also not always needed, but helpful. It's a one, so it's not going to be a problem, as one times anything is always the later.

I'm spending time just doing matrix math, and it's fun, and is giving me a better understanding of what's going on, then, I will go back to the code. Really, this matrix math concept is the only thing that's new in what I'm doing, so I'm pretty confident that I'm on the right track with this.

Tuesday, March 2, 2010

Study week day 2

After yesterday's post I started on lesson 2. It all made relative sense, and it was pretty small compared to the first one, which is good I think. I have to admit I just flipped through lesson 2, as the colour stuff isn't of huge interest to me yet; I wanted to make it move! Which is where lesson 3 comes in.

Lesson 3 was neat, and repeatedly drawing the scene makes perfect sense to me ;) I've done stuff like that in Java applets, although this is much cleaner implementation of the code. Java has a nasty flicker which you must compensate for. Basically, what happens in java is when you draw the screen, it's drawn as you processing the code, and not all at once. So, say you try and draw six objects on the screen; first clear the screen, then the first object will get drawn, and second, and so on. This causes a flicker for whatever reason. The solution is called a double buffering Basically, you draw each item to an offscreen image, one at a time, then draw the offscreen image to the onscreen image in one shot. With this, I did not have to worry about stuff like that, or I do, and it's been done for me and I will soon find out. Actually, it's probably happening behind the scenes because it's awesome. A quick google out of curiosity came up with this four posts down, someone gives a good simple explanation for how double buffering works in webgl.

really though, the way the lessons have it worked out, it's a lot like drawing with an x, y and z axis; the z axis is the third dimension, and all you have to do is change this axis at set intervals to make something move. Pretty simple!! or this info has been spoon fed to me, either way, I'm liking it!

The basis for what I accomplished today is reading lesson 3, and played with it a bit; changing the axis of the objects to -1, to make it spin the other way, or making it spin on a different axis. All neat stuff but now I think I'm done with lesson 3 and want to get started on lesson 4 where I get to make a true 3D object spin! Like so.

Also, giles, the author of these wonderful tutorials has been on my blog, which kinda proves the usefulness of blogging, for all those naysayers. I must thank him for his service and help in making these tutorials :)

I also feel like I've given myself very little time to do this, 5 days is not enough, so I'll get as much as I can, and pick up the pieces later. Think of it like getting my feet wet, then splashing wildly around in the water, It's chaos! but it's fun.

Thunderbird lab

I have finished the Thunderbird lab. I need to make the patch and push it still, and I will updated this post with that later tonight.

Basically, I was doing the whole processing of fixing a bug, from start to end.

A few hurdles.

I was able to find the file I needed to edit, the location in that file, and a pretty good idea of what needed to be done, quite quickly. The hard part was reproducing the bug, getting a built version that worked, and getting a result from editing the file.

The first thing was, when I tried to run my built Thunderbird, I would get this:

Two other students: Jianming and Crystal also received this. I think this was simply an error in the branch that was now fixed, as I don't *think* I did anything to fix it, but I tried. I tried using the comm-1.9.1 repo, which allowed me to build and run the program, but was ridden with error pop ups. I tried for awhile to use comm-1.9.1, but I could not seem to reproduce the bug; I thought it could be because of the version I was using. When it comes to experimenting, you need a completely perfect simulation to be sure something is not the problem, and in this case, I could not be sure until I had the same errors in the comm-central build; which wasn't running. So I continued.

I was having problems reproducing the bug. I was just trying to send myself an email, containing an email in the text, and receive it and expect the mail address to be linked, which it was not. I came across something helpful while re reading the instructions about reproducing the bug. It said "try creating a message with the text above, saving it to Drafts, then open in Drafts to see how it gets rendered." Ah, something I did not try. I did this, and I got the links I wanted.

So the bug is now reproduced, now I need to break this area of the code. I already know where and what I have to do, but I'm just going to make sure I'm in the right spot and it's working before I start coding.

I tried simply adding some letters "HAHA" to the end of the "mailto:" string, to see if I'm in the right spot. and it didn't seem to accept the change. I would reload my draft, and it would just be a boring old "mailto:". I was stumped, and was looking wondering why the code I was changing, did not change the program. Usually these simple, but seemingly impossible problems are the silly ones. I was thinking maybe I had two separate directories I was working in, one I was editing, and the other I was building, or something along those lines. I figured it out when I tried to copy and paste a previous draft into a new email, which shouldn't link the mail address, but all of a sudden it was. It hit me, if I change the code, and wanted to see the results, I would have to make a NEW draft, each time, as the draft only uses the code at the time you create it, and not when you view it. I created a new draft, and voila.

I'm in HAHA.
the next step is to code. I had to find a way to check if there were any "." after the @ but not "..". It was already checking for "." inside an if, so I just needed to add an && !string.contains(".."), or something along those lines. It's already using FincChar to find the "." which won't work for me as I need a character string, and not just a character. My answer was google. I googled "nsDependentString" and came up with Find(). Seems logical "FindChar()" for chars, and "Find()" for strings. Anyway, I implemented it, and ran it.

Looks good to me. I'm leaving out the actual code in case another student wants to read this for hints, but if you want help please ask.

Update: The bug and patch is awaiting review, and located here.

Monday, March 1, 2010

Study week day 1

What's a vertices?


Today I am starting with this tutorial.

First thing, get a browser that can support webGL. I already have one, but if you don't I recommend Minefield. I used it mostly because I had it installed anyway, and it sounds cool. If you don't know what I'm talking about, you should start at tutorial 0.

Anyway, I was going through the code example, and figuring things out along the way. It did some basic stuff like:

<body onload="webGLStart();">

which just loaded the code when it "hit" the body tag.
Inside the body it setup a canvas:

<canvas id="lesson01-canvas" style="border: none;" width="500" height="500">

Then inside the webGLStart(), which was called in the body onload, it got our canvas element:

var canvas = document.getElementById("lesson01-canvas");

I kept on cruising through the code, and got to something I could edit, and see the result!

var vertices = [
0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0
];

A vertices is the plural of vertex. Basically the dots that connect the shape, or corners.

By looking at this, I figured out the triangle, and made the top point larger. I was actually looking at it upside down, and still not sure why. Either -1 means down or to the right, and 1 mean up or to the left, or it's flipped later in the code *shrugs* time will tell. See if you can spot the top most point of the triangle, and make it bigger or smaller. Hint: 0, 0, 0 is the center of the triangle.

There was more stuff to setup and a second shape, a square which is the same as the triangle cept it has an extra vertex.

First moment of weakness


gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

When I first hit this, and at the time of writing this, sentence, I am lost on this one. This | operator, what's it doing. I've never seen this other than c++ bitwise operator, either that, or I'm forgetting something long buried in my head. But as with most thing in javascript, I must trust that they know what they are doing, move along, and the pieces will fall into place when they are ready to. Also, it doesn't seem like a line that I really have to worry about; I just use it, and it does it's thing, for now. This is what the tutorial said about this line "A simple first step: we clear the canvas in preparation for drawing on it." Um, ok, I know what it does, and it sounds pretty simple. It clears the canvas. This must be done once everytime the screen is to be drawn, inside the:

function drawScene() {

This was setup earlier as:

setInterval(drawScene, 15);

These setup a function to be called every 15 intervals, in this case, the function drawScene(), not sure, probably in milliseconds, but as I'm displaying a static none moving image, it could be 15 seconds, but not likely.

Next line... lost again.

perspective(45, 1.0, 0.1, 100.0);

Nvm, it's not as bad as I though. I changed the 45 to 100, and reloaded, and the shapes zoomed out. I'm sure the other three numbers do something just as cool. Weird, I changed the first parameter to 1000 and it flipped the shapes. Something it not what I thought it was. The first parameter is called the field of view. Starting to make sense of it with this "This perspective function is very useful, but is not built into WebGL, so it’s defined as a utility function further up in the code." So, I can see the inner workings of this function and why it's doing things I did not expect. Excellent.

What's a matrices?


Like vertices, matrices is the plural for matrix. It's beyond me right now, but I think it's how you track the movement of a 3D object. Actually, I think it tracks the movements, or path, of an object as it moves, maybe. Anyway, it looks like a grid of numbers, rows and columns. I think that's all I can handle on matrices at this moment, but I'll come back to them as other pieces fall into place.

Making another side of a cube


I decided, with what I've learned, to try and copy and paste bits of the square to make another side of the square. I was able to tilt the one square I had, SO i figured if I drew another square under it, and lined them up, it would look like another side of the square.

Anyway, I played around with the numbers, and settled on this.

I could of probably of documented more, but I went through a lot of iterations while playing, and noticed a lot of what I was doing is still limited because I'm not using shaders, colour, and doing it in a pretty manual way. I am sure there are better ways so I don't want to spend too much time on it. I want to get to the good stuff!

Pay no attention to that man behind the curtain


The rest of what is covered in this tutorial is the use of a few functions used to make everything work. Stuff that can be copied and pasted and used without understanding; I of course must understand it.

Conclusion


This is all the blogging I can handle. I will keep playing with this and get a better understanding of the matrix in general.

Sunday, February 28, 2010

Study week project: day 0.5

This week (starting tomorrow), I'll be going through and learning as much as I can of webGl and 3D programming.

I am doing this because it interests me, and this is the sort of stuff I wanted to learn when I first applied to Seneca. Although, what I have been learning up to this point has been great, and it's all one piece of something valuable, sometimes, it doesn't matter what. A challenge is a challenge.

I will start by going through these tutorials. See how far I get and how long it takes me. I'm not in any rush, and I don't know how far I will end up. I hope to finish up these tutorials and just play around with it a bit. I would like to be able to create a house like object sitting on a flat green surface. I really don't know what I'm getting into, though, so this objective might be too small, or too large, so we'll see. Should be fun.

I skimmed through the tutorials, and they seem to move pretty quick, and it looks like it's mostly the building blocks I will be doing, so that's always good. 15 tutorials total, so obviously if I want to get through this in a week, I must do more than one a day, might be harder than expected *shrugs* The final tutorial has a spinning planet with a reflective water surface. So it's got a moving, 3D shape with a texture, lighting, camera, and reflective surface. Start at the beginning I must.

That is all.

Friday, February 26, 2010

Today's Challenge:

Today, I am going to see if I can edit what I created in my last post, but this time, when the mouse scrolls, I want the circle in this example to follow a circular track, and not an up and down track. Then before the end of the day, I will post my results.

So far, I believe this is what I must do.

  • Create a circle of x and y points, and store them in an array instead of drawing them to the screen

  • Sort the array's points, as I cannot think of a way(yet) to draw a circle in the order it is used.

  • When the mouse wheel is moved up, go to the next point up in the array if it's not the last one, if it's the last one, go to the first. Same thing but reversed for mouse wheel down.


Update: I have created the circle, and set the point into an unsorted array.
Next: sort it, and apply the "track" to the mouse scroll

Update: To make my life and my computer's life easier, I'm going to just create an arc, and sort the arc, then apply the arc three more times. Kinda like 1/4 of the circle, then must copy and paste it, flipping it, after the arc is sorted.

Update: And challenge complete.

Self reminder: As of this point, when I scroll the mouse, it moves the objects, but it will also scroll the scroll bar in the window, I want to figure out a way to disable this, while still allowing the mouse wheel to scroll the scroll bar when the user wants it.

Wednesday, February 24, 2010

Mouse scroll wheel hack: update

Hey.

So I was playing around with my solution, my little mouse wheel hack for processing.js, that I mentioned in my last post. I first was making sure I could get it to work in Firefox, Safari, Opera, and Chrome. It really wasn't all that hard. I also wanted to jazz it up a bit, and use the mouse scroll for something more meaty. This is what I came up with.

In my last example, it was setup to work in all browsers, but it was only being called the Firefox way.

The problem was in this line:

addEventListener('DOMMouseScroll', wheel, false);

Firefox uses 'DOMMouseScroll', Opera, Chrome, and Safari use "mousewheel"

So, after some research, I changed the line to this:

addEventListener(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel", wheel, false);

What this is doing, is testing the navigator.userAgent for the word Firefox. Obviously, if you're using Firefox, the word will exist in the same spot. There are other less reliable ways to do this, as I found in my researching of this problem. I usually lean towards the solutions that make the most sense to me (obviously :P). The rest of the line just loads the certain string inside a ?: conditional statement.

I'll do some testing and cleaning tomorrow, and if I don't find any bugs, I'll flag it for peer-review.

Saturday, February 20, 2010

Mouse scroll wheel hack

Progress for the mouse wheel feature in processing.js.

This is the hack. They call it a hack, as it was not intended for use with processing. It just so happens that any Java code written in processing works, I believe. So I think all I need to do here is the same thing, add a hack. It's already possible to use the mouse wheel in processing.js, as I show here Note, this only works in Firefox that I know of, it does not work in Chrome or Opera. This is without adding anything to the processing code. Because processing.js uses javascript, any javascript is valid code, so I wrote a simple mouse wheel event in javascript using DOMMouseScroll.

I want to clean up the code in the example, though. That's my next task.

Friday, February 19, 2010

processing.js 0.1 release

Introduction
I have finished my work for 0.1 as detailed in my project plans here and here

The project wiki: here.


Specifications
my 0.1 release was in time to make it into the 0.5 release of processing.js

I did bug #226 for my 0.1 as well as some automated test cases for the new code I implemented.

What I had to do was protect string content from the procesing.js parser, then test it.

my initial patch: here

second patch: here

Final result: This code was modified to increase speed every so slightly, but every bit counts.

var strings = aCode.match(/(["'])(\\\1|.)*?(\1)/g);
for ( var i = 0; /(["'])(\\\1|.)*?(\1)/.test(aCode); i++){
aCode = aCode.replace(/(["'])(\\\1|.)*?(\1)/, "");
}

into this.

var strings = [];
aCode = aCode.replace(/(["'])(\\\1|.)*?(\1)/g, function(all) {
strings.push(all);
return "";
});

I have to thank Corban Brook for helping me fix the code, and get it out as soon as I did.

Automated tests: here

What I learned

  • Object orientation in javascript. By seeing Java object oriented code being transformed to JavaScript, I got a good understanding of how JavaScript objects work.

  • Managing and working with processing.js source code; large code, that was not created by me.

  • Basic uses of irc. I used ChatZilla and later irssi. I switched so I could use irssi with screen.

  • Revision control: git and mercurial. I used git to work with processing,js, and mercurial to work with Firefox (to setup js.exe, which I mentioned in this post)

  • I learned how to build Firefox, and setup a Firefox build enviroment.

  • I learned some standards for code. Like where to and not to use whitespace.

  • One of the most important things; I learned the importance of blogs.

  • I learned there is no such thing as too much testing.



Conclusion
A lot of this is technical stuff that required troubleshooting. I am confident that the next release will be less of a learning process, and I can get deeper into the code.

re initial project plan

Introduction
Ok, so I'm going to go back to my initial project plan and re assess things.

project wiki: containing basic information of the overall project. I will be updating it more frequently throughout 0.2 and 0.3.

Changes

  • 0.1: Bug #226
    While researching my first initial processing.js bug, I noticed when there was a comment // inside a character string, the parser would be happy to remove it, which is only the beginning. If there is ANYTHING inside a string that resembled code or keywords, it would break. the parser would grab the keyword, and change it to javasctipt. For example:

    text("int i = 0;", 0, 15);

    would then be parsed to:

    text("var i = 0;", 0, 15);

    After noticing this, I went right to the bug tracking system and found this. The bug I, myself just found. So, I'm going to complete that for my 0.1. I will also implement automated test cases for it.


  • 0.2: Bugs #133 and #230.
    These have been bumped to 0.2 from 0.1. I will also do automated test cases for these too.


  • 0.3: TBD.
    I hope with the experience I have gained, I can do three bugs, and implement automated test cases for them as well.



Conclusion
I've got down the process involved in doing this, and I hope to start back on 0.2 as soon as possible, Monday at the latest. It's best to start small, and start early. This stuff is not something that, for me, can always be accomplished in one night.

Thursday, February 18, 2010

Scott 1 : Firefox 0... 10

The Problem
Alright, I've been messing around with Firefox as described in two previous posts, here and here. Trying to make new tabs load your homepage.

The Solution
I got a solution that works perfectly (assuming you don't mind alerts popping up while browsing...).

First, a HUGE thanks to Benjamin Huang and his post.

What I did was:
In tabbrowser.xml. Note, my copy is a slightly different version.

var blank = !aURI || (aURI == "about:blank");

if ( blank && confirm("would you like to load your homepage?")) {
aURI = gHomeButton.getHomePage();
blank = false;
}

I added a the if statement bellow the var blank statement. This made sense to me as it was an easier way to check everything, then if the page is blank (you don't want the homepage to load when you click on a non new link) it prompts the user to open his/her homepage or not, then set blank to false.

The Conclusion
It's sooooo easy, it just took me time to get there. And honestly, I don't know how long it would of taken me to find gHomeButton.getHomePage() on my own, Benjamin Huang and his post are to thank for that one.

I broke Firefox!

In my last post I attempted to make a simple change to Firefox. Allow an option to select a new tab to open your home page, or a blank page.

I said what I've accomplished. I've found the spot in the code where a new tab is created, and change it to load anything I wanted based on code hard coded right into the code.

Today, I added a simple confirm box, that asked if you wanted to load your homepage (which at this point was just "google.ca") The box appeared, but the page was no longer loaded. It was not working, so I removed the code I added, and reloaded it again, which broke it more. Now, when I load a new tab, it loads the tab as a blank page with the same address fromthe first page writting in the new tabs address box, and if you chage a new tabs address, and hit enter, the original tab loads that page. I highly doubt this is a desired feature :P.

It's because when you're stuck on a problem, you usually have to learn something new to solve it, but it isn't always what you think it is. For example, first step is to understand the problem, second is to get an idea or some direction for what the solution could be, this is usually an abstract idea of sorts, usually has nothing to do with code, just an idea. Like "If I could do this, or bypass this, it would solve the problem". Then, you research your solution, see if it's already been solved by someone, if not, see how it's done (it's always possible), implement it (this is the coding part (notice how it's only one step in the process (for me anyway))), then debug it. This is assuming your idea or solution is the right one, sometimes it's not, but you still learned loads from dead ends. Anyway, this happens a lot, and can happen in a short period of time, then when you discover an answer, you notice you answered the wrong question. This can break code. You can find later, something you tried that did not work, that you forgot to remove, and it's breaking the code. This is what I think I did. So now, instead of combing through 2000 lines of code trying to get it to a working state, I'm just going to start again with a fresh build (that's good practice too, as I learned that when you first clone Firefox, you can specify the name of the directory it will go in, not a big deal, but it's the little things you learn that are the most fascinating sometimes).

I was recently asked in an interview how I go about solving a problem, and well, I don't feel like I gave a complete answer as I was not prepared and answered it best and honest as I could on the fly, well, that last paragraph was the whole answer :P

I've been stumped on this homepage part, and on my last blog another student has given me a useful like I'm going to poke around in, see what I turn up. Reading code seems to be the most time consuming process right now.

Tuesday, February 16, 2010

Firefox build 2.0

In a post which seems like ages ago, I attempted to build Firefox, and, I believe I got it working, and I did, I suppose, but not to my standards.

After what I've learned from working on processing.js and setting up js.exe to use with Javascript, by building Firefox. I needed js.exe to work with javascript right on my box, and setting up a mozilla-build was the easiest way.

I thought this time, I would attempt not only building it again, but attempt some changes. Right now I'm building it to make sure it works under the new build I created for js.exe, then, I'll make some changes (thanks for the push David).

My planned changes are simple (apparently :P ) I plan to add a feature, so when you open a new tab, you get the option to open an about:blank page, or your homepage. I'm pretty sure I know what I need to do, to do this. The step now is to start getting into the code and breaking it, and seeing what I can do :O

I will be back with more later (success/failure) as I plan on pulling an all nighter.

Update:
This Firefox build was more of a success than last time. This time I got Minefiled, which I'm using now to write this post. Last time, I ended up with Namoroka, which was pretty cool too because, and I wouldn't know what it is if I did not stumble upon it.

Update++:
Seriously, it's easier than I thought.

I went though this code, and found the file tabbrowser.xml, then located it on my own box, and just did a simple edit. I added a simple

alert("hihi");

Inside the area that is used to reload a tab *shrugs* it looked like an easy place to find my change.

Recompiled it, not knowing if it would work, and expecting another 40 minutes compile time. This time, it was done in a matter of minutes, maybe 5 minutes? Anyway, I loaded up the new Firefox.exe and hit reload on a tab, and this was the result!

I know, it's a silly update. But it worked. I think this was the hardest hurdle though, as the rest of it is just editing and playing with code, something I have experience in.

Final update:
I'm editing the "addtab" method in the tabbrowser.xml file with some success. The code is beginning to make sense, just so long as I stick to "addtab". What I've done, after breaking it a few times, is this. I fist editied line 1044 to instead contain (!blank) to (true). I'm just testing here. Anyway, now that I broke the "about:blank" load, I was free to tell it to load any page I wanted, so I tested with a string of "http://www.google.ca" instead of aURI on line 1054, compiled, and reloaded. It worked, no point in a screenshot though as you'll just see a new page of google... but yes, it worked. Every time I made a new tab, I was sent to google. Now, I'm testing the "browser.startup.homepage" property? I think that's what it is, well, that's what I'll call it here in my blog, for now. I must close and finish this update in order to test, and I'll continue tomorrow as it's late, and I must wake up at 5.