Angularjs – Percentage input

I create an angular directive use to input percentage of input text. This is very easy

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
myApp.directive("percent", function ($filter, $locale, $window) {
    var p = function (viewValue) {
        if (viewValue == '') {
            return 0;
        }
        var value = stringToNumber(viewValue);
        return value / 100;
    };

   var stringToNumber = function (value) {
        if (angular.isNumber(parseFloat(value))) {
            if (value.indexOf(',') > 0) {
                var number = angular.copy(value) + '';
                number = number.replaceAll($locale.NUMBER_FORMATS.GROUP_SEP, '');
                number = number.replaceAll($locale.NUMBER_FORMATS.DECIMAL_SEP, '.');
                number = parseFloat(number);
                if (isNaN(number)) {
                    return 0;
                } else {
                    return number;
                }
            } else {
                return value;
            }
        } else {
            var number = angular.copy(value) + '';
            number = number.replaceAll($locale.NUMBER_FORMATS.GROUP_SEP, '');
            number = number.replaceAll($locale.NUMBER_FORMATS.DECIMAL_SEP, '.');
            number = parseFloat(number);
            if (isNaN(number)) {
                return 0;
            } else {
                return number;
            }
        }
    }

    var f = function (modelValue) {
        if (angular.isDefined(modelValue)) {
            return $filter('number')(modelValue * 100, 3) + ' %';
        }
    };
    
    return {
        require: 'ngModel',
        link: function(scope, ele, attr, ctrl){
            ctrl.$parsers.unshift(p);
            ctrl.$formatters.unshift(f);
            ele.on('blur', function () {
                if (angular.isDefined(ctrl.$modelValue)) {
                    ele.val($filter('number')(ctrl.$modelValue * 100, 3) + ' %');
                } 
            });
            /*
            ele.on('click', function () {
                if (!$window.getSelection().toString()) {
                    this.setSelectionRange(0, this.value.length)
                }
            });
            */
        }
    };
});

You can use it on html page:

<input percent ng-model="modelValue" />
Advertisements

DETECTING MOBILE DEVICES WITH JAVASCRIPT

While I understand and value the concept of feature detection over browser detection, sometimes the need for knowing whether or not we’re dealing with a mobile device arises. For in-depth device checking, you can rely on a complex library such as The MobileESP Project. But for simpler applications, the following snippet can be useful.

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

While this doesn’t account for all mobile platforms, it will pick up the most popular ones out there.

EXAMPLES

To check to see if the user is on any of the supported mobile devices:

if( isMobile.any() ) alert('Mobile');

To check to see if the user is on a specific mobile device:

if( isMobile.iOS() ) alert('iOS');

SQL – Recursive select parent child

You’ll need your recursion to also build something that can be sorted by at the end:

declare @t TABLE (
[CHILD] [int] NOT NULL,
[PARENT] [int] NOT NULL
) 

insert @t values
( 0, -1),   -- I added this
( 1, 2 ),
( 2, 0 ),
( 3, 1 ),
( 4, 2 ),
( 5, 0 )

(note I have added a true root element)

;with n(CHILD, PARENT, GENERATION, hierarchy) as (
select CHILD, PARENT,0, CAST(CHILD as nvarchar) as GENERATION from @t
where PARENT=-1
union all
select nplus1.CHILD, nplus1.PARENT, GENERATION+1,
cast(n.hierarchy + '.' + CAST(nplus1.child as nvarchar) as nvarchar)
 from
@t as nplus1 inner join n on nplus1.PARENT=n.CHILD
)
select CHILD,GENERATION
from n
order by hierarchy

returns

CHILD GENERATION
0           0
2           1
1           2
3          3
4          2
5          1

SQL Server – Drop Temp Table if Exist

If you’re here then you’ve probably run into the situation where you’ve automatically created a temp table in your script, and every time you execute the script you have to drop the temp table manually. Yes, this can be a pain. I’ve done this myself many times.

So here’s the easy solution. We need to check if the temp table exists within the TempDB database and if it does, we need to drop it.

IF OBJECT_ID(N'tempdb..#Temp') IS NOT NULL
BEGIN
    DROP TABLE #Temp
END

To replicate this, let’s run the following command in the same window multiple times:

-- (Replace the product table below with your table)
SELECT *
INTO #Temp
FROM SalesLT.Product

We get the error message:
There is already an object named ‘#Temp’ in the database.

Now we simple add our snippet of code, and we are able to execute without having to manually drop anymore.

IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
BEGIN
    DROP TABLE #Temp
END

-- (Replace the product table below with your table)
SELECT *
INTO #Temp
FROM SalesLT.Product

Primeface – Refresh Context Menu on selected node of Tree

On the Tree of Primeface, after you selec a node, you want to update menuitem of the Context Menu and show context menu.

But the problem is that the show is called on the context menu before the update, and then the update hide menu.

This is a general problem as it is expected that a context menu can be updated according to the tree selection hence the ‘context’ changes, so I would expect a fix in the core software.

My workaround was to override the show, and then call it after the update is done.

<p:contextMenu id="tableContextMenu" for="treeTableId" widgetVar="tableContextMenuWV">
<p:treeTable  id="treeTableId" >
  <p:ajax event="select" update=":form1:tableContextMenu :form1:treeTableId" oncomplete="tableContextMenuWV.show();"/>
</p:treeTable>
var siteFunctions = {
    //patch to fix a problem that the context menu disappears after update
    //delay the show to occure after the update 
    patchContextMenuShow: function() {
        'use strict';
        var protShow = PrimeFaces.widget.ContextMenu.prototype.show;
        siteFunctions.patchContextMenuShow.lastEvent = null;
        PrimeFaces.widget.ContextMenu.prototype.show = function(e) {
            var ret;
            if (e) {

//                console.log('saving last event');

                siteFunctions.patchContextMenuShow.lastEvent = e;
                siteFunctions.patchContextMenuShow.lastEventArg = arguments;
                siteFunctions.patchContextMenuShow.lastEventContext = this;
            } else if (siteFunctions.patchContextMenuShow.lastEvent) {

//                console.log('executing last event');

                ret = protShow.apply(siteFunctions.patchContextMenuShow.lastEventContext, siteFunctions.patchContextMenuShow.lastEventArg);

//                console.log('clearing last event');
                siteFunctions.patchContextMenuShow.lastEvent = null;
            }
            return ret;
        };
    }
};

$(document).ready(function() {
    'use strict';
    try {
        siteFunctions.patchContextMenuShow();
    } catch (e) {
        console.error(e);
    }
});

Reading JavaScript variables using Selenium RC

When you run selenium test case, if you want to get value of javascript variable, you can use selenium remote control to get value

Javascript in tested page

$(document).ready(function() {
var myTestVariable = [true, true, false, true];
});

You can get value of myTestVariable by using this code

String [] myTestVariableArray= selenium.getEval("this.browserbot.getUserWindow().myTestVariable ").split(",");
for(int i=0;i<myTestVariableArray.length; i++){
  System.out.println(myTestVariableArray[i]);
}

jQuery – input number only

If you have  an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5…9) 0-9. You can use jquery plugin autoNumericautoNumeric 1.9.15 is a jQuery plugin that automatically formats currency and numbers as you type on form inputs. It supports most International numeric formats and currency signs including those used in Europe, North and South America, Asia and India

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
<script src="autoNumeric.js" type=text/javascript> </script>
<script type="text/javascript">
$(document).ready(function() {
 var userLangDecimalSep = ','; // set the separated symbol is common or point
 var maxValue = '24';
 $('#inputNumberOnly').autoNumeric('init',{aSep: '', aDec: userLangDecimalSep, vMax:maxValue, vMin:0, wEmpty: '0.00', mDec: 2});
 $('#inputNumberOnly').focus(function (e){
  /*
  // Update max value
  var maxValue = '25';
  $('#inputNumberOnly').autoNumeric('init',{aSep: '', aDec: ',', vMax:maxValue, vMin:0, wEmpty: '0.00', mDec: 2});
  */
 // select number of input when you focus (fix on IE7)
 $(this).select();
 });
});
</script>