case
ADM Blog
5May/100

Open and Save files to Desktop without going to Server

Few days ago I was working on a jQuery based tool to QA the JavaScript functionality of a website and I was in need of a method to save and load my scripts to Desktop.
In most cases this require a server script where you send the content and it will serve it to download and same for loading it. But a colleague suggested a better solution: to use the FileReference class.
First step was to create a simple flash with the required functionality and send/retrieve data with ExternalInterface. Failed miserably. Why ? Because it seems Flash will not allow you to open a File Dialog from script only. You literally have to click a button from the movie interface to be able to do that. If you knew that good for you, I didn't.

So, I've created another flash movie, where you pass the open and save image and callback and it will insert the flash with the specified images in place and look just like any other buttons.

Here's a small demonstration (other buttons beside open and save are just for show):

So what do you need to set it up ?

First, you have to include the FileDialogs.js in your document (or just paste the code inside it into your own script).

Second, you need your JavaScript callbacks.

1
2
3
4
5
6
7
function openCallback(input) {
     document.getElementById('text').value = input;
}
 
function saveCallback() {
     return document.getElementById('text').value;
}

openCallback() will be called once the user will select a file from the desktop and pass it's content as a parameter
saveCallback() will be called when the user clicks save, before the dialog to choose a file name opens, and it must return the content you want to save to disk

Third, you must setup the whole thing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// call this function on the onload event so the placeHolder element gets created
function onLoad() {
    // Create a config object
    var config = new FileDialogsConfig();
    // width of the entire flash movie (buttons width + padding)
    config.width = 45;
    // height of the movie
    config.height = 16;
    // padding between buttons
    config.padding = 5;
    // open dialog button image and javascript callback function
    config.open.image = "open.png";
    config.open.handler = "openCallback";
    // save dialog button image and javascript callback function
    config.save.image = "save.png";
    config.save.handler = "saveCallback";
    // create the movie inside an element with the given id and configuration
    new FileDialogs("placeHolder", config);
}

Note: Handler callbacks in the config must be declared as String and not reference. IE will freak out and I don't want to fix it.

You can have only one button (open or save) if you chose so. Just don't set the other one.

That's about it. The placeHolder can be any container element. The script will set it's style size based on the configuration, the movie will have transparent background so don't worry about that, and it will set it's float property to left so you can add other stuff after it. But all those things are easy to configure if you mess a bit with the FileDialogs.js file.

Cheers!

Download Source and Demo

28Apr/100

Serialize JavaScript object to JSON

Recently, on a project I was working, I needed a function to serialize a JavaScript object and all I could find online were scripts and jquery plugins for serializing a html form. Then, I found this, a script that takes advantage of the .toSource() method available in Gecko-based browsers and for the rest of them plain old recursion. But it does the trick as expected and I'm pretty sure someone else might need it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function serialize(_obj) {
   if (_obj != undefined && typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined') {
      return _obj.toSource();
   }
   switch (typeof _obj) {
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;
      case 'string':
          return '"' + _obj.replace(/"/mg, "'") + '"';
          break;
      case 'object':
          var str;
          if (_obj.constructor === Array || typeof _obj.callee !== 'undefined') {
              str = '[';
              var i, len = _obj.length;
              for (i = 0; i < len-1; i++) { str += Utils.serialize(_obj[i]) + ','; }
              str += Utils.serialize(_obj[i]) + ']';
          } else {
              str = '{';
              var key;
              for (key in _obj) { str += key + ':' + Utils.serialize(_obj[key]) + ','; }
              str = str.replace(/\,$/, '') + '}';
          }
          return str;
          break;
      default:
          return '""';
          break;
      }
}

To deserialize it, just use eval().

Also, if you need the same thing for your Flash/Flex Actionscript3 project, here is a class for that as well -> Click Me.

Cheers!

11Mar/100

Neural networks in ActionScript 3

Neural Network"An artificial neural network (ANN), usually called "neural network" (NN), is a mathematical model or computational model that tries to simulate the structure and/or functional aspects of biological neural networks. It consists of an interconnected group of artificial neurons and processes information using a connectionist approach to computation. In most cases an ANN is an adaptive system that changes its structure based on external or internal information that flows through the network during the learning phase. Neural networks are non-linear statistical data modeling tools. They can be used to model complex relationships between inputs and outputs or to find patterns in data." (Wikipedia)

Multi Layer PerceptronSo, repetition is the mother of all learning they say. You damn right it is. And you can do it in AS3 of course. Not the fastest choice out there but that's not the point. NN's are usually not that fast but they're useful in so many ways.

So, here is my implementation of a neural network multi-layer-perceptron made in AS3, set to learn a simple XOR problem. It uses 2 inputs neurons , 2 hidden layers, each having 2 neurons and one output neuron. It takes about 2 seconds to train it using 10.000 epochs, but then you can save a snapshot of the NN memory as a byteArray, save it to the server and load it back again in an instant without requiring a new training.  I didn't take the time to thoroughly document the classes just yet but I'm sure you'll find them pretty easy to use.

Some reading material:
http://en.wikipedia.org/wiki/Artificial_neural_network
http://fbim.fh-regensburg.de/~saj39122/jfroehl/diplom/e-index.html (this is great)
http://www.ai-junkie.com/ann/evolved/nnt1.html

Sources and Download


20Jan/100

Every day the same dream

Just brilliant. By molleindustria

24Jun/090

Ho-To: Install Alchemy

For those of you who tried but didn't succed, I found some straigthforward instructions for this.

Setup Hell:

Install cygwin to "c:\cygwin" - make sure to check boxes to install Perl, "Archive" (ZIP), and Devel/gcc:g++ (3.4.4.3 presumably) (is Perl necessary?)
Copy the alchemy directory to: c:\cygwin\home\Lee
Copy the flex sdk bin dir from c:\program files\etc to "c:\flex" (to avoid paths with spaces in it!)
Run the alchemy config script once:

   run cygwin
   cd alchemy
   ./config

Edit the textfile "C:\cygwin\home\Lee\alchemy\alchemy-setup" and uncomment and edit line 22 to: add "export ADL=c:\flex\adl.exe"

Edit .bashrc (in C:\cygwin\home\Lee)

   echo "LEE PROFILE"
   export FLEX_HOME=~/flex
   export ALCHEMY_HOME=~/alchemy
 
   # "This should be added before your PATH is modified" !!
   source /home/Lee/alchemy/alchemy-setup
 
   PATH=$ALCHEMY_HOME/achacks:/home/Lee/flex:$PATH
   export PATH
 
   alc-on

Do this (just once, I think):

   cd $ALCHEMY_HOME/bin
   ln -s llvm-stub llvm-stub.exe

Compiling a SW:

CD to the directory with the source
Always do "alc-on" before compiling, cuz it doesn't work without it even though i added it to the startup (dunno)

    gcc stringecho.c -O3 -Wall -swc -o stringecho.swc
    -- should give you a swc.

Import the swc into your flex builder 4 project and make sure compiler targets SDK v4

Shortcuts

alc-home - takes you to the Alchemy install folder.
alc-on - puts Alchemy gcc toolchain replacements at the front of your path.
alc-off - restores original path.
alc-util - shows you various Alchemy-related environment vars

USEFUL TO KNOW

which gcc - tells you which gcc it will use (should be the one in the achacks dir)
ln - links shit
rm - deletes links as well as files

Ugh: Make sure to do "alc-on" and "alchemy-setup" even though you put it in the startup script :( (?)

...

Objects:
AS3_Val
AS3_ArrayValue

Methods:
AS3_Release
AS3_LibInit