<commit_before>/* global ngGridFlexibleHeightPlugin, Papa*/
'use strict';

/**
 * @ngdoc function
 * @name axisJSApp.controller:MainCtrl
 * @description
 * Main controller. Populates and links the input fields.
 */
angular.module('axisJSApp')
  .controller('MainCtrl', function ($scope) {
    $scope.inputs = {};
    $scope.columns = [];
    $scope.chartData = {};
    $scope.gridOptions = {
      data: 'chartData',
      plugins: [
        new ngGridFlexibleHeightPlugin()
      ]
    };

    $scope.config = {
      data: {
        x: '',
        y: '',
        y2: '',
        columns: [
          ['data1', 30, 200, 100, 400, 150, 250],
          ['data2', 50, 20, 10, 40, 15, 25]
        ],
        axes: {
        },
        type: '',
        types: {
          data1: 'line', // Currently must set explictly on initialisation to populate view.
          data2: 'line'
        },
        colors: {
          data1: '#44a4ed',
          data2: '#AEC1D0'
        }
      },
      axis: {
        x: {
          show: true,
          tick: {
            format: function(d){return d;}
          }
        },
        y: {
          show: true,
          tick: {
            format: function(d){return d;}
          }
        },
        y2: {
          show: false,
          tick: {
            format: function(d){return d;}
          }
        }
      }
    };

    $scope.chartTypes = [ // TODO: Abstract this into the ChartProvider service.
      'line',
      'step',
      'area',
      'area-step',
      'scatter',
      'bar',
      'spline',
      // 'donut', // These are handled via $scope.config.chartGlobalType
      // 'gauge',
      // 'pie'
    ];

    // Populate Initial
    $scope.inputs.csvData = 'data1\tdata2\n30\t50\n200\t20\n100\t10\n400\t40\n150\t15\n250\t25';
    $scope.config.axis.x.show = true;
    $scope.config.axis.y.show = true;
    $scope.config.axis.y2.show = false;
    $scope.config.chartTitle = '';
    $scope.config.chartCredit = '';
    $scope.config.chartSource = '';
    $scope.config.chartWidth = 1000;
    $scope.config.chartGlobalType = 'series';
    $scope.config.cms = (typeof parent.tinymce !== 'undefined' ? true : false);

    $scope.updateData = function() {
      $scope.chartData = []; // Empty, or else new column names will break ng-grid
      $scope.columns = []; // Clear existing
      $scope.config.data.columns = [];

      $scope.chartData = Papa.parse($scope.inputs.csvData, {header: true}).data;
      // n.b., you can also use rows in C3 instead, which is like Papa.parse() without
      // header: true. TODO for anyone wanting to play some code golf...

      if ($scope.chartData.length > 0) {
        $scope.columns = Object.keys($scope.chartData[0]);
        angular.forEach($scope.columns, function(colName) {
          var column = [];
          column.push(colName);
          angular.forEach($scope.chartData, function(datum) {
            column.push(datum[colName]);
          });

          $scope.config.data.columns.push(column);
          if (typeof $scope.config.data.types[colName] === 'undefined') {
            if ($scope.config.chartGlobalType === 'series') {
              $scope.config.data.types[colName] = 'line'; // default to line.
            } else { // else the global chart type
              $scope.config.data.types[colName] = $scope.config.chartGlobalType;
            }

          }
        });
      }
    };

    $scope.setGlobalType = function(type) {
      for (var key in $scope.config.data.types) {
        if ($scope.config.data.types.hasOwnProperty(key)) {
          if (type !== 'series') {
            $scope.config.data.types[key] = type;
          } else {
            $scope.config.data.types[key] = 'line';
          }

        }
      }
    };

    $scope.updateData(); // Push the initial data.
    //$scope.$watch('chartData', function(){$scope.apply;}); // needed? probably not...

    // Repopulate if data is being sent in from WordPress.
    if (typeof parent.tinymce !== 'undefined' && typeof parent.tinymce.activeEditor.windowManager.getParams().axisJS !== 'undefined' ) {
      $scope.config = angular.fromJson(window.atob(parent.tinymce.activeEditor.windowManager.getParams().axisJS));
      $scope.updateData();
    }

  });
<commit_msg>Turning points off as per style.<commit_after>/* global ngGridFlexibleHeightPlugin, Papa*/
'use strict';

/**
 * @ngdoc function
 * @name axisJSApp.controller:MainCtrl
 * @description
 * Main controller. Populates and links the input fields.
 */
angular.module('axisJSApp')
  .controller('MainCtrl', function ($scope) {
    $scope.inputs = {};
    $scope.columns = [];
    $scope.chartData = {};
    $scope.gridOptions = {
      data: 'chartData',
      plugins: [
        new ngGridFlexibleHeightPlugin()
      ]
    };

    $scope.config = {
      data: {
        x: '',
        y: '',
        y2: '',
        columns: [
          ['data1', 30, 200, 100, 400, 150, 250],
          ['data2', 50, 20, 10, 40, 15, 25]
        ],
        axes: {
        },
        type: '',
        types: {
          data1: 'line', // Currently must set explictly on initialisation to populate view.
          data2: 'line'
        },
        colors: {
          data1: '#44a4ed',
          data2: '#AEC1D0'
        }
      },
      axis: {
        x: {
          show: true,
          tick: {
            format: function(d){return d;}
          }
        },
        y: {
          show: true,
          tick: {
            format: function(d){return d;}
          }
        },
        y2: {
          show: false,
          tick: {
            format: function(d){return d;}
          }
        }
      },
      point: {
          show: false
      }
    };

    $scope.chartTypes = [ // TODO: Abstract this into the ChartProvider service.
      'line',
      'step',
      'area',
      'area-step',
      'scatter',
      'bar',
      'spline',
      // 'donut', // These are handled via $scope.config.chartGlobalType
      // 'gauge',
      // 'pie'
    ];

    // Populate Initial
    $scope.inputs.csvData = 'data1\tdata2\n30\t50\n200\t20\n100\t10\n400\t40\n150\t15\n250\t25';
    $scope.config.axis.x.show = true;
    $scope.config.axis.y.show = true;
    $scope.config.axis.y2.show = false;
    $scope.config.chartTitle = '';
    $scope.config.chartCredit = '';
    $scope.config.chartSource = '';
    $scope.config.chartWidth = 1000;
    $scope.config.chartGlobalType = 'series';
    $scope.config.cms = (typeof parent.tinymce !== 'undefined' ? true : false);

    $scope.updateData = function() {
      $scope.chartData = []; // Empty, or else new column names will break ng-grid
      $scope.columns = []; // Clear existing
      $scope.config.data.columns = [];

      $scope.chartData = Papa.parse($scope.inputs.csvData, {header: true}).data;
      // n.b., you can also use rows in C3 instead, which is like Papa.parse() without
      // header: true. TODO for anyone wanting to play some code golf...

      if ($scope.chartData.length > 0) {
        $scope.columns = Object.keys($scope.chartData[0]);
        angular.forEach($scope.columns, function(colName) {
          var column = [];
          column.push(colName);
          angular.forEach($scope.chartData, function(datum) {
            column.push(datum[colName]);
          });

          $scope.config.data.columns.push(column);
          if (typeof $scope.config.data.types[colName] === 'undefined') {
            if ($scope.config.chartGlobalType === 'series') {
              $scope.config.data.types[colName] = 'line'; // default to line.
            } else { // else the global chart type
              $scope.config.data.types[colName] = $scope.config.chartGlobalType;
            }

          }
        });
      }
    };

    $scope.setGlobalType = function(type) {
      for (var key in $scope.config.data.types) {
        if ($scope.config.data.types.hasOwnProperty(key)) {
          if (type !== 'series') {
            $scope.config.data.types[key] = type;
          } else {
            $scope.config.data.types[key] = 'line';
          }

        }
      }
    };

    $scope.updateData(); // Push the initial data.
    //$scope.$watch('chartData', function(){$scope.apply;}); // needed? probably not...

    // Repopulate if data is being sent in from WordPress.
    if (typeof parent.tinymce !== 'undefined' && typeof parent.tinymce.activeEditor.windowManager.getParams().axisJS !== 'undefined' ) {
      $scope.config = angular.fromJson(window.atob(parent.tinymce.activeEditor.windowManager.getParams().axisJS));
      $scope.updateData();
    }

  });
<|endoftext|>


<commit_before>'use strict';

angular.module('stockApp')
  .controller('MainCtrl', function (
    $filter,
    $interval,
    $scope,
    chartXAxis,
    bitcoinData,
    BitcoinChartConfig,
    feedData,
    feeds,
    PieChartConfig,
    StockChartConfig,
    stockData,
    stockSymbols
  ) {

    /* stock ticker */

    var RANGE = 6;

    var startDate = new Date();
    var endDate = new Date();
    startDate.setMonth(startDate.getMonth() - RANGE);

    var startDateFiltered = $filter('date')(startDate, 'yyyy-MM-dd');
    var endDateFiltered = $filter('date')(endDate, 'yyyy-MM-dd');

    $scope.stockSliderConfig = {
      title: '',
      startDate: startDate,
      endDate: endDate,
      slides: [
        {
          text: 'Slide 1',
          type: 'chart',
          stockChartConfig: new StockChartConfig(),
          pieChartConfig: new PieChartConfig()
        },
        {
          text: 'Slide 2',
          type: 'chart',
          stockChartConfig: new StockChartConfig(),
          pieChartConfig: new PieChartConfig()
        }
      ]
    };

    var titles = [];
    angular.forEach(stockSymbols, function (value, key) {
      titles.push(value.join(', '));
      stockData.get(value, startDateFiltered, endDateFiltered).then(function (data) {
        $scope.stockSliderConfig.slides[key].stockChartConfig.series = data;
        $scope.stockSliderConfig.slides[key].stockChartConfig.xAxis = chartXAxis;
        $scope.stockSliderConfig.slides[key].stockChartConfig.title.text = value.join(', ');
        $scope.stockSliderConfig.slides[key].stockChartConfig.loading = false;
        $scope.stockSliderConfig.slides[key].pieChartConfig.series.push(stockData.getPie(data));
        $scope.stockSliderConfig.slides[key].pieChartConfig.loading = false;
      });
    });

    $scope.stockSliderConfig.title = titles.join(' - ');

    /* news feed */

    feedData(feeds[0]).then(function (data) {
      $scope.feed = data;
    });

    var feedIdx = 1;

    var feedInterval = $interval(function () {
      feedData(feeds[feedIdx]).then(function (data) {
        $scope.feed = data;
      });
      feedIdx = (feedIdx + 1) % feeds.length;
    }, 7000);

    /* bitcoins */

    $scope.bitcoin = {};
    $scope.bitcoin.chartConfig = new BitcoinChartConfig();

    bitcoinData.get().then(function (data) {
      $scope.bitcoin.chartConfig.series.push(data);
      var year = 365 * 24 * 3600 * 1000;
      $scope.bitcoin.chartConfig.xAxis.currentMin = new Date().getTime() - year;
      $scope.bitcoin.chartConfig.loading = false;
    });

    /* common */

    // stop intervals on $scope destroy (route change)
    $scope.$on('$destroy', function () {
      $interval.cancel(feedInterval);
    });

  });
<commit_msg>Update StockSliderConfig object<commit_after>'use strict';

angular.module('stockApp')
  .controller('MainCtrl', function (
    $filter,
    $interval,
    $scope,
    chartXAxis,
    bitcoinData,
    BitcoinChartConfig,
    feedData,
    feeds,
    PieChartConfig,
    StockChartConfig,
    stockData,
    stockSymbols
  ) {

    /* stock ticker */

    var RANGE = 6;

    var startDate = new Date();
    var endDate = new Date();
    startDate.setMonth(startDate.getMonth() - RANGE);

    var startDateFiltered = $filter('date')(startDate, 'yyyy-MM-dd');
    var endDateFiltered = $filter('date')(endDate, 'yyyy-MM-dd');

    $scope.stockSliderConfig = {
      title: '',
      startDate: startDate,
      endDate: endDate,
      slides: []
    };

    var titles = [];
    angular.forEach(stockSymbols, function (value, key) {
      titles.push(value.join(', '));
      stockData.get(value, startDateFiltered, endDateFiltered).then(function (data) {
        $scope.stockSliderConfig.slides[key] = {};
        $scope.stockSliderConfig.slides[key].stockChartConfig = new StockChartConfig();
        $scope.stockSliderConfig.slides[key].stockChartConfig.series = data;
        $scope.stockSliderConfig.slides[key].stockChartConfig.xAxis = chartXAxis;
        $scope.stockSliderConfig.slides[key].stockChartConfig.title.text = value.join(', ');
        $scope.stockSliderConfig.slides[key].stockChartConfig.loading = false;
        $scope.stockSliderConfig.slides[key].pieChartConfig = new PieChartConfig();
        $scope.stockSliderConfig.slides[key].pieChartConfig.series.push(stockData.getPie(data));
        $scope.stockSliderConfig.slides[key].pieChartConfig.loading = false;
      });
    });

    $scope.stockSliderConfig.title = titles.join(' - ');

    /* news feed */

    feedData(feeds[0]).then(function (data) {
      $scope.feed = data;
    });

    var feedIdx = 1;

    var feedInterval = $interval(function () {
      feedData(feeds[feedIdx]).then(function (data) {
        $scope.feed = data;
      });
      feedIdx = (feedIdx + 1) % feeds.length;
    }, 7000);

    /* bitcoins */

    $scope.bitcoin = {};
    $scope.bitcoin.chartConfig = new BitcoinChartConfig();

    bitcoinData.get().then(function (data) {
      $scope.bitcoin.chartConfig.series.push(data);
      var year = 365 * 24 * 3600 * 1000;
      $scope.bitcoin.chartConfig.xAxis.currentMin = new Date().getTime() - year;
      $scope.bitcoin.chartConfig.loading = false;
    });

    /* common */

    // stop intervals on $scope destroy (route change)
    $scope.$on('$destroy', function () {
      $interval.cancel(feedInterval);
    });

  });
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name chessmateApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the chessmateApp
 */
angular.module('chessmateApp')
  .controller('MainCtrl', function ($scope,$rootScope) {

    $scope.game = null;
    $scope.$on('game-updated', function (event, game) {
      console.log(game);
      $scope.game = game;

      renderBoard($scope.game.boards[0]);
    });

    $scope.$on('animation-completed', function (event,isMoveForward) {
      if($scope.interval){
        clearInterval($scope.interval);
      }

      var nextBoard = null;
      if(isMoveForward){
        nextBoard = $scope.currentBoard.next($scope.game);
      }else{
        nextBoard = $scope.currentBoard.previous($scope.game);
      }

      renderBoard(nextBoard);

      if($scope.isPlay) {
        setTimeout(function(){
          $rootScope.$broadcast('play', null);
        }, 1000);
      }
    });

    $scope.$on('next', function (event) {
      move($scope.currentBoard, true);
    });
    $scope.$on('play', function (event) {
      move($scope.currentBoard, true);
    });
    $scope.$on('back', function (event) {
      move($scope.currentBoard, false);
    });
    $scope.$on('add-comment', function (event, comment) {
      $scope.currentBoard.comment = comment;
      displayComment($scope.currentBoard);
    });

    $scope.next = function(){
      $scope.isPlay = false;
      $rootScope.$broadcast('next', null);
    };
    $scope.play = function(){
      $scope.isPlay = !$scope.isPlay;
      if($scope.isPlay) {
        $rootScope.$broadcast('play', null);
      } else {
        renderBoard($scope.currentBoard);
      }
    };
    $scope.back = function(){
      $scope.isPlay = false;
      $rootScope.$broadcast('back', null);
    };

    $scope.changeBoard = function(board){
      $scope.isPlay = false;
      displayComment(board);
      renderBoard(board);
    };

    function move(currentBoard, isMoveForward) {
      var source = null;
      var destination = null;

      if(isMoveForward){
        currentBoard = currentBoard.next($scope.game);
        source = currentBoard.source;
        destination = currentBoard.destination;
        displayComment(currentBoard);
      }else{
        source = currentBoard.destination;
        destination = currentBoard.source;
        displayComment(currentBoard.previous($scope.game));
      }

      var desinationPosition = $("#" + destination).position();
      var sourcePosition = $("#" + source).position();

      var piece = $("#" + source).children();

      var destinationClass = buildCss(desinationPosition.left - sourcePosition.left, desinationPosition.top - sourcePosition.top);

      //remove highlight
      $('.piece').removeClass('highlight');
      $('.piece').removeClass('destination');

      setTimeout(function(){
        // move
        $(".board div").addClass("divTransition");
        piece.css(destinationClass);
      }, 100);

      var currentTurn = currentBoard.turn;
      $scope.interval = setInterval(function(){
        if($scope.currentBoard.turn == currentTurn){
          $rootScope.$broadcast('animation-completed', isMoveForward);
        }
      },1500);

      $(piece).on("webkitTransitionEnd otransitionEnd oTransitionEnd msTransitionEnd transitionEnd",function(event) {
        $rootScope.$broadcast('animation-completed', isMoveForward);
      });
    };

    function buildCss(positionX, positionY) {
      var transform = "translate(" + positionX + "px, " + positionY + "px)";
      var cssStyle = { "-webkit-transform": transform,
        "-moz-transform": transform,
        "-o-transform": transform,
        "-ms-transform": transform,
        "transform": transform};
      return cssStyle;
    }

    function displayComment(board) {
      $('.notifications').empty();

      if (board.comment) {
        $("#commentBox").val(board.comment);

        $('.notifications').notify({
          message: { text: board.comment }
        }).show();

        var destPosition = $("#" + board.destination).position();
        if (destPosition) {
          $('.notifications').css('top', destPosition.top + 'px');
          $('.notifications').css('left', (destPosition.left + 80) + 'px');
        }
      } else {
        $("#commentBox").val("");
      }
    }

    function renderBoard(board) {
      // unbind all rows
      $scope.game.rows = [];
      forceScreenRender();

      // rebind all rows
      $scope.currentBoard = board;
      $scope.game.rows = [8, 7, 6, 5, 4, 3, 2, 1];
      forceScreenRender();
    }

    function autoFocusOnGameInfo (turnNumber){
      var dynamicId = 'rowFocus'+turnNumber;
      var intendedRow = $document[0].getElementById(dynamicId);
      intendedRow.scrollIntoView(true);
    }

    function forceScreenRender(){
      if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
        $scope.$apply();
      }
    }
  });
<commit_msg>Refactor and fix auto scroll method<commit_after>'use strict';

/**
 * @ngdoc function
 * @name chessmateApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the chessmateApp
 */
angular.module('chessmateApp')
  .controller('MainCtrl', function ($scope,$rootScope) {

    $scope.game = null;
    $scope.$on('game-updated', function (event, game) {
      console.log(game);
      $scope.game = game;

      renderBoard($scope.game.boards[0]);
    });

    $scope.$on('animation-completed', function (event,isMoveForward) {
      if($scope.interval){
        clearInterval($scope.interval);
      }

      var nextBoard = null;
      if(isMoveForward){
        nextBoard = $scope.currentBoard.next($scope.game);
      }else{
        nextBoard = $scope.currentBoard.previous($scope.game);
      }

      renderBoard(nextBoard);

      if($scope.isPlay) {
        setTimeout(function(){
          $rootScope.$broadcast('play', null);
        }, 1000);
      }
    });

    $scope.$on('next', function (event) {
      move($scope.currentBoard, true);
    });
    $scope.$on('play', function (event) {
      move($scope.currentBoard, true);
    });
    $scope.$on('back', function (event) {
      move($scope.currentBoard, false);
    });
    $scope.$on('add-comment', function (event, comment) {
      $scope.currentBoard.comment = comment;
      displayComment($scope.currentBoard);
    });

    $scope.next = function(){
      $scope.isPlay = false;
      $rootScope.$broadcast('next', null);
    };
    $scope.play = function(){
      $scope.isPlay = !$scope.isPlay;
      if($scope.isPlay) {
        $rootScope.$broadcast('play', null);
      } else {
        renderBoard($scope.currentBoard);
      }
    };
    $scope.back = function(){
      $scope.isPlay = false;
      $rootScope.$broadcast('back', null);
    };

    $scope.changeBoard = function(board){
      $scope.isPlay = false;
      displayComment(board);
      renderBoard(board);
    };

    function move(currentBoard, isMoveForward) {
      var source = null;
      var destination = null;

      if(isMoveForward){
        currentBoard = currentBoard.next($scope.game);
        source = currentBoard.source;
        destination = currentBoard.destination;
        displayComment(currentBoard);
      }else{
        source = currentBoard.destination;
        destination = currentBoard.source;
        displayComment(currentBoard.previous($scope.game));
      }

      var desinationPosition = $("#" + destination).position();
      var sourcePosition = $("#" + source).position();

      var piece = $("#" + source).children();

      var destinationClass = buildCss(desinationPosition.left - sourcePosition.left, desinationPosition.top - sourcePosition.top);

      //remove highlight
      $('.piece').removeClass('highlight');
      $('.piece').removeClass('destination');

      setTimeout(function(){
        // move
        $(".board div").addClass("divTransition");
        piece.css(destinationClass);
      }, 100);

      var currentTurn = currentBoard.turn;
      $scope.interval = setInterval(function(){
        if($scope.currentBoard.turn == currentTurn){
          $rootScope.$broadcast('animation-completed', isMoveForward);
        }
      },1500);

      $(piece).on("webkitTransitionEnd otransitionEnd oTransitionEnd msTransitionEnd transitionEnd",function(event) {
        $rootScope.$broadcast('animation-completed', isMoveForward);
      });
    };

    function buildCss(positionX, positionY) {
      var transform = "translate(" + positionX + "px, " + positionY + "px)";
      var cssStyle = { "-webkit-transform": transform,
        "-moz-transform": transform,
        "-o-transform": transform,
        "-ms-transform": transform,
        "transform": transform};
      return cssStyle;
    }

    function displayComment(board) {
      $('.notifications').empty();

      if (board.comment) {
        $("#commentBox").val(board.comment);

        $('.notifications').notify({
          message: { text: board.comment }
        }).show();

        var destPosition = $("#" + board.destination).position();
        if (destPosition) {
          $('.notifications').css('top', destPosition.top + 'px');
          $('.notifications').css('left', (destPosition.left + 80) + 'px');
        }
      } else {
        $("#commentBox").val("");
      }
    }

    function renderBoard(board) {
      // unbind all rows
      $scope.game.rows = [];
      forceScreenRender();

      // rebind all rows
      $scope.currentBoard = board;
      $scope.game.rows = [8, 7, 6, 5, 4, 3, 2, 1];
      forceScreenRender();
      autoFocusOnGameInfo(board.turn);
    }

    function autoFocusOnGameInfo (turnNumber){
      var dynamicId = 'rowFocus'+turnNumber;
      if(dynamicId=== 'rowFocus0'){
        return;
      }else{
         var intendedRow = document.getElementById(dynamicId);
         intendedRow.scrollIntoView(false);
      }
    }

    function forceScreenRender(){
      if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
        $scope.$apply();
      }
    }
  });
<|endoftext|>


<commit_before>"use strict";

app.filter('location', function(filterFilter) {

    return function(locations, query) {

        var locationPattern = {};

        if (!query.allDistricts()) {
            locationPattern.district = query.district;
        }

        if (query.organic) {
            locationPattern.organic = "1";
        }

        if (query.glutenFree) {
            locationPattern.glutenFree = "1";
        }

        if (query.handicappedAccessible) {
            locationPattern.handicappedAccessible = "1";
        }

        if (query.handicappedAccessibleWc) {
            locationPattern.handicappedAccessibleWc = "1";
        }

        if (query.organic) {
            locationPattern.organic = "1";
        }

        if (query.organic) {
            locationPattern.organic = "1";
        }

        if (query.dog) {
            locationPattern.dog = "1";
        }

        if (query.wlan) {
            locationPattern.wlan = "1";
        }

        if (query.catering) {
            locationPattern.catering = "1";
        }

        if (query.delivery) {
            locationPattern.delivery = "1";
        }

        var filterFunction = function(location, index, array) {

            if (query.openNow) {
                var now = new Date(Date.now());
                return location.isOpen(now.getDay(), now);
            } else if (!query.allWeekDays()) {
                return location.isOpen(parseInt(query.openAtWeekDay), query.openAtTime);
            } else {
                return true;
            }
        };

        var filterFunction2 = function(location, index, array) {

            if (query.distance.enabled) {
                return location.getDistanceToPositionInKm(query.distance.position) <= query.distance.km;
            } else {
                return true;
            }
        };

        var filterFunction3 = function(location, index, array) {

            var searchedValues = [location.name];

            if (!query.textAppliesToNamesOnly) {
                searchedValues = searchedValues.concat([
                    location.street,
                    location.cityCode,
                    location.district,
                    location.publicTransport,
                    location.telephone,
                    location.website,
                    location.email,
                    location.commentWithoutFormatting
                ]);

                searchedValues = searchedValues.concat(location.tags);
            }
            return searchedValues.some(function(property) {
                return normalizeText(property).includes(normalizeText(query.text));
            });
        };

        var filterFunction4 = function(location, index, array) {

            for (var tag in query.tags) {
                if (query.tags.hasOwnProperty(tag) && query.tags[tag]) { // Tag is selected...
                    if (location.tags.indexOf(tag) >= 0) { // ... and location has tag
                        return true;
                    }
                }
            }

            return false;
        };

        var filterFunction5 = function(location, index, array) {

            for (var veganCategory in query.veganCategories) {
                if (query.veganCategories.hasOwnProperty(veganCategory) && query.veganCategories[veganCategory]) { // Vegan category is selected...
                    if (location.getVeganCategoryFriendly() === veganCategory) { // ... and location belongs to it
                        return true;
                    }
                }
            }

            return false;
        };

        var filterFunction6 = function(location, index, array) {

            if (query.review) {
                return location.reviewURL && location.reviewURL.length > 0;
            } else {
                return true;
            }
        }

        var filteredLocations = filterFilter(locations, locationPattern);
        filteredLocations = filterFilter(filteredLocations, filterFunction);
        filteredLocations = filterFilter(filteredLocations, filterFunction2);
        filteredLocations = filterFilter(filteredLocations, filterFunction3);
        filteredLocations = filterFilter(filteredLocations, filterFunction4);
        filteredLocations = filterFilter(filteredLocations, filterFunction5);
        filteredLocations = filterFilter(filteredLocations, filterFunction6);
        return filteredLocations;
    };

    function normalizeText(text) {

        if (typeof text === "undefined") {
            text = "";
        }

        if (!(text === 'string' || text instanceof String)) {
            text+= "";
        }

        // So we find café when searching for cafe and vice versa.
        // Analogous motivation for the other letters.
        text = text.replace(/é/g, "e").replace(/á/g, "a").replace(/à/g, "a").replace(/â/g, "a").replace(/ñ/g, "n");

        return text.toLowerCase();
    }
});<commit_msg>Improved normalization<commit_after>"use strict";

app.filter('location', function(filterFilter) {

    return function(locations, query) {

        var locationPattern = {};

        if (!query.allDistricts()) {
            locationPattern.district = query.district;
        }

        if (query.organic) {
            locationPattern.organic = "1";
        }

        if (query.glutenFree) {
            locationPattern.glutenFree = "1";
        }

        if (query.handicappedAccessible) {
            locationPattern.handicappedAccessible = "1";
        }

        if (query.handicappedAccessibleWc) {
            locationPattern.handicappedAccessibleWc = "1";
        }

        if (query.organic) {
            locationPattern.organic = "1";
        }

        if (query.organic) {
            locationPattern.organic = "1";
        }

        if (query.dog) {
            locationPattern.dog = "1";
        }

        if (query.wlan) {
            locationPattern.wlan = "1";
        }

        if (query.catering) {
            locationPattern.catering = "1";
        }

        if (query.delivery) {
            locationPattern.delivery = "1";
        }

        var filterFunction = function(location, index, array) {

            if (query.openNow) {
                var now = new Date(Date.now());
                return location.isOpen(now.getDay(), now);
            } else if (!query.allWeekDays()) {
                return location.isOpen(parseInt(query.openAtWeekDay), query.openAtTime);
            } else {
                return true;
            }
        };

        var filterFunction2 = function(location, index, array) {

            if (query.distance.enabled) {
                return location.getDistanceToPositionInKm(query.distance.position) <= query.distance.km;
            } else {
                return true;
            }
        };

        var filterFunction3 = function(location, index, array) {

            var searchedValues = [location.name];

            if (!query.textAppliesToNamesOnly) {
                searchedValues = searchedValues.concat([
                    location.street,
                    location.cityCode,
                    location.district,
                    location.publicTransport,
                    location.telephone,
                    location.website,
                    location.email,
                    location.commentWithoutFormatting
                ]);

                searchedValues = searchedValues.concat(location.tags);
            }
            return searchedValues.some(function(property) {
                return normalizeText(property).includes(normalizeText(query.text));
            });
        };

        var filterFunction4 = function(location, index, array) {

            for (var tag in query.tags) {
                if (query.tags.hasOwnProperty(tag) && query.tags[tag]) { // Tag is selected...
                    if (location.tags.indexOf(tag) >= 0) { // ... and location has tag
                        return true;
                    }
                }
            }

            return false;
        };

        var filterFunction5 = function(location, index, array) {

            for (var veganCategory in query.veganCategories) {
                if (query.veganCategories.hasOwnProperty(veganCategory) && query.veganCategories[veganCategory]) { // Vegan category is selected...
                    if (location.getVeganCategoryFriendly() === veganCategory) { // ... and location belongs to it
                        return true;
                    }
                }
            }

            return false;
        };

        var filterFunction6 = function(location, index, array) {

            if (query.review) {
                return location.reviewURL && location.reviewURL.length > 0;
            } else {
                return true;
            }
        }

        var filteredLocations = filterFilter(locations, locationPattern);
        filteredLocations = filterFilter(filteredLocations, filterFunction);
        filteredLocations = filterFilter(filteredLocations, filterFunction2);
        filteredLocations = filterFilter(filteredLocations, filterFunction3);
        filteredLocations = filterFilter(filteredLocations, filterFunction4);
        filteredLocations = filterFilter(filteredLocations, filterFunction5);
        filteredLocations = filterFilter(filteredLocations, filterFunction6);
        return filteredLocations;
    };

    function normalizeText(text) {

        if (typeof text === "undefined") {
            text = "";
        }

        if (!(text === 'string' || text instanceof String)) {
            text+= "";
        }

        // So we find café when searching for cafe and vice versa.
        // Analogous motivation for the other letters.
        text = text.replace(/é/g, "e").replace(/á/g, "a").replace(/à/g, "a").replace(/â/g, "a").replace(/ñ/g, "n").replace(/ô/g, "o");

        return text.toLowerCase();
    }
});<|endoftext|>


<commit_before>import Reflux from 'reflux';
import $ from 'jquery';
import _ from 'underscore';

import config from '../../config'
import GameActions from '../actions/GameActions';

var GameStore = Reflux.createStore({
  listenables: [GameActions],
  init() {
    this.state = {
        usergames: {},
        games: {},
        outstandingRequests: 0,
        loading: false
    };

    this.trigger(this.state);
  },
  getInitialState() {
    return this.state;
  },
  onLoadGames() {
    this.incrementOutstandingRequests()
    $.get(config.apiRoot + '/api/games')
        .fail(_.bind(this.onLoadGamesError, this))
        .then(_.bind(function(games) {
            this.state.usergames = games;

            _.each(games, _.bind(this.onLoadGame, this));
            this.decrementOutstandingRequests();
        }, this));
  },

  incrementOutstandingRequests() {
      this.state.outstandingRequests++;
      this.state.loading = true;
      this.trigger(this.state);
  },

  decrementOutstandingRequests() {
      this.state.outstandingRequests--
      if (this.state.outstandingRequests <= 0) {
          this.state.outstandingRequests = 0;
          this.state.loading = false;
      }
      this.trigger(this.state);
  },

  onLoadGame(gameId) {
    this.state.incrementOutstandingRequests();
    $.get(config.apiRoot + '/api/games/' + gameId)
        .then(_.bind(function(gameInfo) {
            this.state.games[gameId] = gameInfo;
            this.decrementOutstandingRequests();
        }, this));
  },

  onLoadGamesError(error) {
      this.decrementOutstandingRequests();
  },

  onCreateGame(color) {
      var data = {};
      if (color == "white" || color == "black") {
          data.color = color
      }
      $.ajax(config.apiRoot + "/api/games/create", {
          data: JSON.stringify(data),
          contentType: 'application/json',
          type: 'POST'
      }).then(_.bind(this.onLoadGames, this));
  },

});

export default GameStore;
<commit_msg>Fixing something<commit_after>import Reflux from 'reflux';
import $ from 'jquery';
import _ from 'underscore';

import config from '../../config'
import GameActions from '../actions/GameActions';

var GameStore = Reflux.createStore({
  listenables: [GameActions],
  init() {
    this.state = {
        usergames: {},
        games: {},
        outstandingRequests: 0,
        loading: false
    };

    this.trigger(this.state);
  },
  getInitialState() {
    return this.state;
  },
  onLoadGames() {
    this.incrementOutstandingRequests()
    $.get(config.apiRoot + '/api/games')
        .fail(_.bind(this.onLoadGamesError, this))
        .then(_.bind(function(games) {
            this.state.usergames = games;

            _.each(games, _.bind(this.onLoadGame, this));
            this.decrementOutstandingRequests();
        }, this));
  },

  incrementOutstandingRequests() {
      this.state.outstandingRequests++;
      this.state.loading = true;
      this.trigger(this.state);
  },

  decrementOutstandingRequests() {
      this.state.outstandingRequests--
      if (this.state.outstandingRequests <= 0) {
          this.state.outstandingRequests = 0;
          this.state.loading = false;
      }
      this.trigger(this.state);
  },

  onLoadGame(gameId) {
    this.incrementOutstandingRequests();
    $.get(config.apiRoot + '/api/games/' + gameId)
        .then(_.bind(function(gameInfo) {
            this.state.games[gameId] = gameInfo;
            this.decrementOutstandingRequests();
        }, this));
  },

  onLoadGamesError(error) {
      this.decrementOutstandingRequests();
  },

  onCreateGame(color) {
      var data = {};
      if (color == "white" || color == "black") {
          data.color = color
      }
      $.ajax(config.apiRoot + "/api/games/create", {
          data: JSON.stringify(data),
          contentType: 'application/json',
          type: 'POST'
      }).then(_.bind(this.onLoadGames, this));
  },

  onJoinGame(gameId) {
      $.ajax(config.apiRoot + "/api/games/" + gameId + "/join", {
          data: JSON.stringify({}),
          contentType: 'application/json',
          type: 'POST'
      }).then(_.bind(this.onLoadGames, this));
  }

});

export default GameStore;
<|endoftext|>


<commit_before>/*
 Copyright 2016 Mozilla

 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 this file except in compliance with the License. You may obtain a copy of the
 License at http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software distributed
 under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 CONDITIONS OF ANY KIND, either express or implied. See the License for the
 specific language governing permissions and limitations under the License.
 */

import EventEmitter from 'events';
import WebSocket from 'ws';
import request from 'request';
import backoff from 'backoff';
import { logger } from './logging';

function uaRequest(url, service, options) {
  return new Promise((resolve, reject) => {
    request[options.method.toLowerCase()]({
      url: `${url}${service}`,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    }, (err, response, body) => {
      if (err) {
        reject(err);
        return;
      }

      resolve(JSON.parse(body));
    });
  });
}

class UserAgentClient extends EventEmitter {
  constructor() {
    super();
    this._connected = false;
  }

  async startSession() {
    // Do not use `this._connect` promise in the event we call a subsequent
    // `connect()` with different port/host/version information during negotiating
    // the port, for example.
    if (!this._connected) {
      await new Promise(resolve => this.once('connected', resolve));
    }

    const url = `http://${this.host}:${this.port}/${this.version}`;
    return uaRequest(url, '/session/start', {
      method: 'POST',
    });
  }

  /**
   * Connects to the remote User Agent Service, and resolves a promise
   * upon completion. Can be called multiple times and caches the connection
   * promise so consumers can always call `await client.connect(ops)` safely.
   *
   * Calling with different address information will attempt a new connection.
   *
   * @TODO what happens if this never connects?
   */
  async connect({ version, host, port }) {
    if (!version || !host || !port) {
      throw new Error('Must have host, port, and version defined.');
    }

    // If we already connected to this version, host and port,
    // return the same promise.
    if (this._connect &&
        this.version === version &&
        this.host === host &&
        this.port === port) {
      return this._connect;
    }

    this._connected = false;
    this.version = version;
    this.host = host;
    this.port = port;

    const url = `ws://${this.host}:${this.port}/${this.version}/ws`;

    this._connect = new Promise((resolve) => {
      const call = backoff.call(this._connectAttempt, url, (err, ws) => {
        if (err) {
          logger.error(`UserAgentClient: ${err}`);
        } else if (ws) {
          this.ws = ws;
          resolve(this);
        }
      });
      call.setStrategy(new backoff.ExponentialStrategy({
        initialDelay: 50,
        maxDelay: 10000,
      }));
      call.start();
    });

    await this._connect;

    this.ws.on('message', (data) => {
      data = JSON.parse(data);
      const message = data.message;
      delete data.message;
      this.emit(message, data);
    });

    this.emit('connected');

    return this._connect;
  }

  _connectAttempt(url, callback) {
    // Use promises here so we only get one firing over the callback
    // per attempt, but pipe into the callback for compatibility with
    // `backoff` module.
    const attempt = new Promise((resolve, reject) => {
      const ws = new WebSocket(url);
      ws.on('error', reject);
      ws.on('open', () => {
        // The first message should be protocol information
        ws.once('message', (data) => {
          data = JSON.parse(data);

          if (data.message !== 'protocol' || data.version !== 'v1') {
            reject(new Error(`Incorrect message ${JSON.stringify(data)}`));
            return;
          }
          resolve(ws);
        });
      });
    });

    attempt.then(callback.bind(null, null), callback);
  }
}

export default UserAgentClient;
<commit_msg>Fixing activate for Mac OSX. Issue #771 https://github.com/mozilla/tofino/issues/771 (#772)<commit_after>/*
 Copyright 2016 Mozilla

 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 this file except in compliance with the License. You may obtain a copy of the
 License at http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software distributed
 under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 CONDITIONS OF ANY KIND, either express or implied. See the License for the
 specific language governing permissions and limitations under the License.
 */

import EventEmitter from 'events';
import WebSocket from 'ws';
import request from 'request';
import backoff from 'backoff';
import { logger } from './logging';

function uaRequest(url, service, options) {
  return new Promise((resolve, reject) => {
    request[options.method.toLowerCase()]({
      url: `${url}${service}`,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    }, (err, response, body) => {
      if (err) {
        reject(err);
        return;
      }

      resolve(JSON.parse(body));
    });
  });
}

class UserAgentClient extends EventEmitter {
  constructor() {
    super();
    this._connected = false;
  }

  async startSession() {
    // Do not use `this._connect` promise in the event we call a subsequent
    // `connect()` with different port/host/version information during negotiating
    // the port, for example.
    if (!this._connected) {
      await new Promise(resolve => this.once('connected', resolve));
    }

    const url = `http://${this.host}:${this.port}/${this.version}`;
    return uaRequest(url, '/session/start', {
      method: 'POST',
    });
  }

  /**
   * Connects to the remote User Agent Service, and resolves a promise
   * upon completion. Can be called multiple times and caches the connection
   * promise so consumers can always call `await client.connect(ops)` safely.
   *
   * Calling with different address information will attempt a new connection.
   *
   * @TODO what happens if this never connects?
   */
  async connect({ version, host, port }) {
    if (!version || !host || !port) {
      throw new Error('Must have host, port, and version defined.');
    }

    // If we already connected to this version, host and port,
    // return the same promise.
    if (this._connect &&
        this.version === version &&
        this.host === host &&
        this.port === port) {
      return this._connect;
    }

    this._connected = false;
    this.version = version;
    this.host = host;
    this.port = port;

    const url = `ws://${this.host}:${this.port}/${this.version}/ws`;

    this._connect = new Promise((resolve) => {
      const call = backoff.call(this._connectAttempt, url, (err, ws) => {
        if (err) {
          logger.error(`UserAgentClient: ${err}`);
        } else if (ws) {
          this.ws = ws;
          this._connected = true;
          resolve(this);
        }
      });
      call.setStrategy(new backoff.ExponentialStrategy({
        initialDelay: 50,
        maxDelay: 10000,
      }));
      call.start();
    });

    await this._connect;

    this.ws.on('message', (data) => {
      data = JSON.parse(data);
      const message = data.message;
      delete data.message;
      this.emit(message, data);
    });

    this.emit('connected');

    return this._connect;
  }

  _connectAttempt(url, callback) {
    // Use promises here so we only get one firing over the callback
    // per attempt, but pipe into the callback for compatibility with
    // `backoff` module.
    const attempt = new Promise((resolve, reject) => {
      const ws = new WebSocket(url);
      ws.on('error', reject);
      ws.on('open', () => {
        // The first message should be protocol information
        ws.once('message', (data) => {
          data = JSON.parse(data);

          if (data.message !== 'protocol' || data.version !== 'v1') {
            reject(new Error(`Incorrect message ${JSON.stringify(data)}`));
            return;
          }
          resolve(ws);
        });
      });
    });

    attempt.then(callback.bind(null, null), callback);
  }
}

export default UserAgentClient;
<|endoftext|>


<commit_before>/* globals compareTo */
var sortListAlphanumerically = function(src, sortIndex) {
  var $list = $(src).closest('.a-list-container').find('.a-list');
  var rows = $list.find('li:not(.a-list-header)');
  $(src).closest('.a-list-container').find('.a-list-sortHeader').removeClass('a-active');
  $(src).addClass('a-active');
  rows.sort(function(a, b) {
    var A = $($($($(a).children()[0]).children()[sortIndex]).find('.a-js-sortValue')[0]).text()
      .toUpperCase();
    var B = $($($($(b).children()[0]).children()[sortIndex]).find('.a-js-sortValue')[0]).text()
      .toUpperCase();
    return compareTo(A, B);
  });

  $.each(rows, function(index, row) {
    if ($(row).find('.a-js-sortValue').length > 0) {
      $list.append(row);
    }
  });

  $.each(rows, function(index, row) {
    if ($(row).find('.a-js-sortValue').length === 0) {
      $list.append(row);
    }
  });
};

var defaultListSort = function() {
  $('.a-list').each(function() {
    var sortHeader = $(this).find('.a-list-sortHeader')[0];
    var index = $(sortHeader).index();
    sortListAlphanumerically(sortHeader, index);
  });
};

var addListSortHandler = function() {
  $('.a-list-sortHeader').on('click', function() {
    var index = $(this).index();
    sortListAlphanumerically(this, index);
  });

  defaultListSort();
};
<commit_msg>small fix for list sort<commit_after>/* globals compareTo */
var sortListAlphanumerically = function(src, sortIndex) {
  var $list = $(src).closest('.a-list-container').find('.a-list');
  var rows = $list.find('li:not(.a-list-header)');
  $(src).closest('.a-list-container').find('.a-list-sortHeader').removeClass('a-active');
  $(src).addClass('a-active');
  rows.sort(function(a, b) {
    var A = $($($($(a).children()[0]).children()[sortIndex]).find('.a-js-sortValue')[0]).text()
      .toUpperCase();
    var B = $($($($(b).children()[0]).children()[sortIndex]).find('.a-js-sortValue')[0]).text()
      .toUpperCase();
    return compareTo(A, B);
  });

  $.each(rows, function(index, row) {
    if ($(row).find('.a-js-sortValue').length > 0) {
      $list.append(row);
    }
  });

  $.each(rows, function(index, row) {
    if ($(row).find('.a-js-sortValue').length === 0) {
      $list.append(row);
    }
  });
};

var defaultListSort = function() {
  $('.a-list-container').each(function() {
    var sortHeader = $(this).find('.a-list-sortHeader')[0];
    var index = $(sortHeader).index();
    sortListAlphanumerically(sortHeader, index);
  });
};

var addListSortHandler = function() {
  $('.a-list-sortHeader').on('click', function() {
    var index = $(this).index();
    sortListAlphanumerically(this, index);
  });

  defaultListSort();
};
<|endoftext|>


<commit_before>import { asap, isDev } from './utils'
import proc from './proc'
import emitter from './emitter'
import { MONITOR_ACTION } from './monitorActions'
import SagaCancellationException from './SagaCancellationException'

export const RUN_SAGA_DYNAMIC_ERROR = 'Before running a Saga dynamically using middleware.run, you must mount the Saga middleware on the Store using applyMiddleware'

export default function sagaMiddlewareFactory(...sagas) {
  let runSagaDynamically

  function sagaMiddleware({getState, dispatch}) {

    const sagaEmitter = emitter()
    const monitor = isDev ? action => asap(() => dispatch(action)) : undefined

    function runSaga(saga, ...args) {
      return proc(
        saga(getState, ...args),
        sagaEmitter.subscribe,
        dispatch,
        monitor,
        0,
        saga.name
      )
    }

    runSagaDynamically = runSaga

    sagas.forEach(runSaga)

    return next => action => {
      const result = next(action) // hit reducers
      // filter out monitor actions to avoid endless loop
      // see https://github.com/yelouafi/redux-saga/issues/61
      if(!action[MONITOR_ACTION])
        sagaEmitter.emit(action)
      return result;
    }
  }

  sagaMiddleware.run = (saga, ...args) => {
    if(!runSagaDynamically) {
      throw new Error(RUN_SAGA_DYNAMIC_ERROR)
    }
    const task = runSagaDynamically(saga, ...args)
    task.done.catch(err => {
      if(!(err instanceof SagaCancellationException))
        throw err
    })
    return task
  }

  return sagaMiddleware
}
<commit_msg>provide generators with getState param<commit_after>import { asap, isDev } from './utils'
import proc from './proc'
import emitter from './emitter'
import { MONITOR_ACTION } from './monitorActions'
import SagaCancellationException from './SagaCancellationException'

export const RUN_SAGA_DYNAMIC_ERROR = 'Before running a Saga dynamically using middleware.run, you must mount the Saga middleware on the Store using applyMiddleware'

export default function sagaMiddlewareFactory(...sagas) {
  let runSagaDynamically

  function sagaMiddleware({getState, dispatch}) {

    const sagaEmitter = emitter()
    const monitor = isDev ? action => asap(() => dispatch(action)) : undefined

    function runSaga(saga, ...args) {
      return proc(
        saga(getState, ...args),
        sagaEmitter.subscribe,
        dispatch,
        getState,
        monitor,
        0,
        saga.name
      )
    }

    runSagaDynamically = runSaga

    sagas.forEach(runSaga)

    return next => action => {
      const result = next(action) // hit reducers
      // filter out monitor actions to avoid endless loop
      // see https://github.com/yelouafi/redux-saga/issues/61
      if(!action[MONITOR_ACTION])
        sagaEmitter.emit(action)
      return result;
    }
  }

  sagaMiddleware.run = (saga, ...args) => {
    if(!runSagaDynamically) {
      throw new Error(RUN_SAGA_DYNAMIC_ERROR)
    }
    const task = runSagaDynamically(saga, ...args)
    task.done.catch(err => {
      if(!(err instanceof SagaCancellationException))
        throw err
    })
    return task
  }

  return sagaMiddleware
}
<|endoftext|>


<commit_before>/// <reference path="Chunck.js" />
/// <reference path="BoundingBox.js" />
/// <reference path="gl-Matrix.js" />
function Quadtree(option)
{
    this.initialRootSize = option.initialRootSize;

    this.chunck = new Chunck(option.chunckSize);
    this.chunck.create();
    this.nodeCenter = vec3.create();

    this.initialtexturePath = option.initialtexturePath;
    this.initialElevationPath = option.initialElevationPath;

    this.rootNode = new QuadtreeNode(vec3.create([0, 0, 0]), option.initialRootSize, vec3.create([255, 0, 0]), vec3.create([0, 0, 0]), "", option.quadtreeDepth, "", "-1",undefined, this.chunck.bbox);

    this._build(this.rootNode);
    this._Wms = new Wms(option.initialRootSize);
    this.counter = 0;

};

Quadtree.prototype =
{
    _build: function (node)
    {
        if (node.depth > 1)
        {
            this._addNode(node);

            for (var i = 0; i < 4; i++)
            {
                this._build(node.child[i]);
            }
        }
    },

    _removeChilds : function(node) {
        node.child = [];
    },

    _addNode: function (node)
    {
        var scaling = node.scaleFactor * 0.5;

        var centerUpperLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, scaling]), centerUpperLeft);

        var centerUpperRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, scaling]), centerUpperRight);

        var centerLowerLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, -scaling]), centerLowerLeft);

        var centerLowerRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, -scaling]), centerLowerRight);

        var upperLeft  = new QuadtreeNode(centerUpperLeft, scaling, vec3.create([255, 0, 0]), centerUpperLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 2, node, this.chunck.bbox, node.elevation);
        var upperRight = new QuadtreeNode(centerUpperRight, scaling, vec3.create([0, 255, 0]), centerUpperRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 3, node, this.chunck.bbox, node.elevation);
        var lowerLeft  = new QuadtreeNode(centerLowerLeft, scaling, vec3.create([0, 0, 255]), centerLowerLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 0, node, this.chunck.bbox, node.elevation);
        var lowerRight = new QuadtreeNode(centerLowerRight, scaling, vec3.create([255, 0, 255]), centerLowerRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 1, node, this.chunck.bbox, node.elevation);

        node.child[0] = upperLeft;
        node.child[1] = upperRight;
        node.child[2] = lowerLeft;
        node.child[3] = lowerRight;

        node.type = 1;

    },

    setMatrixUniforms : function(projMatrix, viewMatrix, spherify, camera)
    {
        this.chunck.setMatrixUniforms(projMatrix, viewMatrix, spherify, camera);
    },

    setBBoxMatrixUniforms: function (projMatrix, viewMatrix)
    {
        this.chunck.setBBoxMatrixUniforms(projMatrix, viewMatrix);
    },

    setProgram: function ()
    {
        this.chunck.setProgram();
    },

    setBBoxProgram : function() {
        this.chunck.setBBoxProgram();
    },

    disableProgram: function ()
    {
        this.chunck.disableProgram();
    },

    //node.type == 2 ---->leaf
    draw: function (wireframe, frustum, node, ext, delta, tile, Wms) {

        if (node === undefined)
        {
            return;
        }

        if(!frustum.isBoxInsideFrustum(node.bbox)){
            node.type = 2;
            node.child = [];
            return;
        }

        if(frustum.isBoxInsideFrustum(node.bbox) && node.child.length < 4){
            this._addNode(node);
        }

        this.nodeCenter = node.center;
        this.chunckDistFromCamera = Math.sqrt((frustum.position[0] - this.nodeCenter[0]) * (frustum.position[0] - this.nodeCenter[0]) +
                                              (frustum.position[1] - this.nodeCenter[1]) * (frustum.position[1] - this.nodeCenter[1]) +
                                              (frustum.position[2] - this.nodeCenter[2]) * (frustum.position[2] - this.nodeCenter[2]));

        if (this.chunckDistFromCamera > delta && node.type === 1) {

            if (tile !== node.initialtexturePath)
            {
                node.updateTexturePath(tile);
            }

            if (node.parent!== undefined
                && node.parent.child[0].textureLoaded && node.parent.child[0].elevationLoaded
                && node.parent.child[1].textureLoaded && node.parent.child[1].elevationLoaded
                && node.parent.child[2].textureLoaded && node.parent.child[2].elevationLoaded
                && node.parent.child[3].textureLoaded && node.parent.child[3].elevationLoaded) {

                this.chunck.prerender(node);
                this.chunck.draw(wireframe);
                return;
            }

            if (!node.textureLoaded  && this.counter < 6) {

                node.getTexture(ext, function ()
                {
                    if(node.texture.image ===null)
                        return;

                    node.textureLoaded = true;
                    node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                    node.texture.image = null;
                });
                this.counter++;
            }

            if (!node.elevationLoaded  && this.counter < 6) {
                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    if(node.elevation.image ===null)
                        return;

                    node.elevationLoaded = true;
                    node.elevation.image.removeEventListener("load", node.loadElevation, false);
                    node.elevation.image = null;
                });

                this.counter++;
            }

            //Blurring
            if ((!node.elevationLoaded || !node.textureLoaded) && node.type === 1)
                this.draw(wireframe, frustum, node.parent, ext, delta , tile, Wms);

        }
        else
        {
            if (node.type !== 1)
            {
                //Blurring
                this.draw(wireframe, frustum, node.parent, ext, delta , tile, Wms);

                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    this._addNode(node);

                }.bind(this));

                this.counter++;
            }
            else if(node.type === 1 && node.child.length > 0)
            {
                for (var i = 0; i < 4; i++)
                {
                    this.draw(wireframe, frustum, node.child[i], ext, delta/2.0, tile, Wms);
                }
            }
        }
    }
};<commit_msg>optimizations<commit_after>/// <reference path="Chunck.js" />
/// <reference path="BoundingBox.js" />
/// <reference path="gl-Matrix.js" />
function Quadtree(option)
{
    this.initialRootSize = option.initialRootSize;

    this.chunck = new Chunck(option.chunckSize);
    this.chunck.create();
    this.nodeCenter = vec3.create();

    this.initialtexturePath = option.initialtexturePath;
    this.initialElevationPath = option.initialElevationPath;

    this.rootNode = new QuadtreeNode(vec3.create([0, 0, 0]), option.initialRootSize, vec3.create([255, 0, 0]), vec3.create([0, 0, 0]), "", option.quadtreeDepth, "", "-1",undefined, this.chunck.bbox);

    this._build(this.rootNode);
    this._Wms = new Wms(option.initialRootSize);
    this.counter = 0;

};

Quadtree.prototype =
{
    _build: function (node)
    {
        if (node.depth > 1)
        {
            this._addNode(node);

            for (var i = 0; i < 4; i++)
            {
                this._build(node.child[i]);
            }
        }
    },

    _removeChilds : function(node) {
        node.child = [];
    },

    _addNode: function (node)
    {
        var scaling = node.scaleFactor * 0.5;

        var centerUpperLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, scaling]), centerUpperLeft);

        var centerUpperRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, scaling]), centerUpperRight);

        var centerLowerLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, -scaling]), centerLowerLeft);

        var centerLowerRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, -scaling]), centerLowerRight);

        var upperLeft  = new QuadtreeNode(centerUpperLeft, scaling, vec3.create([255, 0, 0]), centerUpperLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 2, node, this.chunck.bbox, node.elevation);
        var upperRight = new QuadtreeNode(centerUpperRight, scaling, vec3.create([0, 255, 0]), centerUpperRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 3, node, this.chunck.bbox, node.elevation);
        var lowerLeft  = new QuadtreeNode(centerLowerLeft, scaling, vec3.create([0, 0, 255]), centerLowerLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 0, node, this.chunck.bbox, node.elevation);
        var lowerRight = new QuadtreeNode(centerLowerRight, scaling, vec3.create([255, 0, 255]), centerLowerRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 1, node, this.chunck.bbox, node.elevation);

        node.child[0] = upperLeft;
        node.child[1] = upperRight;
        node.child[2] = lowerLeft;
        node.child[3] = lowerRight;

        node.type = 1;

    },

    setMatrixUniforms : function(projMatrix, viewMatrix, spherify, camera)
    {
        this.chunck.setMatrixUniforms(projMatrix, viewMatrix, spherify, camera);
    },

    setBBoxMatrixUniforms: function (projMatrix, viewMatrix)
    {
        this.chunck.setBBoxMatrixUniforms(projMatrix, viewMatrix);
    },

    setProgram: function ()
    {
        this.chunck.setProgram();
    },

    setBBoxProgram : function() {
        this.chunck.setBBoxProgram();
    },

    disableProgram: function ()
    {
        this.chunck.disableProgram();
    },

    //node.type == 2 ---->leaf
    draw: function (wireframe, frustum, node, ext, delta, tile, Wms) {

        if (node === undefined)
        {
            return;
        }

        if(!frustum.isBoxInsideFrustum(node.bbox)){
            node.type = 2;
            node.child = [];

            if(node.texture!==null && node.texture.image!==null)
            {
                node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                node.texture.image = null;
            }

            if(node.elevation!==null && node.elevation.image!==null)
            {
                node.elevation.image.removeEventListener("load",node.loadElevation, false);
                node.elevation.image = null;
            }

            return;
        }

        if(frustum.isBoxInsideFrustum(node.bbox) && node.child.length < 4){
            this._addNode(node);
        }

        this.nodeCenter = node.center;
        this.chunckDistFromCamera = Math.sqrt((frustum.position[0] - this.nodeCenter[0]) * (frustum.position[0] - this.nodeCenter[0]) +
                                              (frustum.position[1] - this.nodeCenter[1]) * (frustum.position[1] - this.nodeCenter[1]) +
                                              (frustum.position[2] - this.nodeCenter[2]) * (frustum.position[2] - this.nodeCenter[2]));

        if (this.chunckDistFromCamera > delta && node.type === 1) {

            if (tile !== node.initialtexturePath)
            {
                node.updateTexturePath(tile);
            }

            if (node.parent!== undefined
                && node.parent.child[0].textureLoaded && node.parent.child[0].elevationLoaded
                && node.parent.child[1].textureLoaded && node.parent.child[1].elevationLoaded
                && node.parent.child[2].textureLoaded && node.parent.child[2].elevationLoaded
                && node.parent.child[3].textureLoaded && node.parent.child[3].elevationLoaded) {

                this.chunck.prerender(node);
                this.chunck.draw(wireframe);
                return;
            }

            if (!node.textureLoaded  && this.counter < 6) {

                node.getTexture(ext, function ()
                {
                    if(node.texture.image ===null)
                        return;

                    node.textureLoaded = true;
                    node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                    node.texture.image = null;
                });
                this.counter++;
            }

            if (!node.elevationLoaded  && this.counter < 6) {
                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    if(node.elevation.image ===null)
                        return;

                    node.elevationLoaded = true;
                    node.elevation.image.removeEventListener("load", node.loadElevation, false);
                    node.elevation.image = null;
                });

                this.counter++;
            }

            //Blurring
            if ((!node.elevationLoaded || !node.textureLoaded) && node.type === 1)
                this.draw(wireframe, frustum, node.parent, ext, delta , tile, Wms);

        }
        else
        {
            if (node.type !== 1)
            {
                //Blurring
                this.draw(wireframe, frustum, node.parent, ext, delta , tile, Wms);

                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    this._addNode(node);

                }.bind(this));

                this.counter++;
            }
            else if(node.type === 1 && node.child.length > 0)
            {
                for (var i = 0; i < 4; i++)
                {
                    this.draw(wireframe, frustum, node.child[i], ext, delta/2.0, tile, Wms);
                }
            }
        }
    }
};<|endoftext|>


<commit_before>/*
 * Address field
 * https://github.com/tableau-mkt/jquery.addressfield
 *
 * Licensed under the GPL-2.0 license.
 */

(function ($) {

  /**
   * Modifies an address field for this wrapped set of fields, given a config
   * representing how the country writes its addresses (conforming roughly to
   * xNAL standards), and an array of fields you desire to show (again, roughly
   * xNAL compatible).
   */
  $.fn.addressfield = function(config, enabled_fields) {
    var $container = $(this),
      field_order = [],
      $element,
      field;

    // Iterate through defined address fields for this country.
    for (field in config) {
      // Account for non-field attributes within the configuration.
      if (typeof config[field] === 'object') {
        // Pick out the existing elements for the given field.
        $element = $container.find('.' + field);

        // Account for nested fields.
        if (!config[field].hasOwnProperty('label')) {
          return $.fn.addressfield.call($element, config[field], enabled_fields);
        }
        // Otherwise perform the usual actions.
        else {
          // When swapping out labels / values for existing fields.
          // Ensure the element exists and is configured to be displayed.
          if ($element.length && $.inArray(field, enabled_fields) !== -1) {
            // Push this field onto the field_order array.
            field_order.push(field);

            // Update the options.
            if (typeof config[field].options !== 'undefined') {
              // If this field has options but it's currently a text field,
              // convert it back to a select field.
              if (!$element.is('select')) {
                $element = $.fn.addressfield.convertToSelect.call($element);
              }
              $.fn.addressfield.updateOptions.call($element, config[field].options);
            }
            else {
              // If this field does not have options but it's currently a select
              // field, convert it back to a text field.
              if ($element.is('select')) {
                $element = $.fn.addressfield.convertToText.call($element);
              }
            }

            // Update the label.
            $.fn.addressfield.updateLabel.call($element, config[field].label);
          }

          // When adding fields that didn't previously exist.
          if ($element.not(':visible') && $.inArray(field, enabled_fields) !== -1) {
            $.fn.addressfield.showField.call($element);
          }
        }
      }
    }

    // Now check for fields that are still on the page but shouldn't be.
    $.each(enabled_fields, function (index, field) {
      var $element = $container.find('.' + field);
      if ($element.length && !config.hasOwnProperty(field)) {
        $.fn.addressfield.hideField.call($element);
      }
    });

    // Now ensure the fields are in their given order.
    $.fn.addressfield.orderFields.call($container, field_order);

    return this;
  };

  /**
   * Updates a given field's label with a given label.
   */
  $.fn.addressfield.updateLabel = function (label) {
    if ($(this).prev('label').length) {
      $(this).prev('label').text(label);
    }
  };

  /**
   * Updates a given select field's options with given options.
   */
  $.fn.addressfield.updateOptions = function (options) {
    var $self = $(this),
        oldVal = $self.data('_saved') || $self.val();

    $self.children('option').remove();
    $.each(options, function (value, label) {
      $self.append($('<option></option>').attr('value', value).text(label));
    });

    // Ensure the old value is still reflected after options are updated.
    $self.val(oldVal).change();

    // Clean up the data attribute; no-op if it was not previously populated.
    $self.removeData('_saved');
  };

  /**
   * Converts a given select field to a regular textarea.
   */
  $.fn.addressfield.convertToText = function () {
    var $self = $(this),
        $input = $('<input />').attr('type', 'text');

    $.each($self[0].attributes, function () {
      if ($.inArray(this.name, ['class', 'id', 'name']) !== -1) {
        $input.attr(this.name, this.value);
      }
    });

    // Ensure the old value is still reflected after conversion.
    $input.val($self.val());

    // Replace the existing element with our new one; also return it.
    $self.replaceWith($input);
    return $input;
  };

  /**
   * Converts a given input field to a select field.
   */
  $.fn.addressfield.convertToSelect = function() {
    var $self = $(this),
        $select = $('<select></select>');

    $.each($self[0].attributes, function () {
      if ($.inArray(this.name, ['class', 'id', 'name']) !== -1) {
        $select.attr(this.name, this.value);
      }
    });

    // Save the old input value to a data attribute, for use in updateOptions.
    $select.data('_saved', $self.val());

    // Replace the existing element with our new one; also return it.
    $self.replaceWith($select);
    return $select;
  };

  /**
   * Hides the field, but stores it for restoration later, if necessary.
   */
  $.fn.addressfield.hideField = function() {
    $(this).val('');
    $(this).parent().hide();
  };

  /**
   * Shows / restores the field that had been previously hidden.
   */
  $.fn.addressfield.showField = function() {
    $(this).parent().show();
  };

  /**
   * Re-orders fields given an array of class names representing fields. Note
   * that this can be called recursively if one of the values passed in the
   * order array is itself an array.
   */
  $.fn.addressfield.orderFields = function(order) {
    var length = order.length,
      i = 0,
      $element;

    // Iterate through the fields to be ordered.
    for (i; i < length; ++i) {
      if (i in order) {
        // Save off the element container over its class selector in order.
        $element = $(this).find('.' + order[i]).parent('div, section');
        order[i] = {
          'element': $element.clone(),
          'class': order[i],
          'value': $(this).find('.' + order[i]).val()
        };

        // Remove the original element from the page.
        $element.remove();
      }
    }

    // Elements have been saved off in order and removed. Now, add them back in
    // the correct order.
    for (i = 0; i < length; ++i) {
      if (i in order) {
        $element = $(this).append(order[i].element);

        // The clone process doesn't seem to copy input values; apply that here.
        $element.find('.' + order[i]['class']).val(order[i].value).change();
      }
    }
  };

}(jQuery));
<commit_msg>Updates to the updateLabel method to support the label "for" attribute.<commit_after>/*
 * Address field
 * https://github.com/tableau-mkt/jquery.addressfield
 *
 * Licensed under the GPL-2.0 license.
 */

(function ($) {

  /**
   * Modifies an address field for this wrapped set of fields, given a config
   * representing how the country writes its addresses (conforming roughly to
   * xNAL standards), and an array of fields you desire to show (again, roughly
   * xNAL compatible).
   */
  $.fn.addressfield = function(config, enabled_fields) {
    var $container = $(this),
      field_order = [],
      $element,
      field;

    // Iterate through defined address fields for this country.
    for (field in config) {
      // Account for non-field attributes within the configuration.
      if (typeof config[field] === 'object') {
        // Pick out the existing elements for the given field.
        $element = $container.find('.' + field);

        // Account for nested fields.
        if (!config[field].hasOwnProperty('label')) {
          return $.fn.addressfield.call($element, config[field], enabled_fields);
        }
        // Otherwise perform the usual actions.
        else {
          // When swapping out labels / values for existing fields.
          // Ensure the element exists and is configured to be displayed.
          if ($element.length && $.inArray(field, enabled_fields) !== -1) {
            // Push this field onto the field_order array.
            field_order.push(field);

            // Update the options.
            if (typeof config[field].options !== 'undefined') {
              // If this field has options but it's currently a text field,
              // convert it back to a select field.
              if (!$element.is('select')) {
                $element = $.fn.addressfield.convertToSelect.call($element);
              }
              $.fn.addressfield.updateOptions.call($element, config[field].options);
            }
            else {
              // If this field does not have options but it's currently a select
              // field, convert it back to a text field.
              if ($element.is('select')) {
                $element = $.fn.addressfield.convertToText.call($element);
              }
            }

            // Update the label.
            $.fn.addressfield.updateLabel.call($element, config[field].label);
          }

          // When adding fields that didn't previously exist.
          if ($element.not(':visible') && $.inArray(field, enabled_fields) !== -1) {
            $.fn.addressfield.showField.call($element);
          }
        }
      }
    }

    // Now check for fields that are still on the page but shouldn't be.
    $.each(enabled_fields, function (index, field) {
      var $element = $container.find('.' + field);
      if ($element.length && !config.hasOwnProperty(field)) {
        $.fn.addressfield.hideField.call($element);
      }
    });

    // Now ensure the fields are in their given order.
    $.fn.addressfield.orderFields.call($container, field_order);

    return this;
  };

  /**
   * Updates a given field's label with a given label.
   */
  $.fn.addressfield.updateLabel = function (label) {
    var $this = $(this),
        $previous = $this.prev('label'),
        elementName = $this.attr('id'),
        $label = $('label[for="' + elementName + '"]');

    if ($label.length) {
      $label.text(label);
    }
    else if ($previous.length) {
      $previous.text(label);
    }
  };

  /**
   * Updates a given select field's options with given options.
   */
  $.fn.addressfield.updateOptions = function (options) {
    var $self = $(this),
        oldVal = $self.data('_saved') || $self.val();

    $self.children('option').remove();
    $.each(options, function (value, label) {
      $self.append($('<option></option>').attr('value', value).text(label));
    });

    // Ensure the old value is still reflected after options are updated.
    $self.val(oldVal).change();

    // Clean up the data attribute; no-op if it was not previously populated.
    $self.removeData('_saved');
  };

  /**
   * Converts a given select field to a regular textarea.
   */
  $.fn.addressfield.convertToText = function () {
    var $self = $(this),
        $input = $('<input />').attr('type', 'text');

    $.each($self[0].attributes, function () {
      if ($.inArray(this.name, ['class', 'id', 'name']) !== -1) {
        $input.attr(this.name, this.value);
      }
    });

    // Ensure the old value is still reflected after conversion.
    $input.val($self.val());

    // Replace the existing element with our new one; also return it.
    $self.replaceWith($input);
    return $input;
  };

  /**
   * Converts a given input field to a select field.
   */
  $.fn.addressfield.convertToSelect = function() {
    var $self = $(this),
        $select = $('<select></select>');

    $.each($self[0].attributes, function () {
      if ($.inArray(this.name, ['class', 'id', 'name']) !== -1) {
        $select.attr(this.name, this.value);
      }
    });

    // Save the old input value to a data attribute, for use in updateOptions.
    $select.data('_saved', $self.val());

    // Replace the existing element with our new one; also return it.
    $self.replaceWith($select);
    return $select;
  };

  /**
   * Hides the field, but stores it for restoration later, if necessary.
   */
  $.fn.addressfield.hideField = function() {
    $(this).val('');
    $(this).parent().hide();
  };

  /**
   * Shows / restores the field that had been previously hidden.
   */
  $.fn.addressfield.showField = function() {
    $(this).parent().show();
  };

  /**
   * Re-orders fields given an array of class names representing fields. Note
   * that this can be called recursively if one of the values passed in the
   * order array is itself an array.
   */
  $.fn.addressfield.orderFields = function(order) {
    var length = order.length,
      i = 0,
      $element;

    // Iterate through the fields to be ordered.
    for (i; i < length; ++i) {
      if (i in order) {
        // Save off the element container over its class selector in order.
        $element = $(this).find('.' + order[i]).parent('div, section');
        order[i] = {
          'element': $element.clone(),
          'class': order[i],
          'value': $(this).find('.' + order[i]).val()
        };

        // Remove the original element from the page.
        $element.remove();
      }
    }

    // Elements have been saved off in order and removed. Now, add them back in
    // the correct order.
    for (i = 0; i < length; ++i) {
      if (i in order) {
        $element = $(this).append(order[i].element);

        // The clone process doesn't seem to copy input values; apply that here.
        $element.find('.' + order[i]['class']).val(order[i].value).change();
      }
    }
  };

}(jQuery));
<|endoftext|>


<commit_before>/**
 * @fileoverview Line chart
 * @author NHN Ent.
 *         FE Development Team <dl_javascript@nhnent.com>
 */

'use strict';

var AxisTypeBase = require('./axisTypeBase.js'),
    calculator = require('../helpers/calculator.js'),
    dataConverter = require('../helpers/dataConverter.js'),
    boundsMaker = require('../helpers/boundsMaker.js'),
    axisDataMaker = require('../helpers/axisDataMaker.js'),
    Series = require('../series/LineChartSeries.js');

var LineChart = ne.util.defineClass(AxisTypeBase, /** @lends LineChart.prototype */ {
    /**
     * Line chart.
     * * @constructs LineChart
     * @param {array.<array>} userData chart data
     * @param {object} theme chart theme
     * @param {object} options chart options
     */
    init: function(userData, theme, options) {
        var convertData = dataConverter.convert(userData, options.chart),
            bounds = boundsMaker.make({
                convertData: convertData,
                theme: theme,
                isVertical: true,
                options: options
            }),
            vAxisData, hAxisData;

        AxisTypeBase.call(this, bounds, theme, options);

        vAxisData = axisDataMaker.makeValueAxisData({
            values: convertData.values,
            seriesDimension: bounds.series.dimension,
            stacked: options.series && options.series.stacked || '',
            chartType: options.chartType,
            formatFunctions: convertData.formatFunctions,
            options: options.hAxis,
            isVertical: true
        });

        hAxisData = axisDataMaker.makeLabelAxisData({
            labels: convertData.labels
        });

        this.className = 'ne-line-chart';

        this.addAxisComponents({
            convertData: convertData,
            axes: {
                vAxis: vAxisData,
                hAxis: hAxisData
            },
            plotData: {
                vTickCount: vAxisData.validTickCount,
                hTickCount: hAxisData.validTickCount
            },
            Series: Series,
            seriesData: {
                values: calculator.arrayPivot(convertData.values),
                formattedValues: calculator.arrayPivot(convertData.formattedValues),
                scale: vAxisData.scale
            },
            axisScale: vAxisData.scale,
            isVertical: true,
            options: options
        });
    },

    /**
     * Attach custom event
     * @private
     */
    _attachCustomEvent: function() {
        var tooltip = this.componentMap.tooltip,
            series = this.componentMap.series;
        tooltip.on('showDot', series.onShowDot, series);
        tooltip.on('hideDot', series.onHideDot, series);
        AxisTypeBase.prototype._attachCustomEvent.apply(this);
    }
});

module.exports = LineChart;<commit_msg>Fixed cannot found error.<commit_after>/**
 * @fileoverview Line chart
 * @author NHN Ent.
 *         FE Development Team <dl_javascript@nhnent.com>
 */

'use strict';

var AxisTypeBase = require('./axisTypeBase.js'),
    calculator = require('../helpers/calculator.js'),
    dataConverter = require('../helpers/dataConverter.js'),
    boundsMaker = require('../helpers/boundsMaker.js'),
    axisDataMaker = require('../helpers/axisDataMaker.js'),
    Series = require('../series/lineChartSeries.js');

var LineChart = ne.util.defineClass(AxisTypeBase, /** @lends LineChart.prototype */ {
    /**
     * Line chart.
     * * @constructs LineChart
     * @param {array.<array>} userData chart data
     * @param {object} theme chart theme
     * @param {object} options chart options
     */
    init: function(userData, theme, options) {
        var convertData = dataConverter.convert(userData, options.chart),
            bounds = boundsMaker.make({
                convertData: convertData,
                theme: theme,
                isVertical: true,
                options: options
            }),
            vAxisData, hAxisData;

        AxisTypeBase.call(this, bounds, theme, options);

        vAxisData = axisDataMaker.makeValueAxisData({
            values: convertData.values,
            seriesDimension: bounds.series.dimension,
            stacked: options.series && options.series.stacked || '',
            chartType: options.chartType,
            formatFunctions: convertData.formatFunctions,
            options: options.hAxis,
            isVertical: true
        });

        hAxisData = axisDataMaker.makeLabelAxisData({
            labels: convertData.labels
        });

        this.className = 'ne-line-chart';

        this.addAxisComponents({
            convertData: convertData,
            axes: {
                vAxis: vAxisData,
                hAxis: hAxisData
            },
            plotData: {
                vTickCount: vAxisData.validTickCount,
                hTickCount: hAxisData.validTickCount
            },
            Series: Series,
            seriesData: {
                values: calculator.arrayPivot(convertData.values),
                formattedValues: calculator.arrayPivot(convertData.formattedValues),
                scale: vAxisData.scale
            },
            axisScale: vAxisData.scale,
            isVertical: true,
            options: options
        });
    },

    /**
     * Attach custom event
     * @private
     */
    _attachCustomEvent: function() {
        var tooltip = this.componentMap.tooltip,
            series = this.componentMap.series;
        tooltip.on('showDot', series.onShowDot, series);
        tooltip.on('hideDot', series.onHideDot, series);
        AxisTypeBase.prototype._attachCustomEvent.apply(this);
    }
});

module.exports = LineChart;<|endoftext|>


<commit_before>import React from 'react';

import SprkModal from './SprkModal';

export default {
  title: 'Components|Modal',
  parameters: { component: SprkModal },
};

export const defaultStory = () => (

Modal!

);

defaultStory.story = {
  name: 'Default',
};
<commit_msg>modal stories<commit_after>import React from 'react';

import SprkModal from './SprkModal';

export default {
  title: 'Components|Modal',
  parameters: { component: SprkModal },
};

export const defaultStory = () => (
  <SprkModal
    title="Default Modal"
    isVisible={true}
    confirmText="Yes please"
    cancelText="No thank you"
    confirmClick={() => {
      alert('confirm');
    }}
    cancelClick={() => {
      alert('cancel click');
    }}
  >
    Would you like to buy a mortgage?
  </SprkModal>
);

defaultStory.story = {
  name: 'Default',
};

export const infoStory = () => (
  <SprkModal
    title="Info Modal"
    isVisible={true}
    variant="info"
    confirmClick={() => {
      alert('confirm click');
    }}
    cancelClick={() => {
      alert('cancel click');
    }}
  >
    Your mortgage has been downloaded.
  </SprkModal>
);

infoStory.story = {
  name: 'Info',
};

defaultStory.story = {
  name: 'Default',
};

export const waitStory = () => (
  <SprkModal
    title="Wait Modal"
    isVisible={true}
    variant="wait"
  >
    This mortgage can only be closed with javascript
  </SprkModal>
);

waitStory.story = {
  name: 'Wait',
};
<|endoftext|>


<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import Button from './Button';
import Status from './icons/Status';
import CloseIcon from './icons/base/Close';
import CSSClassnames from '../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.TOAST;
const APP = CSSClassnames.APP;

const DURATION = 8000;
const ANIMATION_DURATION = 1000;

class ToastContents extends Component {

  constructor () {
    super();
    this._onClose = this._onClose.bind(this);
    this.state = {};
  }

  getChildContext () {
    return {
      history: this.props.history,
      intl: this.props.intl,
      router: this.props.router,
      store: this.props.store
    };
  }

  componentDidMount () {
    this._timer = setTimeout(this._onClose, DURATION);
  }

  _onClose () {
    const { onClose } = this.props;
    clearTimeout(this._timer);
    this._timer = undefined;
    this.setState({ closing: true });
    setTimeout(onClose, ANIMATION_DURATION);
  }

  render () {
    const { children, onClose, status } = this.props;
    const { closing } = this.state;

    const classNames = classnames(
      CLASS_ROOT, {
        [`${CLASS_ROOT}--closing`]: closing
      }
    );

    let statusIcon;
    if (status) {
      statusIcon = (
        <Status className={`${CLASS_ROOT}__status`} value={status} />
      );
    }

    let closeControl;
    if (onClose) {
      closeControl = (
        <Button className={`${CLASS_ROOT}__closer`}
          plain={true} onClick={this._onClose}>
          <CloseIcon />
        </Button>
      );
    }

    return (

        {statusIcon}
        <div className={`${CLASS_ROOT}__contents`}>
          {children}

        {closeControl}

    );
  }
}

ToastContents.propTypes = {
  history: PropTypes.object,
  intl: PropTypes.object,
  onClose: PropTypes.func,
  router: PropTypes.any,
  store: PropTypes.any
};

// Because Toast creates a new DOM render context, the context
// is not transfered. For now, we hard code these specific ones.
// TODO: Either figure out how to introspect the context and transfer
// whatever we find or have callers explicitly indicate which parts
// of the context to transfer somehow.
ToastContents.childContextTypes = {
  history: PropTypes.object,
  intl: PropTypes.object,
  router: PropTypes.any,
  store: PropTypes.object
};

export default class Toast extends Component {

  componentDidMount () {
    this._addLayer();
    this._renderLayer();
  }

  componentDidUpdate () {
    this._renderLayer();
  }

  componentWillUnmount () {
    this._removeLayer();
  }

  _addLayer () {
    const { id } = this.props;

    const element = document.createElement('div');
    if (id) {
      element.id = id;
    }
    element.className = `${CLASS_ROOT}__container`;
    // insert before .app, if possible.
    var appElements = document.querySelectorAll(`.${APP}`);
    var beforeElement;
    if (appElements.length > 0) {
      beforeElement = appElements[0];
    } else {
      beforeElement = document.body.firstChild;
    }
    if (beforeElement) {
      this._element =
        beforeElement.parentNode.insertBefore(element, beforeElement);
    }
  }

  _renderLayer () {
    if (this._element) {
      this._element.className = `${CLASS_ROOT}__container`;
      const contents = (
        <ToastContents {...this.props}
          history={this.context.history}
          intl={this.context.intl}
          router={this.context.router}
          store={this.context.store} />
      );
      ReactDOM.render(contents, this._element);
    }
  }

  _removeLayer () {
    ReactDOM.unmountComponentAtNode(this._element);
    this._element.parentNode.removeChild(this._element);
    this._element = null;
  }

  render () {
    return ();
  }
}

Toast.propTypes = {
  onClose: PropTypes.func,
  status: PropTypes.string
};
<commit_msg>Clear timeout if Toast was umounted from outside<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import Button from './Button';
import Status from './icons/Status';
import CloseIcon from './icons/base/Close';
import CSSClassnames from '../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.TOAST;
const APP = CSSClassnames.APP;

const DURATION = 8000;
const ANIMATION_DURATION = 1000;

class ToastContents extends Component {

  constructor () {
    super();
    this._onClose = this._onClose.bind(this);
    this.state = {};
  }

  getChildContext () {
    return {
      history: this.props.history,
      intl: this.props.intl,
      router: this.props.router,
      store: this.props.store
    };
  }

  componentWillUnmount () {
    clearTimeout(this._timer);
    this._timer = undefined;
  }

  componentDidMount () {
    this._timer = setTimeout(this._onClose, DURATION);
  }

  _onClose () {
    const { onClose } = this.props;
    clearTimeout(this._timer);
    this._timer = undefined;
    this.setState({ closing: true });
    setTimeout(onClose, ANIMATION_DURATION);
  }

  render () {
    const { children, onClose, status } = this.props;
    const { closing } = this.state;

    const classNames = classnames(
      CLASS_ROOT, {
        [`${CLASS_ROOT}--closing`]: closing
      }
    );

    let statusIcon;
    if (status) {
      statusIcon = (
        <Status className={`${CLASS_ROOT}__status`} value={status} />
      );
    }

    let closeControl;
    if (onClose) {
      closeControl = (
        <Button className={`${CLASS_ROOT}__closer`}
          plain={true} onClick={this._onClose}>
          <CloseIcon />
        </Button>
      );
    }

    return (

        {statusIcon}
        <div className={`${CLASS_ROOT}__contents`}>
          {children}

        {closeControl}

    );
  }
}

ToastContents.propTypes = {
  history: PropTypes.object,
  intl: PropTypes.object,
  onClose: PropTypes.func,
  router: PropTypes.any,
  store: PropTypes.any
};

// Because Toast creates a new DOM render context, the context
// is not transfered. For now, we hard code these specific ones.
// TODO: Either figure out how to introspect the context and transfer
// whatever we find or have callers explicitly indicate which parts
// of the context to transfer somehow.
ToastContents.childContextTypes = {
  history: PropTypes.object,
  intl: PropTypes.object,
  router: PropTypes.any,
  store: PropTypes.object
};

export default class Toast extends Component {

  componentDidMount () {
    this._addLayer();
    this._renderLayer();
  }

  componentDidUpdate () {
    this._renderLayer();
  }

  componentWillUnmount () {
    this._removeLayer();
  }

  _addLayer () {
    const { id } = this.props;

    const element = document.createElement('div');
    if (id) {
      element.id = id;
    }
    element.className = `${CLASS_ROOT}__container`;
    // insert before .app, if possible.
    var appElements = document.querySelectorAll(`.${APP}`);
    var beforeElement;
    if (appElements.length > 0) {
      beforeElement = appElements[0];
    } else {
      beforeElement = document.body.firstChild;
    }
    if (beforeElement) {
      this._element =
        beforeElement.parentNode.insertBefore(element, beforeElement);
    }
  }

  _renderLayer () {
    if (this._element) {
      this._element.className = `${CLASS_ROOT}__container`;
      const contents = (
        <ToastContents {...this.props}
          history={this.context.history}
          intl={this.context.intl}
          router={this.context.router}
          store={this.context.store} />
      );
      ReactDOM.render(contents, this._element);
    }
  }

  _removeLayer () {
    ReactDOM.unmountComponentAtNode(this._element);
    this._element.parentNode.removeChild(this._element);
    this._element = null;
  }

  render () {
    return ();
  }
}

Toast.propTypes = {
  onClose: PropTypes.func,
  status: PropTypes.string
};
<|endoftext|>