<commit_before>/* global angular */
/* global moment */
/* global navigator */
'use strict'; // jshint ignore:line

angular.module('lumx.date-picker', [])
    .controller('lxDatePickerController', ['$scope', '$timeout', '$window', function($scope, $timeout, $window)
    {
        var self = this,
            activeLocale,
            $datePicker,
            $datePickerFilter,
            $datePickerContainer,
            $computedWindow;

        $scope.ctrlData = {
            isOpen: false
        };

        this.init = function(element, locale)
        {
            $datePicker = element.find('.lx-date-picker');
            $datePickerContainer = element;
            $computedWindow = angular.element($window);

            self.build(locale, false);
        };

        this.build = function(locale, isNewModel)
        {
            if (locale === activeLocale && !isNewModel)
            {
                return;
            }

            activeLocale = locale;

            moment.locale(activeLocale);

            if (angular.isDefined($scope.model))
            {
                $scope.selected = {
                    model: moment($scope.model).format('LL'),
                    date: $scope.model
                };

                $scope.activeDate = moment($scope.model);
            }
            else
            {
                $scope.selected = {
                    model: undefined,
                    date: new Date()
                };

                $scope.activeDate = moment();
            }

            $scope.moment = moment;

            $scope.days = [];
            $scope.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)];

            $scope.years = [];

            for (var y = moment().year() - 100; y <= moment().year() + 100; y++)
            {
                $scope.years.push(y);
            }

            generateCalendar();
        };

        $scope.previousMonth = function()
        {
            $scope.activeDate = $scope.activeDate.subtract(1, 'month');
            generateCalendar();
        };

        $scope.nextMonth = function()
        {
            $scope.activeDate = $scope.activeDate.add(1, 'month');
            generateCalendar();
        };

        $scope.select = function(day)
        {
            $scope.selected = {
                model: day.format('LL'),
                date: day.toDate()
            };

            $scope.model = day.toDate();

            generateCalendar();
        };

        $scope.selectYear = function(year)
        {
            $scope.yearSelection = false;

            $scope.selected.model = moment($scope.selected.date).year(year).format('LL');
            $scope.selected.date = moment($scope.selected.date).year(year).toDate();
            $scope.model = moment($scope.selected.date).toDate();
            $scope.activeDate = $scope.activeDate.add(year - $scope.activeDate.year(), 'year');

            generateCalendar();
        };

        $scope.openPicker = function()
        {
            if ($scope.ctrlData.isOpen)
            {
                return;
            }

            $scope.ctrlData.isOpen = true;

            $timeout(function()
            {
                $scope.yearSelection = false;

                $datePickerFilter = angular.element('<div/>', {
                    class: 'lx-date-filter'
                });

                $datePickerFilter
                    .appendTo('body')
                    .on('click', function()
                    {
                        $scope.closePicker();
                    });

                $datePicker
                    .appendTo('body')
                    .show();

                $timeout(function()
                {
                    $datePickerFilter.addClass('lx-date-filter--is-shown');
                    $datePicker.addClass('lx-date-picker--is-shown');
                }, 100);
            });
        };

        $scope.closePicker = function()
        {
            if (!$scope.ctrlData.isOpen)
            {
                return;
            }

            $datePickerFilter.removeClass('lx-date-filter--is-shown');
            $datePicker.removeClass('lx-date-picker--is-shown');

            $computedWindow.off('resize');

            $timeout(function()
            {
                $datePickerFilter.remove();

                $datePicker
                    .hide()
                    .appendTo($datePickerContainer);

                $scope.ctrlData.isOpen = false;
            }, 600);
        };

        $scope.displayYearSelection = function()
        {
            $scope.yearSelection = true;

            $timeout(function()
            {
                var $yearSelector = $datePicker.find('.lx-date-picker__year-selector');
                var $activeYear = $yearSelector.find('.lx-date-picker__year--is-active');
                console.log($activeYear, $yearSelector.scrollTop(), $activeYear.position().top, $yearSelector.height(), $activeYear.height());
                $yearSelector.scrollTop($yearSelector.scrollTop() + $activeYear.position().top - $yearSelector.height()/2 + $activeYear.height()/2);
            });
        };

        $scope.clearDate = function()
        {
            $scope.model = undefined;
        };

        function generateCalendar()
        {
            var days = [],
                previousDay = angular.copy($scope.activeDate).date(0),
                firstDayOfMonth = angular.copy($scope.activeDate).date(1),
                lastDayOfMonth = angular.copy(firstDayOfMonth).endOf('month'),
                maxDays = angular.copy(lastDayOfMonth).date();

            $scope.emptyFirstDays = [];

            for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--)
            {
                $scope.emptyFirstDays.push({});
            }

            for (var j = 0; j < maxDays; j++)
            {
                var date = angular.copy(previousDay.add(1, 'days'));

                date.selected = angular.isDefined($scope.selected.model) && date.isSame($scope.selected.date, 'day');
                date.today = date.isSame(moment(), 'day');

                days.push(date);
            }

            $scope.emptyLastDays = [];

            for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--)
            {
                $scope.emptyLastDays.push({});
            }

            $scope.days = days;
        }
    }])
    .directive('lxDatePicker', function()
    {
        return {
            restrict: 'AE',
            controller: 'lxDatePickerController',
            scope: {
                model: '=',
                label: '@',
                fixedLabel: '&',
                allowClear: '@',
                icon: '@'
            },
            templateUrl: 'date-picker.html',
            link: function(scope, element, attrs, ctrl)
            {
                ctrl.init(element, checkLocale(attrs.locale));

                attrs.$observe('locale', function()
                {
                    ctrl.build(checkLocale(attrs.locale), false);
                });

                scope.$watch('model', function()
                {
                    ctrl.build(checkLocale(attrs.locale), true);
                });

                attrs.$observe('allowClear', function(newValue)
                {
                    scope.allowClear = !!(angular.isDefined(newValue) && newValue === 'true');
                });

                function checkLocale(locale)
                {
                    if (!locale)
                    {
                        return (navigator.language !== null ? navigator.language : navigator.browserLanguage).split("_")[0].split("-")[0] || 'en';
                    }

                    return locale;
                }
            }
        };
    });
<commit_msg>fix date picker: remove console log<commit_after>/* global angular */
/* global moment */
/* global navigator */
'use strict'; // jshint ignore:line

angular.module('lumx.date-picker', [])
    .controller('lxDatePickerController', ['$scope', '$timeout', '$window', function($scope, $timeout, $window)
    {
        var self = this,
            activeLocale,
            $datePicker,
            $datePickerFilter,
            $datePickerContainer,
            $computedWindow;

        $scope.ctrlData = {
            isOpen: false
        };

        this.init = function(element, locale)
        {
            $datePicker = element.find('.lx-date-picker');
            $datePickerContainer = element;
            $computedWindow = angular.element($window);

            self.build(locale, false);
        };

        this.build = function(locale, isNewModel)
        {
            if (locale === activeLocale && !isNewModel)
            {
                return;
            }

            activeLocale = locale;

            moment.locale(activeLocale);

            if (angular.isDefined($scope.model))
            {
                $scope.selected = {
                    model: moment($scope.model).format('LL'),
                    date: $scope.model
                };

                $scope.activeDate = moment($scope.model);
            }
            else
            {
                $scope.selected = {
                    model: undefined,
                    date: new Date()
                };

                $scope.activeDate = moment();
            }

            $scope.moment = moment;

            $scope.days = [];
            $scope.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)];

            $scope.years = [];

            for (var y = moment().year() - 100; y <= moment().year() + 100; y++)
            {
                $scope.years.push(y);
            }

            generateCalendar();
        };

        $scope.previousMonth = function()
        {
            $scope.activeDate = $scope.activeDate.subtract(1, 'month');
            generateCalendar();
        };

        $scope.nextMonth = function()
        {
            $scope.activeDate = $scope.activeDate.add(1, 'month');
            generateCalendar();
        };

        $scope.select = function(day)
        {
            $scope.selected = {
                model: day.format('LL'),
                date: day.toDate()
            };

            $scope.model = day.toDate();

            generateCalendar();
        };

        $scope.selectYear = function(year)
        {
            $scope.yearSelection = false;

            $scope.selected.model = moment($scope.selected.date).year(year).format('LL');
            $scope.selected.date = moment($scope.selected.date).year(year).toDate();
            $scope.model = moment($scope.selected.date).toDate();
            $scope.activeDate = $scope.activeDate.add(year - $scope.activeDate.year(), 'year');

            generateCalendar();
        };

        $scope.openPicker = function()
        {
            if ($scope.ctrlData.isOpen)
            {
                return;
            }

            $scope.ctrlData.isOpen = true;

            $timeout(function()
            {
                $scope.yearSelection = false;

                $datePickerFilter = angular.element('<div/>', {
                    class: 'lx-date-filter'
                });

                $datePickerFilter
                    .appendTo('body')
                    .on('click', function()
                    {
                        $scope.closePicker();
                    });

                $datePicker
                    .appendTo('body')
                    .show();

                $timeout(function()
                {
                    $datePickerFilter.addClass('lx-date-filter--is-shown');
                    $datePicker.addClass('lx-date-picker--is-shown');
                }, 100);
            });
        };

        $scope.closePicker = function()
        {
            if (!$scope.ctrlData.isOpen)
            {
                return;
            }

            $datePickerFilter.removeClass('lx-date-filter--is-shown');
            $datePicker.removeClass('lx-date-picker--is-shown');

            $computedWindow.off('resize');

            $timeout(function()
            {
                $datePickerFilter.remove();

                $datePicker
                    .hide()
                    .appendTo($datePickerContainer);

                $scope.ctrlData.isOpen = false;
            }, 600);
        };

        $scope.displayYearSelection = function()
        {
            $scope.yearSelection = true;

            $timeout(function()
            {
                var $yearSelector = $datePicker.find('.lx-date-picker__year-selector');
                var $activeYear = $yearSelector.find('.lx-date-picker__year--is-active');
                $yearSelector.scrollTop($yearSelector.scrollTop() + $activeYear.position().top - $yearSelector.height()/2 + $activeYear.height()/2);
            });
        };

        $scope.clearDate = function()
        {
            $scope.model = undefined;
        };

        function generateCalendar()
        {
            var days = [],
                previousDay = angular.copy($scope.activeDate).date(0),
                firstDayOfMonth = angular.copy($scope.activeDate).date(1),
                lastDayOfMonth = angular.copy(firstDayOfMonth).endOf('month'),
                maxDays = angular.copy(lastDayOfMonth).date();

            $scope.emptyFirstDays = [];

            for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--)
            {
                $scope.emptyFirstDays.push({});
            }

            for (var j = 0; j < maxDays; j++)
            {
                var date = angular.copy(previousDay.add(1, 'days'));

                date.selected = angular.isDefined($scope.selected.model) && date.isSame($scope.selected.date, 'day');
                date.today = date.isSame(moment(), 'day');

                days.push(date);
            }

            $scope.emptyLastDays = [];

            for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--)
            {
                $scope.emptyLastDays.push({});
            }

            $scope.days = days;
        }
    }])
    .directive('lxDatePicker', function()
    {
        return {
            restrict: 'AE',
            controller: 'lxDatePickerController',
            scope: {
                model: '=',
                label: '@',
                fixedLabel: '&',
                allowClear: '@',
                icon: '@'
            },
            templateUrl: 'date-picker.html',
            link: function(scope, element, attrs, ctrl)
            {
                ctrl.init(element, checkLocale(attrs.locale));

                attrs.$observe('locale', function()
                {
                    ctrl.build(checkLocale(attrs.locale), false);
                });

                scope.$watch('model', function()
                {
                    ctrl.build(checkLocale(attrs.locale), true);
                });

                attrs.$observe('allowClear', function(newValue)
                {
                    scope.allowClear = !!(angular.isDefined(newValue) && newValue === 'true');
                });

                function checkLocale(locale)
                {
                    if (!locale)
                    {
                        return (navigator.language !== null ? navigator.language : navigator.browserLanguage).split("_")[0].split("-")[0] || 'en';
                    }

                    return locale;
                }
            }
        };
    });
<|endoftext|>


<commit_before>/**
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */
(() => {
  const createSliceMetrics = () => {
    return {
      'accuracy': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/positive_rate@0.50': {
        'doubleValue': NaN,
      },
      'post_export_metrics/true_positive_rate@0.50': {
        'doubleValue': Math.random(),
      },
      'post_export_metrics/false_positive_rate@0.50': {
        'doubleValue': Math.random(),
      },
      'post_export_metrics/positive_rate@0.60': {
        'boundedValue': {
          'lowerBound': NaN,
          'upperBound': NaN,
          'value': NaN,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/true_positive_rate@0.60': {
        'doubleValue': Math.random(),
      },
      'post_export_metrics/false_positive_rate@0.60': {
        'doubleValue': Math.random(),
      },
      'post_export_metrics/example_count':
          {'doubleValue': Math.floor(Math.random() * 100)},
      'totalWeightedExamples': {'doubleValue': 2000 * (Math.random() + 0.8)}
    };
  };

  const SLICES = [
    'Overall', 'Slice:1', 'Slice:2', 'Slice:3', 'Slice:4', 'Slice:5', 'Slice:6',
    'Slice:7', 'Slice:8', 'Slice:9', 'Slice:10', 'Slice:11', 'Slice:12',
    'Slice:13', 'Slice:14', 'Slice:15', 'Slice:16'
  ];
  const input = SLICES.reduce((acc, slice) => {
    acc.push({
      'slice': slice,
      'sliceValue': slice.split(':')[1] || 'Overall',
      'metrics': createSliceMetrics(),
    });
    return acc;
  }, []);
  const input2 = SLICES.reduce((acc, slice) => {
    acc.push({
      'slice': slice,
      'sliceValue': slice.split(':')[1] || 'Overall',
      'metrics': createSliceMetrics(),
    });
    return acc;
  }, []);
  const element = document.getElementsByTagName('fairness-nb-container')[0];
  element.slicingMetrics = input;
  element.slicingMetricsCompare = input2;
  element.evalName = 'Eval1';
  element.evalNameCompare = 'Eval2';
  element.availbleEvaluationRuns = ['1', '2', '3'];
})();
<commit_msg>Update the demo to more situations.<commit_after>/**
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */
(() => {
  const createSliceMetrics1 = () => {
    return {
      'accuracy': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/positive_rate@0.50': {
        'doubleValue': NaN,
      },
      'post_export_metrics/negative_rate@0.50': {
        'doubleValue': Math.random(),
      },
      'post_export_metrics/positive_rate@0.60': {
        'boundedValue': {
          'lowerBound': NaN,
          'upperBound': NaN,
          'value': NaN,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/negative_rate@0.60': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/positive_rate@0.70': {
        'doubleValue': NaN,
      },
      'post_export_metrics/negative_rate@0.70': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/positive_rate@0.80': {
        'boundedValue': {
          'lowerBound': NaN,
          'upperBound': NaN,
          'value': NaN,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/negative_rate@0.80': {
        'doubleValue': Math.random(),
      },
      'post_export_metrics/example_count':
          {'doubleValue': Math.floor(Math.random() * 100)},
      'totalWeightedExamples': {'doubleValue': 2000 * (Math.random() + 0.8)},

      // These two metrics only exist inside this eval result
      'addtionalMetrics1': {'doubleValue': 2000 * (Math.random() + 0.8)},
      'addtionalMetrics2': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      }
    };
  };

  const createSliceMetrics2 = () => {
    return {
      'accuracy': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      // doubleValue NaN vs doubleValue NaN
      'post_export_metrics/positive_rate@0.50': {
        'doubleValue': NaN,
      },
      // doubleValue vs doubleValue
      'post_export_metrics/negative_rate@0.50': {
        'doubleValue': Math.random(),
      },
      // boundedValue NaN vs boundedValue NaN
      'post_export_metrics/positive_rate@0.60': {
        'boundedValue': {
          'lowerBound': NaN,
          'upperBound': NaN,
          'value': NaN,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      // boundedValue vs boundedValue
      'post_export_metrics/negative_rate@0.60': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      // Double NaN vs boundedValue
      'post_export_metrics/positive_rate@0.70': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      // boundedValue vs doubleValue
      'post_export_metrics/negative_rate@0.70': {
        'doubleValue': Math.random(),
      },
      // doubleValue NaN vs Double
      'post_export_metrics/positive_rate@0.80': {
        'doubleValue': Math.random(),

      },
      // doubleValue vs boundedValue
      'post_export_metrics/negative_rate@0.80': {
        'boundedValue': {
          'lowerBound': Math.random() * 0.3,
          'upperBound': Math.random() * 0.3 + 0.6,
          'value': Math.random() * 0.3 + 0.3,
          'methodology': 'POISSON_BOOTSTRAP'
        }
      },
      'post_export_metrics/example_count':
          {'doubleValue': Math.floor(Math.random() * 100)},
      'totalWeightedExamples': {'doubleValue': 2000 * (Math.random() + 0.8)}
    };
  };

  const SLICES = [
    'Overall', 'Slice:1', 'Slice:2', 'Slice:3', 'Slice:4', 'Slice:5', 'Slice:6',
    'Slice:7', 'Slice:8', 'Slice:9', 'Slice:10', 'Slice:11', 'Slice:12',
    'Slice:13', 'Slice:14', 'Slice:15', 'Slice:16'
  ];
  const input1 = SLICES.reduce((acc, slice) => {
    acc.push({
      'slice': slice,
      'sliceValue': slice.split(':')[1] || 'Overall',
      'metrics': createSliceMetrics1(),
    });
    return acc;
  }, []);
  const input2 = SLICES.reduce((acc, slice) => {
    acc.push({
      'slice': slice,
      'sliceValue': slice.split(':')[1] || 'Overall',
      'metrics': createSliceMetrics2(),
    });
    return acc;
  }, []);

  const element = document.getElementsByTagName('fairness-nb-container')[0];
  element.slicingMetrics = input1;
  element.slicingMetricsCompare = input2;
  element.evalName = 'Eval1';
  element.evalNameCompare = 'Eval2';
  element.availbleEvaluationRuns = ['1', '2', '3'];
})();
<|endoftext|>


<commit_before>module.exports = CommonJSFormatter;

var util = require("../util");
var t    = require("../types");

function CommonJSFormatter(file) {
  this.file = file;
}

CommonJSFormatter.prototype.import = function (node, nodes) {
  // import "foo";
  nodes.push(util.template("require", {
    MODULE_NAME: node.source.raw
  }, true));
};

CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
  var variableName = t.getSpecifierName(specifier);

  // import foo from "foo";
  if (specifier.default) {
    specifier.id = t.identifier("default");
  }

  var templateName = "require-assign";

  // import * as bar from "foo";
  if (specifier.type !== "ImportBatchSpecifier") templateName += "-key";

  nodes.push(util.template(templateName, {
    VARIABLE_NAME: variableName,
    MODULE_NAME:   node.source.raw,
    KEY:           specifier.id
  }));
};

CommonJSFormatter.prototype.export = function (node, nodes) {
  var declar = node.declaration;

  if (node.default) {
    var ref = declar;

    if (t.isClass(ref) || t.isFunction(ref)) {
      if (ref.id) {
        nodes.push(ref);
        ref = ref.id;
      }
    }

    nodes.push(util.template("exports-default", {
      VALUE: ref
    }, true));
  } else {
    var id = declar.id;
    if (t.isVariableDeclaration(declar)) {
      id = declar.declarations[0].id;
    }

    var assign = util.template("exports-assign", {
      VALUE: id,
      KEY:   id
    }, true);

    nodes.push(declar);

    if (t.isFunctionDeclaration(declar)) {
      assign._blockHoist = true;
    }

    nodes.push(assign);
  }
};

CommonJSFormatter.prototype._exportSpecifier = function (getRef, specifier, node, nodes) {
  var variableName = t.getSpecifierName(specifier);

  if (node.source) {
    if (t.isExportBatchSpecifier(specifier)) {
      // export * from "foo";
      nodes.push(util.template("exports-wildcard", {
        OBJECT: getRef()
      }, true));
    } else {
      // export { foo } from "test";
      nodes.push(util.template("exports-assign-key", {
        VARIABLE_NAME: variableName.name,
        OBJECT:        getRef(),
        KEY:           specifier.id
      }, true));
    }
  } else {
    // export { foo };
    nodes.push(util.template("exports-assign", {
      VALUE: specifier.id,
      KEY:   variableName
    }, true));
  }
};

CommonJSFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
  return this._exportSpecifier(function () {
    return t.callExpression(t.identifier("require"), [node.source]);
  }, specifier, node, nodes);
};
<commit_msg>combine export declaration assignments into variable declarations<commit_after>module.exports = CommonJSFormatter;

var util = require("../util");
var t    = require("../types");

function CommonJSFormatter(file) {
  this.file = file;
}

CommonJSFormatter.prototype.import = function (node, nodes) {
  // import "foo";
  nodes.push(util.template("require", {
    MODULE_NAME: node.source.raw
  }, true));
};

CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
  var variableName = t.getSpecifierName(specifier);

  // import foo from "foo";
  if (specifier.default) {
    specifier.id = t.identifier("default");
  }

  var templateName = "require-assign";

  // import * as bar from "foo";
  if (specifier.type !== "ImportBatchSpecifier") templateName += "-key";

  nodes.push(util.template(templateName, {
    VARIABLE_NAME: variableName,
    MODULE_NAME:   node.source.raw,
    KEY:           specifier.id
  }));
};

CommonJSFormatter.prototype.export = function (node, nodes) {
  var declar = node.declaration;

  if (node.default) {
    var ref = declar;

    if (t.isClass(ref) || t.isFunction(ref)) {
      if (ref.id) {
        nodes.push(ref);
        ref = ref.id;
      }
    }

    nodes.push(util.template("exports-default", {
      VALUE: ref
    }, true));
  } else {
    var assign;

    if (t.isVariableDeclaration(declar)) {
      var decl = declar.declarations[0]

      if (decl.init) {
        decl.init = util.template("exports-assign", {
          VALUE: decl.init,
          KEY:   decl.id
        });
      }

      nodes.push(declar);
    } else {
      assign = util.template("exports-assign", {
        VALUE: declar.id,
        KEY:   declar.id
      }, true);

      nodes.push(declar);
      nodes.push(assign);

      if (t.isFunctionDeclaration(declar)) {
        assign._blockHoist = true;
      }
    }
  }
};

CommonJSFormatter.prototype._exportSpecifier = function (getRef, specifier, node, nodes) {
  var variableName = t.getSpecifierName(specifier);

  if (node.source) {
    if (t.isExportBatchSpecifier(specifier)) {
      // export * from "foo";
      nodes.push(util.template("exports-wildcard", {
        OBJECT: getRef()
      }, true));
    } else {
      // export { foo } from "test";
      nodes.push(util.template("exports-assign-key", {
        VARIABLE_NAME: variableName.name,
        OBJECT:        getRef(),
        KEY:           specifier.id
      }, true));
    }
  } else {
    // export { foo };
    nodes.push(util.template("exports-assign", {
      VALUE: specifier.id,
      KEY:   variableName
    }, true));
  }
};

CommonJSFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
  return this._exportSpecifier(function () {
    return t.callExpression(t.identifier("require"), [node.source]);
  }, specifier, node, nodes);
};
<|endoftext|>


<commit_before>

// constructor for PacMan
function PacMan(xpos, ypos) {

	// shape
	this.diam = 80;
	this.radius = this.diam / 2;
	this.eyePos = this.diam / 7;
	this.eyeDiam = this.diam / 8;
	this.mouthAngle = (1/6);
	this.mouthChange = 1/128;

	//  position and movement
	this.xpos = xpos;
	this.ypos = ypos;
	this.direction = 0;
	this.change = 0;
	this.xChange = 0;
	this.yChange = 0;
	this.maxDirChange = 4;

	// timing
	this.curTime = 0;
	this.maxTime = 4;
	this.targetTime = random(this.maxTime);

}

PacMan.prototype.draw = function () {
	// call move
	this.timer();
	this.move();

	push();
	translate( this.xpos, this.ypos );

	// check direction
	if ( this.direction === 0 ) {
		// do nothing
	} else if ( this.direction === 1 ) {
		rotate(PI/2);
	} else if ( this.direction === 2 ) {
		scale(-1, 1);
	} else if ( this.direction === 3 ) {
		rotate(-PI/2);
	}

	// draw the pacman
	fill(color("Yellow"));
	arc( 0, 0, this.diam, this.diam, PI*this.mouthAngle, -PI*this.mouthAngle, PIE );

	fill(color("Black"));
	arc( this.eyePos, -this.eyePos * 2, this.eyeDiam, this.eyeDiam, PI*(1/6), -PI*(1/6), PIE );

	pop();
};

//  Moe Function
PacMan.prototype.move = function () {

	// update position
	this.xpos += this.xChange;
	this.ypos += this.yChange;

	//  mouth animation
	this.mouthAngle = this.mouthAngle + ( this.mouthChange * this.change);
	if( this.mouthAngle > (1/6) ){
		this.mouthChange = -this.mouthChange;
		this.mouthAngle = (1/6);
	}
	if( this.mouthAngle < 0.01 ){
		this.mouthChange = -this.mouthChange;
		this.mouthAngle = 0.03;
	}

	// edge check
	if( this.xpos+this.radius >= width ){
		this.xpos = width-this.radius;
		this.xChange = 0;
	} else if ( this.xpos-this.radius <= 0 ){
		this.xpos = 0+this.radius;
		this.xChange = 0;
	}

	if ( this.ypos+this.radius >= height ){
		this.ypos = height-this.radius;
		this.yChange = 0;
	} else if ( this.ypos-this.radius <= 0 ){
		this.ypos = 0+this.radius;
		this.yChange = 0;
	}
};

// Timer
PacMan.prototype.timer = function () {
	var curTime = this.curTime / frameRate();
	if ( curTime >= this.targetTime ){
		// change direction and update timer
		this.changeDirection();
	} else {
		this.curTime++;
	}
};

PacMan.prototype.changeDirection = function () {
	var newDirection;

	// reset timer
	this.curTime = 0;
	this.targetTime = random(this.maxTime);

	// choose a new direction
	do {
		newDirection = floor( random(4) );
	} while ( newDirection == this.direction );

	this.direction = newDirection;

	this.change = random(this.maxDirChange);
	if (newDirection === 0){
		// East
		this.xChange = this.change;
		this.yChange = 0;
	} else if (newDirection === 1){
		// South
		this.xChange = 0;
		this.yChange = this.change;
	} else if (newDirection === 2){
		// West
		this.xChange = -this.change;
		this.yChange = 0;
	} else if (newDirection === 3){
		// North
		this.xChange = 0;
		this.yChange = -this.change;
	}
};
<commit_msg>moving eyes<commit_after>

// constructor for PacMan
function PacMan(xpos, ypos) {

	// shape
	this.diam = 80;
	this.radius = this.diam / 2;
	this.eyePos = this.diam / 7;
	this.eyeDiam = this.diam / 8;
	this.mouthAngle = (1/6);
	this.mouthChange = 1/128;

	//  position and movement
	this.xpos = xpos;
	this.ypos = ypos;
	this.direction = 0;
	this.change = 0;
	this.xChange = 0;
	this.yChange = 0;
	this.maxDirChange = 4;

	// timing
	this.curTime = 0;
	this.maxTime = 4;
	this.targetTime = random(this.maxTime);

}

PacMan.prototype.draw = function () {
	// call move
	this.timer();
	this.move();

	push();
	translate( this.xpos, this.ypos );

	// check direction
	if ( this.direction === 0 ) {
		// do nothing
	} else if ( this.direction === 1 ) {
		rotate(PI/2);
	} else if ( this.direction === 2 ) {
		scale(-1, 1);
	} else if ( this.direction === 3 ) {
		rotate(-PI/2);
	}

	// draw the pacman
	fill(color("Yellow"));
	arc( 0, 0, this.diam, this.diam, PI*this.mouthAngle, -PI*this.mouthAngle, PIE );

	fill(color("Black"));
	arc( this.eyePos, -this.eyePos * 2, this.eyeDiam, this.eyeDiam, PI*this.mouthAngle, -PI*this.mouthAngle, PIE );

	pop();
};

//  Moe Function
PacMan.prototype.move = function () {

	// update position
	this.xpos += this.xChange;
	this.ypos += this.yChange;

	//  mouth animation
	this.mouthAngle = this.mouthAngle + ( this.mouthChange * this.change);
	if( this.mouthAngle > (1/6) ){
		this.mouthChange = -this.mouthChange;
		this.mouthAngle = (1/6);
	}
	if( this.mouthAngle < 0.01 ){
		this.mouthChange = -this.mouthChange;
		this.mouthAngle = 0.03;
	}

	// edge check
	if( this.xpos+this.radius >= width ){
		this.xpos = width-this.radius;
		this.xChange = 0;
	} else if ( this.xpos-this.radius <= 0 ){
		this.xpos = 0+this.radius;
		this.xChange = 0;
	}

	if ( this.ypos+this.radius >= height ){
		this.ypos = height-this.radius;
		this.yChange = 0;
	} else if ( this.ypos-this.radius <= 0 ){
		this.ypos = 0+this.radius;
		this.yChange = 0;
	}
};

// Timer
PacMan.prototype.timer = function () {
	var curTime = this.curTime / frameRate();
	if ( curTime >= this.targetTime ){
		// change direction and update timer
		this.changeDirection();
	} else {
		this.curTime++;
	}
};

PacMan.prototype.changeDirection = function () {
	var newDirection;

	// reset timer
	this.curTime = 0;
	this.targetTime = random(this.maxTime);

	// choose a new direction
	do {
		newDirection = floor( random(4) );
	} while ( newDirection == this.direction );

	this.direction = newDirection;

	this.change = random(this.maxDirChange);
	if (newDirection === 0){
		// East
		this.xChange = this.change;
		this.yChange = 0;
	} else if (newDirection === 1){
		// South
		this.xChange = 0;
		this.yChange = this.change;
	} else if (newDirection === 2){
		// West
		this.xChange = -this.change;
		this.yChange = 0;
	} else if (newDirection === 3){
		// North
		this.xChange = 0;
		this.yChange = -this.change;
	}
};
<|endoftext|>


<commit_before>// allows modification of the settings by the user
const remote = require('electron').remote
const fs = require('fs')

const settings = require('../../../settings/userSettings.js')

// dark theme color values
const darkText = document.getElementById('dark-text')
darkText.value = settings.darkText
const darkBackground = document.getElementById('dark-background')
darkBackground.value = settings.darkBgrd
const darkDarkBackground = document.getElementById('dark-dark-background')
darkDarkBackground.value = settings.darkDarkBgrd
const darkBlack = document.getElementById('dark-black')
darkBlack.value = settings.darkBlack
const darkGray = document.getElementById('dark-gray')
darkGray.value = settings.darkGray
const darkBlue = document.getElementById('dark-blue')
darkBlue.value = settings.darkBlue
const darkRed = document.getElementById('dark-red')
darkRed.value = settings.darkRed
const darkOrange = document.getElementById('dark-orange')
darkOrange.value = settings.darkOrange
const darkGreen = document.getElementById('dark-green')
darkGreen.value = settings.darkGreen
const darkYellow = document.getElementById('dark-yellow')
darkYellow.value = settings.darkYellow
const darkMagenta = document.getElementById('dark-magenta')
darkMagenta.value = settings.darkMagenta
const darkCyan = document.getElementById('dark-cyan')
darkCyan.value = settings.darkCyan

// light theme color values
const lightText = document.getElementById('light-text')
lightText.value = settings.lightText
const lightBackground = document.getElementById('light-background')
lightBackground.value = settings.lightBgrd
const lightDarkBackground = document.getElementById('light-dark-background')
lightDarkBackground.value = settings.lightDarkBgrd
const lightBlack = document.getElementById('light-black')
lightBlack.value = settings.lightBlack
const lightGray = document.getElementById('light-gray')
lightGray.value = settings.lightGray
const lightBlue = document.getElementById('light-blue')
lightBlue.value = settings.lightBlue
const lightRed = document.getElementById('light-red')
lightRed.value = settings.lightRed
const lightOrange = document.getElementById('light-orange')
lightOrange.value = settings.lightOrange
const lightGreen = document.getElementById('light-green')
lightGreen.value = settings.lightGreen
const lightYellow = document.getElementById('light-yellow')
lightYellow.value = settings.lightYellow
const lightMagenta = document.getElementById('light-magenta')
lightMagenta.value = settings.lightMagenta
const lightCyan = document.getElementById('light-cyan')
lightCyan.value = settings.lightCyan

// default color
const defaultColor = document.getElementById('default-color')
defaultColor.value = settings.colorTheme

const numberBubbles = document.getElementById('number-bubbles')
numberBubbles.value = settings.maxNumberOfBubbles

const cveUrl = document.getElementById('cve-url')
cveUrl.value = settings.cveSearchUrl

// capture the save event
const saveBtn = document.getElementById('settings-save')
saveBtn.addEventListener('click', () => {
  // console.log(defaultColor.value)
  const toWrite = `// settings of ASTo

const settings = {}

settings.darkText = '${darkText.value}'
settings.darkBgrd = '${darkBackground.value}'
settings.darkDarkBgrd = '${darkDarkBackground.value}'
settings.darkBlack = '${darkBlack.value}'
settings.darkGray = '${darkGray.value}'
settings.darkBlue = '${darkBlue.value}'
settings.darkRed = '${darkRed.value}'
settings.darkOrange = '${darkOrange.value}'
settings.darkGreen = '${darkGreen.value}'
settings.darkYellow = '${darkYellow.value}'
settings.darkMagenta = '${darkMagenta.value}'
settings.darkCyan = '${darkCyan}'
// light color theme
settings.lightText = '${lightText.value}'
settings.lightBgrd = '${lightBackground.value}'
settings.lightDarkBgrd = '${lightDarkBackground.value}'
settings.lightBlack = '${lightBlack.value}'
settings.lightGray = '${lightGray.value}'
settings.lightBlue = '${lightBlue.value}'
settings.lightRed = '${lightRed.value}'
settings.lightOrange = '${lightOrange.value}'
settings.lightGreen = '${lightGreen.value}'
settings.lightYellow = '${lightYellow.value}'
settings.lightMagenta = '${lightMagenta.value}'
settings.lightCyan = '${lightCyan.value}'

// graph color values
settings.setColors = color => {
  // dark color theme
  if (color === 'dark') {
    settings.text = settings.darkText
    settings.background = settings.darkBgrd
    settings.darkBackground = settings.darkDarkBgrd
    settings.black = settings.darkBlack
    settings.gray = settings.darkGray
    settings.blue = settings.darkBlue
    settings.red = settings.darkRed
    settings.orange = settings.darkOrange
    settings.green = settings.darkGreen
    settings.yellow = settings.darkYellow
    settings.magenta = settings.darkMagenta
    settings.cyan = settings.darkCyan
    // light color theme
  } else if (color === 'light') {
    settings.text = settings.lightText
    settings.background = settings.lightBgrd
    settings.darkBackground = settings.lightDarkBgrd
    settings.black = settings.lightBlack
    settings.gray = settings.lightGray
    settings.blue = settings.lightBlue
    settings.red = settings.lightRed
    settings.orange = settings.lightOrange
    settings.green = settings.lightGreen
    settings.yellow = settings.lightYellow
    settings.magenta = settings.lightMagenta
    settings.cyan = settings.lightCyan
  }
}

// default color theme
settings.colorTheme = 'dark'
// first theme paint
settings.setColors(settings.colorTheme)

// number of maximum bubbles in the message area
settings.maxNumberOfBubbles = 15

// urls

// url for the ASTo wiki
settings.docsURL = 'https://or3stis.github.io/apparatus/docs'
// url for searching vulnerabilities
settings.cveSearchUrl = 'http://cve.circl.lu/api/search/'

module.exports = settings
`

  fs.writeFile('./app/settings/userSettings.js', toWrite, err => {
    if (err) throw err
  })

  // close the window
  const win = remote.getCurrentWindow()
  win.close()
})

// capture the cancel event
const cancelBtn = document.getElementById('settings-cancel')
cancelBtn.addEventListener('click', () => {
  const win = remote.getCurrentWindow()
  win.close()
})

// capture the settings restore event
const restoreBtn = document.getElementById('settings-restore')
restoreBtn.addEventListener('click', () => {
  // TODO uncomment when electron supports node.js < 8.5
  // fs.copyFile('./app/settings/defaultSettings.js', './app/settings/userSettings.js', (err) => {
  //   if (err) throw err
  // })
  fs
    .createReadStream('./app/settings/defaultSettings.js')
    .pipe(fs.createWriteStream('./app/settings/userSettings.js'))

  // close window
  const win = remote.getCurrentWindow()
  win.close()
})
<commit_msg>:bug: cyan was missing value<commit_after>// allows modification of the settings by the user
const remote = require('electron').remote
const fs = require('fs')

const settings = require('../../../settings/userSettings.js')

// dark theme color values
const darkText = document.getElementById('dark-text')
darkText.value = settings.darkText
const darkBackground = document.getElementById('dark-background')
darkBackground.value = settings.darkBgrd
const darkDarkBackground = document.getElementById('dark-dark-background')
darkDarkBackground.value = settings.darkDarkBgrd
const darkBlack = document.getElementById('dark-black')
darkBlack.value = settings.darkBlack
const darkGray = document.getElementById('dark-gray')
darkGray.value = settings.darkGray
const darkBlue = document.getElementById('dark-blue')
darkBlue.value = settings.darkBlue
const darkRed = document.getElementById('dark-red')
darkRed.value = settings.darkRed
const darkOrange = document.getElementById('dark-orange')
darkOrange.value = settings.darkOrange
const darkGreen = document.getElementById('dark-green')
darkGreen.value = settings.darkGreen
const darkYellow = document.getElementById('dark-yellow')
darkYellow.value = settings.darkYellow
const darkMagenta = document.getElementById('dark-magenta')
darkMagenta.value = settings.darkMagenta
const darkCyan = document.getElementById('dark-cyan')
darkCyan.value = settings.darkCyan

// light theme color values
const lightText = document.getElementById('light-text')
lightText.value = settings.lightText
const lightBackground = document.getElementById('light-background')
lightBackground.value = settings.lightBgrd
const lightDarkBackground = document.getElementById('light-dark-background')
lightDarkBackground.value = settings.lightDarkBgrd
const lightBlack = document.getElementById('light-black')
lightBlack.value = settings.lightBlack
const lightGray = document.getElementById('light-gray')
lightGray.value = settings.lightGray
const lightBlue = document.getElementById('light-blue')
lightBlue.value = settings.lightBlue
const lightRed = document.getElementById('light-red')
lightRed.value = settings.lightRed
const lightOrange = document.getElementById('light-orange')
lightOrange.value = settings.lightOrange
const lightGreen = document.getElementById('light-green')
lightGreen.value = settings.lightGreen
const lightYellow = document.getElementById('light-yellow')
lightYellow.value = settings.lightYellow
const lightMagenta = document.getElementById('light-magenta')
lightMagenta.value = settings.lightMagenta
const lightCyan = document.getElementById('light-cyan')
lightCyan.value = settings.lightCyan

// default color
const defaultColor = document.getElementById('default-color')
defaultColor.value = settings.colorTheme

const numberBubbles = document.getElementById('number-bubbles')
numberBubbles.value = settings.maxNumberOfBubbles

const cveUrl = document.getElementById('cve-url')
cveUrl.value = settings.cveSearchUrl

// capture the save event
const saveBtn = document.getElementById('settings-save')
saveBtn.addEventListener('click', () => {
  // console.log(defaultColor.value)
  const toWrite = `// settings of ASTo

const settings = {}

settings.darkText = '${darkText.value}'
settings.darkBgrd = '${darkBackground.value}'
settings.darkDarkBgrd = '${darkDarkBackground.value}'
settings.darkBlack = '${darkBlack.value}'
settings.darkGray = '${darkGray.value}'
settings.darkBlue = '${darkBlue.value}'
settings.darkRed = '${darkRed.value}'
settings.darkOrange = '${darkOrange.value}'
settings.darkGreen = '${darkGreen.value}'
settings.darkYellow = '${darkYellow.value}'
settings.darkMagenta = '${darkMagenta.value}'
settings.darkCyan = '${darkCyan.value}'
// light color theme
settings.lightText = '${lightText.value}'
settings.lightBgrd = '${lightBackground.value}'
settings.lightDarkBgrd = '${lightDarkBackground.value}'
settings.lightBlack = '${lightBlack.value}'
settings.lightGray = '${lightGray.value}'
settings.lightBlue = '${lightBlue.value}'
settings.lightRed = '${lightRed.value}'
settings.lightOrange = '${lightOrange.value}'
settings.lightGreen = '${lightGreen.value}'
settings.lightYellow = '${lightYellow.value}'
settings.lightMagenta = '${lightMagenta.value}'
settings.lightCyan = '${lightCyan.value}'

// graph color values
settings.setColors = color => {
  // dark color theme
  if (color === 'dark') {
    settings.text = settings.darkText
    settings.background = settings.darkBgrd
    settings.darkBackground = settings.darkDarkBgrd
    settings.black = settings.darkBlack
    settings.gray = settings.darkGray
    settings.blue = settings.darkBlue
    settings.red = settings.darkRed
    settings.orange = settings.darkOrange
    settings.green = settings.darkGreen
    settings.yellow = settings.darkYellow
    settings.magenta = settings.darkMagenta
    settings.cyan = settings.darkCyan
    // light color theme
  } else if (color === 'light') {
    settings.text = settings.lightText
    settings.background = settings.lightBgrd
    settings.darkBackground = settings.lightDarkBgrd
    settings.black = settings.lightBlack
    settings.gray = settings.lightGray
    settings.blue = settings.lightBlue
    settings.red = settings.lightRed
    settings.orange = settings.lightOrange
    settings.green = settings.lightGreen
    settings.yellow = settings.lightYellow
    settings.magenta = settings.lightMagenta
    settings.cyan = settings.lightCyan
  }
}

// default color theme
settings.colorTheme = 'dark'
// first theme paint
settings.setColors(settings.colorTheme)

// number of maximum bubbles in the message area
settings.maxNumberOfBubbles = 15

// urls

// url for the ASTo wiki
settings.docsURL = 'https://or3stis.github.io/apparatus/docs'
// url for searching vulnerabilities
settings.cveSearchUrl = 'http://cve.circl.lu/api/search/'

module.exports = settings
`

  fs.writeFile('./app/settings/userSettings.js', toWrite, err => {
    if (err) throw err
  })

  // close the window
  const win = remote.getCurrentWindow()
  win.close()
})

// capture the cancel event
const cancelBtn = document.getElementById('settings-cancel')
cancelBtn.addEventListener('click', () => {
  const win = remote.getCurrentWindow()
  win.close()
})

// capture the settings restore event
const restoreBtn = document.getElementById('settings-restore')
restoreBtn.addEventListener('click', () => {
  // TODO uncomment when electron supports node.js < 8.5
  // fs.copyFile('./app/settings/defaultSettings.js', './app/settings/userSettings.js', (err) => {
  //   if (err) throw err
  // })
  fs
    .createReadStream('./app/settings/defaultSettings.js')
    .pipe(fs.createWriteStream('./app/settings/userSettings.js'))

  // close window
  const win = remote.getCurrentWindow()
  win.close()
})
<|endoftext|>


<commit_before>const fs = require("fs");
const path = require("path");
const l = require("lodash");

const CleanCSS = require("clean-css");
const gulp = require("gulp");
const gulpif = require("gulp-if");
const gzip = require("gulp-gzip");

const mustache = require("gulp-mustache");
const rename = require("gulp-rename");
const svgSprite = require("gulp-svg-sprite");

const mkdirp = require("mkdirp");
const rimraf = require("rimraf");
const sass = require("sass");
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')

const paths = {};
paths.resources = "./resources/";
paths.output = "./resources/public/";
paths.build = "./target/build/";
paths.dist = "./target/dist/";
paths.scss = "./resources/styles/**/*.scss";

/***********************************************
 * Helpers
 ***********************************************/

function isProduction() {
  return (process.env.NODE_ENV === 'production');
}

function scssPipeline(options) {
  const write = (_path, data) => {
    return new Promise((resolve, reject) => {
      fs.writeFile(_path, data, function(err) {
        if (err) { reject(err); }
        else { resolve(); }
      });
    });
  };

  const render = (input) => {
    return new Promise((resolve, reject) => {
      sass.render({file: input}, async function(err, result) {
        if (err) {
          console.log(err.formatted);
          reject(err);
        } else {
          resolve(result.css);
        }
      });
    });
  };

  const postprocess = (data, input, output) => {
    return postcss([autoprefixer])
      .process(data, {map: false, from: input, to: output})
  };

  return function(next) {
    const input = options.input;
    const output = options.output;

    return mkdirp(path.dirname(output))
      .then(() => render(input))
      .then((res) => postprocess(res, input, output))
      .then((res) => write(output, res))
      .catch((err) => null)
      .then(() => {
        next();
      });
  };
}

// Templates

function readSvgSprite() {
  const path = paths.build + "/icons-sprite/symbol/svg/sprite.symbol.svg";
  const content = fs.readFileSync(path, {encoding: "utf8"});
  return content;
}

function readLocales() {
  const path = __dirname + "/resources/locales.json";
  const content = JSON.parse(fs.readFileSync(path, {encoding: "utf8"}));

  let result = {};
  for (let key of Object.keys(content)) {
    const item = content[key];
    if (l.isString(item)) {
      result[key] = {"en": item};
    } else if (l.isPlainObject(item) && l.isPlainObject(item.translations)) {
      result[key] = item.translations;
    }
  }

  return JSON.stringify(result);
}

function readConfig() {
  const backendURL = process.env.UXBOX_BACKEND_URL;
  const demoWarn = process.env.UXBOX_DEMO_WARNING;

  let cfg = {
    demoWarning: demoWarn === "true"
  };

  if (backendURL !== undefined) {
    cfg.backendURL = backendURL;
  }

  return JSON.stringify(cfg);
}

function templatePipeline(options) {
  return function() {
    const input = options.input;
    const output = options.output;
    const ts = Math.floor(new Date());

    const locales = readLocales();
    const icons = readSvgSprite();
    const config = readConfig();

    const tmpl = mustache({
      ts: ts,
      ic: icons,
      config: JSON.stringify(config),
      translations: JSON.stringify(locales),
    });

    return gulp.src(input)
      .pipe(tmpl)
      .pipe(rename("index.html"))
      .pipe(gulp.dest(output));
  };
}

/***********************************************
 * Generic
 ***********************************************/

gulp.task("scss:main", scssPipeline({
  input: paths.resources + "styles/main.scss",
  output: paths.build + "css/main.css"
}));

gulp.task("scss", gulp.parallel("scss:main"));

gulp.task("svg:sprite", function() {
  return gulp.src(paths.resources + "images/icons/*.svg")
    .pipe(rename({prefix: 'icon-'}))
    .pipe(svgSprite({mode:{symbol: {inline: true}}}))
    .pipe(gulp.dest(paths.build + "icons-sprite/"));
});

gulp.task("template:main", templatePipeline({
  input: paths.resources + "templates/index.mustache",
  output: paths.build
}));

gulp.task("templates", gulp.series("svg:sprite", "template:main"));

/***********************************************
 * Development
 ***********************************************/

gulp.task("dev:clean", function(next) {
  rimraf(paths.output, function() {
    rimraf(paths.build, next);
  });
});

gulp.task("dev:copy:images", function() {
  return gulp.src(paths.resources + "images/**/*")
    .pipe(gulp.dest(paths.output + "images/"));
});

gulp.task("dev:copy:css", function() {
  return gulp.src(paths.build + "css/**/*")
    .pipe(gulp.dest(paths.output + "css/"));
});

gulp.task("dev:copy:icons-sprite", function() {
  return gulp.src(paths.build + "icons-sprite/**/*")
    .pipe(gulp.dest(paths.output + "icons-sprite/"));
});

gulp.task("dev:copy:templates", function() {
  return gulp.src(paths.build + "index.html")
    .pipe(gulp.dest(paths.output));
});

gulp.task("dev:copy:fonts", function() {
  return gulp.src(paths.resources + "fonts/**/*")
    .pipe(gulp.dest(paths.output + "fonts/"));
});

gulp.task("dev:copy", gulp.parallel("dev:copy:images",
                                    "dev:copy:css",
                                    "dev:copy:fonts",
                                    "dev:copy:icons-sprite",
                                    "dev:copy:templates"));

gulp.task("dev:dirs", function(next) {
  mkdirp("./resources/public/css/")
    .then(() => next())
});

gulp.task("watch:main", function() {
  gulp.watch(paths.scss, gulp.series("scss", "dev:copy:css"));

  gulp.watch([paths.resources + "templates/*.mustache",
              paths.resources + "locales.json",
              paths.resources + "images/**/*"],
             gulp.series("templates",
                         "dev:copy:images",
                         "dev:copy:templates",
                         "dev:copy:icons-sprite"));
});

gulp.task("watch", gulp.series(
  "dev:dirs",
  gulp.parallel("scss", "templates"),
  "dev:copy",
  "watch:main"
));

/***********************************************
 * Production
 ***********************************************/

gulp.task("dist:clean", function(next) {
  rimraf(paths.dist, function() {
    rimraf(paths.build, next);
  });
});

gulp.task("dist:copy:templates", function() {
  return gulp.src(paths.build + "index.html")
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist:copy:images", function() {
  return gulp.src(paths.resources + "images/**/*")
    .pipe(gulp.dest(paths.dist + "images/"));
});

gulp.task("dist:copy:styles", function() {
  return gulp.src(paths.build + "css/**/*")
    .pipe(gulp.dest(paths.dist + "css/"));
});

gulp.task("dist:copy:icons-sprite", function() {
  return gulp.src(paths.build + "icons-sprite/**/*")
    .pipe(gulp.dest(paths.dist + "icons-sprite/"));
});

gulp.task("dist:copy:fonts", function() {
  return gulp.src(paths.resources + "/fonts/**/*")
    .pipe(gulp.dest(paths.dist + "fonts/"));
});

gulp.task("dist:copy", gulp.parallel("dist:copy:fonts",
                                     "dist:copy:icons-sprite",
                                     "dist:copy:styles",
                                     "dist:copy:templates",
                                     "dist:copy:images"));

gulp.task("dist:gzip", function() {
  return gulp.src(`${paths.dist}**/!(*.gz|*.br|*.jpg|*.png)`)
    .pipe(gzip({gzipOptions: {level: 9}}))
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist", gulp.series(
  "dist:clean",
  "scss",
  "templates",
  "dist:copy"
));
<commit_msg>:construction: Add missing variable on gulpfile.<commit_after>const fs = require("fs");
const path = require("path");
const l = require("lodash");

const CleanCSS = require("clean-css");
const gulp = require("gulp");
const gulpif = require("gulp-if");
const gzip = require("gulp-gzip");

const mustache = require("gulp-mustache");
const rename = require("gulp-rename");
const svgSprite = require("gulp-svg-sprite");

const mkdirp = require("mkdirp");
const rimraf = require("rimraf");
const sass = require("sass");
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')

const paths = {};
paths.resources = "./resources/";
paths.output = "./resources/public/";
paths.build = "./target/build/";
paths.dist = "./target/dist/";
paths.scss = "./resources/styles/**/*.scss";

/***********************************************
 * Helpers
 ***********************************************/

function isProduction() {
  return (process.env.NODE_ENV === 'production');
}

function scssPipeline(options) {
  const write = (_path, data) => {
    return new Promise((resolve, reject) => {
      fs.writeFile(_path, data, function(err) {
        if (err) { reject(err); }
        else { resolve(); }
      });
    });
  };

  const render = (input) => {
    return new Promise((resolve, reject) => {
      sass.render({file: input}, async function(err, result) {
        if (err) {
          console.log(err.formatted);
          reject(err);
        } else {
          resolve(result.css);
        }
      });
    });
  };

  const postprocess = (data, input, output) => {
    return postcss([autoprefixer])
      .process(data, {map: false, from: input, to: output})
  };

  return function(next) {
    const input = options.input;
    const output = options.output;

    return mkdirp(path.dirname(output))
      .then(() => render(input))
      .then((res) => postprocess(res, input, output))
      .then((res) => write(output, res))
      .catch((err) => null)
      .then(() => {
        next();
      });
  };
}

// Templates

function readSvgSprite() {
  const path = paths.build + "/icons-sprite/symbol/svg/sprite.symbol.svg";
  const content = fs.readFileSync(path, {encoding: "utf8"});
  return content;
}

function readLocales() {
  const path = __dirname + "/resources/locales.json";
  const content = JSON.parse(fs.readFileSync(path, {encoding: "utf8"}));

  let result = {};
  for (let key of Object.keys(content)) {
    const item = content[key];
    if (l.isString(item)) {
      result[key] = {"en": item};
    } else if (l.isPlainObject(item) && l.isPlainObject(item.translations)) {
      result[key] = item.translations;
    }
  }

  return JSON.stringify(result);
}

function readConfig() {
  const publicURL = process.env.UXBOX_PUBLIC_URL;
  const demoWarn = process.env.UXBOX_DEMO_WARNING;

  let cfg = {
    demoWarning: demoWarn === "true"
  };

  if (publicURL !== undefined) {
    cfg.publicURL = publicURL;
  }

  return JSON.stringify(cfg);
}

function templatePipeline(options) {
  return function() {
    const input = options.input;
    const output = options.output;
    const ts = Math.floor(new Date());

    const locales = readLocales();
    const icons = readSvgSprite();
    const config = readConfig();

    const tmpl = mustache({
      ts: ts,
      ic: icons,
      config: JSON.stringify(config),
      translations: JSON.stringify(locales),
    });

    return gulp.src(input)
      .pipe(tmpl)
      .pipe(rename("index.html"))
      .pipe(gulp.dest(output));
  };
}

/***********************************************
 * Generic
 ***********************************************/

gulp.task("scss:main", scssPipeline({
  input: paths.resources + "styles/main.scss",
  output: paths.build + "css/main.css"
}));

gulp.task("scss", gulp.parallel("scss:main"));

gulp.task("svg:sprite", function() {
  return gulp.src(paths.resources + "images/icons/*.svg")
    .pipe(rename({prefix: 'icon-'}))
    .pipe(svgSprite({mode:{symbol: {inline: true}}}))
    .pipe(gulp.dest(paths.build + "icons-sprite/"));
});

gulp.task("template:main", templatePipeline({
  input: paths.resources + "templates/index.mustache",
  output: paths.build
}));

gulp.task("templates", gulp.series("svg:sprite", "template:main"));

/***********************************************
 * Development
 ***********************************************/

gulp.task("dev:clean", function(next) {
  rimraf(paths.output, function() {
    rimraf(paths.build, next);
  });
});

gulp.task("dev:copy:images", function() {
  return gulp.src(paths.resources + "images/**/*")
    .pipe(gulp.dest(paths.output + "images/"));
});

gulp.task("dev:copy:css", function() {
  return gulp.src(paths.build + "css/**/*")
    .pipe(gulp.dest(paths.output + "css/"));
});

gulp.task("dev:copy:icons-sprite", function() {
  return gulp.src(paths.build + "icons-sprite/**/*")
    .pipe(gulp.dest(paths.output + "icons-sprite/"));
});

gulp.task("dev:copy:templates", function() {
  return gulp.src(paths.build + "index.html")
    .pipe(gulp.dest(paths.output));
});

gulp.task("dev:copy:fonts", function() {
  return gulp.src(paths.resources + "fonts/**/*")
    .pipe(gulp.dest(paths.output + "fonts/"));
});

gulp.task("dev:copy", gulp.parallel("dev:copy:images",
                                    "dev:copy:css",
                                    "dev:copy:fonts",
                                    "dev:copy:icons-sprite",
                                    "dev:copy:templates"));

gulp.task("dev:dirs", function(next) {
  mkdirp("./resources/public/css/")
    .then(() => next())
});

gulp.task("watch:main", function() {
  gulp.watch(paths.scss, gulp.series("scss", "dev:copy:css"));

  gulp.watch([paths.resources + "templates/*.mustache",
              paths.resources + "locales.json",
              paths.resources + "images/**/*"],
             gulp.series("templates",
                         "dev:copy:images",
                         "dev:copy:templates",
                         "dev:copy:icons-sprite"));
});

gulp.task("watch", gulp.series(
  "dev:dirs",
  gulp.parallel("scss", "templates"),
  "dev:copy",
  "watch:main"
));

/***********************************************
 * Production
 ***********************************************/

gulp.task("dist:clean", function(next) {
  rimraf(paths.dist, function() {
    rimraf(paths.build, next);
  });
});

gulp.task("dist:copy:templates", function() {
  return gulp.src(paths.build + "index.html")
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist:copy:images", function() {
  return gulp.src(paths.resources + "images/**/*")
    .pipe(gulp.dest(paths.dist + "images/"));
});

gulp.task("dist:copy:styles", function() {
  return gulp.src(paths.build + "css/**/*")
    .pipe(gulp.dest(paths.dist + "css/"));
});

gulp.task("dist:copy:icons-sprite", function() {
  return gulp.src(paths.build + "icons-sprite/**/*")
    .pipe(gulp.dest(paths.dist + "icons-sprite/"));
});

gulp.task("dist:copy:fonts", function() {
  return gulp.src(paths.resources + "/fonts/**/*")
    .pipe(gulp.dest(paths.dist + "fonts/"));
});

gulp.task("dist:copy", gulp.parallel("dist:copy:fonts",
                                     "dist:copy:icons-sprite",
                                     "dist:copy:styles",
                                     "dist:copy:templates",
                                     "dist:copy:images"));

gulp.task("dist:gzip", function() {
  return gulp.src(`${paths.dist}**/!(*.gz|*.br|*.jpg|*.png)`)
    .pipe(gzip({gzipOptions: {level: 9}}))
    .pipe(gulp.dest(paths.dist));
});

gulp.task("dist", gulp.series(
  "dist:clean",
  "scss",
  "templates",
  "dist:copy"
));
<|endoftext|>


<commit_before>var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

canvas.width = 400;
canvas.height = 200;

ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ffffff";
ctx.font = "bold 100px arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("CHAOS", canvas.width/2, canvas.height/2);

var char_location = []
var pix_location = [];
var lastX = -1;
var lastY = -1;

for (x = 0; x < canvas.width; x += 2) {
  for (y = 0; y < canvas.height; y += 2) {
    if (ctx.getImageData(x, y, 1,1).data[0] == 255) {
      char_location.push([x,y]);
      pix_location.push([0,0]);
    }
  }
}

canvas.onmousemove = function(e) {
  lastX = e.offsetX;
  lastY = e.offsetY;
}

setInterval(function() {
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#f3482d";
    for (x = 0; x < pix_location.length; x++) {
      var xPos = pix_location[x][0] + 0.1*(char_location[x][0]-pix_location[x][0]);
      var yPos = pix_location[x][1] + 0.1*(char_location[x][1]-pix_location[x][1]);
      if (lastX > 0 && lastY > 0) {
          dx = pix_location[x][0]-lastX;
          dy = pix_location[x][1]-lastY;
          if (Math.sqrt(dx*dx+dy*dy) < 10) {
            yPos = Math.random() > 0.5 ? 0 : canvas.height;
          }
      }
      pix_location[x] = [xPos,yPos];
      ctx.fillRect(pix_location[x][0], pix_location[x][1],2,2);
    }
    lastX = -1;
    lastY = -1;
}, 100);

var k = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
n = 0;
document.addEventListener("keydown", function(e) {
  if (e.keyCode === k[n++]) {
    if (n === k.length) {
      document.body.className = 'transform';
      setTimeout(function(){ document.body.className = ''; },15000);
      n = 0;
      return false;
    }
  } else {
        n = 0;
  }
});

  var notification = document.getElementById('notifbox');
  var notif = setTimeout(function(){
    notification.removeAttribute('hidden');
    notification.className += " fadeInDown";
    unfade(notification);
  }, 5000);

  var dismissTimeout = function(){
    window.clearTimeout(notif);
  };

  var dismissNotif = function(){
    notification.setAttribute('hidden', 'true');
    fade(notification);
  }

function fade(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
            element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
    }, 50);
}

function unfade(element) {
    var op = 0.1;  // initial opacity
    element.style.display = 'block';
    var timer = setInterval(function () {
        if (op >= 1){
            clearInterval(timer);
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 10);
}<commit_msg>merging PR #320: Use requestAnimationFrame in chaos canvas on website<commit_after>var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

canvas.width = 400;
canvas.height = 200;

ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ffffff";
ctx.font = "bold 100px arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("CHAOS", canvas.width/2, canvas.height/2);

var char_location = []
var pix_location = [];
var lastX = -1;
var lastY = -1;

for (x = 0; x < canvas.width; x += 2) {
  for (y = 0; y < canvas.height; y += 2) {
    if (ctx.getImageData(x, y, 1,1).data[0] == 255) {
      char_location.push([x,y]);
      pix_location.push([0,0]);
    }
  }
}

canvas.onmousemove = function(e) {
  lastX = e.offsetX;
  lastY = e.offsetY;
}

function loop() {
    ctx.fillStyle = "#ffffff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#f3482d";
    for (x = 0; x < pix_location.length; x++) {
      var xPos = pix_location[x][0] + 0.1*(char_location[x][0]-pix_location[x][0]);
      var yPos = pix_location[x][1] + 0.1*(char_location[x][1]-pix_location[x][1]);
      if (lastX > 0 && lastY > 0) {
          dx = pix_location[x][0]-lastX;
          dy = pix_location[x][1]-lastY;
          if (Math.sqrt(dx*dx+dy*dy) < 10) {
            yPos = Math.random() > 0.5 ? 0 : canvas.height;
          }
      }
      pix_location[x] = [xPos,yPos];
      ctx.fillRect(pix_location[x][0], pix_location[x][1],2,2);
    }
    lastX = -1;
    lastY = -1;
    window.requestAnimationFrame(loop);
}

window.requestAnimationFrame(loop);

var k = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
n = 0;
document.addEventListener("keydown", function(e) {
  if (e.keyCode === k[n++]) {
    if (n === k.length) {
      document.body.className = 'transform';
      setTimeout(function(){ document.body.className = ''; },15000);
      n = 0;
      return false;
    }
  } else {
        n = 0;
  }
});

  var notification = document.getElementById('notifbox');
  var notif = setTimeout(function(){
    notification.removeAttribute('hidden');
    notification.className += " fadeInDown";
    unfade(notification);
  }, 5000);

  var dismissTimeout = function(){
    window.clearTimeout(notif);
  };

  var dismissNotif = function(){
    notification.setAttribute('hidden', 'true');
    fade(notification);
  }

function fade(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
            element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
    }, 50);
}

function unfade(element) {
    var op = 0.1;  // initial opacity
    element.style.display = 'block';
    var timer = setInterval(function () {
        if (op >= 1){
            clearInterval(timer);
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 10);
}<|endoftext|>


<commit_before>#!/usr/bin/env node

var repl = require('repl');
var util = require('util');
var program = require('commander');
var protocol = require('../lib/protocol.json');
var Chrome = require('../');

program
    .option('-h, --host <host>', 'Remote Debugging Protocol host')
    .option('-p, --port <port>', 'Remote Debugging Protocol port')
    .parse(process.argv);

var options = {
    'host': program.host,
    'port': program.port
};

Chrome(options, function (chrome) {
    var chromeRepl = repl.start({
        'prompt': 'chrome> ',
        'ignoreUndefined': true,
        'writer': function (object) {
            return util.inspect(object, {
                'colors': true,
                'depth': null
            });
        }
    });

    // disconnect on exit
    chromeRepl.on('exit', function () {
        chrome.close();
    });

    // add protocol API
    for (var domainIdx in protocol.domains) {
        var domainName = protocol.domains[domainIdx].domain;
        chromeRepl.context[domainName] = chrome[domainName];
    }
}).on('error', function () {
    console.error('Cannot connect to Chrome');
});
<commit_msg>Change the flag name for the host option in the REPL<commit_after>#!/usr/bin/env node

var repl = require('repl');
var util = require('util');
var program = require('commander');
var protocol = require('../lib/protocol.json');
var Chrome = require('../');

program
    .option('-t, --host <host>', 'Remote Debugging Protocol host')
    .option('-p, --port <port>', 'Remote Debugging Protocol port')
    .parse(process.argv);

var options = {
    'host': program.host,
    'port': program.port
};

Chrome(options, function (chrome) {
    var chromeRepl = repl.start({
        'prompt': 'chrome> ',
        'ignoreUndefined': true,
        'writer': function (object) {
            return util.inspect(object, {
                'colors': true,
                'depth': null
            });
        }
    });

    // disconnect on exit
    chromeRepl.on('exit', function () {
        chrome.close();
    });

    // add protocol API
    for (var domainIdx in protocol.domains) {
        var domainName = protocol.domains[domainIdx].domain;
        chromeRepl.context[domainName] = chrome[domainName];
    }
}).on('error', function () {
    console.error('Cannot connect to Chrome');
});
<|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// npm compatibility
if (typeof define !== 'function') { var define = require('./requirejs-shim')(module); }

define([
    "./widget",
    "./utils",
    "jquery",
    "underscore"
], function(widget, utils, $, _) {
    'use strict';

    var Button = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad button. */

        render : function() {
            this.$el.addClass('ipy-widget widget-controller-button');

            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '16px',
                    'height': '16px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bar = $('<div />')
                .css({
                    'position': 'absolute',
                    'width': '100%',
                    'bottom': 0,
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bar.css('height', 100 * this.model.get('value') + '%');
        },

    });

    var Axis = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad axis. */

        render : function() {

            this.$el.addClass('ipy-widget widget-controller-axis');

            this.$el.css({
                    'width': '16px',
                    'padding': '4px',
                });
            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '4px',
                    'height': '64px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bullet = $('<div />')
                .css({
                    'position': 'absolute',
                    'margin': '-4px',
                    'width': '10px',
                    'height': '10px',
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bullet.css('top', 50 * (this.model.get('value') + 1) + '%');
        },

    });

    var Controller = widget.DOMWidgetModel.extend({
        /* The Controller model. */

        initialize: function() {
            if (navigator.getGamepads === void 0) {
                // Checks if the browser supports the gamepad API
                this.readout = 'This browser does not support gamepads.';
                console.error(this.readout);
            } else {
                // Start the wait loop, and listen to updates of the only
                // user-provided attribute, the gamepad index.
                this.readout = 'Connect gamepad and press any button.';
                // Wait for the state to be provided by the backend.
                this.on('ready', function() {
                    if (this.get('connected')) {
                        // No need to re-create Button and Axis widgets, re-use
                        // the models provided by the backend which may already
                        // be wired to other things.
                        this.update_loop();
                    } else {
                        // Wait for a gamepad to be connected.
                        this.wait_loop();
                    }
                }, this);
            }
        },

        wait_loop: function() {
            /* Waits for a gamepad to be connected at the provided index.
             * Once one is connected, it will start the update loop, which
             * populates the update of axes and button values.
             */
            var index = this.get('index');
            var pad = navigator.getGamepads()[index];
            if (pad) {
                var that = this;
                this.setup(pad).then(function(controls) {
                    that.set(controls);
                    that.save_changes();
                    window.requestAnimationFrame(that.update_loop.bind(that));
                });
            } else {
                window.requestAnimationFrame(this.wait_loop.bind(this));
            }
        },

        setup: function(pad) {
            /* Given a native gamepad object, returns a promise for a dictionary of
             * controls, of the form
             * {
             *     buttons: list of Button models,
             *     axes: list of Axis models,
             * }
             */
            // Set up the main gamepad attributes
            this.set({
                name: pad.id,
                mapping: pad.mapping,
                connected: pad.connected,
                timestamp: pad.timestamp,
            });
            // Create buttons and axes. When done, start the update loop
            var that = this;
            return utils.resolvePromisesDict({
                buttons: Promise.all(pad.buttons.map(function(btn, index) {
                    return that._create_button_model(index);
                })),
                axes: Promise.all(pad.axes.map(function(axis, index) {
                    return that._create_axis_model(index);
                })),
            });
        },

        update_loop: function() {
            /* Update axes and buttons values, until the gamepad is disconnected.
             * When the gamepad is disconnected, this.reset_gamepad is called.
             */
            var index = this.get('index');
            var id = this.get('name');
            var pad = navigator.getGamepads()[index];
            if (pad && index === pad.index && id === pad.id) {
                this.set({
                    timestamp: pad.timestamp,
                    connected: pad.connected,
                });
                this.save_changes();
                this.get('buttons').forEach(function(model, index) {
                    model.set({
                        value: pad.buttons[index].value,
                        pressed: pad.buttons[index].pressed,
                    });
                    model.save_changes();
                });
                this.get('axes').forEach(function(model, index) {
                    model.set('value', pad.axes[index]);
                    model.save_changes();
                });
                window.requestAnimationFrame(this.update_loop.bind(this));
            } else {
                this.reset_gamepad();
            }
        },

        reset_gamepad: function() {
            /* Resets the gamepad attributes, and start the wait_loop.
             */
            this.get('buttons').forEach(function(button) {
                button.close();
            });
            this.get('axes').forEach(function(axis) {
                axis.close();
            });
            this.set({
                name: '',
                mapping: '',
                connected: false,
                timestamp: 0.0,
                buttons: [],
                axes: [],
            });
            this.save_changes();
            window.requestAnimationFrame(this.wait_loop.bind(this));
        },

        _create_button_model: function(index) {
            /* Creates a gamepad button widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'ipywidgets.widgets.widget_controller.Button',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

        _create_axis_model: function(index) {
            /* Creates a gamepad axis widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'ipywidgets.widgets.widget_controller.Axis',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

    }, {
        serializers: _.extend({
            buttons: {deserialize: widget.unpack_models},
            axes: {deserialize: widget.unpack_models},
        }, widget.DOMWidgetModel.serializers)
    });

    var ControllerView = widget.DOMWidgetView.extend({
        /* A simple view for a gamepad. */

        initialize: function() {
            ControllerView.__super__.initialize.apply(this, arguments);

            this.button_views = new widget.ViewList(this.add_button, null, this);
            this.listenTo(this.model, 'change:buttons', function(model, value) {
                this.button_views.update(value);
            }, this);

            this.axis_views = new widget.ViewList(this.add_axis, null, this);
            this.listenTo(this.model, 'change:axes', function(model, value) {
                this.axis_views.update(value);
            }, this);

            this.listenTo(this.model, 'change:name', this.update_label, this);
        },

        render: function(){
            this.$el.addClass('ipy-widget widget-controller');

            this.$box = this.$el;

            this.$label = $('<div />')
                .appendTo(this.$box);

            this.$axis_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.$button_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.button_views.update(this.model.get('buttons'));
            this.axis_views.update(this.model.get('axes'));

            this.update_label();
        },

        update_label: function() {
            this.$label.text(this.model.get('name') || this.model.readout);
        },

        add_button: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$button_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed', that);
                });
                return view;
            }).catch(utils.reject('Could not add button view', true));
        },

        add_axis: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$axis_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed', that);
                });
                return view;
            }).catch(utils.reject('Could not add axis view', true));
        },

        remove: function() {
            ControllerView.__super__.remove.apply(this, arguments);
            this.button_views.remove();
            this.axis_views.remove();
        },

    });

    return {
        ControllerButton: Button,
        ControllerAxis: Axis,
        Controller: Controller,
        ControllerView: ControllerView,
    };
});
<commit_msg>Use python-side registry when instantiating controller buttons and axes<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// npm compatibility
if (typeof define !== 'function') { var define = require('./requirejs-shim')(module); }

define([
    "./widget",
    "./utils",
    "jquery",
    "underscore"
], function(widget, utils, $, _) {
    'use strict';

    var Button = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad button. */

        render : function() {
            this.$el.addClass('ipy-widget widget-controller-button');

            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '16px',
                    'height': '16px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bar = $('<div />')
                .css({
                    'position': 'absolute',
                    'width': '100%',
                    'bottom': 0,
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bar.css('height', 100 * this.model.get('value') + '%');
        },

    });

    var Axis = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad axis. */

        render : function() {

            this.$el.addClass('ipy-widget widget-controller-axis');

            this.$el.css({
                    'width': '16px',
                    'padding': '4px',
                });
            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '4px',
                    'height': '64px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bullet = $('<div />')
                .css({
                    'position': 'absolute',
                    'margin': '-4px',
                    'width': '10px',
                    'height': '10px',
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bullet.css('top', 50 * (this.model.get('value') + 1) + '%');
        },

    });

    var Controller = widget.DOMWidgetModel.extend({
        /* The Controller model. */

        initialize: function() {
            if (navigator.getGamepads === void 0) {
                // Checks if the browser supports the gamepad API
                this.readout = 'This browser does not support gamepads.';
                console.error(this.readout);
            } else {
                // Start the wait loop, and listen to updates of the only
                // user-provided attribute, the gamepad index.
                this.readout = 'Connect gamepad and press any button.';
                // Wait for the state to be provided by the backend.
                this.on('ready', function() {
                    if (this.get('connected')) {
                        // No need to re-create Button and Axis widgets, re-use
                        // the models provided by the backend which may already
                        // be wired to other things.
                        this.update_loop();
                    } else {
                        // Wait for a gamepad to be connected.
                        this.wait_loop();
                    }
                }, this);
            }
        },

        wait_loop: function() {
            /* Waits for a gamepad to be connected at the provided index.
             * Once one is connected, it will start the update loop, which
             * populates the update of axes and button values.
             */
            var index = this.get('index');
            var pad = navigator.getGamepads()[index];
            if (pad) {
                var that = this;
                this.setup(pad).then(function(controls) {
                    that.set(controls);
                    that.save_changes();
                    window.requestAnimationFrame(that.update_loop.bind(that));
                });
            } else {
                window.requestAnimationFrame(this.wait_loop.bind(this));
            }
        },

        setup: function(pad) {
            /* Given a native gamepad object, returns a promise for a dictionary of
             * controls, of the form
             * {
             *     buttons: list of Button models,
             *     axes: list of Axis models,
             * }
             */
            // Set up the main gamepad attributes
            this.set({
                name: pad.id,
                mapping: pad.mapping,
                connected: pad.connected,
                timestamp: pad.timestamp,
            });
            // Create buttons and axes. When done, start the update loop
            var that = this;
            return utils.resolvePromisesDict({
                buttons: Promise.all(pad.buttons.map(function(btn, index) {
                    return that._create_button_model(index);
                })),
                axes: Promise.all(pad.axes.map(function(axis, index) {
                    return that._create_axis_model(index);
                })),
            });
        },

        update_loop: function() {
            /* Update axes and buttons values, until the gamepad is disconnected.
             * When the gamepad is disconnected, this.reset_gamepad is called.
             */
            var index = this.get('index');
            var id = this.get('name');
            var pad = navigator.getGamepads()[index];
            if (pad && index === pad.index && id === pad.id) {
                this.set({
                    timestamp: pad.timestamp,
                    connected: pad.connected,
                });
                this.save_changes();
                this.get('buttons').forEach(function(model, index) {
                    model.set({
                        value: pad.buttons[index].value,
                        pressed: pad.buttons[index].pressed,
                    });
                    model.save_changes();
                });
                this.get('axes').forEach(function(model, index) {
                    model.set('value', pad.axes[index]);
                    model.save_changes();
                });
                window.requestAnimationFrame(this.update_loop.bind(this));
            } else {
                this.reset_gamepad();
            }
        },

        reset_gamepad: function() {
            /* Resets the gamepad attributes, and start the wait_loop.
             */
            this.get('buttons').forEach(function(button) {
                button.close();
            });
            this.get('axes').forEach(function(axis) {
                axis.close();
            });
            this.set({
                name: '',
                mapping: '',
                connected: false,
                timestamp: 0.0,
                buttons: [],
                axes: [],
            });
            this.save_changes();
            window.requestAnimationFrame(this.wait_loop.bind(this));
        },

        _create_button_model: function(index) {
            /* Creates a gamepad button widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'Jupyter.ControllerButton',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

        _create_axis_model: function(index) {
            /* Creates a gamepad axis widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'Jupyter.ControllerAxis',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

    }, {
        serializers: _.extend({
            buttons: {deserialize: widget.unpack_models},
            axes: {deserialize: widget.unpack_models},
        }, widget.DOMWidgetModel.serializers)
    });

    var ControllerView = widget.DOMWidgetView.extend({
        /* A simple view for a gamepad. */

        initialize: function() {
            ControllerView.__super__.initialize.apply(this, arguments);

            this.button_views = new widget.ViewList(this.add_button, null, this);
            this.listenTo(this.model, 'change:buttons', function(model, value) {
                this.button_views.update(value);
            }, this);

            this.axis_views = new widget.ViewList(this.add_axis, null, this);
            this.listenTo(this.model, 'change:axes', function(model, value) {
                this.axis_views.update(value);
            }, this);

            this.listenTo(this.model, 'change:name', this.update_label, this);
        },

        render: function(){
            this.$el.addClass('ipy-widget widget-controller');

            this.$box = this.$el;

            this.$label = $('<div />')
                .appendTo(this.$box);

            this.$axis_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.$button_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.button_views.update(this.model.get('buttons'));
            this.axis_views.update(this.model.get('axes'));

            this.update_label();
        },

        update_label: function() {
            this.$label.text(this.model.get('name') || this.model.readout);
        },

        add_button: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$button_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed', that);
                });
                return view;
            }).catch(utils.reject('Could not add button view', true));
        },

        add_axis: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$axis_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed', that);
                });
                return view;
            }).catch(utils.reject('Could not add axis view', true));
        },

        remove: function() {
            ControllerView.__super__.remove.apply(this, arguments);
            this.button_views.remove();
            this.axis_views.remove();
        },

    });

    return {
        ControllerButton: Button,
        ControllerAxis: Axis,
        Controller: Controller,
        ControllerView: ControllerView,
    };
});
<|endoftext|>


<commit_before>var pump = require('pump')
var ndjson = require('ndjson')
var openDat = require('../lib/open-dat.js')
var abort = require('../lib/abort.js')
var usage = require('../lib/usage.js')('diff.txt')

module.exports = {
  name: 'diff',
  command: handleDiff
}

function handleDiff (args) {
  if (args.help) return usage()
  if (args._.length < 2) return usage()

  openDat(args, function ready (err, db) {
    if (err) abort(err)

    var diffs = db.createDiffStream(args._[0], args._[1])
    pump(diffs, ndjson.serialize(), process.stdout, function done (err) {
      if (err) throw err
    })
  })
}
<commit_msg>Format dat diff properly, to include checkout<commit_after>var pump = require('pump')
var through = require('through2')
var ndjson = require('ndjson')
var openDat = require('../lib/open-dat.js')
var abort = require('../lib/abort.js')
var usage = require('../lib/usage.js')('diff.txt')

module.exports = {
  name: 'diff',
  command: handleDiff
}

function handleDiff (args) {
  if (args.help) return usage()
  if (args._.length < 2) return usage()

  openDat(args, function ready (err, db) {
    if (err) abort(err)

    var headA = args._[0]
    var headB = args._[1]

    var diffs = db.createDiffStream(headA, headB)
    pump(diffs, datDiffFormatter(), ndjson.serialize(), process.stdout, function done (err) {
      if (err) throw err
    })

    function datDiffFormatter () {
      return through.obj(function write (obj, enc, next) {
        var a = obj[0]
        var b = obj[1]
        var diff = {}
        if (a) diff.key = a.key
        if (b) diff.key = b.key
        diff.versions = []
        if (a) {
          a.checkout = headA
          diff.versions.push(a)
        } else {
          diff.versions.push(null)
        }
        if (b) {
          b.checkout = headB
          diff.versions.push(b)
        } else {
          diff.versions.push(null)
        }
        next(null, diff)
      })
    }
  })
}
<|endoftext|>