repo
string
commit
string
message
string
diff
string
as3/as3-utils
ff4acfb3e8dd6f533ad85a008479fa04c0ec0382
changed gitignore to ignore more eclipse files
diff --git a/.gitignore b/.gitignore index 0bce7cd..379fde3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,11 @@ target bin bin-debug bin-release *.iml .actionScriptProperties .flexLibProperties .project .settings/ -.DS_Store \ No newline at end of file +.DS_Store +org.eclipse.core.resources.prefs \ No newline at end of file
as3/as3-utils
2e4d8be719a816db06cd9510d9dc1d84fa1ac769
comments did not pass asdoc, changed <= to less or equal so it will not misinterpate a tag
diff --git a/src/utils/align/interpolateMultiX.as b/src/utils/align/interpolateMultiX.as index a4ef4a8..5efff40 100644 --- a/src/utils/align/interpolateMultiX.as +++ b/src/utils/align/interpolateMultiX.as @@ -1,19 +1,19 @@ package utils.align { /** - * interpolate multiple DisplayObjects at multiple weights at t == (0 <= t <= 1). at tx=1, the position of the object would be aligned to the right-most bounds, and tx=0 would position to the left + * interpolate multiple DisplayObjects at multiple weights at t == (0 less or equal t less or equal 1). at tx=1, the position of the object would be aligned to the right-most bounds, and tx=0 would position to the left * * @param DisplayObject DisplayObject to position * @param positionArray weight array of horizontal position from 0 to 1 * @param width width of horizontal constraint * @offsetX the left offset of the horizontal constraint (default = 0) */ public function interpolateMultiX(objectArray:Array, positionArray:Array, width:Number, offsetX:int = 0):void { var j:int = objectArray.length; for (var i:int = 0; i < j; i++) { interpolateX(objectArray[i], positionArray[i], width, offsetX); } } } \ No newline at end of file diff --git a/src/utils/align/interpolateMultiY.as b/src/utils/align/interpolateMultiY.as index da1b6ec..e0a7ed3 100644 --- a/src/utils/align/interpolateMultiY.as +++ b/src/utils/align/interpolateMultiY.as @@ -1,19 +1,19 @@ package utils.align { /** - * interpolate multiple DisplayObjects at multiple weights at t == (0 <= t <= 1). at tx=1, the position of the object would be aligned to the right-most bounds, and ty=0 would position to the left + * interpolate multiple DisplayObjects at multiple weights at t == (0 less or equal t less or equal 1). at tx=1, the position of the object would be aligned to the right-most bounds, and ty=0 would position to the left * * @param DisplayObject DisplayObject to position * @param positionArray weight array of vertical position from 0 to 1 * @param height width of horizontal constraint * @param offsetY the left offset of the horizontal constraint (default = 0) */ public function interpolateMultiY(objectArray:Array, positionArray:Array, height:Number, offsetY:int = 0):void { var j:int = objectArray.length; for (var i:int = 0; i < j; i++) { interpolateX(objectArray[i], positionArray[i], height, offsetY); } } } \ No newline at end of file diff --git a/src/utils/align/interpolateY.as b/src/utils/align/interpolateY.as index 5f81880..9d8ef51 100644 --- a/src/utils/align/interpolateY.as +++ b/src/utils/align/interpolateY.as @@ -1,17 +1,17 @@ package utils.align { import flash.display.DisplayObject; /** - * interpolate the DisplayObject at weight t == (0 <= t <= 1). a position 1 would position the object to the right-most bounds, and tx=0 would position to the left + * interpolate the DisplayObject at weight t == (0 less or equal t less or equal 1). a position 1 would position the object to the right-most bounds, and tx=0 would position to the left * * @param DisplayObject DisplayObject to position * @param ty weight of verticle position from 0 to 1 * @param height height of the verticle constraint * @offsetY the left offset of the horizontal constraint (default = 0) */ public function interpolateY(object:DisplayObject, ty:Number, height:Number, offsetY:int = 0):void { object.y = (height * ty) + offsetY - (ty * object.height); } } \ No newline at end of file
as3/as3-utils
1e590d8d72f0e1354189332ae1c8dab57318da36
Adding the "Calendar" concept, showChildren, and various date utils
diff --git a/src/utils/date/Calendar.as b/src/utils/date/Calendar.as new file mode 100644 index 0000000..ce4b027 --- /dev/null +++ b/src/utils/date/Calendar.as @@ -0,0 +1,23 @@ +/** + * User: John Lindquist + * Date: 3/16/11 + * Time: 11:27 AM + */ +package utils.date +{ + /** + * Calendar is an exception to the "package-level function" rule + * + * This class provides common dates (today, yesterday, tomorrow, last Sunday, next Thursday, the first of the year, the first of June, etc) + * all based on "now" + * + * To determine whether or not a date belongs in "Calendar", simply ask yourself, "Is this date based on 'now'?" + * + * These properties will leverage many of the package-level functions such as "getNextDay", etc, but will simply be based on "now" + */ + public class Calendar + { + public var now:Date = new Date(); + public var today:Date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0); + } +} \ No newline at end of file diff --git a/src/utils/date/Timezone.as b/src/utils/date/Timezone.as new file mode 100644 index 0000000..ad0a6d6 --- /dev/null +++ b/src/utils/date/Timezone.as @@ -0,0 +1,92 @@ +package utils.date +{ + /* + * Need to discuss how to refactor timezone logic into better utils + * + * This class currently only works with USA (the offsets default to EAST if the timezone is outside of the USA. + * + * */ + public class Timezone + { + public static const EAST:String = "ET"; + public static const WEST:String = "WT"; + public static const ARIZONA:String = "AZ"; + public static const MOUNTAIN:String = "MT"; + public static const CENTRAL:String = "CT"; + public static const PACIFIC:String = "PT"; + public static const ALASKA:String = "AK"; + public static const HAWAII:String = "HT"; + + private static var nonDstOffsetDate:Date = new Date(2010, 1, 1); + private static var dstOffsetDate:Date = new Date(2010, 7, 1); + private static var observesDST:Boolean = (nonDstOffsetDate.timezoneOffset != dstOffsetDate.timezoneOffset); + private static var timezone:String = EAST; + + + public static function get zuluOffset():String + { + var offset:Number = nonDstOffsetDate.timezoneOffset / 60; + + if(offset > 11 || offset <= 5) + { + offset = 4; //defaulting to east coast + return String(offset); + } + + return String(new Date().timezoneOffset / 60); + } + + public static function get dstOffset():String + { + var offset:Number = dstOffsetDate.timezoneOffset / 60; + + if(offset > 10 || offset <= 4) + { + offset = 4; //defaulting to east coast + } + + return String(offset); + } + + public static function get nonDstOffset():String + { + var offset:Number = nonDstOffsetDate.timezoneOffset / 60; + + if(offset > 11 || offset <= 5) + { + offset = 5; //defaulting to east coast + } + return String(offset); + } + + public static function get name():String + { + //Default to Eastern + switch (nonDstOffset) + { + case "10": + timezone = HAWAII; //Hawaii + break; + + case "9": + timezone = ALASKA; //Alaska + break; + + case "8": + timezone = PACIFIC;//Pacific + break; + + case "7": + timezone = MOUNTAIN;//Mountain + if(!observesDST) timezone = ARIZONA; + break; + + case "6": + timezone = CENTRAL;//Central + break; + } + + return timezone; + } + } +} diff --git a/src/utils/date/addWeeks.as b/src/utils/date/addWeeks.as new file mode 100644 index 0000000..82f7211 --- /dev/null +++ b/src/utils/date/addWeeks.as @@ -0,0 +1,8 @@ +package utils.date +{ + public function addWeeks(date:Date, weeks:uint):Date + { + date.date += weeks * 7; + return date; + } +} \ No newline at end of file diff --git a/src/utils/date/clone.as b/src/utils/date/clone.as new file mode 100644 index 0000000..4edd9d0 --- /dev/null +++ b/src/utils/date/clone.as @@ -0,0 +1,7 @@ +package utils.date +{ + public function clone(date:Date):Date + { + return new Date(date.fullYear, date.month, date.date, date.hours, date.minutes, date.seconds, date.milliseconds); + } +} \ No newline at end of file diff --git a/src/utils/date/formatWeekOf.as b/src/utils/date/formatWeekOf.as new file mode 100644 index 0000000..5514395 --- /dev/null +++ b/src/utils/date/formatWeekOf.as @@ -0,0 +1,12 @@ +package utils.date +{ + public function formatWeekOf(date:Date):String + { + date = getLastSunday(date); + + var string:String = ""; + string = "Week of " + String(date.getUTCMonth() + 1) + "/" + String(date.getUTCDate()); + + return string; + } +} \ No newline at end of file diff --git a/src/utils/date/getLastMonday.as b/src/utils/date/getLastMonday.as new file mode 100644 index 0000000..56293bc --- /dev/null +++ b/src/utils/date/getLastMonday.as @@ -0,0 +1,9 @@ +package utils.date +{ + public function getLastMonday(date:Date):Date + { + date.date -= (date.day - 1); + + return date; + } +} \ No newline at end of file diff --git a/src/utils/date/getLastSunday.as b/src/utils/date/getLastSunday.as new file mode 100644 index 0000000..75e5766 --- /dev/null +++ b/src/utils/date/getLastSunday.as @@ -0,0 +1,11 @@ +package utils.date +{ + public function getLastSunday(date:Date):Date + { + var temp:Date = clone(date); + + temp.date -= temp.day; + + return temp; + } +} \ No newline at end of file diff --git a/src/utils/date/getStartOfWeek.as b/src/utils/date/getStartOfWeek.as new file mode 100644 index 0000000..2436340 --- /dev/null +++ b/src/utils/date/getStartOfWeek.as @@ -0,0 +1,12 @@ +package utils.date +{ + public function getStartOfWeek(date:Date):Date + { + var temp:Date = clone(date); + + temp.date -= temp.day; + temp = makeMorning(temp); + + return temp; + } +} \ No newline at end of file diff --git a/src/utils/date/isInCurrentWeek.as b/src/utils/date/isInCurrentWeek.as new file mode 100644 index 0000000..301c9f0 --- /dev/null +++ b/src/utils/date/isInCurrentWeek.as @@ -0,0 +1,15 @@ +package utils.date +{ + public function isInCurrentWeek(date:Date):Boolean + { + var today:Date = new Date(); + var startOfWeek:Date = getStartOfWeek(today); + + var millisecondsDifference:Number = getTimeBetween(startOfWeek, date); + + var b:Boolean; + b = millisecondsDifference < TimeRelationships.WEEK_IN_MILLISECONDS; + b &&= millisecondsDifference >= 0; + return b; + } +} \ No newline at end of file diff --git a/src/utils/display/showChildren.as b/src/utils/display/showChildren.as new file mode 100644 index 0000000..0d24a23 --- /dev/null +++ b/src/utils/display/showChildren.as @@ -0,0 +1,32 @@ +/** + * Created by ${PRODUCT_NAME}. + * User: jlindqui + * Date: 3/9/11 + * Time: 10:21 AM + * To change this template use File | Settings | File Templates. + */ +package utils.display +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + + /** + * + * @param displayObjectContainer - the DisplayObjectContainer that you want to see all the children of + * This is useful for visual debugging of hidden objects. + */ + public function showChildren(displayObjectContainer:DisplayObjectContainer):void + { + var i:int = 0; + while (i < displayObjectContainer.numChildren) + { + var childAt:DisplayObject = displayObjectContainer.getChildAt(i); + childAt.visible = true; + if (childAt is DisplayObjectContainer) + { + showChildren(DisplayObjectContainer(childAt)); + } + i++; + } + } +}
as3/as3-utils
b97b3721a2c393d5961032db7fea4251843cc14e
Removed svn folder. Added url to comments for mvc files.
diff --git a/src/utils/mvc/.svn/all-wcprops b/src/utils/mvc/.svn/all-wcprops deleted file mode 100644 index 746b30b..0000000 --- a/src/utils/mvc/.svn/all-wcprops +++ /dev/null @@ -1,35 +0,0 @@ -K 25 -svn:wc:ra_dav:version-url -V 41 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc -END -AbstractView.as -K 25 -svn:wc:ra_dav:version-url -V 57 -/svn/!svn/ver/46/trunk/src/org/as3lib/mvc/AbstractView.as -END -IView.as -K 25 -svn:wc:ra_dav:version-url -V 50 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IView.as -END -AbstractController.as -K 25 -svn:wc:ra_dav:version-url -V 63 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/AbstractController.as -END -IModel.as -K 25 -svn:wc:ra_dav:version-url -V 51 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IModel.as -END -IController.as -K 25 -svn:wc:ra_dav:version-url -V 56 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IController.as -END diff --git a/src/utils/mvc/.svn/entries b/src/utils/mvc/.svn/entries deleted file mode 100644 index aa3346f..0000000 --- a/src/utils/mvc/.svn/entries +++ /dev/null @@ -1,198 +0,0 @@ -10 - -dir -43 -https://as3lib.googlecode.com/svn/trunk/src/org/as3lib/mvc -https://as3lib.googlecode.com/svn - - - -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - -5ef08cf5-1340-0410-b16c-d3bedfb892dd - -AbstractView.as -file -46 - - - -2011-03-04T19:39:24.000000Z -57c08efb41591e7db519ca10bb33a06d -2011-03-05T16:00:45.645054Z -46 -mimshwright - - - - - - - - - - - - - - - - - - - - - -1290 - -IView.as -file - - - - -2010-04-11T18:14:50.000000Z -2e9423d189bd0dac685cb47fb0c92354 -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -524 - -AbstractController.as -file - - - - -2010-04-11T18:15:18.000000Z -75a2202fe3f66373be757b68d7cb6360 -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -713 - -IModel.as -file - - - - -2010-04-11T18:15:58.000000Z -41685c0f0e474fbb7c240534309c795a -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -121 - -IController.as -file - - - - -2010-04-11T18:14:58.000000Z -fad2a92e5a939e0ea95be08e496d211e -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -601 - diff --git a/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base deleted file mode 100644 index 7b61305..0000000 --- a/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base +++ /dev/null @@ -1,30 +0,0 @@ -package org.as3lib.mvc -{ - /** - * Provides basic services for the "controller" of - * a Model/View/Controller triad. - * - * Based on original AS2 code by Colin Moock - */ - public class AbstractController implements IController - { - /** - * Constructor - * - * @param model The model this controller's view is observing. - */ - public function AbstractController( model : * ) - { - this.model = model; - } - - public function get model():* { return _model; } - public function set model(model:*):void { _model = model; } - protected var _model:*; - - - public function get view():IView { return _view; } - public function set view(view:IView):void { _view = view; } - protected var _view:IView; - } -} diff --git a/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base deleted file mode 100644 index ef26bde..0000000 --- a/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base +++ /dev/null @@ -1,48 +0,0 @@ -package org.as3lib.mvc -{ - import flash.display.DisplayObject; - import flash.display.MovieClip; - - import abstractAS3.AbstractEnforcer; - - public class AbstractView extends MovieClip implements IView - { - public function AbstractView ( model:*, controller:IController = null) { - super(); - this.model = model; - - if (controller != null) { - this.controller = controller; - } - } - - public function asDisplayObject():DisplayObject { - return this; - } - - public function get model():* { return _model; } - public function set model(model:*):void { _model = model; } - protected var _model:*; - - public function get controller():IController { - // If a controller hasn't been defined yet... - if (_controller == null) { - // ...make one. Note that defaultController() is normally overridden - // by the AbstractView subclass so that it returns the appropriate - // controller for the view. - this.controller = getDefaultController( model ); - } - return controller; - } - public function set controller(controller:IController):void { - _controller = controller; - controller.view = this; - } - protected var _controller:IController; - - public function getDefaultController( model:* ):IController { - AbstractEnforcer.enforceMethod(); - return null; - } - } -} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IController.as.svn-base b/src/utils/mvc/.svn/text-base/IController.as.svn-base deleted file mode 100644 index b115880..0000000 --- a/src/utils/mvc/.svn/text-base/IController.as.svn-base +++ /dev/null @@ -1,33 +0,0 @@ -package org.as3lib.mvc -{ - - - /** - * Specifies the minimum services that the "controller" of - * a Model/View/Controller triad must provide. - * - * Modified from original AS2 code by Colin Moock - */ - public interface IController - { - /** - * Sets the model for this controller. - */ - function set model (model:*):void; - - /** - * Returns the model for this controller. - */ - function get model ():*; - - /** - * Sets the view this controller is servicing. - */ - function set view (view:IView):void; - - /** - * Returns this controller's view. - */ - function get view ():IView; - } -} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IModel.as.svn-base b/src/utils/mvc/.svn/text-base/IModel.as.svn-base deleted file mode 100644 index f8b7d80..0000000 --- a/src/utils/mvc/.svn/text-base/IModel.as.svn-base +++ /dev/null @@ -1,11 +0,0 @@ -package org.as3lib.mvc -{ - - /** - * Purely a marker interface for model classes. - */ - public interface IModel - { - - } -} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IView.as.svn-base b/src/utils/mvc/.svn/text-base/IView.as.svn-base deleted file mode 100644 index 5736ec6..0000000 --- a/src/utils/mvc/.svn/text-base/IView.as.svn-base +++ /dev/null @@ -1,22 +0,0 @@ -package org.as3lib.mvc -{ - import org.as3lib.display.IDisplayObject; - - - /** - * Specifies the minimum services that the "view" - * of a Model/View/Controller triad must provide. - * - * Modified from original AS2 code by Colin Moock - */ - public interface IView extends IDisplayObject - { - function set model ( model:* ):void; - function get model ():*; - - function set controller ( controller:IController ):void; - function get controller ():IController; - - function getDefaultController ( model:* ):IController; - } -} \ No newline at end of file diff --git a/src/utils/mvc/AbstractController.as b/src/utils/mvc/AbstractController.as index 44a77c6..3b2ecf4 100644 --- a/src/utils/mvc/AbstractController.as +++ b/src/utils/mvc/AbstractController.as @@ -1,30 +1,30 @@ package utils.mvc { /** * Provides basic implementation of the "controller" of * a Model/View/Controller triad. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public class AbstractController implements IController { /** * Constructor * * @param model The model this controller's view is observing. */ public function AbstractController( model : * ) { this.model = model; } public function get model():* { return _model; } public function set model(model:*):void { _model = model; } protected var _model:*; public function get view():IView { return _view; } public function set view(view:IView):void { _view = view; } protected var _view:IView; } } diff --git a/src/utils/mvc/AbstractView.as b/src/utils/mvc/AbstractView.as index 6ebda0a..3b597c8 100644 --- a/src/utils/mvc/AbstractView.as +++ b/src/utils/mvc/AbstractView.as @@ -1,65 +1,65 @@ package utils.mvc { import flash.display.DisplayObject; import flash.display.MovieClip; /** * A default implementation of IView based on MovieClip. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public class AbstractView extends MovieClip implements IView { /** * Constructor. * * @param model The data model that defines this view. * @param controller A specific controller to use (otherwise, the defaultController will be used) */ public function AbstractView ( model:*, controller:IController = null) { super(); this.model = model; if (controller != null) { this.controller = controller; } } /** @inheritDoc */ public function asDisplayObject():DisplayObject { return this; } /** @inheritDoc */ public function get model():* { return _model; } public function set model(model:*):void { _model = model; } protected var _model:*; /** * The controller for the model that the view will use to modify it. * If it is set to null, the default controller will be used. */ public function get controller():IController { // If a controller hasn't been defined yet... if (_controller == null) { // ...make one. Note that defaultController() is normally overridden // by the AbstractView subclass so that it returns the appropriate // controller for the view. this.controller = getDefaultController( model ); this.controller.view = this; } return controller; } public function set controller(controller:IController):void { _controller = controller; controller.view = this; } protected var _controller:IController; public function getDefaultController( model:* ):IController { // AbstractEnforcer.enforceMethod(); return null; } } } \ No newline at end of file diff --git a/src/utils/mvc/IController.as b/src/utils/mvc/IController.as index 0496ee0..4bd162c 100644 --- a/src/utils/mvc/IController.as +++ b/src/utils/mvc/IController.as @@ -1,33 +1,33 @@ package utils.mvc { /** * Specifies the minimum functionality that the "controller" of * a Model/View/Controller triad must provide. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public interface IController { /** * Sets the model for this controller. */ function set model (model:*):void; /** * Returns the model for this controller. */ function get model ():*; /** * Sets the view this controller is servicing. */ function set view (view:IView):void; /** * Returns this controller's view. */ function get view ():IView; } } \ No newline at end of file diff --git a/src/utils/mvc/IView.as b/src/utils/mvc/IView.as index 626a855..d5da453 100644 --- a/src/utils/mvc/IView.as +++ b/src/utils/mvc/IView.as @@ -1,27 +1,27 @@ package utils.mvc { import utils.display.IDisplayObject; /** * Specifies the minimum functionality that the "view" * of a Model/View/Controller triad must provide. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public interface IView extends IDisplayObject { /** A reference to the model associated with this view. */ function set model ( model:* ):void; function get model ():*; /** A reference to the model's controller. */ function set controller ( controller:IController ):void; function get controller ():IController; /** * Returns an instance to a default implementation of the controller * for the model. */ function getDefaultController ( model:* ):IController; } } \ No newline at end of file
as3/as3-utils
1846a26a5755cac6445ae08c5058ead7f2a640b9
added unapproved code
diff --git a/src/utils/color/Color.as b/src/utils/color/Color.as new file mode 100644 index 0000000..a8d5781 --- /dev/null +++ b/src/utils/color/Color.as @@ -0,0 +1,455 @@ +package utils.color +{ + + import flash.events.Event; + import flash.events.EventDispatcher; + + import utils.number.clamp; + + /** + * A color, based on a 24-bit hex color, that can be manipulated, split into channels, + * and converted into several convenient formats. + * + * This class makes extensive use of bitwise operations. For information on how these work, check out the + * following resources. + * <ul> + * <li><a href="http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math/">Bitwise Gems (Polygonal Labs)</a></li> + * <li><a href="http://www.gamedev.net/reference/articles/article1563.asp">Bitwise Operations in C</a></li> + * <li><a href="http://en.wikipedia.org/wiki/Bitwise_operation">Wikipedia</a></li> + * </ul> + * + * Most of the formulae for converting to and from HSV and HSL color spaces was found in this article. + * <a href="http://en.wikipedia.org/wiki/HSL_and_HSV">Wikipedia - HSL and HSV</a> + * + * @author Mims H. Wright + */ + public class Color extends EventDispatcher + { + [Event(name="colorChanged", type="flash.events.Event")] + public static const COLOR_CHANGED:String = "colorChanged"; + + // Masks and offsets are used for bitwise operations on the color channels. + public static const RED_MASK:uint = 0x00FF0000; + public static const RED_OFFSET:uint = 16; + public static const GREEN_MASK:uint = 0x0000FF00; + public static const GREEN_OFFSET:uint = 8; + public static const BLUE_MASK:uint = 0x000000FF; + public static const BLUE_OFFSET:uint = 0; + + /** Maximum value allowed for a 24-bit color */ + protected static const MAX_COLOR_VALUE:uint = 0xFFFFFF; + /** Maximum value allowed for a single channel */ + protected static const MAX_CHANNEL_VALUE:uint = 0xFF; + /** The step size betwen web color channels */ + protected static const WEB_COLOR_STEP_SIZE:uint = 0x33; + + + /** + * This is the hex value for the Color object in the standard form, 0xrrggbb. + * It is the only true record of the color represented by a Color object. + * All other getters and setters ultimately manipulate this value or are + * derived from it. + */ + [Bindable("colorChanged")] + public function get hex ():uint { return _hex; } + public function set hex (rgb:uint):void { + rgb = clamp(rgb, 0, MAX_COLOR_VALUE); + _hex = rgb; + dispatchEvent(new Event(COLOR_CHANGED)); + } + protected var _hex:uint = 0x000000; + + + /** + * Constructor. + * + * @param value An initial value for the color. + * Note: alpha channel is ignored by the constructor. + * Default is black with full alpha. + */ + public function Color(value:uint = 0x000000) { + this.hex = value; + } + + + + // Individual channel getters and setters + + [Bindable] + /** The hex value for the red channel. */ + public function get red():uint { return (hex & RED_MASK) >>> RED_OFFSET; } + public function set red(red:uint):void { setChannel(red, RED_OFFSET, RED_MASK); } + [Bindable] + /** The percentage value for the red channel. */ + public function get redPercent():Number { return red / MAX_CHANNEL_VALUE } + public function set redPercent(red:Number):void { setChannel(int(red * MAX_CHANNEL_VALUE), RED_OFFSET, RED_MASK); } + + [Bindable] + /** The hex value for the green channel. */ + public function get green():uint { return (hex & GREEN_MASK) >>> GREEN_OFFSET; } + public function set green(green:uint):void { setChannel(green, GREEN_OFFSET, GREEN_MASK); } + [Bindable] + /** The percentage value for the green channel. */ + public function get greenPercent():Number { return green / MAX_CHANNEL_VALUE } + public function set greenPercent(green:Number):void { setChannel(int(green * MAX_CHANNEL_VALUE), GREEN_OFFSET, GREEN_MASK); } + + [Bindable] + /** The hex value for the blue channel. */ + public function get blue():uint { return (hex & BLUE_MASK) >>> BLUE_OFFSET; } + public function set blue(blue:uint):void { setChannel(blue, BLUE_OFFSET, BLUE_MASK); } + [Bindable] + /** The percentage value for the blue channel. */ + public function get bluePercent():Number { return blue / MAX_CHANNEL_VALUE } + public function set bluePercent(blue:Number):void { setChannel(int(blue * MAX_CHANNEL_VALUE), BLUE_OFFSET, BLUE_MASK); } + + + // Channels in the CMYK space. + + /** The percentage for the black value in CMYK. Approximations only. */ + public function get black():Number { return Math.min(1 - redPercent, 1 - greenPercent, 1 - bluePercent); } + + /** The percentage for the cyan value in CMYK. Approximations only. */ + public function get cyan():Number { return (1 - redPercent - black) / (1 - black); } + + /** The percentage for the magnenta value in CMYK. Approximations only. */ + public function get magenta():Number { return (1 - greenPercent - black) / (1 - black); } + + /** The percentage for the yellow value in CMYK. Approximations only. */ + public function get yellow():Number { return (1 - bluePercent - black) / (1 - black); } + + /** + * Converts a value for CMYK to RGB. Each value provided must be in the + * range of 0.0-1.0. + * + * Note: this method is not very accurate and should not be used + * for professional color conversion. + */ + public function setCMYK (c:Number, m:Number, y:Number, k:Number):void { + k = clamp(k, 0, 1); + c = clamp(c, 0, 1) * (1-k) + k; + m = clamp(m, 0, 1) * (1-k) + k; + y = clamp(y, 0, 1) * (1-k) + k; + + red = convertChannel(c); + green = convertChannel(m); + blue = convertChannel(y); + + function convertChannel(channel:Number):Number { + return int((1 - Math.min(1, channel))*255 + 0.5); + } + } + + + /** + * Indicates the color space that HS_ operations will use by default. + * If true, HSV (hue, saturation, value) will be used. + * If false, HSL (hue, saturation, lightness) will be used. + public var useHSV:Boolean = true; + */ + + + /** + * The hue of the color as a value in degrees from 0-360 + */ + public function get hue():Number { + + // nested function to calculate the hue based on the lightest color. + function calculateHue (colorA:uint, colorB:uint, offset:uint):Number { + return (60 * (colorA - colorB) / (lightestChannelValue - darkestChannelValue) + offset) % 360; + } + + if (this.isGrey()) { + return 0; // grey colors don't really have a hue. + } else if (lightestChannelValue == red) { + return calculateHue (green, blue, 0); + } else if (lightestChannelValue == green) { + return calculateHue (blue, red, 120); + } else if (lightestChannelValue == blue) { + return calculateHue (red, green, 240); + } else { + throw new Error("Somehow the brightest channel isn't one of the channels"); + } + } + + public function set hue(hue:Number):void { + setHSV(hue, saturation, value); + } + + + /** The hue as a percentage instead of as a degree */ + public function get huePercent():Number { return hue/360; } + + public function set huePercent(huePercent:Number):void { + hue = huePercent * 360; + } + + + /** The saturation of the color as a percentage. */ + public function get saturation ():Number { + if (lightestChannelValue <= 0) { return 0; } + return uint(lightestChannelValue - darkestChannelValue) / lightestChannelValue; + } + public function set saturation(saturation:Number):void { + setHSV(hue, saturation, value); + } + + /** + * The value of the color in HSV color space. + * range = 0~255 + */ + public function get value ():uint { + return lightestChannelValue; + } + public function set value(value:uint):void { + setHSV(hue, saturation, value); + } + + /** + * The color value as a percentage. + */ + public function get valuePercentage():Number { + return value / MAX_CHANNEL_VALUE; + } + + + /* public function get lightness():Number { + return 0.5 * (lightestChannelValue + darkestChannelValue); + } + public function set lightness(lightness:Number):void { + limit(lightness, 0, 1); + setHSL(hue, saturation, lightness); + } */ + + /** + * Sets the color by providing three values - one for each channel. + */ + public function setRGB(red:uint, green:uint, blue:uint):void { + this.red = red; + this.green = green; + this.blue = blue; + } + + + /** + * Sets the hue, saturation, and lightness of the color. + * + * @param hue The hue in degrees (0~360) + * @param saturation The saturation in percent (0~1) + * @param the lightness in percent (0~1) + public function setHSL(hue:Number, saturation:Number, lightness:Number):void { + + // If saturation is 0, that means the color is grey so just use the lightness value for all channels. + if (saturation == 0) { + red = green = blue = lightness; + return; + } + + // limit parameters to appropriate range. + hue = limit(hue, 0, 360); + saturation = limit(saturation, 0, 1); + lightness = limit(lightness, 0, 1); + + // begin crazy algorithms!!! zOMG!!1 + var q:Number, p:Number, rHue:Number, gHue:Number, bHue:Number; + if (lightness < 0.5) { + q = lightness * (1 + saturation); + } else { + q = lightness + saturation - (lightness * saturation); + } + + p = 2 * lightness - q; + rHue = huePercent + 1/3; + gHue = huePercent; + bHue = huePercent - 1/3; + + if (huePercent < 1/3) { bHue += 1.0; } + if (huePercent > 1/3) { rHue -= 1.0; } + + red = calculateResultForChannel(rHue); + green = calculateResultForChannel(gHue); + blue = calculateResultForChannel(bHue); + + // nested function to figure out results for each channel based on channel hue. + function calculateResultForChannel(channelHue:Number):Number { + if (channelHue < 1/6) { + return p + ((q - p) * 6 * channelHue); + } else if (channelHue < 1/2) { + return q; + } else if (channelHue < 2/3) { + return p + ((q - p) * 6 * (2/3 - channelHue)); + } else { + return p; + } + } + } + */ + + /** + * Sets the hue, saturation, and value of the color. + * + * @param hue The hue in degrees (0~360) + * @param saturation The saturation in percent (0~1) + * @param the value in percent (0~255) + */ + public function setHSV(hue:Number, saturation:Number, value:uint):void { + hue %= 360; + if (hue < 0) hue += 360; + saturation = clamp(saturation, 0, 1); + value = clamp(value, 0, 255); + + var hueRange:Number, i:int, f:Number, p:Number, q:Number, t:Number, v:Number; + + // Begin Crazy algorithms + hueRange = hue / 60; + i = Math.floor(hueRange) % 6; + f = hueRange - Math.floor(hueRange); + p = value * (1 - saturation); + q = value * (1 - f * saturation); + t = value * (1 - (1 - f) * saturation); + v = value; + + switch (i) { + case 0: setRGB(v,t,p); break; + case 1: setRGB(q,v,p); break; + case 2: setRGB(p,v,t); break; + case 3: setRGB(p,q,v); break; + case 4: setRGB(t,p,v); break; + case 5: setRGB(v,p,q); break; + default: throw new Error("Invalid hue while converting HSV to RGB"); + } + } + + + /** + * Returns the <em>value</em> of the lightest color channel (excluding alpha). + * Used internally for hsv and hsl operations. + */ + protected function get lightestChannelValue():uint { + return Math.max(red, Math.max(green, blue)); + } + + /** + * Returns the <em>value</em> of the darkest color channel (excluding alpha). + * Used internally for hsv and hsl operations. + */ + protected function get darkestChannelValue():uint { + return Math.min(red, Math.min(green, blue)); + } + + /** + * Returns true if the color is a shade of grey (including white and black). + * In RGB, colors with the same value for all three channels are grey. + */ + public function isGrey():Boolean { + return (red == green) && (red == blue); + } + + + /** + * Sets the value of a color channel. + * Used by the individual color channel getters and setters. + * + * @param value The new value to set the channel - between 0 and 0xFF + * @param offset The number of places to binary shift the channel value. e.g. 8 for green. + * @param mask The binary mask for the channel + */ + protected function setChannel(value:int, offset:uint, mask:uint):void { + // limit the value between 0 and 0xFF + value = clamp(value, 0, MAX_CHANNEL_VALUE); + // shift the value to the appropriate channel + value <<= offset; + // clear the channel + this.hex &= ~mask; + // set the channel to the new value + this.hex |= value; + } + + /** + * Produces the opposite color of the current value of the color object + * and sets the value of this color to its inverse. + * e.g. yellow becomes blue, black becomes white + */ + public function invert():void { + red = MAX_CHANNEL_VALUE - red; + green = MAX_CHANNEL_VALUE - green; + blue = MAX_CHANNEL_VALUE - blue; + } + + /** + * Produces the opposite color of the current value of the color object. + * e.g. yellow becomes blue, black becomes white + */ + public function getInverse ():Color { + var inverse:Color = new Color(); + inverse.red = MAX_CHANNEL_VALUE - red; + inverse.green = MAX_CHANNEL_VALUE - green; + inverse.blue = MAX_CHANNEL_VALUE - blue; + return inverse; + } + + /** + * Returns the rgb value for the web color that is closest to the color. + * + * @returns uint The value for the nearest web color. + */ + public function getNearestWebColor():uint { + var r:uint, g:uint, b:uint; + r = Math.round(red / WEB_COLOR_STEP_SIZE) * WEB_COLOR_STEP_SIZE; + g = Math.round(green / WEB_COLOR_STEP_SIZE) * WEB_COLOR_STEP_SIZE; + b = Math.round(blue / WEB_COLOR_STEP_SIZE) * WEB_COLOR_STEP_SIZE; + return (r << RED_OFFSET | g << GREEN_OFFSET | b << BLUE_OFFSET); + } + + /** Sets the saturation of the color to 0 making it grey. */ + public function desaturate():void { + this.saturation = 0; + } + + // conversion methods + + /** Return a string value of the color */ + override public function toString():String { return getNumberAsHexString(_hex, 8); } + + /** Return an array of the 3 channels */ + public function toArray():Array { return [red, green, blue]; } //, alpha]; } + + + /** + * Converts a uint into a string in the format “0x123456789ABCDEF”. + * This function is quite useful for displaying hex colors as text. + * + * @author Mims H. Wright (modified by Pimm Hogeling) + * + * @example + * <listing version="3.0"> + * getNumberAsHexString(255); // 0xFF + * getNumberAsHexString(0xABCDEF); // 0xABCDEF + * getNumberAsHexString(0x00FFCC); // 0xFFCC + * getNumberAsHexString(0x00FFCC, 6); // 0x00FFCC + * getNumberAsHexString(0x00FFCC, 6, false); // 00FFCC + * </listing> + * + * + * @param number The number to convert to hex. Note, numbers larger than 0xFFFFFFFF may produce unexpected results. + * @param minimumLength The smallest number of hexits to include in the output. + * Missing places will be filled in with 0’s. + * e.g. getNumberAsHexString(0xFF33, 6); // results in "0x00FF33" + * @param showHexDenotation If true, will append "0x" to the front of the string. + * @return String representation of the number as a string starting with "0x" + */ + private function getNumberAsHexString(number:uint, minimumLength:uint = 1, showHexDenotation:Boolean = true):String { + // The string that will be output at the end of the function. + var string:String = number.toString(16).toUpperCase(); + + // While the minimumLength argument is higher than the length of the string, add a leading zero. + while (minimumLength > string.length) { + string = "0" + string; + } + + // Return the result with a "0x" in front of the result. + if (showHexDenotation) { string = "0x" + string; } + + return string; + } + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/all-wcprops b/src/utils/mvc/.svn/all-wcprops new file mode 100644 index 0000000..746b30b --- /dev/null +++ b/src/utils/mvc/.svn/all-wcprops @@ -0,0 +1,35 @@ +K 25 +svn:wc:ra_dav:version-url +V 41 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc +END +AbstractView.as +K 25 +svn:wc:ra_dav:version-url +V 57 +/svn/!svn/ver/46/trunk/src/org/as3lib/mvc/AbstractView.as +END +IView.as +K 25 +svn:wc:ra_dav:version-url +V 50 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IView.as +END +AbstractController.as +K 25 +svn:wc:ra_dav:version-url +V 63 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/AbstractController.as +END +IModel.as +K 25 +svn:wc:ra_dav:version-url +V 51 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IModel.as +END +IController.as +K 25 +svn:wc:ra_dav:version-url +V 56 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IController.as +END diff --git a/src/utils/mvc/.svn/entries b/src/utils/mvc/.svn/entries new file mode 100644 index 0000000..aa3346f --- /dev/null +++ b/src/utils/mvc/.svn/entries @@ -0,0 +1,198 @@ +10 + +dir +43 +https://as3lib.googlecode.com/svn/trunk/src/org/as3lib/mvc +https://as3lib.googlecode.com/svn + + + +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + +5ef08cf5-1340-0410-b16c-d3bedfb892dd + +AbstractView.as +file +46 + + + +2011-03-04T19:39:24.000000Z +57c08efb41591e7db519ca10bb33a06d +2011-03-05T16:00:45.645054Z +46 +mimshwright + + + + + + + + + + + + + + + + + + + + + +1290 + +IView.as +file + + + + +2010-04-11T18:14:50.000000Z +2e9423d189bd0dac685cb47fb0c92354 +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +524 + +AbstractController.as +file + + + + +2010-04-11T18:15:18.000000Z +75a2202fe3f66373be757b68d7cb6360 +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +713 + +IModel.as +file + + + + +2010-04-11T18:15:58.000000Z +41685c0f0e474fbb7c240534309c795a +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +121 + +IController.as +file + + + + +2010-04-11T18:14:58.000000Z +fad2a92e5a939e0ea95be08e496d211e +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +601 + diff --git a/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base new file mode 100644 index 0000000..7b61305 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base @@ -0,0 +1,30 @@ +package org.as3lib.mvc +{ + /** + * Provides basic services for the "controller" of + * a Model/View/Controller triad. + * + * Based on original AS2 code by Colin Moock + */ + public class AbstractController implements IController + { + /** + * Constructor + * + * @param model The model this controller's view is observing. + */ + public function AbstractController( model : * ) + { + this.model = model; + } + + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + + public function get view():IView { return _view; } + public function set view(view:IView):void { _view = view; } + protected var _view:IView; + } +} diff --git a/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base new file mode 100644 index 0000000..ef26bde --- /dev/null +++ b/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base @@ -0,0 +1,48 @@ +package org.as3lib.mvc +{ + import flash.display.DisplayObject; + import flash.display.MovieClip; + + import abstractAS3.AbstractEnforcer; + + public class AbstractView extends MovieClip implements IView + { + public function AbstractView ( model:*, controller:IController = null) { + super(); + this.model = model; + + if (controller != null) { + this.controller = controller; + } + } + + public function asDisplayObject():DisplayObject { + return this; + } + + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + public function get controller():IController { + // If a controller hasn't been defined yet... + if (_controller == null) { + // ...make one. Note that defaultController() is normally overridden + // by the AbstractView subclass so that it returns the appropriate + // controller for the view. + this.controller = getDefaultController( model ); + } + return controller; + } + public function set controller(controller:IController):void { + _controller = controller; + controller.view = this; + } + protected var _controller:IController; + + public function getDefaultController( model:* ):IController { + AbstractEnforcer.enforceMethod(); + return null; + } + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IController.as.svn-base b/src/utils/mvc/.svn/text-base/IController.as.svn-base new file mode 100644 index 0000000..b115880 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/IController.as.svn-base @@ -0,0 +1,33 @@ +package org.as3lib.mvc +{ + + + /** + * Specifies the minimum services that the "controller" of + * a Model/View/Controller triad must provide. + * + * Modified from original AS2 code by Colin Moock + */ + public interface IController + { + /** + * Sets the model for this controller. + */ + function set model (model:*):void; + + /** + * Returns the model for this controller. + */ + function get model ():*; + + /** + * Sets the view this controller is servicing. + */ + function set view (view:IView):void; + + /** + * Returns this controller's view. + */ + function get view ():IView; + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IModel.as.svn-base b/src/utils/mvc/.svn/text-base/IModel.as.svn-base new file mode 100644 index 0000000..f8b7d80 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/IModel.as.svn-base @@ -0,0 +1,11 @@ +package org.as3lib.mvc +{ + + /** + * Purely a marker interface for model classes. + */ + public interface IModel + { + + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IView.as.svn-base b/src/utils/mvc/.svn/text-base/IView.as.svn-base new file mode 100644 index 0000000..5736ec6 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/IView.as.svn-base @@ -0,0 +1,22 @@ +package org.as3lib.mvc +{ + import org.as3lib.display.IDisplayObject; + + + /** + * Specifies the minimum services that the "view" + * of a Model/View/Controller triad must provide. + * + * Modified from original AS2 code by Colin Moock + */ + public interface IView extends IDisplayObject + { + function set model ( model:* ):void; + function get model ():*; + + function set controller ( controller:IController ):void; + function get controller ():IController; + + function getDefaultController ( model:* ):IController; + } +} \ No newline at end of file diff --git a/src/utils/mvc/AbstractController.as b/src/utils/mvc/AbstractController.as new file mode 100644 index 0000000..44a77c6 --- /dev/null +++ b/src/utils/mvc/AbstractController.as @@ -0,0 +1,30 @@ +package utils.mvc +{ + /** + * Provides basic implementation of the "controller" of + * a Model/View/Controller triad. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public class AbstractController implements IController + { + /** + * Constructor + * + * @param model The model this controller's view is observing. + */ + public function AbstractController( model : * ) + { + this.model = model; + } + + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + + public function get view():IView { return _view; } + public function set view(view:IView):void { _view = view; } + protected var _view:IView; + } +} diff --git a/src/utils/mvc/AbstractView.as b/src/utils/mvc/AbstractView.as new file mode 100644 index 0000000..6ebda0a --- /dev/null +++ b/src/utils/mvc/AbstractView.as @@ -0,0 +1,65 @@ +package utils.mvc +{ + import flash.display.DisplayObject; + import flash.display.MovieClip; + + /** + * A default implementation of IView based on MovieClip. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public class AbstractView extends MovieClip implements IView + { + + /** + * Constructor. + * + * @param model The data model that defines this view. + * @param controller A specific controller to use (otherwise, the defaultController will be used) + */ + public function AbstractView ( model:*, controller:IController = null) { + super(); + this.model = model; + + if (controller != null) { + this.controller = controller; + } + } + + /** @inheritDoc */ + public function asDisplayObject():DisplayObject { + return this; + } + + /** @inheritDoc */ + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + /** + * The controller for the model that the view will use to modify it. + * If it is set to null, the default controller will be used. + */ + public function get controller():IController { + // If a controller hasn't been defined yet... + if (_controller == null) { + // ...make one. Note that defaultController() is normally overridden + // by the AbstractView subclass so that it returns the appropriate + // controller for the view. + this.controller = getDefaultController( model ); + this.controller.view = this; + } + return controller; + } + public function set controller(controller:IController):void { + _controller = controller; + controller.view = this; + } + protected var _controller:IController; + + public function getDefaultController( model:* ):IController { +// AbstractEnforcer.enforceMethod(); + return null; + } + } +} \ No newline at end of file diff --git a/src/utils/mvc/IController.as b/src/utils/mvc/IController.as new file mode 100644 index 0000000..0496ee0 --- /dev/null +++ b/src/utils/mvc/IController.as @@ -0,0 +1,33 @@ +package utils.mvc +{ + + + /** + * Specifies the minimum functionality that the "controller" of + * a Model/View/Controller triad must provide. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public interface IController + { + /** + * Sets the model for this controller. + */ + function set model (model:*):void; + + /** + * Returns the model for this controller. + */ + function get model ():*; + + /** + * Sets the view this controller is servicing. + */ + function set view (view:IView):void; + + /** + * Returns this controller's view. + */ + function get view ():IView; + } +} \ No newline at end of file diff --git a/src/utils/mvc/IView.as b/src/utils/mvc/IView.as new file mode 100644 index 0000000..626a855 --- /dev/null +++ b/src/utils/mvc/IView.as @@ -0,0 +1,27 @@ +package utils.mvc +{ + import utils.display.IDisplayObject; + + /** + * Specifies the minimum functionality that the "view" + * of a Model/View/Controller triad must provide. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public interface IView extends IDisplayObject + { + /** A reference to the model associated with this view. */ + function set model ( model:* ):void; + function get model ():*; + + /** A reference to the model's controller. */ + function set controller ( controller:IController ):void; + function get controller ():IController; + + /** + * Returns an instance to a default implementation of the controller + * for the model. + */ + function getDefaultController ( model:* ):IController; + } +} \ No newline at end of file
as3/as3-utils
870318ef942aa5a04b3390f686390a520c06f6a1
Removed svn folder. Added url to comments for mvc files.
diff --git a/src/utils/mvc/.svn/all-wcprops b/src/utils/mvc/.svn/all-wcprops deleted file mode 100644 index 746b30b..0000000 --- a/src/utils/mvc/.svn/all-wcprops +++ /dev/null @@ -1,35 +0,0 @@ -K 25 -svn:wc:ra_dav:version-url -V 41 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc -END -AbstractView.as -K 25 -svn:wc:ra_dav:version-url -V 57 -/svn/!svn/ver/46/trunk/src/org/as3lib/mvc/AbstractView.as -END -IView.as -K 25 -svn:wc:ra_dav:version-url -V 50 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IView.as -END -AbstractController.as -K 25 -svn:wc:ra_dav:version-url -V 63 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/AbstractController.as -END -IModel.as -K 25 -svn:wc:ra_dav:version-url -V 51 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IModel.as -END -IController.as -K 25 -svn:wc:ra_dav:version-url -V 56 -/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IController.as -END diff --git a/src/utils/mvc/.svn/entries b/src/utils/mvc/.svn/entries deleted file mode 100644 index aa3346f..0000000 --- a/src/utils/mvc/.svn/entries +++ /dev/null @@ -1,198 +0,0 @@ -10 - -dir -43 -https://as3lib.googlecode.com/svn/trunk/src/org/as3lib/mvc -https://as3lib.googlecode.com/svn - - - -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - -5ef08cf5-1340-0410-b16c-d3bedfb892dd - -AbstractView.as -file -46 - - - -2011-03-04T19:39:24.000000Z -57c08efb41591e7db519ca10bb33a06d -2011-03-05T16:00:45.645054Z -46 -mimshwright - - - - - - - - - - - - - - - - - - - - - -1290 - -IView.as -file - - - - -2010-04-11T18:14:50.000000Z -2e9423d189bd0dac685cb47fb0c92354 -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -524 - -AbstractController.as -file - - - - -2010-04-11T18:15:18.000000Z -75a2202fe3f66373be757b68d7cb6360 -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -713 - -IModel.as -file - - - - -2010-04-11T18:15:58.000000Z -41685c0f0e474fbb7c240534309c795a -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -121 - -IController.as -file - - - - -2010-04-11T18:14:58.000000Z -fad2a92e5a939e0ea95be08e496d211e -2010-04-11T18:22:27.529495Z -42 -mimshwright - - - - - - - - - - - - - - - - - - - - - -601 - diff --git a/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base deleted file mode 100644 index 7b61305..0000000 --- a/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base +++ /dev/null @@ -1,30 +0,0 @@ -package org.as3lib.mvc -{ - /** - * Provides basic services for the "controller" of - * a Model/View/Controller triad. - * - * Based on original AS2 code by Colin Moock - */ - public class AbstractController implements IController - { - /** - * Constructor - * - * @param model The model this controller's view is observing. - */ - public function AbstractController( model : * ) - { - this.model = model; - } - - public function get model():* { return _model; } - public function set model(model:*):void { _model = model; } - protected var _model:*; - - - public function get view():IView { return _view; } - public function set view(view:IView):void { _view = view; } - protected var _view:IView; - } -} diff --git a/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base deleted file mode 100644 index ef26bde..0000000 --- a/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base +++ /dev/null @@ -1,48 +0,0 @@ -package org.as3lib.mvc -{ - import flash.display.DisplayObject; - import flash.display.MovieClip; - - import abstractAS3.AbstractEnforcer; - - public class AbstractView extends MovieClip implements IView - { - public function AbstractView ( model:*, controller:IController = null) { - super(); - this.model = model; - - if (controller != null) { - this.controller = controller; - } - } - - public function asDisplayObject():DisplayObject { - return this; - } - - public function get model():* { return _model; } - public function set model(model:*):void { _model = model; } - protected var _model:*; - - public function get controller():IController { - // If a controller hasn't been defined yet... - if (_controller == null) { - // ...make one. Note that defaultController() is normally overridden - // by the AbstractView subclass so that it returns the appropriate - // controller for the view. - this.controller = getDefaultController( model ); - } - return controller; - } - public function set controller(controller:IController):void { - _controller = controller; - controller.view = this; - } - protected var _controller:IController; - - public function getDefaultController( model:* ):IController { - AbstractEnforcer.enforceMethod(); - return null; - } - } -} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IController.as.svn-base b/src/utils/mvc/.svn/text-base/IController.as.svn-base deleted file mode 100644 index b115880..0000000 --- a/src/utils/mvc/.svn/text-base/IController.as.svn-base +++ /dev/null @@ -1,33 +0,0 @@ -package org.as3lib.mvc -{ - - - /** - * Specifies the minimum services that the "controller" of - * a Model/View/Controller triad must provide. - * - * Modified from original AS2 code by Colin Moock - */ - public interface IController - { - /** - * Sets the model for this controller. - */ - function set model (model:*):void; - - /** - * Returns the model for this controller. - */ - function get model ():*; - - /** - * Sets the view this controller is servicing. - */ - function set view (view:IView):void; - - /** - * Returns this controller's view. - */ - function get view ():IView; - } -} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IModel.as.svn-base b/src/utils/mvc/.svn/text-base/IModel.as.svn-base deleted file mode 100644 index f8b7d80..0000000 --- a/src/utils/mvc/.svn/text-base/IModel.as.svn-base +++ /dev/null @@ -1,11 +0,0 @@ -package org.as3lib.mvc -{ - - /** - * Purely a marker interface for model classes. - */ - public interface IModel - { - - } -} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IView.as.svn-base b/src/utils/mvc/.svn/text-base/IView.as.svn-base deleted file mode 100644 index 5736ec6..0000000 --- a/src/utils/mvc/.svn/text-base/IView.as.svn-base +++ /dev/null @@ -1,22 +0,0 @@ -package org.as3lib.mvc -{ - import org.as3lib.display.IDisplayObject; - - - /** - * Specifies the minimum services that the "view" - * of a Model/View/Controller triad must provide. - * - * Modified from original AS2 code by Colin Moock - */ - public interface IView extends IDisplayObject - { - function set model ( model:* ):void; - function get model ():*; - - function set controller ( controller:IController ):void; - function get controller ():IController; - - function getDefaultController ( model:* ):IController; - } -} \ No newline at end of file diff --git a/src/utils/mvc/AbstractController.as b/src/utils/mvc/AbstractController.as index 44a77c6..3b2ecf4 100644 --- a/src/utils/mvc/AbstractController.as +++ b/src/utils/mvc/AbstractController.as @@ -1,30 +1,30 @@ package utils.mvc { /** * Provides basic implementation of the "controller" of * a Model/View/Controller triad. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public class AbstractController implements IController { /** * Constructor * * @param model The model this controller's view is observing. */ public function AbstractController( model : * ) { this.model = model; } public function get model():* { return _model; } public function set model(model:*):void { _model = model; } protected var _model:*; public function get view():IView { return _view; } public function set view(view:IView):void { _view = view; } protected var _view:IView; } } diff --git a/src/utils/mvc/AbstractView.as b/src/utils/mvc/AbstractView.as index 6ebda0a..3b597c8 100644 --- a/src/utils/mvc/AbstractView.as +++ b/src/utils/mvc/AbstractView.as @@ -1,65 +1,65 @@ package utils.mvc { import flash.display.DisplayObject; import flash.display.MovieClip; /** * A default implementation of IView based on MovieClip. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public class AbstractView extends MovieClip implements IView { /** * Constructor. * * @param model The data model that defines this view. * @param controller A specific controller to use (otherwise, the defaultController will be used) */ public function AbstractView ( model:*, controller:IController = null) { super(); this.model = model; if (controller != null) { this.controller = controller; } } /** @inheritDoc */ public function asDisplayObject():DisplayObject { return this; } /** @inheritDoc */ public function get model():* { return _model; } public function set model(model:*):void { _model = model; } protected var _model:*; /** * The controller for the model that the view will use to modify it. * If it is set to null, the default controller will be used. */ public function get controller():IController { // If a controller hasn't been defined yet... if (_controller == null) { // ...make one. Note that defaultController() is normally overridden // by the AbstractView subclass so that it returns the appropriate // controller for the view. this.controller = getDefaultController( model ); this.controller.view = this; } return controller; } public function set controller(controller:IController):void { _controller = controller; controller.view = this; } protected var _controller:IController; public function getDefaultController( model:* ):IController { // AbstractEnforcer.enforceMethod(); return null; } } } \ No newline at end of file diff --git a/src/utils/mvc/IController.as b/src/utils/mvc/IController.as index 0496ee0..4bd162c 100644 --- a/src/utils/mvc/IController.as +++ b/src/utils/mvc/IController.as @@ -1,33 +1,33 @@ package utils.mvc { /** * Specifies the minimum functionality that the "controller" of * a Model/View/Controller triad must provide. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public interface IController { /** * Sets the model for this controller. */ function set model (model:*):void; /** * Returns the model for this controller. */ function get model ():*; /** * Sets the view this controller is servicing. */ function set view (view:IView):void; /** * Returns this controller's view. */ function get view ():IView; } } \ No newline at end of file diff --git a/src/utils/mvc/IView.as b/src/utils/mvc/IView.as index 626a855..d5da453 100644 --- a/src/utils/mvc/IView.as +++ b/src/utils/mvc/IView.as @@ -1,27 +1,27 @@ package utils.mvc { import utils.display.IDisplayObject; /** * Specifies the minimum functionality that the "view" * of a Model/View/Controller triad must provide. * - * @author From original AS2 code by Colin Moock modified by Mims Wright + * @author From original AS2 code by Colin Moock modified by Mims Wright http://www.moock.org/lectures/mvc/ */ public interface IView extends IDisplayObject { /** A reference to the model associated with this view. */ function set model ( model:* ):void; function get model ():*; /** A reference to the model's controller. */ function set controller ( controller:IController ):void; function get controller ():IController; /** * Returns an instance to a default implementation of the controller * for the model. */ function getDefaultController ( model:* ):IController; } } \ No newline at end of file
as3/as3-utils
659b935079c264cc296de74724653e05839636be
added unapproved code
diff --git a/src/utils/color/Color.as b/src/utils/color/Color.as new file mode 100644 index 0000000..a8d5781 --- /dev/null +++ b/src/utils/color/Color.as @@ -0,0 +1,455 @@ +package utils.color +{ + + import flash.events.Event; + import flash.events.EventDispatcher; + + import utils.number.clamp; + + /** + * A color, based on a 24-bit hex color, that can be manipulated, split into channels, + * and converted into several convenient formats. + * + * This class makes extensive use of bitwise operations. For information on how these work, check out the + * following resources. + * <ul> + * <li><a href="http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math/">Bitwise Gems (Polygonal Labs)</a></li> + * <li><a href="http://www.gamedev.net/reference/articles/article1563.asp">Bitwise Operations in C</a></li> + * <li><a href="http://en.wikipedia.org/wiki/Bitwise_operation">Wikipedia</a></li> + * </ul> + * + * Most of the formulae for converting to and from HSV and HSL color spaces was found in this article. + * <a href="http://en.wikipedia.org/wiki/HSL_and_HSV">Wikipedia - HSL and HSV</a> + * + * @author Mims H. Wright + */ + public class Color extends EventDispatcher + { + [Event(name="colorChanged", type="flash.events.Event")] + public static const COLOR_CHANGED:String = "colorChanged"; + + // Masks and offsets are used for bitwise operations on the color channels. + public static const RED_MASK:uint = 0x00FF0000; + public static const RED_OFFSET:uint = 16; + public static const GREEN_MASK:uint = 0x0000FF00; + public static const GREEN_OFFSET:uint = 8; + public static const BLUE_MASK:uint = 0x000000FF; + public static const BLUE_OFFSET:uint = 0; + + /** Maximum value allowed for a 24-bit color */ + protected static const MAX_COLOR_VALUE:uint = 0xFFFFFF; + /** Maximum value allowed for a single channel */ + protected static const MAX_CHANNEL_VALUE:uint = 0xFF; + /** The step size betwen web color channels */ + protected static const WEB_COLOR_STEP_SIZE:uint = 0x33; + + + /** + * This is the hex value for the Color object in the standard form, 0xrrggbb. + * It is the only true record of the color represented by a Color object. + * All other getters and setters ultimately manipulate this value or are + * derived from it. + */ + [Bindable("colorChanged")] + public function get hex ():uint { return _hex; } + public function set hex (rgb:uint):void { + rgb = clamp(rgb, 0, MAX_COLOR_VALUE); + _hex = rgb; + dispatchEvent(new Event(COLOR_CHANGED)); + } + protected var _hex:uint = 0x000000; + + + /** + * Constructor. + * + * @param value An initial value for the color. + * Note: alpha channel is ignored by the constructor. + * Default is black with full alpha. + */ + public function Color(value:uint = 0x000000) { + this.hex = value; + } + + + + // Individual channel getters and setters + + [Bindable] + /** The hex value for the red channel. */ + public function get red():uint { return (hex & RED_MASK) >>> RED_OFFSET; } + public function set red(red:uint):void { setChannel(red, RED_OFFSET, RED_MASK); } + [Bindable] + /** The percentage value for the red channel. */ + public function get redPercent():Number { return red / MAX_CHANNEL_VALUE } + public function set redPercent(red:Number):void { setChannel(int(red * MAX_CHANNEL_VALUE), RED_OFFSET, RED_MASK); } + + [Bindable] + /** The hex value for the green channel. */ + public function get green():uint { return (hex & GREEN_MASK) >>> GREEN_OFFSET; } + public function set green(green:uint):void { setChannel(green, GREEN_OFFSET, GREEN_MASK); } + [Bindable] + /** The percentage value for the green channel. */ + public function get greenPercent():Number { return green / MAX_CHANNEL_VALUE } + public function set greenPercent(green:Number):void { setChannel(int(green * MAX_CHANNEL_VALUE), GREEN_OFFSET, GREEN_MASK); } + + [Bindable] + /** The hex value for the blue channel. */ + public function get blue():uint { return (hex & BLUE_MASK) >>> BLUE_OFFSET; } + public function set blue(blue:uint):void { setChannel(blue, BLUE_OFFSET, BLUE_MASK); } + [Bindable] + /** The percentage value for the blue channel. */ + public function get bluePercent():Number { return blue / MAX_CHANNEL_VALUE } + public function set bluePercent(blue:Number):void { setChannel(int(blue * MAX_CHANNEL_VALUE), BLUE_OFFSET, BLUE_MASK); } + + + // Channels in the CMYK space. + + /** The percentage for the black value in CMYK. Approximations only. */ + public function get black():Number { return Math.min(1 - redPercent, 1 - greenPercent, 1 - bluePercent); } + + /** The percentage for the cyan value in CMYK. Approximations only. */ + public function get cyan():Number { return (1 - redPercent - black) / (1 - black); } + + /** The percentage for the magnenta value in CMYK. Approximations only. */ + public function get magenta():Number { return (1 - greenPercent - black) / (1 - black); } + + /** The percentage for the yellow value in CMYK. Approximations only. */ + public function get yellow():Number { return (1 - bluePercent - black) / (1 - black); } + + /** + * Converts a value for CMYK to RGB. Each value provided must be in the + * range of 0.0-1.0. + * + * Note: this method is not very accurate and should not be used + * for professional color conversion. + */ + public function setCMYK (c:Number, m:Number, y:Number, k:Number):void { + k = clamp(k, 0, 1); + c = clamp(c, 0, 1) * (1-k) + k; + m = clamp(m, 0, 1) * (1-k) + k; + y = clamp(y, 0, 1) * (1-k) + k; + + red = convertChannel(c); + green = convertChannel(m); + blue = convertChannel(y); + + function convertChannel(channel:Number):Number { + return int((1 - Math.min(1, channel))*255 + 0.5); + } + } + + + /** + * Indicates the color space that HS_ operations will use by default. + * If true, HSV (hue, saturation, value) will be used. + * If false, HSL (hue, saturation, lightness) will be used. + public var useHSV:Boolean = true; + */ + + + /** + * The hue of the color as a value in degrees from 0-360 + */ + public function get hue():Number { + + // nested function to calculate the hue based on the lightest color. + function calculateHue (colorA:uint, colorB:uint, offset:uint):Number { + return (60 * (colorA - colorB) / (lightestChannelValue - darkestChannelValue) + offset) % 360; + } + + if (this.isGrey()) { + return 0; // grey colors don't really have a hue. + } else if (lightestChannelValue == red) { + return calculateHue (green, blue, 0); + } else if (lightestChannelValue == green) { + return calculateHue (blue, red, 120); + } else if (lightestChannelValue == blue) { + return calculateHue (red, green, 240); + } else { + throw new Error("Somehow the brightest channel isn't one of the channels"); + } + } + + public function set hue(hue:Number):void { + setHSV(hue, saturation, value); + } + + + /** The hue as a percentage instead of as a degree */ + public function get huePercent():Number { return hue/360; } + + public function set huePercent(huePercent:Number):void { + hue = huePercent * 360; + } + + + /** The saturation of the color as a percentage. */ + public function get saturation ():Number { + if (lightestChannelValue <= 0) { return 0; } + return uint(lightestChannelValue - darkestChannelValue) / lightestChannelValue; + } + public function set saturation(saturation:Number):void { + setHSV(hue, saturation, value); + } + + /** + * The value of the color in HSV color space. + * range = 0~255 + */ + public function get value ():uint { + return lightestChannelValue; + } + public function set value(value:uint):void { + setHSV(hue, saturation, value); + } + + /** + * The color value as a percentage. + */ + public function get valuePercentage():Number { + return value / MAX_CHANNEL_VALUE; + } + + + /* public function get lightness():Number { + return 0.5 * (lightestChannelValue + darkestChannelValue); + } + public function set lightness(lightness:Number):void { + limit(lightness, 0, 1); + setHSL(hue, saturation, lightness); + } */ + + /** + * Sets the color by providing three values - one for each channel. + */ + public function setRGB(red:uint, green:uint, blue:uint):void { + this.red = red; + this.green = green; + this.blue = blue; + } + + + /** + * Sets the hue, saturation, and lightness of the color. + * + * @param hue The hue in degrees (0~360) + * @param saturation The saturation in percent (0~1) + * @param the lightness in percent (0~1) + public function setHSL(hue:Number, saturation:Number, lightness:Number):void { + + // If saturation is 0, that means the color is grey so just use the lightness value for all channels. + if (saturation == 0) { + red = green = blue = lightness; + return; + } + + // limit parameters to appropriate range. + hue = limit(hue, 0, 360); + saturation = limit(saturation, 0, 1); + lightness = limit(lightness, 0, 1); + + // begin crazy algorithms!!! zOMG!!1 + var q:Number, p:Number, rHue:Number, gHue:Number, bHue:Number; + if (lightness < 0.5) { + q = lightness * (1 + saturation); + } else { + q = lightness + saturation - (lightness * saturation); + } + + p = 2 * lightness - q; + rHue = huePercent + 1/3; + gHue = huePercent; + bHue = huePercent - 1/3; + + if (huePercent < 1/3) { bHue += 1.0; } + if (huePercent > 1/3) { rHue -= 1.0; } + + red = calculateResultForChannel(rHue); + green = calculateResultForChannel(gHue); + blue = calculateResultForChannel(bHue); + + // nested function to figure out results for each channel based on channel hue. + function calculateResultForChannel(channelHue:Number):Number { + if (channelHue < 1/6) { + return p + ((q - p) * 6 * channelHue); + } else if (channelHue < 1/2) { + return q; + } else if (channelHue < 2/3) { + return p + ((q - p) * 6 * (2/3 - channelHue)); + } else { + return p; + } + } + } + */ + + /** + * Sets the hue, saturation, and value of the color. + * + * @param hue The hue in degrees (0~360) + * @param saturation The saturation in percent (0~1) + * @param the value in percent (0~255) + */ + public function setHSV(hue:Number, saturation:Number, value:uint):void { + hue %= 360; + if (hue < 0) hue += 360; + saturation = clamp(saturation, 0, 1); + value = clamp(value, 0, 255); + + var hueRange:Number, i:int, f:Number, p:Number, q:Number, t:Number, v:Number; + + // Begin Crazy algorithms + hueRange = hue / 60; + i = Math.floor(hueRange) % 6; + f = hueRange - Math.floor(hueRange); + p = value * (1 - saturation); + q = value * (1 - f * saturation); + t = value * (1 - (1 - f) * saturation); + v = value; + + switch (i) { + case 0: setRGB(v,t,p); break; + case 1: setRGB(q,v,p); break; + case 2: setRGB(p,v,t); break; + case 3: setRGB(p,q,v); break; + case 4: setRGB(t,p,v); break; + case 5: setRGB(v,p,q); break; + default: throw new Error("Invalid hue while converting HSV to RGB"); + } + } + + + /** + * Returns the <em>value</em> of the lightest color channel (excluding alpha). + * Used internally for hsv and hsl operations. + */ + protected function get lightestChannelValue():uint { + return Math.max(red, Math.max(green, blue)); + } + + /** + * Returns the <em>value</em> of the darkest color channel (excluding alpha). + * Used internally for hsv and hsl operations. + */ + protected function get darkestChannelValue():uint { + return Math.min(red, Math.min(green, blue)); + } + + /** + * Returns true if the color is a shade of grey (including white and black). + * In RGB, colors with the same value for all three channels are grey. + */ + public function isGrey():Boolean { + return (red == green) && (red == blue); + } + + + /** + * Sets the value of a color channel. + * Used by the individual color channel getters and setters. + * + * @param value The new value to set the channel - between 0 and 0xFF + * @param offset The number of places to binary shift the channel value. e.g. 8 for green. + * @param mask The binary mask for the channel + */ + protected function setChannel(value:int, offset:uint, mask:uint):void { + // limit the value between 0 and 0xFF + value = clamp(value, 0, MAX_CHANNEL_VALUE); + // shift the value to the appropriate channel + value <<= offset; + // clear the channel + this.hex &= ~mask; + // set the channel to the new value + this.hex |= value; + } + + /** + * Produces the opposite color of the current value of the color object + * and sets the value of this color to its inverse. + * e.g. yellow becomes blue, black becomes white + */ + public function invert():void { + red = MAX_CHANNEL_VALUE - red; + green = MAX_CHANNEL_VALUE - green; + blue = MAX_CHANNEL_VALUE - blue; + } + + /** + * Produces the opposite color of the current value of the color object. + * e.g. yellow becomes blue, black becomes white + */ + public function getInverse ():Color { + var inverse:Color = new Color(); + inverse.red = MAX_CHANNEL_VALUE - red; + inverse.green = MAX_CHANNEL_VALUE - green; + inverse.blue = MAX_CHANNEL_VALUE - blue; + return inverse; + } + + /** + * Returns the rgb value for the web color that is closest to the color. + * + * @returns uint The value for the nearest web color. + */ + public function getNearestWebColor():uint { + var r:uint, g:uint, b:uint; + r = Math.round(red / WEB_COLOR_STEP_SIZE) * WEB_COLOR_STEP_SIZE; + g = Math.round(green / WEB_COLOR_STEP_SIZE) * WEB_COLOR_STEP_SIZE; + b = Math.round(blue / WEB_COLOR_STEP_SIZE) * WEB_COLOR_STEP_SIZE; + return (r << RED_OFFSET | g << GREEN_OFFSET | b << BLUE_OFFSET); + } + + /** Sets the saturation of the color to 0 making it grey. */ + public function desaturate():void { + this.saturation = 0; + } + + // conversion methods + + /** Return a string value of the color */ + override public function toString():String { return getNumberAsHexString(_hex, 8); } + + /** Return an array of the 3 channels */ + public function toArray():Array { return [red, green, blue]; } //, alpha]; } + + + /** + * Converts a uint into a string in the format “0x123456789ABCDEF”. + * This function is quite useful for displaying hex colors as text. + * + * @author Mims H. Wright (modified by Pimm Hogeling) + * + * @example + * <listing version="3.0"> + * getNumberAsHexString(255); // 0xFF + * getNumberAsHexString(0xABCDEF); // 0xABCDEF + * getNumberAsHexString(0x00FFCC); // 0xFFCC + * getNumberAsHexString(0x00FFCC, 6); // 0x00FFCC + * getNumberAsHexString(0x00FFCC, 6, false); // 00FFCC + * </listing> + * + * + * @param number The number to convert to hex. Note, numbers larger than 0xFFFFFFFF may produce unexpected results. + * @param minimumLength The smallest number of hexits to include in the output. + * Missing places will be filled in with 0’s. + * e.g. getNumberAsHexString(0xFF33, 6); // results in "0x00FF33" + * @param showHexDenotation If true, will append "0x" to the front of the string. + * @return String representation of the number as a string starting with "0x" + */ + private function getNumberAsHexString(number:uint, minimumLength:uint = 1, showHexDenotation:Boolean = true):String { + // The string that will be output at the end of the function. + var string:String = number.toString(16).toUpperCase(); + + // While the minimumLength argument is higher than the length of the string, add a leading zero. + while (minimumLength > string.length) { + string = "0" + string; + } + + // Return the result with a "0x" in front of the result. + if (showHexDenotation) { string = "0x" + string; } + + return string; + } + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/all-wcprops b/src/utils/mvc/.svn/all-wcprops new file mode 100644 index 0000000..746b30b --- /dev/null +++ b/src/utils/mvc/.svn/all-wcprops @@ -0,0 +1,35 @@ +K 25 +svn:wc:ra_dav:version-url +V 41 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc +END +AbstractView.as +K 25 +svn:wc:ra_dav:version-url +V 57 +/svn/!svn/ver/46/trunk/src/org/as3lib/mvc/AbstractView.as +END +IView.as +K 25 +svn:wc:ra_dav:version-url +V 50 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IView.as +END +AbstractController.as +K 25 +svn:wc:ra_dav:version-url +V 63 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/AbstractController.as +END +IModel.as +K 25 +svn:wc:ra_dav:version-url +V 51 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IModel.as +END +IController.as +K 25 +svn:wc:ra_dav:version-url +V 56 +/svn/!svn/ver/42/trunk/src/org/as3lib/mvc/IController.as +END diff --git a/src/utils/mvc/.svn/entries b/src/utils/mvc/.svn/entries new file mode 100644 index 0000000..aa3346f --- /dev/null +++ b/src/utils/mvc/.svn/entries @@ -0,0 +1,198 @@ +10 + +dir +43 +https://as3lib.googlecode.com/svn/trunk/src/org/as3lib/mvc +https://as3lib.googlecode.com/svn + + + +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + +5ef08cf5-1340-0410-b16c-d3bedfb892dd + +AbstractView.as +file +46 + + + +2011-03-04T19:39:24.000000Z +57c08efb41591e7db519ca10bb33a06d +2011-03-05T16:00:45.645054Z +46 +mimshwright + + + + + + + + + + + + + + + + + + + + + +1290 + +IView.as +file + + + + +2010-04-11T18:14:50.000000Z +2e9423d189bd0dac685cb47fb0c92354 +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +524 + +AbstractController.as +file + + + + +2010-04-11T18:15:18.000000Z +75a2202fe3f66373be757b68d7cb6360 +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +713 + +IModel.as +file + + + + +2010-04-11T18:15:58.000000Z +41685c0f0e474fbb7c240534309c795a +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +121 + +IController.as +file + + + + +2010-04-11T18:14:58.000000Z +fad2a92e5a939e0ea95be08e496d211e +2010-04-11T18:22:27.529495Z +42 +mimshwright + + + + + + + + + + + + + + + + + + + + + +601 + diff --git a/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base new file mode 100644 index 0000000..7b61305 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/AbstractController.as.svn-base @@ -0,0 +1,30 @@ +package org.as3lib.mvc +{ + /** + * Provides basic services for the "controller" of + * a Model/View/Controller triad. + * + * Based on original AS2 code by Colin Moock + */ + public class AbstractController implements IController + { + /** + * Constructor + * + * @param model The model this controller's view is observing. + */ + public function AbstractController( model : * ) + { + this.model = model; + } + + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + + public function get view():IView { return _view; } + public function set view(view:IView):void { _view = view; } + protected var _view:IView; + } +} diff --git a/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base b/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base new file mode 100644 index 0000000..ef26bde --- /dev/null +++ b/src/utils/mvc/.svn/text-base/AbstractView.as.svn-base @@ -0,0 +1,48 @@ +package org.as3lib.mvc +{ + import flash.display.DisplayObject; + import flash.display.MovieClip; + + import abstractAS3.AbstractEnforcer; + + public class AbstractView extends MovieClip implements IView + { + public function AbstractView ( model:*, controller:IController = null) { + super(); + this.model = model; + + if (controller != null) { + this.controller = controller; + } + } + + public function asDisplayObject():DisplayObject { + return this; + } + + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + public function get controller():IController { + // If a controller hasn't been defined yet... + if (_controller == null) { + // ...make one. Note that defaultController() is normally overridden + // by the AbstractView subclass so that it returns the appropriate + // controller for the view. + this.controller = getDefaultController( model ); + } + return controller; + } + public function set controller(controller:IController):void { + _controller = controller; + controller.view = this; + } + protected var _controller:IController; + + public function getDefaultController( model:* ):IController { + AbstractEnforcer.enforceMethod(); + return null; + } + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IController.as.svn-base b/src/utils/mvc/.svn/text-base/IController.as.svn-base new file mode 100644 index 0000000..b115880 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/IController.as.svn-base @@ -0,0 +1,33 @@ +package org.as3lib.mvc +{ + + + /** + * Specifies the minimum services that the "controller" of + * a Model/View/Controller triad must provide. + * + * Modified from original AS2 code by Colin Moock + */ + public interface IController + { + /** + * Sets the model for this controller. + */ + function set model (model:*):void; + + /** + * Returns the model for this controller. + */ + function get model ():*; + + /** + * Sets the view this controller is servicing. + */ + function set view (view:IView):void; + + /** + * Returns this controller's view. + */ + function get view ():IView; + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IModel.as.svn-base b/src/utils/mvc/.svn/text-base/IModel.as.svn-base new file mode 100644 index 0000000..f8b7d80 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/IModel.as.svn-base @@ -0,0 +1,11 @@ +package org.as3lib.mvc +{ + + /** + * Purely a marker interface for model classes. + */ + public interface IModel + { + + } +} \ No newline at end of file diff --git a/src/utils/mvc/.svn/text-base/IView.as.svn-base b/src/utils/mvc/.svn/text-base/IView.as.svn-base new file mode 100644 index 0000000..5736ec6 --- /dev/null +++ b/src/utils/mvc/.svn/text-base/IView.as.svn-base @@ -0,0 +1,22 @@ +package org.as3lib.mvc +{ + import org.as3lib.display.IDisplayObject; + + + /** + * Specifies the minimum services that the "view" + * of a Model/View/Controller triad must provide. + * + * Modified from original AS2 code by Colin Moock + */ + public interface IView extends IDisplayObject + { + function set model ( model:* ):void; + function get model ():*; + + function set controller ( controller:IController ):void; + function get controller ():IController; + + function getDefaultController ( model:* ):IController; + } +} \ No newline at end of file diff --git a/src/utils/mvc/AbstractController.as b/src/utils/mvc/AbstractController.as new file mode 100644 index 0000000..44a77c6 --- /dev/null +++ b/src/utils/mvc/AbstractController.as @@ -0,0 +1,30 @@ +package utils.mvc +{ + /** + * Provides basic implementation of the "controller" of + * a Model/View/Controller triad. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public class AbstractController implements IController + { + /** + * Constructor + * + * @param model The model this controller's view is observing. + */ + public function AbstractController( model : * ) + { + this.model = model; + } + + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + + public function get view():IView { return _view; } + public function set view(view:IView):void { _view = view; } + protected var _view:IView; + } +} diff --git a/src/utils/mvc/AbstractView.as b/src/utils/mvc/AbstractView.as new file mode 100644 index 0000000..6ebda0a --- /dev/null +++ b/src/utils/mvc/AbstractView.as @@ -0,0 +1,65 @@ +package utils.mvc +{ + import flash.display.DisplayObject; + import flash.display.MovieClip; + + /** + * A default implementation of IView based on MovieClip. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public class AbstractView extends MovieClip implements IView + { + + /** + * Constructor. + * + * @param model The data model that defines this view. + * @param controller A specific controller to use (otherwise, the defaultController will be used) + */ + public function AbstractView ( model:*, controller:IController = null) { + super(); + this.model = model; + + if (controller != null) { + this.controller = controller; + } + } + + /** @inheritDoc */ + public function asDisplayObject():DisplayObject { + return this; + } + + /** @inheritDoc */ + public function get model():* { return _model; } + public function set model(model:*):void { _model = model; } + protected var _model:*; + + /** + * The controller for the model that the view will use to modify it. + * If it is set to null, the default controller will be used. + */ + public function get controller():IController { + // If a controller hasn't been defined yet... + if (_controller == null) { + // ...make one. Note that defaultController() is normally overridden + // by the AbstractView subclass so that it returns the appropriate + // controller for the view. + this.controller = getDefaultController( model ); + this.controller.view = this; + } + return controller; + } + public function set controller(controller:IController):void { + _controller = controller; + controller.view = this; + } + protected var _controller:IController; + + public function getDefaultController( model:* ):IController { +// AbstractEnforcer.enforceMethod(); + return null; + } + } +} \ No newline at end of file diff --git a/src/utils/mvc/IController.as b/src/utils/mvc/IController.as new file mode 100644 index 0000000..0496ee0 --- /dev/null +++ b/src/utils/mvc/IController.as @@ -0,0 +1,33 @@ +package utils.mvc +{ + + + /** + * Specifies the minimum functionality that the "controller" of + * a Model/View/Controller triad must provide. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public interface IController + { + /** + * Sets the model for this controller. + */ + function set model (model:*):void; + + /** + * Returns the model for this controller. + */ + function get model ():*; + + /** + * Sets the view this controller is servicing. + */ + function set view (view:IView):void; + + /** + * Returns this controller's view. + */ + function get view ():IView; + } +} \ No newline at end of file diff --git a/src/utils/mvc/IView.as b/src/utils/mvc/IView.as new file mode 100644 index 0000000..626a855 --- /dev/null +++ b/src/utils/mvc/IView.as @@ -0,0 +1,27 @@ +package utils.mvc +{ + import utils.display.IDisplayObject; + + /** + * Specifies the minimum functionality that the "view" + * of a Model/View/Controller triad must provide. + * + * @author From original AS2 code by Colin Moock modified by Mims Wright + */ + public interface IView extends IDisplayObject + { + /** A reference to the model associated with this view. */ + function set model ( model:* ):void; + function get model ():*; + + /** A reference to the model's controller. */ + function set controller ( controller:IController ):void; + function get controller ():IController; + + /** + * Returns an instance to a default implementation of the controller + * for the model. + */ + function getDefaultController ( model:* ):IController; + } +} \ No newline at end of file
as3/as3-utils
35f14845574c408784cceb9e019866ebfd8c8fa5
modified range
diff --git a/src/utils/math/Range.as b/src/utils/math/Range.as index 446de3e..af50cfb 100644 --- a/src/utils/math/Range.as +++ b/src/utils/math/Range.as @@ -1,212 +1,212 @@ /* CASA Lib for ActionScript 3.0 Copyright (c) 2009, Aaron Clinger & Contributors of CASA Lib All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the CASA Lib nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package utils.math { /** Creates a standardized way of describing and storing an extent of variation/a value range. @author Aaron Clinger @author Mike Creighton @version 10/19/08 */ public class Range { protected var _end:Number; protected var _start:Number; /** Creates and defines a Range object. @param start: Beginning value of the range. @param end: Ending value of the range. @usageNote You are not required to define the range in the contructor you can do it at any point by calling {@link #setRange}. */ public function Range(start:Number, end:Number) { super(); this.setRange(start, end); } /** Defines or redefines range. @param start: Beginning value of the range. @param end: Ending value of the range. */ public function setRange(start:Number, end:Number):void { this.start = start; this.end = end; } /** The start value of the range. */ public function get start():Number { return this._start; } public function set start(value:Number):void { this._start = value; } /** The end value of the range. */ public function get end():Number { return this._end; } public function set end(value:Number):void { this._end = value; } /** The minimum or smallest value of the range. */ public function get min():Number { return Math.min(this.start, this.end); } /** Tthe maximum or largest value of the range. */ public function get max():Number { return Math.max(this.start, this.end); } /** Determines if value is included in the range including the range's start and end values. @return Returns <code>true</code> if value was included in range; otherwise <code>false</code>. */ public function isWithinRange(value:Number):Boolean { return (value <= this.max && value >= this.min); } /** Calculates the percent of the range. @param percent: A {@link Percent} object. @return The value the percent represent of the range. */ public function getValueOfPercent(percent:Percent):Number { var min:Number; var max:Number; var val:Number; var per:Percent = percent.clone(); if (this.start <= this.end) { min = this.start; max = this.end; } else { per.decimalPercentage = 1 - per.decimalPercentage; min = this.end; max = this.start; } val = Math.abs(max - min) * per.decimalPercentage + min; return val; } /** Returns the percentage the value represents out of the range. @param value: An integer. @return A Percent object. */ public function getPercentOfValue(value:Number):Percent { return new Percent((value - this.min) / (this.max - this.min)); } /** Determines if the range specified by the <code>range</code> parameter is equal to this range object. @param percent: A Range object. @return Returns <code>true</code> if ranges are identical; otherwise <code>false</code>. */ public function equals(range:Range):Boolean { return this.start == range.start && this.end == range.end; } /** Determines if this range and the range specified by the <code>range</code> parameter overlap. @param A Range object. @return Returns <code>true</code> if this range contains any value of the range specified; otherwise <code>false</code>. */ public function overlaps(range:Range):Boolean { - if (this.equals(range) || this.contains(range) || range.contains(this) || this.isWithinRange(range.start) || this.isWithinRange(range.end)) + if (this.equals(range) || this.contains(range) || range.contains(Range(this)) || this.isWithinRange(range.start) || this.isWithinRange(range.end)) return true; return false; } /** Determines if this range contains the range specified by the <code>range</code> parameter. @param A Range object. @return Returns <code>true</code> if this range contains all values of the range specified; otherwise <code>false</code>. */ public function contains(range:Range):Boolean { return this.start <= range.start && this.end >= range.end; } /** @return A new range object with the same values as this range. */ public function clone():Range { return new Range(this.start, this.end); } } } \ No newline at end of file
as3/as3-utils
be062acc6fc530a6a2398255f833b602a824735e
edited README
diff --git a/README.md b/README.md index 31676c5..9b50f62 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,45 @@ # as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? HEAPS, too much to list here right now. Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html - number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) - Joel Hooks [@jhooks](http://twitter.com/jhooks) +- Mims H. Wright [@mimshwright](http://twitter.com/mimshwright) - You. # Giving credit where credit is due -Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. \ No newline at end of file +Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. +If you include your own code in the library, please be sure to add a credit for yourself in the comments or use an @author tag in the asDocs. \ No newline at end of file
as3/as3-utils
9846cce18fe00d398f201a9870cce3e562169fd4
Added adChild(), removeChild(), and removeChildAt() which all allow you to use these functions as usual but with many of the typical errors supressed like the index being out of bounds. Removed attTargetToParent() and removeTargetFromParent() since they aren't quite as robust as the new functions added. Fixed a minor error in removeAllChidrenByType() and updated documentation.
diff --git a/src/utils/display/addChild.as b/src/utils/display/addChild.as new file mode 100644 index 0000000..a440833 --- /dev/null +++ b/src/utils/display/addChild.as @@ -0,0 +1,30 @@ +package utils.display +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + + + /** + * Allows you to add a child without first checking that the child or parent exist. + * Allows you to add a child at an index higher than the number of children without error. + * Allows you to use the same function for addChild and addChildAt. + * + * @param child The child DisplayObject to add. + * @param parent The container to add the child to. + * @param atIndex The index to add the child at. Default is to add to the top (-1) + * @return Boolean True if the child was added, false if something prevented it from being added. + * + * @author Mims Wright + */ + public function addChild(child:DisplayObject, parent:DisplayObjectContainer, atIndex:int = -1):Boolean + { + if (child && parent) { + if (atIndex < 0 || atIndex > parent.numChildren) { + atIndex = parent.numChildren; + } + parent.addChildAt(child, atIndex); + return true; + } + return false + } +} \ No newline at end of file diff --git a/src/utils/display/addTargetToParent.as b/src/utils/display/addTargetToParent.as deleted file mode 100644 index 276a83a..0000000 --- a/src/utils/display/addTargetToParent.as +++ /dev/null @@ -1,25 +0,0 @@ -package utils.display -{ - import flash.display.DisplayObject; - import flash.display.DisplayObjectContainer; - - - public function addTargetToParent(_target:DisplayObject, _parent:DisplayObjectContainer, _adjustOrder:int = 1):void - { - const ADD_TARGET_TO_PARENT_ADJUST_ORDER_TYPE_TOP:int = 1; - const ADD_TARGET_TO_PARENT_ADJUST_ORDER_TYPE_LAST:int = 2; - - if (_target != null && _parent != null) - { - switch (_adjustOrder) - { - case ADD_TARGET_TO_PARENT_ADJUST_ORDER_TYPE_LAST: - _parent.addChildAt(_target, _parent.numChildren - 1); - break; - case ADD_TARGET_TO_PARENT_ADJUST_ORDER_TYPE_TOP: - _parent.addChild(_target); - break; - } - } - } -} \ No newline at end of file diff --git a/src/utils/display/removeAllChildrenByType.as b/src/utils/display/removeAllChildrenByType.as index e85afd8..708fae7 100644 --- a/src/utils/display/removeAllChildrenByType.as +++ b/src/utils/display/removeAllChildrenByType.as @@ -1,21 +1,34 @@ package utils.display { + import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; /** - * Remove all children from a container and leave the bottom few - * @param container Container to remove from - * @param the type of children to remove - * @author John Lindquist + * Remove all children of a specific type from a container. + * + * @example <listing version="3.0"> + * var s:Sprite = new Sprite(); + * s.addChild(new Shape()); + * s.addChild(new Shape()); + * s.addChild(new MovieClip()); + * s.addChild(new Sprite()); + * trace(s.numChildren); // 4 + * removeAllChildrenByType(s, Shape); + * trace(s.numChildren); // 2 + * </listing> + * + * @param container Container to remove from + * @param the type of children to remove + * @author John Lindquist */ public function removeAllChildrenByType(container:DisplayObjectContainer, type:Class):void { - for each(var child:DisplayObjectContainer in container) + for each(var child:DisplayObject in container) { if(child is type) { container.removeChild(child); } } } } \ No newline at end of file diff --git a/src/utils/display/removeChild.as b/src/utils/display/removeChild.as new file mode 100644 index 0000000..a0d977e --- /dev/null +++ b/src/utils/display/removeChild.as @@ -0,0 +1,33 @@ +package utils.display +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + + /** + * Removes a child from the parent without throwing errors if the child or parent is null + * or if the child isn't a child of the specified parent. + * + * @param child The child DisplayObject to remove. + * @param parent The parent to remove the child from. If none is specified, the function + * attempts to get the parent from the child's <code>parent</code> property. + * @returns Boolean True if the child was removed from the parent. False if something prevented it. + * + * @author Mims Wright + */ + public function removeChild(child:DisplayObject, parent:DisplayObjectContainer = null):Boolean + { + if (child) { + if (!parent) { + if (!child.parent) { // if parent and child.parent are null + return false; + } + parent = child.parent; + } + if (parent == child.parent) { + parent.removeChild(child); + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/src/utils/display/removeChildAt.as b/src/utils/display/removeChildAt.as new file mode 100644 index 0000000..699fc8e --- /dev/null +++ b/src/utils/display/removeChildAt.as @@ -0,0 +1,26 @@ +package utils.display +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + import flash.filters.DisplacementMapFilter; + + /** + * Removes the child at the index specified in a container and returns it. + * Automatically handles cases that could potentially throw errors such as the index + * being out of bounds or the parent being null. + * + * @param parent The container to remove the child from. + * @param index The index to remove. If left blank or if out of bounds, defaults to the top child. + * @return DisplayObject The child that was removed. + * + * @author Mims Wright + */ + public function removeChildAt(parent:DisplayObjectContainer, index:int = -1):DisplayObject + { + if (parent && parent.numChildren > 0) { + if (index < 0 || index > parent.numChildren) { index = parent.numChildren; } + var child:DisplayObject = parent.removeChildAt(index); + } + return null; + } +} \ No newline at end of file diff --git a/src/utils/display/removeTargetFromParent.as b/src/utils/display/removeTargetFromParent.as deleted file mode 100644 index 0436549..0000000 --- a/src/utils/display/removeTargetFromParent.as +++ /dev/null @@ -1,20 +0,0 @@ -package utils.display -{ - import flash.display.DisplayObjectContainer; - import flash.display.MovieClip; - - public function removeTargetFromParent(_target:DisplayObjectContainer):void - { - if (_target != null) - { - if (_target is MovieClip) - { - (_target as MovieClip).stop(); - } - if (_target.parent != null) - { - _target.parent.removeChild(_target); - } - } - } -} \ No newline at end of file
as3/as3-utils
e94058ecb708fe3c1cb9e632b1eda9b6c3f8899c
Added fullscreen package. tweaks to docs
diff --git a/src/utils/color/getColor.as b/src/utils/color/getColor.as index 5e6bdc3..6fec4b3 100644 --- a/src/utils/color/getColor.as +++ b/src/utils/color/getColor.as @@ -1,21 +1,21 @@ package utils.color { /** Converts a series of individual RGB(A) values to a 32-bit ARGB color value. - @param r: A uint from 0 to 255 representing the red color value. - @param g: A uint from 0 to 255 representing the green color value. - @param b: A uint from 0 to 255 representing the blue color value. - @param a: A uint from 0 to 255 representing the alpha value. Default is <code>255</code>. + @param r A uint from 0 to 255 representing the red color value. + @param g A uint from 0 to 255 representing the green color value. + @param b A uint from 0 to 255 representing the blue color value. + @param a A uint from 0 to 255 representing the alpha value. Default is <code>255</code>. @return Returns a hexidecimal color as a String. @example <listing version="3.0"> var hexColor : String = ColorUtil.getHexStringFromARGB(128, 255, 0, 255); trace(hexColor); // Traces 80FF00FF </listing> */ public function getColor(r:uint, g:uint, b:uint, a:uint = 255):uint { return (a << 24) | (r << 16) | (g << 8) | b; } } \ No newline at end of file diff --git a/src/utils/fullscreen/toggleFullScreen.as b/src/utils/fullscreen/toggleFullScreen.as new file mode 100644 index 0000000..917d177 --- /dev/null +++ b/src/utils/fullscreen/toggleFullScreen.as @@ -0,0 +1,25 @@ +package utils.fullscreen +{ + import flash.display.Stage; + import flash.display.StageDisplayState; + + /** + * Toggles the stage display state between normal and fullscreen. + * + * @param stage A reference to the stage object. + * @returns String The new state. + * + * @author Mims Wright + */ + public function toggleFullScreen(stage:Stage):String + { + var state:String; + if (stage.displayState == StageDisplayState.FULL_SCREEN) { + state = StageDisplayState.NORMAL; + } else { + state = StageDisplayState.FULL_SCREEN; + } + stage.displayState = state; + return state; + } +} \ No newline at end of file diff --git a/src/utils/garbageCollection/gc.as b/src/utils/garbageCollection/gc.as index 6f9ad0e..6f3bb45 100644 --- a/src/utils/garbageCollection/gc.as +++ b/src/utils/garbageCollection/gc.as @@ -1,17 +1,18 @@ package utils.garbageCollection { import flash.net.LocalConnection; + // TODO: Needs documentation public function gc():void { try { new LocalConnection().connect("gc"); new LocalConnection().connect("gc"); } catch (e:Error) { var shouldTouchHere:Boolean = true; } } } \ No newline at end of file
as3/as3-utils
0c640cbaead16c248d7fe34fda8681ec0d2307d4
assign()
diff --git a/src/utils/object/assign.as b/src/utils/object/assign.as new file mode 100644 index 0000000..d908348 --- /dev/null +++ b/src/utils/object/assign.as @@ -0,0 +1,25 @@ +package utils.object { + + + + /** + * Assign properties from params to an Object. + * @param obj Target Object + * @param params Source Object + * @return Resulting Object + */ + public function assign(obj:Object, params:Object):Object { + var out:Object = (obj); + + for(var i:String in params) { + //noinspection EmptyCatchBlockJS,UnusedCatchParameterJS + try { + out[i] = params[i]; + } + catch(err:Error) { + } + } + + return out; + } +}
as3/as3-utils
812afc514150be799567a4a59d90921135232cc0
Reverted === and !==, my bad
diff --git a/src/utils/array/arraysAreEqual.as b/src/utils/array/arraysAreEqual.as index 33d2ecb..13cc945 100644 --- a/src/utils/array/arraysAreEqual.as +++ b/src/utils/array/arraysAreEqual.as @@ -1,37 +1,32 @@ -package utils.array -{ +package utils.array { /** * Compares two arrays and returns a boolean indicating whether the arrays * contain the same values at the same indexes. * * @param arr1 The first array that will be compared to the second. * * @param arr2 The second array that will be compared to the first. * * @return True if the arrays contains the same values at the same indexes. - False if they do not. + False if they do not. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function arraysAreEqual(arr1:Array, arr2:Array):Boolean - { - if (arr1.length != arr2.length) - { + public function arraysAreEqual(arr1:Array, arr2:Array):Boolean { + if(arr1.length != arr2.length) { return false; } var len:Number = arr1.length; - for (var i:Number = 0; i < len; i++) - { - if (arr1[i] !== arr2[i]) - { + for(var i:Number = 0; i < len; i++) { + if(arr1[i] != arr2[i]) { return false; } } return true; } -} \ No newline at end of file +} diff --git a/src/utils/array/removeValueFromArray.as b/src/utils/array/removeValueFromArray.as index e312810..067a39e 100644 --- a/src/utils/array/removeValueFromArray.as +++ b/src/utils/array/removeValueFromArray.as @@ -1,26 +1,22 @@ -package utils.array -{ +package utils.array { /** * Remove all instances of the specified value from the array, * * @param arr The array from which the value will be removed * * @param value The object that will be removed from the array. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function removeValueFromArray(arr:Array, value:Object):void - { + public function removeValueFromArray(arr:Array, value:Object):void { var len:uint = arr.length; - for (var i:Number = len; i > -1; i--) - { - if (arr[i] === value) - { + for(var i:Number = len; i > -1; i--) { + if(arr[i] == value) { arr.splice(i, 1); } } } -} \ No newline at end of file +} diff --git a/src/utils/date/iso8601ToDate.as b/src/utils/date/iso8601ToDate.as index db96137..285ebf9 100644 --- a/src/utils/date/iso8601ToDate.as +++ b/src/utils/date/iso8601ToDate.as @@ -1,71 +1,71 @@ package utils.date { import utils.conversion.minutesToHours; import utils.object.isEmpty; /** * Converts W3C ISO 8601 date String into a Date object. * Example code: * <pre> * trace(iso8601ToDate("1994-11-05T08:15:30-05:00").toString()); * </pre> * @param iso8601 Valid ISO 8601 formatted String * @return Date object of the specified date and time of the ISO 8601 String in universal time * @see <a href="http://www.w3.org/TR/NOTE-datetime">W3C ISO 8601 specification</a> * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function iso8601ToDate(iso8601:String):Date { var parts:Array = iso8601.toUpperCase().split("T"); var date:Array = parts[0].split("-"); var time:Array = (parts.length <= 1) ? [] : parts[1].split(":"); var year:uint = isEmpty(date[0]) ? 0 : Number(date[0]); var month:uint = isEmpty(date[1]) ? 0 : Number(date[1] - 1); var day:uint = isEmpty(date[2]) ? 1 : Number(date[2]); var hour:int = isEmpty(time[0]) ? 0 : Number(time[0]); var minute:uint = isEmpty(time[1]) ? 0 : Number(time[1]); var second:uint = 0; var millisecond:uint = 0; - if(time[2] !== undefined) { + if(time[2] != undefined) { var index:int = time[2].length; var temp:Number; if(time[2].indexOf("+") > -1) { index = time[2].indexOf("+"); } else if(time[2].indexOf("-") > -1) { index = time[2].indexOf("-"); } else if(time[2].indexOf("Z") > -1) { index = time[2].indexOf("Z"); } if(isNaN(index)) { temp = Number(time[2].slice(0, index)); second = Math.floor(temp); millisecond = 1000 * (temp % 1); } if(index != time[2].length) { var offset:String = time[2].slice(index); var userOffset:Number = minutesToHours(new Date(year, month, day).getTimezoneOffset()); switch(offset.charAt(0)) { case "+" : case "-" : hour -= userOffset + Number(offset.slice(0)); break; case "Z" : hour -= userOffset; break; default: } } } return new Date(year, month, day, hour, minute, second, millisecond); } } diff --git a/src/utils/date/timeCode.as b/src/utils/date/timeCode.as index c78d4ce..7feb77b 100644 --- a/src/utils/date/timeCode.as +++ b/src/utils/date/timeCode.as @@ -1,18 +1,18 @@ package utils.date { /** * Utility function for generating time code given a number seconds. * @param sec Seconds * @return Timecode * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function timeCode(sec:Number):String { var h:Number = Math.floor(sec / 3600); var m:Number = Math.floor((sec % 3600) / 60); var s:Number = Math.floor((sec % 3600) % 60); - return (h === 0 ? "" : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + (m < 10 ? "0" + String(m) : String(m)) + ":" + (s < 10 ? "0" + String(s) : String(s)); + return (h == 0 ? "" : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + (m < 10 ? "0" + String(m) : String(m)) + ":" + (s < 10 ? "0" + String(s) : String(s)); } } diff --git a/src/utils/location/getLocationName.as b/src/utils/location/getLocationName.as index d2b0814..c62965a 100644 --- a/src/utils/location/getLocationName.as +++ b/src/utils/location/getLocationName.as @@ -1,50 +1,50 @@ package utils.location { import flash.external.ExternalInterface; /** * Return current location name. * @return Current location name * @author Aaron Clinger * @author Shane McCartney * @author David Nelson * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function getLocationName():String { var out:String; var browserAgent:String; if(isStandAlone()) { out = locationNames.STANDALONE_PLAYER; } else { if(ExternalInterface.available) { // uses external interface to reach out to browser and grab browser useragent info. browserAgent = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); // determines brand of browser using a find index. If not found indexOf returns (-1). // noinspection IfStatementWithTooManyBranchesJS - if(browserAgent !== null && browserAgent.indexOf("Firefox") >= 0) { + if(browserAgent != null && browserAgent.indexOf("Firefox") >= 0) { out = locationNames.BROWSER_FIREFOX; - } else if(browserAgent !== null && browserAgent.indexOf("Safari") >= 0) { + } else if(browserAgent != null && browserAgent.indexOf("Safari") >= 0) { out = locationNames.BROWSER_SAFARI; - } else if(browserAgent !== null && browserAgent.indexOf("MSIE") >= 0) { + } else if(browserAgent != null && browserAgent.indexOf("MSIE") >= 0) { out = locationNames.BROWSER_IE; - } else if(browserAgent !== null && browserAgent.indexOf("Opera") >= 0) { + } else if(browserAgent != null && browserAgent.indexOf("Opera") >= 0) { out = locationNames.BROWSER_OPERA; } else { out = locationNames.BROWSER_UNDEFINED; } } else { // standalone player out = locationNames.BROWSER_UNDEFINED; } } return out; } } diff --git a/src/utils/location/openURL.as b/src/utils/location/openURL.as index bec5279..3863b0c 100644 --- a/src/utils/location/openURL.as +++ b/src/utils/location/openURL.as @@ -1,34 +1,34 @@ package utils.location { import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; /** * Simlifies navigateToURL by allowing you to either use a String or an URLRequest * reference to the URL. This method also helps prevent pop-up blocking by trying to use * openWindow() before calling navigateToURL. * @param request A String or an URLRequest reference to the URL you wish to open/navigate to * @param window Browser window or HTML frame in which to display the URL indicated by the request parameter * @throws Error if you pass a value type other than a String or URLRequest to parameter request. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ public function openURL(request:*, window:String = "_self" /* windowNames.WINDOW_SELF */):void { var r:* = request; if(r is String) { r = new URLRequest(r); } else if(!(r is URLRequest)) { throw new Error("request"); } - if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE() && request._data === null) { + if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE() && request._data == null) { if(openWindow(r.url, window)) return } navigateToURL(r, window); } } diff --git a/src/utils/object/inspect.as b/src/utils/object/inspect.as index 7d1479f..7e410a2 100644 --- a/src/utils/object/inspect.as +++ b/src/utils/object/inspect.as @@ -1,39 +1,39 @@ package utils.object { import flash.utils.describeType; /** * Scan an Object. * @param obj Object to be scanned * @param depth Depth of scanning * @return Scan result */ public function inspect(obj:Object, depth:int = 10, prefix:String = "\t"):String { var scan:Function = function(obj:Object, depth:int, prefix:String):String { var out:String; if(depth < 1) { out = obj is String ? "\"" + obj + "\"" : String(obj); } else { const classDef:XML = describeType(obj); var str:String = ""; for each(var variable:XML in classDef.variable) { str += prefix + variable.@name + " = " + scan(obj[variable.@name], depth - 1, prefix + "\t") + "\n"; } for(var s:String in obj) { str += prefix + s + "=" + scan(obj[s], depth - 1, prefix + "\t") + "\n"; } //noinspection NestedConditionalExpressionJS,NegatedConditionalExpressionJS - out = str == "" ? ((obj !== null) ? (obj is String ? "\"" + obj + "\"" : obj + "") : "null") : ("[" + classDef.@name + "] {\n" + str + (prefix.substr(0, prefix.length - 1)) + "}"); + out = str == "" ? ((obj != null) ? (obj is String ? "\"" + obj + "\"" : obj + "") : "null") : ("[" + classDef.@name + "] {\n" + str + (prefix.substr(0, prefix.length - 1)) + "}"); } return out; }; return prefix + scan(obj, depth, prefix + "\t"); } } diff --git a/src/utils/object/isNull.as b/src/utils/object/isNull.as index 6414a7e..ac93f96 100644 --- a/src/utils/object/isNull.as +++ b/src/utils/object/isNull.as @@ -1,13 +1,11 @@ -package utils.object -{ +package utils.object { /** - Uses the strict equality operator to determine if object is <code>null</code>. + Uses the strict equality operator to determine if object is <code>null</code>. - @param obj: Object to determine if <code>null</code>. - @return Returns <code>true</code> if object is <code>null</code>; otherwise <code>false</code>. + @param obj: Object to determine if <code>null</code>. + @return Returns <code>true</code> if object is <code>null</code>; otherwise <code>false</code>. */ - public function isNull(obj:Object):Boolean - { - return obj === null; + public function isNull(obj:Object):Boolean { + return obj == null; } -} \ No newline at end of file +} diff --git a/src/utils/type/isInterface.as b/src/utils/type/isInterface.as index 1902737..fe80a38 100644 --- a/src/utils/type/isInterface.as +++ b/src/utils/type/isInterface.as @@ -1,13 +1,11 @@ -package utils.type -{ +package utils.type { /** * Returns whether the passed in Class object is an interface. * * @param clazz the class to check * @return true if the clazz is an interface; false if not */ - public function isInterface(clazz:Class):Boolean - { - return (clazz === Object) ? false : (describeType(clazz).factory.extendsClass.length() == 0); + public function isInterface(clazz:Class):Boolean { + return (clazz == Object) ? false : (describeType(clazz).factory.extendsClass.length() == 0); } -} \ No newline at end of file +}
as3/as3-utils
70c5246c4883caf0bbd8e59e5c85973362658a01
added some new drawing shape functions
diff --git a/src/utils/draw/createCircleShape.as b/src/utils/draw/createCircleShape.as new file mode 100644 index 0000000..e397a43 --- /dev/null +++ b/src/utils/draw/createCircleShape.as @@ -0,0 +1,31 @@ +package utils.draw +{ + import flash.display.Graphics; + import flash.display.Shape; + + /** + * Create a shape that is a simple solid color-filled circle + * + * @param r Radius of the circle. + * @param color Color of the circle. Default is black. + * @param alpha Alpha of the circle. Default is full opacity. + * @param x Initial x position + * @param y Initial y position + * @return The created shape + * + * @author Mims Wright + */ + public function createCircleShape (r:Number, color:uint = 0, alpha:Number = 1, x:Number = 0, y:Number = 0):Shape + { + var circle:Shape = new Shape(); + var g:Graphics = circle.graphics; + g.beginFill(color, alpha); + g.drawCircle(0,0,r); + g.endFill(); + + circle.x = x; + circle.y = y; + + return circle; + } +} \ No newline at end of file diff --git a/src/utils/draw/createEllipseShape.as b/src/utils/draw/createEllipseShape.as new file mode 100644 index 0000000..ba150d2 --- /dev/null +++ b/src/utils/draw/createEllipseShape.as @@ -0,0 +1,36 @@ +package utils.draw +{ + import flash.display.Graphics; + import flash.display.Shape; + + /** + * Create a shape that is a simple solid color-filled ellipse + * + * @param w Width of the ellipse. + * @param h Height of the ellipse. + * @param color Color of the ellipse. Default is black. + * @param alpha Alpha of the ellipse. Default is full opacity. + * @param x Initial x position + * @param y Initial y position + * @return The created shape + * + * @author Mims Wright + */ + public function createEllipseShape(w:Number, h:Number = 0, color:uint = 0, alpha:Number = 1, x:Number = 0, y:Number = 0):Shape + { + if (h <= 0) { + h = w; + } + + var ellipse:Shape = new Shape(); + var g:Graphics = ellipse.graphics; + g.beginFill(color, alpha); + g.drawEllipse(0,0,w,h); + g.endFill(); + + ellipse.x = x; + ellipse.y = y; + + return ellipse; + } +} \ No newline at end of file diff --git a/src/utils/draw/createRectangleShape.as b/src/utils/draw/createRectangleShape.as index b3e5605..027ca9f 100644 --- a/src/utils/draw/createRectangleShape.as +++ b/src/utils/draw/createRectangleShape.as @@ -1,26 +1,32 @@ package utils.draw { import flash.display.Graphics; import flash.display.Shape; /** * Create a shape that is a simple solid color-filled rectangle + * * @param width Width of the rectangle * @param height Height of the rectangle - * @param color Color of the rectangle - * @param alpha Alpha of the rectangle + * @param color Color of the rectangle. Default is black. + * @param alpha Alpha of the rectangle. Default is full opacity. + * @param x Initial x position + * @param y Initial y position * @return The created shape - * @author Jackson Dunstan + * @author Jackson Dunstan, modified by Mims Wright */ - public function createRectangleShape(width:uint, height:uint, color:uint, alpha:Number):Shape + public function createRectangleShape(width:uint, height:uint, color:uint = 0, alpha:Number = 1, x:Number = 0, y:Number = 0):Shape { var rect:Shape = new Shape(); var g:Graphics = rect.graphics; g.beginFill(color, alpha); g.drawRect(0, 0, width, height); g.endFill(); + + rect.x = x; + rect.y = y; return rect; } } \ No newline at end of file diff --git a/src/utils/draw/drawWedge.as b/src/utils/draw/drawWedge.as index a49f61b..399090e 100644 --- a/src/utils/draw/drawWedge.as +++ b/src/utils/draw/drawWedge.as @@ -1,58 +1,58 @@ package utils.draw { import flash.display.Graphics; import utils.geom.Ellipse; /** Draws a circular wedge. - @param graphics: The location where drawing should occur. - @param ellipse: An Ellipse object that contains the size and position of the shape. - @param startAngle: The starting angle of wedge in degrees. - @param arc: The sweep of the wedge in degrees. + @param graphics The location where drawing should occur. + @param ellipse An Ellipse object that contains the size and position of the shape. + @param startAngle The starting angle of wedge in degrees. + @param arc The sweep of the wedge in degrees. @usage - <code> + <listing version="3.0"> this.graphics.beginFill(0xFF00FF); DrawUtil.drawWedge(this.graphics, new Ellipse(0, 0, 300, 200), 0, 300); this.graphics.endFill(); - </code> + </listing> */ public function drawWedge(graphics:Graphics, ellipse:Ellipse, startAngle:Number, arc:Number):void { if (Math.abs(arc) >= 360) { graphics.drawEllipse(ellipse.x, ellipse.y, ellipse.width, ellipse.height); return; } startAngle += 90; var radius:Number = ellipse.width * .5; var yRadius:Number = ellipse.height * .5; var x:Number = ellipse.x + radius; var y:Number = ellipse.y + yRadius; var segs:Number = Math.ceil(Math.abs(arc) / 45); var segAngle:Number = -arc / segs; var theta:Number = -(segAngle / 180) * Math.PI; var angle:Number = -(startAngle / 180) * Math.PI; var ax:Number = x + Math.cos(startAngle / 180 * Math.PI) * radius; var ay:Number = y + Math.sin(-startAngle / 180 * Math.PI) * yRadius; var angleMid:Number; graphics.moveTo(x, y); graphics.lineTo(ax, ay); var i:Number = -1; while (++i < segs) { angle += theta; angleMid = angle - (theta * .5); graphics.curveTo(x + Math.cos(angleMid) * (radius / Math.cos(theta * .5)), y + Math.sin(angleMid) * (yRadius / Math.cos(theta * .5)), x + Math.cos(angle) * radius, y + Math.sin(angle) * yRadius); } graphics.lineTo(x, y); } } \ No newline at end of file diff --git a/src/utils/number/isRoughlyEqual.as b/src/utils/number/isRoughlyEqual.as index 882bd23..e09440e 100644 --- a/src/utils/number/isRoughlyEqual.as +++ b/src/utils/number/isRoughlyEqual.as @@ -1,19 +1,19 @@ package utils.number { /** * Returns true if the two numbers are within "maxPercentDifferent" percent of each other. * * @example <listing version='3.0'> - * FuzzyMath.roughlyEqual(0.7, 0.69); // true - * FuzzyMath.roughlyEqual(0.7, 0.5); // false + * isRoughlyEqual(0.7, 0.69); // true + * isRoughlyEqual(0.7, 0.5); // false * - * FuzzyMath.roughlyEqual(123456789, 123450000); // true - * FuzzyMath.roughlyEqual(123456789, 100000000); // false - * FuzzyMath.roughlyEqual(123456789, 100000000, 0.25); // true + * isRoughlyEqual(123456789, 123450000); // true + * isRoughlyEqual(123456789, 100000000); // false + * isRoughlyEqual(123456789, 100000000, 0.25); // true * * </listing> */ public function isRoughlyEqual ( a:Number, b:Number, maxPercentDifferent:Number = 0.10 ):Boolean { return Math.abs((a/b) - 1.0) < maxPercentDifferent; } } \ No newline at end of file
as3/as3-utils
216ca88bbad986cbe3892c8d12f1f0d51c2c94f7
renamed timeRelationships to TimeRelationships. added toggleAMPM
diff --git a/src/utils/date/timeRelationships.as b/src/utils/date/TimeRelationships.as similarity index 97% rename from src/utils/date/timeRelationships.as rename to src/utils/date/TimeRelationships.as index 326dc7b..4592f57 100644 --- a/src/utils/date/timeRelationships.as +++ b/src/utils/date/TimeRelationships.as @@ -1,47 +1,47 @@ package utils.date { - public class timeRelationships + public class TimeRelationships { // // Milliseconds // public static const YEAR_IN_MILLISECONDS:Number = 31536000000.0; public static const THIRTY_ONE_DAY_MONTH_IN_MILLISECONDS:Number = 2678400000.0; public static const THIRTY_DAY_MONTH_IN_MILLISECONDS:Number = 2592000000.0; public static const TWENTY_EIGHT_DAY_MONTH_IN_MILLISECONDS:Number = 2419200000.0; public static const WEEK_IN_MILLISECONDS:Number = 604800000.0; public static const DAY_IN_MILLISECONDS:Number = 86400000.0; public static const HOUR_IN_MILLISECONDS:Number = 3600000.0; public static const MINUTE_IN_MILLISECONDS:Number = 60000.0; // // Seconds // public static const YEAR_IN_SECONDS:Number = 31536000; public static const THIRTY_ONE_DAY_MONTH_IN_SECONDS:Number = 2678400; public static const THIRTY_DAY_MONTH_IN_SECONDS:Number = 2592000; public static const TWENTY_EIGHT_DAY_MONTH_IN_SECONDS:Number = 2419200; public static const WEEK_IN_SECONDS:Number = 604800; public static const DAY_IN_SECONDS:Number = 86400; public static const HOUR_IN_SECONDS:Number = 3600; public static const MINUTE_IN_SECONDS:Number = 60; } } \ No newline at end of file diff --git a/src/utils/date/toggleAMPM.as b/src/utils/date/toggleAMPM.as new file mode 100644 index 0000000..7bf45e5 --- /dev/null +++ b/src/utils/date/toggleAMPM.as @@ -0,0 +1,21 @@ +package utils.date +{ + /** + * If a date is AM, changes it to PM and vice versa. + * + * @author Mims H. Wright + * + * @param date The Date to flip. + * @returns A new date object, 12 hours later or earlier depending. + */ + public function toggleAMPM(date:Date):Date + { + var d:Date = new Date(date.time); + if (getAMPM(date) == "PM") { + d.hours -= 12; + } else { + d.hours += 12; + } + return d; + } +} \ No newline at end of file
as3/as3-utils
bab4496c818bd0ab0282e342ed1eed4eaee29c89
added IDisplayObject
diff --git a/src/utils/display/IDisplayObject.as b/src/utils/display/IDisplayObject.as new file mode 100644 index 0000000..a22f83d --- /dev/null +++ b/src/utils/display/IDisplayObject.as @@ -0,0 +1,26 @@ +package utils.display +{ + import flash.display.DisplayObject; + + /** + * An interface to work around the lack of interface for display objects. + * Especially useful when you want to type a variable with an interface + * and add it to the stage without type casting to DisplayObject each time + * (and running the risk of an error). + * + * @example <listing version="3.0"> + * var d:IDisplayObject = new ClassThatImplementsIDisplayObject(); + * addChild(d.asDisplayObject()); + * </listing> + * + * @author Mims H. Wright + */ + public interface IDisplayObject + { + /** + * Returns a representation of the object as a DisplayObject. + * Usually would return the object itself. + */ + function asDisplayObject():DisplayObject; + } +} \ No newline at end of file
as3/as3-utils
685f04cbae836eab7010619cf9c5b0df13918a56
Added new class TextFieldWrapper. renamed utils.xml.constants to utils.xml.XMLConstants.
diff --git a/src/utils/textField/TextFieldWrapper.as b/src/utils/textField/TextFieldWrapper.as new file mode 100644 index 0000000..ebfcb6f --- /dev/null +++ b/src/utils/textField/TextFieldWrapper.as @@ -0,0 +1,45 @@ +package utils.textField +{ + import flash.display.MovieClip; + import flash.text.TextField; + + /** + * Because TextFields are not MovieClips, you cannot do timeline + * tweens on a TextField in Flash CSx without first making it a child + * of a MovieClip. + * + * This class acts as a base class for creating these types of movieclips + * so you don't need to create a new class for each text field that + * does this. + * + * In the flash library, create a new movieclip symbol containing the + * textField. Make sure you set the instance name for the text field to + * "textField". Make the base class for the symbol + * "util.textfield.TextFieldWrapper". Allow Flash to automatically + * generate the class for you. + * When referencing this MovieClip in your code, use the type + * AbstractTextFieldWrapper insatead of MovieClip. You will be able to set + * the text of the TextField using the .text property. + * + * @author Mims H. Wright + */ + public class TextFieldWrapper extends MovieClip + { + /** + * Direct reference to the text field. + */ + public var textField:TextField; + + /** Passes the text through to the text field. */ + public function set text(text:String):void { + textField.text = text; + } + public function get text():String { + return textField.text; + } + + public function TextFieldWrapper() { + super(); + } + } +} \ No newline at end of file diff --git a/src/utils/xml/constants.as b/src/utils/xml/XMLConstants.as similarity index 92% rename from src/utils/xml/constants.as rename to src/utils/xml/XMLConstants.as index a773bb6..9b1cd32 100644 --- a/src/utils/xml/constants.as +++ b/src/utils/xml/XMLConstants.as @@ -1,56 +1,59 @@ package utils.xml { - public class constants + /** + * Contains references to XML related string constants. + */ + public class XMLConstants { /** * Constant representing a text node type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const TEXT:String = "text"; /** * Constant representing a comment node type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const COMMENT:String = "comment"; /** * Constant representing a processing instruction type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const PROCESSING_INSTRUCTION:String = "processing-instruction"; /** * Constant representing an attribute type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const ATTRIBUTE:String = "attribute"; /** * Constant representing a element type returned from XML.nodeKind. * * @see XML.nodeKind() * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public static const ELEMENT:String = "element"; } } \ No newline at end of file diff --git a/src/utils/xml/isValidXML.as b/src/utils/xml/isValidXML.as index bc369a3..486a87a 100644 --- a/src/utils/xml/isValidXML.as +++ b/src/utils/xml/isValidXML.as @@ -1,29 +1,29 @@ package utils.xml { /** * Checks whether the specified string is valid and well formed XML. * * @param data The string that is being checked to see if it is valid XML. * * @return A Boolean value indicating whether the specified string is * valid XML. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public function isValidXML(data:String):Boolean { var xml:XML; try { xml = new XML(data); } catch (e:Error) { return false; } - return xml.nodeKind() == constants.ELEMENT; + return xml.nodeKind() == XMLConstants.ELEMENT; } } \ No newline at end of file
as3/as3-utils
65ad0e81bd262cd67888e035c9feceb0b487420e
added circular dictionary added stricktIs
diff --git a/src/utils/dictionary/CircularDictionary.as b/src/utils/dictionary/CircularDictionary.as new file mode 100644 index 0000000..fccbe07 --- /dev/null +++ b/src/utils/dictionary/CircularDictionary.as @@ -0,0 +1,76 @@ +package utils.dictionary +{ + import flash.errors.IllegalOperationError; + import flash.utils.Dictionary; + + /** + * A dictionary which allows a pairing of two values to point to each other. + * For example, if you have two objects, A and B, A would point to B and + * B would point to A. + * + * @example <listing version="3.0"> + * var dict:CircularDictionary = new CircularDictionary(); + * dict.addPair(A, B); + * dict.getCounterpartTo(A); // B + * dict.getCounterpartTo(B); // A + * dict.getCounterpartTo(dict.getCounterpartTo(A)); // A + * dict.dictionary[B]; // A. Same as getCounterpartTo(B) + * dict.removePair(B); // removes both A and B. + * </listing> + * + * @author Mims H. Wright + */ + public class CircularDictionary + { + private var _dictionary:Dictionary; + public function get dictionary():Dictionary { return _dictionary; } + + /** + * Constructor. + * + * @param useWeakReferences Indicates whether the internal dictionary should use weak references. + */ + public function CircularDictionary(useWeakReferences:Boolean = false) + { + _dictionary = new Dictionary ( useWeakReferences ); + } + + /** + * Adds a related pair of values. + * + * @throws IllegalOperationError If the same key is added more than once. + * + * @param a The first value (references b) + * @param b The second value (references a) + */ + public function addPair(a:*, b:*):void { + if ( _dictionary[a] == undefined && _dictionary[b] == undefined) { + _dictionary[a] = b; + _dictionary[b] = a; + return; + } + throw new IllegalOperationError ("You cannot use the same key or value more than once."); + } + + /** + * Removes a related pair of values. + * + * @param aOrB Either value, a or b. Both references to each other are removed. + * @returns The counterpart to whatever value you provided. + */ + public function removePair (aOrB:*):* { + var counterpart:* = _dictionary[aOrB]; + delete _dictionary[aOrB]; + delete _dictionary[counterpart]; + return counterpart; + } + + /** + * Returns the corresponding value to the key you provided. If key = a, + * returns b, and vice versa. + */ + public function getCounterpartTo(key:*):* { + return _dictionary[key]; + } + } +} \ No newline at end of file diff --git a/src/utils/type/strictIs.as b/src/utils/type/strictIs.as new file mode 100755 index 0000000..fc47c90 --- /dev/null +++ b/src/utils/type/strictIs.as @@ -0,0 +1,29 @@ +package utils.type +{ + import flash.utils.*; + + /** + * Checks the class of <code>instance</code> against the <code>compareClass</code> for strict + * equality. If the classes are exactly the same, returns true. If + * the classes are different even if the <code>instance</code>'s class is a subclass + * of <code>compareClass</code>, it returns false. + * Does not work with interfaces. The compareClass must be a class. + * + * @author Mims Wright + * + * @example <listing version="3.0"> + * var myBase:BaseClass = new BaseClass(); + * var mySub:SubClass = new SubClass(); + * trace(strictIs(myBase, BaseClass)); // true + * trace(strictIs(mySub, SubClass)); // true + * trace(strictIs(mySub, BaseClass)); // false + * </listing> + * + * @param instance - the object whos class you want to check. + * @param compareClass - the class to compare your object against. + * @return true if instance is strictly of type compareClass. + */ + public function strictIs(instance:Object, compareClass:Class):Boolean { + return compareClass == Class(instance.constructor); + } +} \ No newline at end of file
as3/as3-utils
79ac310b15fa6b7059a311cfa084c4b10a74fbb4
Added isRoughlyEqual()
diff --git a/.gitignore b/.gitignore index 8a0c108..0bce7cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,10 @@ target bin bin-debug bin-release -*.iml \ No newline at end of file +*.iml +.actionScriptProperties +.flexLibProperties +.project +.settings/ +.DS_Store \ No newline at end of file diff --git a/src/utils/number/isRoughlyEqual.as b/src/utils/number/isRoughlyEqual.as new file mode 100644 index 0000000..882bd23 --- /dev/null +++ b/src/utils/number/isRoughlyEqual.as @@ -0,0 +1,19 @@ +package utils.number { + + /** + * Returns true if the two numbers are within "maxPercentDifferent" percent of each other. + * + * @example <listing version='3.0'> + * FuzzyMath.roughlyEqual(0.7, 0.69); // true + * FuzzyMath.roughlyEqual(0.7, 0.5); // false + * + * FuzzyMath.roughlyEqual(123456789, 123450000); // true + * FuzzyMath.roughlyEqual(123456789, 100000000); // false + * FuzzyMath.roughlyEqual(123456789, 100000000, 0.25); // true + * + * </listing> + */ + public function isRoughlyEqual ( a:Number, b:Number, maxPercentDifferent:Number = 0.10 ):Boolean { + return Math.abs((a/b) - 1.0) < maxPercentDifferent; + } +} \ No newline at end of file
as3/as3-utils
3374510c48cac1478d8c4c06b0177fdce96a832b
fixed example text
diff --git a/src/utils/number/max.as b/src/utils/number/max.as index 7a2879e..6f1e9cc 100644 --- a/src/utils/number/max.as +++ b/src/utils/number/max.as @@ -1,29 +1,29 @@ package utils.number { /** Evaluates <code>val1</code> and <code>val2</code> and returns the larger value. Unlike <code>Math.max</code> this method will return the defined value if the other value is <code>null</code> or not a number. @param val1: A value to compare. @param val2: A value to compare. @return Returns the largest value, or the value out of the two that is defined and valid. @example <code> - trace(NumberUtil.max(-5, null)); // Traces -5 - trace(NumberUtil.max(-5, "CASA")); // Traces -5 - trace(NumberUtil.max(-5, -13)); // Traces -5 + trace(max(-5, null)); // Traces -5 + trace(max(-5, "CASA")); // Traces -5 + trace(max(-5, -13)); // Traces -5 </code> */ public function max(val1:*, val2:*):Number { if (isNaN(val1) && isNaN(val2) || val1 == null && val2 == null) return NaN; if (val1 == null || val2 == null) return (val2 == null) ? val1 : val2; if (isNaN(val1) || isNaN(val2)) return (isNaN(val2)) ? val1 : val2; return Math.max(val1, val2); } } \ No newline at end of file diff --git a/src/utils/number/min.as b/src/utils/number/min.as index 64fc1f7..050745a 100644 --- a/src/utils/number/min.as +++ b/src/utils/number/min.as @@ -1,29 +1,29 @@ package utils.number { /** Evaluates <code>val1</code> and <code>val2</code> and returns the smaller value. Unlike <code>Math.min</code> this method will return the defined value if the other value is <code>null</code> or not a number. @param val1: A value to compare. @param val2: A value to compare. @return Returns the smallest value, or the value out of the two that is defined and valid. @example <code> - trace(NumberUtil.min(5, null)); // Traces 5 - trace(NumberUtil.min(5, "CASA")); // Traces 5 - trace(NumberUtil.min(5, 13)); // Traces 5 + trace(min(5, null)); // Traces 5 + trace(min(5, "CASA")); // Traces 5 + trace(min(5, 13)); // Traces 5 </code> */ public function min(val1:*, val2:*):Number { if (isNaN(val1) && isNaN(val2) || val1 == null && val2 == null) return NaN; if (val1 == null || val2 == null) return (val2 == null) ? val1 : val2; if (isNaN(val1) || isNaN(val2)) return isNaN(val2) ? val1 : val2; return Math.min(val1, val2); } } \ No newline at end of file
as3/as3-utils
c7d9bd3f13e380545651450e273d5d56e8903d8e
Few API changes in new utils caused by refactoring from older Utilitaris libraries (no getters)
diff --git a/src/utils/location/getLocationName.as b/src/utils/location/getLocationName.as index 64d27fb..d2b0814 100644 --- a/src/utils/location/getLocationName.as +++ b/src/utils/location/getLocationName.as @@ -1,52 +1,50 @@ package utils.location { import flash.external.ExternalInterface; - import flash.net.URLRequest; - import flash.net.navigateToURL; /** * Return current location name. * @return Current location name * @author Aaron Clinger * @author Shane McCartney * @author David Nelson * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function getLocationName():String { var out:String; var browserAgent:String; - if(isStandAlone) { + if(isStandAlone()) { out = locationNames.STANDALONE_PLAYER; } else { if(ExternalInterface.available) { // uses external interface to reach out to browser and grab browser useragent info. browserAgent = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); // determines brand of browser using a find index. If not found indexOf returns (-1). // noinspection IfStatementWithTooManyBranchesJS if(browserAgent !== null && browserAgent.indexOf("Firefox") >= 0) { out = locationNames.BROWSER_FIREFOX; } else if(browserAgent !== null && browserAgent.indexOf("Safari") >= 0) { out = locationNames.BROWSER_SAFARI; } else if(browserAgent !== null && browserAgent.indexOf("MSIE") >= 0) { out = locationNames.BROWSER_IE; } else if(browserAgent !== null && browserAgent.indexOf("Opera") >= 0) { out = locationNames.BROWSER_OPERA; } else { out = locationNames.BROWSER_UNDEFINED; } } else { // standalone player out = locationNames.BROWSER_UNDEFINED; } } return out; } } diff --git a/src/utils/location/isAirApplication.as b/src/utils/location/isAirApplication.as index 564017c..c6b6371 100644 --- a/src/utils/location/isAirApplication.as +++ b/src/utils/location/isAirApplication.as @@ -1,16 +1,16 @@ package utils.location { import flash.system.Capabilities; /** * Determines if the runtime environment is an Air application. * @return true if the runtime environment is an Air application * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ - public function get isAirApplication():Boolean { + public function isAirApplication():Boolean { return Capabilities.playerType == "Desktop"; } } diff --git a/src/utils/location/isIDE.as b/src/utils/location/isIDE.as index 3945c4d..06a83a6 100644 --- a/src/utils/location/isIDE.as +++ b/src/utils/location/isIDE.as @@ -1,16 +1,16 @@ package utils.location { import flash.system.Capabilities; /** * Determines if the SWF is running in the IDE. * @return true if SWF is running in the Flash Player version used by the external player or test movie mode * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ - public function get isIDE():Boolean { + public function isIDE():Boolean { return Capabilities.playerType == "External"; } } diff --git a/src/utils/location/isPlugin.as b/src/utils/location/isPlugin.as index 83b09cf..8f3c03a 100644 --- a/src/utils/location/isPlugin.as +++ b/src/utils/location/isPlugin.as @@ -1,16 +1,16 @@ package utils.location { import flash.system.Capabilities; /** * Determines if the SWF is running in a browser plug-in. * @return true if SWF is running in the Flash Player browser plug-in * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ - public function get isPlugin():Boolean { + public function isPlugin():Boolean { return Capabilities.playerType == "PlugIn" || Capabilities.playerType == "ActiveX"; } } diff --git a/src/utils/location/isStandAlone.as b/src/utils/location/isStandAlone.as index 02f5ac4..6c3ffc2 100644 --- a/src/utils/location/isStandAlone.as +++ b/src/utils/location/isStandAlone.as @@ -1,16 +1,16 @@ package utils.location { import flash.system.Capabilities; /** * Determines if the SWF is running in the StandAlone player. * @return true if SWF is running in the Flash StandAlone Player * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ - public function get isStandAlone():Boolean { + public function isStandAlone():Boolean { return Capabilities.playerType == "StandAlone"; } } diff --git a/src/utils/location/openURL.as b/src/utils/location/openURL.as index 5a11496..bec5279 100644 --- a/src/utils/location/openURL.as +++ b/src/utils/location/openURL.as @@ -1,34 +1,34 @@ package utils.location { import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; /** * Simlifies navigateToURL by allowing you to either use a String or an URLRequest * reference to the URL. This method also helps prevent pop-up blocking by trying to use * openWindow() before calling navigateToURL. * @param request A String or an URLRequest reference to the URL you wish to open/navigate to * @param window Browser window or HTML frame in which to display the URL indicated by the request parameter * @throws Error if you pass a value type other than a String or URLRequest to parameter request. * @author Aaron Clinger * @author Shane McCartney * @author David Nelson */ - public function openURL(request:*, window:String = windowNames.WINDOW_SELF):void { + public function openURL(request:*, window:String = "_self" /* windowNames.WINDOW_SELF */):void { var r:* = request; if(r is String) { r = new URLRequest(r); } else if(!(r is URLRequest)) { throw new Error("request"); } - if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE && request._data === null) { + if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE() && request._data === null) { if(openWindow(r.url, window)) return } navigateToURL(r, window); } }
as3/as3-utils
bc190e734400d69b62b0cc9aaa493e470de827b6
cropBitmapData(), scheduleForNextFrame() and traceChildren()
diff --git a/src/utils/display/cropBitmapData.as b/src/utils/display/cropBitmapData.as new file mode 100644 index 0000000..6457186 --- /dev/null +++ b/src/utils/display/cropBitmapData.as @@ -0,0 +1,23 @@ +package utils.display { + import flash.display.BitmapData; + import flash.geom.Point; + import flash.geom.Rectangle; + + + + /** + * Crop the BitmapData source and return a new BitmapData. + * @param source Source BitmapData + * @param dest Crop area as Rectangle + * @return Cropped source as BitmapData + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function cropBitmapData(source:BitmapData, dest:Rectangle):BitmapData { + var o:BitmapData = new BitmapData(dest.width, dest.height); + var point:Point = new Point(0, 0); + + o.copyPixels(source, dest, point); + + return o; + } +} diff --git a/src/utils/display/scheduleForNextFrame.as b/src/utils/display/scheduleForNextFrame.as new file mode 100644 index 0000000..b6707f1 --- /dev/null +++ b/src/utils/display/scheduleForNextFrame.as @@ -0,0 +1,21 @@ +package utils.display { + import flash.display.Shape; + import flash.events.Event; + + + + /** + * Wait for a next frame. + * Prevents high CPU state, when AVM doesn't send ENTER_FRAMES. It just simply waits until it gets one. + * @param callback Function to call once when next frame is displayed + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function scheduleForNextFrame(callback:Function):void { + var obj:Shape = new Shape(); + + obj.addEventListener(Event.ENTER_FRAME, function(ev:Event):void { + obj.removeEventListener(Event.ENTER_FRAME, arguments.callee); + callback(); + }); + } +} diff --git a/src/utils/display/traceChildren.as b/src/utils/display/traceChildren.as new file mode 100644 index 0000000..c82628d --- /dev/null +++ b/src/utils/display/traceChildren.as @@ -0,0 +1,27 @@ +package utils.display { + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + + + + /** + * trace() children of the DisplayObjectContainer. + * @param container DisplayObjectContainer to get children of + * @param indentLevel Indetnation level (default 0) + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function traceChildren(container:DisplayObjectContainer, indentLevel:int = 0):void { + for(var i:int = 0; i < container.numChildren; i++) { + var thisChild:DisplayObject = container.getChildAt(i); + var output:String = ""; + + for(var j:int = 0; j < indentLevel; j++) output += " "; + + output += "+ " + thisChild.name + " = " + String(thisChild); + + trace(output); + + if(thisChild is DisplayObjectContainer) traceChildren(DisplayObjectContainer(thisChild), indentLevel + 1); + } + } +}
as3/as3-utils
f4ef8a745f83a293287702920cd319d3f761716f
truncate2()
diff --git a/src/utils/string/truncate2.as b/src/utils/string/truncate2.as new file mode 100644 index 0000000..38454f1 --- /dev/null +++ b/src/utils/string/truncate2.as @@ -0,0 +1,36 @@ +package utils.string { + + + + /** + * Returns a String truncated to a specified length with optional suffix. + * @param value Input String + * @param length Length the String should be shortend to + * @param suffix (optional, default="...") String to append to the end of the truncated String + * @returns String String truncated to a specified length with optional suffix + */ + public function truncate2(value:String, length:uint, suffix:String = "..."):String { + var out:String = ""; + var l:uint = length; + + if(value) { + l -= suffix.length; + + var trunc:String = value; + + if(trunc.length > l) { + trunc = trunc.substr(0, l); + + if(/[^\s]/.test(value.charAt(l))) { + trunc = rtrim(trunc.replace(/\w+$|\s+$/, "")); + } + + trunc += suffix; + } + + out = trunc; + } + + return out; + } +}
as3/as3-utils
cd4fc57a7cf7456c4dc5c3d4587726eda54e7f5a
new String utils
diff --git a/src/utils/string/padLeft.as b/src/utils/string/padLeft.as new file mode 100644 index 0000000..3d9fb2c --- /dev/null +++ b/src/utils/string/padLeft.as @@ -0,0 +1,24 @@ +package utils.string { + + + + /** + * Pads value with specified padChar character to a specified length from the left. + * @param value Input String + * @param padChar Character for pad + * @param length Length to pad to + * @returns Padded String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function padLeft(value:String, padChar:String, length:uint):String { + var s:String = value; + + while(s.length < length) { + s = padChar + s; + } + + return s; + } +} diff --git a/src/utils/string/padRight.as b/src/utils/string/padRight.as new file mode 100644 index 0000000..fc64644 --- /dev/null +++ b/src/utils/string/padRight.as @@ -0,0 +1,24 @@ +package utils.string { + + + + /** + * Pads value with specified padChar character to a specified length from the right. + * @param value Input String + * @param padChar Character for pad + * @param length Length to pad to + * @returns Padded String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function padRight(value:String, padChar:String, length:uint):String { + var s:String = value; + + while(s.length < length) { + s += padChar; + } + + return s; + } +} diff --git a/src/utils/string/properCase.as b/src/utils/string/properCase.as new file mode 100644 index 0000000..5697b38 --- /dev/null +++ b/src/utils/string/properCase.as @@ -0,0 +1,24 @@ +package utils.string { + + + + /** + * Properly cases the String in "sentence format". + * @param value Input String + * @returns Cased String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function properCase(value:String):String { + var out:String = ""; + + if(value) { + var str:String = value.toLowerCase().replace(/\b([^.?;!]+)/, capitalize); + + out = str.replace(/\b[i]\b/, "I"); + } + + return out; + } +} diff --git a/src/utils/string/randomSequence.as b/src/utils/string/randomSequence.as new file mode 100644 index 0000000..4276224 --- /dev/null +++ b/src/utils/string/randomSequence.as @@ -0,0 +1,16 @@ +package utils.string { + import utils.number.randomIntegerWithinRange; + + + + /** + * Get random sentence. + * @param maxLength Max chars + * @param minLength Min chars + * @return Random sentence + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function randomSequence(maxLength:uint = 50, minLength:uint = 10):String { + return randomCharacters(randomIntegerWithinRange(minLength, maxLength), " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + } +} diff --git a/src/utils/string/removeExtraWhitespace.as b/src/utils/string/removeExtraWhitespace.as new file mode 100644 index 0000000..82704f5 --- /dev/null +++ b/src/utils/string/removeExtraWhitespace.as @@ -0,0 +1,21 @@ +package utils.string { + + + + /** + * Removes extraneous whitespace (extra spaces, tabs, line breaks, etc) from the specified String. + * @param value String whose extraneous whitespace will be removed + * @returns Output String + */ + public function removeExtraWhitespace(value:String):String { + var out:String = ""; + + if(value) { + var str:String = trim(value); + + out = str.replace(/\s+/g, " "); + } + + return out; + } +} diff --git a/src/utils/string/repeat.as b/src/utils/string/repeat.as new file mode 100644 index 0000000..4441479 --- /dev/null +++ b/src/utils/string/repeat.as @@ -0,0 +1,8 @@ +package utils.string { + + + + public function repeat(n:uint, str:String = " "):String { + return new Array(n + 1).join(str); + } +} diff --git a/src/utils/string/reverse.as b/src/utils/string/reverse.as new file mode 100644 index 0000000..4e19678 --- /dev/null +++ b/src/utils/string/reverse.as @@ -0,0 +1,22 @@ +package utils.string { + + + + /** + * Returns the specified String in reverse character order. + * @param value String that will be reversed + * @returns Output String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function reverse(value:String):String { + var out:String = ""; + + if(value) { + out = value.split("").reverse().join(""); + } + + return out; + } +} diff --git a/src/utils/string/reverseWords.as b/src/utils/string/reverseWords.as new file mode 100644 index 0000000..d81c318 --- /dev/null +++ b/src/utils/string/reverseWords.as @@ -0,0 +1,22 @@ +package utils.string { + + + + /** + * Returns the specified String in reverse word order. + * @param value String that will be reversed + * @returns Output String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function reverseWords(value:String):String { + var out:String = ""; + + if(value) { + out = value.split(/\s+/).reverse().join(""); + } + + return out; + } +} diff --git a/src/utils/string/similarity.as b/src/utils/string/similarity.as new file mode 100644 index 0000000..be9ecc2 --- /dev/null +++ b/src/utils/string/similarity.as @@ -0,0 +1,25 @@ +package utils.string { + + + + /** + * Determines the percentage of similiarity, based on editDistance. + * @param value Input String + * @param tgt Target String + * @returns Percentage of similiarity, based on editDistance + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function similarity(value:String, tgt:String):Number { + var out:Number = 100; + var ed:uint = editDistance(value, tgt); + var maxLen:uint = Math.max(value.length, tgt.length); + + if(maxLen !== 0) { + out = (1 - ed / maxLen) * 100; + } + + return out; + } +} diff --git a/src/utils/string/wordCount.as b/src/utils/string/wordCount.as new file mode 100644 index 0000000..57faf65 --- /dev/null +++ b/src/utils/string/wordCount.as @@ -0,0 +1,22 @@ +package utils.string { + + + + /** + * Determins the number of words in a String. + * @param value Input String + * @returns Number of words in a String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function wordCount(value:String):uint { + var out:uint = 0; + + if(value) { + out = value.match(/\b\w+\b/g).length; + } + + return out; + } +}
as3/as3-utils
68d7eb4f03172e3ba9b277c55facfcf289e737ee
randomCharacters() optimization
diff --git a/src/utils/string/randomCharacters.as b/src/utils/string/randomCharacters.as index 17aa00b..f30c720 100644 --- a/src/utils/string/randomCharacters.as +++ b/src/utils/string/randomCharacters.as @@ -1,13 +1,24 @@ -package utils.string -{ +package utils.string { + + + /** - * Generate a set of random characters. + * Generate a random String. + * @param amount String length (default 10) + * @param charSet Chars used (default "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + * @return Random String */ - public function randomCharacters(amount:Number):String - { - var str:String = ""; - for (var i:int = 0; i < amount; i++) - str += String.fromCharCode(Math.round(Math.random() * (126 - 33)) + 33); - return str; + public function randomCharacters(amount:Number, charSet:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):String { + var alphabet:Array = charSet.split(""); + var alphabetLength:int = alphabet.length; + var randomLetters:String = ""; + + for(var j:uint = 0; j < amount; j++) { + var r:Number = Math.random() * alphabetLength; + var s:int = Math.floor(r); + randomLetters += alphabet[s]; + } + + return randomLetters; } -} \ No newline at end of file +}
as3/as3-utils
efeb9db80d755aaef374176df5889bb7a0677cf8
trim(), ltrim() and rtrim() optimizations
diff --git a/src/utils/string/ltrim.as b/src/utils/string/ltrim.as index 11cedcd..a9cc2f3 100644 --- a/src/utils/string/ltrim.as +++ b/src/utils/string/ltrim.as @@ -1,26 +1,25 @@ -package utils.string -{ +package utils.string { + + + /** * Removes whitespace from the front of the specified string. * - * @param input The String whose beginning whitespace will will be removed. + * @param value The String whose beginning whitespace will will be removed. * * @returns A String with whitespace removed from the begining * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function ltrim(input:String):String - { - var size:Number = input.length; - for (var i:Number = 0; i < size; i++) - { - if (input.charCodeAt(i) > 32) - { - return input.substring(i); - } + public function ltrim(value:String):String { + var out:String = ""; + + if(value) { + out = value.replace(/^\s+/, ""); } - return ""; + + return out; } -} \ No newline at end of file +} diff --git a/src/utils/string/rtrim.as b/src/utils/string/rtrim.as index 195522b..2b26f2c 100644 --- a/src/utils/string/rtrim.as +++ b/src/utils/string/rtrim.as @@ -1,27 +1,25 @@ -package utils.string -{ +package utils.string { + + + /** * Removes whitespace from the end of the specified string. * - * @param input The String whose ending whitespace will will be removed. + * @param value The String whose ending whitespace will will be removed. * * @returns A String with whitespace removed from the end * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function rtrim(input:String):String - { - var size:Number = input.length; - for (var i:Number = size; i > 0; i--) - { - if (input.charCodeAt(i - 1) > 32) - { - return input.substring(0, i); - } + public function rtrim(value:String):String { + var out:String = ""; + + if(value) { + out = value.replace(/\s+$/, ""); } - return ""; + return out; } -} \ No newline at end of file +} diff --git a/src/utils/string/trim.as b/src/utils/string/trim.as index cad3c06..dffe9b0 100644 --- a/src/utils/string/trim.as +++ b/src/utils/string/trim.as @@ -1,20 +1,27 @@ -package utils.string -{ +package utils.string { + + + /** * Removes whitespace from the front and the end of the specified * string. * - * @param input The String whose beginning and ending whitespace will + * @param value The String whose beginning and ending whitespace will * will be removed. * * @returns A String with whitespace removed from the begining and end * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * @tiptext */ - public function trim(input:String):String - { - return ltrim(rtrim(input)); + public function trim(value:String):String { + var out:String = ""; + + if(value) { + out = value.replace(/^\s+|\s+$/g, ""); + } + + return out; } -} \ No newline at end of file +}
as3/as3-utils
d0e2488d5b2081a6a0bba0a4deac60fecd7a738f
New String utils
diff --git a/src/utils/string/afterFirst.as b/src/utils/string/afterFirst.as new file mode 100644 index 0000000..e970a8e --- /dev/null +++ b/src/utils/string/afterFirst.as @@ -0,0 +1,28 @@ +package utils.string { + + + + /** + * Returns everything after the first occurrence of the provided character in the String. + * @param value Input String + * @param ch Character or sub-string + * @returns Output String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function afterFirst(value:String, ch:String):String { + var out:String = ""; + + if(value) { + var idx:int = value.indexOf(ch); + + if(idx != -1) { + idx += ch.length; + out = value.substr(idx); + } + } + + return out; + } +} diff --git a/src/utils/string/afterLast.as b/src/utils/string/afterLast.as new file mode 100644 index 0000000..a00ce82 --- /dev/null +++ b/src/utils/string/afterLast.as @@ -0,0 +1,28 @@ +package utils.string { + + + + /** + * Returns everything after the last occurence of the provided character in value. + * @param value Input String + * @param ch Character or sub-string + * @return Output String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function afterLast(value:String, ch:String):String { + var out:String = ""; + + if(value) { + var idx:int = value.lastIndexOf(ch); + + if(idx != -1) { + idx += ch.length; + out = value.substr(idx); + } + } + + return out; + } +} diff --git a/src/utils/string/arrayList.as b/src/utils/string/arrayList.as new file mode 100644 index 0000000..5369cfd --- /dev/null +++ b/src/utils/string/arrayList.as @@ -0,0 +1,22 @@ +package utils.string { + + + + /** + * Convert an Array to a list. + * @param a Input Array + * @return List as "item1, item2, item3" + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function arrayList(a:Array):String { + var out:String = ""; + + for each(var i:String in a) { + out += i + ", "; + } + + return out.substr(0, out.length - 2); + } +} diff --git a/src/utils/string/beforeFirst.as b/src/utils/string/beforeFirst.as new file mode 100644 index 0000000..c7f17c9 --- /dev/null +++ b/src/utils/string/beforeFirst.as @@ -0,0 +1,27 @@ +package utils.string { + + + + /** + * Returns everything before the first occurrence of the provided character in the String. + * @param value Input String + * @param ch Character or sub-string + * @returns Everything before the first occurence of the provided character in the String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function beforeFirst(value:String, ch:String):String { + var out:String = ""; + + if(value) { + var idx:int = value.indexOf(ch); + + if(idx != -1) { + out = value.substr(0, idx); + } + } + + return out; + } +} diff --git a/src/utils/string/beforeLast.as b/src/utils/string/beforeLast.as new file mode 100644 index 0000000..f251189 --- /dev/null +++ b/src/utils/string/beforeLast.as @@ -0,0 +1,27 @@ +package utils.string { + + + + /** + * Returns everything before the last occurrence of the provided character in the String. + * @param value Input String + * @param ch Character or sub-string + * @returns Everything before the last occurrence of the provided character in the String + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function beforeLast(value:String, ch:String):String { + var out:String = ""; + + if(value) { + var idx:int = value.lastIndexOf(ch); + + if(idx != -1) { + out = value.substr(0, idx); + } + } + + return out; + } +} diff --git a/src/utils/string/between.as b/src/utils/string/between.as new file mode 100644 index 0000000..e46df6b --- /dev/null +++ b/src/utils/string/between.as @@ -0,0 +1,34 @@ +package utils.string { + + + + /** + * Returns everything after the first occurance of begin and before the first occurrence of end in String. + * @param value Input String + * @param start Character or sub-string to use as the start index + * @param end Character or sub-string to use as the end index + * @returns Everything after the first occurance of begin and before the first occurrence of end in String. + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function between(value:String, start:String, end:String):String { + var out:String = ""; + + if(value) { + var startIdx:int = value.indexOf(start); + + if(startIdx != -1) { + startIdx += start.length; // RM: should we support multiple chars? (or ++startIdx); + + var endIdx:int = value.indexOf(end, startIdx); + + if(endIdx != -1) { + out = value.substr(startIdx, endIdx - startIdx); + } + } + } + + return out; + } +} diff --git a/src/utils/string/convertBytesString.as b/src/utils/string/convertBytesString.as new file mode 100644 index 0000000..d936562 --- /dev/null +++ b/src/utils/string/convertBytesString.as @@ -0,0 +1,15 @@ +package utils.string { + import utils.conversion.bytesToKilobytes; + + + + /** + * Convert bytes to a String ("X B" or "X kB") + * @param value Bytes count + * @return Result String + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function convertBytesString(value:uint):String { + return (value <= 8192 ? (String(value) + " B") : (String(bytesToKilobytes(value)) + " kB")); + } +} diff --git a/src/utils/string/humanizeTime.as b/src/utils/string/humanizeTime.as new file mode 100644 index 0000000..ac09870 --- /dev/null +++ b/src/utils/string/humanizeTime.as @@ -0,0 +1,55 @@ +package utils.string { + + + + /** + * Convert seconds to a humanized String. + * @param seconds Seconds + * @return Humanized String + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function humanizeTime(seconds:uint, formatSeconds:String = "|:?=%d seconds|:1=jednu second", + formatMinutes:String = "|:?=%d minutes|:1=%d minute", formatHours:String = "|:?=%d hours|:1=%d hour", + formatDays:String = "|:?=%d days|:1=%d day"):String { + var days:int = int(seconds / 86400); + var hours:int = int((seconds - days * 86400) / 3600); + var minutes:int = int(((seconds - days * 86400) - hours * 3600) / 60); + var secondsTrimmed:int = seconds - (days * 86400) - (hours * 3600) - (minutes * 60); + + var out:String; + + if(!out && seconds < 60) { + // less than a minute + out = convertCounterString(formatSeconds, seconds); + } + + if(!out && seconds < 60 * 60) { + // minute to one hour + if(seconds % 60 === 0) { + out = convertCounterString(formatMinutes, minutes); + } else { + out = convertCounterString(formatMinutes, minutes) + ", " + convertCounterString(formatSeconds, secondsTrimmed); + } + } + + if(!out && seconds < 60 * 60 * 24) { + // hour to a day + if(minutes % 60 === 0) { + out = convertCounterString(formatHours, hours); + } else { + out = convertCounterString(formatHours, hours) + ", " + convertCounterString(formatMinutes, minutes); + } + } + + if(!out) { + // days + if(hours % 24 === 0) { + out = convertCounterString(formatDays, days); + } else { + out = convertCounterString(formatDays, days) + ", " + convertCounterString(formatHours, hours); + } + } + + return out; + } +}
as3/as3-utils
6e62f25607ff079ee4633c1d5dfb65175d1fac80
New ratio utils
diff --git a/src/utils/ratio/defineRect.as b/src/utils/ratio/defineRect.as new file mode 100644 index 0000000..ef700bd --- /dev/null +++ b/src/utils/ratio/defineRect.as @@ -0,0 +1,14 @@ +package utils.ratio { + import flash.geom.Rectangle; + + + + public function defineRect(size:Rectangle, width:Number, height:Number, snapToPixel:Boolean):Rectangle { + var scaled:Rectangle = size.clone(); + + scaled.width = snapToPixel ? int(width) : width; + scaled.height = snapToPixel ? int(height) : height; + + return scaled; + } +} diff --git a/src/utils/ratio/heightToWidth.as b/src/utils/ratio/heightToWidth.as new file mode 100644 index 0000000..7e4d4cd --- /dev/null +++ b/src/utils/ratio/heightToWidth.as @@ -0,0 +1,16 @@ +package utils.ratio { + import flash.geom.Rectangle; + + + + /** + * Determines the ratio of height to width. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function heightToWidth(rect:Rectangle):Number { + return rect.height / rect.width; + } +} diff --git a/src/utils/ratio/scale.as b/src/utils/ratio/scale.as new file mode 100644 index 0000000..0f13f55 --- /dev/null +++ b/src/utils/ratio/scale.as @@ -0,0 +1,20 @@ +package utils.ratio { + import flash.geom.Rectangle; + + import utils.math.Percent; + + + + /** + * Scales an area's width and height while preserving aspect ratio. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @param amount Amount you wish to scale by + * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function scale(rect:Rectangle, amount:Percent, snapToPixel:Boolean = true):Rectangle { + return defineRect(rect, rect.width * amount.decimalPercentage, rect.height * amount.decimalPercentage, snapToPixel); + } +} diff --git a/src/utils/ratio/scaleHeight.as b/src/utils/ratio/scaleHeight.as new file mode 100644 index 0000000..c7b66ed --- /dev/null +++ b/src/utils/ratio/scaleHeight.as @@ -0,0 +1,20 @@ +package utils.ratio { + import flash.geom.Rectangle; + + import utils.math.Percent; + + + + /** + * Scales the height of an area while preserving aspect ratio. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @param width Width to scale to + * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function scaleHeight(rect:Rectangle, width:Number, snapToPixel:Boolean = true):Rectangle { + return defineRect(rect, width, width * heightToWidth(rect), snapToPixel); + } +} diff --git a/src/utils/ratio/scaleToFill.as b/src/utils/ratio/scaleToFill.as new file mode 100644 index 0000000..e4e74df --- /dev/null +++ b/src/utils/ratio/scaleToFill.as @@ -0,0 +1,24 @@ +package utils.ratio { + import flash.geom.Rectangle; + + import utils.math.Percent; + + + + /** + * Resizes an area to fill the bounding area while preserving aspect ratio. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @param bounds Area to fill - the Rectangle's x and y values are ignored + * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function scaleToFill(rect:Rectangle, bounds:Rectangle, snapToPixel:Boolean = true):Rectangle { + var scaled:Rectangle = scaleHeight(rect, bounds.width, snapToPixel); + + if(scaled.height < bounds.height) scaled = scaleWidth(rect, bounds.height, snapToPixel); + + return scaled; + } +} diff --git a/src/utils/ratio/scaleToFit.as b/src/utils/ratio/scaleToFit.as new file mode 100644 index 0000000..5497972 --- /dev/null +++ b/src/utils/ratio/scaleToFit.as @@ -0,0 +1,24 @@ +package utils.ratio { + import flash.geom.Rectangle; + + import utils.math.Percent; + + + + /** + * Resizes an area to the maximum size of a bounding area without exceeding while preserving aspect ratio. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @param bounds Area the rectangle needs to fit within - the Rectangle's x and y values are ignored + * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function scaleToFit(rect:Rectangle, bounds:Rectangle, snapToPixel:Boolean = true):Rectangle { + var scaled:Rectangle = scaleHeight(rect, bounds.width, snapToPixel); + + if(scaled.height > bounds.height) scaled = scaleWidth(rect, bounds.height, snapToPixel); + + return scaled; + } +} diff --git a/src/utils/ratio/scaleWidth.as b/src/utils/ratio/scaleWidth.as new file mode 100644 index 0000000..b4381aa --- /dev/null +++ b/src/utils/ratio/scaleWidth.as @@ -0,0 +1,20 @@ +package utils.ratio { + import flash.geom.Rectangle; + + import utils.math.Percent; + + + + /** + * Scales the width of an area while preserving aspect ratio. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @param height Height to scale to + * @param snapToPixel true to force the scale to whole pixels, or false to allow sub-pixels + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function scaleWidth(rect:Rectangle, height:Number, snapToPixel:Boolean = true):Rectangle { + return defineRect(rect, height * widthToHeight(rect), height, snapToPixel); + } +} diff --git a/src/utils/ratio/widthToHeight.as b/src/utils/ratio/widthToHeight.as new file mode 100644 index 0000000..d490894 --- /dev/null +++ b/src/utils/ratio/widthToHeight.as @@ -0,0 +1,16 @@ +package utils.ratio { + import flash.geom.Rectangle; + + + + /** + * Determines the ratio of width to height. + * @param rect Area's width and height expressed as a Rectangle - the Rectangle's x and y values are ignored + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function widthToHeight(rect:Rectangle):Number { + return rect.width / rect.height; + } +}
as3/as3-utils
d9851e71a03ae950113e2a4953025a10c2c3a22c
inspect() now uses tabs to display tree structure
diff --git a/src/utils/object/inspect.as b/src/utils/object/inspect.as index 6222e6a..7d1479f 100644 --- a/src/utils/object/inspect.as +++ b/src/utils/object/inspect.as @@ -1,34 +1,39 @@ -package utils.object -{ +package utils.object { import flash.utils.describeType; - public function inspect(obj:Object, depth:int = 2):String - { - var scan:Function = function(obj:Object, depth:int, prefix:String):String - { - if (depth < 1) - return String(obj); - const classDef:XML = describeType(obj); + /** + * Scan an Object. + * @param obj Object to be scanned + * @param depth Depth of scanning + * @return Scan result + */ + public function inspect(obj:Object, depth:int = 10, prefix:String = "\t"):String { + var scan:Function = function(obj:Object, depth:int, prefix:String):String { + var out:String; + + if(depth < 1) { + out = obj is String ? "\"" + obj + "\"" : String(obj); + } else { + const classDef:XML = describeType(obj); var str:String = ""; - for each (var variable:XML in classDef.variable) - { - str += prefix + variable.@name + " : " + scan(obj[variable.@name], depth - 1, prefix + "\t") + "\n"; - } - /*for each(var accessor:XML in classDef.accessor.(@access == "readwrite" || @access == "readonly")) - { - str += prefix + accessor.@name + " : " + scan(obj[accessor.@name], depth - 1, prefix + "\t") + "\n"; - }*/ + for each(var variable:XML in classDef.variable) { + str += prefix + variable.@name + " = " + scan(obj[variable.@name], depth - 1, prefix + "\t") + "\n"; + } - for (var s:Object in obj) - { - str += prefix + s + " = " + scan(obj[s], depth - 1, prefix + "\t") + "\n"; + for(var s:String in obj) { + str += prefix + s + "=" + scan(obj[s], depth - 1, prefix + "\t") + "\n"; } - return str != "" ? ("[" + classDef.@name + "] {\n" + str + prefix + "}\n") : ((obj != null) ? obj + "" : "null"); - }; - return scan(obj, depth, ""); + //noinspection NestedConditionalExpressionJS,NegatedConditionalExpressionJS + out = str == "" ? ((obj !== null) ? (obj is String ? "\"" + obj + "\"" : obj + "") : "null") : ("[" + classDef.@name + "] {\n" + str + (prefix.substr(0, prefix.length - 1)) + "}"); + } + + return out; + }; + + return prefix + scan(obj, depth, prefix + "\t"); } -} \ No newline at end of file +}
as3/as3-utils
b8dcdb732940cfd1165b1290eb39247093375135
New object utils
diff --git a/src/utils/object/contains.as b/src/utils/object/contains.as new file mode 100644 index 0000000..31a143c --- /dev/null +++ b/src/utils/object/contains.as @@ -0,0 +1,25 @@ +package utils.object { + + + + /** + * Searches the first level properties of an Object for a another Object. + * @param obj Object to search in. + * @param member Object to search for. + * @return true if Object was found + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function contains(obj:Object, member:Object):Boolean { + var out:Boolean; + + for(var prop:String in obj) { + if(obj[prop] == member) { + out = true; + } + } + + return out; + } +}
as3/as3-utils
4b7a6752184e6c00d6da05a144d2b02b3ff16834
New random utils
diff --git a/src/utils/number/fastMax2.as b/src/utils/number/fastMax2.as new file mode 100644 index 0000000..0c6cfe9 --- /dev/null +++ b/src/utils/number/fastMax2.as @@ -0,0 +1,16 @@ +package utils.number { + + + + /** + * Get fast max for two numbers. + * @param val1 Number A + * @param val2 Number B + * @return Max + * @author Jackson Dunstan (http://jacksondunstan.com/articles/445) + */ + public function fastMax2(val1:Number, val2:Number):Number { + if((!(val1 <= 0) && !(val1 > 0)) || (!(val2 <= 0) && !(val2 > 0))) return NaN; + return val1 > val2 ? val1 : val2; + } +} diff --git a/src/utils/number/fastMin2.as b/src/utils/number/fastMin2.as new file mode 100644 index 0000000..a39c5b1 --- /dev/null +++ b/src/utils/number/fastMin2.as @@ -0,0 +1,16 @@ +package utils.number { + + + + /** + * Get fast min for two numbers. + * @param val1 Number A + * @param val2 Number B + * @return Min + * @author Jackson Dunstan (http://jacksondunstan.com/articles/445) + */ + public function fastMin2(val1:Number, val2:Number):Number { + if((!(val1 <= 0) && !(val1 > 0)) || (!(val2 <= 0) && !(val2 > 0))) return NaN; + return val1 < val2 ? val1 : val2; + } +} diff --git a/src/utils/number/isNegative.as b/src/utils/number/isNegative.as new file mode 100644 index 0000000..9dbb4aa --- /dev/null +++ b/src/utils/number/isNegative.as @@ -0,0 +1,16 @@ +package utils.number { + + + + /** + * Determines whether or not the supplied Number is negative. + * @param value Number to evaluate + * @return Whether or not the supplied Number is negative + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function isNegative(value:Number):Boolean { + return !isPositive(value); + } +} diff --git a/src/utils/number/isPositive.as b/src/utils/number/isPositive.as new file mode 100644 index 0000000..8f327c6 --- /dev/null +++ b/src/utils/number/isPositive.as @@ -0,0 +1,16 @@ +package utils.number { + + + + /** + * Determines whether or not the supplied Number is positive. + * @param value Number to evaluate + * @return Whether or not the supplied Number is positive + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function isPositive(value:Number):Boolean { + return Boolean(value >= 0); + } +} diff --git a/src/utils/number/randomBoolean.as b/src/utils/number/randomBoolean.as new file mode 100644 index 0000000..5f062e1 --- /dev/null +++ b/src/utils/number/randomBoolean.as @@ -0,0 +1,24 @@ +package utils.number { + + + + /** + * Returns a Boolean. + * Example code: + * <pre> + * RandomUtils.boolean(); // returns true or false (50% chance of true) + * </pre> + * Another example code: + * <pre> + * RandomUtils.boolean(0.8); // returns true or false (80% chance of true) + * </pre> + * @param chance Chance Number (0-1) + * @return Float Number between min-max exclusive. + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function randomBoolean(chance:Number = 0.5):Boolean { + return(Math.random() < chance); + } +} diff --git a/src/utils/number/randomSign.as b/src/utils/number/randomSign.as new file mode 100644 index 0000000..dd68ba4 --- /dev/null +++ b/src/utils/number/randomSign.as @@ -0,0 +1,24 @@ +package utils.number { + + + + /** + * Returns an int: -1 or 1. + * Example code: + * <pre> + * RandomUtils.sign(); // returns 1 or -1 (50% chance of 1) + * </pre> + * Another example code: + * <pre> + * RandomUtils.sign(0.8); // returns 1 or -1 (80% chance of 1) + * </pre> + * @param chance Chance Number (0-1) + * @return int: -1 or 1. + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function randomSign(chance:Number = 0.5):int { + return(Math.random() < chance) ? 1 : -1; + } +}
as3/as3-utils
6e899653a074d4a447cc00bbba36b67b6263d95f
New location utils
diff --git a/src/utils/location/getDomain.as b/src/utils/location/getDomain.as new file mode 100644 index 0000000..f9bb6e6 --- /dev/null +++ b/src/utils/location/getDomain.as @@ -0,0 +1,24 @@ +package utils.location { + import flash.display.DisplayObject; + + + + /** + * Detects MovieClip's domain location. + * Function does not return folder path or file name. The method also treats "www" and sans "www" as the same; if "www" is present method does not return it. + * Example code: + * <pre> + * trace(getDomain(_root)); + * </pre> + * @param location MovieClip to get location of + * @return Full domain (including sub-domains) of MovieClip's location + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function getDomain(location:DisplayObject):String { + var baseUrl:String = location.loaderInfo.url.split("://")[1].split("/")[0]; + return (baseUrl.substr(0, 4) == "www.") ? baseUrl.substr(4) : baseUrl; + } +} diff --git a/src/utils/location/getLocationName.as b/src/utils/location/getLocationName.as new file mode 100644 index 0000000..64d27fb --- /dev/null +++ b/src/utils/location/getLocationName.as @@ -0,0 +1,52 @@ +package utils.location { + import flash.external.ExternalInterface; + import flash.net.URLRequest; + import flash.net.navigateToURL; + + + + /** + * Return current location name. + * @return Current location name + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function getLocationName():String { + var out:String; + var browserAgent:String; + + if(isStandAlone) { + out = locationNames.STANDALONE_PLAYER; + } + + else { + if(ExternalInterface.available) { + // uses external interface to reach out to browser and grab browser useragent info. + browserAgent = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); + + // determines brand of browser using a find index. If not found indexOf returns (-1). + // noinspection IfStatementWithTooManyBranchesJS + if(browserAgent !== null && browserAgent.indexOf("Firefox") >= 0) { + out = locationNames.BROWSER_FIREFOX; + } else if(browserAgent !== null && browserAgent.indexOf("Safari") >= 0) { + out = locationNames.BROWSER_SAFARI; + } else if(browserAgent !== null && browserAgent.indexOf("MSIE") >= 0) { + out = locationNames.BROWSER_IE; + } else if(browserAgent !== null && browserAgent.indexOf("Opera") >= 0) { + out = locationNames.BROWSER_OPERA; + } else { + out = locationNames.BROWSER_UNDEFINED; + } + } + + else { + // standalone player + out = locationNames.BROWSER_UNDEFINED; + } + } + + return out; + } +} diff --git a/src/utils/location/isAirApplication.as b/src/utils/location/isAirApplication.as new file mode 100644 index 0000000..564017c --- /dev/null +++ b/src/utils/location/isAirApplication.as @@ -0,0 +1,16 @@ +package utils.location { + import flash.system.Capabilities; + + + + /** + * Determines if the runtime environment is an Air application. + * @return true if the runtime environment is an Air application + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function get isAirApplication():Boolean { + return Capabilities.playerType == "Desktop"; + } +} diff --git a/src/utils/location/isDomain.as b/src/utils/location/isDomain.as new file mode 100644 index 0000000..2a0e7ee --- /dev/null +++ b/src/utils/location/isDomain.as @@ -0,0 +1,27 @@ +package utils.location { + import flash.display.DisplayObject; + + + + /** + * Detects if MovieClip's embed location matches passed domain. + * Check for domain: + * <pre> + * trace(isDomain(_root, "google.com")); + * trace(isDomain(_root, "bbc.co.uk")); + * </pre> + * You can even check for subdomains: + * <pre> + * trace(isDomain(_root, "subdomain.aaronclinger.com")) + * </pre> + * @param location MovieClip to compare location of + * @param domain Web domain + * @return true if file's embed location matched passed domain + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function isDomain(location:DisplayObject, domain:String):Boolean { + return getDomain(location).slice(-domain.length) == domain; + } +} diff --git a/src/utils/location/isIDE.as b/src/utils/location/isIDE.as new file mode 100644 index 0000000..3945c4d --- /dev/null +++ b/src/utils/location/isIDE.as @@ -0,0 +1,16 @@ +package utils.location { + import flash.system.Capabilities; + + + + /** + * Determines if the SWF is running in the IDE. + * @return true if SWF is running in the Flash Player version used by the external player or test movie mode + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function get isIDE():Boolean { + return Capabilities.playerType == "External"; + } +} diff --git a/src/utils/location/isPlugin.as b/src/utils/location/isPlugin.as new file mode 100644 index 0000000..83b09cf --- /dev/null +++ b/src/utils/location/isPlugin.as @@ -0,0 +1,16 @@ +package utils.location { + import flash.system.Capabilities; + + + + /** + * Determines if the SWF is running in a browser plug-in. + * @return true if SWF is running in the Flash Player browser plug-in + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function get isPlugin():Boolean { + return Capabilities.playerType == "PlugIn" || Capabilities.playerType == "ActiveX"; + } +} diff --git a/src/utils/location/isStandAlone.as b/src/utils/location/isStandAlone.as new file mode 100644 index 0000000..02f5ac4 --- /dev/null +++ b/src/utils/location/isStandAlone.as @@ -0,0 +1,16 @@ +package utils.location { + import flash.system.Capabilities; + + + + /** + * Determines if the SWF is running in the StandAlone player. + * @return true if SWF is running in the Flash StandAlone Player + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function get isStandAlone():Boolean { + return Capabilities.playerType == "StandAlone"; + } +} diff --git a/src/utils/location/isWeb.as b/src/utils/location/isWeb.as new file mode 100644 index 0000000..1430c3e --- /dev/null +++ b/src/utils/location/isWeb.as @@ -0,0 +1,21 @@ +package utils.location { + import flash.display.DisplayObject; + + + + /** + * Determines if the SWF is being served on the internet. + * Example code: + * <pre> + * trace(isWeb(_root)); + * </pre> + * @param location DisplayObject to get location of + * @return true if SWF is being served on the internet + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function isWeb(location:DisplayObject):Boolean { + return location.loaderInfo.url.substr(0, 4) == "http"; + } +} diff --git a/src/utils/location/locationNames.as b/src/utils/location/locationNames.as new file mode 100644 index 0000000..9e3022a --- /dev/null +++ b/src/utils/location/locationNames.as @@ -0,0 +1,25 @@ +package utils.location { + public class locationNames { + + + /** Firefox */ + public static const BROWSER_FIREFOX:String = "browserFirefox"; + + /** Safari */ + public static const BROWSER_SAFARI:String = "browserSafari"; + + /** Internet Explorer */ + public static const BROWSER_IE:String = "browserIE"; + + /** Opera */ + public static const BROWSER_OPERA:String = "browserOpera"; + + /** Undefined browser */ + public static const BROWSER_UNDEFINED:String = "browserUndefined"; + + /** Standalone player */ + public static const STANDALONE_PLAYER:String = "standalonePlayer"; + + + } +} diff --git a/src/utils/location/openURL.as b/src/utils/location/openURL.as new file mode 100644 index 0000000..5a11496 --- /dev/null +++ b/src/utils/location/openURL.as @@ -0,0 +1,34 @@ +package utils.location { + import flash.external.ExternalInterface; + import flash.net.URLRequest; + import flash.net.navigateToURL; + + + + /** + * Simlifies navigateToURL by allowing you to either use a String or an URLRequest + * reference to the URL. This method also helps prevent pop-up blocking by trying to use + * openWindow() before calling navigateToURL. + * @param request A String or an URLRequest reference to the URL you wish to open/navigate to + * @param window Browser window or HTML frame in which to display the URL indicated by the request parameter + * @throws Error if you pass a value type other than a String or URLRequest to parameter request. + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson + */ + public function openURL(request:*, window:String = windowNames.WINDOW_SELF):void { + var r:* = request; + + if(r is String) { + r = new URLRequest(r); + } else if(!(r is URLRequest)) { + throw new Error("request"); + } + + if(window == windowNames.WINDOW_BLANK && ExternalInterface.available && !isIDE && request._data === null) { + if(openWindow(r.url, window)) return + } + + navigateToURL(r, window); + } +} diff --git a/src/utils/location/openWindow.as b/src/utils/location/openWindow.as new file mode 100644 index 0000000..83e9d4b --- /dev/null +++ b/src/utils/location/openWindow.as @@ -0,0 +1,38 @@ +package utils.location { + import flash.external.ExternalInterface; + import flash.net.URLRequest; + import flash.net.navigateToURL; + + + + /** + * Open a new browser window and prevent browser from blocking it. + * Based on script by Sergey Kovalyov (http://skovalyov.blogspot.com/2007/01/how-to-prevent-pop-up-blocking-in.html) + * Based on script by Jason the Saj (http://thesaj.wordpress.com/2008/02/12/the-nightmare-that-is-_blank-part-ii-help) + * Original: http://apdevblog.com/problems-using-navigatetourl + * You also have to set the wmode inside your containing html file to "opaque" and the allowScriptAccess to "always". + * @param url url to be opened + * @param window Window target + * @param features Additional features for window.open function + * @author Sergey Kovalyov + * @author Jason the Saj + * @author Aron Woost (<a href="http://apdevblog.com">apdevblog.com</a>) + * @author Philipp Kyeck (<a href="http://apdevblog.com">apdevblog.com</a>) + */ + public function openWindow(url:String, window:String = "_blank", features:String = ""):void { + switch(getLocationName()) { + case locationNames.BROWSER_FIREFOX: + ExternalInterface.call("window.open", url, window, features); + break; + + case locationNames.BROWSER_IE: + ExternalInterface.call("function setWMWindow() {window.open('" + url + "');}"); + break; + + default: + // otherwise, use Flash's native 'navigateToURL()' function to pop-window. + // this is necessary because Safari 3 no longer works with the above ExternalInterface work-a-round. + navigateToURL(new URLRequest(url), window); + } + } +} diff --git a/src/utils/location/windowNames.as b/src/utils/location/windowNames.as new file mode 100644 index 0000000..9065519 --- /dev/null +++ b/src/utils/location/windowNames.as @@ -0,0 +1,12 @@ +package utils.location { + public class windowNames { + + + public static const WINDOW_SELF:String = "_self"; + public static const WINDOW_BLANK:String = "_blank"; + public static const WINDOW_PARENT:String = "_parent"; + public static const WINDOW_TOP:String = "_top"; + + + } +}
as3/as3-utils
80c6eb7350a714399932136de4d11a5309273502
New JS utils
diff --git a/src/utils/js/callJSFunction.as b/src/utils/js/callJSFunction.as new file mode 100644 index 0000000..f57086b --- /dev/null +++ b/src/utils/js/callJSFunction.as @@ -0,0 +1,40 @@ +package utils.js { + import flash.external.ExternalInterface; + + + + /** + * Call a JS function. + * @param func Name of the function to be called + * @param arg1 Argument 1 + * @param arg2 Argument 2 + * @param arg3 Argument 3 + * @param arg4 Argument 4 + * @throws Error if empty function name supplied + * @throws Error if SecurityError occured + * @throws Error if Error occured + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) + */ + public function callJSFunction(func:String, arg1:* = null, arg2:* = null, arg3:* = null, arg4:* = null):void { + if(func == "") { + throw new Error("A valid function argument must be supplied"); + } + + // track avea if a type is supplied + if(ExternalInterface.available) { + try { + ExternalInterface.call(func, arg1, arg2, arg3, arg4); + } + catch(error:SecurityError) { + throw new Error(func + " request failed. A SecurityError occurred: " + error.message + "\n"); + } + catch (error:Error) { + throw new Error(func + " request failed. An Error occurred: " + error.message + "\n"); + } + } + + else { + throw new Error(func + " request Failed. External interface is not available for this container. If you're trying to use it locally, try using it through an HTTP address."); + } + } +}
as3/as3-utils
0e87696c406e33db272900436843fe7138101648
Docs update
diff --git a/src/utils/date/formatDate.as b/src/utils/date/formatDate.as index e106d32..cca4465 100644 --- a/src/utils/date/formatDate.as +++ b/src/utils/date/formatDate.as @@ -1,406 +1,409 @@ package utils.date { import utils.conversion.minutesToSeconds; import utils.number.addLeadingZero; import utils.number.format; import utils.number.getOrdinalSuffix; /** * Formats a Date object for display. Acts almost identically to the PHP date() function. * You can prevent a recognized character in the format string from being expanded by escaping it with a preceding ^. * <table border="1"> * <tr> * <th style="width:150px;">Format character</th> * <th>Description</th> * <th style="width:200px;">Example returned values</th> * </tr> * <tr> * <td>d</td> * <td>Day of the month, 2 digits with leading zeros.</td> * <td>01 to 31</td> * </tr> * <tr> * <td>D</td> * <td>A textual representation of a day, three letters.</td> * <td>Mon through Sun</td> * </tr> * <tr> * <td>j</td> * <td>Day of the month without leading zeros.</td> * <td>1 to 31</td> * </tr> * <tr> * <td>l</td> * <td>A full textual representation of the day of the week.</td> * <td>Sunday through Saturday</td> * </tr> * <tr> * <td>N</td> * <td>ISO-8601 numeric representation of the day of the week.</td> * <td>1 (for Monday) through 7 (for Sunday)</td> * </tr> * <tr> * <td>S</td> * <td>English ordinal suffix for the day of the month, 2 characters.</td> * <td>st, nd, rd or th</td> * </tr> * <tr> * <td>w</td> * <td>Numeric representation of the day of the week.</td> * <td>0 (for Sunday) through 6 (for Saturday)</td> * </tr> * <tr> * <td>z</td> * <td>The day of the year (starting from 0).</td> * <td>0 through 365</td> * </tr> * <tr> * <td>W</td> * <td>ISO-8601 week number of year, weeks starting on Monday.</td> * <td>Example: 42 (the 42nd week in the year)</td> * </tr> * <tr> * <td>F</td> * <td>A full textual representation of a month, such as January or March.</td> * <td>January through December</td> * </tr> * <tr> * <td>m</td> * <td>Numeric representation of a month, with leading zeros.</td> * <td>01 through 12</td> * </tr> * <tr> * <td>M</td> * <td>A short textual representation of a month, three letters.</td> * <td>Jan through Dec</td> * </tr> * <tr> * <td>n</td> * <td>Numeric representation of a month, without leading zeros.</td> * <td>1 through 12</td> * </tr> * <tr> * <td>t</td> * <td>Number of days in the given month.</td> * <td>28 through 31</td> * </tr> * <tr> * <td>L</td> * <td>Determines if it is a leap year.</td> * <td>1 if it is a leap year, 0 otherwise</td> * </tr> * <tr> * <td>o or Y</td> * <td>A full numeric representation of a year, 4 digits.</td> * <td>Examples: 1999 or 2003</td> * </tr> * <tr> * <td>y</td> * <td>A two digit representation of a year.</td> * <td>Examples: 99 or 03</td> * </tr> * <tr> * <td>a</td> * <td>Lowercase Ante meridiem and Post meridiem.</td> * <td>am or pm</td> * </tr> * <tr> * <td>A</td> * <td>Uppercase Ante meridiem and Post meridiem.</td> * <td>AM or PM</td> * </tr> * <tr> * <td>B</td> * <td>Swatch Internet time.</td> * <td>000 through 999</td> * </tr> * <tr> * <td>g</td> * <td>12-hour format of an hour without leading zeros.</td> * <td>1 through 12</td> * </tr> * <tr> * <td>G</td> * <td>24-hour format of an hour without leading zeros.</td> * <td>0 through 23</td> * </tr> * <tr> * <td>h</td> * <td>12-hour format of an hour with leading zeros.</td> * <td>01 through 12</td> * </tr> * <tr> * <td>H</td> * <td>24-hour format of an hour with leading zeros.</td> * <td>00 through 23</td> * </tr> * <tr> * <td>i</td> * <td>Minutes with leading zeros.</td> * <td>00 to 59</td> * </tr> * <tr> * <td>s</td> * <td>Seconds, with leading zeros.</td> * <td>00 through 59</td> * </tr> * <tr> * <td>I</td> * <td>Determines if the date is in daylight saving time.</td> * <td>1 if Daylight Saving Time, 0 otherwise</td> * </tr> * <tr> * <td>O</td> * <td>Difference to coordinated universal time (UTC) in hours.</td> * <td>Example: +0200</td> * </tr> * <tr> * <td>P</td> * <td>Difference to Greenwich time (GMT/UTC) in hours with colon between hours and minutes.</td> * <td>Example: +02:00</td> * </tr> * <tr> * <td>e or T</td> * <td>Timezone abbreviation.</td> * <td>Examples: EST, MDT</td> * </tr> * <tr> * <td>Z</td> * <td>Timezone offset in seconds.</td> * <td>-43200 through 50400</td> * </tr> * <tr> * <td>c</td> * <td>ISO 8601 date.</td> * <td>2004-02-12T15:19:21+00:00</td> * </tr> * <tr> * <td>r</td> * <td>RFC 2822 formatted date.</td> * <td>Example: Thu, 21 Dec 2000 16:01:07 +0200</td> * </tr> * <tr> * <td>U</td> * <td>Seconds since the Unix Epoch.</td> * <td>Example: 1171479314</td> * </tr> * </table> * Example code: * <pre> * trace(DateUtils.formatDate(new Date(), "l ^t^h^e dS ^of F Y h:i:s A")); * </pre> * @param dateToFormat Date object you wish to format * @param formatString Format of the outputted date String. See the format characters options above. + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson */ public function formatDate(dateToFormat:Date, formatString:String):String { var out:String = ""; var c:String; var i:int = -1; var l:uint = formatString.length; var t:Number; while(++i < l) { c = formatString.substr(i, 1); if(c == "^") { out += formatString.substr(++i, 1); } else { switch(c) { case "d" : // Day of the month, 2 digits with leading zeros out += addLeadingZero(dateToFormat.getDate()); break; case "D" : // A textual representation of a day, three letters out += getDayAbbrName(dateToFormat.getDay()); break; case "j" : // Day of the month without leading zeros out += String(dateToFormat.getDate()); break; case "l" : // A full textual representation of the day of the week out += getDayAsString(dateToFormat.getDay()); break; case "N" : // ISO-8601 numeric representation of the day of the week t = dateToFormat.getDay(); if(t == 0) t = 7; out += String(t); break; case "S" : // English ordinal suffix for the day of the month, 2 characters out += getOrdinalSuffix(dateToFormat.getDate()); break; case "w" : // Numeric representation of the day of the week out += String(dateToFormat.getDay()); break; case "z" : // The day of the year (starting from 0) out += String(addLeadingZero(getDayOfTheYear(dateToFormat))); break; case "W" : // ISO-8601 week number of year, weeks starting on Monday out += String(addLeadingZero(getWeekOfTheYear(dateToFormat))); break; case "F" : // A full textual representation of a month, such as January or March out += getMonthName(dateToFormat.getMonth()); break; case "m" : // Numeric representation of a month, with leading zeros out += addLeadingZero(dateToFormat.getMonth() + 1); break; case "M" : // A short textual representation of a month, three letters out += getMonthAbbrName(dateToFormat.getMonth()); break; case "n" : // Numeric representation of a month, without leading zeros out += String((dateToFormat.getMonth() + 1)); break; case "t" : // Number of days in the given month out += String(getDaysInMonth(dateToFormat.getMonth(), dateToFormat.getFullYear())); break; case "L" : // Whether it is a leap year out += (isLeapYear(dateToFormat.getFullYear())) ? "1" : "0"; break; case "o" : case "Y" : // A full numeric representation of a year, 4 digits out += String(dateToFormat.getFullYear()); break; case "y" : // A two digit representation of a year out += String(dateToFormat.getFullYear()).substr(-2); break; case "a" : // Lowercase Ante meridiem and Post meridiem out += getMeridiem(dateToFormat.getHours()).toLowerCase(); break; case "A" : // Uppercase Ante meridiem and Post meridiem out += getMeridiem(dateToFormat.getHours()); break; case "B" : // Swatch Internet time out += format(getInternetTime(dateToFormat), 3, null, "0"); break; case "g" : // 12-hour format of an hour without leading zeros t = dateToFormat.getHours(); if(t == 0) { t = 12; } else if(t > 12) { t -= 12; } out += String(t); break; case "G" : // 24-hour format of an hour without leading zeros out += String(dateToFormat.getHours()); break; case "h" : // 12-hour format of an hour with leading zeros t = dateToFormat.getHours() + 1; if(t == 0) { t = 12; } else if(t > 12) { t -= 12; } out += addLeadingZero(t); break; case "H" : // 24-hour format of an hour with leading zeros out += addLeadingZero(dateToFormat.getHours()); break; case "i" : // Minutes with leading zeros out += addLeadingZero(dateToFormat.getMinutes()); break; case "s" : // Seconds, with leading zeros out += addLeadingZero(dateToFormat.getSeconds()); break; case "I" : // Whether or not the date is in daylights savings time out += (isDaylightSavings(dateToFormat)) ? "1" : "0"; break; case "O" : // Difference to Greenwich time (GMT/UTC) in hours out += getFormattedDifferenceFromUTC(dateToFormat); break; case "P" : out += getFormattedDifferenceFromUTC(dateToFormat, ":"); break; case "e" : case "T" : // Timezone identifier out += getTimezone(dateToFormat); break; case "Z" : // Timezone offset (GMT/UTC) in seconds. out += String(int(minutesToSeconds(dateToFormat.getTimezoneOffset()))); break; case "c" : // ISO 8601 date out += dateToFormat.getFullYear() + "-" + addLeadingZero(dateToFormat.getMonth() + 1) + "-" + addLeadingZero(dateToFormat.getDate()) + "T" + addLeadingZero(dateToFormat.getHours()) + ":" + addLeadingZero(dateToFormat.getMinutes()) + ":" + addLeadingZero(dateToFormat.getSeconds()) + getFormattedDifferenceFromUTC(dateToFormat, ":"); break; case "r" : // RFC 2822 formatted date out += getDayAbbrName(dateToFormat.getDay()) + ", " + dateToFormat.getDate() + " " + getMonthAbbrName(dateToFormat.getMonth()) + " " + dateToFormat.getFullYear() + " " + addLeadingZero(dateToFormat.getHours()) + ":" + addLeadingZero(dateToFormat.getMinutes()) + ":" + addLeadingZero(dateToFormat.getSeconds()) + " " + getFormattedDifferenceFromUTC(dateToFormat); break; case "U" : // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) t = int(dateToFormat.getTime() / 1000); out += String(t); break; default : out += formatString.substr(i, 1); } } } return out; } } diff --git a/src/utils/date/iso8601ToDate.as b/src/utils/date/iso8601ToDate.as index d39e7ae..db96137 100644 --- a/src/utils/date/iso8601ToDate.as +++ b/src/utils/date/iso8601ToDate.as @@ -1,68 +1,71 @@ package utils.date { import utils.conversion.minutesToHours; import utils.object.isEmpty; /** * Converts W3C ISO 8601 date String into a Date object. * Example code: * <pre> * trace(iso8601ToDate("1994-11-05T08:15:30-05:00").toString()); * </pre> * @param iso8601 Valid ISO 8601 formatted String * @return Date object of the specified date and time of the ISO 8601 String in universal time * @see <a href="http://www.w3.org/TR/NOTE-datetime">W3C ISO 8601 specification</a> + * @author Aaron Clinger + * @author Shane McCartney + * @author David Nelson */ public function iso8601ToDate(iso8601:String):Date { var parts:Array = iso8601.toUpperCase().split("T"); var date:Array = parts[0].split("-"); var time:Array = (parts.length <= 1) ? [] : parts[1].split(":"); var year:uint = isEmpty(date[0]) ? 0 : Number(date[0]); var month:uint = isEmpty(date[1]) ? 0 : Number(date[1] - 1); var day:uint = isEmpty(date[2]) ? 1 : Number(date[2]); var hour:int = isEmpty(time[0]) ? 0 : Number(time[0]); var minute:uint = isEmpty(time[1]) ? 0 : Number(time[1]); var second:uint = 0; var millisecond:uint = 0; if(time[2] !== undefined) { var index:int = time[2].length; var temp:Number; if(time[2].indexOf("+") > -1) { index = time[2].indexOf("+"); } else if(time[2].indexOf("-") > -1) { index = time[2].indexOf("-"); } else if(time[2].indexOf("Z") > -1) { index = time[2].indexOf("Z"); } if(isNaN(index)) { temp = Number(time[2].slice(0, index)); second = Math.floor(temp); millisecond = 1000 * (temp % 1); } if(index != time[2].length) { var offset:String = time[2].slice(index); var userOffset:Number = minutesToHours(new Date(year, month, day).getTimezoneOffset()); switch(offset.charAt(0)) { case "+" : case "-" : hour -= userOffset + Number(offset.slice(0)); break; case "Z" : hour -= userOffset; break; default: } } } return new Date(year, month, day, hour, minute, second, millisecond); } } diff --git a/src/utils/date/timeCode.as b/src/utils/date/timeCode.as index 31617ea..c78d4ce 100644 --- a/src/utils/date/timeCode.as +++ b/src/utils/date/timeCode.as @@ -1,18 +1,18 @@ package utils.date { /** * Utility function for generating time code given a number seconds. * @param sec Seconds * @return Timecode + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function timeCode(sec:Number):String { var h:Number = Math.floor(sec / 3600); var m:Number = Math.floor((sec % 3600) / 60); var s:Number = Math.floor((sec % 3600) % 60); - //noinspection NestedConditionalExpressionJS return (h === 0 ? "" : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + (m < 10 ? "0" + String(m) : String(m)) + ":" + (s < 10 ? "0" + String(s) : String(s)); } } diff --git a/src/utils/geom/simplifyAngle.as b/src/utils/geom/simplifyAngle.as index 13b9cda..911af54 100644 --- a/src/utils/geom/simplifyAngle.as +++ b/src/utils/geom/simplifyAngle.as @@ -1,20 +1,21 @@ package utils.geom { /** * Simplifys the supplied angle to its simpliest representation. * Example code: * <pre> * var simpAngle:Number = simplifyAngle(725); // returns 5 * var simpAngle2:Number = simplifyAngle(-725); // returns -5 * </pre> * @param value Angle to simplify * @return Supplied angle simplified + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function simplifyAngle(value:Number):Number { var _rotations:Number = Math.floor(value / 360); return (value >= 0) ? value - (360 * _rotations) : value + (360 * _rotations); } } diff --git a/src/utils/geom/trimAngle.as b/src/utils/geom/trimAngle.as index 083680a..5ace1aa 100644 --- a/src/utils/geom/trimAngle.as +++ b/src/utils/geom/trimAngle.as @@ -1,22 +1,23 @@ package utils.geom { /** * Trims the supplied angle to its 0..360 representation. * Example code: * <pre> * var simpAngle:Number = trimAngle(725); // returns 5 * </pre> * @param value Angle to trim * @return Supplied angle trimmed + * @author Vaclav Vancura (<a href="http://vancura.org">vancura.org</a>, <a href="http://twitter.com/vancura">@vancura</a>) */ public function trimAngle(value:Number):Number { var a:Number = value; while(a < 0) a += 360; while(a > 360) a -= 360; return a; } }
as3/as3-utils
28b01cdb6f0b45ea7e609d722235921056664d8e
New geom utils
diff --git a/src/utils/geom/getRectangleCenter.as b/src/utils/geom/getRectangleCenter.as new file mode 100644 index 0000000..cb781ca --- /dev/null +++ b/src/utils/geom/getRectangleCenter.as @@ -0,0 +1,14 @@ +package utils.geom { + import flash.geom.Point; + import flash.geom.Rectangle; + + + + /** + * Calculates center Point of a Rectangle. + * @param value Rectangle to determine center Point of + */ + public function getRectangleCenter(value:Rectangle):Point { + return new Point(value.x + (value.width / 2), value.y + (value.height / 2)); + } +} diff --git a/src/utils/geom/reverseRectangle.as b/src/utils/geom/reverseRectangle.as new file mode 100644 index 0000000..2af2f0e --- /dev/null +++ b/src/utils/geom/reverseRectangle.as @@ -0,0 +1,14 @@ +package utils.geom { + import flash.geom.Rectangle; + + + + /** + * Reverse a rectangle. + * @param value Source rectangle + * @return Reversed rectangle + */ + public function reverseRectangle(value:Rectangle):Rectangle { + return new Rectangle(value.left, value.top, -value.width, -value.height); + } +} diff --git a/src/utils/geom/roundPoint.as b/src/utils/geom/roundPoint.as new file mode 100644 index 0000000..ee91837 --- /dev/null +++ b/src/utils/geom/roundPoint.as @@ -0,0 +1,14 @@ +package utils.geom { + import flash.geom.Point; + + + + /** + * Rounds x and y of a Point. + * @param value Source Point to be rounded + * @return Rounded Point + */ + public function roundPoint(value:Point):Point { + return new Point(int(value.x), int(value.y)); + } +} diff --git a/src/utils/geom/simplifyAngle.as b/src/utils/geom/simplifyAngle.as new file mode 100644 index 0000000..13b9cda --- /dev/null +++ b/src/utils/geom/simplifyAngle.as @@ -0,0 +1,20 @@ +package utils.geom { + + + + /** + * Simplifys the supplied angle to its simpliest representation. + * Example code: + * <pre> + * var simpAngle:Number = simplifyAngle(725); // returns 5 + * var simpAngle2:Number = simplifyAngle(-725); // returns -5 + * </pre> + * @param value Angle to simplify + * @return Supplied angle simplified + */ + public function simplifyAngle(value:Number):Number { + var _rotations:Number = Math.floor(value / 360); + + return (value >= 0) ? value - (360 * _rotations) : value + (360 * _rotations); + } +} diff --git a/src/utils/geom/trimAngle.as b/src/utils/geom/trimAngle.as new file mode 100644 index 0000000..083680a --- /dev/null +++ b/src/utils/geom/trimAngle.as @@ -0,0 +1,22 @@ +package utils.geom { + + + + /** + * Trims the supplied angle to its 0..360 representation. + * Example code: + * <pre> + * var simpAngle:Number = trimAngle(725); // returns 5 + * </pre> + * @param value Angle to trim + * @return Supplied angle trimmed + */ + public function trimAngle(value:Number):Number { + var a:Number = value; + + while(a < 0) a += 360; + while(a > 360) a -= 360; + + return a; + } +}
as3/as3-utils
9aedf754f67463435e76f54f0c2ab86f1196cf01
New Time utils
diff --git a/src/utils/date/timeCode.as b/src/utils/date/timeCode.as new file mode 100644 index 0000000..31617ea --- /dev/null +++ b/src/utils/date/timeCode.as @@ -0,0 +1,18 @@ +package utils.date { + + + + /** + * Utility function for generating time code given a number seconds. + * @param sec Seconds + * @return Timecode + */ + public function timeCode(sec:Number):String { + var h:Number = Math.floor(sec / 3600); + var m:Number = Math.floor((sec % 3600) / 60); + var s:Number = Math.floor((sec % 3600) % 60); + + //noinspection NestedConditionalExpressionJS + return (h === 0 ? "" : (h < 10 ? "0" + String(h) + ":" : String(h) + ":")) + (m < 10 ? "0" + String(m) : String(m)) + ":" + (s < 10 ? "0" + String(s) : String(s)); + } +}
as3/as3-utils
c435d480eeb1ce5d26c607ce045444a89ae48dca
New Date utils
diff --git a/src/utils/date/dayAbbrNames.as b/src/utils/date/dayAbbrNames.as new file mode 100644 index 0000000..8e31d66 --- /dev/null +++ b/src/utils/date/dayAbbrNames.as @@ -0,0 +1,7 @@ +package utils.date { + + + public const dayAbbrNames:Array = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]; + + +} diff --git a/src/utils/date/formatDate.as b/src/utils/date/formatDate.as new file mode 100644 index 0000000..e106d32 --- /dev/null +++ b/src/utils/date/formatDate.as @@ -0,0 +1,406 @@ +package utils.date { + import utils.conversion.minutesToSeconds; + import utils.number.addLeadingZero; + import utils.number.format; + import utils.number.getOrdinalSuffix; + + + + /** + * Formats a Date object for display. Acts almost identically to the PHP date() function. + * You can prevent a recognized character in the format string from being expanded by escaping it with a preceding ^. + * <table border="1"> + * <tr> + * <th style="width:150px;">Format character</th> + * <th>Description</th> + * <th style="width:200px;">Example returned values</th> + * </tr> + * <tr> + * <td>d</td> + * <td>Day of the month, 2 digits with leading zeros.</td> + * <td>01 to 31</td> + * </tr> + * <tr> + * <td>D</td> + * <td>A textual representation of a day, three letters.</td> + * <td>Mon through Sun</td> + * </tr> + * <tr> + * <td>j</td> + * <td>Day of the month without leading zeros.</td> + * <td>1 to 31</td> + * </tr> + * <tr> + * <td>l</td> + * <td>A full textual representation of the day of the week.</td> + * <td>Sunday through Saturday</td> + * </tr> + * <tr> + * <td>N</td> + * <td>ISO-8601 numeric representation of the day of the week.</td> + * <td>1 (for Monday) through 7 (for Sunday)</td> + * </tr> + * <tr> + * <td>S</td> + * <td>English ordinal suffix for the day of the month, 2 characters.</td> + * <td>st, nd, rd or th</td> + * </tr> + * <tr> + * <td>w</td> + * <td>Numeric representation of the day of the week.</td> + * <td>0 (for Sunday) through 6 (for Saturday)</td> + * </tr> + * <tr> + * <td>z</td> + * <td>The day of the year (starting from 0).</td> + * <td>0 through 365</td> + * </tr> + * <tr> + * <td>W</td> + * <td>ISO-8601 week number of year, weeks starting on Monday.</td> + * <td>Example: 42 (the 42nd week in the year)</td> + * </tr> + * <tr> + * <td>F</td> + * <td>A full textual representation of a month, such as January or March.</td> + * <td>January through December</td> + * </tr> + * <tr> + * <td>m</td> + * <td>Numeric representation of a month, with leading zeros.</td> + * <td>01 through 12</td> + * </tr> + * <tr> + * <td>M</td> + * <td>A short textual representation of a month, three letters.</td> + * <td>Jan through Dec</td> + * </tr> + * <tr> + * <td>n</td> + * <td>Numeric representation of a month, without leading zeros.</td> + * <td>1 through 12</td> + * </tr> + * <tr> + * <td>t</td> + * <td>Number of days in the given month.</td> + * <td>28 through 31</td> + * </tr> + * <tr> + * <td>L</td> + * <td>Determines if it is a leap year.</td> + * <td>1 if it is a leap year, 0 otherwise</td> + * </tr> + * <tr> + * <td>o or Y</td> + * <td>A full numeric representation of a year, 4 digits.</td> + * <td>Examples: 1999 or 2003</td> + * </tr> + * <tr> + * <td>y</td> + * <td>A two digit representation of a year.</td> + * <td>Examples: 99 or 03</td> + * </tr> + * <tr> + * <td>a</td> + * <td>Lowercase Ante meridiem and Post meridiem.</td> + * <td>am or pm</td> + * </tr> + * <tr> + * <td>A</td> + * <td>Uppercase Ante meridiem and Post meridiem.</td> + * <td>AM or PM</td> + * </tr> + * <tr> + * <td>B</td> + * <td>Swatch Internet time.</td> + * <td>000 through 999</td> + * </tr> + * <tr> + * <td>g</td> + * <td>12-hour format of an hour without leading zeros.</td> + * <td>1 through 12</td> + * </tr> + * <tr> + * <td>G</td> + * <td>24-hour format of an hour without leading zeros.</td> + * <td>0 through 23</td> + * </tr> + * <tr> + * <td>h</td> + * <td>12-hour format of an hour with leading zeros.</td> + * <td>01 through 12</td> + * </tr> + * <tr> + * <td>H</td> + * <td>24-hour format of an hour with leading zeros.</td> + * <td>00 through 23</td> + * </tr> + * <tr> + * <td>i</td> + * <td>Minutes with leading zeros.</td> + * <td>00 to 59</td> + * </tr> + * <tr> + * <td>s</td> + * <td>Seconds, with leading zeros.</td> + * <td>00 through 59</td> + * </tr> + * <tr> + * <td>I</td> + * <td>Determines if the date is in daylight saving time.</td> + * <td>1 if Daylight Saving Time, 0 otherwise</td> + * </tr> + * <tr> + * <td>O</td> + * <td>Difference to coordinated universal time (UTC) in hours.</td> + * <td>Example: +0200</td> + * </tr> + * <tr> + * <td>P</td> + * <td>Difference to Greenwich time (GMT/UTC) in hours with colon between hours and minutes.</td> + * <td>Example: +02:00</td> + * </tr> + * <tr> + * <td>e or T</td> + * <td>Timezone abbreviation.</td> + * <td>Examples: EST, MDT</td> + * </tr> + * <tr> + * <td>Z</td> + * <td>Timezone offset in seconds.</td> + * <td>-43200 through 50400</td> + * </tr> + * <tr> + * <td>c</td> + * <td>ISO 8601 date.</td> + * <td>2004-02-12T15:19:21+00:00</td> + * </tr> + * <tr> + * <td>r</td> + * <td>RFC 2822 formatted date.</td> + * <td>Example: Thu, 21 Dec 2000 16:01:07 +0200</td> + * </tr> + * <tr> + * <td>U</td> + * <td>Seconds since the Unix Epoch.</td> + * <td>Example: 1171479314</td> + * </tr> + * </table> + * Example code: + * <pre> + * trace(DateUtils.formatDate(new Date(), "l ^t^h^e dS ^of F Y h:i:s A")); + * </pre> + * @param dateToFormat Date object you wish to format + * @param formatString Format of the outputted date String. See the format characters options above. + */ + public function formatDate(dateToFormat:Date, formatString:String):String { + var out:String = ""; + var c:String; + var i:int = -1; + var l:uint = formatString.length; + var t:Number; + + while(++i < l) { + c = formatString.substr(i, 1); + + if(c == "^") { + out += formatString.substr(++i, 1); + } + + else { + switch(c) { + case "d" : + // Day of the month, 2 digits with leading zeros + out += addLeadingZero(dateToFormat.getDate()); + break; + + case "D" : + // A textual representation of a day, three letters + out += getDayAbbrName(dateToFormat.getDay()); + break; + + case "j" : + // Day of the month without leading zeros + out += String(dateToFormat.getDate()); + break; + + case "l" : + // A full textual representation of the day of the week + out += getDayAsString(dateToFormat.getDay()); + break; + + case "N" : + // ISO-8601 numeric representation of the day of the week + t = dateToFormat.getDay(); + if(t == 0) t = 7; + out += String(t); + break; + + case "S" : + // English ordinal suffix for the day of the month, 2 characters + out += getOrdinalSuffix(dateToFormat.getDate()); + break; + + case "w" : + // Numeric representation of the day of the week + out += String(dateToFormat.getDay()); + break; + + case "z" : + // The day of the year (starting from 0) + out += String(addLeadingZero(getDayOfTheYear(dateToFormat))); + break; + + case "W" : + // ISO-8601 week number of year, weeks starting on Monday + out += String(addLeadingZero(getWeekOfTheYear(dateToFormat))); + break; + + case "F" : + // A full textual representation of a month, such as January or March + out += getMonthName(dateToFormat.getMonth()); + break; + + case "m" : + // Numeric representation of a month, with leading zeros + out += addLeadingZero(dateToFormat.getMonth() + 1); + break; + + case "M" : + // A short textual representation of a month, three letters + out += getMonthAbbrName(dateToFormat.getMonth()); + break; + + case "n" : + // Numeric representation of a month, without leading zeros + out += String((dateToFormat.getMonth() + 1)); + break; + + case "t" : + // Number of days in the given month + out += String(getDaysInMonth(dateToFormat.getMonth(), dateToFormat.getFullYear())); + break; + + case "L" : + // Whether it is a leap year + out += (isLeapYear(dateToFormat.getFullYear())) ? "1" : "0"; + break; + + case "o" : + case "Y" : + // A full numeric representation of a year, 4 digits + out += String(dateToFormat.getFullYear()); + break; + + case "y" : + // A two digit representation of a year + out += String(dateToFormat.getFullYear()).substr(-2); + break; + + case "a" : + // Lowercase Ante meridiem and Post meridiem + out += getMeridiem(dateToFormat.getHours()).toLowerCase(); + break; + + case "A" : + // Uppercase Ante meridiem and Post meridiem + out += getMeridiem(dateToFormat.getHours()); + break; + + case "B" : + // Swatch Internet time + out += format(getInternetTime(dateToFormat), 3, null, "0"); + break; + + case "g" : + // 12-hour format of an hour without leading zeros + t = dateToFormat.getHours(); + if(t == 0) { + t = 12; + } else if(t > 12) { + t -= 12; + } + out += String(t); + break; + + case "G" : + // 24-hour format of an hour without leading zeros + out += String(dateToFormat.getHours()); + break; + + case "h" : + // 12-hour format of an hour with leading zeros + t = dateToFormat.getHours() + 1; + if(t == 0) { + t = 12; + } else if(t > 12) { + t -= 12; + } + out += addLeadingZero(t); + break; + + case "H" : + // 24-hour format of an hour with leading zeros + out += addLeadingZero(dateToFormat.getHours()); + break; + + case "i" : + // Minutes with leading zeros + out += addLeadingZero(dateToFormat.getMinutes()); + break; + + case "s" : + // Seconds, with leading zeros + out += addLeadingZero(dateToFormat.getSeconds()); + break; + + case "I" : + // Whether or not the date is in daylights savings time + out += (isDaylightSavings(dateToFormat)) ? "1" : "0"; + break; + + case "O" : + // Difference to Greenwich time (GMT/UTC) in hours + out += getFormattedDifferenceFromUTC(dateToFormat); + break; + + case "P" : + out += getFormattedDifferenceFromUTC(dateToFormat, ":"); + break; + + case "e" : + case "T" : + // Timezone identifier + out += getTimezone(dateToFormat); + break; + + case "Z" : + // Timezone offset (GMT/UTC) in seconds. + out += String(int(minutesToSeconds(dateToFormat.getTimezoneOffset()))); + break; + + case "c" : + // ISO 8601 date + out += dateToFormat.getFullYear() + "-" + addLeadingZero(dateToFormat.getMonth() + 1) + "-" + addLeadingZero(dateToFormat.getDate()) + "T" + addLeadingZero(dateToFormat.getHours()) + ":" + addLeadingZero(dateToFormat.getMinutes()) + ":" + addLeadingZero(dateToFormat.getSeconds()) + getFormattedDifferenceFromUTC(dateToFormat, ":"); + break; + + case "r" : + // RFC 2822 formatted date + out += getDayAbbrName(dateToFormat.getDay()) + ", " + dateToFormat.getDate() + " " + getMonthAbbrName(dateToFormat.getMonth()) + " " + dateToFormat.getFullYear() + " " + addLeadingZero(dateToFormat.getHours()) + ":" + addLeadingZero(dateToFormat.getMinutes()) + ":" + addLeadingZero(dateToFormat.getSeconds()) + " " + getFormattedDifferenceFromUTC(dateToFormat); + break; + + case "U" : + // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) + t = int(dateToFormat.getTime() / 1000); + out += String(t); + break; + + default : + out += formatString.substr(i, 1); + } + } + } + + return out; + } +} diff --git a/src/utils/date/getDayAbbrName.as b/src/utils/date/getDayAbbrName.as new file mode 100644 index 0000000..249009e --- /dev/null +++ b/src/utils/date/getDayAbbrName.as @@ -0,0 +1,13 @@ +package utils.date { + + + + /** + * Returns the English abbreviation name of the provided day. + * @param day the index of the day, where zero returns 'Sun' and six returns 'Sat' + * @return + */ + public function getDayAbbrName(day:int):String { + return dayAbbrNames[day]; + } +} diff --git a/src/utils/date/getFormattedDifferenceFromUTC.as b/src/utils/date/getFormattedDifferenceFromUTC.as new file mode 100644 index 0000000..fa932cb --- /dev/null +++ b/src/utils/date/getFormattedDifferenceFromUTC.as @@ -0,0 +1,18 @@ +package utils.date { + import utils.conversion.minutesToHours; + import utils.number.addLeadingZero; + + + + /** + * Formats the difference to coordinated undefined time (UTC). + * @param date Date object to find the time zone offset of + * @param separator Character(s) that separates the hours from minutes + * @return Formatted time difference from UTC + */ + public function getFormattedDifferenceFromUTC(date:Date, separator:String = ""):String { + var pre:String = (-date.getTimezoneOffset() < 0) ? "-" : "+"; + + return pre + addLeadingZero(Math.floor(minutesToHours(date.getTimezoneOffset()))) + separator + addLeadingZero(date.getTimezoneOffset() % 60); + } +} diff --git a/src/utils/date/getMonthAbbrName.as b/src/utils/date/getMonthAbbrName.as new file mode 100644 index 0000000..f80145c --- /dev/null +++ b/src/utils/date/getMonthAbbrName.as @@ -0,0 +1,13 @@ +package utils.date { + + + + /** + * Returns the English abbreviation name of the provided month. + * @param month the index of the month, starting at zero + * @return + */ + public function getMonthAbbrName(month:int):String { + return monthAbbrNames[month]; + } +} diff --git a/src/utils/date/iso8601ToDate.as b/src/utils/date/iso8601ToDate.as new file mode 100644 index 0000000..d39e7ae --- /dev/null +++ b/src/utils/date/iso8601ToDate.as @@ -0,0 +1,68 @@ +package utils.date { + import utils.conversion.minutesToHours; + import utils.object.isEmpty; + + + + /** + * Converts W3C ISO 8601 date String into a Date object. + * Example code: + * <pre> + * trace(iso8601ToDate("1994-11-05T08:15:30-05:00").toString()); + * </pre> + * @param iso8601 Valid ISO 8601 formatted String + * @return Date object of the specified date and time of the ISO 8601 String in universal time + * @see <a href="http://www.w3.org/TR/NOTE-datetime">W3C ISO 8601 specification</a> + */ + public function iso8601ToDate(iso8601:String):Date { + var parts:Array = iso8601.toUpperCase().split("T"); + var date:Array = parts[0].split("-"); + var time:Array = (parts.length <= 1) ? [] : parts[1].split(":"); + var year:uint = isEmpty(date[0]) ? 0 : Number(date[0]); + var month:uint = isEmpty(date[1]) ? 0 : Number(date[1] - 1); + var day:uint = isEmpty(date[2]) ? 1 : Number(date[2]); + var hour:int = isEmpty(time[0]) ? 0 : Number(time[0]); + var minute:uint = isEmpty(time[1]) ? 0 : Number(time[1]); + var second:uint = 0; + var millisecond:uint = 0; + + if(time[2] !== undefined) { + var index:int = time[2].length; + var temp:Number; + + if(time[2].indexOf("+") > -1) { + index = time[2].indexOf("+"); + } else if(time[2].indexOf("-") > -1) { + index = time[2].indexOf("-"); + } else if(time[2].indexOf("Z") > -1) { + index = time[2].indexOf("Z"); + } + + if(isNaN(index)) { + temp = Number(time[2].slice(0, index)); + second = Math.floor(temp); + millisecond = 1000 * (temp % 1); + } + + if(index != time[2].length) { + var offset:String = time[2].slice(index); + var userOffset:Number = minutesToHours(new Date(year, month, day).getTimezoneOffset()); + + switch(offset.charAt(0)) { + case "+" : + case "-" : + hour -= userOffset + Number(offset.slice(0)); + break; + + case "Z" : + hour -= userOffset; + break; + + default: + } + } + } + + return new Date(year, month, day, hour, minute, second, millisecond); + } +} diff --git a/src/utils/date/monthAbbrNames.as b/src/utils/date/monthAbbrNames.as new file mode 100644 index 0000000..a291d0f --- /dev/null +++ b/src/utils/date/monthAbbrNames.as @@ -0,0 +1,7 @@ +package utils.date { + + + public const monthAbbrNames:Array = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; + + +}
as3/as3-utils
7be40d67ac86ce3daf48c6f18477a3c27578b14a
comments did not pass asdoc, changed <= to less or equal so it will not misinterpate a tag
diff --git a/src/utils/align/interpolateMultiX.as b/src/utils/align/interpolateMultiX.as index a4ef4a8..5efff40 100644 --- a/src/utils/align/interpolateMultiX.as +++ b/src/utils/align/interpolateMultiX.as @@ -1,19 +1,19 @@ package utils.align { /** - * interpolate multiple DisplayObjects at multiple weights at t == (0 <= t <= 1). at tx=1, the position of the object would be aligned to the right-most bounds, and tx=0 would position to the left + * interpolate multiple DisplayObjects at multiple weights at t == (0 less or equal t less or equal 1). at tx=1, the position of the object would be aligned to the right-most bounds, and tx=0 would position to the left * * @param DisplayObject DisplayObject to position * @param positionArray weight array of horizontal position from 0 to 1 * @param width width of horizontal constraint * @offsetX the left offset of the horizontal constraint (default = 0) */ public function interpolateMultiX(objectArray:Array, positionArray:Array, width:Number, offsetX:int = 0):void { var j:int = objectArray.length; for (var i:int = 0; i < j; i++) { interpolateX(objectArray[i], positionArray[i], width, offsetX); } } } \ No newline at end of file diff --git a/src/utils/align/interpolateMultiY.as b/src/utils/align/interpolateMultiY.as index da1b6ec..e0a7ed3 100644 --- a/src/utils/align/interpolateMultiY.as +++ b/src/utils/align/interpolateMultiY.as @@ -1,19 +1,19 @@ package utils.align { /** - * interpolate multiple DisplayObjects at multiple weights at t == (0 <= t <= 1). at tx=1, the position of the object would be aligned to the right-most bounds, and ty=0 would position to the left + * interpolate multiple DisplayObjects at multiple weights at t == (0 less or equal t less or equal 1). at tx=1, the position of the object would be aligned to the right-most bounds, and ty=0 would position to the left * * @param DisplayObject DisplayObject to position * @param positionArray weight array of vertical position from 0 to 1 * @param height width of horizontal constraint * @param offsetY the left offset of the horizontal constraint (default = 0) */ public function interpolateMultiY(objectArray:Array, positionArray:Array, height:Number, offsetY:int = 0):void { var j:int = objectArray.length; for (var i:int = 0; i < j; i++) { interpolateX(objectArray[i], positionArray[i], height, offsetY); } } } \ No newline at end of file diff --git a/src/utils/align/interpolateY.as b/src/utils/align/interpolateY.as index 5f81880..9d8ef51 100644 --- a/src/utils/align/interpolateY.as +++ b/src/utils/align/interpolateY.as @@ -1,17 +1,17 @@ package utils.align { import flash.display.DisplayObject; /** - * interpolate the DisplayObject at weight t == (0 <= t <= 1). a position 1 would position the object to the right-most bounds, and tx=0 would position to the left + * interpolate the DisplayObject at weight t == (0 less or equal t less or equal 1). a position 1 would position the object to the right-most bounds, and tx=0 would position to the left * * @param DisplayObject DisplayObject to position * @param ty weight of verticle position from 0 to 1 * @param height height of the verticle constraint * @offsetY the left offset of the horizontal constraint (default = 0) */ public function interpolateY(object:DisplayObject, ty:Number, height:Number, offsetY:int = 0):void { object.y = (height * ty) + offsetY - (ty * object.height); } } \ No newline at end of file
as3/as3-utils
0e8884f9d321a4a7e261bdf895ca0f3976a55b0c
Some general cleanup. Added test for clone(object). Added some comments. Added my name to the README.
diff --git a/README.md b/README.md index d9720e9..31676c5 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,43 @@ -# as3-utils +# as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? -HEAPS, too much to list here right now. +HEAPS, too much to list here right now. -Oh ok here's a taste, there are umpteen utils for +Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html -- number +- number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) +- Joel Hooks [@jhooks](http://twitter.com/jhooks) - You. # Giving credit where credit is due Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. \ No newline at end of file diff --git a/src/utils/align/alignToRectangleBottom.as b/src/utils/align/alignToRectangleBottom.as index 71c2dfe..a22bfa2 100644 --- a/src/utils/align/alignToRectangleBottom.as +++ b/src/utils/align/alignToRectangleBottom.as @@ -1,19 +1,19 @@ package utils.align { import flash.display.DisplayObject; import flash.geom.Rectangle; /** Aligns a DisplayObject to the bottom of the bounding Rectangle. - @param displayObject: The DisplayObject to align. - @param bounds: The area in which to align the DisplayObject. - @param snapToPixel: Force the position to whole pixels <code>true</code>, or to let the DisplayObject be positioned on sub-pixels <code>false</code>. - @param outside: Align the DisplayObject to the outside of the bounds <code>true</code>, or the inside <code>false</code>. + @param displayObject The DisplayObject to align. + @param bounds The area in which to align the DisplayObject. + @param snapToPixel Force the position to whole pixels <code>true</code>, or to let the DisplayObject be positioned on sub-pixels <code>false</code>. + @param outside Align the DisplayObject to the outside of the bounds <code>true</code>, or the inside <code>false</code>. */ public function alignToRectangleBottom(displayObject:DisplayObject, bounds:Rectangle, snapToPixel:Boolean = true, outside:Boolean = false):void { var y:Number = outside ? bounds.bottom : bounds.bottom - displayObject.height; displayObject.y = snapToPixel ? Math.round(y) : y; } } \ No newline at end of file diff --git a/src/utils/align/interpolate.as b/src/utils/align/interpolate.as index 3a8a426..3c8314b 100644 --- a/src/utils/align/interpolate.as +++ b/src/utils/align/interpolate.as @@ -1,21 +1,22 @@ package utils.align { import flash.display.DisplayObject; /** - * interpolate the DisplayObject at weight t == (0 &lt;= t &lt;= 1). a position 1 would position the object to the right-most bounds, and tx=0 would position to the left + * interpolate the DisplayObject at weight t == (0 &lt;= t &lt;= 1). a position 1 would position the object to the + * right-most bounds, and tx=0 would position to the left * - * @param DisplayObject DisplayObject to position + * @param object DisplayObject to position * @param tx weight of horizontal position from 0 to 1 * @param ty weight of verticle position from 0 to 1 * @param width width of horizontal constraint * @param height height of the verticle constraint * @offsetX the left offset of the horizontal constraint (default = 0) * @offsetY the topmost offset of verticle constraint (default = 0) */ public function interpolate(object:DisplayObject, tx:Number, ty:Number, width:Number, height:Number, offsetX:int = 0, offsetY:int = 0):void { object.x = (width * tx) + offsetX - (tx * object.width); object.y = (height * ty) + offsetY - (ty * object.height); } } \ No newline at end of file diff --git a/src/utils/object/clone.as b/src/utils/object/clone.as index a450e38..dea45e1 100644 --- a/src/utils/object/clone.as +++ b/src/utils/object/clone.as @@ -1,12 +1,18 @@ package utils.object { import flash.utils.ByteArray; + /** + * Creates a generic object clone of a given object. Does <strong>not</strong> retain type. + * + * @param obj + * @return + */ public function clone(obj:Object):Object { const byt:ByteArray = new ByteArray(); byt.writeObject(obj); byt.position = 0; return byt.readObject(); } } \ No newline at end of file diff --git a/src/utils/object/combine.as b/src/utils/object/combine.as index ab201df..92c1a2c 100644 --- a/src/utils/object/combine.as +++ b/src/utils/object/combine.as @@ -1,17 +1,28 @@ package utils.object { + /** + * Combines all of the properties from two objects into a single objects. Note that + * duplicate properties will be overwritten by the values on the second parameter object. + * + * @param defaultVars + * @param additionalVars + * @return + */ public function combine(defaultVars:Object, additionalVars:Object):Object { var combinedObject:Object = {}; var property:String; + for (property in defaultVars) { combinedObject[property] = defaultVars[property]; } + for (property in additionalVars) { combinedObject[property] = additionalVars[property]; } + return combinedObject; } } \ No newline at end of file diff --git a/src/utils/object/inspect.as b/src/utils/object/inspect.as index b5f28ed..6222e6a 100644 --- a/src/utils/object/inspect.as +++ b/src/utils/object/inspect.as @@ -1,35 +1,34 @@ package utils.object { import flash.utils.describeType; public function inspect(obj:Object, depth:int = 2):String { var scan:Function = function(obj:Object, depth:int, prefix:String):String { if (depth < 1) return String(obj); const classDef:XML = describeType(obj); var str:String = ""; for each (var variable:XML in classDef.variable) { str += prefix + variable.@name + " : " + scan(obj[variable.@name], depth - 1, prefix + "\t") + "\n"; } /*for each(var accessor:XML in classDef.accessor.(@access == "readwrite" || @access == "readonly")) { str += prefix + accessor.@name + " : " + scan(obj[accessor.@name], depth - 1, prefix + "\t") + "\n"; }*/ for (var s:Object in obj) { str += prefix + s + " = " + scan(obj[s], depth - 1, prefix + "\t") + "\n"; } return str != "" ? ("[" + classDef.@name + "] {\n" + str + prefix + "}\n") : ((obj != null) ? obj + "" : "null"); - } - + }; return scan(obj, depth, ""); } } \ No newline at end of file diff --git a/src/utils/object/toString.as b/src/utils/object/toString.as index fc2eff0..0529a0e 100644 --- a/src/utils/object/toString.as +++ b/src/utils/object/toString.as @@ -1,36 +1,36 @@ package utils.object { /** * Convert the object to a string of form: <code>PROP: VAL&amp;PROP: VAL</code> * where: * <ul> * <li><code>PROP</code> is a property</li> * <li><code>VAL</code> is its corresponding value</li> * <li>&amp; is the specified optional delimiter</li> * </ul> * * @param obj Object to convert * @param delimiter (optional) Delimiter of property/value pairs * @return An string of all property/value pairs delimited by the * given string or null if the input object or delimiter is * null. * @author Jackson Dunstan */ - - function toString(obj:Object = null, delimiter:String = "\n"):String + + public function toString(obj:Object = null, delimiter:String = "\n"):String { if (obj == null || delimiter == null) { return ""; } else { var ret:Array = []; for (var s:Object in obj) { ret.push(s + ": " + obj[s]); } return ret.join(delimiter); } } } \ No newline at end of file diff --git a/src/utils/string/detectBr.as b/src/utils/string/detectBr.as index 77e3329..623102c 100644 --- a/src/utils/string/detectBr.as +++ b/src/utils/string/detectBr.as @@ -1,10 +1,10 @@ package utils.string { /** * Detect HTML line breaks. */ public function detectBr(str:String):Boolean { - return (str.split("<br").length > 1) ? true : false; + return str.split("<br").length > 1; } } \ No newline at end of file diff --git a/test/utils/object/cloneTest.as b/test/utils/object/cloneTest.as new file mode 100644 index 0000000..4d312eb --- /dev/null +++ b/test/utils/object/cloneTest.as @@ -0,0 +1,31 @@ +package utils.object +{ + import org.hamcrest.assertThat; + import org.hamcrest.object.hasProperties; + + public class cloneTest + { + [Test] + public function clone_creates_object_with_equal_properties():void + { + var originalObject:SimpleObject = new SimpleObject(); + var cloneObject:Object; + + cloneObject = clone(originalObject); + + assertThat( + "cloned object properties equal original object properties", + cloneObject, + hasProperties({propOne:"propOne",propTwo:true,propThree:10}) + ); + } + + } +} + +class SimpleObject +{ + public var propOne:String = "propOne"; + public var propTwo:Boolean = true; + public var propThree:int = 10; +} \ No newline at end of file
as3/as3-utils
010bcd1ee086aaea7f6222d41eefcb0651091831
IntelliJ told me that some logic could be simplified. must... obey... ide... overlord...
diff --git a/src/utils/xml/isValidXML.as b/src/utils/xml/isValidXML.as index 25bbfcc..bc369a3 100644 --- a/src/utils/xml/isValidXML.as +++ b/src/utils/xml/isValidXML.as @@ -1,34 +1,29 @@ package utils.xml { /** * Checks whether the specified string is valid and well formed XML. * * @param data The string that is being checked to see if it is valid XML. * * @return A Boolean value indicating whether the specified string is * valid XML. * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 */ public function isValidXML(data:String):Boolean { var xml:XML; try { xml = new XML(data); } catch (e:Error) { return false; } - if (xml.nodeKind() != constants.ELEMENT) - { - return false; - } - - return true; + return xml.nodeKind() == constants.ELEMENT; } } \ No newline at end of file
as3/as3-utils
1537a7846324e43c8f17e454c668dd898f37d211
Added tests for alignCenter(). Tests exposed incorrect algorithm in xAlignCenter and yAlignCenter. Replaced with algorithm found at http://chargedweb.com/labs/2010/07/27/alignutil_align_objects_easily/ which also takes into account the object's rotation and scale so it should be more useful overall.
diff --git a/src/utils/align/xAlignCenter.as b/src/utils/align/xAlignCenter.as index f8a244b..1d4d4b6 100644 --- a/src/utils/align/xAlignCenter.as +++ b/src/utils/align/xAlignCenter.as @@ -1,12 +1,27 @@ package utils.align { import flash.display.DisplayObject; + import flash.geom.Point; + import flash.geom.Rectangle; - /** + /** * Horizontal center align object to target. - */ + * Alignment algorithm taken from: + * http://chargedweb.com/labs/2010/07/27/alignutil_align_objects_easily/ + * Copyright 2010 Julius Loa | [email protected] + * license: MIT {http://www.opensource.org/licenses/mit-license.php} + * + * This algorith takes the objects rotation and scale into account. + */ public function xAlignCenter(item:DisplayObject, target:DisplayObject):void { - item.x = int(target.width / 2 - item.width / 2); + //item.x = int(target.width / 2 - item.width / 2); + + var b:Rectangle = item.transform.pixelBounds; + var bp:Point = target.globalToLocal(new Point(b.x, b.y)); + b.x = bp.x; b.y = bp.y; + item.x = int((target.width - b.width)/2 + item.x - b.x); } + + } \ No newline at end of file diff --git a/src/utils/align/yAlignCenter.as b/src/utils/align/yAlignCenter.as index ca1ac03..e1441f0 100644 --- a/src/utils/align/yAlignCenter.as +++ b/src/utils/align/yAlignCenter.as @@ -1,12 +1,24 @@ package utils.align { import flash.display.DisplayObject; + import flash.geom.Point; + import flash.geom.Rectangle; - /** + /** * Vertical center align object to target. + * + * Alignment algorithm taken from: + * http://chargedweb.com/labs/2010/07/27/alignutil_align_objects_easily/ + * Copyright 2010 Julius Loa | [email protected] + * license: MIT {http://www.opensource.org/licenses/mit-license.php} + * + * This algorith takes the objects rotation and scale into account. */ public function yAlignCenter(item:DisplayObject, target:DisplayObject):void { - item.y = int(target.height / 2 - item.height / 2); + var b:Rectangle = item.transform.pixelBounds; + var bp:Point = target.globalToLocal(new Point(b.x, b.y)); + b.x = bp.x; b.y = bp.y; + item.y = int((target.height - b.height)/2 + item.y - b.y); } } \ No newline at end of file diff --git a/test/utils/align/alignCenterTest.as b/test/utils/align/alignCenterTest.as new file mode 100644 index 0000000..2b3da96 --- /dev/null +++ b/test/utils/align/alignCenterTest.as @@ -0,0 +1,61 @@ +package utils.align +{ + import flash.display.Sprite; + + import mx.core.UIComponent; + + import org.fluint.uiImpersonation.UIImpersonator; + import org.hamcrest.assertThat; + + import org.hamcrest.object.equalTo; + + public class alignCenterTest + { + + [Test] + public function alignCenter_aligns_display_object_centers_x():void + { + var item:Sprite = drawSprite(10,10,10,10); + var target:Sprite = drawSprite(20,20,10,10); + addItemAndTargetToStage(item, target); + + alignCenter(item, target); + + assertThat(item.x, equalTo(target.x)); + } + + [Test] + public function alignCenter_aligns_display_object_centers_y():void + { + var item:Sprite = drawSprite(10,10,10,10); + var target:Sprite = drawSprite(20,20,10,10); + addItemAndTargetToStage(item, target); + + alignCenter(item, target); + + assertThat(item.y, equalTo(target.y)); + } + + private function drawSprite(x:int, y:int, width:int, height:int):Sprite + { + var sprite:Sprite = new Sprite(); + + sprite.graphics.beginFill(0x000000); + sprite.graphics.drawRect(0,0,width,height); + + sprite.x = x; + sprite.y = y; + + return sprite; + } + + private function addItemAndTargetToStage(item:Sprite, target:Sprite):void + { + var uiComponent:UIComponent = new UIComponent(); + + UIImpersonator.addChild(uiComponent); + uiComponent.addChild(item); + uiComponent.addChild(target); + } + } +} \ No newline at end of file
as3/as3-utils
20aac7ff1ff92eec2838038a30c8f8f5ad1f4fe4
added hamcrest and mockolate library swcs and updated .gitignore to disregard IntelliJ .iml files
diff --git a/.gitignore b/.gitignore index ce8a1a2..8a0c108 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ target bin bin-debug -bin-release \ No newline at end of file +bin-release +*.iml \ No newline at end of file diff --git a/libs/hamcrest-as3-flex-1.1.3.swc b/libs/hamcrest-as3-flex-1.1.3.swc new file mode 100644 index 0000000..5080a60 Binary files /dev/null and b/libs/hamcrest-as3-flex-1.1.3.swc differ diff --git a/libs/mockolate-0.9.3.swc b/libs/mockolate-0.9.3.swc new file mode 100644 index 0000000..d0ff63d Binary files /dev/null and b/libs/mockolate-0.9.3.swc differ
as3/as3-utils
8470f13347653b56e34cd2f187802976b7e0b0a2
adding getNextDay and getPreviousDay with tests
diff --git a/src/utils/date/getNextDay.as b/src/utils/date/getNextDay.as new file mode 100644 index 0000000..a716631 --- /dev/null +++ b/src/utils/date/getNextDay.as @@ -0,0 +1,23 @@ +package utils.date +{ + /** Returns the next calender date following the provided Date. + * If no Date is provided, the current date is used. + * @param startDate The date you wish to get the next day of + * @return + */ + public function getNextDay(startDate:Date=null):Date + { + const millisecondsPerDay:int = 1000 * 60 * 60 * 24; + + if(!startDate) + startDate = new Date(); + + //scrub the time of day + var tmpDate:Date = new Date(startDate.getFullYear(), + startDate.getMonth(), + startDate.getDate()); + + tmpDate.setTime(tmpDate.getTime() + millisecondsPerDay); + return tmpDate; + } +} diff --git a/src/utils/date/getPreviousDay.as b/src/utils/date/getPreviousDay.as new file mode 100644 index 0000000..d699c0c --- /dev/null +++ b/src/utils/date/getPreviousDay.as @@ -0,0 +1,21 @@ +package utils.date +{ + /** Returns the previous calender date to the provided Date. + * If no Date is provided, the current date is used. + * @param startDate The date you wish to get the previous day of + * @return + */ + public function getPreviousDay(startDate:Date=null):Date + { + const millisecondsPerDay:int = 1000 * 60 * 60 * 24; + + if(!startDate) + startDate = new Date(); + + //scrub the time of day + var tmpDate:Date = new Date(startDate.getFullYear(), + startDate.getMonth(), + startDate.getDate()); + return new Date(tmpDate.getTime() - millisecondsPerDay); + } +} diff --git a/test/utils/date/GetNextDayTest.as b/test/utils/date/GetNextDayTest.as new file mode 100644 index 0000000..3c67d9f --- /dev/null +++ b/test/utils/date/GetNextDayTest.as @@ -0,0 +1,59 @@ +package utils.date +{ +import org.flexunit.asserts.assertTrue; +import org.flexunit.asserts.fail; +import utils.date.getNextDay; + +public class GetNextDayTest + { + [Test] + public function returnsNextDay():void + { + + var jan14:Date = new Date(2010, 0, 14); + var jan15:Date = new Date(2010, 0, 15); + + assertTrue(getNextDay(jan14).getTime() == jan15.getTime()); + } + + [Test] + public function passingNoDateUsesToday():void + { + var today:Date = new Date(); + var tomorrow:Date = getNextDay(today); + + assertTrue(getNextDay().getTime() == tomorrow.getTime()); + } + + [Test] + public function wrapsToNextMonth():void + { + var endOfMonth:Date = new Date(2010, 0, 31); + + assertTrue(getNextDay(endOfMonth).getMonth() == 1); + } + [Test] + public function wrapsToNextMonthForFebruary():void + { + var endOfFeb:Date = new Date(2011, 1, 28); + + assertTrue(getNextDay(endOfFeb).getMonth() == 2); + } + [Test] + public function doesntWrapToNextMonthForFebruaryInLeapYear():void + { + var endOfFeb:Date = new Date(2012, 1, 28); + + assertTrue(getNextDay(endOfFeb).getMonth() == 1); + } + + [Test] + public function wrapsToNextYear():void + { + var endOfYear:Date = new Date(2010, 11, 31); + + assertTrue(getNextDay(endOfYear).getFullYear() == 2011); + } + + } +} \ No newline at end of file diff --git a/test/utils/date/GetPrevDayTest.as b/test/utils/date/GetPrevDayTest.as new file mode 100644 index 0000000..bb673ba --- /dev/null +++ b/test/utils/date/GetPrevDayTest.as @@ -0,0 +1,45 @@ +package utils.date +{ +import org.flexunit.asserts.assertTrue; +import org.flexunit.asserts.fail; +import utils.date.getPreviousDay; + +public class GetPrevDayTest + { + [Test] + public function returnsPrevDay():void + { + + var jan14:Date = new Date(2010, 0, 14); + var jan15:Date = new Date(2010, 0, 15); + + assertTrue(getPreviousDay(jan15).getTime() == jan14.getTime()); + } + + [Test] + public function passingNoDateUsesToday():void + { + var today:Date = new Date(); + var yesterday:Date = getPreviousDay(today); + + assertTrue(getPreviousDay().getTime() == yesterday.getTime()); + } + + [Test] + public function wrapsToPrevMonth():void + { + var startOfMonth:Date = new Date(2010, 0, 1); + + assertTrue(getPreviousDay(startOfMonth).getMonth() == 11); + } + + [Test] + public function wrapsToPrevYear():void + { + var startOfYear:Date = new Date(2011, 0, 1); + + assertTrue(getPreviousDay(startOfYear).getFullYear() == 2010); + } + + } +} \ No newline at end of file
as3/as3-utils
fb7d4e1127160bc7404f060bfd782ff10540459d
utils to go back and forth from cartesian to polar coordinates
diff --git a/src/utils/geom/cartesianToPolarCoordinates.as b/src/utils/geom/cartesianToPolarCoordinates.as new file mode 100644 index 0000000..8ff0f6a --- /dev/null +++ b/src/utils/geom/cartesianToPolarCoordinates.as @@ -0,0 +1,25 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: Sep 30, 2010 + * Time: 11:56:07 AM + */ +package utils.geom { + + /** + Converts cartesian coordinates to polar coordinates. + + @param x: The x value of the cartesian point. + @param y: The y value of the cartesian point. + @return Returns an array containing polar coordinates r and q. + */ + + public function cartesianToPolarCoordinates(x:Number, y:Number) : Array { + + var r:Number = Math.sqrt(Math.pow(x,2) + Math.pow(y,2)); + var q:Number = Math.atan(y/x) * (180/Math.PI); + + return [r, q]; + } + +} \ No newline at end of file diff --git a/src/utils/geom/polarToCartesianCoordinates.as b/src/utils/geom/polarToCartesianCoordinates.as new file mode 100644 index 0000000..9b5b9c0 --- /dev/null +++ b/src/utils/geom/polarToCartesianCoordinates.as @@ -0,0 +1,25 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: Sep 30, 2010 + * Time: 1:00:51 PM + */ +package utils.geom { +import flash.geom.Point; + + /** + Converts polar coordinates to cartesian coordinates. + + @param r: The r value of the polar coordinate. + @param q: The q value of the polar coordinate in degrees. + */ + + public function polarToCartesianCoordinates(r:Number, q:Number) : Point { + + var x:Number = r * Math.cos(q); + var y:Number = r * Math.sin(q); + + return new Point(x,y) + } + +} \ No newline at end of file diff --git a/test/utils/geom/CartesianToPolarCoordinatesTest.as b/test/utils/geom/CartesianToPolarCoordinatesTest.as new file mode 100644 index 0000000..cb2140c --- /dev/null +++ b/test/utils/geom/CartesianToPolarCoordinatesTest.as @@ -0,0 +1,33 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: Sep 30, 2010 + * Time: 11:50:50 AM + */ +package utils.geom +{ + +import org.flexunit.asserts.assertTrue; +import utils.geom.cartesianToPolarCoordinates; + + public class CartesianToPolarCoordinatesTest + { + + [Before] + public function setup():void + { + + } + + [Test] + public function CartesianToPolarCoordinatesReturnsProperCoords():void + { + + var polarCoord:Array = cartesianToPolarCoordinates(3, 4); + + assertTrue(polarCoord[0] == 5 && polarCoord[1] == 53.13010235415598) + + } + + } +} \ No newline at end of file diff --git a/test/utils/geom/PolarToCartesianCoordinatesTest.as b/test/utils/geom/PolarToCartesianCoordinatesTest.as new file mode 100644 index 0000000..f66d4e7 --- /dev/null +++ b/test/utils/geom/PolarToCartesianCoordinatesTest.as @@ -0,0 +1,35 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian McLean + * Date: Sep 30, 2010 + * Time: 11:50:50 AM + */ +package utils.geom +{ +import flash.geom.Point; + +import org.flexunit.asserts.assertTrue; +import utils.geom.cartesianToPolarCoordinates; +import utils.geom.polarToCartesianCoordinates; + +public class PolarToCartesianCoordinatesTest + { + + [Before] + public function setup():void + { + + } + + [Test] + public function PolarToCartesianCoordinatesReturnsProperCoords():void + { + + var cartesianPoint:Point = polarToCartesianCoordinates(5, 53.13010235415598); + + assertTrue(cartesianPoint.x == 3, cartesianPoint.y == 4); + + } + + } +} \ No newline at end of file
as3/as3-utils
4fc142b97c2a006bd9f887c1c64a518ba8d86f85
had to edit intellij template
diff --git a/src/utils/date/getFullDayIndex.as b/src/utils/date/getFullDayIndex.as deleted file mode 100644 index 5588a73..0000000 --- a/src/utils/date/getFullDayIndex.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the index of the day that the full day name string - * represents. - * - * @param m A full day name. - * - * @return A int that represents that full day represented by the specifed - * full month name. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see FULL_DAY - */ - public function getFullDayIndex(d:String):int - { - return DateBase.dayNamesLong.indexOf(d); - } -} \ No newline at end of file diff --git a/src/utils/date/getFullDayName.as b/src/utils/date/getFullDayName.as deleted file mode 100644 index d323b46..0000000 --- a/src/utils/date/getFullDayName.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the English full day name for the day that - * the Date represents. - * - * @param d The Date instance whose day will be used to retrieve the - * full day name. - * - * @return An English full day name. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see FULL_DAY - */ - public function getFullDayName(d:Date):String - { - return DateBase.dayNamesLong[d.getDay()]; - } -} \ No newline at end of file diff --git a/src/utils/date/getFullMonthIndex.as b/src/utils/date/getFullMonthIndex.as deleted file mode 100644 index cb461da..0000000 --- a/src/utils/date/getFullMonthIndex.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the index of the month that the full month name string - * represents. - * - * @param m A full month name. - * - * @return A int that represents that month represented by the specifed - * full month name. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see FULL_MONTH - */ - public function getFullMonthIndex(m:String):int - { - return DateBase.monthNamesLong.indexOf(m); - } -} \ No newline at end of file diff --git a/src/utils/date/getFullMonthName.as b/src/utils/date/getFullMonthName.as deleted file mode 100644 index 0f7b5b4..0000000 --- a/src/utils/date/getFullMonthName.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the English full Month name for the Month that - * the Date represents. - * - * @param d The Date instance whose month will be used to retrieve the - * full month name. - * - * @return An English full month name. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see FULL_MONTH - */ - public function getFullMonthName(d:Date):String - { - return DateBase.monthNamesLong[d.getMonth()]; - } -} \ No newline at end of file diff --git a/src/utils/date/getShortDayIndex.as b/src/utils/date/getShortDayIndex.as deleted file mode 100644 index 4efe58a..0000000 --- a/src/utils/date/getShortDayIndex.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the index of the day that the short day name string - * represents. - * - * @param m A short day name. - * - * @return A int that represents that short day represented by the specifed - * full month name. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see SHORT_DAY - */ - public function getShortDayIndex(d:String):int - { - return DateBase.dayNamesShort.indexOf(d); - } -} \ No newline at end of file diff --git a/src/utils/date/getShortDayName.as b/src/utils/date/getShortDayName.as deleted file mode 100644 index 4d18a58..0000000 --- a/src/utils/date/getShortDayName.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the English Short Day name (3 letters) for the day that - * the Date represents. - * - * @param d The Date instance whose day will be used to retrieve the - * short day name. - * - * @return An English 3 Letter day abbreviation. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see SHORT_DAY - */ - public function getShortDayName(d:Date):String - { - return DateBase.dayNamesShort[d.getDay()]; - } -} \ No newline at end of file diff --git a/src/utils/date/getShortMonthIndex.as b/src/utils/date/getShortMonthIndex.as deleted file mode 100644 index 6526272..0000000 --- a/src/utils/date/getShortMonthIndex.as +++ /dev/null @@ -1,27 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the index of the month that the short month name string - * represents. - * - * @param m The 3 letter abbreviation representing a short month name. - * - * @param Optional parameter indicating whether the search should be case - * sensitive - * - * @return A int that represents that month represented by the specifed - * short name. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see SHORT_MONTH - */ - public function getShortMonthIndex(m:String):int - { - return DateBase.monthNamesShort.indexOf(m); - } -} \ No newline at end of file diff --git a/src/utils/date/getShortMonthName.as b/src/utils/date/getShortMonthName.as deleted file mode 100644 index 1870541..0000000 --- a/src/utils/date/getShortMonthName.as +++ /dev/null @@ -1,24 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns the English Short Month name (3 letters) for the Month that - * the Date represents. - * - * @param d The Date instance whose month will be used to retrieve the - * short month name. - * - * @return An English 3 Letter Month abbreviation. - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see SHORT_MONTH - */ - public function getShortMonthName(d:Date):String - { - return DateBase.monthNamesShort[d.getMonth()]; - } -} \ No newline at end of file diff --git a/src/utils/date/parseRFC822.as b/src/utils/date/parseRFC822.as deleted file mode 100644 index 6d8dec2..0000000 --- a/src/utils/date/parseRFC822.as +++ /dev/null @@ -1,135 +0,0 @@ -package utils.date -{ - /** - * Parses dates that conform to RFC822 into Date objects. This method also - * supports four-digit years (not supported in RFC822), but two-digit years - * (referring to the 20th century) are fine, too. - * - * This function is useful for parsing RSS .91, .92, and 2.0 dates. - * - * @param str - * - * @returns Date - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see http://asg.web.cmu.edu/rfc/rfc822.html - */ - public function parseRFC822(str:String):Date - { - var finalDate:Date; - try - { - var dateParts:Array = str.split(" "); - var day:String = null; - - if (dateParts[0].search(/\d/) == -1) - { - day = dateParts.shift().replace(/\W/, ""); - } - - var date:Number = Number(dateParts.shift()); - var month:Number = Number(getShortMonthIndex(dateParts.shift())); - var year:Number = Number(dateParts.shift()); - var timeParts:Array = dateParts.shift().split(":"); - var hour:Number = int(timeParts.shift()); - var minute:Number = int(timeParts.shift()); - var second:Number = (timeParts.length > 0) ? int(timeParts.shift()) : 0; - - var milliseconds:Number = Date.UTC(year, month, date, hour, minute, second, 0); - - var timezone:String = dateParts.shift(); - var offset:Number = 0; - - if (timezone.search(/\d/) == -1) - { - switch (timezone) - { - case "UT": - offset = 0; - break; - case "UTC": - offset = 0; - break; - case "GMT": - offset = 0; - break; - case "EST": - offset = (-5 * 3600000); - break; - case "EDT": - offset = (-4 * 3600000); - break; - case "CST": - offset = (-6 * 3600000); - break; - case "CDT": - offset = (-5 * 3600000); - break; - case "MST": - offset = (-7 * 3600000); - break; - case "MDT": - offset = (-6 * 3600000); - break; - case "PST": - offset = (-8 * 3600000); - break; - case "PDT": - offset = (-7 * 3600000); - break; - case "Z": - offset = 0; - break; - case "A": - offset = (-1 * 3600000); - break; - case "M": - offset = (-12 * 3600000); - break; - case "N": - offset = (1 * 3600000); - break; - case "Y": - offset = (12 * 3600000); - break; - default: - offset = 0; - } - } - else - { - var multiplier:Number = 1; - var oHours:Number = 0; - var oMinutes:Number = 0; - if (timezone.length != 4) - { - if (timezone.charAt(0) == "-") - { - multiplier = -1; - } - timezone = timezone.substr(1, 4); - } - oHours = Number(timezone.substr(0, 2)); - oMinutes = Number(timezone.substr(2, 2)); - offset = (((oHours * 3600000) + (oMinutes * 60000)) * multiplier); - } - - finalDate = new Date(milliseconds - offset); - - if (finalDate.toString() == "Invalid Date") - { - throw new Error("This date does not conform to RFC822."); - } - } - catch (e:Error) - { - var eStr:String = "Unable to parse the string [" + str + "] into a date. "; - eStr += "The internal error was: " + e.toString(); - throw new Error(eStr); - } - return finalDate; - } -} \ No newline at end of file diff --git a/src/utils/date/toRFC822.as b/src/utils/date/toRFC822.as deleted file mode 100644 index 877c949..0000000 --- a/src/utils/date/toRFC822.as +++ /dev/null @@ -1,59 +0,0 @@ -package utils.date -{ - import mx.formatters.DateBase; - - /** - * Returns a date string formatted according to RFC822. - * - * @param d - * - * @returns String - * - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - * - * @see http://asg.web.cmu.edu/rfc/rfc822.html - */ - public function toRFC822(d:Date):String - { - var date:Number = d.getUTCDate(); - var hours:Number = d.getUTCHours(); - var minutes:Number = d.getUTCMinutes(); - var seconds:Number = d.getUTCSeconds(); - var sb:String = new String(); - sb += DateBase.dayNamesShort[d.getUTCDay()]; - sb += ", "; - - if (date < 10) - { - sb += "0"; - } - sb += String(date); - sb += " "; - //sb += DateUtil.SHORT_MONTH[d.getUTCMonth()]; - sb += DateBase.monthNamesShort[d.getUTCMonth()]; - sb += " "; - sb += String(d.getUTCFullYear()); - sb += " "; - if (hours < 10) - { - sb += "0"; - } - sb += String(hours); - sb += ":"; - if (minutes < 10) - { - sb += "0"; - } - sb += String(minutes); - sb += ":"; - if (seconds < 10) - { - sb += "0"; - } - sb += String(seconds); - sb += " GMT"; - return sb; - } -} \ No newline at end of file diff --git a/src/utils/display/removeAllChildrenByType.as b/src/utils/display/removeAllChildrenByType.as new file mode 100644 index 0000000..e85afd8 --- /dev/null +++ b/src/utils/display/removeAllChildrenByType.as @@ -0,0 +1,21 @@ +package utils.display +{ + import flash.display.DisplayObjectContainer; + + /** + * Remove all children from a container and leave the bottom few + * @param container Container to remove from + * @param the type of children to remove + * @author John Lindquist + */ + public function removeAllChildrenByType(container:DisplayObjectContainer, type:Class):void + { + for each(var child:DisplayObjectContainer in container) + { + if(child is type) + { + container.removeChild(child); + } + } + } +} \ No newline at end of file diff --git a/src/utils/object/toString.as b/src/utils/object/toString.as index de313ff..fc2eff0 100644 --- a/src/utils/object/toString.as +++ b/src/utils/object/toString.as @@ -1,35 +1,36 @@ package utils.object { /** * Convert the object to a string of form: <code>PROP: VAL&amp;PROP: VAL</code> * where: * <ul> * <li><code>PROP</code> is a property</li> * <li><code>VAL</code> is its corresponding value</li> * <li>&amp; is the specified optional delimiter</li> * </ul> * * @param obj Object to convert * @param delimiter (optional) Delimiter of property/value pairs * @return An string of all property/value pairs delimited by the * given string or null if the input object or delimiter is * null. * @author Jackson Dunstan */ - public function toString(obj:Object = null, delimiter:String = "\n"):String + + function toString(obj:Object = null, delimiter:String = "\n"):String { if (obj == null || delimiter == null) { return ""; } else { var ret:Array = []; for (var s:Object in obj) { ret.push(s + ": " + obj[s]); } return ret.join(delimiter); } } } \ No newline at end of file diff --git a/src/utils/range/randomRangeDate.as b/src/utils/range/randomRangeDate.as index 7f68c42..cea3c40 100644 --- a/src/utils/range/randomRangeDate.as +++ b/src/utils/range/randomRangeDate.as @@ -1,44 +1,43 @@ /** * Created by IntelliJ IDEA. - * User: Ian + * User: Ian McLean * Date: Sep 26, 2010 * Time: 1:59:33 PM - * To change this template use File | Settings | File Templates. */ package utils.range { /** * Returns a random date within a given range */ public function randomRangeDate(date1:Date, date2:Date) : Date { if(date1.getTime() == date2.getTime()){ throw new Error("Dates specified are the same") } if(date2.getTime() < date1.getTime() ){ var temp:Date = date1; date1 = date2; date2 = temp; } var diff:Number = date2.getTime() - date1.getTime(); var rand:Number = Math.random() * diff; var time:Number = date1.getTime() + rand; var d:Date = new Date(); d.setTime(time) return d; } } \ No newline at end of file
as3/as3-utils
43db7338ed4489eab2b23563e176646ccae70f44
had to edit intellij template
diff --git a/src/utils/range/randomRangeDate.as b/src/utils/range/randomRangeDate.as index 7f68c42..cea3c40 100644 --- a/src/utils/range/randomRangeDate.as +++ b/src/utils/range/randomRangeDate.as @@ -1,44 +1,43 @@ /** * Created by IntelliJ IDEA. - * User: Ian + * User: Ian McLean * Date: Sep 26, 2010 * Time: 1:59:33 PM - * To change this template use File | Settings | File Templates. */ package utils.range { /** * Returns a random date within a given range */ public function randomRangeDate(date1:Date, date2:Date) : Date { if(date1.getTime() == date2.getTime()){ throw new Error("Dates specified are the same") } if(date2.getTime() < date1.getTime() ){ var temp:Date = date1; date1 = date2; date2 = temp; } var diff:Number = date2.getTime() - date1.getTime(); var rand:Number = Math.random() * diff; var time:Number = date1.getTime() + rand; var d:Date = new Date(); d.setTime(time) return d; } } \ No newline at end of file
as3/as3-utils
a59fd7170128ed1dda60ed230ed00ccd651c738c
util to generate a date within a range
diff --git a/src/utils/range/randomRangeDate.as b/src/utils/range/randomRangeDate.as new file mode 100644 index 0000000..7f68c42 --- /dev/null +++ b/src/utils/range/randomRangeDate.as @@ -0,0 +1,44 @@ +/** + * Created by IntelliJ IDEA. + * User: Ian + * Date: Sep 26, 2010 + * Time: 1:59:33 PM + * To change this template use File | Settings | File Templates. + */ +package utils.range { + + /** + * Returns a random date within a given range + */ + + public function randomRangeDate(date1:Date, date2:Date) : Date { + + if(date1.getTime() == date2.getTime()){ + + throw new Error("Dates specified are the same") + + } + + if(date2.getTime() < date1.getTime() ){ + + var temp:Date = date1; + + date1 = date2; + date2 = temp; + + } + + var diff:Number = date2.getTime() - date1.getTime(); + + var rand:Number = Math.random() * diff; + + var time:Number = date1.getTime() + rand; + + var d:Date = new Date(); + d.setTime(time) + + return d; + + } + +} \ No newline at end of file diff --git a/test/utils/range/RandomRangeDateTest.as b/test/utils/range/RandomRangeDateTest.as new file mode 100644 index 0000000..4f1caf4 --- /dev/null +++ b/test/utils/range/RandomRangeDateTest.as @@ -0,0 +1,69 @@ +package utils.range +{ +import org.flexunit.asserts.assertTrue; +import org.flexunit.asserts.fail; + +public class RandomRangeDateTest + { + + + [Before] + public function setup():void + { + + } + + [Test] + public function randomDateReturnsWithinRange():void + { + + var firstDate:Date = new Date(); + firstDate.month = 5; + var secondDate:Date = new Date(); + secondDate.month = 10; + + var date:Date = randomRangeDate(firstDate,secondDate) ; + + assertTrue(date.getTime() > firstDate.getTime() && date.getTime() < secondDate.getTime()); + + } + + [Test] + public function randomDateReturnWithinRangeWithValuesSwapped():void + { + + var firstDate:Date = new Date(); + firstDate.month = 10; + var secondDate:Date = new Date(); + secondDate.month = 5; + + var date:Date = randomRangeDate(firstDate,secondDate) ; + + assertTrue(date.getTime() < firstDate.getTime() && date.getTime() > secondDate.getTime()); + + } + + [Test] + public function randomDateThrowsErrorWhenDatesAreTheSame():void + { + + var firstDate:Date = new Date(); + var secondDate:Date = new Date(); + + try{ + var date:Date = randomRangeDate(firstDate,secondDate) ; + } + catch(e:Error) { + + assertTrue(1 == 1); + return; + + } + + fail("Error was not thrown"); + + + } + + } +} \ No newline at end of file
as3/as3-utils
35a4af5b1dd8dd37cec5a4c03f15d5ee072a442a
NOTES about as3-utils, issues to fix, functionality duplication audit results.
diff --git a/NOTES.md b/NOTES.md new file mode 100644 index 0000000..55f9102 --- /dev/null +++ b/NOTES.md @@ -0,0 +1,251 @@ +# as3-utils + +# ISSUES + +- parameter names are not descriptive +- variable names are not descriptive +- nomenclature is inconsistent +-- use functional-programming names? +-- use designer friendly names? +-- provide aliases for common functions with multiple common names? +- ASDocs +-- missing tags +-- incorrect descriptions +-- incorrect tags + +# Refactoring Guidelines + +- predicate methods should be prefixed with is* + +# AUDIT + +The below is the results of a quick audit of the functions available in as3-utils, and their specific issues. + +# ALIGN + +alignLeft +alignToRectangleLeft + duplicates + +alignRight +alignToRectangleRight + duplicates + +align to edges +distribute by edges +grid alignment + +hAlign(targets:Array, hSpacing:int = 0, alignment:Alignment = Alignment.LEFT):Array +vAlign(targets:Array, vSpacing:int = 0, alignment:Alignment = Alignment.TOP):Array +gAlign(targets:Array, columns:int, rows:int, hSpacing:int = 0, vSpacing:int = 0, alignment:Alignment = Alignment.TOP_LEFT):Array +gAlign = gridAlign + + /** + * Aligns all the target DisplayObjects by their left edge to the left-most target. + * + * Similar to the Flash IDE Alignment panel. + */ + alignLeft(targets:Vector.<DisplayObject>):Vector.<DisplayObject> + + /** + * Aligns all the target DisplayObjects by their right edge to the right-most target. + * + * Similar to the Flash IDE Alignment panel. + */ + alignRight(targets:Vector.<DisplayObject>):Vector.<DisplayObject> + + /** + * Aligns all the target DisplayObjects by their top edges to the top-most target. + * + * Similar to the Flash IDE Alignment panel. + */ + alignTop(targets:Vector.<DisplayObject>):Vector.<DisplayObject> + + /** + * Aligns all the target DisplayObjects by their bottom edges to the bottom-most target. + * + * Similar to the Flash IDE Alignment panel. + */ + alignBottom(targets:Vector.<DisplayObject>):Vector.<DisplayObject> + + /** + * Aligns all the target DisplayObjects by their horizontal center edges to the horizontal center of the all the targets. + * + * Similar to the Flash IDE Alignment panel. + */ + alignHorizontalCenter(targets:Vector.<DisplayObject>):Vector.<DisplayObject> + + /** + * Aligns all the target DisplayObjects by their vertical center edges to the vertical center of the all the targets. + * + * Similar to the Flash IDE Alignment panel. + */ + alignVerticalCenter(targets:Vector.<DisplayObject>):Vector.<DisplayObject> + +alignToLeftEdge(of:DisplayObject, ...targets) + +alignLeftEdges(...targets):Array +alignRightEdges(...targets):Array +alignTopEdges(...targets):Array +alignBottomEdges(...targets):Array +alignCenters(...targets):Array + +distributeByLeftEdge(...targets):Array +distributeByRightEdge(...targets):Array +distributeByTopEdge(...targets):Array +distributeByBottomEdge(...targets):Array +distributeByHorizontalCenter(...targets):Array +distributeByVerticalCenter(...targets):Array + +# ARRAY + +utils.array.contains():int + badly named, should be something like numReferencesInArray, arrayRefCount + +utils.array.copyArray() + remove, pointless, use array.slice() instead. + +utils.array.createUniqueCopy +utils.array.removeDuplicates + duplicates asx.array.unique + +utils.array.arraysAreEqual +utils.array.equals + duplicates + +utils.array.getHighestValue +utils.array.getLowestValue + use the Array constants, not magic numbers + +utils.array.randomize + too much code for what it does + could be faster + +utils.array.removeItem +utils.array.removeValueFromArray + duplicates + +utils.array.retainItems + duplicates asx.array.union + +utils.array.sum + duplicates asx.array.sum + +# ASSERT + +utils.assert.* + suggestion: use the assertions provided by hamcrest-as3 or flexunit + should throw an AssertionError instead of Error + +utils.capabilities.getPlayerInfo + dubious value + +# CAPABILITIES + +utils.capabilities.isMac +utils.capabilities.isPC + change isMac to be !isPC + DRY + +# COLOR + +utils.color.randomColor + implementation is whack, why convert to a Number to a String to a Number? + +utils.color.toGrayscale + which reference was used for the mix ratios? + +# COOKIE + +utils.cookie.setCookie + potential global javascript namespace pollution + +# DATE + +utils.date.toRFC822 + missing result examples, and appears to reference the wrong RFC number + +utils.date.toW3CDTF + missing result examples + +# DISPLAY + +utils.display.addTargetToParent + dubious value + uses a switch for two values + uses magic numbers + +utils.display.Alignment + values should be same as key + move to utils.align.Alignment + eg BOTTOM_LEFT:String = "BOTTOM_LEFT" + +utils.display.sumProps + remove + replace with utils.number.sum, asx.object.pluck + +# ERROR + +utils.error.getStackTrace + no try-catch required + return new Error().getStackTrace(); + dubious value + +# EVENT + +utils.event.addTargetEventListener +utils.event.removeTargetEventListener + dubious value + +# FRAME + +utils.frame.addFrameScript +utils.frame.removeFrameScript + needs an appropriate error message + can multiple framescripts exist on a single frame? + +# GEOM + +utils.geom.Point3D + move static methods to instance method, both deal with Point3D as arguments, and there are already instance methods for add, subtract, offset + +# NUMBER + +utils.number.clamp +utils.number.confine +utils.number.constrain +utils.range.resolve + duplicates asx.number.bound + replace with clamp + +utils.number.insertCommas + there is easier way to do this, using reverse, split and join + +utils.number.isBetween + duplicates asx.number.between + +# RANGE + +utils.range.resolve + duplicates utils.number.clamp etc + +# STRING + +utils.string.addSlashes + bad name, escapeChars is more accurate + +utils.string.slashUnsafeChars + bad name, escapeRegExpChars is more accurate + +utils.string.constants + bad name, separate to package level or rename + +utils.string.firstToUpper + bad name, rename to capitalize + +utils.string.replace + dubious value + +utils.string.stripSlashes + bad name, unescapeChars + \ No newline at end of file
as3/as3-utils
d1d0a161c6321018f098fa883ac41834e08da483
reimplemented alignLeft, alignRight to behave like the Align panel in Flash IDE.
diff --git a/src/utils/align/alignLeft.as b/src/utils/align/alignLeft.as index 42c850e..8bb810b 100644 --- a/src/utils/align/alignLeft.as +++ b/src/utils/align/alignLeft.as @@ -1,13 +1,66 @@ package utils.align { - import flash.display.DisplayObject; - /** - * Left align object to target. + * Aligns all the target DisplayObjects by their left edge to the left-most target. + * + * Similar to the Flash IDE Alignment panel. + * + * Given the following arrangement of targets: + * <code> + * t1 + * t2 + * t3 + * </code> + * + * After calling <code>alignLeft([ t1, t2, t3 ])</code> the arrangment will be: + * <code> + * t1 + * t2 + * t3 + * </code> + * + * @param targets Array of DisplayObject (or Object with an <code>x</code> property like <code>Point</code>). + * @return targets Array. + * + * @example + * <listing version="3.0"> + * var t1:Sprite = new Sprite(); + * t1.x = 5; + * + * var t2:Sprite = new Sprite(); + * t2.x = 30; + * + * var t3:Sprite = new Sprite(); + * t3.x = 15; + * + * var targets:Array = [t1, t2, t3]; + * alignLeft(targets); + * + * trace(t1.x, t2.x t3.x); + * // 5 5 5 + * </listing> + * + * @author drewbourne */ - public function alignLeft(item:DisplayObject, target:DisplayObject):void + public function alignLeft(targets:Array):Array { - xAlignLeft(item, target); - yAlignLeft(item, target); + var minX:Number = Number.MAX_VALUE; + var targetX:Number; + var target:Object; + + for each (target in targets) + { + targetX = target.x; + + if (targetX < minX) + minX = targetX; + } + + for each (target in targets) + { + target.x = minX; + } + + return targets; } } \ No newline at end of file diff --git a/src/utils/align/alignRight.as b/src/utils/align/alignRight.as index 23ac020..8a91d44 100644 --- a/src/utils/align/alignRight.as +++ b/src/utils/align/alignRight.as @@ -1,13 +1,59 @@ package utils.align { - import flash.display.DisplayObject; - /** - * Right align object to target. + * Aligns all the target DisplayObjects by their left edge to the left-most target. + * + * Similar to the Flash IDE Alignment panel. + * + * Given the following arrangement of targets: + * <code> + * t1 + * t2 + * t3 + * </code> + * + * After calling <code>alignRight([ t1, t2, t3 ])</code> the arrangment will be: + * <code> + * t1 + * t2 + * t3 + * </code> + * + * @param targets Array of DisplayObject + * or Object with an <code>x</code> property like <code>Point</code> + * or Object with an <code>x</code> and <code>width</code> properties like <code>Rectangle</code>. + * + * @return targets Array. + * + * @example + * <listing version="3.0"> + * + * </listing> + * + * @author drewbourne */ - public function alignRight(item:DisplayObject, target:DisplayObject):void + public function alignRight(targets:Array):Array { - xAlignRight(item, target); - yAlignRight(item, target); + var maxX:Number = Number.MIN_VALUE; + var targetW:Number; + var targetX:Number; + var target:Object; + + for each (target in targets) + { + targetW = "width" in target ? target["width"] : 0; + targetX = target.x + targetW; + + if (targetX > maxX) + maxX = targetX; + } + + for each (target in targets) + { + targetW = "width" in target ? target["width"] : 0; + target.x = maxX - targetW; + } + + return targets; } } \ No newline at end of file diff --git a/test/utils/align/AlignLeftTest.as b/test/utils/align/AlignLeftTest.as new file mode 100644 index 0000000..e26324e --- /dev/null +++ b/test/utils/align/AlignLeftTest.as @@ -0,0 +1,37 @@ +package utils.align +{ + import flash.display.DisplayObject; + import flash.display.Sprite; + + import org.hamcrest.assertThat; + import org.hamcrest.collection.array; + import org.hamcrest.object.hasProperties; + + import utils.object.create; + + public class AlignLeftTest + { + public var targets:Array; + + [Before] + public function setup():void + { + targets = [ create(Sprite, null, { x: 5, y: 15 }) + , create(Sprite, null, { x: 15, y: 50 }) + , create(Sprite, null, { x: 50, y: 5 }) + ]; + } + + [Test] + public function alignLeftShouldAlignLeftEdgesOfTargetsToLeftMostTarget():void + { + assertThat( + "alignLeft set the x of each target to 5" + , alignLeft(targets) + , array(hasProperties({ x: 5, y: 15 }) + , hasProperties({ x: 5, y: 50 }) + , hasProperties({ x: 5, y: 5 }) + )); + } + } +} \ No newline at end of file diff --git a/test/utils/align/AlignRightTest.as b/test/utils/align/AlignRightTest.as new file mode 100644 index 0000000..bf02300 --- /dev/null +++ b/test/utils/align/AlignRightTest.as @@ -0,0 +1,78 @@ +package utils.align +{ + import flash.display.DisplayObject; + import flash.display.Shape; + import flash.display.Sprite; + import flash.geom.Point; + + import org.hamcrest.assertThat; + import org.hamcrest.collection.array; + import org.hamcrest.object.hasProperties; + + import utils.object.create; + + public class AlignRightTest + { + public var targets:Array; + + [Before] + public function setup():void + { + targets = [ create(Square, [20], { x: 5, y: 15 }) + , create(Square, [100], { x: 15, y: 50 }) + , create(Square, [50], { x: 50, y: 5 }) + ]; + } + + [Test] + public function alignRightShouldAlignRightEdgesOfTargetsToRightMostTarget():void + { + assertThat( + "alignRight" + , alignRight(targets) + , array(hasProperties({ x: 95, y: 15 }) + , hasProperties({ x: 15, y: 50 }) + , hasProperties({ x: 65, y: 5 }) + )); + } + + [Test] + public function alignRightShouldWorkForWidthlessObjects():void + { + targets = [ new Point(5, 15) + , new Point(15, 50) + , new Point(50, 5) + ]; + + assertThat( + "alignRight" + , alignRight(targets) + , array(hasProperties({ x: 50, y: 15 }) + , hasProperties({ x: 50, y: 50 }) + , hasProperties({ x: 50, y: 5 }) + )); + } + } +} + +import flash.display.Shape; + +internal class Square extends Shape +{ + public function Square(size:int = 50) + { + graphics.beginFill(0xFFFFFF, 1.0); + graphics.drawRect(0, 0, size, size); + graphics.endFill(); + } + + override public function toString():String + { + return "[Square" + + " x=" + x + + " y=" + y + + " w=" + width + + " h=" + height + + "]"; + } +} \ No newline at end of file
as3/as3-utils
420212ef88077d6484012593e719f81e316834c4
fixed ASDoc errors with unencoded html-entities
diff --git a/src/utils/color/averageBlue.as b/src/utils/color/averageBlue.as index 7bee2b5..177d77f 100644 --- a/src/utils/color/averageBlue.as +++ b/src/utils/color/averageBlue.as @@ -1,17 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** - * Sample & average the <i>Blue</i> (RGB) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>blue</i> value on a scale of 0-255. + * Sample &amp; average the <i>Blue</i> (RGB) value from a display object or one of its region. + * + * @param src The DisplayObject + * @param accuracy Percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>blue</i> value on a scale of 0-255. */ public function averageBlue(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'b'); } } \ No newline at end of file diff --git a/src/utils/color/averageGreen.as b/src/utils/color/averageGreen.as index 3ed17d7..621701d 100644 --- a/src/utils/color/averageGreen.as +++ b/src/utils/color/averageGreen.as @@ -1,17 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** - * Sample & average the <i>Green</i> (RGB) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>green</i> value on a scale of 0-255. + * Sample &amp; average the <i>Green</i> (RGB) value from a display object or one of its region. + * + * @param src The DisplayObject + * @param accuracy Percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>green</i> value on a scale of 0-255. */ public function averageGreen(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'g'); } } \ No newline at end of file diff --git a/src/utils/color/averageHue.as b/src/utils/color/averageHue.as index 6ab347d..dbad89d 100644 --- a/src/utils/color/averageHue.as +++ b/src/utils/color/averageHue.as @@ -1,17 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** - * Sample & average the <i>Hue</i> (HSL) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>hue</i> value on a scale of 0-360. + * Sample &amp; average the <i>Hue</i> (HSL) value from a display object or one of its region. + * + * @param src The DisplayObject + * @param accuracy percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>hue</i> value on a scale of 0-360. */ public function averageHue(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'h'); } } \ No newline at end of file diff --git a/src/utils/color/averageLightness.as b/src/utils/color/averageLightness.as index e4cea14..067ed86 100644 --- a/src/utils/color/averageLightness.as +++ b/src/utils/color/averageLightness.as @@ -1,17 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** - * Sample & average the <i>Lightness</i> (HSL) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>lightness</i> value on a scale of 0-255. + * Sample &amp; average the <i>Lightness</i> (HSL) value from a display object or one of its region. + * + * @param src The DisplayObject + * @param accuracy percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>lightness</i> value on a scale of 0-255. */ public function averageLightness(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'l'); } } \ No newline at end of file diff --git a/src/utils/color/averageRed.as b/src/utils/color/averageRed.as index b278f0b..1dfd769 100644 --- a/src/utils/color/averageRed.as +++ b/src/utils/color/averageRed.as @@ -1,19 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; - // BITMAP VALUE AVERAGING - /** - * Sample & average the <i>Red</i> (RGB) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>red</i> value on a scale of 0-255. + * Sample &amp; average the <i>Red</i> (RGB) value from a display object or one of its region. + * + * @param src The DisplayObject. + * @param accuracy Percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>red</i> value on a scale of 0-255. */ public function averageRed(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):int { return averageColorProperty(src, region, accuracy, 'r'); } } \ No newline at end of file diff --git a/src/utils/color/averageSaturation.as b/src/utils/color/averageSaturation.as index 81b8ce4..3fba545 100644 --- a/src/utils/color/averageSaturation.as +++ b/src/utils/color/averageSaturation.as @@ -1,17 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** - * Sample & average the <i>Saturation</i> (HSL) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>saturation</i> value on a scale of 0-1. + * Sample &amp; average the <i>Saturation</i> (HSL) value from a display object or one of its region. + * + * @param src The DisplayObject. + * @param accuracy percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>saturation</i> value on a scale of 0-1. */ public function averageSaturation(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):Number { return averageColorProperty(src, region, accuracy, 's'); } } \ No newline at end of file diff --git a/src/utils/color/averageValue.as b/src/utils/color/averageValue.as index 9498187..e0d4687 100644 --- a/src/utils/color/averageValue.as +++ b/src/utils/color/averageValue.as @@ -1,17 +1,18 @@ package utils.color { import flash.display.DisplayObject; import flash.geom.Rectangle; /** - * Sample & average the <i>Value</i> (HSV) value from a display object or one of its region. - * @param src of the display object. - * @param accuracy percentage of pixels to sample when averaging. - * @param region to sample from [Default: null = entire src object]. - * @return the sampled average <i>lightness</i> value on a scale of 0-1. + * Sample &amp; average the <i>Value</i> (HSV) value from a display object or one of its region. + * + * @param src The DisplayObject + * @param accuracy percentage of pixels to sample when averaging. + * @param region to sample from [Default: null = entire src object]. + * @return the sampled average <i>lightness</i> value on a scale of 0-1. */ public function averageValue(src:DisplayObject, accuracy:Number = 0.01, region:Rectangle = null):Number { return averageColorProperty(src, region, accuracy, 'v'); } } \ No newline at end of file diff --git a/src/utils/display/Alignment.as b/src/utils/display/Alignment.as index e71a1c6..9b6042c 100644 --- a/src/utils/display/Alignment.as +++ b/src/utils/display/Alignment.as @@ -1,45 +1,45 @@ package utils.display { /** - * @author Justin Windle ([email protected]) + * @author Justin Windle (justin(at)soulwire.co.uk) */ public class Alignment { /** * Specifies that alignment is at the bottom. */ public static const BOTTOM : String = "B"; /** * Specifies that alignment is in the bottom-left corner. */ public static const BOTTOM_LEFT : String = "BL"; /** * Specifies that alignment is in the bottom-right corner. */ public static const BOTTOM_RIGHT : String = "BR"; /** * Specifies that alignment is on the left. */ public static const LEFT : String = "L"; /** * Specifies that alignment is in the middle */ public static const MIDDLE : String = "C"; /** * Specifies that alignment is on the right. */ public static const RIGHT : String = "R"; /** * Specifies that alignment is at the top. */ public static const TOP : String = "T"; /** * Specifies that alignment is in the top-left corner. */ public static const TOP_LEFT : String = "TL"; /** * Specifies that alignment is in the top-right corner. */ public static const TOP_RIGHT : String = "TR"; } } diff --git a/src/utils/display/filterChildrenByProps.as b/src/utils/display/filterChildrenByProps.as index e102375..3eef6cb 100644 --- a/src/utils/display/filterChildrenByProps.as +++ b/src/utils/display/filterChildrenByProps.as @@ -1,27 +1,27 @@ package utils.display { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; public function filterChildrenByProps(container:DisplayObjectContainer, props:Object):Array { var filteredChildren:Array = []; var child:DisplayObject; - for (var i:int = 0, l = container.numChildren; i < l; i++) + for (var i:int = 0, l:int = container.numChildren; i < l; i++) { child = container.getChildAt(i); var isOK:Boolean = true; for (var prop:String in props) { if (child[prop] != props[prop]) { isOK = false; break; } } if (isOK) filteredChildren.push(child); } return filteredChildren; } } \ No newline at end of file diff --git a/src/utils/display/setProperties.as b/src/utils/display/setProperties.as index b0111a8..78d466e 100644 --- a/src/utils/display/setProperties.as +++ b/src/utils/display/setProperties.as @@ -1,17 +1,17 @@ package utils.display { import flash.display.DisplayObject; public function setProperties(children:Array, props:Object):void { var child:DisplayObject; - for (var i:int = 0, l = children.length; i < l; i++) + for (var i:int = 0, l:int = children.length; i < l; i++) { child = children[i]; for (var prop:String in props) { child[prop] = props[prop]; } } } } \ No newline at end of file diff --git a/src/utils/display/sumProps.as b/src/utils/display/sumProps.as index 6dfe865..a77e8c2 100644 --- a/src/utils/display/sumProps.as +++ b/src/utils/display/sumProps.as @@ -1,12 +1,12 @@ package utils.display { public function sumProps(children:Array, prop:String):Number { var sum:Number = 0; - for (var i:int = 0, l = children.length; i < l; i++) + for (var i:int = 0, l:int = children.length; i < l; i++) { sum += children[i][prop]; } return sum; } } \ No newline at end of file diff --git a/src/utils/number/getWeightedAverage.as b/src/utils/number/getWeightedAverage.as index 357a627..5f60ef3 100644 --- a/src/utils/number/getWeightedAverage.as +++ b/src/utils/number/getWeightedAverage.as @@ -1,17 +1,24 @@ package utils.number { /** - Low pass filter alogrithm for easing a value toward a destination value. Works best for tweening values when no definite time duration exists and when the destination value changes. - - If <code>(0.5 < n < 1)</code>, then the resulting values will overshoot (ping-pong) until they reach the destination value. When <code>n</code> is greater than 1, as its value increases, the time it takes to reach the destination also increases. A pleasing value for <code>n</code> is 5. - - @param value: The current value. - @param dest: The destination value. - @param n: The slowdown factor. - @return The weighted average. + * Low pass filter alogrithm for easing a value toward a destination value. + * Works best for tweening values when no definite time duration exists and + * when the destination value changes. + * + * When <code>(0.5 &gt; n &gt; 1)</code>, then the resulting values will + * overshoot (ping-pong) until they reach the destination value. + * + * When <code>n</code> is greater than 1, as its value increases, the time + * it takes to reach the destination also increases. A pleasing value for + * <code>n</code> is 5. + * + * @param value The current value. + * @param dest The destination value. + * @param n The slowdown factor. + * @return The weighted average. */ public function getWeightedAverage(value:Number, dest:Number, n:Number):Number { return value + (dest - value) / n; } } \ No newline at end of file diff --git a/src/utils/object/copy.as b/src/utils/object/copy.as index e1cc0ce..d23b093 100644 --- a/src/utils/object/copy.as +++ b/src/utils/object/copy.as @@ -1,27 +1,27 @@ package utils.object { /** * Copy an object * @param obj Object to copy * @param into (optional) Object to copy into. If null, a new object * is created. * @return A one-level deep copy of the object or null if the argument * is null * @author Jackson Dunstan */ public function copy(obj:Object, into:Object = null):Object { if (into == null) { into = {}; } if (obj != null) { - for (var o in obj) + for (var o:Object in obj) { into[o] = obj[o]; } } return into; } } \ No newline at end of file diff --git a/src/utils/object/inspect.as b/src/utils/object/inspect.as index 425a564..0082552 100644 --- a/src/utils/object/inspect.as +++ b/src/utils/object/inspect.as @@ -1,34 +1,34 @@ package utils.object { import flash.utils.describeType; public function inspect(obj:Object, depth:int = 2):String { var scan:Function = function(obj:Object, depth:int, prefix:String):String { if (depth < 1) return String(obj); const classDef:XML = describeType(obj); var str:String = ""; for each(var variable:XML in classDef.variable) { str += prefix + variable.@name + " : " + scan(obj[variable.@name], depth - 1, prefix + "\t") + "\n"; } /*for each(var accessor:XML in classDef.accessor.(@access == "readwrite" || @access == "readonly")) { str += prefix + accessor.@name + " : " + scan(obj[accessor.@name], depth - 1, prefix + "\t") + "\n"; }*/ - for (var s in obj) + for (var s:Object in obj) { str += prefix + s + " = " + scan(obj[s], depth - 1, prefix + "\t") + "\n"; } return str != "" ? ("[" + classDef.@name + "] {\n" + str + prefix + "}\n") : ((obj != null) ? obj + "" : "null"); } return scan(obj, depth, ""); } } \ No newline at end of file diff --git a/src/utils/object/toString.as b/src/utils/object/toString.as index 1ab1c60..9ed7493 100644 --- a/src/utils/object/toString.as +++ b/src/utils/object/toString.as @@ -1,31 +1,35 @@ package utils.object { /** - * Convert the object to a string of form: PROP: VAL&PROP: VAL where: - * PROP is a property - * VAL is its corresponding value - * & is the specified optional delimiter - * @param obj Object to convert - * @param delimiter (optional) Delimiter of property/value pairs - * @return An string of all property/value pairs delimited by the - * given string or null if the input object or delimiter is - * null. - * @author Jackson Dunstan + * Convert the object to a string of form: <code>PROP: VAL&amp;PROP: VAL</code> + * where: + * <ul> + * <li><code>PROP</code> is a property</li> + * <li><code>VAL</code> is its corresponding value</li> + * <li>&amp; is the specified optional delimiter</li> + * </ul> + * + * @param obj Object to convert + * @param delimiter (optional) Delimiter of property/value pairs + * @return An string of all property/value pairs delimited by the + * given string or null if the input object or delimiter is + * null. + * @author Jackson Dunstan */ public function toString(obj:Object = null, delimiter:String = "\n"):String { if (obj == null || delimiter == null) { return ""; } else { var ret:Array = []; - for (var s in obj) + for (var s:Object in obj) { ret.push(s + ": " + obj[s]); } return ret.join(delimiter); } } } \ No newline at end of file diff --git a/src/utils/swf/SWFReader.as b/src/utils/swf/SWFReader.as index b7b3805..7144ff1 100644 --- a/src/utils/swf/SWFReader.as +++ b/src/utils/swf/SWFReader.as @@ -1,710 +1,712 @@ package utils.swf { import flash.display.ActionScriptVersion; import flash.geom.*; import flash.utils.ByteArray; import flash.utils.Endian; /** * Reads the bytes of a SWF (as a ByteArray) to acquire * information from the SWF file header. Some of * this information is inaccessible to ActionScript * otherwise. */ public class SWFReader { // properties starting with those // found first in the byte stream /** * Indicates whether or not the SWF * is compressed. */ public var compressed:Boolean; /** * The major version of the SWF. */ public var version:uint; /** * The file size of the SWF. */ public var fileSize:uint; // compression starts here if SWF compressed: /** * The dimensions of the SWF in the form of * a Rectangle instance. */ public function get dimensions():Rectangle { return _dimensions; } private var _dimensions:Rectangle = new Rectangle(); // dimensions gets accessor since we don't // want people nulling the rect; it should // always have a value, even if 0-ed /** * Width of the stage as defined by the SWF. * Same as dimensions.width. */ public function get width():uint { return uint(_dimensions.width); } /** * Height of the stage as defined by the SWF. * Same as dimensions.height. */ public function get height():uint { return uint(_dimensions.height); } /** * When true, the bytes supplied in calls made to the tagCallback * function includes the RECORDHEADER of that tag which includes * the tag and the size of the tag. By default (false) this * information is not included. */ public function get tagCallbackBytesIncludesHeader():Boolean { return _tagCallbackBytesIncludesHeader; } public function set tagCallbackBytesIncludesHeader(value:Boolean):void { _tagCallbackBytesIncludesHeader = value; } private var _tagCallbackBytesIncludesHeader:Boolean = false; /** * The frame rate of the SWF in frames * per second. */ public var frameRate:uint; /** * The total number of frames of the SWF. */ public var totalFrames:uint; /** * ActionScript version. */ public var asVersion:uint; /** * Determines local playback security; when * true, indicates that when this file is * run locally, it can only access the network. * When false, only local files can be accessed. * This does not apply when the SWF is being * run in a local-trusted sandbox. */ public var usesNetwork:Boolean; /** * The background color of the SWF. */ public var backgroundColor:uint; /** * Determines if the SWF is protected from * being imported into an authoring tool. */ public var protectedFromImport:Boolean; /** * Determines if remote debugging is enabled. */ public var debuggerEnabled:Boolean; /** * The XMP metadata defined in the SWF. */ public var metadata:XML; /** * Maximun allowed levels of recursion. */ public var recursionLimit:uint; /** * Time in seconds a script will run in a * single frame before a timeout error * occurs. */ public var scriptTimeoutLimit:uint; /** * The level of hardware acceleration specified * for the SWF. 0 is none, 1 is direct, and 2 * is GPU (Flash Player 10+). */ public var hardwareAcceleration:uint; /** * A callback function that will be called when * a tag is read during the parse process. The * callback function should contain the parameters * (tag:uint, bytes:ByteArray). */ public var tagCallback:Function; /** * Indicates that the SWF bytes last provided * were successfully parsed. If the SWF bytes * were not successfully parsed, no SWF data * will be available. */ public var parsed:Boolean; /** * The Flash Player error message that resulted * from the error that caused a parse to fail. */ public var errorText:String = ""; // keeping track of data private var bytes:ByteArray; private var currentByte:int; // used in bit reading private var bitPosition:int; // used in bit reading private var currentTag:uint; // tag flags private var bgColorFound:Boolean; // constants private const GET_DATA_SIZE:int = 5; private const TWIPS_TO_PIXELS:Number = 0.05; // 20 twips in a pixel private const TAG_HEADER_ID_BITS:int = 6; private const TAG_HEADER_MAX_SHORT:int = 0x3F; private const SWF_C:uint = 0x43; // header characters private const SWF_F:uint = 0x46; private const SWF_W:uint = 0x57; private const SWF_S:uint = 0x53; private const TAG_ID_EOF:uint = 0; // recognized SWF tags private const TAG_ID_BG_COLOR:uint = 9; private const TAG_ID_PROTECTED:uint = 24; private const TAG_ID_DEBUGGER1:uint = 58; private const TAG_ID_DEBUGGER2:uint = 64; private const TAG_ID_SCRIPT_LIMITS:uint = 65; private const TAG_ID_FILE_ATTS:uint = 69; private const TAG_ID_META:uint = 77; private const TAG_ID_SHAPE_1:uint = 2; private const TAG_ID_SHAPE_2:uint = 22; private const TAG_ID_SHAPE_3:uint = 32; private const TAG_ID_SHAPE_4:uint = 83; /** * SWFHeader constructor. * @param swfBytes Bytes of the SWF in a ByteArray. * You can get the bytes of a SWF by loading it into * a URLLoader or using Loader.bytes once a SWF has * been loaded into that Loader. */ public function SWFReader(swfBytes:ByteArray = null) { parse(swfBytes); } /** * Provides a string presentation of the SWFHeader * object which outlines the different values * obtained from a parsed SWF * @return The String form of the instance */ public function toString():String { if (parsed) { var compression:String = (compressed) ? "compressed" : "uncompressed"; var frames:String = totalFrames > 1 ? "frames" : "frame"; return "[SWF" + version + " AS"+asVersion+".0: " + totalFrames + " "+frames+" @ " + frameRate + " fps " + _dimensions.width + "x" + _dimensions.height + " " + compression + "]"; } // default toString if SWF not parsed return Object.prototype.toString.call(this) as String; } /** * Parses the bytes of a SWF file to extract * properties from its header. * @param swfBytes Bytes of a SWF to parse. */ public function parse(swfBytes:ByteArray):void { parseDefaults(); // null bytes, exit if (swfBytes == null) { parseError("Error: Cannot parse a null value."); return; } // assume at start parse completed successfully // on failure, this will be set to false parsed = true; // -------------------------------------- // HEADER // -------------------------------------- try { // try to parse the bytes. Failures // results in cleared values for the data bytes = swfBytes; bytes.endian = Endian.LITTLE_ENDIAN; bytes.position = 0; // get header characters var swfFC:uint = bytes.readUnsignedByte(); // F, or C if compressed var swfW:uint = bytes.readUnsignedByte(); // W var swfS:uint = bytes.readUnsignedByte(); // S // validate header characters if ((swfFC != SWF_F && swfFC != SWF_C) || swfW != SWF_W || swfS != SWF_S) { parseError("Error: Invalid SWF header."); return; } compressed = Boolean(swfFC == SWF_C); // == SWF_F if not compressed version = bytes.readUnsignedByte(); fileSize = bytes.readUnsignedInt(); // mostly redundant since we should have full bytes // if compressed, need to uncompress // the data after the first 8 bytes // (first 8 already read above) if (compressed) { // use a temporary byte array to // represent the compressed portion // of the SWF file var temp:ByteArray = new ByteArray(); bytes.readBytes(temp); bytes = temp; bytes.endian = Endian.LITTLE_ENDIAN; bytes.position = 0; temp = null; // temp no longer needed bytes.uncompress(); // Note: at this point, the original // uncompressed 8 bytes are no longer // part of the current bytes byte array } _dimensions = readRect(); bytes.position++; // one up after rect frameRate = bytes.readUnsignedByte(); totalFrames = bytes.readUnsignedShort(); }catch (error:Error) { // header parse error parseError(error.message); return; } // -------------------------------------- // TAGS // -------------------------------------- // read all the tags in the file // up until the END tag try { - while(readTag()); + while(readTag()) { + // noop + } }catch (error:Error) { // error in tag parsing. EOF would throw // an error, but the END tag should be // reached before that occurs parseError(error.message); return; } // parse completed successfully! // null bytes since no longer needed bytes = null; } /** * Defines default values for all the class * properties. This is used to have accurate * values for properties which may not be * present in the SWF file such as asVersion * which is only required to be specified in * SWF8 and above (in FileAttributes tag). */ private function parseDefaults():void { compressed = false; version = 1; // SWF1 fileSize = 0; _dimensions = new Rectangle(); frameRate = 12; // default from Flash authoring (flex == 24) totalFrames = 1; metadata = null; asVersion = ActionScriptVersion.ACTIONSCRIPT2; // 2 if not explicit usesNetwork = false; backgroundColor = 0xFFFFFF; // white background protectedFromImport = false; debuggerEnabled = true; scriptTimeoutLimit = 256; recursionLimit = 15; hardwareAcceleration = 0; errorText = ""; // clear existing error text // tag helper flags bgColorFound = false; } /** * Clears variable data and logs an error * message. */ private function parseError(message:String = "Unkown error."):void { compressed = false; version = 0; fileSize = 0; _dimensions = new Rectangle(); frameRate = 0; totalFrames = 0; metadata = null; asVersion = 0; usesNetwork = false; backgroundColor = 0; protectedFromImport = false; debuggerEnabled = false; scriptTimeoutLimit = 0; recursionLimit = 0; hardwareAcceleration = 0; parsed = false; bytes = null; errorText = message; } /** * Utility to convert a unit value into a string * in hex style padding value with "0" characters. * @return The string representation of the hex value. */ private function paddedHex(value:uint, numChars:int = 6):String { var str:String = value.toString(16); while (str.length < numChars) str = "0" + str; return "0x" + str; } /** * Reads a string in the byte stream by * reading all bytes until a null byte (0) * is reached. * @return The string having been read. */ private function readString():String { // find ending null character that // terminates the string var i:uint = bytes.position; try { while(bytes[i] != 0) i++; }catch (error:Error) { return ""; } // null byte should have been found // return the read string return bytes.readUTFBytes(i - bytes.position); } /** * Reads RECT data from the current * location in the current bytes object * @return A rectangle object whose values * match those of the RECT read. */ private function readRect():Rectangle { nextBitByte(); var rect:Rectangle = new Rectangle(); var dataSize:uint = readBits(GET_DATA_SIZE); rect.left = readBits(dataSize, true)*TWIPS_TO_PIXELS; rect.right = readBits(dataSize, true)*TWIPS_TO_PIXELS; rect.top = readBits(dataSize, true)*TWIPS_TO_PIXELS; rect.bottom = readBits(dataSize, true)*TWIPS_TO_PIXELS; return rect; } private function readMatrix():Matrix { nextBitByte(); var dataSize:uint; var matrix:Matrix = new Matrix(); if (readBits(1)){ // has scale dataSize = readBits(GET_DATA_SIZE); matrix.a = readBits(dataSize, true); matrix.d = readBits(dataSize, true); } if (readBits(1)){ // has rotation dataSize = readBits(GET_DATA_SIZE); matrix.b = readBits(dataSize, true); matrix.c = readBits(dataSize, true); } // translation dataSize = readBits(GET_DATA_SIZE); matrix.tx = readBits(dataSize, true)*TWIPS_TO_PIXELS; matrix.ty = readBits(dataSize, true)*TWIPS_TO_PIXELS; return matrix; } /** * Reads a series of bits from the current byte * defined by currentByte based on the but at * position bitPosition. If more bits are required * than are available in the current byte, the next * byte in the bytes array is read and the bits are * taken from there to complete the request. * @param numBits The number of bits to read. * @return The bits read as a uint. */ private function readBits(numBits:uint, signed:Boolean = false):Number { var value:Number = 0; // int or uint var remaining:uint = 8 - bitPosition; var mask:uint; // can get all bits from current byte if (numBits <= remaining){ mask = (1 << numBits) - 1; value = (currentByte >> (remaining - numBits)) & mask; if (numBits == remaining) nextBitByte(); else bitPosition += numBits; // have to get bits from 2 (or more) // bytes the current and the next (recursive) }else{ mask = (1 << remaining) - 1; var firstValue:uint = currentByte & mask; var over:uint = numBits - remaining; nextBitByte(); value = (firstValue << over) | readBits(over); } // convert to signed int if signed bitflag exists if (signed && value >> (numBits - 1) == 1){ remaining = 32 - numBits; // 32-bit uint mask = (1 << remaining) - 1; return int(mask << numBits | value); } // unsigned int return uint(value); } /** * Reads the next byte in the stream assigning * it to currentByte and resets the value of * bitPosition to 0. */ private function nextBitByte():void { currentByte = bytes.readByte(); bitPosition = 0; } /** * Parses the tag at the current byte location. * @return false if the tag read is the END tag; * true if more tags should be present in the file. */ private function readTag():Boolean { var currentTagPosition:uint = bytes.position; // read tag header var tagHeader:int = bytes.readUnsignedShort(); currentTag = tagHeader >> TAG_HEADER_ID_BITS; var tagLength:uint = tagHeader & TAG_HEADER_MAX_SHORT; // if a long tag, the tag length will be // set to its maximum. If so, set // the tag length to the long length if (tagLength == TAG_HEADER_MAX_SHORT) { tagLength = bytes.readUnsignedInt(); } // when the tag is read, the position // of the byte stream must be set to the // end of this tag for the start of the next // tag. This assures the correct position // no matter what happens in readTagData() var nextTagPosition:uint = bytes.position + tagLength; // read the data in the tag (if supported) var moreTags:Boolean = readTagData(tagLength, currentTagPosition, nextTagPosition); if (!moreTags) return false; // end tag // next tag bytes.position = nextTagPosition; return true; } /** * Called from readTag, this parses the value of individual * tag based on the tag id read in the tag header. * @param tag A tag object containing a tag's id and length. * @param start The start position of the full tag. * @param end The end position of the full tag. * @return false if the tag read is the END tag; * true if more tags should be present in the file. */ private function readTagData(tagLength:uint, start:uint, end:uint):Boolean { // if defined, call the tag callback with // the tag id and a copy of the bytes // specific to the tag if (tagCallback != null) { var tagBytes:ByteArray = new ByteArray(); if (_tagCallbackBytesIncludesHeader){ tagBytes.writeBytes(bytes, start, end - start); }else{ if (tagLength){ tagBytes.writeBytes(bytes, bytes.position, tagLength); } } tagBytes.position = 0; tagCallback(currentTag, tagBytes); } // handle each tag individually based on // it's tag id switch (currentTag) { // FileAttributes tag was only required for // SWF 8 and later. Calling defaults() // assures default values for the properties // determined here if the tag is not present case TAG_ID_FILE_ATTS: nextBitByte(); // read file attributes in bits readBits(1); // reserved hardwareAcceleration = readBits(2); readBits(1); // hasMetaData; auto-determined by tag asVersion = (readBits(1) && version >= 9) ? ActionScriptVersion.ACTIONSCRIPT3 : ActionScriptVersion.ACTIONSCRIPT2; readBits(2); // reserved (2) usesNetwork = Boolean(readBits(1) == 1); // bunch of others reserved after this break; // Metadata in a SWF is in the format of // XMP XML. Though the FileAttributes will // determine if it is present, it's easier to // just check for the metadata tag id case TAG_ID_META: try { metadata = new XML(readString()); }catch (error:Error) { // error reading string or parsing as XML } break; // Many background colors could potentially exist // for a single SWF, but we're assuming there's // only one. If there are more, the first will be used case TAG_ID_BG_COLOR: // check the bg color found flag // if true, we want to ignore all other colors // since they would be added after this one if (!bgColorFound) { bgColorFound = true; backgroundColor = readRGB(); } break; // Only determines if the SWF is protected from // import; a password, if provided, will not // be retrieved from the SWF case TAG_ID_PROTECTED: protectedFromImport = Boolean(bytes.readUnsignedByte() != 0); // password if needed break; // the debugger 1 tag is for SWF5 only // the debugger 2 tag is for SWF6+ case TAG_ID_DEBUGGER1: if (version == 5) debuggerEnabled = true; // password if needed break; case TAG_ID_DEBUGGER2: if (version > 5) debuggerEnabled = true; // password if needed break; // for both timeout and recursion but I don't // think any tool lets you set recursion case TAG_ID_SCRIPT_LIMITS: recursionLimit = bytes.readUnsignedShort(); scriptTimeoutLimit = bytes.readUnsignedShort(); break; case TAG_ID_EOF: return false; // end of file break; default: // unrecognized tag by this parser; do nothing // if you want to support other tags // make sure they're caught above in // this switch statement. break; } // not last tag, continue reading return true; } private function readRGB():uint { return (bytes.readUnsignedByte() << 16) // R | (bytes.readUnsignedByte() << 8) // G | bytes.readUnsignedByte(); // B } private function readARGB():uint { return (bytes.readUnsignedByte() << 24) // A | (bytes.readUnsignedByte() << 16) // R | (bytes.readUnsignedByte() << 8) // G | bytes.readUnsignedByte(); // B } private function readRGBA():uint { var rByte:uint = bytes.readUnsignedByte(); // R var gByte:uint = bytes.readUnsignedByte(); // G var bByte:uint = bytes.readUnsignedByte(); // B var aByte:uint = bytes.readUnsignedByte(); // A return (aByte << 24) // A | (rByte << 16) // R | (gByte << 8) // G | bByte; // B } } } \ No newline at end of file diff --git a/src/utils/textField/setStyledText.as b/src/utils/textField/setStyledText.as index 6805199..65f89d9 100644 --- a/src/utils/textField/setStyledText.as +++ b/src/utils/textField/setStyledText.as @@ -1,18 +1,20 @@ package utils.textField { import flash.text.StyleSheet; import flash.text.TextField; /** - * Apply a <code>StyleSheet</code> to a <code>TextField</code> & set its contents. - * @param tf <code>TextField</code> to display. - * @param str of text to apply. - * @param stylesheet to apply to the <code>TextField</code>'s (Default: <code>App.css</code>). + * Apply a <code>StyleSheet</code> to a <code>TextField</code> &amp; set its contents. + * + * @param tf <code>TextField</code> to display. + * @param str of text to apply. + * @param stylesheet to apply to the <code>TextField</code>'s (Default: <code>App.css</code>). + * * @see sekati.core.App#css */ public function setStyledText(tf:TextField, str:String, stylesheet:StyleSheet = null):void { styleFields(tf, stylesheet); tf.htmlText = str; } } \ No newline at end of file diff --git a/src/utils/validation/encodeCreditCardNumber.as b/src/utils/validation/encodeCreditCardNumber.as index 6533f27..06d3dbf 100644 --- a/src/utils/validation/encodeCreditCardNumber.as +++ b/src/utils/validation/encodeCreditCardNumber.as @@ -1,23 +1,27 @@ package utils.validation { /** - * Encode a credit card number as a string and encode all digits except the last </code>digitsShown</code>. + * Encode a credit card number as a string and encode all digits except the + * last <code>digitsShown</code>. + * * @param strNumber credit card number as string * @param digitsShown display this many digits at the end of the card number for security purposes * @param encodeChar optional encoding character to use instead of default '*' - * @example <listing version="3.0"> + * + * @example + * <listing version="3.0"> * trace(CreditCardValidator.EncodeNumber("1234567890123456")); // ************3456 * trace(CreditCardValidator.EncodeNumber("1234567890123456", 5, "x")); // xxxxxxxxxxx23456 * </listing> */ public function encodeCreditCardNumber(strNumber:String, digitsShown:uint = 4, encodeChar:String = "*"):String { var encoded:String = ""; for (var i:Number = 0; i < strNumber.length - digitsShown; i++) { encoded += encodeChar; } encoded += strNumber.slice(-digitsShown); return encoded; } } \ No newline at end of file
as3/as3-utils
0944ff8f7c00ae85dd447d2e3d961df8f2890e22
updating readme
diff --git a/README.md b/README.md index dcc9128..d9720e9 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,42 @@ # as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? HEAPS, too much to list here right now. Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html - number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) - You. # Giving credit where credit is due - Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. \ No newline at end of file +Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. \ No newline at end of file
as3/as3-utils
c57898c5c828fab90cb90aee21bd31cc94f2a800
updating readme
diff --git a/README.md b/README.md index 71672b5..dcc9128 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,42 @@ # as3-utils ActionScript 3 Utilities and Object Extensions provided as reusable package-level functions that solve common problems. # What have you got for me? HEAPS, too much to list here right now. Oh ok here's a taste, there are umpteen utils for - array - color - conversions - date - event - garbage collection - html - number - string - validation - and [more](http://github.com/as3/as3-utils/tree/master/src/utils/). # Gimme some utils Got Git? Lets go! $ git clone git://github.com/as3/as3-utils.git $ ant # Got something to share? Fork the [as3-utils project](http://github.com/as3/as3-utils) on GitHub, see the [forking guide](http://help.github.com/forking/) and then send a pull request. # Contributors - John Lindquist [@johnlindquist](http://twitter.com/johnlindquist) - Drew Bourne [@drewbourne](http://twitter.com/drewbourne) -- You. \ No newline at end of file +- You. + +# Giving credit where credit is due + + Many of these utils are copy/pasted from open-source projects from around the web. We will attribute functions to their creators (it's on our list of things to do) and we hope function authors understand that we're not trying to take credit for their work. We don't want credit, we just want a collection of great open-source utils supported by the community. \ No newline at end of file
as3/as3-utils
53c905acec5ac80838e9ccf200ddf780b78d28ba
ignore generated directories
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ce8a1a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +target +bin +bin-debug +bin-release \ No newline at end of file
as3/as3-utils
0263a176ea94f33418ec585c24bf11f48824b0a4
fix asdoc error about @see and HTML
diff --git a/src/utils/validation/isEmail.as b/src/utils/validation/isEmail.as index 5c7cfc0..1306842 100644 --- a/src/utils/validation/isEmail.as +++ b/src/utils/validation/isEmail.as @@ -1,15 +1,15 @@ package utils.validation { /** Determines if String is a valid email address. @param email: String to verify as email. @return Returns <code>true</code> if String is a valid email; otherwise <code>false</code>. - @see <a href="http://www.regular-expressions.info/email.html">Read more about the regular expression used by this method.</a> + @see http://www.regular-expressions.info/email.html Read more about the regular expression used by this method. */ public function isEmail(email:String):Boolean { var pattern:RegExp = /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; return email.match(pattern) != null; } } \ No newline at end of file
as3/as3-utils
940ee8da6d079bdaf1047ca407916db20d8ddd68
build.xml: clean, initialize, compile, test, report, doc, package.
diff --git a/build.properties b/build.properties new file mode 100644 index 0000000..6ec6a0f --- /dev/null +++ b/build.properties @@ -0,0 +1,12 @@ +project.name=as3-utils + +build.groupId=as3 +build.artifactId=as3-utils +build.version=0.1 +build.artifact=${build.artifactId}-${build.version} + +test.runner=UtilsTestRunner +test.runner.ext=as + +flexunit.version=4.0.0 +flexpmd.version=1.1 \ No newline at end of file diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..f6581cc --- /dev/null +++ b/build.xml @@ -0,0 +1,236 @@ +<?xml version="1.0"?> +<project + name="as3-utils" + basedir="." + default="package"> + + <!-- + as3-utils + + usage: + $ ant -v clean package + + @author drewbourne + --> + + <!-- properties --> + <property environment="env" /> + <property file="build.properties" /> + + <!-- paths: existing --> + <property name="src.loc" location="${basedir}/src" /> + <property name="test.loc" location="${basedir}/test" /> + <property name="lib.loc" location="${basedir}/libs" /> + <property name="build.loc" location="${basedir}/build" /> + <property name="build.pmd.loc" location="${build.loc}/pmd" /> + <property name="build.flexunit.loc" location="${build.loc}/flexunit" /> + + <!-- paths: enerated --> + <property name="dist.loc" location="${basedir}/target" /> + <property name="bin.loc" location="${dist.loc}/bin" /> + <property name="doc.loc" location="${dist.loc}/doc" /> + <property name="report.loc" location="${dist.loc}/report" /> + <property name="report.flexunit.loc" location="${report.loc}/flexunit" /> + + <!-- Flex SDK --> + <property name="FLEX_HOME" location="${env.FLEX_HOME}" /> + + <!-- taskdefs --> + <taskdef resource="flexTasks.tasks" + classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> + + <!-- targets --> + <target + name="clean" + description="Removes generated artifacts and directories"> + + <delete dir="${dist.loc}" /> + + </target> + + <target + name="initialize" + description="Creates generated directories "> + + <mkdir dir="${dist.loc}" /> + <mkdir dir="${bin.loc}" /> + <mkdir dir="${doc.loc}" /> + <mkdir dir="${report.loc}" /> + <mkdir dir="${report.flexunit.loc}" /> + + </target> + + <target + name="compile-check-if-required" + description="Checks if a compile is required" + depends="initialize"> + + <uptodate + property="compile.not-required" + targetfile="${bin.loc}/${build.artifact}.swc"> + <srcresources> + <fileset dir="${src.loc}"> + <include name="**/*.as" /> + <include name="**/*.mxml" /> + </fileset> + <fileset dir="${lib.loc}"> + <include name="**/*.swc" /> + </fileset> + </srcresources> + </uptodate> + + </target> + + <target + name="compile" + description="Compiles the library" + depends="initialize, compile-check-if-required" + unless="compile.not-required"> + + <compc output="${bin.loc}/${build.artifact}.swc"> + <source-path path-element="${src.loc}" /> + + <include-sources dir="${src.loc}"> + <include name="**/*.as" /> + <include name="**/*.mxml" /> + </include-sources> + + <library-path dir="${lib.loc}" append="true"> + <include name="*.swc" /> + </library-path> + + <compiler.verbose-stacktraces>true</compiler.verbose-stacktraces> + <compiler.headless-server>true</compiler.headless-server> + </compc> + + </target> + + <target name="test" + description="Run the test suite" + depends="initialize"> + + <taskdef resource="flexUnitTasks.tasks" + classpath="${build.flexunit.loc}/flexUnitTasks-${flexunit.version}.jar" /> + + <!-- Compile Test --> + <mxmlc + file="${test.loc}/${test.runner}.${test.runner.ext}" + output="${bin.loc}/${test.runner}.swf"> + + <library-path dir="${bin.loc}" append="true"> + <include name="${build.artifact}.swc" /> + </library-path> + + <library-path dir="${lib.loc}" append="true"> + <include name="*.swc" /> + </library-path> + + <compiler.verbose-stacktraces>true</compiler.verbose-stacktraces> + <compiler.headless-server>true</compiler.headless-server> + </mxmlc> + + <!-- Execute Tests --> + <flexunit + swf="${bin.loc}/${test.runner}.swf" + toDir="${report.flexunit.loc}" + headless="true" + haltonfailure="false" + verbose="true" + localTrusted="true" /> + + </target> + + <target name="report" + description="Generates test reports from FlexUnit, FlexPMD, FlexCPD, FlexMetrics" + depends="test"> + + <!-- Generate readable report for FlexUnit --> + <junitreport todir="${report.flexunit.loc}"> + <fileset dir="${report.flexunit.loc}"> + <include name="TEST-*.xml" /> + </fileset> + <report format="frames" todir="${report.flexunit.loc}/html" /> + </junitreport> + + <!-- FlexPMD config --> + <path id="flexpmd.base"> + <pathelement location="${build.pmd.loc}/as3-parser-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/as3-parser-api-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/as3-plugin-utils-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/flex-pmd-files-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/pmd-4.2.5.jar" /> + </path> + + <taskdef name="pmd" classname="com.adobe.ac.pmd.ant.FlexPmdAntTask" classpath="${build.pmd.loc}/flex-pmd-ant-task-${flexpmd.version}.jar"> + <classpath> + <path refid="flexpmd.base" /> + <pathelement location="${build.pmd.loc}/commons-lang-2.4.jar" /> + <pathelement location="${build.pmd.loc}/flex-pmd-core-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/flex-pmd-ruleset-api-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/flex-pmd-ruleset-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/plexus-utils-1.0.2.jar" /> + </classpath> + </taskdef> + + <taskdef name="cpd" classname="com.adobe.ac.cpd.ant.FlexCpdAntTask" classpath="${build.pmd.loc}/flex-pmd-cpd-ant-task-${flexpmd.version}.jar"> + <classpath> + <path refid="flexpmd.base" /> + <pathelement location="${build.pmd.loc}/flex-pmd-cpd-${flexpmd.version}.jar" /> + </classpath> + </taskdef> + + <taskdef name="metrics" classname="com.adobe.ac.pmd.metrics.ant.FlexMetricsAntTask" classpath="${build.pmd.loc}/flex-pmd-metrics-ant-task-${flexpmd.version}.jar"> + <classpath> + <path refid="flexpmd.base" /> + <pathelement location="${build.pmd.loc}/commons-lang-2.4.jar" /> + <pathelement location="${build.pmd.loc}/dom4j-1.6.1.jar" /> + <pathelement location="${build.pmd.loc}/flex-pmd-metrics-${flexpmd.version}.jar" /> + <pathelement location="${build.pmd.loc}/flex-pmd-ruleset-api-${flexpmd.version}.jar" /> + </classpath> + </taskdef> + + <!-- Executions --> + <pmd sourceDirectory="${src.loc}" outputDirectory="${report.loc}" /> + + <cpd minimumTokenCount="50" outputFile="${report.loc}/cpd.xml"> + <fileset dir="${src.loc}"> + <include name="**/*.as" /> + <include name="**/*.mxml" /> + </fileset> + </cpd> + + <metrics sourcedirectory="${src.loc}" outputfile="${report.loc}/javancss.xml" /> + + </target> + + <target name="doc" + description="Generate ASDoc for ${ant.project.name}" + depends="initialize"> + + <!-- Generate asdocs --> + <java jar="${FLEX_HOME}/lib/asdoc.jar" fork="true" failonerror="true"> + <arg line="+flexlib '${FLEX_HOME}/frameworks'" /> + <arg line="-doc-sources '${src.loc}'" /> + <arg line="-source-path+='${src.loc}'" /> + <arg line="-output '${doc.loc}'" /> + <arg line="-main-title '${project.name} API Documentation'" /> + <arg line="-window-title '${project.name} API Documentation'" /> + </java> + + </target> + + <target name="package" + description="Package ${ant.project.name} into a zip" + depends="compile, test, report, doc"> + + <!-- Create distribution for binaries with docs --> + <zip destfile="${dist.loc}/${build.artifact}.zip"> + <zipfileset dir="${bin.loc}"> + <include name="${build.artifact}.swc" /> + </zipfileset> + <zipfileset dir="${doc.loc}" prefix="doc" /> + </zip> + + </target> + +</project> \ No newline at end of file diff --git a/build/flexunit/flexUnitTasks-4.0.0.jar b/build/flexunit/flexUnitTasks-4.0.0.jar new file mode 100644 index 0000000..c4686a9 Binary files /dev/null and b/build/flexunit/flexUnitTasks-4.0.0.jar differ diff --git a/build/pmd/LICENSE.txt b/build/pmd/LICENSE.txt new file mode 100644 index 0000000..c2ef16c --- /dev/null +++ b/build/pmd/LICENSE.txt @@ -0,0 +1,28 @@ + Copyright (c) 2009, Adobe Systems, Incorporated + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + * Neither the name of the Adobe Systems, Incorporated. nor the names of + its contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/build/pmd/as3-parser-1.1.jar b/build/pmd/as3-parser-1.1.jar new file mode 100644 index 0000000..b48151c Binary files /dev/null and b/build/pmd/as3-parser-1.1.jar differ diff --git a/build/pmd/as3-parser-api-1.1.jar b/build/pmd/as3-parser-api-1.1.jar new file mode 100644 index 0000000..89b6d50 Binary files /dev/null and b/build/pmd/as3-parser-api-1.1.jar differ diff --git a/build/pmd/as3-plugin-utils-1.1.jar b/build/pmd/as3-plugin-utils-1.1.jar new file mode 100644 index 0000000..f684289 Binary files /dev/null and b/build/pmd/as3-plugin-utils-1.1.jar differ diff --git a/build/pmd/commons-lang-2.4.jar b/build/pmd/commons-lang-2.4.jar new file mode 100644 index 0000000..532939e Binary files /dev/null and b/build/pmd/commons-lang-2.4.jar differ diff --git a/build/pmd/dom4j-1.6.1.jar b/build/pmd/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/build/pmd/dom4j-1.6.1.jar differ diff --git a/build/pmd/flex-pmd-ant-task-1.1.jar b/build/pmd/flex-pmd-ant-task-1.1.jar new file mode 100644 index 0000000..c0efeb4 Binary files /dev/null and b/build/pmd/flex-pmd-ant-task-1.1.jar differ diff --git a/build/pmd/flex-pmd-command-line-1.1.jar b/build/pmd/flex-pmd-command-line-1.1.jar new file mode 100644 index 0000000..9f28c1b Binary files /dev/null and b/build/pmd/flex-pmd-command-line-1.1.jar differ diff --git a/build/pmd/flex-pmd-command-line-api-1.1.jar b/build/pmd/flex-pmd-command-line-api-1.1.jar new file mode 100644 index 0000000..efee2df Binary files /dev/null and b/build/pmd/flex-pmd-command-line-api-1.1.jar differ diff --git a/build/pmd/flex-pmd-core-1.1.jar b/build/pmd/flex-pmd-core-1.1.jar new file mode 100644 index 0000000..8c753a5 Binary files /dev/null and b/build/pmd/flex-pmd-core-1.1.jar differ diff --git a/build/pmd/flex-pmd-cpd-1.1.jar b/build/pmd/flex-pmd-cpd-1.1.jar new file mode 100644 index 0000000..24bdf3b Binary files /dev/null and b/build/pmd/flex-pmd-cpd-1.1.jar differ diff --git a/build/pmd/flex-pmd-cpd-ant-task-1.1.jar b/build/pmd/flex-pmd-cpd-ant-task-1.1.jar new file mode 100644 index 0000000..e114b1f Binary files /dev/null and b/build/pmd/flex-pmd-cpd-ant-task-1.1.jar differ diff --git a/build/pmd/flex-pmd-cpd-command-line-1.1.jar b/build/pmd/flex-pmd-cpd-command-line-1.1.jar new file mode 100644 index 0000000..6d96d0c Binary files /dev/null and b/build/pmd/flex-pmd-cpd-command-line-1.1.jar differ diff --git a/build/pmd/flex-pmd-files-1.1.jar b/build/pmd/flex-pmd-files-1.1.jar new file mode 100644 index 0000000..2ee7905 Binary files /dev/null and b/build/pmd/flex-pmd-files-1.1.jar differ diff --git a/build/pmd/flex-pmd-metrics-1.1.jar b/build/pmd/flex-pmd-metrics-1.1.jar new file mode 100644 index 0000000..0dfa304 Binary files /dev/null and b/build/pmd/flex-pmd-metrics-1.1.jar differ diff --git a/build/pmd/flex-pmd-metrics-ant-task-1.1.jar b/build/pmd/flex-pmd-metrics-ant-task-1.1.jar new file mode 100644 index 0000000..4dcadc8 Binary files /dev/null and b/build/pmd/flex-pmd-metrics-ant-task-1.1.jar differ diff --git a/build/pmd/flex-pmd-metrics-command-line-1.1.jar b/build/pmd/flex-pmd-metrics-command-line-1.1.jar new file mode 100644 index 0000000..848a337 Binary files /dev/null and b/build/pmd/flex-pmd-metrics-command-line-1.1.jar differ diff --git a/build/pmd/flex-pmd-ruleset-1.1.jar b/build/pmd/flex-pmd-ruleset-1.1.jar new file mode 100644 index 0000000..36bf912 Binary files /dev/null and b/build/pmd/flex-pmd-ruleset-1.1.jar differ diff --git a/build/pmd/flex-pmd-ruleset-api-1.1.jar b/build/pmd/flex-pmd-ruleset-api-1.1.jar new file mode 100644 index 0000000..a701a00 Binary files /dev/null and b/build/pmd/flex-pmd-ruleset-api-1.1.jar differ diff --git a/build/pmd/jsap-2.1.jar b/build/pmd/jsap-2.1.jar new file mode 100644 index 0000000..15d1f37 Binary files /dev/null and b/build/pmd/jsap-2.1.jar differ diff --git a/build/pmd/plexus-utils-1.0.2.jar b/build/pmd/plexus-utils-1.0.2.jar new file mode 100644 index 0000000..63b4486 Binary files /dev/null and b/build/pmd/plexus-utils-1.0.2.jar differ diff --git a/build/pmd/pmd-4.2.5.jar b/build/pmd/pmd-4.2.5.jar new file mode 100644 index 0000000..f43f8c7 Binary files /dev/null and b/build/pmd/pmd-4.2.5.jar differ diff --git a/libs/flexunit-4.0.0.swc b/libs/flexunit-4.0.0.swc new file mode 100644 index 0000000..72373d9 Binary files /dev/null and b/libs/flexunit-4.0.0.swc differ diff --git a/libs/flexunit-cilistener-4.0.0.swc b/libs/flexunit-cilistener-4.0.0.swc new file mode 100644 index 0000000..0c215c4 Binary files /dev/null and b/libs/flexunit-cilistener-4.0.0.swc differ diff --git a/libs/flexunit-uilistener-4.0.0.swc b/libs/flexunit-uilistener-4.0.0.swc new file mode 100644 index 0000000..3b1de14 Binary files /dev/null and b/libs/flexunit-uilistener-4.0.0.swc differ diff --git a/test/UtilsTestRunner.as b/test/UtilsTestRunner.as new file mode 100644 index 0000000..dd297a2 --- /dev/null +++ b/test/UtilsTestRunner.as @@ -0,0 +1,31 @@ +package +{ + import flash.display.Sprite; + + import org.flexunit.internals.TraceListener; + import org.flexunit.listeners.CIListener; + import org.flexunit.runner.FlexUnitCore; + + import utils.UtilsTestSuite; + + [SWF] + + public class UtilsTestRunner extends Sprite + { + public var core:FlexUnitCore; + + public function UtilsTestRunner() + { + super(); + run(); + } + + public function run():void + { + core = new FlexUnitCore(); + core.addListener(new TraceListener()); + core.addListener(new CIListener()); + core.run(UtilsTestSuite); + } + } +} \ No newline at end of file diff --git a/test/utils/UtilsTestSuite.as b/test/utils/UtilsTestSuite.as new file mode 100644 index 0000000..7dc7cf0 --- /dev/null +++ b/test/utils/UtilsTestSuite.as @@ -0,0 +1,9 @@ +package utils +{ + [Suite] + [RunWith("org.flexunit.runners.Suite")] + public class UtilsTestSuite + { + + } +} \ No newline at end of file
pattex/jekyll_scaffold
5d96d200e833fb0691d97d35f6280de21b82a8b5
Added a gitignore file.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cf30e03 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +_site/*
pattex/jekyll_scaffold
5b3693fc8612f217ca5c13eecd1d20f6c648177d
Page title should link to home.
diff --git a/_layouts/default.html b/_layouts/default.html index c0b1893..e3aa4a9 100644 --- a/_layouts/default.html +++ b/_layouts/default.html @@ -1,17 +1,17 @@ <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>{{ site.title }}: {{ page.title }}</title> <meta name="author" content="{{ site.author }}" /> <link href="atom.xml" rel="alternate" title="{{ site.title }}" type="application/atom+xml" /> <link rel="stylesheet" href="/css/screen.css" type="text/css" media="screen, projection" /> </head> <body> - <h1><a href="{{ first_post.url }}" title="{{ site.title }}">{{ site.title }}</a></h1> + <h1><a href="/" title="{{ site.title }}">{{ site.title }}</a></h1> {{ content }} </body> </html>
pattex/jekyll_scaffold
58ed661f5241c62c3631584658c02f8c9d202552
Useless junk removed.
diff --git a/_config.yml b/_config.yml index c74001e..c7cb024 100644 --- a/_config.yml +++ b/_config.yml @@ -1,5 +1,4 @@ ---- - url: http://example.com/jjjsite/ - author: John Doe - email: [email protected] - title: johns juicy joke site \ No newline at end of file +url: http://example.com/jjjsite/ +author: John Doe +email: [email protected] +title: johns juicy joke site \ No newline at end of file
pattex/jekyll_scaffold
5d6720a110e1343fcc2ba30cc73abf49c4f31dd2
Redundant "/" removed.
diff --git a/atom.xml b/atom.xml index 1b13e6e..fd2315b 100644 --- a/atom.xml +++ b/atom.xml @@ -1,27 +1,27 @@ --- layout: nil --- <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>{{ site.title }}</title> - <link href="{{ site.url }}/atom.xml" rel="self"/> + <link href="{{ site.url }}atom.xml" rel="self"/> <link href="{{ site.url }}"/> <updated>{{ site.time | date_to_xmlschema }}</updated> <id>{{ site.url }}</id> <author> <name>{{ site.author }}</name> <email>{{ site.email }}</email> </author> {% for post in site.posts %} <entry> <title>{{ post.title }}</title> <link href="{{ site.url }}{{ post.url }}"/> <updated>{{ post.date | date_to_xmlschema }}</updated> <id>{{ site.url }}{{ post.id }}</id> <content type="html">{{ post.content | xml_escape }}</content> </entry> {% endfor %} </feed>
pattex/jekyll_scaffold
6137888535e314ca268be2a279a303bc7d273ef1
Added a readme file.
diff --git a/README.textile b/README.textile new file mode 100644 index 0000000..4031c77 --- /dev/null +++ b/README.textile @@ -0,0 +1,28 @@ +h1. Jekyll Scaffold + +I made a few websites lately. For generating the static HTML i used "Jekyll":http://github.com/mojombo/jekyll/ which i really like. But to save oneself to do the same steps again and again i made me this little scaffold. + +h2. Usage + +# Clone this repository. +@git clone git://github.com/pattex/jekyll_scaffold.git my_site@ +# Edit @_config.yml@ like you want it to be. +# Let Jekyll do the work for you and check if everything is well done. +@cd my_site +jekyll --server@ +# Do your changes, like replacing the dummy posts with some more impressive stuff and adding a beautiful design. + +h2. License + +<p xmlns:dct="http://purl.org/dc/terms/" xmlns:vcard="http://www.w3.org/2001/vcard-rdf/3.0#"> + <a rel="license" href="http://creativecommons.org/publicdomain/zero/1.0/" style="text-decoration:none;"> + <img src="http://i.creativecommons.org/l/zero/1.0/88x31.png" border="0" alt="CC0" /> + </a> + <br /> + To the extent possible under law, + <span rel="dct:publisher" resource="[_:publisher]">the person who associated CC0</span> + with this work has waived all copyright and related or neighboring + rights to this work. +</p> + +THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file
lfundaro/GoogleCodeJam
d89720f5b05b989c22a8003bca8bb15c96a703a4
Changed index start.
diff --git a/codejam-2011/store_credit/s_sol.hs b/codejam-2011/store_credit/s_sol.hs index ee79bce..851ebd8 100644 --- a/codejam-2011/store_credit/s_sol.hs +++ b/codejam-2011/store_credit/s_sol.hs @@ -1,56 +1,56 @@ import Data.List (genericSplitAt) type Index = Integer type II = (Integer,Index) index :: [Integer] -> [II] -index x = zip x [0..] +index x = zip x [1..] norep :: (II,II) -> Bool norep ((a,c),(b,d)) = not (a == b && c == d) combine :: [II] -> [ (II,II) ] combine x = filter norep $ [ ((a,c),(b,d)) | (a,c) <- x , (b,d) <- x ] seed :: Integer -> (Index,Index,Integer,Integer) seed credit = (-1,-1,credit,credit) disc :: (Index,Index,Integer,Integer) -> (II,II) -> (Index,Index,Integer,Integer) disc old@(i1,i2,cr,diff) ((a,c),(b,d)) = let cdiff = (cr - (a + b)) in if cdiff >= 0 then if cdiff < diff then (c,d,cr,cdiff) else old else old credit :: Integer -> [(II,II)] -> (Index,Index,Integer,Integer) credit credit = foldl disc (seed credit) -- returns problems as a tuple of items and credit parseCases :: [Integer] -> [([Integer],Integer)] parseCases (numCases:xs) = go xs where go [] = [] go (credit:times:rest) = let (art,next) = genericSplitAt times rest in (art,credit) : go next solve :: ([Integer],Integer) -> (Integer,Integer) solve (art,cr) = let (i1,i2,_,_) = credit cr (combine.index $ art) in if i1 <= i2 then - (i1+1,i2+1) + (i1,i2) else - (i2+1,i1+1) + (i2,i1) main :: IO () main = do file <- getContents let raw = (map read (words file)) :: [Integer] let cases = parseCases raw let results = map solve cases putStr (concatMap (\(i,n) -> "Case #" ++ show i ++ ": " ++ show n ++ "\n") (zip [1..] results)) \ No newline at end of file
lfundaro/GoogleCodeJam
cc85f49cebd582adc30919cdb43c50d9dd39c4eb
Added input example.
diff --git a/codejam-2011/store_credit/input b/codejam-2011/store_credit/input new file mode 100644 index 0000000..6ab4b08 --- /dev/null +++ b/codejam-2011/store_credit/input @@ -0,0 +1,10 @@ +3 +100 +3 +5 75 25 +200 +7 +150 24 79 50 88 345 3 +8 +8 +2 1 9 4 4 56 90 3 \ No newline at end of file
lfundaro/GoogleCodeJam
da8c0ba0af2cfba9db2b09fa693f2ec0694f4a74
Added input and output processing.
diff --git a/codejam-2011/store_credit/s_sol.hs b/codejam-2011/store_credit/s_sol.hs index d224bd0..ee79bce 100644 --- a/codejam-2011/store_credit/s_sol.hs +++ b/codejam-2011/store_credit/s_sol.hs @@ -1,33 +1,56 @@ +import Data.List (genericSplitAt) + type Index = Integer type II = (Integer,Index) index :: [Integer] -> [II] index x = zip x [0..] norep :: (II,II) -> Bool norep ((a,c),(b,d)) = not (a == b && c == d) combine :: [II] -> [ (II,II) ] combine x = filter norep $ [ ((a,c),(b,d)) | (a,c) <- x , (b,d) <- x ] seed :: Integer -> (Index,Index,Integer,Integer) seed credit = (-1,-1,credit,credit) disc :: (Index,Index,Integer,Integer) -> (II,II) -> (Index,Index,Integer,Integer) disc old@(i1,i2,cr,diff) ((a,c),(b,d)) = let cdiff = (cr - (a + b)) in if cdiff >= 0 then if cdiff < diff then (c,d,cr,cdiff) else old else old credit :: Integer -> [(II,II)] -> (Index,Index,Integer,Integer) credit credit = foldl disc (seed credit) --- main = do --- :( i need a monad to do this ... - +-- returns problems as a tuple of items and credit +parseCases :: [Integer] -> [([Integer],Integer)] +parseCases (numCases:xs) = go xs + where + go [] = [] + go (credit:times:rest) = let (art,next) = genericSplitAt times rest + in (art,credit) : go next + +solve :: ([Integer],Integer) -> (Integer,Integer) +solve (art,cr) = let (i1,i2,_,_) = credit cr (combine.index $ art) + in + if i1 <= i2 then + (i1+1,i2+1) + else + (i2+1,i1+1) + +main :: IO () +main = do + file <- getContents + let raw = (map read (words file)) :: [Integer] + let cases = parseCases raw + let results = map solve cases + putStr (concatMap (\(i,n) -> "Case #" ++ show i ++ ": " ++ show n ++ "\n") + (zip [1..] results)) \ No newline at end of file
lfundaro/GoogleCodeJam
618f93ad662ea432ea8c1109902a21ebcceee4d9
Added ghci based solution for the Store Credit problem - South Africa 2010. I still need to figure out input and output.
diff --git a/codejam-2011/store_credit/s_sol.hs b/codejam-2011/store_credit/s_sol.hs new file mode 100644 index 0000000..d224bd0 --- /dev/null +++ b/codejam-2011/store_credit/s_sol.hs @@ -0,0 +1,33 @@ +type Index = Integer +type II = (Integer,Index) + +index :: [Integer] -> [II] +index x = zip x [0..] + +norep :: (II,II) -> Bool +norep ((a,c),(b,d)) = not (a == b && c == d) + +combine :: [II] -> [ (II,II) ] +combine x = filter norep $ [ ((a,c),(b,d)) | (a,c) <- x , (b,d) <- x ] + +seed :: Integer -> (Index,Index,Integer,Integer) +seed credit = (-1,-1,credit,credit) + +disc :: (Index,Index,Integer,Integer) -> (II,II) -> (Index,Index,Integer,Integer) +disc old@(i1,i2,cr,diff) ((a,c),(b,d)) = + let cdiff = (cr - (a + b)) in + if cdiff >= 0 then + if cdiff < diff then + (c,d,cr,cdiff) + else + old + else + old + +credit :: Integer -> [(II,II)] -> (Index,Index,Integer,Integer) +credit credit = foldl disc (seed credit) + +-- main = do +-- :( i need a monad to do this ... + + \ No newline at end of file
lfundaro/GoogleCodeJam
09694bcd5d53e963f905404b07b71930eff33500
Agregando el problema del Google Code Jam Qualification Round Africa and Arabia 2011 de nombre 'Closing the Loop'
diff --git a/codejam-2011/closing_the_loop/loop.py b/codejam-2011/closing_the_loop/loop.py new file mode 100644 index 0000000..c53abd7 --- /dev/null +++ b/codejam-2011/closing_the_loop/loop.py @@ -0,0 +1,53 @@ +import sys + +# calculates the size of the rope loop given the two lists +# of ropes by color +def size_of_loop(list1,list2): + + #if any of the list is empty there is no loop + if ((not list1) or (not list2)): + return 0 + + #order from greater to lower + list1.sort(reverse=True) + list2.sort(reverse=True) + + #calculate the maximum set of best sizes + min_length = min(len(list1),len(list2)) + small_list_1 = list1[:min_length] + small_list_2 = list2[:min_length] + + loop_size = sum(small_list_1) + sum(small_list_2) - (len(small_list_1)+len(small_list_2)) + return loop_size + +def parse_file(in_file): + num_cases = int(in_file.readline()) + cases = [num_cases,[],[]] + for c in range(num_cases): + num_values = int(in_file.readline()) + rope_list = in_file.readline().strip('\n').split() + blue_list, red_list = parse_list(rope_list) + cases[1].append(blue_list) + cases[2].append(red_list) + + return cases + +def parse_list(rope_list): + blue_list = [] + red_list = [] + for e in rope_list: + if e[-1]=='R': + red_list.append(int(e[:-1])) + else: + blue_list.append(int(e[:-1])) + return [blue_list,red_list] + +out_file = open('output.out','w+') +in_file = sys.stdin +num_cases, blue_list, red_list = parse_file(in_file) + +for c in range(1,num_cases+1): + case = 'Case #'+str(c)+': ' + result= case+ str(size_of_loop(blue_list[c-1],red_list[c-1]))+'\n' + out_file.write(result) +
lfundaro/GoogleCodeJam
2c8e3fc7e8d2b80e889cb4e3cc00e773abfaab55
Adding Python solution for t9 spelling and small/large output
diff --git a/javier/t9spelling/t9spelling.py b/javier/t9spelling/t9spelling.py new file mode 100644 index 0000000..5741667 --- /dev/null +++ b/javier/t9spelling/t9spelling.py @@ -0,0 +1,31 @@ + + +#Translate the given word 'word' using the letters dictionary +#letters-to-numbers given in dict +def trans_word(word,dic): + word.lower() + last ='none' + res=[] + for l in word: + if (dic[last][0]==dic[l][0]): + res.append(' '+dic[l]) + else: + res.append(dic[l]) + last = l + + return ''.join(res) + + +import sys + +out_file = open('output.out','w+') +in_file = sys.stdin +num_cases = int(in_file.readline()) + +ldic = {'a':'2','b':'22','c':'222','d':'3','e':'33','f':'333','g':'4','h':'44','i':'444','j':'5','k':'55','l':'555','m':'6','n':'66','o':'666','p':'7','q':'77','r':'777','s':'7777','t':'8','u':'88','v':'888','w':'9','x':'99','y':'999','z':'9999',' ':'0','none':'-1'} + +for c in range(1,num_cases+1): + word = in_file.readline().strip('\n') + case = 'Case #'+str(c)+': ' + out_file.write(case+trans_word(word,ldic)+'\n') +
lfundaro/GoogleCodeJam
86389d4a48fbfd7d4e86228750943ba18814af7b
Changin some small features to improve speed... Improves just a bit -> The fact of using lists makes it crappy. Important: This problem is so an efficient access and distribution of memory problem. So C/C++. Be careful, be efficient from the beginning
diff --git a/javier/crop-triangles/crop.py b/javier/crop-triangles/crop.py index 774efa8..9820169 100644 --- a/javier/crop-triangles/crop.py +++ b/javier/crop-triangles/crop.py @@ -1,48 +1,55 @@ # Google code jam - Online round 1B # Crop triangles - Small # Javier Fernandez: [email protected] import sys out_file = open('output.out','w+') in_file = sys.stdin num_cases = int(in_file.readline()) # sort and add to set def ord_set(set,list): element.sort() set.add(element) for c in range(1,num_cases+1): n,A,B,C,D,x0,y0,M = map(int,in_file.readline().split()) points =[] # google snippet X = x0 Y = y0 points.append((X,Y)) for i in range(1,n): X = (A * X + B) % M Y = (C * Y + D) % M points.append((X,Y)) # kinda ugly multiple iteration , maybe possible to make # it more beautiful with map and comprehension list # the multiple cicle is inevitable. Optimized with # progressive checking in the same array [ci:] and [cj:] triangles = [] count = 0 ci=0 cj=0 - for i in points: + + lp = len(points) + while(ci<lp):#while's used to avoid list cutting cj=ci+1 - for j in points[ci:]:#Avoid previous tuples - for k in points[cj:]: - if (((i[0]+j[0]+k[0])%3 ==0) and ((i[1]+j[1]+k[1])%3 ==0)): - t = [i,j,k] - triangles.append(t) + while(cj<lp): + ck=cj+1 + while(ck<lp): + pi=points[ci] + pj=points[cj] + pk=points[ck] + if ((pi[0]+pj[0]+pk[0])%3 ==0): + if ((pi[1]+pj[1]+pk[1])%3 ==0): + t = [pi,pj,pk] count+=1 + ck+=1 cj+=1 ci+=1 out_file.write('Case #'+str(c)+': '+str(count)+'\n')
lfundaro/GoogleCodeJam
e38d991019fb5fa33b305ef6eb146f86f19cfa91
Adding code for crop-triangles . It only solves the small input, no doubt that python is not good for this problem. There are optimizations that can be done at the beginning for avoiding unnecessary comparisons, but mostly organizing the pairs in a matrix.
diff --git a/javier/crop-triangles/crop.py b/javier/crop-triangles/crop.py new file mode 100644 index 0000000..774efa8 --- /dev/null +++ b/javier/crop-triangles/crop.py @@ -0,0 +1,48 @@ +# Google code jam - Online round 1B +# Crop triangles - Small +# Javier Fernandez: [email protected] + +import sys +out_file = open('output.out','w+') +in_file = sys.stdin +num_cases = int(in_file.readline()) + +# sort and add to set +def ord_set(set,list): + element.sort() + set.add(element) + +for c in range(1,num_cases+1): + n,A,B,C,D,x0,y0,M = map(int,in_file.readline().split()) + points =[] + # google snippet + X = x0 + Y = y0 + points.append((X,Y)) + for i in range(1,n): + X = (A * X + B) % M + Y = (C * Y + D) % M + points.append((X,Y)) + + # kinda ugly multiple iteration , maybe possible to make + # it more beautiful with map and comprehension list + + # the multiple cicle is inevitable. Optimized with + # progressive checking in the same array [ci:] and [cj:] + triangles = [] + count = 0 + ci=0 + cj=0 + for i in points: + cj=ci+1 + for j in points[ci:]:#Avoid previous tuples + for k in points[cj:]: + if (((i[0]+j[0]+k[0])%3 ==0) and ((i[1]+j[1]+k[1])%3 ==0)): + t = [i,j,k] + triangles.append(t) + count+=1 + cj+=1 + ci+=1 + + out_file.write('Case #'+str(c)+': '+str(count)+'\n') +
lfundaro/GoogleCodeJam
dec4bae842a0096c59491c701caf3977e76540b3
final numbers -> lack of input/output
diff --git a/javier/numbers/numbers.hs b/javier/numbers/numbers.hs index 25e8906..804fe27 100644 --- a/javier/numbers/numbers.hs +++ b/javier/numbers/numbers.hs @@ -1,73 +1,86 @@ {- Google code jam - Online round A 2008 - warming up Problem: Numbers Implementation: free precision numbers (on lists) multiplied to obtain the n power of the number. From there the three lower precision numbers are taken -} {- Big Number: Positive lis, precision List and precision value -} data BigNumber = BN [Int] Int deriving (Show, Eq) instance Num BigNumber where (BN pos prec) * (BN pos2 prec2) = multiply (BN pos prec) (BN pos2 prec2) showBigNumber::BigNumber->String showBigNumber (BN p pr) = show p ++" "++show pr {- Returns the multiplication of the reverse lists. The first list is already reverse for threeSquareFive efficiency -} multiply::BigNumber -> BigNumber -> BigNumber multiply (BN p1 pr1) (BN p2 pr2) = (BN (reverse (multiplication (reverse p1) (reverse p2) [] [])) (pr1+pr2)) unitMul::[Int]->Int-> Int -> [Int]->[Int] unitMul [] _ 0 l3 = l3 unitMul [] _ carry l3 = l3++[carry] unitMul (xl1:yl1) xl2 carry l3 | (xl1*xl2)+carry>9 = unitMul yl1 xl2 (div ((xl1*xl2)+carry) 10) (l3++[mod ((xl1*xl2)+carry) 10]) | otherwise = unitMul yl1 xl2 0 (l3++[(xl1*xl2)+carry]) {- Accumulated sum of two reversed list of int -} unitSum::[Int]->[Int]->Int->[Int]->[Int] unitSum l1 [] 0 l3 = l3++l1 unitSum [] l2 0 l3 = l3++l2 unitSum (xl1:yl1) [] carry l3 = l3++((xl1+carry):yl1) unitSum [] (xl2:yl2) carry l3 = l3++((xl2+carry):yl2) unitSum [] [] carry l3 = l3++[carry] unitSum (xl1:yl1) (xl2:yl2) carry l3 |((xl1+xl2)+carry)>9 = unitSum yl1 yl2 (div ((xl1+xl2)+carry) 10) (l3++[mod ((xl1+xl2)+carry) 10]) | otherwise = unitSum yl1 yl2 0 (l3++[(xl1+xl2)+carry]) {- Accumulated multiplication of two reversed lists of int -} multiplication::[Int]->[Int]->[Int]->[Int]->[Int] multiplication l1 [] _ l3 = l3 multiplication l1 (xl1:yl2) expand l3 = unitSum (expand ++ (unitMul l1 xl1 0 [])) (multiplication l1 yl2 (0:expand) []) 0 [] power::Int->BigNumber->BigNumber power n (BN l pr) = tailPower n (BN l pr) (BN l pr) tailPower::Int->BigNumber->BigNumber->BigNumber tailPower 1 _ (BN l pr) = (BN l pr) tailPower n (BN l pr) (BN l2 pr2) = tailPower (n-1) (BN l pr) (multiply (BN l pr) (BN l2 pr2)) {-Computes the n power of 3 + sqrt 5 -} threeSquareFive::Int->BigNumber threeSquareFive n = - power n (BN [5,2,3,6,0,6,7,9,8] 1) - - + power n (BN [5,2,3,6,0,6,7,9,8] 8) + +nAfterColon::Int->BigNumber->[Int] +nAfterColon n (BN l pr)= + nextN n (drop pr (reverse l)) [] + +nextN::Int->[Int]->[Int]->[Int] +nextN 0 _ nDigits = nDigits +nextN n (x:xs) nDigits = + nextN (n-1) xs (x:nDigits) +nextN n [] nDigits = + nextN (n-1) [] (0:nDigits) + +numbers::Int->Int->[Int] +numbers nAfter nPower = + nAfterColon nAfter (threeSquareFive nPower)
lfundaro/GoogleCodeJam
85b0d07f929c84239ca4fdf5d07554f4befaea2d
Adding numbers problem from Online Round 1A google code jam Haskell implementation for three square root calculation
diff --git a/javier/numbers/numbers.hs b/javier/numbers/numbers.hs new file mode 100644 index 0000000..25e8906 --- /dev/null +++ b/javier/numbers/numbers.hs @@ -0,0 +1,73 @@ + +{- + Google code jam - Online round A 2008 - warming up + Problem: Numbers + Implementation: free precision numbers (on lists) multiplied + to obtain the n power of the number. From there the three + lower precision numbers are taken +-} + +{- Big Number: Positive lis, precision List and precision value +-} +data BigNumber = BN [Int] Int deriving (Show, Eq) + +instance Num BigNumber where + (BN pos prec) * (BN pos2 prec2) = multiply (BN pos prec) (BN pos2 prec2) + +showBigNumber::BigNumber->String +showBigNumber (BN p pr) = + show p ++" "++show pr + +{- Returns the multiplication of the reverse lists. +The first list is already reverse for threeSquareFive efficiency +-} + +multiply::BigNumber -> BigNumber -> BigNumber +multiply (BN p1 pr1) (BN p2 pr2) = + (BN (reverse (multiplication (reverse p1) (reverse p2) [] [])) (pr1+pr2)) + +unitMul::[Int]->Int-> Int -> [Int]->[Int] +unitMul [] _ 0 l3 = l3 +unitMul [] _ carry l3 = l3++[carry] +unitMul (xl1:yl1) xl2 carry l3 + | (xl1*xl2)+carry>9 = unitMul yl1 xl2 (div ((xl1*xl2)+carry) 10) (l3++[mod ((xl1*xl2)+carry) 10]) + | otherwise = unitMul yl1 xl2 0 (l3++[(xl1*xl2)+carry]) + +{- Accumulated sum of two reversed list of int +-} +unitSum::[Int]->[Int]->Int->[Int]->[Int] +unitSum l1 [] 0 l3 = l3++l1 +unitSum [] l2 0 l3 = l3++l2 +unitSum (xl1:yl1) [] carry l3 = l3++((xl1+carry):yl1) +unitSum [] (xl2:yl2) carry l3 = l3++((xl2+carry):yl2) +unitSum [] [] carry l3 = l3++[carry] + +unitSum (xl1:yl1) (xl2:yl2) carry l3 + |((xl1+xl2)+carry)>9 = unitSum yl1 yl2 (div ((xl1+xl2)+carry) 10) (l3++[mod ((xl1+xl2)+carry) 10]) + | otherwise = unitSum yl1 yl2 0 (l3++[(xl1+xl2)+carry]) + +{- Accumulated multiplication of two reversed lists of int +-} + +multiplication::[Int]->[Int]->[Int]->[Int]->[Int] +multiplication l1 [] _ l3 = l3 +multiplication l1 (xl1:yl2) expand l3 = + unitSum (expand ++ (unitMul l1 xl1 0 [])) (multiplication l1 yl2 (0:expand) []) 0 [] + +power::Int->BigNumber->BigNumber +power n (BN l pr) = + tailPower n (BN l pr) (BN l pr) + +tailPower::Int->BigNumber->BigNumber->BigNumber +tailPower 1 _ (BN l pr) = (BN l pr) +tailPower n (BN l pr) (BN l2 pr2) = + tailPower (n-1) (BN l pr) (multiply (BN l pr) (BN l2 pr2)) + +{-Computes the n power of 3 + sqrt 5 +-} +threeSquareFive::Int->BigNumber +threeSquareFive n = + power n (BN [5,2,3,6,0,6,7,9,8] 1) + + +
lfundaro/GoogleCodeJam
66e899048fd065fea190324c671735630087d24e
minimum scalar product solved, what a MAMEY this was, 15 min
diff --git a/lorenzo/__init__.py b/lorenzo/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lorenzo/min_scalar/__init__.py b/lorenzo/min_scalar/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lorenzo/min_scalar/min_scalar.py b/lorenzo/min_scalar/min_scalar.py new file mode 100644 index 0000000..a52b84b --- /dev/null +++ b/lorenzo/min_scalar/min_scalar.py @@ -0,0 +1,35 @@ +#! /usr/bin/python + +import sys + +def prepare_string(string): + string = string.split(' ') + for i in range(len(string)): + string[i] = string[i].strip('\n') + string[i] = int(string[i]) + return string + + + +def min_scalar(v1, v2, vector_size): + # Ordering + v1.sort() + v2.sort(reverse = True) + + min = 0 + for i in range(vector_size): + min = min + v1[i]*v2[i] + + return min + + +f = file(sys.argv[1], 'r') +cases = int(f.readline()) + +for times in range(cases): + vector_size = prepare_string(f.readline()) + v1 = prepare_string(f.readline()) + v2 = prepare_string(f.readline()) + answer = min_scalar(v1, v2, vector_size[0]) + print 'Case #' + str(times + 1) + ': ' + str(answer) + diff --git a/lorenzo/tools/__init__.py b/lorenzo/tools/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lorenzo/tools/tools.py b/lorenzo/tools/tools.py new file mode 100644 index 0000000..4555468 --- /dev/null +++ b/lorenzo/tools/tools.py @@ -0,0 +1,8 @@ +#! /usr/bin/python + +def prepare_string(string): + string = string.split(' ') + for i in range(len(string)): + string[i] = string[i].strip('\n') + string[i] = int(string[i]) + return string
lfundaro/GoogleCodeJam
fe2745a2455f104ed9b3292b96c82f49d53ef300
get2work is done...
diff --git a/lorenzo/get_to_work/get_to_work.py b/lorenzo/get_to_work/get_to_work.py new file mode 100644 index 0000000..8740053 --- /dev/null +++ b/lorenzo/get_to_work/get_to_work.py @@ -0,0 +1,83 @@ +#! /usr/bin/python + +import sys + +def prepare_string(string): + string = string.split(' ') + for i in range(len(string)): + string[i] = string[i].strip('\n') + string[i] = int(string[i]) + return string + +def init_list(N): + map = [] + for i in range(N): + map.append([0,[]]) + return map + +def order_map(map): + for i in map: + i[1].sort(reverse = True) + +def to_work(map, T, N): + result = [] + for i in range(N): + result.append(0) + + before = map[:T] + after = map[T+1:] + + b = 0 + for elem in before: + while elem[0] > 0: + if elem[1] == [] or elem[1][0] == 0: + return 'IMPOSSIBLE' + + if elem[0] > elem[1][0]: + elem[0] = elem[0] - elem[1][0] + elem[1] = elem[1][1:] + result[b] += 1 + elif elem[0] <= elem[1][0]: + elem[0] = 0 + result[b] += 1 + + b += 1 + + a = T + 1 + for elem in after: + while elem[0] > 0: + if elem[1] == [] or elem[1][0] == 0: + return 'IMPOSSIBLE' + + if elem[0] > elem[1][0]: + elem[0] = elem[0] - elem[1][0] + elem[1] = elem[1][1:] + result[a] += 1 + elif elem[0] <= elem[1][0]: + elem[0] = 0 + result[a] += 1 + + a += 1 + + min_cars = '' + for cars in result: + min_cars = min_cars + str(cars) + ' ' + + return min_cars + +f = file(sys.argv[1], 'r') +cases = int(f.readline()) + +for times in range(cases): + towns = prepare_string(f.readline()) + T = towns[1] + N = towns[0] + map = init_list(N) + employees = prepare_string(f.readline()) + for i in range(employees[0]): + ins = prepare_string(f.readline()) + map[ins[0]-1][0] += 1 + map[ins[0]-1][1].append(ins[1]) + order_map(map) + answer = to_work(map, T - 1, N) + print 'Case #' + str(times + 1) + ': ' + answer.strip(' ')
lfundaro/GoogleCodeJam
f6c613323a86df39850f2a59c2b140eff8d55183
odd man out solved, finally
diff --git a/lorenzo/minority/minority.py b/lorenzo/minority/minority.py index 3146b0b..135285c 100644 --- a/lorenzo/minority/minority.py +++ b/lorenzo/minority/minority.py @@ -1,80 +1,65 @@ #! /usr/bin/python -def minority(T): - if len(T) <= 1: +import sys + +def minority(T, length): + if length <= 1: return T - mid = len(T) / 2 - left = T[:mid] - right = T[mid:] - left = minority(left) - right = minority(right) + mid = length / 2 + left = minority(T[:mid], mid) + right = minority(T[mid:], length - mid) if left == []: return right elif right == []: return left - elif left[-1] >= right[0]: - result = eliminate(left, right) - else: - result = left.extend(right) - - return result - -def eliminate(left, right): - len_left = len(left) - len_right = len(right) - while len_left > 0 and len_right > 0: - left = left[1:] - right = right[1:] - len_left -= 1 - len_right -= 1 - - if len_left == 0: - return right + if left[-1] >= right[0]: + return eliminate(left, right) else: + left.extend(right) return left +def eliminate(left, right): + r_len = len(right) + l_len = len(left) + result = [] + + while r_len > 0 and l_len > 0: + if left[0] == right[0]: + left = left[1:] + right = right[1:] + l_len -= 1 + r_len -= 1 + elif left[0] < right[0]: + result.append(left[0]) + left = left[1:] + l_len -= 1 + else: + result.append(right[0]) + right = right[1:] + r_len -= 1 + + if l_len == 0: + result.extend(right) + return result + else: + result.extend(left) + return result +f = file(sys.argv[1], 'r') +cases = int(f.readline()) +for times in range(cases): + length = f.readline() # reading number of elements + str_list = f.readline() # reading list as string + str_list = str_list.split(' ') + for i in range(len(str_list)): + str_list[i] = str_list[i].strip('\n') + T = [] + for i in str_list: + T.append(int(i)) + answer = minority(T, int(length)) + print 'Case #' + str(times + 1) + ': ' + str(answer[0]) - - - - -# def majority(T): -# length = len(T) -# low = length / 2 -# if length != 1: -# m_element = majority(T[:low]) -# else: -# return (T[0],1) - -# count = 0 -# for x in T[low:]: #parte derecha de la lista -# if x != m_element[0]: -# continue -# else: -# count += 1 -# break - -# if count == 0: -# return (m_element[0], m_element[1]) - -# # Se busca el elemento en la derecha -# m_element = majority(T[low:]) -# count = 0 - -# for x in T[:low]: #parte izquierda de la lista -# if x != m_element[0]: -# continue -# else: -# count += 1 -# break - -# if count == 0: -# return (m_element[0], m_element[1]) -# else: -# return (0,0) -
sipsorcery/samples
222496daebba7660859197739bf6d7e99966a1cb
Added CallAnnouncement ruby script.
diff --git a/CallAnnouncement.rb b/CallAnnouncement.rb new file mode 100644 index 0000000..8640fdb --- /dev/null +++ b/CallAnnouncement.rb @@ -0,0 +1,232 @@ +# Copyright 2011 Mike Telis +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# Modifications: +# 15 Feb 2011 Aaron Clauson Changes to configuration section to remove user specific information. + +# Call announcement + +require 'java' + +SS_User = 'your_sipsorcery_userame' # Sipsorcery login name +TransferURI = '[email protected]' # Destination URI +AnsDeadline = 20 # Answer incoming call in 20 sec (to prevent it from going to VM) +AnsTimeout = 40 # Time-out waiting for user's input (to accept or not to accept) +MyName = 'your_name' # Destination's name ("Looking for Mike...") +MOH = 'http://hosting.tropo.com/40053/www/audio/Sinatra.mp3' # Music-On-Hold file + +# ***************** U T I L S ***************** + +Start = "<?xml version='1.0'?><speak>" +End = "</speak>" + +=begin +phone_to_vxml produces VXML from *formatted* phone number. It breaks the number into chunks delimited with +spaces or dashes and then joins chunks together separating them with pauses (breaks). Options: +:pre => String - this goes before the number +:post => String - this goes after the number +:pause => 'weak' or 'medium' or 'strong' - duration of pause between the chunks + +Example: + +say phone_to_vxml '+1 212 555-1212', { + :pre => 'You got a call from', + :post => 'Press 1 to accept, 2 to reject' + } +=end + +def phone_to_vxml num, options + opt = { :pause => 'weak' } + opt.update(options) + + pause = "<break strength='#{opt[:pause]}'/>" + + chunks = num.split(/\s|\-/).map do |chunk| + chunk.gsub(/./) { |c| c =~ /\d/ ? c + ' ' : '' }.chop + end + + Start + opt[:pre].to_s + pause + chunks.join(pause) + pause + opt[:post].to_s + End +end + +=begin +formatNum formats phone number (must be in ENUM format). If 2nd parameter is true, the number will only +be formatted if it follows the rules for this particular country code. + +formatNum '123456' => +1 23456 +formatNum '123456', true => 123456 +=end + +def formatNum(num,exact=false) + case num + when /^([17])(\d{3})(\d{3})(\d{4})$/, # USA, Russia + /^(61)(\d)(\d{4})(\d{4})/, # Australia + /^(380|375|41|48|998)(\d{2})(\d{3})(\d{4})$/, # Ukraine, Belarus, Swiss, Poland, Uzbekistan + /^(972)(\d{1,2})(\d{3})(\d{4})$/, # Israel + /^(36)(1|\d\d)(\d{3})(\d{3,4})$/, # Hungary + /^(34)(9[1-9]|[5-9]\d\d)(\d{3})(\d{3,4})$/, # Spain + /^(86)(10|2\d|\d{3})(\d{3,4})(\d{4})$/ # China: Beijing, 2x, others 3-dig area code + "+#$1 (#$2) #$3-#$4" + + when /^(33)(\d)(\d{2})(\d{2})(\d{2})(\d{2})$/ # France + "+#$1 (#$2) #$3 #$4 #$5 #$6" + + when /^(44)(11\d|1\d1|2\d|[389]\d\d)(\d{3,4})(\d{4})$/ # UK 2- and 3-digit area codes + "+#$1 (#$2) #$3 #$4" # 11x, 1x1, 2x, 3xx, 8xx, 9xx + + when /^(44)(\d{4})(\d{6,7})$/ # UK 4-digit area codes + "+#$1 (#$2) #$3" + + when /^(39)(0[26]|0\d[0159]|0\d{3}|3\d\d)(\d*)(\d{4})$/, # Italy: Milan, Rome, 0x0, 0x1, 0x5, 0x9, 4-digit + /^(49)(1[5-7]\d|30|40|69|89|\d\d1|\d{4})(\d*)(\d{4})$/,# Germany: (mobile|2dig|3dig|4dig) area + /^(370)(469|528|37|45|46|57|5|\d{3})(\d*)(\d{4})$/, # Lithuania + /^(32)(4[789]\d|[89]0\d|[2-4]|[15-8]\d)(\d*)(\d{4})$/, # Belgium + /^(91)(11|20|33|40|44|79|80|\d{3})(\d*)(\d{4})$/, # India + /^(886)(37|49|89|\d)(\d*)(\d{4})$/ # Taiwan + sep = $3[2] ? ' ' : '' # separator if $3 group has 3 or more digits + "+#$1 #$2 #$3#{sep}#$4" + + when /^(420)(\d{3})(\d{3})(\d{3})$/ # Czech Republic + "+#$1 #$2 #$3 #$4" + + when /^(37[12])(\d{3,4})(\d{4})$/ # Latvia, Estonia + "+#$1 #$2-#$3" + + when /^(373)([67]\d{2})(\d{2})(\d{3})$/ # Moldova mobile + "+#$1 #$2-#$3-#$4" + + when /^(373)(22|\d{3})(\d{1,2})(\d{2})(\d{2})$/ # Moldova landline + "+#$1 (#$2) #$3-#$4-#$5" + + when /^(1|2[07]|3[0-469]|4[^2]|5[1-8]|6[0-6]|7|8[1246]|9[0-58]|\d{3})/ # all country codes + exact ? num : "+#$1 #$'" # the pattern used only if exact == false + + else num # No match - skip formatting + end +end + +# ****************** M A I N ****************** + +t = Time.now +callid_1 = $currentCall.getHeader("x-sbc-call-id") +from = $currentCall.getHeader('x-sbc-from') +callid_2 = t.strftime('99%H%M%S') + "%03d" % (t.usec / 1000) # more or less unique caller ID + +from =~ /^\s*("?)([^\1]*)\1\s*<sip\:(.*)@(.*)>/ +name, user, host = $2, $3, $4 +user = ('1' + user) if user =~ /^[2-9]\d\d[2-9]\d{6}$/ # prepend US numbers with '1' +user.sub!(/^(\+|00|011)/,'') # Remove international prefixes, if any +log "Call from: #{from}\nName: '#{name}', User: '#{user}', Host: '#{host}'" + +goFlag = false # go transfer incoming call +doneFlag = false # xfer Thread's done +newCall = false + +xfer = Thread.new do # In this thread we call @TransferURI and ask whether they want to accept the call + begin + event = call "sip:#{TransferURI}", { + :callerID => "+#{callid_2}", + :headers => { "x-tropo-from" => from }, + } + if event.name == 'answer' + log "#{MyName} answered" + newCall = event.value + + question = phone_to_vxml formatNum(user, true), { + :pre => "Call from " + (name =~ /[^0-9()\s\+\-]/ ? name + '. Number' : ''), + :post => "Press 1 to accept, 2 to reject" + } + + result = newCall.ask question, { + :repeat => 3, + :timeout => 5, + :choices => "1,2", + :minConfidence => 0.45, + :onHangup => lambda {|event| log "newCall hangup!"}, + :onBadChoice => lambda {|event| newCall.say "Wrong choice!"} + } + + log "Got: #{result.name}, #{result.value}" + + if result.name == "choice" + case result.value + when "1" # When the user has selected "Yes" + goFlag = true + newCall.say "Call accepted, connecting" + else + newCall.say "Rejecting incoming call" + end + end + end + rescue + log "Exception: '#$!'" + case $!.to_s + when "Call dropped", "Answer timeout" # handle both in the same manner + wait 500 + newCall.say "Too late, incoming call dropped" if newCall + goFlag = false + end + ensure + doneFlag = true + end +end + +# Main thread + +status = '' +AnsTimeout.times do |i| # Here we're monitoring incoming call to detect hangup +# wait 1000 # *********** replaced with sleep, interferes with ask in xfer thread! + sleep 1 # check every second + # answer incoming call if we can't wait any longer, play music-on-hold + Thread.new { answer; wait 2000; say "Looking for #{MyName}, please hold. #{MOH}" } if i == AnsDeadline + status = $currentCall.state + log "State = " + status + if status == "DISCONNECTED" + xfer.raise "Call dropped" # Notify xfer thread + break + end + break if doneFlag +end + +xfer.raise "Answer timeout" unless doneFlag # !doneFlag means AnsTimeout secs passed with no decision + +xfer.join + +if goFlag + Thread.new { newCall.say(MOH) } # start playing music-on-hold + + answer unless status == "ANSWERED" # answer incoming cal if not already + wait 1000 + +# say "Your call is being connected" + + # initiate dual transfer + svcURL = "http://www.sipsorcery.com/callmanager.svc/dualtransfer?user=#{SS_User}&callid1=#{callid_1}&callid2=#{callid_2}" + log "URL:" + svcURL + url= java.net.URL.new svcURL + conn = url.openConnection + log "javaURL created" + stm = conn.getInputStream + transferResult = org.apache.commons.io.IOUtils.toString(stm) + + unless transferResult.empty? + say "Transfer failed" + log "Dual transfer failed:\n" + transferResult + end +end + +# Clean-up +case $currentCall.state + when "RINGING" then reject + when "ANSWERED" + say "Unable to locate #{MyName}" + hangup +end +newCall.hangup if newCall \ No newline at end of file
sipsorcery/samples
36aa8b69693ab69c1c271c1577b60863a23dd245
Added wizard consumer script.
diff --git a/wizardconsumer.rb b/wizardconsumer.rb new file mode 100644 index 0000000..a8ff3f8 --- /dev/null +++ b/wizardconsumer.rb @@ -0,0 +1,22 @@ +require 'mikesgem' + +settings = lookup.GetSettings() +Tz = settings.GetTimezoneOffset() +Country = settings.Options.countrycode +Area = settings.Options.areacode +EnableSafeguards = settings.Options.enablesafeguards +WP_key = settings.Options.whitepageskey +sys.Log("Enable Safeguards=#{EnableSafeguards}.") +Allowed_Country = settings.GetAllowedCountries() +EnumDB = settings.GetENUMServers() +ExcludedPrefixes = settings.GetExcludedPrefixes() +Speeddial = settings.GetSpeedDials() +CNAM = settings.GetCNAMs() +MyENUM = settings.GetENUMs() +Routes = settings.Routes +Providers = {} +settings.Providers.each { |p| + Providers[p.key] = VSP.new p.value.providerprefix, p.value.providerdialstring, p.value.providerdescription +} + +require 'dialplanwizard' \ No newline at end of file
sipsorcery/samples
ec8c0622913f36dcc0bddbe47cd6ec64221add16
Adding dialplan wizard script
diff --git a/dialplanwizard.rb b/dialplanwizard.rb new file mode 100644 index 0000000..e5ee670 --- /dev/null +++ b/dialplanwizard.rb @@ -0,0 +1,257 @@ +# Copyright 2010 Mike Telis +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# Modifications: +# 9 Feb 2011 Aaron Clauson Crudely hacked around with to work with new dial plan wizard web configuration page. + +require 'mikesgem' + +Host = 'sipsorcery.com' # Replaces "host" on incoming calls + +def selectVSP # VoIP provider selection + + providerFound = false; + Routes.each {|x| + if @num =~ /^(#{x.routepattern})/ && Providers[x.routedestination] + sys.Log("provider selected #{x.routedestination}.") + providerFound = true; + route_to Providers[x.routedestination], x.routedescription, nil + end + } + + if providerFound + rejectCall(603, "Call failed on all attempted providers") + else + rejectCall(603, "No provider matched for number") + #route_to F9default + end +end + +# ******************** i n c o m i n g C a l l ************************* + +def incomingCall + sys.SetFromHeader(formatNum(@cname || @cid,true), nil, Host) # Set FromName & FromHost for sys.Dial + + # Forward call to the bindings (ATA / softphone) + # Change FromURI when forwarding to @local, or else Bria won't find contact in its phonebook! + + callswitch("#{@user}@local[fu=#{@cid}]",45) unless (30..745) === @t.hour*100 + @t.min # reject incoming calls from 0:30a to 7:45a + + @code, @reason = 480, "#{@user} is asleep" unless @code # if nothing else, must be the night hour + @code = 486 if @trunk =~ /IPCOMM/i ## *** temporary fix for IPCOMMS *** +end + +# ************************** t o E N U M ******************************* + +def to_ENUM num + num.gsub!(/[^0-9*+]/,'') # Delete all fancy chars (only digits, '+' and '*' allowed) + + # Check if the number begins with one of international prefixes: + # '+' - international format + # 00 - European style international prefix (00) + # 011 - US style international prefix (011) + # 0011 - Australian style international prefix (0011) + + num =~ /^(\+|0011|00|011)/ and return $' # if yes, remove prefix and return + + case num # Special cases + when /^0(\d+)$/ # National number. + Country + $1 # Prefix with country code. + when /^[1-9]\d+$/ # Local number. + Country + Area + num # Prefix with country and area code. + when /^\*/ # Voxalot voicemail, echotest & other special numbers + num # ... as is + else + rejectCall(603,"Wrong number: '#{num}', check & dial again") + end +end + +# ****** E N D O F C O N F I G U R A T I O N S E C T I O N ******** # + +# ************************** C A L L S W I T C H ********************** + +def callswitch(num,*args) + @timeout = args[0] + num.gsub!(/%([0-9A-F]{2})/) {$1.to_i(16).chr} # Convert %hh into ASCII + @num = Speeddial.ContainsKey(num) ? Speeddial[num] : num # If there is speed dial entry for it... + + if @num =~ /@/ # If we already have URI, just dial and return + sys.Log("URI dialing: #@num") + dial(@num,*args) + else + # Not URI + rexp = VSP.tab.keys.sort {|a,b| b.length <=> a.length}.map {|x| Regexp.escape(x)}.join('|') + if @num =~ /^(#{rexp})/ # If number starts with VSP selection prefix + @num = $' + @forcedRoute = VSP.tab[$1] + @noSafeGuards = (@forcedRoute.fmt =~ /Disable\s*Safe\s*Guards/i) + end + + @num = to_ENUM(@num) # Convert to ENUM + + rejectCall(503,"Number's empty") if @num.empty? + sys.Log("Number in ENUM format: #{@num}") + if @forcedRoute && !@noSafeGuards + route_to @forcedRoute, "Forced routing!", false # if forced with prefix, skip ENUM, safeguards & VSP selection + else + checkNum if EnableSafeguards && !@noSafeGuards + selectVSP # Pick appropriate provider for the call + end + end # URI +end + +# *************************** R O U T E _ T O **************************** + +def route_to vsp, dest=nil, enum = EnumDB + enum.to_a.each do |db| # if enum enabled, look in all enum databases + sys.Log("enum lookup in #{db}") + if uri = (db.class == Hash)? db[@num] : sys.ENUMLookup("#{@num}.#{db}") + sys.Log("ENUM entry found: '#{uri}' in #{db.class == Hash ? 'local' : db} database") + dial(uri) + end + end # ENUM not found or failed, call via regular VSP + + return unless vsp # No VSP - do nothing + + uri = vsp.fmt.gsub(/\s+/,'').gsub(/\$\{EXTEN(:([^:}]+)(:([^}]+))?)?\}/) {@num[$2.to_i,$4? $4.to_i : 100]} + dest &&= " (#{dest})"; with = vsp.name; with &&= " with #{with}" + sys.Log("Calling #{formatNum(@num)}#{dest}#{with}") + + if vsp.is_gv? + vsp.repeat.times do |i| + @code, @reason = 200, "OK" # assume OK + sys.GoogleVoiceCall *vsp.getparams(uri, i + (vsp.rand ? @t.to_i : 0)) + sys.Log("Google Voice Call failed!") + @code, @reason = 603, 'Service Unavailable' + end + else + vsp.repeat.times do + dial(uri, @timeout || vsp.tmo || 300) # Dial, global time-out overrides account + end + end +end + +# ******************************* D I A L ******************************** + +def dial *args + @code, @reason = nil + sys.Dial *args # dial URI + status() # We shouldn't be here! Get error code... + sys.Log("Call failed: code #{@code}, #{@reason}") +end + +# ***************************** S T A T U S ****************************** + +def status + begin + @code, @reason = 487, 'Cancelled by Sipsorcery' + sys.LastDialled.each do |ptr| + if ptr + ptr = ptr.TransactionFinalResponse + @code = ptr.StatusCode; @reason = ptr.ReasonPhrase; break if @code == 200 +# sys.Log("#{ptr.ToString()}") + end + end + rescue + end +end + +# ************************ r e j e c t C a l l *************************** + +def rejectCall code, reason + @code = code; @reason = reason + sys.Respond code, reason +end + +# **************************** C H E C K N U M ************************** + +def checkNum + return if @num.match(/^\D/) # skip if number doesn't begin with a digit + + # Reject calls to not blessed countries and premium numbers + # (unless VSP was forced using #n dial prefix) + + if(Allowed_Country != nil) then + rejectCall(503,"Calls to code #{formatNum(@num).split(' ')[0]} not allowed") \ + unless @num.match "^(#{Allowed_Country.join('|')})" + end + + if(ExcludedPrefixes != nil) then + rejectCall(503,"Calls to '#{formatNum($&)}' not allowed") if @num.match \ + '^(' + ExcludedPrefixes.map { |x| "(:?#{x.gsub(/\s*/,'')})" }.join('|') + ')' + end +end + +# ********************** k e y s t o E N U M ************************* + +def keys_to_ENUM (table) + Hash[*table.keys.map! {|key| to_ENUM(key.dup)}.zip(table.values).flatten] +end + +# ************************** g e t T I M E ******************************* + +def getTime + Time.now.utc + Tz * 60 # Get current UTC time and adjust to local. +end + +# ******************************* M A I N ******************************** + +begin + sys.Log("** Call from #{req.Header.From} to #{req.URI.User} **") + sys.ExtendScriptTimeout(15) # preventing long running dialscript time-out + @t = getTime() + sys.Log(@t.strftime('Local time: %c')) + if EnumDB != nil then + EnumDB.map! {|x| x.class == Hash ? keys_to_ENUM(x) : x } # rebuild local ENUM table + end + + if sys.In # If incoming call... + @cid = req.Header.from.FromURI.User.to_s # Get caller ID + + # Prepend 10-digit numbers with "1" (US country code) and remove int'l prefix (if present) + + @cid = ('1' + @cid) if @cid =~ /^[2-9]\d\d[2-9]\d{6}$/ + @cid.sub!(/^(\+|00|011)/,'') # Remove international prefixes, if any + + prs = req.URI.User.split('.') # parse User into chunks + @trunk = prs[-2] # get trunk name + @user = prs[-1] # called user name + + # Check CNAM first. If not found and US number, try to lookup caller's name in Whitepages + + if !(@cname = keys_to_ENUM(CNAM)[@cid]) && @cid =~ /^1([2-9]\d\d[2-9]\d{6})$/ && defined?(WP_key) + url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.whitepages.com%2Freverse_phone%2F1.0%2F%3Fphone%3D#{$1}%3Bapi_key%3D#{WP_key}'%20and%20itemPath%3D'wp.listings.listing'&format=json" + if js = sys.WebGet(url,4).to_s + @cname, dname, city, state = %w(businessname displayname city state).map {|x| js =~ /"#{x}":"([^"]+)"/; $1} + @cname ||= dname; @cname ||= "#{city}, #{state}" if city && state + end + end + + sys.Log("Caller's number: '#{@cid}'"); sys.Log("Caller's name: '#{@cname}'") if @cname + incomingCall() # forward incoming call + + else # Outbound call ... + + # check if it's URI or phone number. + # If destination's host is in our domain, it's a phone call + + num = req.URI.User.to_s; reqHost = req.URI.Host.to_s # Get User and Host + host = reqHost.downcase.split(':')[0] # Convert to lowercase and delete optional ":port" + num << '@' << reqHost unless sys.GetCanonicalDomain(host) != nil # URI dialing unless host is in our domain list + + callswitch(num) + + end + sys.Respond(@code,@reason) # Forward error code to ATA +rescue + # Gives a lot more details at what went wrong (borrowed from Myatus' dialplan) + sys.Log("** Error: " + $!) unless $!.to_s =~ /Thread was being aborted./ +end \ No newline at end of file
jrockway/kiokux-debug-leaks
b74bd89514b4e6eec7ab114531f01a5775a981ef
initial import
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..78371b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +blib +inc +pm_to_blib +META.yml +MANIFEST +MANIFEST.* +Makefile +Makfile.old diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..a3e3361 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,11 @@ +use inc::Module::Install; +use strict; + +requires 'Context::Preserve'; +requires 'KiokuDB'; # technically not required... but... + +build_requires 'Test::More'; +build_requires 'Test::Exception'; +build_requires 'ok'; + +WriteAll(); diff --git a/lib/KiokuX/Debug/Leaks.pm b/lib/KiokuX/Debug/Leaks.pm new file mode 100644 index 0000000..c310e60 --- /dev/null +++ b/lib/KiokuX/Debug/Leaks.pm @@ -0,0 +1,28 @@ +package KiokuX::Debug::Leaks; +use strict; +use warnings; + +use Context::Preserve qw/preserve_context/; + +our $VERSION = '0.01'; + +use Sub::Exporter -setup => { + exports => ['do_with_scope'], +}; + +sub do_with_scope(&$){ + my ($code, $kiokudb) = @_; + + my $scope = $kiokudb->new_scope; + + # i want to use a guard, but that dies at the wrong time + return preserve_context { $code->($scope) } + after => sub { + my $l = $scope->live_objects; + undef $scope; + my @live_objects = $l->live_objects; + die $l if @live_objects; + }; +} + +1; diff --git a/t/basic.t b/t/basic.t new file mode 100644 index 0000000..5394174 --- /dev/null +++ b/t/basic.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use Test::More tests => 5; +use Test::Exception; + +use KiokuDB; +use KiokuX::Debug::Leaks qw(do_with_scope); + +my $db = KiokuDB->connect( 'hash' ); +ok 'connected ok'; + +lives_ok { + do_with_scope { + my $obj = { foo => 'bar' }; + my $id = $db->store($obj); + undef $obj; + $obj = $db->lookup($id); + ok $obj, 'reloaded ok'; + } $db; +} 'leakless lives'; + +my $drain; + +dies_ok { + do_with_scope { + my $faucet = { key => 'value' }; + my $id = $db->store($faucet); + undef $faucet; + $faucet = $db->lookup($id); + ok $faucet, 'reloaded ok'; + $drain = $faucet; # get it? leaky faucet!!! HAHAHAHAHAHAHA + } $db; +} 'dies when we leak something'; diff --git a/t/load.t b/t/load.t new file mode 100644 index 0000000..02eb220 --- /dev/null +++ b/t/load.t @@ -0,0 +1,7 @@ +use strict; +use warnings; +use Test::More tests => 1; + +use ok 'KiokuX::Debug::Leaks'; + +1;
shashi/shellsparrow
6d00e231e32d3638a3e27c23e5f19b8e37e513e9
I am not planning world dominance :)
diff --git a/sample.shellsparrowrc b/sample.shellsparrowrc index 51ff807..d86af92 100644 --- a/sample.shellsparrowrc +++ b/sample.shellsparrowrc @@ -1,10 +1,10 @@ # You have to create a file called .sparrowshellrc in the $HOME directory # Here is a sample config file that you can build on [jabbersh] jid: [email protected]/bot # user account to use to go online (get one from register.jabber.org) password: nothing # password [users] # List of all Jabber IDs to grant access to [email protected] = shashi [email protected] = serveruser
shashi/shellsparrow
8ffdbacbce66903a99aa093dbc249468b7ebfdf7
added LICENSE
diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..c5f829d --- /dev/null +++ b/COPYING @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2009 Shashi Gowda <[email protected]> + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the Software), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.textile b/README.textile index dd010ca..2eee81c 100644 --- a/README.textile +++ b/README.textile @@ -1,26 +1,31 @@ h1. ShellSparrow v0.1 ShellSparrow lets you connect to a daemon on your computer over your favourite XMPP client and execute commands on your favourite command line shell like bash. h2(#config). Configuration A sample configuration is given in sample.shellsparrowrc file, it's pretty self-explanatory, but let me break it down for you: # the [shellsparrow] section compulsorily should contain these: # jid: [email protected]/thedaemon ->full UID of the jabber account the daemon should use to connect. # password: password for the above account. # the [users] section should contain the JID (without resource name) of the users you want to grant access to. h2. Installation & Usage I am working on making a .deb for shellsparrow, but till then you will have to set it up manually, here's how you do it: # create a file called .shellsparrowrc in the $HOME directory and fill it up with the "configuration":#config # cd into the code directory type python shsd to start the daemon # use your favourite XMPP client from anywhere in the universe to connect to your computer! -You can find the history of all the commands in $HOME/.shellsparrow/commandlog +# You can find the history of all the commands in $HOME/.shellsparrow/commandlog h2. Todo There's a lot todo yet, briefly: # create a script to simplify configuration # make more configuration options available, like path of the shell binary to use # make sessions consistent (currently, each command starts a new shell instance) +# implement mapping of local usernames with JIDs to allow access with various user levels + +h2. License + +ShellSparrow is a Free Software, you are free to copy/adopt it untill you agree to keep it free. It is licensed under the MIT License, see COPYING for the full text. diff --git a/fortunelog b/fortunelog new file mode 100644 index 0000000..e69de29
shashi/shellsparrow
48c9bc476730acfe2c9d7b6f903f2b7f20606eca
1st commit
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b25c15b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*~ diff --git a/README.textile b/README.textile new file mode 100644 index 0000000..dd010ca --- /dev/null +++ b/README.textile @@ -0,0 +1,26 @@ +h1. ShellSparrow v0.1 + +ShellSparrow lets you connect to a daemon on your computer over your favourite XMPP client and execute commands on your favourite command line shell like bash. + +h2(#config). Configuration + +A sample configuration is given in sample.shellsparrowrc file, it's pretty self-explanatory, but let me break it down for you: +# the [shellsparrow] section compulsorily should contain these: + # jid: [email protected]/thedaemon ->full UID of the jabber account the daemon should use to connect. + # password: password for the above account. +# the [users] section should contain the JID (without resource name) of the users you want to grant access to. + +h2. Installation & Usage + +I am working on making a .deb for shellsparrow, but till then you will have to set it up manually, here's how you do it: +# create a file called .shellsparrowrc in the $HOME directory and fill it up with the "configuration":#config +# cd into the code directory type python shsd to start the daemon +# use your favourite XMPP client from anywhere in the universe to connect to your computer! +You can find the history of all the commands in $HOME/.shellsparrow/commandlog + +h2. Todo + +There's a lot todo yet, briefly: +# create a script to simplify configuration +# make more configuration options available, like path of the shell binary to use +# make sessions consistent (currently, each command starts a new shell instance) diff --git a/sample.shellsparrowrc b/sample.shellsparrowrc new file mode 100644 index 0000000..51ff807 --- /dev/null +++ b/sample.shellsparrowrc @@ -0,0 +1,10 @@ +# You have to create a file called .sparrowshellrc in the $HOME directory +# Here is a sample config file that you can build on + +[jabbersh] +jid: [email protected]/bot # user account to use to go online (get one from register.jabber.org) +password: nothing # password + +[users] # List of all Jabber IDs to grant access to [email protected] = shashi + diff --git a/shs b/shs new file mode 100755 index 0000000..c75351b --- /dev/null +++ b/shs @@ -0,0 +1,47 @@ +#!/usr/bin/env python + +# ShellSparrow helper script +# create your own options + +import sys +if "help" in sys.argv: + print """ +**ShellSparrow** + +Hi, Welcome to ShellSparrow. Using Jabber +Shell you can access any computer connected +to the internet regaurdless of how many +routers it is behind, and all that over the +neat XMPP protocol. You can use any backend +shell of your choice (for example, bash) by +specifying it on the server. + +Usage: + + * You can use any command that the user + running the daemon can run on this + computer, i.e if the shell daemon is + being run by the root user, you can + virtually do anything! + * If a command requires additional stdin + input, you can specify the input in + the next line (in the same nessage) + after the command for example, + sudo apt-get install somepackage + Y + Will confirm that you want to really + install the packages (notice the "Y" + in the second line). + * For commands that usem sudo (like the + one above), someone on the computer + has to enter the password in the same + terminal as the ShellSparrow for the + command to be completed. + +Help ShS: + ShellSparrow is released under the MIT + License. The source code can be obtained + at http://github.com/shashi/shellsparrow +""" +else: + print "Usage: `python shs help` for help" diff --git a/shsd b/shsd new file mode 100755 index 0000000..df793b2 --- /dev/null +++ b/shsd @@ -0,0 +1,270 @@ +#!/usr/bin/env python + +## ShellSparrow version 0.1 +## +## Copyright (C) 2009 Shashi Gowda <[email protected]> +## +## (Most part of the code in this file is derived from jabber-logger.py) +## This program is free software; you can redistribute it and/or modify +## it under the terms of the MIT Lisence + +import warnings +warnings.simplefilter("ignore",DeprecationWarning) +#TODO: Fix this ^ + +import pyxmpp +import os +import ConfigParser +import sys +import logging +import locale +import codecs +import subprocess + +from pyxmpp.all import JID,Iq,Presence,Message,StreamError +from pyxmpp.jabber.client import JabberClient + + +homed = os.getenv("HOME") + + +def execCommand(str,usr): + if not authUser(usr.split('/')[0]): + return ('go save the polar bears!','') + str=str.split('\n',1) + if(len(str)>1): + input=str[1] + else: + input=None + str=str[0]+"\n" #newline is required + retcode=subprocess.Popen( + str, + shell=True, + executable="/bin/sh", + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + stdout=subprocess.PIPE) + ret=retcode.communicate(input) + return ret #return value is a tuple (<stdout>,<stderr>) + +if not homed: # No such environment variable + homed = "" +else: + homed = homed+"/" + +if not os.path.exists(homed+".shellsparrow"): + os.makedirs(homed+".shellsparrow") + +# Command Logger +logfile = homed+".shellsparrow/commandlog" +logfile = open(logfile,"a") + +def logCommand(str): + logfile.write(str) + +class Client(JabberClient): + """Simple bot (client) example. Uses `pyxmpp.jabber.client.JabberClient` + class as base. That class provides basic stream setup (including + authentication) and Service Discovery server. It also does server address + and port discovery based on the JID provided.""" + + def __init__(self, jid, password): + + # if bare JID is provided add a resource -- it is required + if not jid.resource: + jid=JID(jid.node, jid.domain, "Logger") + + # setup client with provided connection information + # and identity data + JabberClient.__init__(self, jid, password, + disco_name="ShellSparrow", disco_type="bot") + + # register features to be announced via Service Discovery + self.disco_info.add_feature("jabber:iq:version") + + def stream_state_changed(self,state,arg): + """This one is called when the state of stream connecting the component + to a server changes. This will usually be used to let the user + know what is going on.""" + #print "*** State changed: %s %r ***" % (state,arg) + + def session_started(self): + """This is called when the IM session is successfully started + (after all the neccessery negotiations, authentication and + authorizasion). + That is the best place to setup various handlers for the stream. + Do not forget about calling the session_started() method of the base + class!""" + JabberClient.session_started(self) + + # set up handlers for supported <iq/> queries + self.stream.set_iq_get_handler("query","jabber:iq:version",self.get_version) + + # set up handlers for <presence/> stanzas + self.stream.set_presence_handler("available",self.presence) + self.stream.set_presence_handler("subscribe",self.presence_control) + self.stream.set_presence_handler("subscribed",self.presence_control) + self.stream.set_presence_handler("unsubscribe",self.presence_control) + self.stream.set_presence_handler("unsubscribed",self.presence_control) + + # set up handler for <message stanza> + self.stream.set_message_handler("normal",self.message) + + def get_version(self,iq): + """Handler for jabber:iq:version queries. + + jabber:iq:version queries are not supported directly by PyXMPP, so the + XML node is accessed directly through the libxml2 API. This should be + used very carefully!""" + iq=iq.make_result_response() + q=iq.new_query("jabber:iq:version") + q.newTextChild(q.ns(),"name","Echo component") + q.newTextChild(q.ns(),"version","1.0") + self.stream.send(iq) + return True + + def message(self,stanza): + """Message handler for the component. + + Echoes the message back if its type is not 'error' or + 'headline', also sets own presence status to the message body. Please + note that all message types but 'error' will be passed to the handler + for 'normal' message unless some dedicated handler process them. + + :returns: `True` to indicate, that the stanza should not be processed + any further.""" + subject=stanza.get_subject() + body=stanza.get_body() + t=stanza.get_type() + #print u'Message from %s received.' % (unicode(stanza.get_from(),)), + if subject: + logCommand(u'Subject: "%s".' % (subject,),) + if (body and t=="chat"): + logCommand('<'+unicode(stanza.get_from())+'> '+unicode(body)+'') + op = execCommand(body,stanza.get_from().__str__()) + body='' + if(op[0]!=''): body+=u"%s" % (op[0]) + if(op[1]!=''): body+=u"\nERROR: op[1]"+op[1] + if stanza.get_type()=="headline": + # 'headline' messages should never be replied to + return True + if subject: + subject=u"Re: "+subject + m=Message( + to_jid=stanza.get_from(), + from_jid=stanza.get_to(), + stanza_type=stanza.get_type(), + subject=subject, + body=body) + self.stream.send(m) + + #if body: + # p=Presence(status=body) + # self.stream.send(p) + return True + + def presence(self,stanza): + """Handle 'available' (without 'type') and 'unavailable' <presence/>.""" + msg=u"%s has become " % (stanza.get_from()) + t=stanza.get_type() + if t=="unavailable": + msg+=u"unavailable" + else: + msg+=u"available" + + show=stanza.get_show() + if show: + msg+=u"(%s)" % (show,) + + status=stanza.get_status() + if status: + msg+=u": "+status + logCommand(msg) + + def presence_control(self,stanza): + """Handle subscription control <presence/> stanzas -- acknowledge + them.""" + + t=stanza.get_type() + + p=stanza.make_accept_response() + self.stream.send(p) + return True + + def print_roster_item(self,item): + + if item.name: + name=item.name + else: + name=u"" + print (u'%s "%s" subscription=%s groups=%s' + % (unicode(item.jid), name, item.subscription, + u",".join(item.groups)) ) + + def roster_updated(self,item=None): + if not item: + print u"My roster:" + for item in self.roster.get_items(): + self.print_roster_item(item) + return + print u"Roster item updated:" + self.print_roster_item(item) + + +def logIn(): + c=Client(JID(p.get(PN,"jid")) ,p.get(PN,"password")) + + try: + print u"connecting..." + c.connect() + # Component class provides basic "main loop" for the applitation + # Though, most applications would need to have their own loop and call + # component.stream.loop_iter() from it whenever an event on + # component.stream.fileno() occurs. + print u"looping..." + c.loop(1) + + except KeyboardInterrupt: + print u"Thanks for using shellsparrow!\nBye..." + c.disconnect() + except: + print 'Error Occoured!\nAttempting relogin...' + c.disconnect() + logIn() + + +# XMPP protocol is Unicode-based to properly display data received +# _must_ convert it to local encoding or UnicodeException may be raised +locale.setlocale(locale.LC_CTYPE,"") +encoding=locale.getlocale()[1] +if not encoding: + encoding="us-ascii" +sys.stdout=codecs.getwriter(encoding)(sys.stdout,errors="replace") +sys.stderr=codecs.getwriter(encoding)(sys.stderr,errors="replace") + +# PyXMPP uses `logging` module for its debug output +# applications should set it up as needed + +logging.basicConfig(filename=homed+".shellsparrow/errlog") +logger=logging.getLogger() +logger.addHandler(logging.StreamHandler()) +logger.setLevel(logging.INFO) # change to DEBUG for higher verbosity + +p = ConfigParser.ConfigParser() +p.read( homed + ".shellsparrowrc" ) +PN = 'shellsparrow' + +if not p.has_option(PN,"jid") or not p.has_option(PN,"password"): + print u"Please configure jid and password in %s" % ( + homed+".shellsparrowrc") + sys.exit(1) + +def authUser(user): + return p.has_option("users",user) + +print u"creating client..." +logIn() + +print u"exiting..." +# vi: sts=4 et sw=4 +
spencertipping/webtimer
e70eb844638470a53e56b1da1d0fc7d2dd4f726b
Added input filtering
diff --git a/timer.html b/timer.html index ce91d2b..700599f 100644 --- a/timer.html +++ b/timer.html @@ -1,107 +1,109 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { - var hashtag = $('#hashtag').val(); - var number = Number($('#number').val()); + var hashtag = $('#hashtag').val().toLowerCase().replace (/^\s*/, '').replace (/\s*$/, ''); + var number = Number($('#number').val().replace (/^\s*/, '').replace (/\s*$/, '')); + + /^#/.test(hashtag) || (hashtag = '#' + hashtag); $('input').attr('disabled', 'disabled'); var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var standard_deviation = stat ('SD', Math.sqrt (variance)); var conservative_rate = stat ('Conservative rate estimate', average_rate + standard_deviation); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - (last.number + 1)); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes. ' + 'Over the past hour, the average progress has been ' + (average_rate * 60000) + ' people per minute.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
f05c7caee08676ad4c47def8ecb5cdbf152c0107
Treating all numbers as n+1. This is to avoid problems with a number having been up for a while. Rounding up should help.
diff --git a/timer.html b/timer.html index 33d99fd..ce91d2b 100644 --- a/timer.html +++ b/timer.html @@ -1,107 +1,107 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('input').attr('disabled', 'disabled'); var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var standard_deviation = stat ('SD', Math.sqrt (variance)); var conservative_rate = stat ('Conservative rate estimate', average_rate + standard_deviation); var last = results_within_hour[results_within_hour.length - 1]; - var distance_to_travel = stat ('Distance', number - last.number); + var distance_to_travel = stat ('Distance', number - (last.number + 1)); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes. ' + 'Over the past hour, the average progress has been ' + (average_rate * 60000) + ' people per minute.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
591c0ab8a0dc17e4e877e2b499f4edfe629edd82
Showing throughput
diff --git a/timer.html b/timer.html index ba1d7f7..33d99fd 100644 --- a/timer.html +++ b/timer.html @@ -1,106 +1,107 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('input').attr('disabled', 'disabled'); var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var standard_deviation = stat ('SD', Math.sqrt (variance)); var conservative_rate = stat ('Conservative rate estimate', average_rate + standard_deviation); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - last.number); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + - 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes. ' + + 'Over the past hour, the average progress has been ' + (average_rate * 60000) + ' people per minute.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
0215465d27505e71ba84464ee6453a53e17b6bad
Disabling inputs
diff --git a/timer.html b/timer.html index 54fb8a1..ba1d7f7 100644 --- a/timer.html +++ b/timer.html @@ -1,104 +1,106 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); + $('input').attr('disabled', 'disabled'); + var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var standard_deviation = stat ('SD', Math.sqrt (variance)); var conservative_rate = stat ('Conservative rate estimate', average_rate + standard_deviation); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - last.number); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
aff80e8d2b564510c75848bd91240b7cffbcb1a8
Making conservative estimate less conservative
diff --git a/timer.html b/timer.html index 37f9498..54fb8a1 100644 --- a/timer.html +++ b/timer.html @@ -1,104 +1,104 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var standard_deviation = stat ('SD', Math.sqrt (variance)); - var conservative_rate = stat ('Conservative rate estimate', average_rate + 2 * standard_deviation); + var conservative_rate = stat ('Conservative rate estimate', average_rate + standard_deviation); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - last.number); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
d5f13de21ce833469768c75b516c12ece1961d87
Using SD instead of variance
diff --git a/timer.html b/timer.html index b01a79c..37f9498 100644 --- a/timer.html +++ b/timer.html @@ -1,103 +1,104 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); + var standard_deviation = stat ('SD', Math.sqrt (variance)); - var conservative_rate = stat ('Conservative rate estimate', average_rate + 2 * variance); + var conservative_rate = stat ('Conservative rate estimate', average_rate + 2 * standard_deviation); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - last.number); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
f8221870598e8fa2f3dcbd91fdf81346899fcb77
Fix function
diff --git a/timer.html b/timer.html index 864b21c..b01a79c 100644 --- a/timer.html +++ b/timer.html @@ -1,103 +1,103 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); - var clear = $('#statistics').text(''); + var clear = function () {$('#statistics').text('')}; var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var conservative_rate = stat ('Conservative rate estimate', average_rate + 2 * variance); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - last.number); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
8b1169a2cc6aa3f3830a251de9dd83f8a921fd50
Fix space
diff --git a/timer.html b/timer.html index af3c3f9..864b21c 100644 --- a/timer.html +++ b/timer.html @@ -1,103 +1,103 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); var clear = $('#statistics').text(''); var stat = function () { $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); return arguments[arguments.length - 1]; }; $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { clear (); var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: stat ('Found number', match[1]), time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); stat ('Final variance', variance /= estimated_rates.length); var conservative_rate = stat ('Conservative rate estimate', average_rate + 2 * variance); var last = results_within_hour[results_within_hour.length - 1]; var distance_to_travel = stat ('Distance', number - last.number); var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; - $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes.' + + $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes. ' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> <h1>Statistical Stuff</h1> <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
96002d66920d6992df12e36af5428f8f2b7c7f5a
Put in lots of debugging code
diff --git a/timer.html b/timer.html index b023eaf..af3c3f9 100644 --- a/timer.html +++ b/timer.html @@ -1,92 +1,103 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); + var clear = $('#statistics').text(''); + var stat = function () { + $('#statistics').text ($('#statistics').text() + '\n' + Array.prototype.slice.call (arguments).join (' ')); + return arguments[arguments.length - 1]; + }; + $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { + clear (); + var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) - results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); + results_within_hour.push ({number: stat ('Found number', match[1]), + time: stat ('At time', Date.parse (results.results[i].created_at))}); results_within_hour.sort (function (x, y) { - var xd = Date.parse (x.created_at), yd = Date.parse (y.created_at); - return xd < yd ? -1 : xd > yd ? 1 : 0; + return x.time < y.time ? -1 : x.time > y.time ? 1 : 0; }); var rate_between = function (i1, i2) { var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; return (r2.number - r1.number) / (r2.time - r1.time); }; // Get an average and variance for the different time estimates that exist. var estimated_rates = []; for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) - estimated_rates.push (rate_between (i, i + 1)); + estimated_rates.push (stat ('Micro-rate (dn/dt)', rate_between (i, i + 1))); var sqr = function (x) {return x * x}; - var average_rate = rate_between (0, results_within_hour.length - 1); + var average_rate = stat ('Macro-rate (dn/dt)', rate_between (0, results_within_hour.length - 1)); var variance = 0; for (var i = 0, l = estimated_rates.length; i < l; ++i) - variance += sqr (estimated_rates[i] - average_rate); + stat ('Accumulated variance', variance += sqr (estimated_rates[i] - average_rate)); - variance /= estimated_rates.length; + stat ('Final variance', variance /= estimated_rates.length); - var conservative_rate = average_rate + 2 * variance; + var conservative_rate = stat ('Conservative rate estimate', average_rate + 2 * variance); var last = results_within_hour[results_within_hour.length - 1]; - var distance_to_travel = number - last.number; - var time_already_elapsed = new Date().getTime() - last.time; + var distance_to_travel = stat ('Distance', number - last.number); + var time_already_elapsed = stat ('Elapsed', new Date().getTime() - last.time); var total_time_given_rate = function (rate) { return distance_to_travel / rate - time_already_elapsed; }; var average_estimate = total_time_given_rate (average_rate) / 60000; var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes.' + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> + + <h1>Statistical Stuff</h1> + <pre id='statistics'></pre> </body> </html>
spencertipping/webtimer
d69c813f559c200b99e1d14f979f6b07bf751092
Revised the estimation logic and added statistical variance.
diff --git a/timer.html b/timer.html index 6a60fe9..b023eaf 100644 --- a/timer.html +++ b/timer.html @@ -1,74 +1,92 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); results_within_hour.sort (function (x, y) { var xd = Date.parse (x.created_at), yd = Date.parse (y.created_at); return xd < yd ? -1 : xd > yd ? 1 : 0; }); - // Take the minimum and maximum values and find the rate. - var first = results_within_hour[0]; - var middle = results_within_hour[results_within_hour.length >> 1]; - var last = results_within_hour[results_within_hour.length - 1]; + var rate_between = function (i1, i2) { + var r1 = results_within_hour[i1] || i1, r2 = results_within_hour[i2] || i2; + return (r2.number - r1.number) / (r2.time - r1.time); + }; - var dt = (last.time - first.time) / 60000; // In minutes - var dn = last.number - first.number; + // Get an average and variance for the different time estimates that exist. + var estimated_rates = []; + for (var i = 0, l = results_within_hour.length - 1; i < l; ++i) + estimated_rates.push (rate_between (i, i + 1)); - // Now that we have the rate, we can project how far out the user's number is likely to be. - var rate = dn / dt; - var time = (new Date().getTime() - first.time) / 60000; // Also in minutes - var diff = number - first.number; + var sqr = function (x) {return x * x}; + var average_rate = rate_between (0, results_within_hour.length - 1); + var variance = 0; - var expected = diff * rate; + for (var i = 0, l = estimated_rates.length; i < l; ++i) + variance += sqr (estimated_rates[i] - average_rate); - $('#result').text ('Your expected wait is ' + (expected - time >> 0) + ' minutes.'); + variance /= estimated_rates.length; + + var conservative_rate = average_rate + 2 * variance; + + var last = results_within_hour[results_within_hour.length - 1]; + var distance_to_travel = number - last.number; + var time_already_elapsed = new Date().getTime() - last.time; + + var total_time_given_rate = function (rate) { + return distance_to_travel / rate - time_already_elapsed; + }; + + var average_estimate = total_time_given_rate (average_rate) / 60000; + var conservative_estimate = total_time_given_rate (conservative_rate) / 60000; + + $('#result').text ('The current number is ' + last.number + ', and your expected wait is ' + (average_estimate >> 0) + ' minutes.' + + 'To be on the safe side, you should probably allow for only ' + (conservative_estimate >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
634b57e4da3c378cc34b58943c279e8e8422bfc5
Fix variable name
diff --git a/timer.html b/timer.html index 490161b..6a60fe9 100644 --- a/timer.html +++ b/timer.html @@ -1,74 +1,74 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); - results_with_hour.sort (function (x, y) { + results_within_hour.sort (function (x, y) { var xd = Date.parse (x.created_at), yd = Date.parse (y.created_at); return xd < yd ? -1 : xd > yd ? 1 : 0; }); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; // Now that we have the rate, we can project how far out the user's number is likely to be. var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected = diff * rate; $('#result').text ('Your expected wait is ' + (expected - time >> 0) + ' minutes.'); }); }; // Use the Twitter API to query for the numbers. setInterval (lookup, 10000); lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
f48f82b2d0425052b0801a33ebc963c722dd13e2
Sorting results
diff --git a/timer.html b/timer.html index 98e1b99..490161b 100644 --- a/timer.html +++ b/timer.html @@ -1,66 +1,74 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); - // Use the Twitter API to query for the numbers. - setInterval (function () { + var lookup = function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); + results_with_hour.sort (function (x, y) { + var xd = Date.parse (x.created_at), yd = Date.parse (y.created_at); + return xd < yd ? -1 : xd > yd ? 1 : 0; + }); + // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; // Now that we have the rate, we can project how far out the user's number is likely to be. var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected = diff * rate; $('#result').text ('Your expected wait is ' + (expected - time >> 0) + ' minutes.'); }); - }, 2000); + }; + + // Use the Twitter API to query for the numbers. + setInterval (lookup, 10000); + lookup(); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
ff655da8a463449cf47862c463e069bb81017568
Fix variable name
diff --git a/timer.html b/timer.html index b10b2a4..98e1b99 100644 --- a/timer.html +++ b/timer.html @@ -1,66 +1,66 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); // Use the Twitter API to query for the numbers. setInterval (function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; // Now that we have the rate, we can project how far out the user's number is likely to be. var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; - var expected_time = diff * rate; + var expected = diff * rate; $('#result').text ('Your expected wait is ' + (expected - time >> 0) + ' minutes.'); }); }, 2000); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
62f3ab2ddce46a8314ed379323263960cc571997
Reduce timeout
diff --git a/timer.html b/timer.html index bfd83c2..b10b2a4 100644 --- a/timer.html +++ b/timer.html @@ -1,66 +1,66 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); // Use the Twitter API to query for the numbers. setInterval (function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; // Now that we have the rate, we can project how far out the user's number is likely to be. var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected_time = diff * rate; $('#result').text ('Your expected wait is ' + (expected - time >> 0) + ' minutes.'); }); - }, 10000); + }, 2000); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
49eb502a09d0c5ec3c0b9d0fcd80483798dd75cc
Preserving sign
diff --git a/timer.html b/timer.html index 65e4441..bfd83c2 100644 --- a/timer.html +++ b/timer.html @@ -1,66 +1,66 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); // Use the Twitter API to query for the numbers. setInterval (function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; // Now that we have the rate, we can project how far out the user's number is likely to be. var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected_time = diff * rate; - $('#result').text ('Your expected wait is ' + (expected - time >>> 0) + ' minutes.'); + $('#result').text ('Your expected wait is ' + (expected - time >> 0) + ' minutes.'); }); }, 10000); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
b11f5e7f98ad7e767102ad27b045195edb5c4c44
Perhaps fixed the timing logic.
diff --git a/timer.html b/timer.html index c73f3e2..65e4441 100644 --- a/timer.html +++ b/timer.html @@ -1,65 +1,66 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); $('#estimate').hide(); // Use the Twitter API to query for the numbers. setInterval (function () { $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; + // Now that we have the rate, we can project how far out the user's number is likely to be. var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; - var expected = diff / rate * time; + var expected_time = diff * rate; - $('#result').text ('Your expected wait is ' + (expected >>> 0) + ' minutes.'); + $('#result').text ('Your expected wait is ' + (expected - time >>> 0) + ' minutes.'); }); }, 10000); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
5cda266275b50f17f43872a5aa0a11f3e43e8f44
Using auto-refresh and hiding the button to prevent stacking
diff --git a/timer.html b/timer.html index b4922bf..c73f3e2 100644 --- a/timer.html +++ b/timer.html @@ -1,62 +1,65 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); + $('#estimate').hide(); // Use the Twitter API to query for the numbers. - $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { - var results_within_hour = []; - var match = null; - for (var i = 0, l = results.results.length; i < l; ++i) - if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && - (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) - results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); - - // Take the minimum and maximum values and find the rate. - var first = results_within_hour[0]; - var middle = results_within_hour[results_within_hour.length >> 1]; - var last = results_within_hour[results_within_hour.length - 1]; - - var dt = (last.time - first.time) / 60000; // In minutes - var dn = last.number - first.number; - - var rate = dn / dt; - var time = (new Date().getTime() - first.time) / 60000; // Also in minutes - var diff = number - first.number; - - var expected = diff / rate * time; - - $('#result').text ('Your expected wait is ' + (expected >>> 0) + ' minutes.'); - }); + setInterval (function () { + $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { + var results_within_hour = []; + var match = null; + for (var i = 0, l = results.results.length; i < l; ++i) + if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && + (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) + results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); + + // Take the minimum and maximum values and find the rate. + var first = results_within_hour[0]; + var middle = results_within_hour[results_within_hour.length >> 1]; + var last = results_within_hour[results_within_hour.length - 1]; + + var dt = (last.time - first.time) / 60000; // In minutes + var dn = last.number - first.number; + + var rate = dn / dt; + var time = (new Date().getTime() - first.time) / 60000; // Also in minutes + var diff = number - first.number; + + var expected = diff / rate * time; + + $('#result').text ('Your expected wait is ' + (expected >>> 0) + ' minutes.'); + }); + }, 10000); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> - <button onclick='estimate()'>Estimate</button> + <button id='estimate' onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
a01cbfe136dd6f927d65723fb5d1cb1be8b941d0
Using JSONP
diff --git a/timer.html b/timer.html index 1a0f93b..b4922bf 100644 --- a/timer.html +++ b/timer.html @@ -1,62 +1,62 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); // Use the Twitter API to query for the numbers. - $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag), function (results) { + $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag) + '&callback=?', function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected = diff / rate * time; $('#result').text ('Your expected wait is ' + (expected >>> 0) + ' minutes.'); }); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
0c6749b8a2af1dbf0292400cb9998d4ddb427628
Fix jQuery URL
diff --git a/timer.html b/timer.html index 4b0d9ab..1a0f93b 100644 --- a/timer.html +++ b/timer.html @@ -1,62 +1,62 @@ <html> <head> <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> - <script src='http://ajax.googleapis.com/libs/ajax/jquery/1.4.2/jquery.min.js'></script> + <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); // Use the Twitter API to query for the numbers. $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag), function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected = diff / rate * time; $('#result').text ('Your expected wait is ' + (expected >>> 0) + ' minutes.'); }); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>
spencertipping/webtimer
9ddffab0a52eb9a1d01232cf72c548f84a94930a
Removed references to DMV, and made the match more lenient
diff --git a/timer.html b/timer.html index 9c8c96a..4b0d9ab 100644 --- a/timer.html +++ b/timer.html @@ -1,62 +1,62 @@ <html> <head> - <title>DMV Waiting List Estimator</title> + <title>Waiting List Estimator</title> <style> body {font-family: sans-serif} </style> <script src='http://ajax.googleapis.com/libs/ajax/jquery/1.4.2/jquery.min.js'></script> <script> var estimate = function () { var hashtag = $('#hashtag').val(); var number = Number($('#number').val()); $('#result').text ('Gathering data and producing estimate...'); // Use the Twitter API to query for the numbers. $.getJSON ('http://search.twitter.com/search.json?q=' + escape (hashtag), function (results) { var results_within_hour = []; var match = null; for (var i = 0, l = results.results.length; i < l; ++i) if (new Date().getTime() - Date.parse (results.results[i].created_at) < 3600 * 1000 && - (match = /^\s*(\d+)\s+#/.exec (results.results[i].text))) + (match = /^\s*(\d+)\s*#/.exec (results.results[i].text))) results_within_hour.push ({number: match[1], time: Date.parse (results.results[i].created_at)}); // Take the minimum and maximum values and find the rate. var first = results_within_hour[0]; var middle = results_within_hour[results_within_hour.length >> 1]; var last = results_within_hour[results_within_hour.length - 1]; var dt = (last.time - first.time) / 60000; // In minutes var dn = last.number - first.number; var rate = dn / dt; var time = (new Date().getTime() - first.time) / 60000; // Also in minutes var diff = number - first.number; var expected = diff / rate * time; $('#result').text ('Your expected wait is ' + (expected >>> 0) + ' minutes.'); }); }; </script> </head> <body> <h1>Wait Estimator</h1> <p>This application estimates your wait if you are in a numbered queue. To provide data, tweet the current number on a Twitter channel. For example, if the current number at the Boulder DMV office is 904, you would tweet <code>904 #boulderdmv</code>.</p> <p>To compute your wait, enter the Twitter hashtag and your number. Based on the tweets that you and others have provided, the amount of time left will be estimated in a few seconds.</p> <p>Keep in mind that this estimate is exact; if you are worried about missing your appointment, you should arrive early. It is only an estimate, not a guarantee; so it is possibly inaccurate.</p> <table><tr><td>Twitter hashtag (e.g. <code>#boulderdmv</code>): </td><td><input id='hashtag'></input></td></tr> <tr><td>Your number: </td><td><input id='number'></input></td></tr></table> <button onclick='estimate()'>Estimate</button> <div id='result'></div> </body> </html>