<commit_before>/* global d3 */
/*
 ng-radial-gauge 1.0
 (c) 2010-2014 Stéphane Therrien,
 https://github.com/stherrienaspnet/ngRadialGauge
 License: MIT
*/
"use strict";
angular.module("ngRadialGauge",[]).directive('ngRadialGauge', ['$window', '$timeout',
 function ($window, $timeout) {
     return {
         restrict: 'EAC',
         scope: {
             lowerLimit: '=',
             upperLimit: '=',
             ranges: '=',
             value: '=',
             valueUnit: '=',
             precision: '=',
             label: '@',
             onClick: '&'
         },
         link: function (scope, ele, attrs) {
             var initialized = false;
             var renderTimeout;
             var width = parseInt(attrs.width) || 300;
             var innerRadius = Math.round((width * 130) / 300);
             var outterRadius = Math.round((width * 145) / 300);
             var majorGraduations = parseInt(attrs.majorGraduations - 1) || 5;
             var minorGraduations = parseInt(attrs.minorGraduations) || 10;
             var majorGraduationLenght = Math.round((width * 16) / 300);
             var minorGraduationLenght = Math.round((width * 10) / 300);
             var majorGraduationMarginTop = Math.round((width * 7) / 300);
             var majorGraduationColor = attrs.majorGraduationColor || "#B0B0B0";
             var minorGraduationColor = attrs.minorGraduationColor || "#D0D0D0";
             var majorGraduationTextColor = attrs.majorGraduationTextColor || "#6C6C6C";
             var needleColor = attrs.needleColor || "#416094";
             var valueVerticalOffset = Math.round((width * 30) / 300);
             var unactiveColor = "#D7D7D7";
             var transitionMs = parseInt(attrs.transitionMs) || 750;
             var majorGraduationTextSize = parseInt(attrs.majorGraduationTextSize);
             var needleValueTextSize = parseInt(attrs.needleValueTextSize);

             var maxLimit = scope.upperLimit ? scope.upperLimit : 100;
             var minLimit = scope.lowerLimit ? scope.lowerLimit : 0;

             var needle = undefined;
             var scale = d3.scale.linear()
                           .range([0,1])
                           .domain([minLimit, maxLimit]);

             var svg = d3.select(ele[0])
                 .append('svg')
                 .attr('width', width)
                 .attr('height', width * 0.75);
             var renderMajorGraduations = function (majorGraduationsAngles) {
                 var centerX = width / 2;
                 var centerY = width / 2;
                 //Render Major Graduations
                 $.each(majorGraduationsAngles, function (index, value) {
                     var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                     var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                     var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                     var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                     var x1 = centerX + cos1Adj;
                     var y1 = centerY + sin1Adj * -1;
                     var x2 = centerX + cos2Adj;
                     var y2 = centerY + sin2Adj * -1;
                     svg.append("svg:line")
                     .attr("x1", x1)
                     .attr("y1", y1)
                     .attr("x2", x2)
                     .attr("y2", y2)
                     .style("stroke", majorGraduationColor);

                     renderMinorGraduations(majorGraduationsAngles, index);
                 });
             };
             var renderMinorGraduations = function (majorGraduationsAngles, indexMajor) {
                 var minorGraduationsAngles = [];

                 if (indexMajor > 0) {
                     var minScale = majorGraduationsAngles[indexMajor - 1];
                     var maxScale = majorGraduationsAngles[indexMajor];
                     var scaleRange = maxScale - minScale;

                     for (var i = 1; i < minorGraduations; i++) {
                         var scaleValue = minScale + i * scaleRange / minorGraduations;
                         minorGraduationsAngles.push(scaleValue);
                     }

                     var centerX = width / 2;
                     var centerY = width / 2;
                     //Render Minor Graduations
                     $.each(minorGraduationsAngles, function (indexMinor, value) {
                         var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                         var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                         var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                         var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                         var x1 = centerX + cos1Adj;
                         var y1 = centerY + sin1Adj * -1;
                         var x2 = centerX + cos2Adj;
                         var y2 = centerY + sin2Adj * -1;
                         svg.append("svg:line")
                         .attr("x1", x1)
                         .attr("y1", y1)
                         .attr("x2", x2)
                         .attr("y2", y2)
                         .style("stroke", minorGraduationColor);
                     });
                 }
             };
             var getMajorGraduationValues = function (minLimit, maxLimit) {
                 var scaleRange = maxLimit - minLimit;
                 var majorGraduationValues = [];
                 for (var i = 0; i <= majorGraduations; i++) {
                     var scaleValue = minLimit + i * scaleRange / (majorGraduations);
                     majorGraduationValues.push(scaleValue.toFixed(scope.precision));
                 }

                 return majorGraduationValues;
             };
             var getMajorGraduationAngles = function () {
                 var scaleRange = 240;
                 var minScale = -120;
                 var graduationsAngles = [];
                 for (var i = 0; i <= majorGraduations; i++) {
                     var scaleValue = minScale + i * scaleRange / (majorGraduations);
                     graduationsAngles.push(scaleValue);
                 }

                 return graduationsAngles;
             };
             var getNewAngle = function(value){
                 var ratio = scale(value);
                 var range = 240;
                 var minScale = -120;
                 var newAngle = minScale + (ratio * range);
                 return newAngle;
             };
             var renderMajorGraduationTexts = function (majorGraduationsAngles, majorGraduationValues) {
                 if (!scope.ranges) return;

                 var centerX = width / 2;
                 var centerY = width / 2;
                 var textVerticalPadding = 5;
                 var textHorizontalPadding = 5;

                 var lastGraduationValue = majorGraduationValues[majorGraduationValues.length - 1];
                 var textSize = isNaN(majorGraduationTextSize) ? (width * 12) / 300 : majorGraduationTextSize;
                 var fontStyle = textSize + "px Courier";

                 var dummyText = svg.append("text")
                     .attr("x", centerX)
                     .attr("y", centerY)
                     .attr("fill", "transparent")
                     .attr("text-anchor", "middle")
                     .style("font", fontStyle)
                     .text(lastGraduationValue + scope.valueUnit);

                 var textWidth = dummyText.node().getBBox().width;

                 for (var i = 0; i < majorGraduationsAngles.length; i++) {
                     var angle = majorGraduationsAngles[i];
                     var cos1Adj = Math.round(Math.cos((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textHorizontalPadding));
                     var sin1Adj = Math.round(Math.sin((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textVerticalPadding));

                     var sin1Factor = 1;
                     if (sin1Adj < 0) sin1Factor = 1.1;
                     if (sin1Adj > 0) sin1Factor = 0.9;
                     if (cos1Adj > 0) {
                         if (angle > 0 && angle < 45) {
                             cos1Adj -= textWidth / 2;
                         } else {
                             cos1Adj -= textWidth;
                         }
                     }
                     if (cos1Adj < 0) {
                         if (angle < 0 && angle > -45) {
                             cos1Adj -= textWidth / 2;
                         }
                     }
                     if (cos1Adj == 0) {
                         cos1Adj -= angle == 0 ? textWidth / 4 : textWidth / 2;
                     }

                     var x1 = centerX + cos1Adj;
                     var y1 = centerY + sin1Adj * sin1Factor * -1;

                     svg.append("text")
                     .attr("class", "mtt-majorGraduationText")
                     .style("font", fontStyle)
                     .attr("text-align", "center")
                     .attr("x", x1)
                     .attr("dy", y1)
                     .attr("fill", majorGraduationTextColor)
                     .text(majorGraduationValues[i] + scope.valueUnit);
                 }
             };
             var renderGraduationNeedle = function (minLimit, maxLimit) {
                 svg.selectAll('.mtt-graduation-needle').remove();
                 svg.selectAll('.mtt-graduationValueText').remove();
                 svg.selectAll('.mtt-graduation-needle-center').remove();

                 var centerX = width / 2;
                 var centerY = width / 2;
                 var centerColor;

                 if (typeof scope.value === 'undefined') {
                     centerColor = unactiveColor;
                 } else {
                     centerColor = needleColor;
                     var needleAngle = getNewAngle(scope.value);
                     var needleLen = innerRadius - majorGraduationLenght - majorGraduationMarginTop;
                     var needleRadius = (width * 2.5) / 300;
                     var textSize = isNaN(needleValueTextSize) ? (width * 12) / 300 : needleValueTextSize;
                     var fontStyle = textSize + "px Courier";

                     if (scope.value >= minLimit && scope.value <= maxLimit) {
                         var lineData = [
                            [needleRadius, 0],
                            [0, -needleLen],
                            [-needleRadius, 0],
                            [needleRadius, 0]
                         ];
                         var pointerLine = d3.svg.line().interpolate('monotone');
                         var pg = svg.append('g').data([lineData])
                                     .attr('class', 'mtt-graduation-needle')
                                     .style("fill", needleColor)
                                     .attr('transform', 'translate(' + centerX + ',' + centerY + ')');
                         needle = pg.append('path')
                                    .attr('d', pointerLine)
                                    .attr('transform', 'rotate('+needleAngle+')');
                     }

                     svg.append("text")
                         .attr("x", centerX)
                         .attr("y", centerY + valueVerticalOffset)
                         .attr("class", "mtt-graduationValueText")
                         .attr("fill", needleColor)
                         .attr("text-anchor", "middle")
                         .attr("font-weight", "bold")
                         .style("font", fontStyle)
                         .text('[ ' + scope.value.toFixed(scope.precision) + scope.valueUnit + ' ]');
                 }

                 var circleRadius = (width * 6) / 300;

                 svg.append("circle")
                   .attr("r", circleRadius)
                   .attr("cy", centerX)
                   .attr("cx", centerY)
                   .attr("fill", centerColor)
                   .attr("class", "mtt-graduation-needle-center");
             };
             $window.onresize = function () {
                 scope.$apply();
             };
             scope.$watch(function () {
                 return angular.element($window)[0].innerWidth;
             }, function () {
                 scope.render();
             });
             scope.$watch('ranges', function () {
                 scope.render();
             }, true);

             scope.render = function () {
                 svg.selectAll('*').remove();
                 if (renderTimeout) clearTimeout(renderTimeout);

                 renderTimeout = $timeout(function () {
                     var d3DataSource = [];

                     if (typeof scope.ranges === 'undefined') {
                         d3DataSource.push([minLimit, maxLimit, unactiveColor]);
                     } else {
                         //Data Generation
                         $.each(scope.ranges, function (index, value) {
                             d3DataSource.push([value.min, value.max, value.color]);
                         });
                     }

                     //Render Gauge Color Area
                     var translate = "translate(" + width / 2 + "," + width / 2 + ")";
                     var cScale = d3.scale.linear().domain([minLimit, maxLimit]).range([-120 * (Math.PI / 180), 120 * (Math.PI / 180)]);
                     var arc = d3.svg.arc()
                         .innerRadius(innerRadius)
                         .outerRadius(outterRadius)
                         .startAngle(function (d) { return cScale(d[0]); })
                         .endAngle(function (d) { return cScale(d[1]); });
                     svg.selectAll("path")
                         .data(d3DataSource)
                         .enter()
                         .append("path")
                         .attr("d", arc)
                         .style("fill", function (d) { return d[2]; })
                         .attr("transform", translate);

                     var majorGraduationsAngles = getMajorGraduationAngles();
                     var majorGraduationValues = getMajorGraduationValues(minLimit, maxLimit);
                     renderMajorGraduations(majorGraduationsAngles);
                     renderMajorGraduationTexts(majorGraduationsAngles, majorGraduationValues);
                     renderGraduationNeedle(minLimit, maxLimit);
                     initialized = true;
                 }, 200);

             };
             var update = function(){
                 if (typeof scope.value === 'undefined') {
                     centerColor = unactiveColor;
                 } else {
                     if (scope.value >= minLimit && scope.value <= maxLimit) {
                         var needleAngle = getNewAngle(scope.value);
                         needle.transition()
                               .duration(transitionMs)
                               .ease('elastic')
                               .attr('transform', 'rotate('+needleAngle+')');
                         svg.selectAll('.mtt-graduationValueText')
                            .text('[ ' + scope.value.toFixed(scope.precision) + scope.valueUnit + ' ]') ;
                     } else {
                         svg.selectAll('.mtt-graduation-needle').remove();
                         svg.selectAll('.mtt-graduationValueText').remove();
                         svg.selectAll('.mtt-graduation-needle-center').attr("fill", unactiveColor);
                     }
                 }
             };
             scope.$watch('value', function () {
                 if (!initialized) return;
                 update();
             }, true);
         }
     };
 }]);
<commit_msg>Update ng-radial-gauge-dir.js<commit_after>/* global d3 */
/*
 ng-radial-gauge 1.0
 (c) 2010-2014 Stéphane Therrien,
 https://github.com/stherrienaspnet/ngRadialGauge
 License: MIT
*/
"use strict";
angular.module("ngRadialGauge",[]).directive('ngRadialGauge', ['$window', '$timeout',
 function ($window, $timeout) {
     return {
         restrict: 'EAC',
         scope: {
             lowerLimit: '=',
             upperLimit: '=',
             ranges: '=',
             value: '=',
             valueUnit: '=',
             precision: '=',
             label: '@',
             onClick: '&'
         },
         link: function (scope, ele, attrs) {
             var initialized = false;
             var renderTimeout;
             var gaugeAngle = parseInt(attrs.angle) || 120;
             var width = parseInt(attrs.width) || 300;
             var innerRadius = Math.round((width * 130) / 300);
             var outterRadius = Math.round((width * 145) / 300);
             var majorGraduations = parseInt(attrs.majorGraduations - 1) || 5;
             var minorGraduations = parseInt(attrs.minorGraduations) || 10;
             var majorGraduationLenght = Math.round((width * 16) / 300);
             var minorGraduationLenght = Math.round((width * 10) / 300);
             var majorGraduationMarginTop = Math.round((width * 7) / 300);
             var majorGraduationColor = attrs.majorGraduationColor || "#B0B0B0";
             var minorGraduationColor = attrs.minorGraduationColor || "#D0D0D0";
             var majorGraduationTextColor = attrs.majorGraduationTextColor || "#6C6C6C";
             var needleColor = attrs.needleColor || "#416094";
             var valueVerticalOffset = Math.round((width * 30) / 300);
             var unactiveColor = "#D7D7D7";
             var transitionMs = parseInt(attrs.transitionMs) || 750;
             var majorGraduationTextSize = parseInt(attrs.majorGraduationTextSize);
             var needleValueTextSize = parseInt(attrs.needleValueTextSize);

             var maxLimit = scope.upperLimit ? scope.upperLimit : 100;
             var minLimit = scope.lowerLimit ? scope.lowerLimit : 0;

             var needle = undefined;
             var scale = d3.scale.linear()
                           .range([0,1])
                           .domain([minLimit, maxLimit]);

             var svg = d3.select(ele[0])
                 .append('svg')
                 .attr('width', width)
                 .attr('height', width * 0.75);
             var renderMajorGraduations = function (majorGraduationsAngles) {
                 var centerX = width / 2;
                 var centerY = width / 2;
                 //Render Major Graduations
                 $.each(majorGraduationsAngles, function (index, value) {
                     var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                     var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght));
                     var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                     var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                     var x1 = centerX + cos1Adj;
                     var y1 = centerY + sin1Adj * -1;
                     var x2 = centerX + cos2Adj;
                     var y2 = centerY + sin2Adj * -1;
                     svg.append("svg:line")
                     .attr("x1", x1)
                     .attr("y1", y1)
                     .attr("x2", x2)
                     .attr("y2", y2)
                     .style("stroke", majorGraduationColor);

                     renderMinorGraduations(majorGraduationsAngles, index);
                 });
             };
             var renderMinorGraduations = function (majorGraduationsAngles, indexMajor) {
                 var minorGraduationsAngles = [];

                 if (indexMajor > 0) {
                     var minScale = majorGraduationsAngles[indexMajor - 1];
                     var maxScale = majorGraduationsAngles[indexMajor];
                     var scaleRange = maxScale - minScale;

                     for (var i = 1; i < minorGraduations; i++) {
                         var scaleValue = minScale + i * scaleRange / minorGraduations;
                         minorGraduationsAngles.push(scaleValue);
                     }

                     var centerX = width / 2;
                     var centerY = width / 2;
                     //Render Minor Graduations
                     $.each(minorGraduationsAngles, function (indexMinor, value) {
                         var cos1Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                         var sin1Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - minorGraduationLenght));
                         var cos2Adj = Math.round(Math.cos((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                         var sin2Adj = Math.round(Math.sin((90 - value) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop));
                         var x1 = centerX + cos1Adj;
                         var y1 = centerY + sin1Adj * -1;
                         var x2 = centerX + cos2Adj;
                         var y2 = centerY + sin2Adj * -1;
                         svg.append("svg:line")
                         .attr("x1", x1)
                         .attr("y1", y1)
                         .attr("x2", x2)
                         .attr("y2", y2)
                         .style("stroke", minorGraduationColor);
                     });
                 }
             };
             var getMajorGraduationValues = function (minLimit, maxLimit) {
                 var scaleRange = maxLimit - minLimit;
                 var majorGraduationValues = [];
                 for (var i = 0; i <= majorGraduations; i++) {
                     var scaleValue = minLimit + i * scaleRange / (majorGraduations);
                     majorGraduationValues.push(scaleValue.toFixed(scope.precision));
                 }

                 return majorGraduationValues;
             };
             var getMajorGraduationAngles = function () {
                 var scaleRange = 2 * gaugeAngle;
                 var minScale = -1 * gaugeAngle;
                 var graduationsAngles = [];
                 for (var i = 0; i <= majorGraduations; i++) {
                     var scaleValue = minScale + i * scaleRange / (majorGraduations);
                     graduationsAngles.push(scaleValue);
                 }

                 return graduationsAngles;
             };
             var getNewAngle = function(value){
                 var ratio = scale(value);
                 var scaleRange = 2 * gaugeAngle;
                 var minScale = -1 * gaugeAngle;
                 var newAngle = minScale + (ratio * range);
                 return newAngle;
             };
             var renderMajorGraduationTexts = function (majorGraduationsAngles, majorGraduationValues) {
                 if (!scope.ranges) return;

                 var centerX = width / 2;
                 var centerY = width / 2;
                 var textVerticalPadding = 5;
                 var textHorizontalPadding = 5;

                 var lastGraduationValue = majorGraduationValues[majorGraduationValues.length - 1];
                 var textSize = isNaN(majorGraduationTextSize) ? (width * 12) / 300 : majorGraduationTextSize;
                 var fontStyle = textSize + "px Courier";

                 var dummyText = svg.append("text")
                     .attr("x", centerX)
                     .attr("y", centerY)
                     .attr("fill", "transparent")
                     .attr("text-anchor", "middle")
                     .style("font", fontStyle)
                     .text(lastGraduationValue + scope.valueUnit);

                 var textWidth = dummyText.node().getBBox().width;

                 for (var i = 0; i < majorGraduationsAngles.length; i++) {
                     var angle = majorGraduationsAngles[i];
                     var cos1Adj = Math.round(Math.cos((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textHorizontalPadding));
                     var sin1Adj = Math.round(Math.sin((90 - angle) * Math.PI / 180) * (innerRadius - majorGraduationMarginTop - majorGraduationLenght - textVerticalPadding));

                     var sin1Factor = 1;
                     if (sin1Adj < 0) sin1Factor = 1.1;
                     if (sin1Adj > 0) sin1Factor = 0.9;
                     if (cos1Adj > 0) {
                         if (angle > 0 && angle < 45) {
                             cos1Adj -= textWidth / 2;
                         } else {
                             cos1Adj -= textWidth;
                         }
                     }
                     if (cos1Adj < 0) {
                         if (angle < 0 && angle > -45) {
                             cos1Adj -= textWidth / 2;
                         }
                     }
                     if (cos1Adj == 0) {
                         cos1Adj -= angle == 0 ? textWidth / 4 : textWidth / 2;
                     }

                     var x1 = centerX + cos1Adj;
                     var y1 = centerY + sin1Adj * sin1Factor * -1;

                     svg.append("text")
                     .attr("class", "mtt-majorGraduationText")
                     .style("font", fontStyle)
                     .attr("text-align", "center")
                     .attr("x", x1)
                     .attr("dy", y1)
                     .attr("fill", majorGraduationTextColor)
                     .text(majorGraduationValues[i] + scope.valueUnit);
                 }
             };
             var renderGraduationNeedle = function (minLimit, maxLimit) {
                 svg.selectAll('.mtt-graduation-needle').remove();
                 svg.selectAll('.mtt-graduationValueText').remove();
                 svg.selectAll('.mtt-graduation-needle-center').remove();

                 var centerX = width / 2;
                 var centerY = width / 2;
                 var centerColor;

                 if (typeof scope.value === 'undefined') {
                     centerColor = unactiveColor;
                 } else {
                     centerColor = needleColor;
                     var needleAngle = getNewAngle(scope.value);
                     var needleLen = innerRadius - majorGraduationLenght - majorGraduationMarginTop;
                     var needleRadius = (width * 2.5) / 300;
                     var textSize = isNaN(needleValueTextSize) ? (width * 12) / 300 : needleValueTextSize;
                     var fontStyle = textSize + "px Courier";

                     if (scope.value >= minLimit && scope.value <= maxLimit) {
                         var lineData = [
                            [needleRadius, 0],
                            [0, -needleLen],
                            [-needleRadius, 0],
                            [needleRadius, 0]
                         ];
                         var pointerLine = d3.svg.line().interpolate('monotone');
                         var pg = svg.append('g').data([lineData])
                                     .attr('class', 'mtt-graduation-needle')
                                     .style("fill", needleColor)
                                     .attr('transform', 'translate(' + centerX + ',' + centerY + ')');
                         needle = pg.append('path')
                                    .attr('d', pointerLine)
                                    .attr('transform', 'rotate('+needleAngle+')');
                     }

                     svg.append("text")
                         .attr("x", centerX)
                         .attr("y", centerY + valueVerticalOffset)
                         .attr("class", "mtt-graduationValueText")
                         .attr("fill", needleColor)
                         .attr("text-anchor", "middle")
                         .attr("font-weight", "bold")
                         .style("font", fontStyle)
                         .text('[ ' + scope.value.toFixed(scope.precision) + scope.valueUnit + ' ]');
                 }

                 var circleRadius = (width * 6) / 300;

                 svg.append("circle")
                   .attr("r", circleRadius)
                   .attr("cy", centerX)
                   .attr("cx", centerY)
                   .attr("fill", centerColor)
                   .attr("class", "mtt-graduation-needle-center");
             };
             $window.onresize = function () {
                 scope.$apply();
             };
             scope.$watch(function () {
                 return angular.element($window)[0].innerWidth;
             }, function () {
                 scope.render();
             });
             scope.$watch('ranges', function () {
                 scope.render();
             }, true);

             scope.render = function () {
                 svg.selectAll('*').remove();
                 if (renderTimeout) clearTimeout(renderTimeout);

                 renderTimeout = $timeout(function () {
                     var d3DataSource = [];

                     if (typeof scope.ranges === 'undefined') {
                         d3DataSource.push([minLimit, maxLimit, unactiveColor]);
                     } else {
                         //Data Generation
                         $.each(scope.ranges, function (index, value) {
                             d3DataSource.push([value.min, value.max, value.color]);
                         });
                     }

                     //Render Gauge Color Area
                     var translate = "translate(" + width / 2 + "," + width / 2 + ")";
                     var cScale = d3.scale.linear().domain([minLimit, maxLimit]).range([-1 * gaugeAngle * (Math.PI / 180), gaugeAngle * (Math.PI / 180)]);
                     var arc = d3.svg.arc()
                         .innerRadius(innerRadius)
                         .outerRadius(outterRadius)
                         .startAngle(function (d) { return cScale(d[0]); })
                         .endAngle(function (d) { return cScale(d[1]); });
                     svg.selectAll("path")
                         .data(d3DataSource)
                         .enter()
                         .append("path")
                         .attr("d", arc)
                         .style("fill", function (d) { return d[2]; })
                         .attr("transform", translate);

                     var majorGraduationsAngles = getMajorGraduationAngles();
                     var majorGraduationValues = getMajorGraduationValues(minLimit, maxLimit);
                     renderMajorGraduations(majorGraduationsAngles);
                     renderMajorGraduationTexts(majorGraduationsAngles, majorGraduationValues);
                     renderGraduationNeedle(minLimit, maxLimit);
                     initialized = true;
                 }, 200);

             };
             var update = function(){
                 if (typeof scope.value === 'undefined') {
                     centerColor = unactiveColor;
                 } else {
                     if (scope.value >= minLimit && scope.value <= maxLimit) {
                         var needleAngle = getNewAngle(scope.value);
                         needle.transition()
                               .duration(transitionMs)
                               .ease('elastic')
                               .attr('transform', 'rotate('+needleAngle+')');
                         svg.selectAll('.mtt-graduationValueText')
                            .text('[ ' + scope.value.toFixed(scope.precision) + scope.valueUnit + ' ]') ;
                     } else {
                         svg.selectAll('.mtt-graduation-needle').remove();
                         svg.selectAll('.mtt-graduationValueText').remove();
                         svg.selectAll('.mtt-graduation-needle-center').attr("fill", unactiveColor);
                     }
                 }
             };
             scope.$watch('value', function () {
                 if (!initialized) return;
                 update();
             }, true);
         }
     };
 }]);
<|endoftext|>


<commit_before>/* jshint -W030,-W117 */

/*
 * grunt-EmailBuilder
 * https://github.com/yargalot/Email-Builder
 *
 * Copyright (c) 2013 Steven Miller
 * Licensed under the MIT license.
 */

 // Required modules
var juice     = require('juice'),
    path      = require('path'),
    cheerio   = require('cheerio'),
    async     = require('async'),
    encode    = require('./entityEncode'),
    Litmus    = require('./litmus');

function EmailBuilder(task) {

  this.task     = task;
  this.options  = task.options(EmailBuilder.Defaults);
  this.basepath = process.cwd();
  this.done     = this.task.async();

  // Cheerio
  // ---------------
  this.$;
  this.$title;
  this.$doctype;
  this.$styleTags;
  this.$styleLinks;

}

EmailBuilder.taskName         = 'emailBuilder';
EmailBuilder.taskDescription  = 'Compile Files';
EmailBuilder.Defaults         = {};

EmailBuilder.prototype.run = function(grunt) {

  var _that   = this;

  async.eachSeries(this.task.files, function(file, next) {

    var fileData = grunt.file.read(file.src);

    // Cheerio Init
    $           = cheerio.load(fileData);
    $title      = $('title').text().trim();
    $doctype    = $._root.children[0].data;
    $styleTags  = $('style');
    $styleLinks = $('link');

    // Read Css Files
    var srcFiles    = _that.getLinkTags($styleLinks);
    var embeddedCss = _that.getStyleTags($styleTags);
    var externalCss = _that.getExternalCss(srcFiles, file.src);
    var allCss      = embeddedCss + externalCss;

    // Get file output ready
    var output     = allCss ? juice.inlineContent($.html(), allCss) : $.html();

    // Encode special characters if option encodeSpecialChars is true
    if(_that.options.encodeSpecialChars === true) {
      output = encode.htmlEncode(output);
    }

    _that.writeFile(file.dest, output, next);

  }, function() {

    _that.done();

  });
};

EmailBuilder.prototype.getExternalCss = function(files, fileSource) {

  var externalCss = '';
  var grunt = this.task.grunt;

  // Set to target file path to get css
  grunt.file.setBase(path.dirname(fileSource));

  files.forEach(function(srcFile) {
    var css = grunt.file.read(srcFile.file);

    if(srcFile.inline) {
      externalCss += css;
    } else {
      $('head').append('<style>' + css + '</style>');
    }
  });

  // Set cwd back to root folder
  grunt.file.setBase(this.basepath);

  return externalCss;

};

// If doctype options is true, preserve doctype or add HTML5 doctype since jsdom removes it
EmailBuilder.prototype.getDoctype = function(output) {

  var doctyped = '';

  if ( this.options.doctype !== false ) {

    if ( $doctype.trim().length ) {
      doctyped = '<' + $doctype + '>' + output;
    } else {
      doctyped = '<!DOCTYPE html>' + output;
    }

  }else{
    doctyped = output;
  }

  return doctyped;

};

EmailBuilder.prototype.getStyleTags = function(styleTags) {

  var css = '';

  styleTags.each(function(i, element){
    var $this = $(this);

    if(!$this.attr('data-ignore')) {
      css += $this.text();
      $this.remove();
    }
  });

  return css;

};

EmailBuilder.prototype.getLinkTags = function(styleLinks) {

  var linkedStyles = [];

  styleLinks.each(function(i, link) {
    var $this = $(this),
        target = $this.attr('href'),
        map = {
          file: target,
          inline: $this.attr('data-ignore') ? false : true
        };

    linkedStyles.push(map);
    $this.remove();
  });

  return linkedStyles;

};

EmailBuilder.prototype.writeFile = function(fileDest, fileData, nextFile) {

  var grunt     = this.task.grunt;
  var writeData = this.getDoctype(fileData);

  grunt.log.writeln('Writing...'.cyan);
  grunt.file.write(fileDest, writeData);
  grunt.log.writeln('File ' + fileDest.cyan + ' created.');

  if (this.options.litmus) {
    this.litmus(writeData);
  }else{
    nextFile();
  }

};

EmailBuilder.prototype.litmus = function(emailData) {

  var litmus = new Litmus(this.options.litmus),
      date    = this.task.grunt.template.today('yyyy-mm-dd'),
      subject = this.options.litmus.subject;

  if( (subject === undefined) || (subject.trim().length === 0) ){
    subject = $title;
  }

  // If no subject or title then set to date
  if(subject.trim().length === 0){
    subject = date;
  }

  litmus.run(emailData, subject.trim());

};

EmailBuilder.registerWithGrunt = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask(EmailBuilder.taskName, EmailBuilder.taskDescription, function() {

    this.grunt = grunt;

    var task = new EmailBuilder(this);

    task.run(grunt);
  });
};

module.exports = EmailBuilder;<commit_msg>Using regex to find doctype instead of cheerio, removing global vars<commit_after>/* jshint -W030,-W117 */

/*
 * grunt-EmailBuilder
 * https://github.com/yargalot/Email-Builder
 *
 * Copyright (c) 2013 Steven Miller
 * Licensed under the MIT license.
 */

 // Required modules
var juice     = require('juice'),
    path      = require('path'),
    cheerio   = require('cheerio'),
    async     = require('async'),
    encode    = require('./entityEncode'),
    Litmus    = require('./litmus');

function EmailBuilder(task) {

  this.task     = task;
  this.options  = task.options(EmailBuilder.Defaults);
  this.basepath = process.cwd();
  this.done     = this.task.async();

}

EmailBuilder.taskName         = 'emailBuilder';
EmailBuilder.taskDescription  = 'Compile Files';
EmailBuilder.Defaults         = {};

EmailBuilder.prototype.run = function(grunt) {

  var _that = this;

  async.eachSeries(this.task.files, function(file, next) {

    var fileData  = grunt.file.read(file.src),
        reDoctype = /<!doctype.*?>/gi;

    _that.doctype = fileData.match(reDoctype);

    // Cheerio Init
    var $           = _that.$  = cheerio.load(fileData),
        $styleTags  = $('style'),
        $styleLinks = $('link');

    // Read Css Files
    var srcFiles    = _that.getLinkTags($styleLinks),
        embeddedCss = _that.getStyleTags($styleTags),
        externalCss = _that.getExternalCss(srcFiles, file.src),
        allCss      = embeddedCss + externalCss;

    // Get file output ready
    var output      = allCss ? juice.inlineContent($.html(), allCss) : $.html();

    // Encode special characters if option encodeSpecialChars is true
    if(_that.options.encodeSpecialChars === true) {
      output = encode.htmlEncode(output);
    }

    _that.writeFile(file.dest, output, next);

  }, function() {

    _that.done();

  });
};

EmailBuilder.prototype.getExternalCss = function(files, fileSource) {

  var externalCss = '',
      grunt       = this.task.grunt,
      $           = this.$;

  // Set to target file path to get css
  grunt.file.setBase(path.dirname(fileSource));

  files.forEach(function(srcFile) {
    var css = grunt.file.read(srcFile.file);

    if(srcFile.inline) {
      externalCss += css;
    } else {
      $('head').append('<style>' + css + '</style>');
    }
  });

  // Set cwd back to root folder
  grunt.file.setBase(this.basepath);

  return externalCss;

};

EmailBuilder.prototype.getStyleTags = function(styleTags) {

  var $   = this.$,
      css = '';

  styleTags.each(function(i, element){
    var $this = $(this);

    if(!$this.attr('data-ignore')) {
      css += $this.text();
      $this.remove();
    }
  });

  return css;

};

EmailBuilder.prototype.getLinkTags = function(styleLinks) {

  var $            = this.$,
      linkedStyles = [];

  styleLinks.each(function(i, link) {
    var $this  = $(this),
        target = $this.attr('href'),
        map = {
          file: target,
          inline: $this.attr('data-ignore') ? false : true
        };

    linkedStyles.push(map);
    $this.remove();
  });

  return linkedStyles;

};

// If doctype options is true, preserve doctype or add HTML5 doctype since jsdom removes it
EmailBuilder.prototype.addDoctype = function(output) {

  var doctyped = '',
      dt       = this.doctype;

  if ( this.options.doctype !== false ) {

    if ( dt !== null ) {
      doctyped = dt[0] + output;
    } else {
      doctyped = '<!DOCTYPE html>' + output;
    }

  }else{
    doctyped = output;
  }

  return doctyped;

};

EmailBuilder.prototype.writeFile = function(fileDest, fileData, nextFile) {

  var grunt     = this.task.grunt,
      writeData = this.addDoctype(fileData);

  grunt.log.writeln('Writing...'.cyan);
  grunt.file.write(fileDest, writeData);
  grunt.log.writeln('File ' + fileDest.cyan + ' created.');

  if (this.options.litmus) {
    this.litmus(writeData);
  }else{
    nextFile();
  }

};

EmailBuilder.prototype.litmus = function(emailData) {

  var litmus  = new Litmus(this.options.litmus),
      date    = this.task.grunt.template.today('yyyy-mm-dd'),
      subject = this.options.litmus.subject,
      $       = this.$,
      $title  = $('title').text().trim();

  if( (subject === undefined) || (subject.trim().length === 0) ){
    subject = $title;
  }

  // If no subject or title then set to date
  if(subject.trim().length === 0){
    subject = date;
  }

  litmus.run(emailData, subject.trim());

};

EmailBuilder.registerWithGrunt = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask(EmailBuilder.taskName, EmailBuilder.taskDescription, function() {

    this.grunt = grunt;

    var task = new EmailBuilder(this);

    task.run(grunt);
  });
};

module.exports = EmailBuilder;<|endoftext|>


<commit_before>'use strict';

var npmlog = require('npmlog')
  , path = require('path')
  , fs = require('fs')
  ;

var stderr_write = process.stderr.write;

if (process.env.VALUEPACK_DEBUG) npmlog.level = 'silly';

function formatDate (d) {
  return d.toDateString() +  ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds();
}

function enhance (level) {
  var origFn = npmlog[level];

  npmlog[level] = function () {
    var args = Array.prototype.slice.call(arguments);

    // '/lib/get-github-repos.js' becomes 'get-github-repos'
    args[0] = path.basename(args[0], '.js');
    return origFn.apply(this, args);
  };
}

[ 'error', 'warn', 'info', 'verbose', 'silly' ]
  .forEach(enhance);

module.exports = exports = npmlog;

function getFilestream (filename, count) {
  var ext = path.extname(filename);
  var numberedFilename = filename.slice(0, -ext.length) + '.' + count + ext;

    stderr_write('logfile: [' + numberedFilename + ']\n');
  return fs.createWriteStream(numberedFilename, { encoding: 'utf-8', flags: 'a' });
}

exports.writeTo = function (filename, writesToRollover) {
  writesToRollover = writesToRollover || 2000;
  var count = -1;
  var outlog, writes;

  var buf = '';

  function rollover () {
    writes = 0;
    count++;
    outlog = getFilestream(filename, count);
  }

  rollover();

  process.stderr.write = function (data) {

    buf += data;
    var parts = buf.split('\n');

    if (parts.length > 1) {
      var date = '\u001b[90m' + formatDate(new Date()) + ' \u001b[39m';
      outlog.write(date + parts[0] + '\n');
      buf = parts[1];
      writes++;
    }

    // logging to a huge file slows things down so we regularly roll over to the next one
    if (writes > writesToRollover) rollover();
  };
};

// Test
if (!module.parent) {
  var log = exports;
  var msgs = 0;
  log.writeTo(path.join(__dirname, '../logs', 'test.log'));

  log.info(__filename, 'message %d', msgs++);
}
<commit_msg>injecting timestamp into log<commit_after>'use strict';

var npmlog = require('npmlog')
  , path = require('path')
  , fs = require('fs')
  ;

var stderr_write = process.stderr.write;

if (process.env.VALUEPACK_DEBUG) npmlog.level = 'silly';

function formatDate (d) {
  return d.toDateString() +  ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds();
}

function enhance (level) {
  var origFn = npmlog[level];

  npmlog[level] = function () {
    var args = Array.prototype.slice.call(arguments);
    var date = '\u001b[90m' + formatDate(new Date()) + ' \u001b[39m';

    // '/lib/get-github-repos.js' becomes 'get-github-repos'
    args[0] = date + path.basename(args[0], '.js');
    return origFn.apply(this, args);
  };
}

[ 'error', 'warn', 'info', 'verbose', 'silly' ]
  .forEach(enhance);

module.exports = exports = npmlog;

function getFilestream (filename, count) {
  var ext = path.extname(filename);
  var numberedFilename = filename.slice(0, -ext.length) + '.' + count + ext;

    stderr_write('logfile: [' + numberedFilename + ']\n');
  return fs.createWriteStream(numberedFilename, { encoding: 'utf-8', flags: 'a' });
}

exports.writeTo = function (filename, writesToRollover) {
  writesToRollover = writesToRollover || 2000;
  var count = -1;
  var outlog, writes;

  var buf = '';

  function rollover () {
    writes = 0;
    count++;
    outlog = getFilestream(filename, count);
  }

  rollover();

  process.stderr.write = function (data) {

    buf += data;
    var parts = buf.split('\n');

    if (parts.length > 1) {
      var date = '\u001b[90m' + formatDate(new Date()) + ' \u001b[39m';
      outlog.write(date + parts[0] + '\n');
      buf = parts[1];
      writes++;
    }

    // logging to a huge file slows things down so we regularly roll over to the next one
    if (writes > writesToRollover) rollover();
  };
};

// Test
if (!module.parent) {
  var log = exports;
  var msgs = { count: 0, text: 'hello this is a very long text', othertext: 'hello this is another very long text'  }

  log.info(__filename, 'message', msgs);
}
<|endoftext|>


<commit_before>const { series, src, dest } = require('gulp');
const del = require('del');
const _ = require('lodash');
const jsonfile = require('jsonfile');
const path = require('path');
const argv = require('yargs').argv;
let srcPath;
let destPath;
const DELETE_KEY = 'marked_to_remove';

srcPath = argv.src || process.cwd();
destPath = argv.dest;
console.log('srcPath = ' + srcPath);
console.log('destPath = ' + destPath);

async function cleanForUpgrade() {
    if (srcPath && destPath) {
        return del([
            './*',
            './src/*',
            '!./src',
            '!./src/app',
            '!./proxy-config.json'
        ], { force: true, cwd: destPath });
    } else {
        return console.log("plese set the dest value to continue");

    }
}

async function copyForUpgrade() {
    if (srcPath && destPath) {
        return src(['./**/*', '!./upgrade-helper', '!./upgrade-helper/*'], { cwd: srcPath })
            .pipe(dest('./', { cwd: destPath, overwrite: false }));
    }
}

async function cleanForInstall() {
    if (srcPath && destPath) {
        return del([
            './*'
        ], { force: true, cwd: destPath });
    } else {
        console.log("plese set the dest value to continue");
        return;
    }
}

async function copyForInstall() {
    if (srcPath && destPath) {
        return src(['./**/*', '!./upgrade-helper', '!./upgrade-helper/*'], { cwd: srcPath })
            .pipe(dest('./', { cwd: destPath }));
    }
}

async function updateProxyConfig() {

    if (srcPath && destPath) {
        const srcFile = jsonfile.readFileSync(path.join(srcPath, '/proxy-config.json'));
        const destFile = jsonfile.readFileSync(path.join(destPath, '/proxy-config.json'));
        _.forEach(srcFile, function (value, key) {
            if (!(_.has(destFile, key))) {
                _.set(destFile, key, value)
            } else if (value['value'] == DELETE_KEY) {
                _.unset(destFile, key);
            }
        });
        jsonfile.writeFileSync(path.join(destPath, '/proxy-config.json'), destFile);
    }
}

async function updateConfig() {
    if (srcPath && destPath) {
        const srcFile = jsonfile.readFileSync(path.join(srcPath, '/src/app/config/config.json'));
        const destFile = jsonfile.readFileSync(path.join(destPath, '/src/app/config/config.json'));
        _.forEach(srcFile, function (value, key) {
            if (!(_.has(destFile, key))) {
                _.set(destFile, key, value)
            } else if (value['value'] == DELETE_KEY) {
                _.unset(destFile, key);
            }
        });
        jsonfile.writeFileSync(path.join(destPath, '/src/app/config/config.json'), destFile);
    }
}

async function updateLocale() {
    if (srcPath && destPath) {
        const srcFile = jsonfile.readFileSync(path.join(srcPath, '/src/app/locale/en.json'));
        const destFile = jsonfile.readFileSync(path.join(destPath, '/src/app/locale/en.json'));
        _.forEach(srcFile, function (rootValue, rootKey) {
            if (!(_.has(destFile, rootKey))) {
                _.set(destFile, rootKey, rootValue);
            } else if (rootValue == DELETE_KEY) {
                _.unset(destFile, rootKey);
            }
            else {
                _.forEach(rootValue, function (levelOneValue, levelOneKey) {
                    if (!(_.has(destFile[rootKey], levelOneKey))) {
                        _.set(destFile[rootKey], levelOneKey, levelOneValue);
                    } else if (levelOneValue == DELETE_KEY) {
                        _.unset(destFile[rootKey], levelOneKey);
                    }
                    else {
                        _.forEach(levelOneValue, function (levelTwoValue, levelTwoKey) {
                            if (!(_.has(destFile[rootKey][levelOneKey], levelTwoKey))) {
                                _.set(destFile[rootKey][levelOneKey], levelTwoKey, levelTwoValue);
                            } else if (levelTwoValue == DELETE_KEY) {
                                _.unset(destFile[rootKey][levelOneKey], levelTwoKey);
                            }
                            else {
                                //this is deep enough for now
                            }
                        });
                    }
                });
            }
        });
        jsonfile.writeFileSync(path.join(destPath, '/src/app/locale/en.json'), destFile);
    }
}

async function updateResources() {
    if (srcPath && destPath) {
        return src(['./src/app/resources/*'], { cwd: srcPath })
        .pipe(dest('./src/app/resources/', { cwd: destPath, overwrite: false }));
    }
}

exports.upgrade = series(cleanForUpgrade, copyForUpgrade, updateProxyConfig, updateConfig, updateLocale, updateResources);
exports.install = series(cleanForInstall, copyForInstall);<commit_msg>MOB-504 : improve upgrade procedure<commit_after>const { series, src, dest } = require('gulp');
const del = require('del');
const _ = require('lodash');
const jsonfile = require('jsonfile');
const path = require('path');
const argv = require('yargs').argv;
let srcPath;
let destPath;
const DELETE_KEY = 'marked_to_remove';

srcPath = argv.src || process.cwd();
destPath = argv.dest;
console.log('srcPath = ' + srcPath);
console.log('destPath = ' + destPath);

async function cleanForUpgrade() {
    if (srcPath && destPath) {
        return del([
            './*',
            './src/*',
            '!./src',
            '!./src/app',
            '!./proxy-config.json'
        ], { force: true, cwd: destPath });
    } else {
        return console.log("please set the dest value to continue");

    }
}

async function copyForUpgrade() {
    if (srcPath && destPath) {
        return src(['./**/*', '!./upgrade-helper', '!./upgrade-helper/**/*'], { cwd: srcPath })
            .pipe(dest('./', { cwd: destPath, overwrite: false }));
    }
}

async function cleanForInstall() {
    if (srcPath && destPath) {
        return del([
            './*'
        ], { force: true, cwd: destPath });
    } else {
        console.log("please set the dest value to continue");
        return;
    }
}

async function copyForInstall() {
    if (srcPath && destPath) {
        return src(['./**/*', '!./upgrade-helper', '!./upgrade-helper/**/*'], { cwd: srcPath })
            .pipe(dest('./', { cwd: destPath }));
    }
}

async function updateProxyConfig() {

    if (srcPath && destPath) {
        const srcFile = jsonfile.readFileSync(path.join(srcPath, '/proxy-config.json'));
        const destFile = jsonfile.readFileSync(path.join(destPath, '/proxy-config.json'));
        _.forEach(srcFile, function (value, key) {
            if (value != DELETE_KEY && !(_.has(destFile, key))) {
                _.set(destFile, key, value)
            } else if (value == DELETE_KEY) {
                _.unset(destFile, key);
            }
        });
        jsonfile.writeFileSync(path.join(destPath, '/proxy-config.json'), destFile, { spaces: 2, EOL: '\r\n' });
    }
}

async function updateConfig() {
    if (srcPath && destPath) {
        const srcFile = jsonfile.readFileSync(path.join(srcPath, '/src/app/config/config.json'));
        const destFile = jsonfile.readFileSync(path.join(destPath, '/src/app/config/config.json'));
        _.forEach(srcFile, function (value, key) {
            if (value != DELETE_KEY && !(_.has(destFile, key))) {
                _.set(destFile, key, value)
            } else if (value == DELETE_KEY) {
                _.unset(destFile, key);
            }
        });
        jsonfile.writeFileSync(path.join(destPath, '/src/app/config/config.json'), destFile, { spaces: 2, EOL: '\r\n' });
    }
}

async function updateLocale() {
    if (srcPath && destPath) {
        const srcFile = jsonfile.readFileSync(path.join(srcPath, '/src/app/locale/en.json'));
        const destFile = jsonfile.readFileSync(path.join(destPath, '/src/app/locale/en.json'));
        _.forEach(srcFile, function (rootValue, rootKey) {
            if (rootValue != DELETE_KEY && !(_.has(destFile, rootKey))) {
                _.set(destFile, rootKey, rootValue);
            } else if (rootValue == DELETE_KEY) {
                _.unset(destFile, rootKey);
            }
            else {
                _.forEach(rootValue, function (levelOneValue, levelOneKey) {
                    if (levelOneValue != DELETE_KEY && !(_.has(destFile[rootKey], levelOneKey))) {
                        _.set(destFile[rootKey], levelOneKey, levelOneValue);
                    } else if (levelOneValue == DELETE_KEY) {
                        _.unset(destFile[rootKey], levelOneKey);
                    }
                    else {
                        _.forEach(levelOneValue, function (levelTwoValue, levelTwoKey) {
                            if (levelTwoValue != DELETE_KEY && !(_.has(destFile[rootKey][levelOneKey], levelTwoKey))) {
                                _.set(destFile[rootKey][levelOneKey], levelTwoKey, levelTwoValue);
                            } else if (levelTwoValue == DELETE_KEY) {
                                _.unset(destFile[rootKey][levelOneKey], levelTwoKey);
                            }
                            else {
                                //this is deep enough for now
                            }
                        });
                    }
                });
            }
        });
        jsonfile.writeFileSync(path.join(destPath, '/src/app/locale/en.json'), destFile, { spaces: 2, EOL: '\r\n' });
    }
}

async function updateResources() {
    if (srcPath && destPath) {
        return src(['./src/app/resources/*'], { cwd: srcPath })
        .pipe(dest('./src/app/resources/', { cwd: destPath, overwrite: false }));
    }
}

exports.upgrade = series(cleanForUpgrade, copyForUpgrade, updateProxyConfig, updateConfig, updateLocale, updateResources);
exports.install = series(cleanForInstall, copyForInstall);<|endoftext|>


<commit_before>var crypto = require('crypto')

var HANDLER = process.argv[2] || process.env.AWS_LAMBDA_FUNCTION_HANDLER || 'index.handler'
var EVENT_BODY = process.argv[3] || process.env.AWS_LAMBDA_EVENT_BODY || '{}'

var FN_NAME = process.env.AWS_LAMBDA_FUNCTION_NAME || 'test'
var VERSION = process.env.AWS_LAMBDA_FUNCTION_VERSION || '$LATEST'
var MEM_SIZE = process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE || 1536
var TIMEOUT = process.env.AWS_LAMBDA_FUNCTION_TIMEOUT || 300
var REGION = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || 'us-east-1'
var ACCOUNT_ID = process.env.AWS_ACCOUNT_ID || randomAccountId()
var ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID || 'SOME_ACCESS_KEY_ID'
var SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY || 'SOME_SECRET_ACCESS_KEY'
var SESSION_TOKEN = process.env.AWS_SESSION_TOKEN

function consoleLog(str) {
  process.stderr.write(formatConsole(str))
}

function systemLog(str) {
  process.stderr.write(formatSystem(str) + '\n')
}

function systemErr(str) {
  process.stderr.write(formatErr(str) + '\n')
}

function handleResult(resultStr) {
  process.stdout.write(resultStr)
}

// Don't think this can be done in the Docker image
process.umask(2)

process.env.AWS_LAMBDA_FUNCTION_NAME = FN_NAME
process.env.AWS_LAMBDA_FUNCTION_VERSION = VERSION
process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE = MEM_SIZE
process.env.AWS_LAMBDA_LOG_GROUP_NAME = '/aws/lambda/' + FN_NAME
process.env.AWS_LAMBDA_LOG_STREAM_NAME = new Date().toISOString().slice(0, 10).replace(/-/g, '/') +
  '/[' + VERSION + ']' + crypto.randomBytes(16).toString('hex')
process.env.AWS_REGION = REGION
process.env.AWS_DEFAULT_REGION = REGION

var OPTIONS = {
  initInvokeId: uuid(),
  invokeId: uuid(),
  handler: HANDLER,
  suppressInit: true,
  credentials: {
    key: ACCESS_KEY_ID,
    secret: SECRET_ACCESS_KEY,
    session: SESSION_TOKEN,
  },
  eventBody: EVENT_BODY,
  contextObjects: {
    // clientContext: '{}',
    // cognitoIdentityId: undefined,
    // cognitoPoolId: undefined,
  },
  invokedFunctionArn: arn(REGION, ACCOUNT_ID, FN_NAME),
}

// Some weird spelling error in the source?
OPTIONS.invokeid = OPTIONS.invokeId

var invoked = false
var errored = false
var start = null

module.exports = {
  initRuntime: function() { return OPTIONS },
  waitForInvoke: function(fn) {
    if (invoked) return
    systemLog('START RequestId: ' + OPTIONS.invokeId + ' Version: ' + VERSION)
    start = process.hrtime()
    invoked = true
    fn(OPTIONS)
  },
  reportRunning: function(invokeId) {}, // eslint-disable-line no-unused-vars
  reportDone: function(invokeId, errType, resultStr) {
    if (!invoked) return
    var diffMs = hrTimeMs(process.hrtime(start))
    var billedMs = Math.min(100 * (Math.floor(diffMs / 100) + 1), TIMEOUT * 1000)
    systemLog('END RequestId: ' + invokeId)
    systemLog([
      'REPORT RequestId: ' + invokeId,
      'Duration: ' + diffMs.toFixed(2) + ' ms',
      'Billed Duration: ' + billedMs + ' ms',
      'Memory Size: ' + MEM_SIZE + ' MB',
      'Max Memory Used: ' + Math.round(process.memoryUsage().rss / (1024 * 1024)) + ' MB',
      '',
    ].join('\t'))
    if (typeof resultStr == 'string') {
      handleResult(resultStr)
    }
    process.exit(errored || errType ? 1 : 0)
  },
  reportFault: function(invokeId, msg, errName, errStack) {
    errored = true
    systemErr(msg + (errName ? ': ' + errName : ''))
    if (errStack) systemErr(errStack)
  },
  reportUserInitStart: function() {},
  reportUserInitEnd: function() {},
  reportUserInvokeStart: function() {},
  reportUserInvokeEnd: function() {},
  reportException: function() {},
  getRemainingTime: function() {
    return (TIMEOUT * 1000) - Math.floor(hrTimeMs(process.hrtime(start)))
  },
  sendConsoleLogs: consoleLog,
  maxLoggerErrorSize: 256 * 1024,
}

function formatConsole(str) {
  return str.replace(/^[0-9TZ:\.\-]+\t[0-9a-f\-]+\t/, '\033[34m$&\u001b[0m')
}

function formatSystem(str) {
  return '\033[32m' + str + '\033[0m'
}

function formatErr(str) {
  return '\033[31m' + str + '\033[0m'
}

function hrTimeMs(hrtime) {
  return (hrtime[0] * 1e9 + hrtime[1]) / 1e6
}

// Approximates the look of a v1 UUID
function uuid() {
  return crypto.randomBytes(4).toString('hex') + '-' +
    crypto.randomBytes(2).toString('hex') + '-' +
    crypto.randomBytes(2).toString('hex').replace(/^./, '1') + '-' +
    crypto.randomBytes(2).toString('hex') + '-' +
    crypto.randomBytes(6).toString('hex')
}

function randomAccountId() {
  return String(0x100000000 * Math.random())
}

function arn(region, accountId, fnName) {
  return 'arn:aws:lambda:' + region + ':' + accountId.replace(/[^\d]/g, '') + ':function:' + fnName
}

<commit_msg>Wait for stdout flush in before exiting in nodejs 4.3<commit_after>var crypto = require('crypto')

var HANDLER = process.argv[2] || process.env.AWS_LAMBDA_FUNCTION_HANDLER || 'index.handler'
var EVENT_BODY = process.argv[3] || process.env.AWS_LAMBDA_EVENT_BODY || '{}'

var FN_NAME = process.env.AWS_LAMBDA_FUNCTION_NAME || 'test'
var VERSION = process.env.AWS_LAMBDA_FUNCTION_VERSION || '$LATEST'
var MEM_SIZE = process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE || 1536
var TIMEOUT = process.env.AWS_LAMBDA_FUNCTION_TIMEOUT || 300
var REGION = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || 'us-east-1'
var ACCOUNT_ID = process.env.AWS_ACCOUNT_ID || randomAccountId()
var ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID || 'SOME_ACCESS_KEY_ID'
var SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY || 'SOME_SECRET_ACCESS_KEY'
var SESSION_TOKEN = process.env.AWS_SESSION_TOKEN

function consoleLog(str) {
  process.stderr.write(formatConsole(str))
}

function systemLog(str) {
  process.stderr.write(formatSystem(str) + '\n')
}

function systemErr(str) {
  process.stderr.write(formatErr(str) + '\n')
}

function handleResult(resultStr, cb) {
  if (!process.stdout.write(resultStr)) {
    process.stdout.once('drain', cb)
  } else {
    process.nextTick(cb)
  }
}

// Don't think this can be done in the Docker image
process.umask(2)

process.env.AWS_LAMBDA_FUNCTION_NAME = FN_NAME
process.env.AWS_LAMBDA_FUNCTION_VERSION = VERSION
process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE = MEM_SIZE
process.env.AWS_LAMBDA_LOG_GROUP_NAME = '/aws/lambda/' + FN_NAME
process.env.AWS_LAMBDA_LOG_STREAM_NAME = new Date().toISOString().slice(0, 10).replace(/-/g, '/') +
  '/[' + VERSION + ']' + crypto.randomBytes(16).toString('hex')
process.env.AWS_REGION = REGION
process.env.AWS_DEFAULT_REGION = REGION

var OPTIONS = {
  initInvokeId: uuid(),
  invokeId: uuid(),
  handler: HANDLER,
  suppressInit: true,
  credentials: {
    key: ACCESS_KEY_ID,
    secret: SECRET_ACCESS_KEY,
    session: SESSION_TOKEN,
  },
  eventBody: EVENT_BODY,
  contextObjects: {
    // clientContext: '{}',
    // cognitoIdentityId: undefined,
    // cognitoPoolId: undefined,
  },
  invokedFunctionArn: arn(REGION, ACCOUNT_ID, FN_NAME),
}

// Some weird spelling error in the source?
OPTIONS.invokeid = OPTIONS.invokeId

var invoked = false
var errored = false
var start = null

module.exports = {
  initRuntime: function() { return OPTIONS },
  waitForInvoke: function(fn) {
    if (invoked) return
    systemLog('START RequestId: ' + OPTIONS.invokeId + ' Version: ' + VERSION)
    start = process.hrtime()
    invoked = true
    fn(OPTIONS)
  },
  reportRunning: function(invokeId) {}, // eslint-disable-line no-unused-vars
  reportDone: function(invokeId, errType, resultStr) {
    if (!invoked) return
    var diffMs = hrTimeMs(process.hrtime(start))
    var billedMs = Math.min(100 * (Math.floor(diffMs / 100) + 1), TIMEOUT * 1000)
    systemLog('END RequestId: ' + invokeId)
    systemLog([
      'REPORT RequestId: ' + invokeId,
      'Duration: ' + diffMs.toFixed(2) + ' ms',
      'Billed Duration: ' + billedMs + ' ms',
      'Memory Size: ' + MEM_SIZE + ' MB',
      'Max Memory Used: ' + Math.round(process.memoryUsage().rss / (1024 * 1024)) + ' MB',
      '',
    ].join('\t'))

    var exitCode = errored || errType ? 1 : 0
    if (typeof resultStr == 'string') {
      handleResult(resultStr, function() { process.exit(exitCode) })
    } else {
      process.exit(exitCode)
    }
  },
  reportFault: function(invokeId, msg, errName, errStack) {
    errored = true
    systemErr(msg + (errName ? ': ' + errName : ''))
    if (errStack) systemErr(errStack)
  },
  reportUserInitStart: function() {},
  reportUserInitEnd: function() {},
  reportUserInvokeStart: function() {},
  reportUserInvokeEnd: function() {},
  reportException: function() {},
  getRemainingTime: function() {
    return (TIMEOUT * 1000) - Math.floor(hrTimeMs(process.hrtime(start)))
  },
  sendConsoleLogs: consoleLog,
  maxLoggerErrorSize: 256 * 1024,
}

function formatConsole(str) {
  return str.replace(/^[0-9TZ:\.\-]+\t[0-9a-f\-]+\t/, '\033[34m$&\u001b[0m')
}

function formatSystem(str) {
  return '\033[32m' + str + '\033[0m'
}

function formatErr(str) {
  return '\033[31m' + str + '\033[0m'
}

function hrTimeMs(hrtime) {
  return (hrtime[0] * 1e9 + hrtime[1]) / 1e6
}

// Approximates the look of a v1 UUID
function uuid() {
  return crypto.randomBytes(4).toString('hex') + '-' +
    crypto.randomBytes(2).toString('hex') + '-' +
    crypto.randomBytes(2).toString('hex').replace(/^./, '1') + '-' +
    crypto.randomBytes(2).toString('hex') + '-' +
    crypto.randomBytes(6).toString('hex')
}

function randomAccountId() {
  return String(0x100000000 * Math.random())
}

function arn(region, accountId, fnName) {
  return 'arn:aws:lambda:' + region + ':' + accountId.replace(/[^\d]/g, '') + ':function:' + fnName
}
<|endoftext|>


<commit_before>/*
 * grunt-urturn-component
 * https://github.com/urturn/grunt-urturn-component
 *
 * Copyright (c) 2013 Olivier Amblet
 * Licensed under the MIT license.
 */

'use strict';

var Component = require('../component.js');

var bower = require("bower");
var async = require("async");
var path = require('path');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('urturn_component', 'Manage urturn component.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      bower: false,
      manifest: false,
      install: false
    });
    var done = this.async();
    var bowerInstall = function(callback) {
      if(options.bower){
        grunt.log.write("Install bower components: ");
        bower.commands.install()
          .on('error', function(error){
            console.log('an error occured');
            callback(error);
          })
          .on('end', function(){
            grunt.log.writeln("installed");
            callback(null);
          });
      } else {
        callback();
      }
    };
    var generateManifest = function(callback) {
      if(options.manifest) {
        grunt.log.write("Create manifest file: ");
        var manifest = options.manifest;
        var base = grunt.file.readJSON(bower.config.json);
        var json = {};
        json.name = base.name;
        json.version = base.version;
        json.dependencies = manifest.dependencies || base.dependencies;
        json.includes = manifest.includes || [];
        json.main = manifest.main;
        json.assets = manifest.assets;
        grunt.file.write('component.urturn.json', JSON.stringify(json, null, 2));
        grunt.log.writeln("component.urturn.json written");
        callback();
      } else {
        callback();
      }
    };
    var urturnInstall = function(callback) {
      if(options.install) {
        grunt.log.write("Install urturn component: ");
        var dest = options.install.dest || 'lib';
        var info = grunt.file.readJSON('component.urturn.json');
        info.basedir = '.';
        var component = Component.fromOptions(info);

        Component.list.forEach(function(comp){
          var files;
          if(comp.includedIn){
            comp.assets.forEach(function(f){
              grunt.file.copy( path.join(comp.basedir, f), path.join(dest, comp.name, f));
            });
          } else {
            comp.files().forEach(function(f){
              grunt.file.copy( path.join(comp.basedir, f), path.join(dest, comp.name, f));
            });
          }
        });
        grunt.log.writeln('installed');
        callback();
      } else {
        callback();
      }
    };

    async.series([bowerInstall, generateManifest, urturnInstall], done);
  });
};
<commit_msg>Now a multi task.<commit_after>/*
 * grunt-urturn-component
 * https://github.com/urturn/grunt-urturn-component
 *
 * Copyright (c) 2013 Olivier Amblet
 * Licensed under the MIT license.
 */

'use strict';

var Component = require('../component.js');

var bower = require("bower");
var async = require("async");
var path = require('path');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('urturn_component', 'Manage urturn component.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({}),
        bowerOpts = this.data.bower || false,
        manifestOpts = this.data.manifest || false,
        installOpts = this.data.install || false;

    var done = this.async();
    var bowerInstall = function(callback) {
      if(bowerOpts){
        grunt.log.write("Install bower components: ");
        bower.commands.install()
          .on('error', function(error){
            console.log('an error occured');
            callback(error);
          })
          .on('end', function(){
            grunt.log.writeln("installed");
            callback(null);
          });
      } else {
        callback();
      }
    };
    var generateManifest = function(callback) {
      if(manifestOpts) {
        grunt.log.write("Create manifest file: ");
        var manifest = manifestOpts;
        var base = grunt.file.readJSON(bower.config.json);
        var json = {};
        json.name = base.name;
        json.version = base.version;
        json.dependencies = manifest.dependencies || base.dependencies;
        json.includes = manifest.includes || [];
        json.main = manifest.main;
        json.assets = manifest.assets;
        grunt.file.write('component.urturn.json', JSON.stringify(json, null, 2));
        grunt.log.writeln("component.urturn.json written");
        callback();
      } else {
        callback();
      }
    };
    var urturnInstall = function(callback) {
      if(installOpts) {
        grunt.log.write("Install urturn component: ");
        var dest = installOpts.dest || 'lib';
        var info = grunt.file.readJSON('component.urturn.json');
        info.basedir = '.';
        var component = Component.fromOptions(info);

        Component.list.forEach(function(comp){
          var files;
          if(comp.includedIn){
            comp.assets.forEach(function(f){
              grunt.file.copy( path.join(comp.basedir, f), path.join(dest, comp.name, f));
            });
          } else {
            comp.files().forEach(function(f){
              grunt.file.copy( path.join(comp.basedir, f), path.join(dest, comp.name, f));
            });
          }
        });
        grunt.log.writeln('installed');
        callback();
      } else {
        callback();
      }
    };

    async.series([bowerInstall, generateManifest, urturnInstall], done);
  });
};
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var isObject = function (obj) {
    return typeof obj !== 'undefined' && obj.toString() == "[object Object]";
  };

  var isFunction = function (func) {
    return typeof func === "function";
  };

  var states = {
    PENDING: 0,
    FULFILLED: 1,
    REJECTED: 2
  };

  var u = undefined;

  function asap(cb) {
    setTimeout(cb, 1);
  }

  var vPromise = function (fn) {
    this.value = undefined;
    this._state = states.PENDING;
    this.chain = [];
    var prms = this;

    try {
      fn(function (val) {
        prms.resolve(val);
      }, function (reason) {
        prms.reject(reason);
      });
    } catch (exc) {
      prms.reject(exc);
    }

    this.then = function (onFulfilled, onRejected) {
      var prms = this;

      return new vPromise(function (resolve, reject) {
        prms.chain.push({
          onFulfilled: onFulfilled,
          resolve: resolve,
          onRejected: onRejected,
          reject: reject
        });

        prms.done();
      });
    };
    return this;
  };

  vPromise.prototype.done = function () {
    var prms = this;

    asap(function () {
      if (prms._state == states.PENDING) {
        return;
      }

      var chainLength = prms.chain.length;
      if (chainLength == 0) { // nothing to do
        return;
      }

      var ii;
      var next;
      var onFulfilled, resolve, onRejected, reject;
      for (ii = 0; ii < chainLength; ii++) {
        next = prms.chain.shift();

        onFulfilled = next.onFulfilled;
        resolve = next.resolve;
        onRejected = next.onRejected;
        reject = next.reject;

        if (prms._state === states.FULFILLED) {
          if (isFunction(onFulfilled)) {
            resolve(onFulfilled.call(u, prms.value));
          } else {
            resolve(prms.value);
          }
        }

        if (prms._state == states.REJECTED) {
          if (isFunction(onRejected)) {
            reject(onRejected.call(u, prms.value));
          } else {
            reject(prms.value);
          }
        }
      }
      prms.chains = []; // done with chains
    });
  };

  vPromise.prototype.resolve = function (x) {
    var prms = this;

    if (prms === x) {
      throw new TypeError("promise and x can not be same object");
    }
    if (isFunction(x) || isObject(x)) {
      var then = x.then; // TODO 2.3.3.2
    }

    if (isFunction(then)) {
      var called = false;
      then.call(x, function (y) {
        if (called) {
          return;
        }
        called = true;
        prms.resolve(prms, y);
      }, function (r) {
        if (called) {
          return;
        }
        called = true;
        prms.reject(prms, r);
      });
    }

    prms._state = states.FULFILLED;
    prms.value = x;
    prms.done();
  };

  vPromise.prototype.reject = function (reason) {
    var prms = this;

    prms._state = states.REJECTED;
    prms.value = reason;
    prms.done();
  };

  vPromise.resolve = function (value) {
    return new vPromise(function (resolve) {
      resolve(value);
    });
  };

  vPromise.reject = function (reason) {
    return new vPromise(function (resolve, reject) {
      reject(reason);
    });
  };

  if (typeof module != 'undefined') {
    module.exports = vPromise;
  }

}());
<commit_msg>Get some of 2.2.6 to pass.<commit_after>(function () {
  'use strict';

  var isObject = function (obj) {
    return typeof obj !== 'undefined' && obj.toString() == "[object Object]";
  };

  var isFunction = function (func) {
    return typeof func === "function";
  };

  var states = {
    PENDING: 0,
    FULFILLED: 1,
    REJECTED: 2
  };

  var u = undefined;

  function asap(cb) {
    setTimeout(cb, 1);
  }

  var vPromise = function (fn) {
    this.value = undefined;
    this._state = states.PENDING;
    this.chain = [];
    var prms = this;

    try {
      fn(function (val) {
        prms.resolve(val);
      }, function (reason) {
        prms.reject(reason);
      });
    } catch (exc) {
      prms.reject(exc);
    }

    this.then = function (onFulfilled, onRejected) {
      var prms = this;

      return new vPromise(function (resolve, reject) {
        prms.chain.push({
          onFulfilled: onFulfilled,
          resolve: resolve,
          onRejected: onRejected,
          reject: reject
        });

        prms.done();
      });
    };
    return this;
  };

  vPromise.prototype.done = function () {
    var prms = this;

    asap(function () {
      if (prms._state == states.PENDING) {
        return;
      }

      var chainLength = prms.chain.length;
      if (chainLength == 0) { // nothing to do
        return;
      }

      var ii;
      var next;
      var onFulfilled, resolve, onRejected, reject;
      for (ii = 0; ii < chainLength; ii++) {
        next = prms.chain.shift();

        onFulfilled = next.onFulfilled;
        resolve = next.resolve;
        onRejected = next.onRejected;
        reject = next.reject;
        try {
          if (prms._state === states.FULFILLED) {
            if (isFunction(onFulfilled)) {
              resolve(onFulfilled.call(u, prms.value));
            } else {
              resolve(prms.value);
            }
          }

          if (prms._state === states.REJECTED) {
            if (isFunction(onRejected)) {
              reject(onRejected.call(u, prms.value));
            } else {
              reject(prms.value);
            }
          }
        } catch (reason) {
          reject(reason);
        }
      }
    });
  };

  vPromise.prototype.resolve = function (x) {
    var prms = this;

    if (prms === x) {
      throw new TypeError("promise and x can not be same object");
    }
    if (isFunction(x) || isObject(x)) {
      var then = x.then; // TODO 2.3.3.2
    }

    if (isFunction(then)) {
      var called = false;
      try {
        then.call(x, function (y) {
          if (called) {
            return;
          }
          called = true;
          prms.resolve(prms, y);
        }, function (r) {
          if (called) {
            return;
          }
          called = true;
          prms.reject(prms, r);
        });
        return;
      } catch (reason) {
        if (called) {
          return;
        }
        called = true;
        prms.reject(reason);
        return;
      }
    }

    prms._state = states.FULFILLED;
    prms.value = x;
    prms.done();
  };

  vPromise.prototype.reject = function (reason) {
    var prms = this;

    prms._state = states.REJECTED;
    prms.value = reason;
    prms.done();
  };

  vPromise.resolve = function (value) {
    return new vPromise(function (resolve) {
      resolve(value);
    });
  };

  vPromise.reject = function (reason) {
    return new vPromise(function (resolve, reject) {
      reject(reason);
    });
  };

  if (typeof module != 'undefined') {
    module.exports = vPromise;
  }

}());
<|endoftext|>


<commit_before>// ==UserScript==
// @name       Ingress OPR Logger
// @namespace  https://github.com/finntaur/monkey
// @version    0.201705231750
// @description  Logs coordinates and names of portal candidates.
// @include    https://opr.ingress.com/recon
// @include    http://opr.ingress.com/recon
// @match      https://opr.ingress.com/recon
// @match      http://opr.ingress.com/recon
// @grant      none
// @copyright  2017+, Finntaur
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==

function wrapper() {
    if ( typeof window.plugin !== 'function' ) window.plugin = function() {};

    window.plugin.logger = function() {};

    // SETTINGS
    // ------------------------------------------------------------------------

    window.plugin.logger.LOG_NUMBER_OF_STARS = true;
    window.plugin.logger.DEBUG = false;
    window.plugin.logger.AUTOLOAD_ALL_IMAGES = false;
    window.plugin.logger.MARKER_COLOR = "#55efec";

    // ------------------------------------------------------------------------
    // END SETTINGS

    // Extend standard String object with a hashCode method.
    String.prototype.hashCode = function() {
        var hash = 0;
        if ( this.length === 0 ) return hash;
        for ( var i = 0; i < this.length; i++ ) {
            char = this.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    };

    window.plugin.logger.currentId = null;
    window.plugin.logger.imgEl = null;
    window.plugin.logger.locationEl = null;
    window.plugin.logger.titleEl = null;

    // Find the location elements that hold the gmaps uri and the title.
    window.plugin.logger.findContainers = function() {

        var alist = $("#descriptionDiv").find("a");
        var titleRegexp    = /^https?:\/\/www\.google\.[a-z]+\/search/i;
        var locationRegexp = /^https?:\/\/maps\.google\./i;
        alist.each(function(i) {
            var href = $(this).attr("href");
            if ( locationRegexp.test(href) ) {
                if ( window.plugin.logger.DEBUG ) console.log("Location element found.");
                window.plugin.logger.locationEl = $(this);
            }
            if ( titleRegexp.test(href) ) {
                if ( window.plugin.logger.DEBUG ) console.log("Title element found.");
                window.plugin.logger.titleEl = $(this);
            }
        });
        window.plugin.logger.imgEl = $("div.ingress-background img")[0];

    };

    // How many stars are currently being given to the candidate.
    window.plugin.logger.updateStars = function(id) {

        if ( null === id || false === window.plugin.logger.LOG_NUMBER_OF_STARS ) return;
        var stars = $("button[ng-model='answerCtrl.formData.quality']").find(".gold").length;
        var item = JSON.parse(localStorage.getItem(id));
        item.stars = stars;
        var str = JSON.stringify(item);
        if ( window.plugin.logger.DEBUG ) console.log("Updating: " + str);
        localStorage.setItem(id, str);

    };

    // Extract portal candidate details.
    window.plugin.logger.extractDetails = function() {

        var details = {};
        details.id = 0;
        details.image = null;
        details.title = null;
        details.latitude = null;
        details.longitude = null;

        if ( null === window.plugin.logger.locationEl ||
            null === window.plugin.logger.titleEl ||
            null === window.plugin.logger.imgEl )
            window.plugin.logger.findContainers();

        try {
            details.title = window.plugin.logger.titleEl.text().trim();
            details.image = window.plugin.logger.imgEl.src;
            details.id = details.image.split("/").slice(-1)[0].hashCode();

            var href = window.plugin.logger.locationEl.attr("href");
            // if ( window.plugin.logger.DEBUG ) console.log(href);
            details.latitude = href.split("@")[1].split(",")[0];
            details.longitude = href.split("@")[1].split(",")[1];

            if ( null === details.latitude || "" === details.latitude ||
                null === details.longitude || "" === details.longitude ||
                null === details.title || "" === details.title ||
                null === details.image || "" === details.image ||
                0 === details.id ) throw "Portal data unavailable.";

        } catch(err) {
            if ( window.plugin.logger.DEBUG ) console.log(err);
            details = null;
        }

        if ( window.plugin.logger.DEBUG ) console.log(details);
        return details;

    };

    // Display all logged entries.
    window.plugin.logger.display = function() {

        $("#logModal")[0].style.display = "block";
        var table = $("#logModalContent");
        table.html('
Photo	' +
             ( window.plugin.logger.LOG_NUMBER_OF_STARS ? '	' : '' ) +
             'Title	Longitude	Latitude
'
        );

        var iitcExport = "";
        var items = localStorage.length;
        for ( var i = 0; i < items; i++ ) {
            var item = JSON.parse(localStorage.getItem(localStorage.key(i)));
            if ( window.plugin.logger.DEBUG ) console.log(item);
            var image = '';
            } else {
                image += 'src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" ' +
                    'onclick="this.src = \'' + item.image + '\';"' + '>';
            }
            table.append(
                '
' +
                '' + image + '	' +
                ( window.plugin.logger.LOG_NUMBER_OF_STARS ? '' + ( item.stars || 0 ) + '	' : '' ) +
                '' + item.title + '	' +
                '' + item.longitude + '	' +
                '' + item.latitude + '	' +
                '
'
            );
            iitcExport += '{"type":"marker","latLng":{"lat":' +
                item.latitude + ',"lng":' +
                item.longitude + '},"color":"' +
                window.plugin.logger.MARKER_COLOR + '"},';
        }

        $("#logModalExport").html("[" + iitcExport.slice(0, -1) + "]");

    };

    // Setup this plugin.
    window.plugin.logger.setup = function() {

        // Add means to access logs from the UI.
        $("ul.nav").append('
Log
');
        $("#openLog").click(window.plugin.logger.display);
        $("head").append(
            ''
        );
        $("body").append(
            '
' +
            '
' +
            '×' +
            'Your OPR Log (' + localStorage.length + ' entries)' +
            '
' +
            '
' +
            'IITC Export:
' +
            '<textarea readonly id="logModalExport" style="margin: 16px 0px 0px 0px; padding: 4px; border: 2px solid #55efec; background: black; color: white; width: 100%; height: 50px;"></textarea>' +
            '
' +
            '

' +
            '
'
        );
        $("#logModalCloseButton").click(function() { $("#logModal")[0].style.display = "none"; });

        // Try to extract portal candidate details on every click until successful.
        $("body").click(function() {
            if ( null === window.plugin.logger.currentId ) {
                var details = window.plugin.logger.extractDetails();
                if ( null === details ) {
                    console.log("Could not extract and record portal data.");
                } else {
                    var id = details.id;
                    delete details.id;
                    if ( null === localStorage.getItem(id) ) {
                        var str = JSON.stringify(details);
                        if ( window.plugin.logger.DEBUG ) console.log("Appending: " + str);
                        localStorage.setItem(id, str);
                    } else {
                        if ( window.plugin.logger.DEBUG ) console.log("Object " + id + " already exists in OPR log.");
                    }
                    window.plugin.logger.currentId = id;
                }
            } else {
                if ( window.plugin.logger.DEBUG ) console.log("This candidate has already been logged.");
            }
            window.plugin.logger.updateStars(window.plugin.logger.currentId);
        });

    };

} // wrapper end
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);

window.plugin.logger.setup();
if ( window.plugin.logger.DEBUG ) console.log("Logger initialized.");
<commit_msg>Update ingress-opr-logger.user.js<commit_after>// ==UserScript==
// @name       Ingress OPR Logger
// @namespace  https://github.com/finntaur/monkey
// @version    0.201705241715
// @description  Logs details of handled portal candidates.
// @include    https://opr.ingress.com/recon
// @include    http://opr.ingress.com/recon
// @match      https://opr.ingress.com/recon
// @match      http://opr.ingress.com/recon
// @include    https://opr.ingress.com/
// @include    http://opr.ingress.com/
// @match      https://opr.ingress.com/
// @match      http://opr.ingress.com/
// @grant      none
// @copyright  2017+, Finntaur
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==

function wrapper() {
    if ( typeof window.plugin !== 'function' ) window.plugin = function() {};

    window.plugin.logger = function() {};

    // SETTINGS
    // ------------------------------------------------------------------------

    window.plugin.logger.LOG_NUMBER_OF_STARS = true;
    window.plugin.logger.DEBUG = false;
    window.plugin.logger.AUTOLOAD_ALL_IMAGES = false;
    window.plugin.logger.MARKER_COLOR = "#55efec";

    // ------------------------------------------------------------------------
    // END SETTINGS

    // Extend standard String object with a hashCode method.
    String.prototype.hashCode = function() {
        var hash = 0;
        if ( this.length === 0 ) return hash;
        for ( var i = 0; i < this.length; i++ ) {
            char = this.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    };

    window.plugin.logger.operateAtUrl = /^https?:\/\/opr\.ingress\.com\/recon/i;
    window.plugin.logger.currentId = null;
    window.plugin.logger.imgEl = null;
    window.plugin.logger.locationEl = null;
    window.plugin.logger.titleEl = null;

    // Find the location elements that hold the gmaps uri and the title.
    window.plugin.logger.findContainers = function() {

        var alist = $("#descriptionDiv").find("a");
        var titleRegexp    = /^https?:\/\/www\.google\.[a-z]+\/search/i;
        var locationRegexp = /^https?:\/\/maps\.google\./i;
        alist.each(function(i) {
            var href = $(this).attr("href");
            if ( locationRegexp.test(href) ) {
                if ( window.plugin.logger.DEBUG ) console.log("Location element found.");
                window.plugin.logger.locationEl = $(this);
            }
            if ( titleRegexp.test(href) ) {
                if ( window.plugin.logger.DEBUG ) console.log("Title element found.");
                window.plugin.logger.titleEl = $(this);
            }
        });
        window.plugin.logger.imgEl = $("div.ingress-background img")[0];

    };

    // How many stars are currently being given to the candidate.
    window.plugin.logger.updateStars = function(id) {

        if ( null === id || false === window.plugin.logger.LOG_NUMBER_OF_STARS ) return;
        var stars = $("button[ng-model='answerCtrl.formData.quality']").find(".gold").length;
        var item = JSON.parse(localStorage.getItem(id));
        item.stars = stars;
        var str = JSON.stringify(item);
        if ( window.plugin.logger.DEBUG ) console.log("Updating: " + str);
        localStorage.setItem(id, str);

    };

    // Extract portal candidate details.
    window.plugin.logger.extractDetails = function() {

        var details = {};
        details.id = 0;
        details.image = null;
        details.title = null;
        details.latitude = null;
        details.longitude = null;

        if ( null === window.plugin.logger.locationEl ||
            null === window.plugin.logger.titleEl ||
            null === window.plugin.logger.imgEl )
            window.plugin.logger.findContainers();

        try {
            details.title = window.plugin.logger.titleEl.text().trim();
            details.image = window.plugin.logger.imgEl.src;
            details.id = details.image.split("/").slice(-1)[0].hashCode();

            var href = window.plugin.logger.locationEl.attr("href");
            // if ( window.plugin.logger.DEBUG ) console.log(href);
            details.latitude = href.split("@")[1].split(",")[0];
            details.longitude = href.split("@")[1].split(",")[1];

            if ( null === details.latitude || "" === details.latitude ||
                null === details.longitude || "" === details.longitude ||
                null === details.title || "" === details.title ||
                null === details.image || "" === details.image ||
                0 === details.id ) throw "Portal data unavailable.";

        } catch(err) {
            if ( window.plugin.logger.DEBUG ) console.log(err);
            details = null;
        }

        if ( window.plugin.logger.DEBUG ) console.log(details);
        return details;

    };

    // Display all logged entries.
    window.plugin.logger.display = function() {

        $("#logModal")[0].style.display = "block";
        var table = $("#logModalContent");
        table.html('
Photo	' +
             ( window.plugin.logger.LOG_NUMBER_OF_STARS ? '	' : '' ) +
             'Title	Longitude	Latitude
'
        );

        var iitcExport = "";
        var items = localStorage.length;
        for ( var i = 0; i < items; i++ ) {
            var item = JSON.parse(localStorage.getItem(localStorage.key(i)));
            if ( window.plugin.logger.DEBUG ) console.log(item);
            var image = '';
            } else {
                image += 'src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" ' +
                    'onclick="this.src = \'' + item.image + '\';"' + '>';
            }
            table.append(
                '
' +
                '' + image + '	' +
                ( window.plugin.logger.LOG_NUMBER_OF_STARS ? '' + ( item.stars || 0 ) + '	' : '' ) +
                '' + item.title + '	' +
                '' + item.longitude + '	' +
                '' + item.latitude + '	' +
                '
'
            );
            iitcExport += '{"type":"marker","latLng":{"lat":' +
                item.latitude + ',"lng":' +
                item.longitude + '},"color":"' +
                window.plugin.logger.MARKER_COLOR + '"},';
        }

        $("#logModalExport").html("[" + iitcExport.slice(0, -1) + "]");

    };

    // Setup this plugin.
    window.plugin.logger.setup = function() {

        // Add means to access logs from the UI.
        $("ul.nav:lt(1)").append('
Log
');
        $("#openLog").click(window.plugin.logger.display);
        $("head").append(
            ''
        );
        $("body").append(
            '
' +
            '
' +
            '×' +
            'Your OPR Log (' + localStorage.length + ' entries)' +
            '
' +
            '
' +
            'IITC Export:
' +
            '<textarea readonly id="logModalExport" style="margin: 16px 0px 0px 0px; padding: 4px; border: 2px solid #55efec; background: black; color: white; width: 100%; height: 50px;"></textarea>' +
            '
' +
            '

' +
            '
'
        );
        $("#logModalCloseButton").click(function() { $("#logModal")[0].style.display = "none"; });

        // Try to extract portal candidate details on every click until successful.
        if ( window.plugin.logger.operateAtUrl.test(window.location.href) ) $("body").click(function() {
            if ( null === window.plugin.logger.currentId ) {
                var details = window.plugin.logger.extractDetails();
                if ( null === details ) {
                    console.log("Could not extract and record portal data.");
                } else {
                    var id = details.id;
                    delete details.id;
                    if ( null === localStorage.getItem(id) ) {
                        var str = JSON.stringify(details);
                        if ( window.plugin.logger.DEBUG ) console.log("Appending: " + str);
                        localStorage.setItem(id, str);
                    } else {
                        if ( window.plugin.logger.DEBUG ) console.log("Object " + id + " already exists in OPR log.");
                    }
                    window.plugin.logger.currentId = id;
                }
            } else {
                if ( window.plugin.logger.DEBUG ) console.log("This candidate has already been logged.");
            }
            window.plugin.logger.updateStars(window.plugin.logger.currentId);
        });

    };

} // wrapper end
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);

window.plugin.logger.setup();
if ( window.plugin.logger.DEBUG ) console.log("Logger initialized.");
<|endoftext|>