Warning: include() [function.include]: Unable to access /var/www/html/rogue-development/blog2/wp-content/advanced-cache.php in /var/www/html/rogue-development/blog2/wp-settings.php on line 62

Warning: include(/var/www/html/rogue-development/blog2/wp-content/advanced-cache.php) [function.include]: failed to open stream: No such file or directory in /var/www/html/rogue-development/blog2/wp-settings.php on line 62

Warning: include() [function.include]: Failed opening '/var/www/html/rogue-development/blog2/wp-content/advanced-cache.php' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/rogue-development/blog2/wp-settings.php on line 62

Notice: add_option was called with an argument that is deprecated since version 2.3 with no alternative available. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3468

Notice: register_sidebar_widget is deprecated since version 2.8! Use wp_register_sidebar_widget() instead. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3382

Notice: register_widget_control is deprecated since version 2.8! Use wp_register_widget_control() instead. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3382
Marc « Marc’s Musings


Notice: get_author_name is deprecated since version 2.8! Use get_the_author_meta('display_name') instead. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3382

Author Archive for Marc

Page 4 of 25

My wish: type Checking in CSS

I wish there was type-checking in CSS for Flex applications. Way too many times have I come across a style that either:

  1. Uses a style attribute that’s not valid for the component type
  2. Uses a value for an attribute that’s the wrong type

These are the types of issues that should be caught at compile time.  I’m not sure if it’s possible to do with CSS since it’d be a really complex problem to try and solve.  Especially with “nested” styles where a style attribute is specifying the stylename of a sub component.

Hell, maybe I am really wishing for something other than CSS for flex apps.  I wonder what a nice type-safe format for specifying style information might look like.  It’d have to retain the centrally-located benefit of CSS, and probably not sacrifice much of the flexibility.

ByteArray writeUTF vs. writeUTFBytes

I just got bit by using writeUTF instead of writeUTFBytes, I knew they worked differently, but it took me a couple google searches to figure out why.

writeUTF appends a 16 bit length, and then your actual data
writeUTFBytes simply appends your data

So why does writeUTF work like that?

When you read data back in, readUTF can get how long the string to read is, and then read exactly that much in. On the other hand, readUTFBytes just reads everything back. Seems like a minor difference, but imagine these two scenarios.

This works perfectly:

  1.  
  2. myByteArray.writeUTF("Hello World");
  3. myByteArray.writeFloat(100);
  4. a = myByteArray.readUTF();
  5. b = myByteArray.readFloat();
  6.  

This next example does not work because the readUTFBytes also reads in that float we wrote, so the readFloat call has nothing to retrieve:

  1.  
  2. myByteArray.writeUTFBytes("Hello World");
  3. myByteArray.writeFloat(100);
  4. a = myByteArray.readUTFBytes(myByteArray.length);
  5. b = myByteArray.readFloat();
  6.  

On the other hand, the writeUTF method can only handle strings up to 64k float. So if you have an arbitrarily sized string it’ll eventually failed. This is what I ran into.

So here’s a couple simple rules for choosing which to use:

1) If you need to write arbitrarily sized large strings, use writeUTFBytes, but don’t write anything after it.
2) If you need to write multiple items to your byte array and read them back that way, use writeUTF, but don’t exceed 64k strings
3) If you need to create a byte array with no “header” of that leading length, use writeUTFBytes (like if you’re making a stand-alone file to inter operate with some other system)

Compiling FXP->SWC, a Catalyst workflow

The other day, I blogged about an alternate workflow to Catalyst. It was somewhat confusing with a few steps involved. Towards the end of the post I had a couple wishes including:

  1. Let me select a package that components get created in.
  2. Export a swc with everything in it so we don’t have to go through most of this.

Last night I wrote a ruby script capable of doing exactly those two things.  I call it fxp2swc.rb.

Using the script is simple.  First open it up and set the two variables at the top.

  1. @flex_dir = "/Applications/Adobe\\ Flash\\ Builder\\ Beta/sdks/4.0.0";
  2. @default_package = "com.roguedevelopment.catalyst";

The flex_dir just tells the script where your Flex SDK is. The default_package tells it what package you want your catalyst based components made in.

After you edit that, put the script in the same directory as your .fxp files. Run the script and you should see output like this:

$ ./fxp2swc.rb
=== FCTest.fxp
 Extracting to FCTest.fxp.tmp
 Creating directory FCTest.fxp.tmp/src/com
 Creating directory FCTest.fxp.tmp/src/com/roguedevelopment
 Creating directory FCTest.fxp.tmp/src/com/roguedevelopment/catalyst
 Creating directory FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest
 Copying Main.mxml
 Copying FCTest.fxp.tmp/src/components/Background.mxml -> FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest
 Copying FCTest.fxp.tmp/src/components/CustomComponent1.mxml -> FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest
 Copying FCTest.fxp.tmp/src/components/LoginButton.mxml -> FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest
 Copying FCTest.fxp.tmp/src/components/LoginForm.mxml -> FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest
 Copying FCTest.fxp.tmp/src/components/TextInput1.mxml -> FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest
 Removing old source locations
 Fixing package names in FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest/Background.mxml
 Fixing package names in FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest/CustomComponent1.mxml
 Fixing package names in FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest/LoginButton.mxml
 Fixing package names in FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest/LoginForm.mxml
 Fixing package names in FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest/Main.mxml
 Fixing package names in FCTest.fxp.tmp/src/com/roguedevelopment/catalyst/FCTest/TextInput1.mxml
 Creating swcconfig.xml
 Invoking compc -load-config+=swcconfig.xml
Loading configuration file /Applications/Adobe Flash Builder Beta/sdks/4.0.0/frameworks/flex-config.xml
Loading configuration file /Users/mhughes/Dropbox/fxg2swc/swcconfig.xml
/Users/mhughes/Dropbox/fxp2swc/FCTest.swc (1463574 bytes)
Deleting temp dir
Done!

You now have a one .swc for every .fxp file! As easy as that!

Take the swc, and plop it into the “libs” folder of you Flash Builder project, and you can start using the components from it. They’ll be in a package that starts with your default_package variable and ends with the name of the .fxp you compiled. So for my example FCTest.fxp, the package is: com.roguedevelopment.catalyst.FCTest

Here’s a quick example of what it looks like to use one of those components:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
  3.      xmlns:s="library://ns.adobe.com/flex/spark"
  4.      xmlns:mx="library://ns.adobe.com/flex/halo"
  5.      minWidth="1024" minHeight="768"
  6.      viewSourceURL="srcview/index.html"
  7.      xmlns:FCTest="com.roguedevelopment.catalyst.FCTest.*">
  8.  
  9.         <FCTest:Background verticalCenter="0" horizontalCenter="0" />
  10.  
  11. </s:Application>

You can still use the composition or inheritance methods of using those components that I blogged about the other day. Here’s an example showing that with view-source enabled.

I’m on OSX using Ruby v1.8.6 with this script. Your mileage may vary on other platforms. Two things that will likely need to change for Windows users:

  • The compc call should use compc.exe
  • It uses the unzip command line utility, not sure if that’s a standard tool on Windows

Boston area job opening: Project Manager

The company I work for is hiring a project manager with an engineering background.  I think we’ll be doing some cool stuff over the next couple years if you’re interested. This product will make a difference in a lot of kid’s lives.

Every time I post one of these I get a flood of contact from way too many people.  Here’s a few answers:

  • Yes, this is an on-site position we are not considering any remote option.
  • No, do not email or call me, I’m not the hiring manager / contact person on this one.  The email address to contact is below.
  • No, recruiters are not welcome to contact me in any way about this or anything else whatsoever.

Software Engineering Project Manager

Tom Snyder Productions, a Scholastic company and developer of innovative educational software products, is seeking a Software Engineering Project Manager for a major new math education project.  This position is directly responsible for coordinating the resources, schedules and deliverables of multiple engineering teams working on components of an innovative software-driven math curriculum product.  The ideal candidate for this hands-on position has:

•    Ability to provide schedule and deliverable management for multiple engineering teams
•    Experience with Agile methodology for focusing on manageable development iterations and coordinating the work of multiple engineering teams with “Scrum of Scrums” process
•    Excellent communication skills – listening, verbal and written
•    Strong problem-solving skills
•    Desire to work as part of an efficient, agile software development and publishing organization
•    Enthusiasm about education

Responsibilities include:
•    Recruiting and staffing of multiple engineering teams tasked with developing multiple application modules, including content authoring/management system application, classroom course-delivery software, individual response/polling systems, interactive mathematics tools, individual differentiated-instruction environment, and performance data collection and analysis framework
•    Development of master engineering schedule; management of schedules, milestones and engineering tasks across multiple teams
•    Synthesis of technical requirements from detailed use cases and functional requirements
•    Estimation of task labor, tracking of engineering progress metrics and adjustment of future scheduling

This position offers the tremendous satisfaction of contributing directly to the lives of young people by delivering extraordinary learning products into their classrooms.

Tom Snyder Productions, a Scholastic company, is the developer and publisher of award-winning educational software products for K-12 classrooms.  We offer a vibrant and friendly work atmosphere focused on making a difference in the lives of students and teachers.

Compensation is based on experience and includes excellent benefits.

Job Qualifications/Requirements
•    Bachelor’s degree or equivalent experience.
•    Minimum 4 years experience in software industry, including at least 2 years of technical project management
•    Hands-on problem solving skills, and outstanding oral and written communication skills
•    Software Engineering skills desireable, including experience coding in object-oriented languages and frameworks such as Java, ActionScript 3, Flex
•    Experience with configuration management, defect and test case tracking, design patterns
•    Capable of learning new processes and technologies quickly

How To Apply
Interested candidates please send resume and cover letter to:
Email: Proddev@tomsnyder.com

A Flash Catalyst / Builder workflow method

Update: Check out the new post where I describe how to compile to a swc.

I’ve been playing around with the Flash Catalyst and Builder betas today and one thing that scares me a little is the built-in designer/developer workflow that’s implied.  From what I can gather, a designer uses a design tool, imports that into Catalyst, and then hands of a .FXP file that a developer then imports into Builder to work on.  Then the developer jumps into the files generated by Catalyst, and modifies them.

For smallish projects, that’s a slam-dunk.  If you don’t work on large projects, stop reading here and just stick with that.

But there’s a number of reasons I really don’t like this intended workflow for larger projects.

First, it’s not scaleable.  One catalyst file -> one Flash Builder project.  It’s awefully hard for a team of 5 designers to work on a single catalyst file.

It implies some exclusivity.  If the designer hands off the .FXP file, they really shouldn’t continue working on it because the developer will start modifying it.  It’s kind of like having a Word document that you pass back and forth between the designer and the developer.  If they both want to work on it at the same exact time, you’ll get race conditions.

Second, I don’t trust anybody to get a perfect Generated Code <-> User Edited Code tool to work perfectly all the time.  If Catalyst generates some code, I edit that, and then we bring it back into Catalyst, I just know that will break at some point.  (Sorry Adobe guys, I know you’ll do a rocking job with it, and I know it will almost always work, but it’s just too hard a problem)

So here’s a solution I’ve been playing with:

Step 1: Create your design comp

Here’s a Photoshop file I created with a pretty simple login form.  Make sure to name your layers so they’re easy to find later.

Step 2: Import it into Flash Catalyst just like you’re supposed to.  Edit it to your heart’s content.

There’s a bunch of tutorials out there (great one from Lee Brimlow here) that show how to actually use Catalyst.  But one difference from all those tutorials.  We won’t be using the Main root level item.  So don’t go crazy adding states to your base stage.  But DO go crazy creating sub-components and adding states and behaviors to those.

Here’s a screenshot of my Catalyst project.  This is showing off a LoginForm component that I created.  Notice it has a few states with transitions set up between those states.

Step 3: Save it as a .FXP

File->Save from Flash Catalyst.

For my example, I used FCTest.fxp as the name.

Step 4: Create an empty Flash Builder project (not importing anything here)

Just create a plain old Flash Builder project with a Flex based application in it.  (Make sure you’re using a Flex 4 SDK!)

Step 5: Take your .FXP from above, and unzip it somewhere

Here’s the sneaky part.  That .fxp file is really just a zip file that contains a Flash Builder project.  You can unzip it with any standard zip tool.  In OSX I just open a terminal and did a:

unzip FCTest.fxp

It creates a directory structure that looks something like this:

Notice the two folders with arrows pointing to them, they’re important in the next step.

Step 6: Take the components and assets folders from that unzipping and put them in a brand new folder.

We can take those two folders and use them in our Flash Builder project to get access to all of our custom components that we made in Flash Catalyst.  I’m planning ahead a little bit so I created a “CatalystAssets” folder, and a “FCTest.fxp” folder inside that, and placed them there.  This will allow me to have assets from many different catalyst files in the future someday.

Step 7: Link to that folder from your Flash Builder project

Flash Builder can link to source directories outside of the project.  To do that go to Project->Properties->Flex Build Path.  Click the “Add Folder…” button and add the FCTest.fxp folder (the folder we created, not the file Catalyst made).

In Flash Builder’s Package Explorer you’ll see something like this after you do that:

The developer should NEVER EDIT anything in the FCTest folder.  Consider that all auto-generated stuff that will wipe out anything you do in there.

The developer can and should work in the normal Flash Builder src folder, likely importing classes and assets from the FCTest folder and using them.

Step 8: Use the Flash Catalyst based assets!

For simple components that you don’t need to add any functionality to, you can just use them in your MXML.  For example, I created a component called Background in my Catalyst file.  To use it in the Flex application you just do something like this:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
  3.  xmlns:s="library://ns.adobe.com/flex/spark"
  4.  xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768"
  5.  xmlns:components="components.*">
  6.  
  7.  <components:Background verticalCenter="0" horizontalCenter="0" />
  8.  
  9. </s:Application>

Notice the components namespace with the Background component name.

Adding non-interactive components isn’t all that interesting.  So what happens if you want to add functionality to components created in catalyst?  There’s two options here, either use the assets from the .FXP through composition or inheritance.  Here are two examples that show how to do them both:

Extending a Catalyst component through inheritance:

  1. package com.roguedevelopment.fctest
  2. {
  3.  
  4.   import components.LoginForm;
  5.   import flash.events.MouseEvent;
  6.   import flash.utils.setTimeout;
  7.   import mx.controls.Alert;
  8.   import mx.events.FlexEvent;
  9.  
  10.   public class InheritenceExample extends LoginForm
  11.   {
  12.     public function InheritenceExample()
  13.     {
  14.       super();
  15.       addEventListener(FlexEvent.CREATION_COMPLETE, creationComplete );
  16.     }
  17.     protected function creationComplete(event:FlexEvent):void
  18.     {
  19.       setTimeout( function():void{ currentState = "Normal"; }, 300 );
  20.       textinput2.displayAsPassword = true;
  21.       button1.addEventListener(MouseEvent.CLICK, onLoginButtonClick );
  22.       textinput1.setFocus();
  23.     }
  24.  
  25.     protected function onLoginButtonClick(event:MouseEvent):void
  26.     {
  27.       var correct:Boolean = ( textinput1.text == "marc" ) &amp;&amp;
  28.                       ( textinput2.text = "1234" );
  29.  
  30.       if( correct )
  31.       {
  32.         currentState = "Working";
  33.         setTimeout( success , 1500 );
  34.       }
  35.       else
  36.       {
  37.         currentState = "Error";
  38.         setTimeout( function():void{ currentState = "Normal"; }, 1500 );
  39.       }
  40.     }
  41.  
  42.     protected function success() : void
  43.     {
  44.       Alert.show("Correct log in!");
  45.       currentState = "Normal";
  46.     }
  47. }
  48. }

Or, if you want to use composition instead of inheritance you could do something like this:

  1. package com.roguedevelopment.fctest
  2. {
  3.   import components.LoginForm;
  4.   import flash.events.MouseEvent;
  5.   import flash.utils.setTimeout;
  6.   import mx.controls.Alert;
  7.   import spark.components.Group;
  8.  
  9.   public class CompositionExample extends Group
  10.   {
  11.     protected var loginForm:LoginForm;
  12.  
  13.     public function CompositionExample()
  14.     {
  15.       super();
  16.     }
  17.  
  18.     override protected function createChildren() : void
  19.     {
  20.       loginForm = new LoginForm();
  21.       addElement(loginForm);
  22.       width = 527;
  23.       height = 325;
  24.       setTimeout( function():void{ loginForm.currentState = "Normal"; }, 300 );
  25.       loginForm.textinput2.displayAsPassword = true;
  26.       loginForm.button1.addEventListener(MouseEvent.CLICK, onLoginButtonClick );
  27.       loginForm.textinput1.setFocus();
  28.     }
  29.  
  30.     protected function onLoginButtonClick(event:MouseEvent):void
  31.     {
  32.       var correct:Boolean = ( loginForm.textinput1.text == "marc" ) &amp;&amp;
  33.                  ( loginForm.textinput2.text = "1234" );
  34.  
  35.       if( correct )
  36.       {
  37.         loginForm.currentState = "Working";
  38.         setTimeout( success , 1500 );
  39.       }
  40.       else
  41.       {
  42.         loginForm.currentState = "Error";
  43.         setTimeout( function():void{ loginForm.currentState = "Normal"; }, 1500 );
  44.       }
  45.     }
  46.  
  47.     protected function success() : void
  48.     {
  49.       Alert.show("Correct log in!");
  50.       loginForm.currentState = "Normal";
  51.     }
  52.   }
  53. }

Now that you have your components with some added functionality, you can use them in your main application like you would any other Flex based component. You can see a working demo, with view-source enabled here:

http://rogue-development.com/uploads/catalystWorkflow/FCTest.html

As you can tell, that seems like a LOT of extra work. But here’s the payoff:

  1. The designer is free to continue working in Flash Catalyst while the developer works in Flash builder.  Whenever he has changes, he just hands off a brand new .FXP, and the developer repeats steps 5 and 6 to replace some files and then refreshes the Flash Builder workspace.
  2. You can create multiple folders inside that “CatalystAssets” folder, and then use assets from multiple FlashCatalyst projects in a single Flash Builder project.
  3. You can add those Flash Catalyst assets to version control and easily distribute them to multiple developers. (Not to mention track changes!)

I did up a quick shell-script to unzip the .fxp file, make some directories, and copy the files to the appropriate place.  I can run this whenever the designer gives me a new .fxp. I think with a little work we could create a Eclipse “Builder” (that’s unrelated to the product name “Flash Builder”) that would completely automate this entire process.

  1. #!/bin/bash
  2.  
  3. rm -rf .tmp
  4. mkdir .tmp
  5. cd .tmp
  6.  
  7. unzip -o ../FCTest.fxp
  8.  
  9. cd ..
  10.  
  11. rm -rf CatalystAssets/FCTest.fxp/com/roguedevelopment/fctest
  12.  
  13. mkdir CatalystAssets/FCTest.fxp
  14. mkdir CatalystAssets/FCTest.fxp/assets
  15.  
  16. mv .tmp/src/components CatalystAssets/FCTest.fxp
  17. mv .tmp/src/assets/FCTest CatalystAssets/FCTest.fxp/assets

Some things I wish Flash Catalyst did:

  1. Let me select a package that components get created in. (maybe there’s a way to do that?)
  2. Make it easier to intelligently name the classes and property names that get generated
  3. Export a swc with everything in it so we don’t have to go through most of this.

Well anyways, I give Catalyst 2 thumbs up and even if we have to go through this process for a sane workflow it will save huge amounts of time in our shop.

P.S. I’m no Catalyst expert so maybe there IS a better workflow that I just haven’t seen yet.

My Flash CS4 favorite new feature

I’ve only been using Flash CS4 for a couple weeks now. The 3d stuff, the reverse kinematics, even the new text stuff hasn’t been all that interesting. But this little baby rocks my socks:

CS4 Library Search Field

CS4 Library Search Field

ObjectHandles V2, sneak peek

Today I’ve been working on the next major release of ObjectHandles. Below is an example showing off some of the new features. I’m most excited about the enhanced rotation support.   This new version is focused on making a version that will easily work with MVC frameworks like Moccasin. Some of the changes include:

  • You no longer have to re-parent your components.
  • What and where handles appear is now completely configurable
  • ObjectHandles modifies your data object instead of moving a component around (there’s 3 example visual components / data models in the source)
  • Optionally, object handles won’t swallow all of your mouse events.
  • Will now work with non-flex components (still requires Flex SDK to compile, I have to look into that)
  • Rotation support is completely smooth
  • Configurable constraints/rules system
  • Smaller, cleaner code base!

Scroll down for demo.

Click to see the early proof of concept of it working within Mocassin.

ObjectHandles is a library to easily add graphical move/resize user gestures to a Flex based application.

[kml_flashembed fversion="8.0.0" movie="/uploads/ohv2/ObjectHandles2Example.swf" targetclass="flashmovie" publishmethod="static" width="700" height="700" fvars="undefined"]

Get Adobe Flash player

[/kml_flashembed]


Flicker related to modules and custom components

In a Flex application I’m working on we’ve been plagued with some flickering problems that have been very tough to pin down. I think I’ve finally figured out (at least one) source of the problem. We have a bunch of custom components developed. Those components have static intializers that set up the default styles for them like this:

  1. private static var classConstructed:Boolean = classConstruct();
  2. private static function classConstruct():Boolean {
  3.    if (!StyleManager.getStyleDeclaration("NumericDisplay"))
  4.    {
  5.       var myStyles:CSSStyleDeclaration = new CSSStyleDeclaration();
  6.        myStyles.defaultFactory = function():void
  7.                 {
  8.                     this.fractionLabelStyleName = "";
  9.                     this.wholeLabelStyleName = "";
  10.                     this.topGap = 0;
  11.                     this.barStrokeColor = 0;
  12.                     this.barColor  = 0;
  13.                     this.barWeight = 2;
  14.                 }
  15.         StyleManager.setStyleDeclaration("NumericDisplay", myStyles, true);
  16.  
  17.    }
  18.    return true;
  19.  }
  20.  

Now, usually, that works A-OK. It runs before there’s anything on screen so no flicker.

But, what happens if the class that contains that isn’t in your main application swf and is instead a loaded module? Well, that initializer doesn’t run until the module loads. And the call to StyleManager.setStyleDeclaration causes the entire application to update it’s display which causes a visual flicker.

I was considering some solutions like:
Making sure the class gets compiled into your main application swf.
Add the default CSS to a .css file that gets loaded at startup instead of doing it in code.

But then I realized that the last param to the setStyle call determines whether or not to update styles, setting that to false fixes the flicker. Since the static initializer has to run before any of that component are constructed, we don’t actually need to be doing an update anyways.

  1.  
  2.  StyleManager.setStyleDeclaration("NumericDisplay", myStyles, false);
  3.  

After googling a bit, I found “best practice” examples that did it both ways. I’d suggest sticking with “false” due to this type of problem.

Reminder: Floats are not precise

I was chatting with a couple friends the other day about an odd bug that was due to floating point precision.  Neither of them got it at first, and it reminded me that not everyone realizes how imprecise floating point math can be.  I know this, you know this, even the friends I was talking to knew it after they thought about it.  But it’s so easy to ignore it since floating point math usually does what we want.  Here’s three amazingly simple examples:

Actionscript:

  1. var val:Number = 0.0;
  2. for( var i:int = 0 ; i < 10 ; i++ )
  3. {
  4.         val += 0.1;
  5. }
  6. trace(val);

Java:

  1. public class FloatTest {
  2.         public static void main(String[] args) {
  3.                 float val = 0;
  4.                 for( int i = 0 ; i < 10 ; i++)
  5.                 {
  6.                         val += 0.1;
  7.                 }
  8.                 System.out.println( val );
  9.         }
  10. }

Ruby (I had to go a bit higher on the loop since it rounds differently):

  1. val = 0
  2. (1..100).each do
  3.   val += 0.1
  4. end
  5. print val

What would you expect the output of those to be? Probably 1, 1, and 10 right?

Wrong.

The actionscript example comes out to 0.9999999999999999, java has 1.0000001, and ruby gets 9.99999999999998

Here’s another actionscript example:

  1. trace( (0.1 + 0.1 ) == (2/10) );
  2. trace( (0.1 + 0.1 + 0.1) == (3/10) );

That traces out:
true
false

Baffling huh? A float should easily have the precision to represent a tenth, right? It should easily be able to add up ten tenths to get one, right?

Here’s the problem. Floats really operate in binary (duh). In binary, you can’t represent a lot of simple decimal values, such as 0.10 without a repeating pattern. 0.10 decimal works out to 0.000110011 in binary, with the last 4 digits repeating forever. So the 0.1 you see when you trace out 0.1 is really just a rounded off binary value. If you do math with those values, the error can accumulate until it’s big enough to be seen despite the rounding.

So you should never use floats for anything like:

  • Money
  • “Real mathematics” (for instance, I work on educational math software where the numbers have to always actually add up)
  • Anything requiring a certain precision, like sending a probe to mars or calculating medication dosage

You should use floats for things where precision doesn’t really matter.  Things, that if you’re off by a little nobody will ever notice.  Games, animations, audio compression, etc.   Otherwise, the easiest solution is to stick to integer based math.  You can pick a unit of measure magnitudes higher than you need.  Example: for money use cents (or thenths of cents?) instead of dollars as your UoM.  Then when you display the value you divide by 100 to show dollars.  Or you could use a richer class that handles precise numbers like Java’s BigDecimal, or ruby’s Rational type.

But like I said, we already knew this, right?

Creating nested objects with JSON in Rails


Notice: Undefined index: STRICT_MODE_APPLIES in /var/www/html/rogue-development/blog2/wp-content/plugins/deans_code_highlighter/geshi.php on line 1036

Did you know it’s possible to send a single JSON based request to a stanard rails controller and have it create an object, plus an entire tree of children records?  I knew it was possible, but I was wracking my brain trying to figure out how to do it for several days. Imagine you have a data model something like this:

  1. class Commute < ActiveRecord::Base
  2.   has_many :locations
  3. end
  4.  
  5. class Location < ActiveRecord::Base
  6.   belongs_to :commute
  7. end

That’s a pretty simple many-to-one relationship.  Now, if you have a regular old Rails controller, how do you pass that single JSON request to create both the commute object, as well as several location children?

The first step is to add the accepts_nested_attributes_for attribute to the commute model object.

  1. class Commute < ActiveRecord::Base
  2.   has_many :locations
  3.   accepts_nested_attributes_for :locations, :allow_destroy => true
  4. end

And… that’s it on the server side!

To use this functionality, your client should send a PUT request with the following JSON in the body:

  1. {
  2.     "commute": {
  3.         "minutes": 0,
  4.         "startTime": "Wed May 06 22:14:12 EDT 2009",
  5.         "locations_attributes": [
  6.             {
  7.                 "latitude": "40.4220061",
  8.                 "longitude": "127.4220061"
  9.             },
  10.             {
  11.                 "latitude": "42.4220061",
  12.                 "longitude": "41.4220061"
  13.             }
  14.         ]
  15.     }
  16. }

minutes and starttime are two properties of the commute object. And likewise latitude and longitude are two properties of the location objects.
The only thing strange there is instead of passing a locations array, you have to pass a locations_attributes array. The “_attributes” is the magic piece that I couldn’t figure out.  This lets Rails know you want it to figure out how to create the children, and you’re not simply passing those children in.

If you don’t put the _attributes suffix in, you’ll get errors like the following because Rails is creating a generic hash and trying to shove that into where a Location object should go.

ActiveRecord::AssociationTypeMismatch (Location(#18269790) expected, got HashWithIndifferentAccess(#2654720)):

This general approach should work with XML or HTTP params based requests as well.