Pixel Everywhere

There are only 10 types of people in this world. Those who know binary and those who don't.

Running MongoDB on Windows — July 9, 2015

Running MongoDB on Windows

This was only tested on Windows 7.

  1. Download and install from MongoDB website https://www.mongodb.org/downloads
  2. Select appropriate MSI or ZIP either for 32 or 64 bit system
  3. Once installed, locate the installation directory usually on C:\Program Files (x86)\MongoDB
  4. Create 2 folders and a file namely:
    1. log
    2. data
    3. mongo.config
  5. Next, Open the mongo.config file and type these 3 lines:
    • dbpath=C:\Program Files (x86)\MongoDB\data
    • logpath=C:\Program Files (x86)\MongoDB\log\mongo.log
    • diaglog=3
  6. Open command prompt as Administrator
  7. Go to the bin folder inside the installation directory cd C:\Program Files (x86)\MongoDB\Server\3.0\bin
  8. Type mongod.exe ––config=”C:\Program Files (x86)\MongoDB\mongo.config”
  9. Open another command prompt as Administrator , go again to the bin directory and type mongo
  10. In the Mongo Shell, type db. It should display a word test

* It’s up to you to put the paths in your environment variables

Other Items:

  • MongoDB can also be run by going to a NodeJS app’s bin directory using mongod.exe –dbpath path\to\my\nodejs\app\bin. Open another command prompt and type mongo
  • There are 2 default ports:
    • 27017
    • 28017 is used for accessing through the browser like http://localhost:28017 when starting mongo server using mongod.exe ––config=”C:\Program Files (x86)\MongoDB\mongo.config” ––rest
  • There’s no rename method for DBs. Use these instead:
    1. db.copyDatabase(‘fromDbName’, ‘toDbName’, ‘localhost’) to duplicate existing database
    2. use fromDbName switch to the the existing database to be deleted
    3. db.dropDatabase() to delete the used database
    4. use toDbName to switch to the newly created database
  • To dump a database along with its collections, there is only export to BSON option. The JSON option is per collection only. So use BSON instead: C:\Program Files (x86)\MongoDB\Server\3.0\bin>mongodump /d mynodejsapp /o mynodejsapp.json. The output will be contained in a mynodejsapp folder inside C:\Program Files (x86)\MongoDB\Server\3.0\bin
Advertisements
PHP CLI Single Line Display — July 4, 2015

PHP CLI Single Line Display

Tested only on Windows 7 using a PHP command line:

php -f myfile.php

  $exit = false;
  while(!$exit){
    echo 'Enter a value: ';
    $cmd = trim(fgets(STDIN));
    if($cmd == 'q' || empty($cmd)){
      $exit = true;
    }else{
      $dots = '.';
      echo "Loading";
      for($a = 1; $a <= $cmd; $a++){
        usleep(10000);
        $s = "\t" . $dots . "$a%\r";
        echo $s;
        $dots .= '.';
      }
      echo "\n";
    }
  }
  exit;
Useful CLI Commands — June 16, 2015

Useful CLI Commands

There are infinite commands out there but it’s a good to write a small amount of them. My world usually revolves around these commands when inside a project folder:

Composer

  • Installing: $ curl -sS https://getcomposer.org/installer | php
  • Using: $ composer install[, require, remove, search] [package]
  • Updating: $ composer update (after deleting or updating lock file)
  • Creating $ composer init
  • For any PHAR or JSON issues, re-install Cygwin

PHPDoc

  • File: $ php phpDocumentor.phar  -f path/to/an/additional/file -t path/to/my/api/docs
  • Directory: $ php phpDocumentor.phar -d path/to/my/project -t path/to/my/api/docs

cURL

  • $  curl -X DELETE  –data “id=1” -H “Accept:application/json” http://localhost/project/user

Git

  • $ git add .
  • $ git commit -m ‘Message.’ -a
  • $ git tag -a 1.0.0.0 -m ‘Major release.’
  • $ git push origin master
  • $ git push origin –tags

NodeJS

  • $ taskkill /IM node.exe (if an app/server is stuck, use this command)
  • $ npm ls -g –depth=0 (remove depth to list all dependencies)
WordPress.Org Plugins I Usually Need — June 15, 2015

WordPress.Org Plugins I Usually Need

These are my personal choices and the ones I normally use when creating new projects. Of course, there are other items like PayPal, Facebook Comments, eCommerce and such. But these items are a bit tricky to find and remember:

  1. Custom Post Type – to create different post types such as posts, pages, ads, etc.
  2. Advanced Custom fields – to create different form fields per page
  3. Duplicator – used for replicating everything from localhost all the way to an online hosting server
  4. Nav Menu Roles – allows freedom to determine which menu items are shown based on user log sessions
  5. User Role Editor – provides a way to create new user types, roles and permissions
  6. Pie Register – provides generic pages for user pages such as login, register, forgot password
  7. Role Scoper
LocalConnection Bug In IE — September 29, 2011

LocalConnection Bug In IE

If you’re planning to communicate two Flash movies using the LocalConnection class and constantly removing the other Flash movie by removing its HTML tag container, you need to close the connection first.  Unlike Firefox, IE has a tendency to store the previously opened connections.  Otherwise you’ll have a connection that looks like it’s intermittent or on a certain on and off interval every time you open a new connection.

Have fun!

Using htmlText in Flash AS3 CS Versions —

Using htmlText in Flash AS3 CS Versions

There’s a tricky part in using the htmlText property of a text field when using any latest versions of Flash.  One thing to point out is that if you’re not using an embedded font to render an htmlText property of a text field, its  only available characters will depend on another text field that’s being on the stage that’s not using htmlText.  Try this:

1.  Place two dynamic TextFields in the stage and name one as myTextField

2.  In the Actions Panel, type in myTextField.htmlText = “<b>hello world</b>”;

3.  Go back to the stage and manually enter a text to the TextField that has no instance name.  Try placing just one letter like “o” without the quotes

4.  Preview the movie and see what happens to the myTextField’s value and the style.  Looks weird huh!

So, to correctly use htmlText, do the following:

1.  Embed the needed fonts

2.  Use device fonts

*A note on device fonts is that they won’t work on masking.

Enjoy!

Solving Class Name Conflicts in Flex APEngine — January 20, 2011

Solving Class Name Conflicts in Flex APEngine

If you ever encounter two classes named Vector and Group under higher versions of Flex 3.5 from Tour de Flex’s ActionScript Physics Engine, then just rename the files using Flash Builder 4. It has a great way of refactoring in many ways. One of them is renaming files.

Try to create a new project and add a new directory to the Source Path under Flex Build Path properties. Right click the Vector class and rename it anything you like. Let’s say APEVector and APEGroup for the Group class.

When you rename these files, Flash Builder 4 will automatically update the files that are linked to it. It will change all the imports, variable declarations, instantiations, method returns and much more.

Now go and create those motor cycles. Enjoy!

Font Manager —

Font Manager

It’s a good practice to separate your embedded fonts so as not to bloat your main file. One example for this is the embedding of fonts that are contained on a particular .SWF file. This class will act as a font factory for registering those embedded fonts. It can also provide the style and weight properties of a certain standard font.

package Managers
{
	import Interfaces.IFont;	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.text.Font;
	import flash.text.TextFormat;
	public class FontManager extends EventDispatcher
	{
		public static const REGULAR:String = "Regular";
		public static const BOLD:String = "Bold";
		public static const ITALIC:String = "Italic";
		public static const BOLD_ITALIC:String = "Bold Italic";
		public static const UNDERLINE:String = "Underline";
		//
		private var aFonts:Array;
		private var iCtr:int;
		public function FontManager()
		{
			this.iCtr = 0;
			this.aFonts = new Array();
		}
		/**
		 * Sets the target's appropriate fontFamily name according to 
		 * its current style and weight.  Assuming that the fontFamily
		 * naming conventions are:
* FontName Regular
* FontName Bold
* FontName Italic
* FontName Bold Italic

* @param target A DisplayObject that supports TextFormat. * @return The newly styled TextFormat. * */ public static function setStyle(target:*, style:String):TextFormat { var t:* = target; var i:int = t.selectionBeginIndex; var j:int = t.selectionEndIndex; var tf:TextFormat = t.getTextFormat(i, j); var name:String = tf.font ? tf.font : t.getTextFormat(i, i + 1).font; var prefix:String = name.substring(0, name.indexOf(" ") + 1); switch(style) { case FontManager.BOLD: tf.bold = !tf.bold; tf.font = prefix + style; break; case FontManager.ITALIC: tf.italic = !tf.italic; tf.font = prefix + style; break; case FontManager.UNDERLINE: tf.underline = !tf.underline; break; } if(tf.bold && tf.italic) tf.font = prefix + FontManager.BOLD_ITALIC; else if(!tf.bold && !tf.italic) tf.font = prefix + FontManager.REGULAR; t.setTextFormat(tf, i, j); return tf; } public final function addFont(name:String):Boolean { var i:int = this.aFonts.length; for (var a:int = 0; a < i.valueOf(); a++) if (name == this.aFonts[a]) return false; this.aFonts.push(name); return true; } public final function removeFont(name:String):Boolean { var i:int = this.aFonts.length; for (var a:int = 0; a = this.aFonts.length ? this.dispatchEvent(new Event(Event.COMPLETE)) : this.loadFonts(); } public final function get fonts():Array { return this.aFonts.slice(0); } public final function loadFonts():void { var s:String = this.aFonts[this.iCtr.valueOf()]; this.iCtr++; var l:Loader = new Loader(); l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onError); l.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onFontLoaded); l.load(new URLRequest(s)); } private final function onFontLoaded(e:Event):void { var d:IFont = IFont(e.target.content); if (e.type == Event.COMPLETE) { if (d.regular()) Font.registerFont(d.regular()); if (d.bold()) Font.registerFont(d.bold()); if (d.italic()) Font.registerFont(d.italic()); if (d.boldItalic()) Font.registerFont(d.boldItalic()); } this.iCtr.valueOf() >= this.aFonts.length ? this.dispatchEvent(new Event(Event.COMPLETE)) : this.loadFonts(); } } }

Here’s the CSS format for embedding the fonts.

@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
@font-face
{
	src:url("arial.ttf");
	font-family:"Arial Regular";
	embedFonts: true;
	embedAsCFF: false;
}
@font-face
{
	src:url("ariali.ttf");
	font-family:"Arial Italic";
	embedFonts: true;
	embedAsCFF: false;
}
@font-face
{
	src:url("arialbd.ttf");
	font-family:"Arial Bold";
	embedFonts: true;
	font-weight:bold;
	embedAsCFF: false;
}
@font-face
{
	src:url("arialbi.ttf");
	font-family:"Arial Bold Italic";
	embedFonts: true;
	font-weight:bold;
	font-style:italic;
	embedAsCFF: false;
}

Here’s an example of embedding fonts using a metadata on a .AS file that will be converted in to a .SWF file.

package Fonts
{
	import Interfaces.IFont;
	import flash.display.Sprite;
	public class Arial extends Sprite implements IFont
	{
		[Embed(source = "Fonts/Arials/arial.ttf",
						fontFamily = "Arial Regular",
						embedAsCFF="false")]
						private static const Regular:Class;
		[Embed(source = "Fonts/Arials/arialbd.ttf",
						fontFamily = "Arial Bold",
						fontWeight = "bold",
						embedAsCFF="false")]
						private static const Bold:Class;
		[Embed(source = "Fonts/Arials/arialbi.ttf",
						fontFamily = "Arial Bold Italic",
						fontWeight = "bold",
						fontStyle = "italic",
						embedAsCFF="false")]
						private static const BoldItalic:Class;
		[Embed(source = "Fonts/Arials/ariali.ttf",
						fontFamily = "Arial Italic",
						fontStyle = "italic",
						embedAsCFF="false")]
						private static const Italic:Class;
		public final function regular():Class
		{
			return Arial.Regular;
		}
		public final function bold():Class
		{
			return Arial.Bold;
		}
		public final function italic():Class
		{
			return Arial.Italic;
		}
		public final function boldItalic():Class
		{
			return Arial.BoldItalic;
		}
	}
}

And here’s the interface.

package Interfaces
{
	public interface IFont
	{
		function regular():Class;
		function bold():Class;
		function italic():Class;
		function boldItalic():Class;
	}
}

If you’re going to use the metadata embedded mechanism, just load and automatically register the public classes of the generated .SWF file such as Arial.swf using FontManager.addFont(“Arial”) method.

To use the setStyle method on a Flex 4 project, you can do so like:

<mx:HBox>
<s:Button label="Bold" click="FontManager.setStyle(this.txtTgt, FontManager.BOLD);" />
<s:Button label="Italic" click="FontManager.setStyle(this.txtTgt, FontManager.ITALIC);" />
<s:Button label="Underline" click="FontManager.setStyle(this.txtTgt, FontManager.UNDERLINE);" />
</mx:HBox>

Enjoy!

Local SVN — January 13, 2011

Local SVN

In this tutorial, you’ll be able to setup a new SVN repository that’s residing on your local directory for your projects so you’ll no longer be creating duplicates for your project’s backup and constantly changing their names using a date token and such. Plus you’ll be able to merge, revert and commit your changes on the fly.


1. Download Tortoise SVN (currently at 1.6.6)
2. Let’s assume we have an existing project called MySpecialProject anywhere in your hard drive. Be sure to back up this folder for now, so you’ll have a copy if you’re unsuccessful in these following steps
3. Create 1 new directory under My Documents called SVNLocalRepository
4. Inside SVNLocalRepository, create 2 new directories:
– MySpecialProject (the same name as your existing project)
– Tmp
5. Right click the newly created MySpecialProject folder, select TortoiseSVN and select Create Repository here
6. Inside Tmp, create 3 folders, tags, branches and trunk
7. Cut and paste all files and folders inside the original MySpecialProject where your existing project files are and transfer them all the way to the newly created Tmp’s trunk folder. By now, your original MySpecialProject folder should be empty. Don’t worry, once we’re done, we’re going to import the versioned MySpecialProject from the repository
8. Right click Tmp, select TortoiseSVN and then Import…
9. Enter the full path of the newly created MySpecialProject repository with an initial path file:/// in the URL of Repository. So in this case it’s file:///My Documents/SVNLocalRepository/MySpecialProject. Your current project is now in the SVN local repository
10. To get started, go to your original MySpecialProject folder, right click and Checkout from the URL of Repository file:///My Documents/SVNLocalRepository/MySpecialProject
11. Remove your project backup that’s stated in step 2
12. Remove the Tmp folder in step 4

To unversion your checked in project, right click the root folder of your project, which is My Documents/MySpecialProject select Export and point to the same exact project folder. It should prompt you whether to unversion the selected project or not.

Enjoy!

Storing Values to AS3 using Google Spreadsheets — November 9, 2010

Storing Values to AS3 using Google Spreadsheets

This topic is separated into two parts –storing and retrieving. Retrieving is in another topic. Imagine storing values to a spreadsheet that Flash can retrieve and store them into variables wherein the designer or the project manager no longer has to request for you to change the values. They can change them, themselves. For example, if you have a war game that has a “Bullet Speed” in it, you can just place a column in the spreadsheet and the designers can enter desired values themselves. A self-documenting and a better way to interact with other development teams.

Before we start, there are certain stuffs that you need to setup and download:

1. Firefox and Firebug, which enables us to determine the page header’s request and response values. Once Firebug is installed in Firefox, press F12, go to the “Net” tab and select “Enabled”

2. XAMPP (with cURL enabled) for Windows, which enables us to create a crossdomain policy file that gives us privileges to write into Google’s spreadsheets

3. A Google account to create our spreadsheets

Setting up the spreadsheet

Login to Google and create a spreadsheet. In the empty spreadsheet, search for the phrase “Public on the web”, click “Change”, select “Public on the web” and check “Allow anyone to edit (no sign-in required)”. Save and close the dialog.

Click Form > Create a form. A popup window will appear.

In the Question Title, remove the word “Sample Question 1” and enter the word “BulletSpeed” and click Done.

Remove “Sample Question 2” by clicking its Trash icon.

Click Save.

Before closing the popup window, take note of the formKey value below the window and save it. This value is required when we submit values from Flash to the spreadsheet.

Close the popup window.

By the time the popup window closes, the spreadsheet creates a “Timestamp” and “BulletSpeed” columns in rows A1 and B1, respectively. Timestamp is automatically created by the spreadsheet, which tracks changes in the spread.

Leave the spread like that for now and proceed to setting up the PHP directory and crossdomain proxy file.

Setting up a project directory and crossdomain proxy file using PHP’s cURL

In your XAMPP’s HTDocs directory, create a new directory called WarGame. Inside that directory, create a php file called crossdomain_proxy.php and paste this code:

<?php
	/* Only proxy to URLs matching this */
	$sProxyUrlRegex = '#^http://spreadsheets.google.com/#';
	/**
	* Make a simple status/error page.
	*/
	function showErrorStatus ($iCode=500, $sText='Internal Server Error')
	{
		header("HTTP/1.1 $iCode $sText");
		header("Status: $iCode $sText");
		echo "<html><head><title>Oops</title></head><body><h1>" . $sText . "</h1></body></html>";
	}

	/**
	* Replacement for curl_setopt which only exists in PHP>=5.1.3
	*
	* @param resource $rCh
	* @param array $aCurlOpt
	*/
	function local_curl_setopt_array ($rCh, $aCurlOpt)
	{
		foreach ($aCurlOpt as $sKey=>$sVal) {
			if (!curl_setopt($rCh, $sKey, $sVal)) {
				return false;
			}
		}
		return true;
	}

	/* Set cURL options */
	function init (){
		$aCurlOpt = array (
			CURLOPT_FAILONERROR		=> true, // Fail on non-200 responses
			CURLOPT_POST			=> true,
			CURLOPT_RETURNTRANSFER	=> true,
			CURLOPT_TIMEOUT			=> 60,
			CURLOPT_HEADER			=> false, // Don't include header in response
			CURLOPT_USERAGENT		=> 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)',
			CURLOPT_FOLLOWLOCATION	=> true,
			CURLOPT_MAXREDIRS		=> 5
		);

		/* Check URL is specified */
		if (!isset($_POST['_url']) || empty($_POST['_url'])) {
			showErrorStatus(400, 'No URL specified');
			exit;
		}

		/* Set cURL URL and remove from POST before forwarding */
		$sCurlUrl = $_POST['url'];
		unset($_POST['url']);

		/* Make POST string */
		$aPostData = array();
		foreach ($_POST as $sKey=>$sVal) {
			$sKey = str_replace('_', '.', $sKey); // Revert PHP conversion nonsense
			$aPostData[] = urlencode($sKey) . '=' . urlencode($sVal);
		}

		$sPostData = join('&', $aPostData);

		/* Do cURL stuff */
		if (false == preg_match($sProxyUrlRegex, $sCurlUrl)) {
			showErrorStatus(401, 'Naughty, you can\'t proxy to ' . $sCurlUrl);
		} else if (!$rCh = curl_init($sCurlUrl)) {
			showErrorStatus(NULL, 'Couldn\'t initialize cURL to ' . $sCurlUrl);
		} else if (false == local_curl_setopt_array($rCh, $aCurlOpt)) {
			showErrorStatus(NULL, 'Couldn\'t set cURL options');
		} else if (false == curl_setopt($rCh, CURLOPT_POSTFIELDS, $sPostData)) {
			showErrorStatus(NULL, 'Couldn\'t set POST vars');
		} else if (false == ($sResponse = curl_exec($rCh))) {
			showErrorStatus(NULL, 'Response was false');
		} else {
			/* All good */
			echo $sResponse;
		}
	}
	//
	init();
	exit;
?>

Coding the AS3

function storeVariables():void
{
	var loader:URLLoader = new URLLoader();
	var variables:URLVariables = new URLVariables();
	variables["entry.0.single"] = "hello world";
	var key = "0AlmPB8Zwh3pZdDBjMzY5TzJjZnhTSmFmbmlyVkJXNWc";
	variables["url"] = "http://spreadsheets.google.com/formResponse?key="+key;
	//Call the proxy page passing all the variables above.
	var request:URLRequest = new URLRequest("crossdomain_proxy.php");
	request.data = variables;
	request.method = URLRequestMethod.POST;
	loader.addEventListener(Event.COMPLETE, function(e:Event):void{
		trace(e.target.data);
	});
	loader.load(request);
}

Proving the spreadsheet’s field naming convention

You may be wondering, how did “entry.0.single” get in there? I myself isn’t quite sure as to why Google named it that way. However, to determine how I got this property, I still use Firebug.

Go to the Google spreadsheet…

Tracking the changes by watching the Cache

A simple note whenever you’re trying to modify any of the .php or .as files, always clear the browser’s cache. To prove that the .php file is cached, go to the method “showErrorStatus” in “crossdomain_proxy.php”, try deleting a simple greater-than symbol in the last portion of the echoed string and determine its value in the Firebug’s “Net” tab.

echo “<html><head><title>Oops</title></head><body><h1>$sText</h1></body></html”;

Refresh your browser without clearing the cache and launch Firebug.

Locate “POST crossdomain_proxy.php” and go the the “Response” tab. If the output is not the same on the above, then your Flash page is being cached by the browser.

There you have it! Storing values to the Google spreadsheet using AS3. You may want to proceed in Retrieving Values from Google Spreadsheets using AS3 to continue on the second part of this post.

Download

FlashToGoogleSpreadsheet.zip