Posts tagged actionscript

Get hours, minutes and seconds from a number without maths operations

Today I’m gonna show you a secret ninja technique to extract hours, minutes and seconds from a number (representing an amount of seconds). In my example I will show an Actionscript code, but this can be implemented in JavaScript and maybe other languages too.
So, the scenario is the following: we have a number representing seconds and we want to know how many hours this amount of seconds contains, how many minutes and how many remaining seconds. We know that a minute is composed by 60 seconds and an hour by 60 minutes and we could write a series of maths operations in order to accomplish our objective, but there is a way far simple and fast: use the Date class!
Date class already implements all the methods we need:

  • getHours()
  • getMinutes()
  • getSeconds()

So, in order to take advantage of these useful methods, all we have to do is initialize a “fake” date using the amount of seconds we want to “split” into hours, minutes and seconds. The Date class has several OPTIONAL arguments that can be specified during its initializations, these are:

  • year
  • month
  • date (day number)
  • hours
  • minutes
  • seconds
  • milliseconds

Because theme all are optional, we can create a date object by specifying only the know arguments (in our case seconds) and by assigning null or zero to the others:

1
var date:Date = new Date(null, null, null, 0, 0, 9137);

Then by calling getHours, getMinutes and getSeconds we will obtain what we expect:

1
2
3
trace("hours: ", date.getHours()); // 2 hours
trace("minutes: ", date.getMinutes()); // 32 minutes
trace("seconds: ", date.getSeconds()); // 17 seconds

Not sure about the result? Let’s test it:

60 * 60 * 2 = 7200; (seconds contained in 2 hours)
32 * 60 = 1920; (seconds contained in 32 minutes)
7200 + 1920 + 17 = 9137; (original seconds!)

AIR applications logging… my own extension to Flex’s logging framework

Finally it’s time to release my little project and my first personal and public Actionscript library.
What I’m talking about? I realized a little “subframework” which goal is to extend Flex’s logging framework, in order to write log messages to files on the disk and provide a custom Flex’s UI component (which can be easy used into every AIR application) to read/filtering these log files.

Learn more here: http://www.daveoncode.com/air-logging-framework

Just a note: although I tested the library (windows and mac) and it works fine, this project may contains bugs or doesn’t work under some circumstances. Comments and feedback are welcome!

Deploy and work with Flex swc library

When we need to use a series of Actionscript classes in several projects and centralize them into a single place, the best option available is to deploy our classes as an SWC library and then add it to the “library path” under Flex Builder’s “build path” panel.

Read the rest of this entry »

ArrayCollection: filterFuntion with multiple filter functions using decorator pattern

I was looking for an elegant solution to implement multiple filter functions on an ArrayCollection (which provides a method filterFunction() that can be assigned dynamically in order to filter data inside the collection). The first and only valid solution I found was that one from Cristian Rotundu, he has extended ArrayCollection class providing a filterFunctions properties which accepts an Array of functions which will be executed in sequence (into a loop) once filterFunction is triggered. Anyway I didn’t want to subclass ArrayCollection and by using the decorator pattern I implemented my own multiple filters version.

So, this is what I done:

  1. I defined an interface IFilter, which declares only one method: apply()
  2. I defined a dummy Filter class (which implements IFilter in a basic way just to agree to the interface), that is used as a basic empty filter to decorate. It also has a constant called ALL_VALUES which is used as a wildcard for filters (it’s a simple string with value “*”, which means “all values are allowed”)
  3. I defined an abstract AbstractFilterDecorator class
  4. I created as many subclass of AbstractFilterDecorator as the filters I need (yes I treat filters as classes not mere functions)

The implementation code is the following:

1
2
3
4
5
6
7
8
9
var data:ArrayCollection = ArrayCollection(grid.dataProvider);
var filter:IFilter = new Filter();
               
filter = new LevelFilter(filter, levelValue);
filter = new CategoryFilter(filter, categoryValue);
filter = new DateFilter(filter, dateValue, "DD/MM/YY");
               
data.filterFunction = filter.apply;
data.refresh();

The filter object is wrapped by decorators which all accepts 2 common arguments: an IFilter reference and an Object representing a value. The DateFilter has a third parameter which is used to configure an internal DateFormatter (from mx.formatters package).
I’m pretty satisfied :)
Uh… and if you are worried about performance, it is fast enough because filter object are created once and then the function assigned to filterFunction is a reference to the resulting decorated filter.

UPDATE:
I realized a very simple example application which can be downloaded here.
This following is the content of the mxml file:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:Script>
        <![CDATA[
       
            import mx.collections.ArrayCollection;
            import com.daveoncode.filters.*;
           
            private function applyFilters():void {
               
                var data:ArrayCollection  = ArrayCollection(userGrid.dataProvider);
                var filter:IFilter = new Filter();
               
                filter = new AgeFilter(filter, ageFilterValue.text);
                filter = new DateFilter(filter, dateFilterValue.selectedDate);
                filter = new SexFilter(filter, sexFilterValue.value);
               
                data.filterFunction = filter.apply;
                data.refresh();
               
            }
           
        ]]>
    </mx:Script>
   
    <mx:Panel title="Filters" width="600">
        <mx:Form>
            <mx:FormItem label="Age:">
                <mx:TextInput id="ageFilterValue" width="30" />
            </mx:FormItem>
            <mx:FormItem label="Sex:">
                <mx:ComboBox id="sexFilterValue" dataProvider="{[{data: Filter.ALL_VALUES, label: 'ALL'}, {data: 'm', label: 'Male'}, {data: 'f', label: 'Female'}]}" />
            </mx:FormItem>
            <mx:FormItem label="Join date:">
                <mx:DateField id="dateFilterValue" formatString="DD/MM/YY" />
            </mx:FormItem>
            <mx:FormItem>
                <mx:Button label="Apply filters" click="{this.applyFilters()}" />
            </mx:FormItem>
        </mx:Form>
    </mx:Panel>
   
    <mx:Panel title="Users" width="600">
        <mx:DataGrid id="userGrid" width="100%">
            <mx:dataProvider>
                <mx:ArrayCollection>
                    <mx:Array>
                        <mx:Object age="24" sex="f" name="Susan" joinDate="{new Date(2007, 5, 15)}" />
                        <mx:Object age="36" sex="f" name="Ashley" joinDate="{new Date(1998, 7, 20)}" />
                        <mx:Object age="24" sex="f" name="Jennifer" joinDate="{new Date(2001, 3, 24)}" />
                        <mx:Object age="19" sex="f" name="Emma" joinDate="{new Date(2002, 3, 24)}" />
                        <mx:Object age="44" sex="f" name="Carol" joinDate="{new Date(1999, 9, 16)}" />
                        <mx:Object age="28" sex="m" name="Peter" joinDate="{new Date(2005, 3, 12)}" />
                        <mx:Object age="35" sex="m" name="Mike" joinDate="{new Date(2008, 10, 10)}" />
                        <mx:Object age="26" sex="m" name="Dave" joinDate="{new Date(2008, 10, 10)}" />
                        <mx:Object age="44" sex="m" name="William" joinDate="{new Date(2004, 9, 16)}" />
                        <mx:Object age="24" sex="m" name="Sean" joinDate="{new Date(2006, 3, 24)}" />
                    </mx:Array>
                </mx:ArrayCollection>
            </mx:dataProvider>
        </mx:DataGrid>
    </mx:Panel>
   
</mx:Application>

Learning design patterns with Actionscript 3: episode 2 – Decorator pattern

The objective of the decorator pattern is to provide a way to add extra features and responsibilities to a class at runtime without to subclass it.

The classes diagram of this pattern is composed by an interface or an abstract class which will define the supertype of the class that will be extended (decorated) by one or more classes implementing the same interface and extending an abstract class which identify these as decorator classes.

Read the rest of this entry »

Set DataGridColumn’s width in percentage with ease

I was trying to set the columns of a DataGrid to a certain percentage, but I discovered that inexplicably DataGridColumn doesn’t provide percentageWidth property nor it accepts a percentage string as width property… so I did a quick search on google and I found that is sad but true and moreover the solution I found on the web is to use a function to calculate each single column width after creationComplete event is dispatched… terrible! However I did a test before, by assign a decimal value to width (0.5 instead of 50%) and it works! The width property in fact accepts a Number as value not an int, so we can specify a value under 1, which is treated as a percentage… what surprise me, is that no one seems to had this idea… anyway I hope this will be helpful for all.

This is a piece of my AS code to set DataGridColumn width in percentage:

1
2
col = new DataGridColumn();
col.width = options[i] == "Message" ? 0.6 : 0.1;

In my code I’m setting the columns to 10% and to 60% only for “Message” column.

parseInt(): difference between Javascript and Actionscript

Today is the day of the little big discoveries. I realized that the parseInt() function, which objective is the same in both languages (Actionscript and Javascript), is a bit different between them. In Actionscript the function is based on base 10 numeration, in Javascript instead the funny thing is that it try to guess the radix by analyzing the string received as first argument, so if you want to be sure of the result returned you have to explicitly pass the radix in the second argument.

Example:

var myString = "000123";
alert(parseInt(myString));

The code above will alert 83 instead of 123 (because the default base guessed by Javascript isn’t 10 like in Actionscript), to get 123 the code must be:

var myString = "000123";
alert(parseInt(myString, 10));

Extending Flex’s logging framework to write custom log files

In these days I played with Flex’s logging framework and I extended it to write log messages to files, both plain text .log files and dynamic HTML, CSS formatted and Javascript powered files with the ability to filter message type (debug, error, fatal and so on).

The logging framework is a powerful feature that comes with Flex’s sdk and it’s composed by the classes under mx.logging package, which includes the two “subpackages” mx.logging.errors and mx.logging.target.

Java developers should be already confident whit such framework, because logging api are commonly used in Java programming,  Actionscript /Flash/Flex developers may find this tool a novelty (as I did).

The objective of logging framework is to provide a tool that offers a far better, flexible and centralized way to debug an application than simple use a lot of trace() callings. With Flex’s debugging framework we are able to print and filtering among different types of message based on their severity, such:

  • DEBUG
  • ERROR
  • FATAL
  • INFO
  • WARN

We can also print the timestamp of the message and the class it refers to, and finally we can simultaneously print messages to different targets.

Read the rest of this entry »

Converting Java to Actionscript… maybe is not so hard (I hope)

After valuate my own realization of a certain library, I opted to try the porting of an already existent one… which is made in Java. This library has a lot of classes and interfaces and the manually translation would be very time-expensive, considering also that it uses a lot of classes and functions which are unavailable in Actionscript 3. Fortunately I found a small and useful AIR application which automatically converts .java files to .as files (the application is here: http://thunderhead.esri.com/readonlyurl/J2AS3.air), this application anyway helps a lot but many extra-work is required to properly convert the classes… for example Actionscript has not the abstract key, variable can’t be market as final and so on, so we have to manually adjust these issues. Another useful stuff I found is an Actionscript library which aim is to provide to AS3 developers the same (more or less) features and power of Java Collection framework, which provide classes like HashMap, ArrayList, LinkedList and so on (the library can be found here: http://code.google.com/p/addicted2flash/). Despite these helps I’m still facing some incompatibility issues… classes/methods AS3 is missing, but implementing them by myself is quite simple. For example I implemented the Java’s System.arraycopy() in 2 minutes, by following the JavaDoc ).

In conclusion Actionscript and Java have a  lot of stuff in common, the syntax and structure is quite the same, except for some issues like abstract classes and methods, multiple methods and constructors declaration (override). The main difference is that Java provides an huge number of Classes that Actionscript doesn’t, however it seems not so hard to translate Java code and implement Java functionality in Actionscript.

I hope I won’t have to deny my words :)

Using bitwise operators with Actionscript to create arguments flags

Among all books I bought (including Java books), I haven’t one which explain in depth and in a clear manner what bitwise operators are and how to use them. Almost all books has at least a page about the argument but none is able to give an exhaustive explanation. So, after searching the net, I found an extreme useful article by Joseph Farrell on gamedev.net (direct link: http://www.gamedev.net/reference/articles/article1563.asp), which explains bitwise operators in C starting from an introduction to Numbers and number system. The article is valid to Actionscript, Java and other languages too. I started to try to understand bitwise operators, after looked to Flex’s Alert class, which can accept several options (different buttons) as an unique argument (flags). This can be accomplished by using the bitwise OR operator |  (a pipe), which “joins” together different constants:

Read the rest of this entry »