AS3: Results of casting primitive types

I have many bugs in my code connected with incorrect casting. To avoid them I’ve created small class to list all interesting cases:

String (1               :String)             = 1
String (0               :String)             = 0
String (0               :int)                = 0
String (1               :int)                = 1
String (true            :String)             = true
String (false           :String)             = false
String (true            :Boolean)            = true
String (false           :Boolean)            = false
String (null            :null)               = null
String (undefined       :undefined)          = undefined
String (NaN             :Number)             = NaN
String ([object Object] :Object)             = [object Object]
String (a,b             :Array)              = a,b
String (                :Array)              =
Number (1               :String)             = 1
Number (0               :String)             = 0
Number (0               :int)                = 0
Number (1               :int)                = 1
Number (true            :String)             = NaN
Number (false           :String)             = NaN
Number (true            :Boolean)            = 1
Number (false           :Boolean)            = 0
Number (null            :null)               = 0
Number (undefined       :undefined)          = NaN
Number (NaN             :Number)             = NaN
Number ([object Object] :Object)             = NaN
Number (a,b             :Array)              = NaN
Number (                :Array)              = 0
int (1                  :String)             = 1
int (0                  :String)             = 0
int (0                  :int)                = 0
int (1                  :int)                = 1
int (true               :String)             = 0
int (false              :String)             = 0
int (true               :Boolean)            = 1
int (false              :Boolean)            = 0
int (null               :null)               = 0
int (undefined          :undefined)          = 0
int (NaN                :Number)             = 0
int ([object Object]    :Object)             = 0
int (a,b                :Array)              = 0
int (                   :Array)              = 0
Boolean (1              :String)             = true
Boolean (0              :String)             = true
Boolean (0              :int)                = false
Boolean (1              :int)                = true
Boolean (true           :String)             = true
Boolean (false          :String)             = true
Boolean (true           :Boolean)            = true
Boolean (false          :Boolean)            = false
Boolean (null           :null)               = false
Boolean (undefined      :undefined)          = false
Boolean (NaN            :Number)             = false
Boolean ([object Object]:Object)             = true
Boolean (a,b            :Array)              = true
Boolean (               :Array)              = true

By the way I’ve recalled about library – as3-commons and its’ module Lang, which contains StringUtils class. It gave me ability to create quickly good looking traces. Small things gives great joy…


package as3
{
	import flash.utils.describeType;
	import org.as3commons.lang.StringUtils;
	/**
	* @author parhelium [mail-at-parhelium-dot-pl]
	* 2011-01-29 11:15
	*/
	public class primitives
	{
		private var test:Array = ["1", "0", 0, 1, "true","false",true, false, null, undefined, NaN, { }, ["a","b"],[]]
		private var types:Array = [String, Number, int, Boolean]
		public function primitives() {
			for each(var c:Class in types) {
				for each (var item:* in test) {
					makeTest(item,c);
				}
			}
		}
		private function makeTest(obj:*, castToType:*):void {
			var s:String = "" + claz(castToType) + " (" + obj
			s = StringUtils.rightPad(s, 24, " ")
			s += ":" + claz(obj)+")";
			s = StringUtils.rightPad(s, 45, " ")
			s +=  "= "+castToType(obj);
			trace(s)
		}
		private function str(obj:*):String {
			return obj+"  :"+claz(obj)
		}
		public static function claz(claz:*):String {
			if (claz === null) return "null";
			if (claz === undefined) return "undefined";

			var x:XML = new XML(describeType(claz));
			return String(x.@name).replace(/(.*)::(.*)/, "$2");
		}
	}
}

Groovy: remove unexpected duplications of images

GroovyConsole with my code


Today i realised that in one of my photo album (“D:/Entertainment/photos/2010/20100814″) there are many duplications (one for each file).
It looked like here:

_MG_9884.CR2
_MG_9884.xmp
_MG_9884-1.CR2
_MG_9884-1.xmp

I thought it’s time for groovyConsole :-)
Solution was incredibly simple and intuitive:

new File("D:/Entertainment/photos/2010/20100814")
    .eachFileMatch(~/(.*?)-1\.(CR2|xmp)/){ file ->
        println file.name
        file.delete();
    }

Automatically focus swf in browser on start

Recently I finished site for my friend who set up the band called “nebo“. The aim was to make clean and simple design with one extra feature – browsing their first album “Chwala i czesc” in 3d environment (3d cover). It’s easy to rotate and resize album by using keyboard and mouse scroll. After some attempts and googling, finally I achieve the goal – swf file is focused in browser by javascript in the beginning.

How to gain focus on swf file in any browser on load ?

In your html file put code:

var randomnumber=Math.floor(Math.random()*10000);
var attributes = { id:'frame', name:'frame' };
function  setupSWFObjectFocus()	{
    var swf = document.getElementById("frame");
    swf.focus();
}
swfobject.embedSWF("nebo.swf?"+randomnumber,
                              'frame',
                              '100%',
                              '100%',
                              '10.0.0',
                              'assets/swfobject/expressinstall.swf',
                              {},
                              {   bgcolor: '#000000',
                                   menu: 'false',
                                   allowFullScreen: '},
                              attributes,
                              {},
                              setupSWFObjectFocus
);

In flash file invoke method setupSWFObjectFocus from javascript by using:

import flash.external.ExternalInterface;
...
ExternalInterface.call("setupSWFObjectFocus");

And that’s all.
It’s important to note, that above solution doesn’t require you to use wmode:opaque. You can simply use default value for wmode. My experience is that default (wmode:window) value provides better perfomance than opaque one.


Latex – tip for disabling *sections in table of contents

I’ve just found solution for disabling ‘subsection’ or ‘subsubsection’ from table of contents in latex.
What’s important that solution doesn’t affect ‘*section’ number in text.

To disable subsubsections in TOC write:

  \tableofcontents
  \addtocontents{toc}{\protect\setcounter{tocdepth}{2}}

To disable subsections in TOC write:

  \tableofcontents
  \addtocontents{toc}{\protect\setcounter{tocdepth}{1}}

Source


Unix – count files in directory

I need to count files in directory on server. Quite obvious:
ls -1 | wc -l


Groovy – strip html tags in string

Input:

"<html>Welcome!</html>".replaceAll("<(.|\n)*?>", '');

Output:

Welcome!"

Automatically copy data from one object to another in as3

Before I write some important function for my project always try to find solution on internet – there are a lot of smart guys out there. It’s quite reasonable – probably many people do the same. Today I found something very useful -> function to copy objects. For instance you have class Person:

package
{
	public class Person{
		public var name:String;
		public var age:int;
		public var tall:Number;
	}
}

You create instance of class Person:

var jack:Person = new Person();
jack.name = "Jack";
jack.age = 34;
jack.tall = 177.2;

Finally you would like to duplicate that object. You can do it like this:

var duplicationOfJack:Person = new Person();
duplicationOfJack.name = jack.name;
duplicationOfJack.age = jack.age;
duplicationOfJack.tall = jack.tall;

or like this:

var duplicationOfJack:Person = new Person();
copyData(jack, duplicationOfJack);

Function copyData was publicated here:
http://blog.another-d-mention.ro/programming/how-to-clone-duplicate-an-object-in-actionscript-3/

Thank you! It’s really useful.


Calculate average and standard deviation in Scala

I needed to have class that will help me to calculate average and standard deviation of some numbers. Something which should work like this:

val c = new Calculator();
for(i <- 1 to 10) c.add(i);
c.avg;
c.stdDev;

Wrote simple class Calculator.scala and it returns:

scala> res1: String = Calculator -> 1.0 2.0 3.0 4.0 5.0 6.0
scala> res2: Double = 3.5
scala> res3: Double = 1.8708286933869707

Source could be found here:

import collection.mutable.ArrayBuffer

class Calculator(){
  val numbers = new ArrayBuffer[Double]();
  def add(number:Double):Unit = {
    numbers += number;
  }
  def avg():Double = {
      var sum:Double = 0.0;
      for(x:Double <- numbers){
        sum = sum + x;
      }
      sum/numbers.length;
  }
   // Thanks to Christopher Martin
  def avg_short:Double = numbers.reduceLeft(_ + _) / numbers.length

  def stdDev():Double = {
      var sum:Double    = 0.0;
      if(numbers.length>=2){
        val mean = avg();
        val factor:Double = 1.0/(numbers.length.toDouble-1);
        for(x:Double <- numbers){
          sum = sum + ((x-mean)*(x-mean));
        }
        sum = sum * factor;
      }
      return Math.sqrt(sum);
  }
  def print():String = {
    var result:String = "";
    result = result + "Calculator -> ";
    for(x <- numbers) result = result + x +" ";
    return result;
  }
  def reset():Unit = {
    numbers.clear();
  }
}

Scala – retrieve data from XML

I started learning Scala 2 months ago, because Groovy’s performance was too low for my purpose -> modelling epidemies on cellular automata.
Appeared a need to throw variables – important for epidemy simulation – to external file.
Scala provides simple interface to use XML data.
Below you can find examples how to retrieve data from XML.
It’s very convenient to work with Scala through console:

scala> x
res5: scala.xml.Elem = 

       0.01
       0.4
       0.5
       
            0.7
       

Get “init” node in 2 ways:

scala> x \\ "init"
res15: scala.xml.NodeSeq = 0.01

scala> x \ "init"
res16: scala.xml.NodeSeq = 0.01

Get “individual” node in 2 ways:

scala> x \\ "individual"
res17: scala.xml.NodeSeq = 0.7

scala> x \ "die" \ "individual"
res23: scala.xml.NodeSeq = 0.7

Conclusion:

  • “\” is used to search through first level of node’s children
  • “\\” is used to search through every level od node’s children.

Get “init” value :

scala> (x \ "init").text
res19: String = 0.01

scala> (x \ "init").text.toDouble
res20: Double = 0.01

Get “individual” value:

scala> (x \ "die" \ "individual").text
res22: String = 0.7

Similarly you can get attribute:

scala> x \ "recover" \ "@tip"
res28: scala.xml.NodeSeq = const|individual

scala> (x \ "recover" \ "@tip").text
res29: String = const|individual

If you would like to react on specific value in attribute use:

scala> (x \ "recover" \ "@src").text match{
                                            case "const" => true;
                                            case "individual" => false;
                                            case _ => false;
                                        }
res31: Boolean = true

Scala – save file to disk

var path:String = new File("./").getCanonicalPath+"/"
var file:String = path+"fileName.txt"
val writer = new PrintWriter( BufferedWriter(new FileWriter(file,false)));
writer.print(temp+" ")
writer.println("")
writer.close()