Vim

As of recent I have been playing with my Rpi, and it has brought me to a curious decision. It is a pain to constantly shift code from my laptop to the pi for a quick test, them make adjustments and try again. Mercurial is great, allowing me to push and pull changesets all over the place… but I feel that I have reached the point in my life where I must learn the “Vim”.

I have maintained this personal joke about myself that I am not a “true programmer” until I learn python. Interestingly enough, the Raspberry Pi was introduced and thus held my hand (and mental reasonings) into the world of python. Along with that experience I am now met with this need/desire to learn the ‘Vim’s… So with thus, for my Pi projects on-forth  Vim will be my editor of choice.

I will teach myself Vim the same way I taught myself to type… brute force.

VM Ware Fusion

tldr; Shared directory sym links under windows for VMware Fusion
At my new work, it is mostly a Mac shop. And since I develop with a few tools that are Windows only, I needed a solution to cope with my needs. Dual boot/bootcamp wasn’t an option in no way did I want to be constantly restarting my system, and I also doubt that bootcamp drivers were even available for my Mac with retina display.

I could have gone with VirtualBox, my trusted VM solution of choice, for many years… but instead I had done some more research into the matter and discovered that VMware Fusion was a very specific but powerful solution. It is also a commercial product. Retailing just under the $50 mark, it isn’t terribly expensive for what you will be getting. And shadows in comparison to the cost of the Windows OS I would be needing to purchase as well.

I went the VMware Fusion route and have been exceedingly pleased. This product is not an end-all for any of my virtualization needs, VirtualBox will remain my vm of choice for Linux based hosts… But the performance and flexibility of VMware is smooth and beautiful, it provides better hardware drivers to things like the graphics card and it will run with Windows Aero enabled without even blinking an eye. Full screen or in Unity (interlaced / seamless) mode  it works great.

I have not tried gaming within the VM yet, but my guess is that it works well. Prob not perfect, but well enough to make it do-able.

One hurdle I had to overcome was shared directories.

Mapping a directory via conventional means didn’t work. I am a developer, so when using a source code compiler, it tends to be incompatible with network paths. Often it attempts to resolve it or use .bat scripts which cannot cope with network paths. So the solution is to map a network path to a local directory using a symlink under windows.

mklink /d “C:\Users\andy\Repositories” “Z:\andy On My Mac\Documents\Repositories”

The above command is an example of something I have used to resolve such an issue. The only downsides is that the IDE doesn’t pickup external changes automatically. If you change something outside of the IDE, you must refresh the directory. Not a big deal, since its the click of one button and changes are found. The other downside is compile time. What would normally be a 10 or 15 second compile turns into a 20 to 30 second compile. Nearly double. This is believed to be because it must loop through a virtual network adapter to give it the network-like features. There are ways around this as well, my IDE has a ‘bridge’ feature to allow compiling on the host, but I haven’t bothered to set that up yet because even though there is a slightly longer delay, the system works very well and is very stable.

Hostmonster Provides SVN

Good news to those who use hostmonster and want to use SVN for a source code version control!

If you are looking for web hosting, I would strongly recommend hostmonster, one low price, all the features, no limits! (Take THAT GoDaddy!)

My email to Hostmonster:

It has come to my observation that both of the programs “svn” and “svnadmin” are installed and openly available to hosted users while using ssh access. This does not seem to be a highly publicized feature or benefit provided by hostmonster over other providers, which leads me to question the availability of such programs.

All of my websites are developed and hosted through hostmonster, I use svn to manage the website files durring development and deployment. So having a hosting provider also provide me with SVN tools truely cements my loyalty to that provider. The reason I ask about these tools is to verify that they were not installed by ‘mistake’ and that I can rely on them being persistently in place. I don’t want to start using the SVN tools you provide and then have them stripped away with a comment such as “they were not supposed to be there in the first place”.

Also, I am not sure if the use of an SVN repository would constitute as a form of backup and thus mark my account for termination.

I am a fan of hostmonster and have several clients go through me for hosting, and several others have started hostmonster due to my referrals. So I do want to stay on good terms with you guys!

Thanks much, Andy

Response from Hostmonster:

That service is made available to our customers, it is not a loophole or anything. You are able to use it for websites you have on the server. We do allow you to keep 1 backup of your websites on the server, and I believe this falls in that category. I don’t foresee us removing this feature but I can’t make any guarantee that it will always be available.

Thank you, Zachary

Terms of Service Compliance Department
1958 South 950 East
Provo, UT 84606
P: 866.573.4678 Option 5 | F: 801.765.1992

(Did you notice that it is Utah support? Based in the US? Another thing I like about Hostmonster. I can call them up, talk to them, understand them, and they don’t treat me like an idiot for the first half hour running me through a bunch of basic tests to which I have already tried before I contacted them in the first place.)

There ya have it folks… Can anyone say SCORE!! I was so excited when I found this out! Saves me money and gives me the ability to setup private SVN repositories!

And please, if you do decide to sign up, do it through this link here: Sign up for hostmonster.com

Yes, it is an affiliate plug. But it is not a reason for bias. I would not use (and then promote) a service that I disliked. It helps keeps the lights on around this place, doesn’t hurt you any, especially if you were going to sign up for a host(monster) account anyways!

SVN dump, rsync, and restore

This script will dump the repository, as a form of complete backup. This is one of the safest ways to ensure you have all of your revision history, and that it is restore-able . Using svnadmin’s ‘hotcopy’ is only really good for backing up that server at that instance. It is faster, but lets say you ditch that server/repo and want to, lets say, upload it to a hosted svn service. Well your hotcopy is gonna do you no good, whereas the dump is essentially an understood format snapshot.

Scipt:

svnadmin dump centerorbit.svn | gzip | split -d -b 20M – backups/centerorbit.svn/backup.

Great! Now you have a backup of your repo! Where is it? Oh its still on the same server/computer as the repo is. So in the case your computer gets lost/stolen/dropped of a cliff, your backup will do you no good.

No worries though! The reason we split it into 20 Meg chunks in the last script was so that we could easily use rsync to transfer our backup elsewhere! Just use this script:

 

rsync -e ssh user@domain.com:repository/backups/centerorbit.svn/* ./

In this script we tell rsync to go through ssh:
” -e ssh”

and to go to “user@domain.com”, but the ‘domain.com’ part could also be an IP address:
“user@domain.com:”

and once we are there (at the remote computer, this is the folder that we want to copy all of the files to the other computer:
“repository/backups/centerorbit.svn/*”

Note: The above command will start its folder reference from wherever your ssh session starts you. Usually this is your users home directory. If you want to start from the root of the filesystem, put a ‘/’ at the beginning of your folder location (right after the ‘:’).

Lastly, here is where we want rsync to place them on this computer:
./

Note: Which means “Put all the files in the exact same folder that the terminal is currently at”. You can see where this is by typing the command “pwd” which stands for “print working directory”. 

Now if we want to get the dump file extracted from the archive, in case we want to actually restore the dump:

cat backup.* | gunzip > dump.svn

and this command will produce a dump.svn file which can then be restored to an svn repo by using:

svnadmin load dump.svn

 

PHP generated image caching

So a recent challenge I had was storing binary data (a PNG image) in a MySQL database behind PHP, to which I would pull out upon request, format it and use it as a displayed image in the webpage.

My initial code looked very simple and easy.

header(“Cache-Control: private, max-age=10800, pre-check=10800”);
header(“Pragma: private”);
header(“Expires: ” . date(DATE_RFC822,strtotime(” 2 day”)));

header(‘Content-type: image/png’);
header(‘Content-MD5: ‘. base64_encode(pack(‘H*’, md5($row[‘Icon’]))));
header(‘Content-Length: ‘.filesize($row[‘Icon’]));
header(‘Content-Disposition: attachment; filename=”‘.$_GET[“ElementID”].’.png”‘);
echo $row[‘Icon’];

Now I wouldn’t suggest using this, as I found out Content-Length was way wrong, along with expires just set for 2 days. I needed to manually flush my browser cache to see any updates. Bad way to push out an image from MySQL through PHP.

The link below from rd2inc.com was the majority of my solution, but to that I had to change the way it got the additional header information. This was because apache_request_headers() wasn’t a function in my PHP. So in the link to php manual (below) I found and then had to slightly modify the code for the .htaccess file to this:

RewriteEngine on
RewriteRule (.*) – [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]
RewriteRule (.*) – [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

Now I can use:

$_SERVER[‘HTTP_IF_MODIFIED_SINCE’]
$_SERVER[‘HTTP_IF_NONE_MATCH’]

And how did I check for update change? Just set a hook in MySQL to update a timestamp  whenever that row is updated!

Links where I got info:

AS3 Garbage Collection with Event Listeners

A quick word of warning to AS3 programmers. Don’t use anonymous functions with event listeners, because they WILL be garbage collected.

Took me forever to find this bug, it seemed that after 30 seconds or so all of a sudden my event listener would stop functioning. The event was never removed, still showed up in the debugger tools, everything. It wasn’t until after over 3 days of nailing my head against the keyboard that I finally figured it out.

Why use an anonymous function? Because that allowed me to pass variables seemlessly to my functions that I wanted to call. For example:

var aNumber:Number = 3;

aClip.addEventListener(
MouseEvent.ON_ClICK,
function(evt:Event):void {
callThisFunction(aNumber);
}
);

This is just a crude example snippit, but in this case if I have a MovieClip called “aClip” and I want it to call the function “callThisFunction” on the event of if it gets clicked, but I also want to pass it a parameter “aNumber”.

It was (in my eyes) a beautiful way to handle the situation, until the AS3 garbage collector stepped onto the stage (pun intended haha).

Hope this helps some desperate AS3 programmer that surfs Google like a starving vulture in a dessert looking for the smallest scrap of meat to appease their application from sporadic behavior.

PHP Dev Tools

If you are a PHP developer (or an aspiring one) then you will need a development environment. If you have been trying to write a site using windows notepad, then I feel oh so sorry for you. There is help…

You will find that the industry standard are all eclipse based. eclipse is an open source IDE that is customizable for just about any programming you would need it for on just about any OS that you would like to do it on. I believe eclipse was started with the Java language, but is now used for everything from android to zend.

Aptana studio is a fork from the eclipse project with their main focus to be on building a specific application that is tailored directly for web development ventures. I have used Aptana and it is a very promising platform. Everything is present very well and the interface is definitely more clean than eclipses. With that said, I did not stick with the product for a reason in which I don’t fully remember, it has been awhile since I used the product, and if anyone has the intentions to strictly do web development and nothing more I would insist that you take a peek at aptana first. The getup-and-go ability of this application is very nice since eclipse (being as versatile as it is) does require some configuration to get it just right for your purposes.
http://aptana.com

Now for eclipse. I have used it quite a bit, everything from raw java development, to php, to android dev. I would suggest that if you have the intentions to do more than just web programming, that perhaps you start looking at eclipse. It may get frustrating trying to get the right plugins installed and configured correctly, but once everything is setup properly it is a very stable and very usable IDE. With that said you might wonder “well what version do I use?”, as you will quickly see, the eclipse download page offeres many downloads for many different types of development. I would suggest that you should download the top version, which is usually the one tailored for Java developers… but that doesnt matter because you will have to install your own custom plugins anyways which will change everything you need. Now when it comes to PHP plugins for eclipse, I believe there are a few to choose from, but hands-down you should install the PDT plugin. This stands for “PHP Development Tools”… not only is it an official plugin from eclipse, but Zend ( a very big company focused on the advancement of php) commits a lot of code and resources to the development of this plugin ( and you will soon see why). But this means that it will have the most features you need with the easiest of use and functionality. Proper code highlighting and syntax checking.
http://www.eclipse.org

Note: If you are using a Linux OS with eclipse I would strongly suggest downloading the IDE from the eclipse website rather than installing it from the source repository. I had used this method once-upon-a-time because I figured “Oh now this will keep it all updated”, but what I soon realized while trying to utilize some new(er) features is that the repo version was several years old! This was not going to work for me, so I uninstalled it and simply replaced it with a fresh download from the eclipse site. In retrospect, this is a better approach because the last thing a developer wants to deal with while in mid-project is having an auto-updater demolish his IDE (which sometimes updates do). This way helps protect yourself by knowing exactly when and why you choose to update your IDE.

Last (but not least) is Zend studio. As I had mentioned earlier, Zend is a big company focused around PHP and what it can do for companies. One of their products is of course Zend Studio. Which offers many useful tools and features specifically tailored for PHP. If you are lucky enough to have a copy of this software, it would also be likely that you are running a Zend server. In this case you will have access to a WHOLE SLEW of additional features where you can actively debug on the server, view very detailed statistics about performance and load balancing your code. It is very nice… I personally have never used the tool, but have watched a few tutorials about it, and have drooled a bit over it as well… But in the end basically it is the eclipse framework with an overhaul of the PDT plugin and a little (or a lot) of Zend spice in there to really make it a sound product. If I come around to downloading a trial version of it, I will definitely post my feedback.
http://www.zend.com/en/products/studio/

PHP Static Class Variable

Recently found out that when you serialize a class (in my case it was storing it in a $_SESSION[] variable)  that the class’s static variable gets reset to it’s default value. Consider the following:

  1. (page) script runs
  2. class constructed
  3. class used (static variable set)
  4. class serialized at end of script (automatically when stored in a $_SESSION[] variable)
  5. (new/next page) different or same script runs
  6. class deserialized (automatically by referencing you $_SESSION[] variable)
  7. !static variable is default!

This doesn’t mean what you set it to in the constructor, since the constructor doesn’t get called when an object is deserialized. Rather when you declare the variable in the class. For example:

Class User{
	private  static $loggedIn = 0;
}

So if you do not declare a default value, then your variable will simply be ‘unset’ when you reference your freshly deserialized class object.

A solution? Here is where the __magic begins!

So if the static variable isn’t preserved then you must use the magic php class functions __destruct() and __wakeup(). Consider the following, where you want to preserver whether a single user is logged in or not:

Class User{
	private  static $loggedIn = 0;
	private $thisLoggedIn;

	function isUserLoggedIn(){
		return self::$loggedIn;
	}

	function __destruct() {
		$this->thisLoggedIn = self::$loggedIn;
	}

	public function __wakeup(){
		self::$loggedIn = $this->thisLoggedIn;
	}
}

Here is what happens:

I always store and use the instance of the User class from a $_SESSION[‘user’] variable, this is important because any changes I make to the object is preserved after the script terminates and the object is serialized.

So you will see that in the destructor we have:

$this->thisLoggedIn = self::$loggedIn;

This way, at the end of the page script the destructor is called. We set the private variable $thisLoggedIn as what our static variable $loggedIn is. The importance of this is that the value of ‘self::$loggedIn’ is preserved as ‘$this->thisLoggedIn’ when the object gets serialized.

Then when the object is automatically deserialiezed, the magic php function ‘__wakeup()’ is automatically called. In this we reset the static variable to what was serialized and stored inbetween page transitions in the  $_SESSION[‘user’] variable.

The only thing that you must be sure of now is that besides in the ‘__destruct()’ and ‘__wakeup()’ calls, never use ‘$thisLoggedIn’ anywhere in the class. Always reference the static variable ‘self::$loggedIn’. That way you can be sure that what you are storing and then restoring is what your expecting.

AS3 blocking or yielding

Learned about a characteristic of ActionScript today. Although I have observed this attribute with the language, and had also learned how to work around it. I just had never had someone spell it out to me, and thus didn’t know the name/terms of “blocking” and “yielding”.

It makes sense from the overview of how AS3 is actually constructed and runs, but it is nice to have ‘closure’ of sorts and to have a full understanding as to why it acts this way.

Here is where I read about it
http://blogs.adobe.com/aharui/2008/01/threads_in_actionscript_3.html

Here are the important snips of the above article:

“… there is no yielding or blocking in Actionscript either. If the next line of code is supposed to run, you cannot prevent the next line of code from running. That means that when you call Alert.show(), the next line of code following that runs right away. In many other runtimes, the Alert window has to be closed before the next line of code continues.”

“…There is no solution to allow for blocking or yielding other than refactoring the application to be event-driven…”

Which with the event-driven solution mentioned above is actually what I have personally started using to solve this problem (or condition) before actually knowing about this content.

And so now you know.