<commit_before>var modalHTML = "\

\
  \

\

";
var modal = undefined;
var flashInterval = 1250;
var flashWaitMultiple = 6;
var enterCode = 13;
var escapeCode = 27;
var spaceCode = 32;
var closeModalKeyCodes = [enterCode, escapeCode, spaceCode];
var notificationAudio = document.currentScript.dataset.notificationAudio;

function Modal(){
    this.msgQueue = [];
    this.modalElement = undefined;
}

// Add messages to the Modal queue
Modal.prototype.queueMsg = function queueMsg(msg) {
    this.msgQueue.push(msg);
    this.generateModal();
};

// Create a modal from modalHTML and append to the bottom of the document
Modal.prototype.createModal = function createModal(msg) {
    var span = document.createElement("span");
    span.id = "gentle-alerts-modal";
    span.innerHTML = modalHTML;
    document.documentElement.appendChild(span);
    var modalContent = document.getElementById("gentle-alerts-modal-content-text");
    modalContent.textContent = msg;
    this.modalElement = document.getElementById("gentle-alerts-modal");
    this.modalElement.style.display = "block";
    this.flashTab();
};

// Find and delete the modal
Modal.prototype.deleteModal = function deleteModal() {
    if (this.modalElement === undefined) {
        return;
    }
    this.modalElement.parentNode.removeChild(this.modalElement);
    this.modalElement = undefined;
    this.stopFlashTab();
};

// Create, set the modal content, and show it
Modal.prototype.generateModal = function generateModal() {
    if (this.modalElement) {
        return;
    }
    var msg = this.msgQueue.shift();
    if (msg === undefined) {
        return;
    }
    this.createModal(msg);
    this.registerModalClose();
};

// Set up an event to process closing the modal
Modal.prototype.registerModalClose = function registerModalClose() {
    var self = this;
    var originalCallbacks = {};
    function isOnclick(onClickEvent) {
        return onClickEvent.target == self.modalElement;
    }
    function isOnKeyUp(onKeyUpEvent) {
        return closeModalKeyCodes.indexOf(onKeyUpEvent.keyCode) >= 0;
    }
    function generateEvent(onClickCorrect, windowEvent) {
        originalCallbacks[windowEvent] = window[windowEvent];
        var callback = function eventCallback(eventObject) {
            if (!onClickCorrect(eventObject)) {
                return;
            }
            self.deleteModal();
            Object.keys(originalCallbacks).forEach(function (key) {
                var originalCallback = originalCallbacks[key];
                window[key] = originalCallback;
            });
            self.generateModal();
            eventObject.preventDefault();
            return false;
        };
        window[windowEvent] = callback;
    }
    // When the user clicks anywhere outside of the modal, close it
    generateEvent(isOnclick, "onclick");
    generateEvent(isOnKeyUp, "onkeyup");
};

// Start flashing tab at intervals
Modal.prototype.flashTab = function flashTab() {
    this.flasher = setInterval(function flashOn() {
        if (notificationAudio) {
            var audio = new Audio(notificationAudio);
            audio.play();
        }
        var originalTitle = document.title;
        document.title = originalTitle + " - Alert";
        setTimeout(function flashOff() {
            document.title = originalTitle;
        }, flashInterval);
    }, flashInterval * flashWaitMultiple);
};

// Stop flashing tab
Modal.prototype.stopFlashTab = function stopFlashTab() {
    clearInterval(this.flasher);
};

function gentleAlert(msg) {
    if (modal === undefined) {
        modal = new Modal();
    }
    modal.queueMsg(msg);
}

if (typeof window !== "undefined" && window.alert != "undefined") {
    window.alert = gentleAlert;
}
<commit_msg>Remove commented out close button<commit_after>var modalHTML = "\

\

\

";
var modal = undefined;
var flashInterval = 1250;
var flashWaitMultiple = 6;
var enterCode = 13;
var escapeCode = 27;
var spaceCode = 32;
var closeModalKeyCodes = [enterCode, escapeCode, spaceCode];
var notificationAudio = document.currentScript.dataset.notificationAudio;

function Modal(){
    this.msgQueue = [];
    this.modalElement = undefined;
}

// Add messages to the Modal queue
Modal.prototype.queueMsg = function queueMsg(msg) {
    this.msgQueue.push(msg);
    this.generateModal();
};

// Create a modal from modalHTML and append to the bottom of the document
Modal.prototype.createModal = function createModal(msg) {
    var span = document.createElement("span");
    span.id = "gentle-alerts-modal";
    span.innerHTML = modalHTML;
    document.documentElement.appendChild(span);
    var modalContent = document.getElementById("gentle-alerts-modal-content-text");
    modalContent.textContent = msg;
    this.modalElement = document.getElementById("gentle-alerts-modal");
    this.modalElement.style.display = "block";
    this.flashTab();
};

// Find and delete the modal
Modal.prototype.deleteModal = function deleteModal() {
    if (this.modalElement === undefined) {
        return;
    }
    this.modalElement.parentNode.removeChild(this.modalElement);
    this.modalElement = undefined;
    this.stopFlashTab();
};

// Create, set the modal content, and show it
Modal.prototype.generateModal = function generateModal() {
    if (this.modalElement) {
        return;
    }
    var msg = this.msgQueue.shift();
    if (msg === undefined) {
        return;
    }
    this.createModal(msg);
    this.registerModalClose();
};

// Set up an event to process closing the modal
Modal.prototype.registerModalClose = function registerModalClose() {
    var self = this;
    var originalCallbacks = {};
    function isOnclick(onClickEvent) {
        return onClickEvent.target == self.modalElement;
    }
    function isOnKeyUp(onKeyUpEvent) {
        return closeModalKeyCodes.indexOf(onKeyUpEvent.keyCode) >= 0;
    }
    function generateEvent(onClickCorrect, windowEvent) {
        originalCallbacks[windowEvent] = window[windowEvent];
        var callback = function eventCallback(eventObject) {
            if (!onClickCorrect(eventObject)) {
                return;
            }
            self.deleteModal();
            Object.keys(originalCallbacks).forEach(function (key) {
                var originalCallback = originalCallbacks[key];
                window[key] = originalCallback;
            });
            self.generateModal();
            eventObject.preventDefault();
            return false;
        };
        window[windowEvent] = callback;
    }
    // When the user clicks anywhere outside of the modal, close it
    generateEvent(isOnclick, "onclick");
    generateEvent(isOnKeyUp, "onkeyup");
};

// Start flashing tab at intervals
Modal.prototype.flashTab = function flashTab() {
    this.flasher = setInterval(function flashOn() {
        if (notificationAudio) {
            var audio = new Audio(notificationAudio);
            audio.play();
        }
        var originalTitle = document.title;
        document.title = originalTitle + " - Alert";
        setTimeout(function flashOff() {
            document.title = originalTitle;
        }, flashInterval);
    }, flashInterval * flashWaitMultiple);
};

// Stop flashing tab
Modal.prototype.stopFlashTab = function stopFlashTab() {
    clearInterval(this.flasher);
};

function gentleAlert(msg) {
    if (modal === undefined) {
        modal = new Modal();
    }
    modal.queueMsg(msg);
}

if (typeof window !== "undefined" && window.alert != "undefined") {
    window.alert = gentleAlert;
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name ng.directive:ngView
 * @restrict ECA
 *
 * @description
 * # Overview
 * `ngView` is a directive that complements the {@link ng.$route $route} service by
 * including the rendered template of the current route into the main layout (`index.html`) file.
 * Every time the current route changes, the included view changes with it according to the
 * configuration of the `$route` service.
 *
 * @scope
 * @example
    <example module="ngView">
      <file name="index.html">

          Choose:
          Moby |
          Moby: Ch1 |
          Gatsby |
          Gatsby: Ch4 |
          Scarlet Letter

$location.path() = {{$location.path()}}

$route.current.template = {{$route.current.template}}

$route.current.params = {{$route.current.params}}

$route.current.scope.name = {{$route.current.scope.name}}

$routeParams = {{$routeParams}}

      </file>

      <file name="book.html">
        controller: {{name}}

        Book Id: {{params.bookId}}

      </file>

      <file name="chapter.html">
        controller: {{name}}

        Book Id: {{params.bookId}}

        Chapter Id: {{params.chapterId}}
      </file>

      <file name="script.js">
        angular.module('ngView', [], function($routeProvider, $locationProvider) {
          $routeProvider.when('/Book/:bookId', {
            templateUrl: 'book.html',
            controller: BookCntl
          });
          $routeProvider.when('/Book/:bookId/ch/:chapterId', {
            templateUrl: 'chapter.html',
            controller: ChapterCntl
          });

          // configure html5 to get links working on jsfiddle
          $locationProvider.html5Mode(true);
        });

        function MainCntl($scope, $route, $routeParams, $location) {
          $scope.$route = $route;
          $scope.$location = $location;
          $scope.$routeParams = $routeParams;
        }

        function BookCntl($scope, $routeParams) {
          $scope.name = "BookCntl";
          $scope.params = $routeParams;
        }

        function ChapterCntl($scope, $routeParams) {
          $scope.name = "ChapterCntl";
          $scope.params = $routeParams;
        }
      </file>

      <file name="scenario.js">
        it('should load and compile correct template', function() {
          element('a:contains("Moby: Ch1")').click();
          var content = element('.doc-example-live [ng-view]').text();
          expect(content).toMatch(/controller\: ChapterCntl/);
          expect(content).toMatch(/Book Id\: Moby/);
          expect(content).toMatch(/Chapter Id\: 1/);

          element('a:contains("Scarlet")').click();
          content = element('.doc-example-live [ng-view]').text();
          expect(content).toMatch(/controller\: BookCntl/);
          expect(content).toMatch(/Book Id\: Scarlet/);
        });
      </file>
    </example>
 */

/**
 * @ngdoc event
 * @name ng.directive:ngView#$viewContentLoaded
 * @eventOf ng.directive:ngView
 * @eventType emit on the current ngView scope
 * @description
 * Emitted every time the ngView content is reloaded.
 */
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
                       '$controller',
               function($http,   $templateCache,   $route,   $anchorScroll,   $compile,
                        $controller) {
  return {
    restrict: 'ECA',
    terminal: true,
    link: function(scope, element, attr) {
      var lastScope,
          onloadExp = attr.onload || '';

      scope.$on('$routeChangeSuccess', update);
      update();

      function destroyLastScope() {
        if (lastScope) {
          lastScope.$destroy();
          lastScope = null;
        }
      }

      function clearContent() {
        element.html('');
        destroyLastScope();
      }

      function update() {
        var locals = $route.current && $route.current.locals,
            template = locals && locals.$template;

        if (template) {
          element.html(template);
          destroyLastScope();

          var link = $compile(element.contents()),
              current = $route.current,
              controller;

          lastScope = current.scope = scope.$new();
          if (current.controller) {
            locals.$scope = lastScope;
            controller = $controller(current.controller, locals);
            element.contents().data('$ngControllerController', controller);
          }

          link(lastScope);
          lastScope.$emit('$viewContentLoaded');
          lastScope.$eval(onloadExp);

          // $anchorScroll might listen on event...
          $anchorScroll();
        } else {
          clearContent();
        }
      }
    }
  };
}];
<commit_msg>docs(ngView): fix code example (change template to templateUrl)<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name ng.directive:ngView
 * @restrict ECA
 *
 * @description
 * # Overview
 * `ngView` is a directive that complements the {@link ng.$route $route} service by
 * including the rendered template of the current route into the main layout (`index.html`) file.
 * Every time the current route changes, the included view changes with it according to the
 * configuration of the `$route` service.
 *
 * @scope
 * @example
    <example module="ngView">
      <file name="index.html">

          Choose:
          Moby |
          Moby: Ch1 |
          Gatsby |
          Gatsby: Ch4 |
          Scarlet Letter

$location.path() = {{$location.path()}}

$route.current.templateUrl = {{$route.current.templateUrl}}

$route.current.params = {{$route.current.params}}

$route.current.scope.name = {{$route.current.scope.name}}

$routeParams = {{$routeParams}}

      </file>

      <file name="book.html">
        controller: {{name}}

        Book Id: {{params.bookId}}

      </file>

      <file name="chapter.html">
        controller: {{name}}

        Book Id: {{params.bookId}}

        Chapter Id: {{params.chapterId}}
      </file>

      <file name="script.js">
        angular.module('ngView', [], function($routeProvider, $locationProvider) {
          $routeProvider.when('/Book/:bookId', {
            templateUrl: 'book.html',
            controller: BookCntl
          });
          $routeProvider.when('/Book/:bookId/ch/:chapterId', {
            templateUrl: 'chapter.html',
            controller: ChapterCntl
          });

          // configure html5 to get links working on jsfiddle
          $locationProvider.html5Mode(true);
        });

        function MainCntl($scope, $route, $routeParams, $location) {
          $scope.$route = $route;
          $scope.$location = $location;
          $scope.$routeParams = $routeParams;
        }

        function BookCntl($scope, $routeParams) {
          $scope.name = "BookCntl";
          $scope.params = $routeParams;
        }

        function ChapterCntl($scope, $routeParams) {
          $scope.name = "ChapterCntl";
          $scope.params = $routeParams;
        }
      </file>

      <file name="scenario.js">
        it('should load and compile correct template', function() {
          element('a:contains("Moby: Ch1")').click();
          var content = element('.doc-example-live [ng-view]').text();
          expect(content).toMatch(/controller\: ChapterCntl/);
          expect(content).toMatch(/Book Id\: Moby/);
          expect(content).toMatch(/Chapter Id\: 1/);

          element('a:contains("Scarlet")').click();
          content = element('.doc-example-live [ng-view]').text();
          expect(content).toMatch(/controller\: BookCntl/);
          expect(content).toMatch(/Book Id\: Scarlet/);
        });
      </file>
    </example>
 */

/**
 * @ngdoc event
 * @name ng.directive:ngView#$viewContentLoaded
 * @eventOf ng.directive:ngView
 * @eventType emit on the current ngView scope
 * @description
 * Emitted every time the ngView content is reloaded.
 */
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
                       '$controller',
               function($http,   $templateCache,   $route,   $anchorScroll,   $compile,
                        $controller) {
  return {
    restrict: 'ECA',
    terminal: true,
    link: function(scope, element, attr) {
      var lastScope,
          onloadExp = attr.onload || '';

      scope.$on('$routeChangeSuccess', update);
      update();

      function destroyLastScope() {
        if (lastScope) {
          lastScope.$destroy();
          lastScope = null;
        }
      }

      function clearContent() {
        element.html('');
        destroyLastScope();
      }

      function update() {
        var locals = $route.current && $route.current.locals,
            template = locals && locals.$template;

        if (template) {
          element.html(template);
          destroyLastScope();

          var link = $compile(element.contents()),
              current = $route.current,
              controller;

          lastScope = current.scope = scope.$new();
          if (current.controller) {
            locals.$scope = lastScope;
            controller = $controller(current.controller, locals);
            element.contents().data('$ngControllerController', controller);
          }

          link(lastScope);
          lastScope.$emit('$viewContentLoaded');
          lastScope.$eval(onloadExp);

          // $anchorScroll might listen on event...
          $anchorScroll();
        } else {
          clearContent();
        }
      }
    }
  };
}];
<|endoftext|>


<commit_before>/*********************
//* jQuery Drop Line Menu- By Dynamic Drive: http://www.dynamicdrive.com/
//* Last updated: May 9th, 11'
//* Menu avaiable at DD CSS Library: http://www.dynamicdrive.com/style/
*********************/

var droplinemenu={

arrowimage: {classname: 'downarrowclass', src: '/bundles/ceradapp/images/down.gif', leftpadding: 5}, //customize down arrow image
animateduration: {over: 200, out: 100}, //duration of slide in/ out animation, in milliseconds

buildmenu:function(menuid){
	jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={h:$curobj.find('a:eq(0)').outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			if (!this.istopheader)
				$subul.css({left:0, top:this._dimensions.h})
			var $innerheader=$curobj.children('a').eq(0)
			$innerheader=($innerheader.children().eq(0).is('span'))? $innerheader.children().eq(0) : $innerheader //if header contains inner SPAN, use that
			$innerheader.append(
				''
			)
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					if ($targetul.queue().length<=1) //if 1 or less queued animations
						if (this.istopheader)
							$targetul.css({left: $mainmenu.position().left, top: $mainmenu.position().top+this._dimensions.h})
						if (document.all && !window.XMLHttpRequest) //detect IE6 or less, fix issue with overflow
							$mainmenu.find('ul').css({overflow: (this.istopheader)? 'hidden' : 'visible'})
						$targetul.dequeue().slideDown(droplinemenu.animateduration.over)
				},
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					$targetul.dequeue().slideUp(droplinemenu.animateduration.out)
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible', width:$mainmenu.width()})
	}) //end document.ready
}
}

<commit_msg>Updated path to images<commit_after>/*********************
//* jQuery Drop Line Menu- By Dynamic Drive: http://www.dynamicdrive.com/
//* Last updated: May 9th, 11'
//* Menu avaiable at DD CSS Library: http://www.dynamicdrive.com/style/
*********************/

var droplinemenu={

arrowimage: {classname: 'downarrowclass', src: '/s1games/bundles/ceradapp/images/down.gif', leftpadding: 5}, //customize down arrow image
animateduration: {over: 200, out: 100}, //duration of slide in/ out animation, in milliseconds

buildmenu:function(menuid){
	jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={h:$curobj.find('a:eq(0)').outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			if (!this.istopheader)
				$subul.css({left:0, top:this._dimensions.h})
			var $innerheader=$curobj.children('a').eq(0)
			$innerheader=($innerheader.children().eq(0).is('span'))? $innerheader.children().eq(0) : $innerheader //if header contains inner SPAN, use that
			$innerheader.append(
				''
			)
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					if ($targetul.queue().length<=1) //if 1 or less queued animations
						if (this.istopheader)
							$targetul.css({left: $mainmenu.position().left, top: $mainmenu.position().top+this._dimensions.h})
						if (document.all && !window.XMLHttpRequest) //detect IE6 or less, fix issue with overflow
							$mainmenu.find('ul').css({overflow: (this.istopheader)? 'hidden' : 'visible'})
						$targetul.dequeue().slideDown(droplinemenu.animateduration.over)
				},
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					$targetul.dequeue().slideUp(droplinemenu.animateduration.out)
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible', width:$mainmenu.width()})
	}) //end document.ready
}
}

<|endoftext|>


<commit_before>/**
 * Show the request user has made in the last times (month or 21 days)
 *
 * It just prints the requests data as a simple chart.
 * It needs the data as an Array to work.
 *
 * Usage example:
 *
 *    // D3 API Requests
 *    this.stats = this.stats = new cdb.admin.D3Stats({
 *      el: this.$el.find("li:eq(2)"),
 *      stats: { 2013-12-05: 3, 2013-12-06: 0, 2013-12-07: 30, 2013-12-08: 100, 2013-12-09: 0 }
 *    });
 */

cdb.admin.D3Stats = cdb.core.View.extend({

  tagName: 'div',
  className: 'stats',

  default_options: {
    show_today: false,
    width: 291,
    height: 33,
    stroke_width: 2
  },

  initialize: function() {

    // Get data
    this.requests = _.toArray(this.options.stats)
    this.dates    = _.keys(this.options.stats);

    this.options = _.extend(this.default_options, this.options);

    // Render graphic!
    this.render();
  },

  render: function() {

    var self = this;

    // SVG
    var width  = this.options.width
      , height = this.options.height
      , svg    = d3.select(this.$("div.stats")[0])
                .append("svg")
                .attr("width", width)
                .attr("height", height + 3)
      , max = _.max(_(this.requests).map(function(m){ return parseInt(m, 10) }));

    // Get scales and create the line
    var x = d3.scale.linear().domain([0, this.requests.length]).range([0, width])
      , y = d3.scale.linear().domain([0,max]).range([height,2])
      , line = d3.svg.line()
      .x(function(d,i) { return x(i); })
      .y(function(d)   { return y(d); })
      , area = d3.svg.area()
      .x(function(d,i) { return x(i); })
      .y0(function(d)  { return height + 3; })
      .y1(function(d)  { return y(d); });

    var div;

    // Creates the tooltip
    if (!$(".mapviews_tooltip").length) {

      var div = d3.select("body").append("div")
        .attr("class", "mapviews_tooltip")
        .style("opacity", 1e-6);

      div.append("span");

      div.append("div")
        .attr("class", "tip")

    } else {
      div = d3.select(".mapviews_tooltip")
    }

    function mouseover() {
      div.transition().duration(200).style("opacity", 1);
    }

    function mousemove() {
      var x0    = d3.mouse(this)[0];
      var y0    = d3.mouse(this)[1];
      var n     = x.invert(x0) | 0;
      var value = self.requests[n];
      var total =  _.reduce(self.requests, function(memo, num){ return memo + num; }, 0);

      var w = $(".mapviews_tooltip").width();

      var when = self.dates[n];

      if (moment(new Date()).format("YYYY-MM-DD") == when ) when = "today";
      else when = "in " + when;

      $(".mapviews_tooltip span").html(self._formatNumber(value) + " " + when + ".
" + self._formatNumber(total) + " in the last month");
      $(".mapviews_tooltip .tip")
        .css("left", (w/2 + 0) + "px")

        div
        .style("left", (d3.event.pageX - w/2 - 2) + "px")
        .style("top", (d3.event.pageY - 45) + "px")

    }

    function mouseout() {
      div.transition().duration(200).style("opacity", 1e-6);
    }

    svg
      .on("mouseover", mouseover)
      .on("mousemove", mousemove)
      .on("mouseout", mouseout)

      // display the line by appending an svg:path element with the data line we created above
      svg.append("svg:path")
      .attr("d", area(this.requests))
      .style("fill", "#ECF5FA")

      var l = svg.append("svg:path")
      .attr("d", line(this.requests))
      .style("fill", "none")
      .style("stroke-width", this.options.stroke_width)
      .style("stroke", "#409FCE")

      if (this.options.show_today) {

        var lx = this.requests.length - 1;
        var ly = this.requests[this.requests.length - 1];

        if (lx != null && ly != null) {
          circle = svg.append("svg:circle")
            .attr("cx", x(lx))
            .attr("cy", y(ly))
            .attr("r", 2)
            .style("stroke", "none")
            .style("fill", "#409FCE")
        }
      }

    // Put total api calls
    this.$("p").html(
        "" + this._formatNumber(_.reduce(this.requests, function(memo, num){ return memo + num; }, 0)) + " map views last " + _.size(this.requests) + " days"
        )

      return this;
  },

  _formatNumber: function(str) {
    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";
    for ( var i = 0; i <= amount.length-1; i++ ){
      output = amount[i] + output;
      if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
    }
    return output;
  }

});
<commit_msg>CDB-1589 #fixes Fixes d3stats for organizations<commit_after>/**
 * Show the request user has made in the last times (month or 21 days)
 *
 * It just prints the requests data as a simple chart.
 * It needs the data as an Array to work.
 *
 * Usage example:
 *
 *    // D3 API Requests
 *    this.stats = this.stats = new cdb.admin.D3Stats({
 *      el: this.$el.find("li:eq(2)"),
 *      stats: { 2013-12-05: 3, 2013-12-06: 0, 2013-12-07: 30, 2013-12-08: 100, 2013-12-09: 0 }
 *    });
 */

cdb.admin.D3Stats = cdb.core.View.extend({

  tagName: 'div',
  className: 'stats',

  default_options: {
    show_today: false,
    width: 291,
    height: 33,
    stroke_width: 2
  },

  initialize: function() {

    // Get data
    if (this.options.api_calls) {
      this.requests = this.options.api_calls;
      //this.dates    = _.keys(this.options.stats);
    } else {
      this.requests = _.toArray(this.options.stats)
      this.dates    = _.keys(this.options.stats);
    }

    this.options = _.extend(this.default_options, this.options);

    // Render graphic!
    this.render();
  },

  render: function() {

    var self = this;

    // SVG
    var width  = this.options.width
      , height = this.options.height
      , svg    = d3.select(this.$("div.stats")[0])
                .append("svg")
                .attr("width", width)
                .attr("height", height + 3)
      , max = _.max(_(this.requests).map(function(m){ return parseInt(m, 10) }));

    // Get scales and create the line
    var x = d3.scale.linear().domain([0, this.requests.length]).range([0, width])
      , y = d3.scale.linear().domain([0,max]).range([height,2])
      , line = d3.svg.line()
      .x(function(d,i) { return x(i); })
      .y(function(d)   { return y(d); })
      , area = d3.svg.area()
      .x(function(d,i) { return x(i); })
      .y0(function(d)  { return height + 3; })
      .y1(function(d)  { return y(d); });

    var div;

    // Creates the tooltip
    if (!$(".mapviews_tooltip").length) {

      var div = d3.select("body").append("div")
        .attr("class", "mapviews_tooltip")
        .style("opacity", 1e-6);

      div.append("span");

      div.append("div")
        .attr("class", "tip")

    } else {
      div = d3.select(".mapviews_tooltip")
    }

    function mouseover() {
      div.transition().duration(200).style("opacity", 1);
    }

    function mousemove() {
      var x0    = d3.mouse(this)[0];
      var y0    = d3.mouse(this)[1];
      var n     = x.invert(x0) | 0;
      var value = self.requests[n];
      var total =  _.reduce(self.requests, function(memo, num){ return memo + num; }, 0);

      var w = $(".mapviews_tooltip").width();

      var when;

      if (self.dates) {
        when = self.dates[n];
      } else {
        when = self.requests[n];
      }

      if (moment(new Date()).format("YYYY-MM-DD") == when ) when = "today";
      else when = "in " + when;

      $(".mapviews_tooltip span").html(self._formatNumber(value) + " " + when + ".
" + self._formatNumber(total) + " in the last month");
      $(".mapviews_tooltip .tip")
        .css("left", (w/2 + 0) + "px")

        div
        .style("left", (d3.event.pageX - w/2 - 2) + "px")
        .style("top", (d3.event.pageY - 45) + "px")

    }

    function mouseout() {
      div.transition().duration(200).style("opacity", 1e-6);
    }

    svg
      .on("mouseover", mouseover)
      .on("mousemove", mousemove)
      .on("mouseout", mouseout)

      // display the line by appending an svg:path element with the data line we created above
      svg.append("svg:path")
      .attr("d", area(this.requests))
      .style("fill", "#ECF5FA")

      var l = svg.append("svg:path")
      .attr("d", line(this.requests))
      .style("fill", "none")
      .style("stroke-width", this.options.stroke_width)
      .style("stroke", "#409FCE")

      if (this.options.show_today) {

        var lx = this.requests.length - 1;
        var ly = this.requests[this.requests.length - 1];

        if (lx != null && ly != null) {
          circle = svg.append("svg:circle")
            .attr("cx", x(lx))
            .attr("cy", y(ly))
            .attr("r", 2)
            .style("stroke", "none")
            .style("fill", "#409FCE")
        }
      }

    // Put total api calls
    this.$("p").html(
        "" + this._formatNumber(_.reduce(this.requests, function(memo, num){ return memo + num; }, 0)) + " map views last " + _.size(this.requests) + " days"
        )

      return this;
  },

  _formatNumber: function(str) {
    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";
    for ( var i = 0; i <= amount.length-1; i++ ){
      output = amount[i] + output;
      if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
    }
    return output;
  }

});
<|endoftext|>


<commit_before>/**
 * base class for all small dialogs
 * inherit from this class, see EditTextDialog
 * for an example
 */
cdb.admin.SmallDialog = cdb.ui.common.Dialog.extend({

  className: 'floating',

  initialize: function() {
    _.extend(this.options, {
              title: '',
              description: '',
              clean_on_hide: true
    });
    cdb.ui.common.Dialog.prototype.initialize.apply(this);
    this.render();
    $(document.body).append(this.el);
  },

  /** show at position */
  showAt: function(x, y, width, fix) {
    this.$el.css({
      top: y,
      left: x,
      minWidth: width
    });

    if (fix) {
      this.$el.find("> textarea, > input").css({
        minWidth: width - 22
      })
    }

    this.show();
  },

  /**
   * show the dialog on top of an element
   * useful in events:
      dlg.showAtElement(e.target);
   */
  showAtElement: function(el) {
    var pos = $(el).offset();
    this.showAt(pos.left, pos.top);
  }
});

cdb.admin.EditTextDialog = cdb.admin.SmallDialog.extend({

  events: cdb.core.View.extendEvents({
    'keypress input': '_keyPress',
    'click': '_stopPropagation'
  }),

  initialize: function() {
    _.defaults(this.options, {
      template_name: 'old_common/views/dialog_small_edit',
      ok_title: 'Save',
      modal_class: 'edit_text_dialog',
      clean_on_hide: true
    });
    this.constructor.__super__.initialize.apply(this);
  },

  render_content: function() {
    this._focusInput();
    var input = '<input value="' + this.options.initial_value.replace(/\"/g,'"').replace(/\'/g,"'") + '" ';
    if(this.options.maxLength) {
      input += 'maxLength = ' + this.options.maxLength;
    }
    input += ' type="text"/>';
    return input;
  },

  _stopPropagation: function(e) {
    e.stopPropagation();
  },

  _focusInput: function() {
    var self = this;
    setTimeout(function(){
      var width = self.$el.outerWidth() - self.$el.find("a.button").outerWidth() - 35;
      self.$el.find("input").width(width).focus();
    },0);
  },

  _keyPress: function(e) {
    if(e.keyCode === 13) {
      this._ok();
    }
  },

  ok: function() {
    if(this.options.onResponse) {
      this.options.onResponse(this.$('input').val());
    }
  }
});

cdb.admin.EditMarkdownDialog = cdb.admin.SmallDialog.extend({

  events: cdb.core.View.extendEvents({
    'keypress input': '_keyPress',
    'click': '_stopPropagation'
  }),

  initialize: function() {
    _.defaults(this.options, {
      old_template_name: 'old_common/views/dialog_markdown_edit',
      ok_title: 'Save',
      modal_class: 'edit_name_dialog markdown',
      clean_on_hide: true
    });
    this.constructor.__super__.initialize.apply(this);
  },

  render_content: function() {
    this._focusInput();
    var input = '
<input value="' + this.options.initial_value.replace(/\"/g,'"').replace(/\'/g,"'") + '" ';
    if(this.options.maxLength) {
      input += 'maxLength = ' + this.options.maxLength;
    }
    input += ' type="text"/>
**bold** *italics* [link title](url)

';
    return input;
  },

  _stopPropagation: function(e) {
    e.stopPropagation();
  },

  _focusInput: function() {
    var self = this;
    setTimeout(function(){
      var width = self.$el.outerWidth() - self.$el.find("a.button").outerWidth() - 35;
      self.$el.find(".input_field").width(width);
      self.$el.find(".input_field input").focus();
    },0);
  },

  _keyPress: function(e) {
    if(e.keyCode === 13) {
      this._ok();
    }
  },

  ok: function() {
    if(this.options.onResponse) {
      this.options.onResponse(this.$('input').val());
    }
  }

});

cdb.admin.TagsDialog = cdb.admin.SmallDialog.extend({

  className: "floating edit_name_dialog tags-dialog",

  events: cdb.core.View.extendEvents({
    'click': '_stopPropagation'
  }),

  initialize: function() {
    _.defaults(this.options, {
      template_name: 'old_common/views/dialog_small_edit',
      ok_title: 'Save',
      modal_class: 'edit_text_dialog',
      clean_on_hide: true
    });
    this.constructor.__super__.initialize.apply(this);
  },

  render_content: function() {
    var $list = this.$list = $("
")
      , list  = this.options.initial_value
      , self  = this;

    _.each(list, function(li) {
      $list.append("
" + li + "
");
    });

    $list.tagit({
      allowSpaces: true,
      onSubmitTags: function(ev,tagList) {
        self.$el.find("a.ok").click();
      }
    });

    this._focusInput();

    return $list;
  },

  _stopPropagation: function(e) {
    e.stopPropagation();
  },

  _focusInput: function() {
    var self = this;
    setTimeout(function(){
      self.$el.find("input").focus();
    },0);
  },

  ok: function() {
    if (this.options.onResponse) {
      var tags = [];
      this.$el.find("li span.tagit-label").each(function(i,el){
        tags.push($(this).text());
      });

      this.$list.tagit("destroy");
      this.options.onResponse(tags);
    }
  }
});
<commit_msg>Removed small tags dialog from small_dialog view<commit_after>/**
 * base class for all small dialogs
 * inherit from this class, see EditTextDialog
 * for an example
 */
cdb.admin.SmallDialog = cdb.ui.common.Dialog.extend({

  className: 'floating',

  initialize: function() {
    _.extend(this.options, {
              title: '',
              description: '',
              clean_on_hide: true
    });
    cdb.ui.common.Dialog.prototype.initialize.apply(this);
    this.render();
    $(document.body).append(this.el);
  },

  /** show at position */
  showAt: function(x, y, width, fix) {
    this.$el.css({
      top: y,
      left: x,
      minWidth: width
    });

    if (fix) {
      this.$el.find("> textarea, > input").css({
        minWidth: width - 22
      })
    }

    this.show();
  },

  /**
   * show the dialog on top of an element
   * useful in events:
      dlg.showAtElement(e.target);
   */
  showAtElement: function(el) {
    var pos = $(el).offset();
    this.showAt(pos.left, pos.top);
  }
});

cdb.admin.EditTextDialog = cdb.admin.SmallDialog.extend({

  events: cdb.core.View.extendEvents({
    'keypress input': '_keyPress',
    'click': '_stopPropagation'
  }),

  initialize: function() {
    _.defaults(this.options, {
      template_name: 'old_common/views/dialog_small_edit',
      ok_title: 'Save',
      modal_class: 'edit_text_dialog',
      clean_on_hide: true
    });
    this.constructor.__super__.initialize.apply(this);
  },

  render_content: function() {
    this._focusInput();
    var input = '<input value="' + this.options.initial_value.replace(/\"/g,'"').replace(/\'/g,"'") + '" ';
    if(this.options.maxLength) {
      input += 'maxLength = ' + this.options.maxLength;
    }
    input += ' type="text"/>';
    return input;
  },

  _stopPropagation: function(e) {
    e.stopPropagation();
  },

  _focusInput: function() {
    var self = this;
    setTimeout(function(){
      var width = self.$el.outerWidth() - self.$el.find("a.button").outerWidth() - 35;
      self.$el.find("input").width(width).focus();
    },0);
  },

  _keyPress: function(e) {
    if(e.keyCode === 13) {
      this._ok();
    }
  },

  ok: function() {
    if(this.options.onResponse) {
      this.options.onResponse(this.$('input').val());
    }
  }
});

cdb.admin.EditMarkdownDialog = cdb.admin.SmallDialog.extend({

  events: cdb.core.View.extendEvents({
    'keypress input': '_keyPress',
    'click': '_stopPropagation'
  }),

  initialize: function() {
    _.defaults(this.options, {
      old_template_name: 'old_common/views/dialog_markdown_edit',
      ok_title: 'Save',
      modal_class: 'edit_name_dialog markdown',
      clean_on_hide: true
    });
    this.constructor.__super__.initialize.apply(this);
  },

  render_content: function() {
    this._focusInput();
    var input = '
<input value="' + this.options.initial_value.replace(/\"/g,'"').replace(/\'/g,"'") + '" ';
    if(this.options.maxLength) {
      input += 'maxLength = ' + this.options.maxLength;
    }
    input += ' type="text"/>
**bold** *italics* [link title](url)

';
    return input;
  },

  _stopPropagation: function(e) {
    e.stopPropagation();
  },

  _focusInput: function() {
    var self = this;
    setTimeout(function(){
      var width = self.$el.outerWidth() - self.$el.find("a.button").outerWidth() - 35;
      self.$el.find(".input_field").width(width);
      self.$el.find(".input_field input").focus();
    },0);
  },

  _keyPress: function(e) {
    if(e.keyCode === 13) {
      this._ok();
    }
  },

  ok: function() {
    if(this.options.onResponse) {
      this.options.onResponse(this.$('input').val());
    }
  }

});<|endoftext|>


<commit_before>function booksCatalogController($scope, $http){

    $scope.books = {};
    $scope.onLoad=onLoad;
    $scope.addToCart = addToCart;
    onLoad();

    function onLoad(){
        $http.get('/booksCatalog/loadBooks')
            .success(function(data){
                $scope.books = data
        })
            .error(function(data){
                console.log("Error: "+data);
            });
    }

    function addToCart()
    {
        $http.get()
            .success(function (data) {

            })
            .error(function (data) {
               console.log("Error: "+data);
            });
    }

}
<commit_msg>Delete booksCatalogController.js<commit_after><|endoftext|>


<commit_before>"use strict";

$(function() {

    $("body").on('click', 'a', function() {

        if ($(this).data('rel') != 'form') {
            return;
        }

        var url = $(this).attr('href');
        var modal = $('#modal-form');

        var origin = $(this);

        $.get(url, function(html) {
            modal.html(html);
            initForm(modal, url, origin);
            modal.modal({}).one('hidden.bs.modal', function() {
                $(this).removeData('bs.modal').empty();
            });
        }).fail(function() {
            alert('Server Error, pleae reload page.');
        });

        return false;
    });

    if (navigator.userAgent.match('CriOS')) {
        $('body').addClass('ios-chrome');
    }

});

/**
 * Initializes an ajax form to allow refreshing on error and redirecting,
 * reloading, going back or calling a custom callback function on success.
 *
 * @param {jQuery} modal
 * @param {jQuery} origin optional. The original link clicked to
 */
function initForm(modal, url, origin) {

    var form = modal.find('form');

	form.find('.htmlarea textarea').wysihtml5({
		locale : "he-IL"
	}).css({
		'width' : '100%',
		'border-top-right-radius' : '0',
		'border-top-left-radius' : '0',
		'border-top' : '0'
	});

    form.ajaxForm({

        url : url,

        beforeSubmit : function() {
            form.find('input[type="submit"]').prop('disabled', true);
            if (form.find('input[type="file"]').length > 0) {
                $('input#id_file').parent().find('span.loader').remove();
                $('input#id_file').parent().append($('span.loader:first').clone().show());
            }
        },

        success : function(resp) {
            if (resp) {

                var appendTo = $(origin).data('append-to');
                if (appendTo) {
                    $(appendTo).append(resp);
                    $(modal).modal('hide');
                    return;
                }

                if (resp == '-') {
                    window.history.back();
                } else {
                    window.location.href = resp;
                }
            } else {
                window.location.reload();
            }
        },

        error : function(resp) {
            if (resp.status == 403) {
                var newEl = $(resp.responseText.trim());
                form.html(newEl.find('form').html());
            } else {
                alert('Server Error! please try again or reload the page.');
                form.find('input[type="submit"]').prop('disabled', false);
            }
        }
    });

}

<commit_msg>whitespace<commit_after>"use strict";

$(function() {

    $("body").on('click', 'a', function() {

        if ($(this).data('rel') != 'form') {
            return;
        }

        var url = $(this).attr('href');
        var modal = $('#modal-form');

        var origin = $(this);

        $.get(url, function(html) {
            modal.html(html);
            initForm(modal, url, origin);
            modal.modal({}).one('hidden.bs.modal', function() {
                $(this).removeData('bs.modal').empty();
            });
        }).fail(function() {
            alert('Server Error, pleae reload page.');
        });

        return false;
    });

    if (navigator.userAgent.match('CriOS')) {
        $('body').addClass('ios-chrome');
    }

});

/**
 * Initializes an ajax form to allow refreshing on error and redirecting,
 * reloading, going back or calling a custom callback function on success.
 *
 * @param {jQuery} modal
 * @param {jQuery} origin optional. The original link clicked to
 */
function initForm(modal, url, origin) {

    var form = modal.find('form');

    form.find('.htmlarea textarea').wysihtml5({
        locale : "he-IL"
    }).css({
        'width' : '100%',
        'border-top-right-radius' : '0',
        'border-top-left-radius' : '0',
        'border-top' : '0'
    });

    form.ajaxForm({

        url : url,

        beforeSubmit : function() {
            form.find('input[type="submit"]').prop('disabled', true);
            if (form.find('input[type="file"]').length > 0) {
                $('input#id_file').parent().find('span.loader').remove();
                $('input#id_file').parent().append($('span.loader:first').clone().show());
            }
        },

        success : function(resp) {
            if (resp) {

                var appendTo = $(origin).data('append-to');
                if (appendTo) {
                    $(appendTo).append(resp);
                    $(modal).modal('hide');
                    return;
                }

                if (resp == '-') {
                    window.history.back();
                } else {
                    window.location.href = resp;
                }
            } else {
                window.location.reload();
            }
        },

        error : function(resp) {
            if (resp.status == 403) {
                var newEl = $(resp.responseText.trim());
                form.html(newEl.find('form').html());
            } else {
                alert('Server Error! please try again or reload the page.');
                form.find('input[type="submit"]').prop('disabled', false);
            }
        }
    });

}
<|endoftext|>


<commit_before>import React from 'react';
import SPELLS from 'common/SPELLS';
import CoreCastEfficiency from 'Parser/Core/Modules/CastEfficiency';

class CastEfficiency extends CoreCastEfficiency {
  static CPM_ABILITIES = [
    ...CoreCastEfficiency.CPM_ABILITIES,
    {
      spell: SPELLS.FELBLADE_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FELBLADE_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 10 / (1 + haste),
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is your main Fury filler spell. Try to always cast it on cooldown. It can be used to charge to the desired target too, making it very strong movement spell. ,
    },
    {
      spell: SPELLS.FURY_OF_THE_ILLIDARI,
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 60,
      recommendedCastEfficiency: 0.9,
      extraSuggestion: This does a huge ammount of AoE passive damage and it's one of the main damage spells for Havoc Demon Hunters. You should cast it as soon as it become available. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output.  ,
    },
    {
      spell: SPELLS.EYE_BEAM,
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 45,
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is a great AoE damage spell, but also does a great damage on single target. You should cast it as soon as it gets off cooldown. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output. ,
    },
    {
      spell: SPELLS.NEMESIS_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.NEMESIS_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 120,
      recommendedCastEfficiency: 0.95,
      extraSuggestion: This is your main damage increase buff. You should use it as much as you can to maximize your damage output. ,
    },
    {
      spell: SPELLS.MOMENTUM_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.MOMENTUM_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 10,
      recommendedCastEfficiency: 0.95,
      extraSuggestion: This is your main damage increase buff. You should use it as much as you can to maximize your damage output. ,
    },
    {
      spell: SPELLS.FEL_ERUPTION_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FEL_ERUPTION_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 30,
      recommendedCastEfficiency: 0.95,
      extraSuggestion: This is a great Chaos burst damage spell and it does a huge single target DPS increase by just 10 Fury per cast. Should definitively be used as soon as it gets available. ,
    },
    {
      spell: SPELLS.FEL_BARRAGE_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FEL_BARRAGE_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 60,
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is a great AoE damage spell, but also does a great damage on single target. You should cast it as soon as it gets off cooldown. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output. ,
    },
    {
      spell: SPELLS.FEL_BARRAGE_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FEL_BARRAGE_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 60,
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is a great AoE damage spell, but also does a great damage on single target. You should cast it as soon as it gets off cooldown. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output. ,
    },
    {
      spell: SPELLS.CHAOS_STRIKE,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 3,
      recommendedCastEfficiency: 0.9,
      noSuggestion: true,
    },
  ];
}

export default CastEfficiency;
<commit_msg>Included some new spell tracking in Havoc Cast Efficiency<commit_after>import React from 'react';
import SPELLS from 'common/SPELLS';
import CoreCastEfficiency from 'Parser/Core/Modules/CastEfficiency';

class CastEfficiency extends CoreCastEfficiency {
  static CPM_ABILITIES = [
    ...CoreCastEfficiency.CPM_ABILITIES,
    {
      spell: SPELLS.FELBLADE_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FELBLADE_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 10 / (1 + haste),
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is your main Fury filler spell. Try to always cast it on cooldown. It can be used to charge to the desired target too, making it very strong movement spell. ,
    },
    {
      spell: SPELLS.FURY_OF_THE_ILLIDARI,
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 60,
      recommendedCastEfficiency: 0.9,
      extraSuggestion: This does a huge ammount of AoE passive damage and it's one of the main damage spells for Havoc Demon Hunters. You should cast it as soon as it become available. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output.  ,
    },
    {
      spell: SPELLS.EYE_BEAM,
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 45,
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is a great AoE damage spell, but also does a great damage on single target. You should cast it as soon as it gets off cooldown. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output. ,
    },
    {
      spell: SPELLS.NEMESIS_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.NEMESIS_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 120,
      recommendedCastEfficiency: 0.95,
      extraSuggestion: This is your main damage increase buff. You should use it as much as you can to maximize your damage output. ,
    },
    {
      spell: SPELLS.MOMENTUM_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.MOMENTUM_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 10,
      recommendedCastEfficiency: 0.95,
      extraSuggestion: This is your main damage increase buff. You should use it as much as you can to maximize your damage output. ,
    },
    {
      spell: SPELLS.FEL_ERUPTION_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FEL_ERUPTION_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 30,
      recommendedCastEfficiency: 0.95,
      extraSuggestion: This is a great Chaos burst damage spell and it does a huge single target DPS increase by just 10 Fury per cast. Should definitively be used as soon as it gets available. ,
    },
    {
      spell: SPELLS.FEL_BARRAGE_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FEL_BARRAGE_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 60,
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is a great AoE damage spell, but also does a great damage on single target. You should cast it as soon as it gets off cooldown. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output. ,
    },
    {
      spell: SPELLS.FEL_BARRAGE_TALENT,
      isActive: combatant => combatant.hasTalent(SPELLS.FEL_BARRAGE_TALENT.id),
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 60,
      recommendedCastEfficiency: 0.85,
      extraSuggestion: This is a great AoE damage spell, but also does a great damage on single target. You should cast it as soon as it gets off cooldown. The only moment you can delay it's cast is if you already expect an add wave to maximize it's efficiency and damage output. ,
    },
    {
      spell: SPELLS.CHAOS_STRIKE,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 3,
      recommendedCastEfficiency: 0.8,
      noSuggestion: true,
    },
    {
      spell: SPELLS.ANNIHILATION,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 14,
      recommendedCastEfficiency: 0.8,
      noSuggestion: true,
    },
    {
      spell: SPELLS.BLADE_DANCE,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 10 / (1 + haste),
      recommendedCastEfficiency: 0.8,
      noSuggestion: true,
    },
    {
      spell: SPELLS.DEATH_SWEEP,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 45,
      recommendedCastEfficiency: 0.8,
      noSuggestion: true,
    },
    {
      spell: SPELLS.METAMORPHOSIS_HAVOC,
      category: CastEfficiency.SPELL_CATEGORIES.COOLDOWNS,
      getCooldown: haste => 240,
      recommendedCastEfficiency: 1.0,
      noSuggestion: true,
    },
    {
      spell: SPELLS.FEL_RUSH,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 10,
      recommendedCastEfficiency: 0.6,
      noSuggestion: true,
    },
    {
      spell: SPELLS.THROW_GLAIVE_HAVOC,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 10,
      recommendedCastEfficiency: 0.5,
      noSuggestion: true,
    },
    {
      spell: SPELLS.VENGEFUL_RETREAT,
      category: CastEfficiency.SPELL_CATEGORIES.ROTATIONAL,
      getCooldown: haste => 25,
      recommendedCastEfficiency: 0.5,
      noSuggestion: true,
    },
  ];
}

export default CastEfficiency;
<|endoftext|>


<commit_before>'use strict';

function FloatingText(width, text, type, scene, current_color) {

    this.get_text_length = function() {
        if (this.is_2D_text) {
            return this.dynamic_texture.getTextLength(this.text);
        } else {
            return this.width;
        }
    };

    /*   __   __        __  ___  __        __  ___  __   __
        /  ` /  \ |\ | /__`  |  |__) |  | /  `  |  /  \ |__)
        \__, \__/ | \| .__/  |  |  \ \__/ \__,  |  \__/ |  \ */
    this.width         = width;
    this.type          = type;
    this.scene         = scene;
    this.object3D      = new THREE.Object3D();
    this.current_color = null;
    this.default_color = null;

    // Default value.
    this.normal_depth  = 1;

    if (is_defined(current_color)) {
        this.current_color = current_color;
        this.default_color = current_color;
    }
    // Convert to the correct color type.
    if (is_list(this.current_color)) {
        var temp = this.current_color;
        if (this.is_2D_text) {
            this.current_color = temp[COLOR_STRING_INDEX];
            this.default_color = temp[COLOR_STRING_INDEX];
        } else {
            this.current_color = temp[COLOR_HEX_INDEX];
            this.default_color = temp[COLOR_HEX_INDEX];
        }
    }

    if (this.type === TYPE_INPUT_PASSWORD) {
        this.text = '';
        for (var c = 0; c < text.length; c++) {
            this.text += '*';
        }
        this.hidden_text = text;
    } else {
        this.text = text;
    }

    // Call the child initialize functions.
    this.initialize();

    // Gets called from child functions.
    this.final_initialize = function() {
        this.is_in_interactive_list = false;
        if(!is_defined(this.current_color)) {
            switch (this.type) {
            case TYPE_BUTTON:
            case TYPE_CHECK_BOX:
                this.set_default_color(COLOR_TEXT_BUTTON);
                this.maintain_engage_when_tabbed_to = false;
                this.engable = false;
                break;
            case TYPE_CONSTANT_TEXT:
            case TYPE_TITLE_CONSTANT:
            case TYPE_SUPER_TITLE_CONSTANT:
                this.set_default_color(COLOR_TEXT_CONSTANT);
                this.engable = false;
                break;
            case TYPE_TITLE:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            default:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            }
        }
    };

    /*   ___            __  ___    __        __
        |__  |  | |\ | /  `  |  | /  \ |\ | /__`
        |    \__/ | \| \__,  |  | \__/ | \| .__/ */
    this.set_default_color = function(default_color) {
        if (is_list(default_color)) {
            if (this.is_2D_text) {
                this.default_color = default_color[COLOR_STRING_INDEX];
            } else {
                this.default_color = default_color[COLOR_HEX_INDEX];
            }
        } else {
            if (!this.is_2D_text) {
                if (default_color.toString().includes('#')) {
                    default_color = parseInt(default_color.replace('#', '0x'));
                }
            }
            this.default_color = default_color;
        }
        this.current_color = this.default_color;
        this._update_color();
    };

    // Gets called in constructor so defining this function first.
    this.update_color = function(color) {
        if (is_list(color)) {
            var color_to_set = null;
            if (this.is_2D_text) {
                color_to_set = color[COLOR_STRING_INDEX];
            } else {
                color_to_set = color[COLOR_HEX_INDEX];
            }
            this.current_color = color_to_set;
            this._update_color();
        } else {
            if (this.is_2D_text) {
                this.current_color = color;
                this._update_color();
            } else {
                if (color.toString().includes('#')) {
                    color = parseInt(color.replace('#', '0x'));
                    this.current_color = color;
                    this._update_color();
                }
            }
        }
    };

    this.update_text = function(text) {
        // TODO : This is currently assuming this function never gets called on a Password field.
        if (this.text !== text) {
            if (is_defined(this.value_changed_function)) {
                l('Value changed function is defined');
                this.value_changed_function(text);
            }
            this.text = text;
            this._update_text();
        }
    };

    this.get_text_as_value = function() {
        return parseInt(this.get_text());
    };

    this.get_text = function() {
        if (this.type === TYPE_INPUT_PASSWORD) {
            return this.hidden_text;
        }
        return this.text;
    };

    this._add_character = function(character) {
        this.update_text(this.text + character);
    };

    this._pop_character = function() {
        this.update_text(this.text.slice(0, -1));
    };

    this.parse_text = function(text) {
        for (var i = 0; i < text.length; i++) {
            if (this.type === TYPE_INPUT_PASSWORD) {
                this.hidden_text += text.charAt(i);
                this._add_character('*');
            } else {
                this._add_character(text.charAt(i));
            }
        }
    };

    this.parse_keycode = function(event) {
        var keycode = event.keyCode;

        if (keycode === KEY_CODE_DELETE) {
            if (this.text.length > 0) {
                this._pop_character();
                if (this.type === TYPE_INPUT_PASSWORD) {
                    this.hidden_text = this.hidden_text.slice(0, -1);
                }
                MANAGER_AUDIO.play_typing_sound();
            }
        } else if (event.key.length === 1) {
            if (this.type === TYPE_INPUT_PASSWORD) {
                this.hidden_text += event.key;
                this._add_character('*');
            } else if (this.type === TYPE_INPUT_REGULAR) {
                this._add_character(event.key);
            } else if (this.type === TYPE_TITLE) {
                this._add_character(event.key);
            }
            MANAGER_AUDIO.play_typing_sound();
        }
    };

    this.get_position = function() {
        return this.object3D.position;
    };

    this.update_position_and_look_at_origin = function(position_vector) {
        this.update_position_and_normal(position_vector, new THREE.Vector3(0 - position_vector.x, 0, 0 - position_vector.z));
    };

    this.update_position = function(position_vector) {
        // TODO : optimize

        this.object3D.position.x = position_vector.x + this.normal.x * this.normal_depth;
        this.object3D.position.y = position_vector.y + this.normal.y * this.normal_depth;
        this.object3D.position.z = position_vector.z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.update_position_with_offset_xyz = function(x, y, z) {
        // TODO : optimize

        this.object3D.position.x = this.x_without_normal + x + this.normal.x * this.normal_depth;
        this.object3D.position.y = this.y_without_normal + y + this.normal.y * this.normal_depth;
        this.object3D.position.z = this.z_without_normal + z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.set_normal_depth = function(depth) {
        if (depth <= 0) {
            this.normal_depth = 1;
        } else {
            this.normal_depth = depth;
        }
    };

    this.update_normal = function(normal) {
        this.normal = new THREE.Vector3(normal.x, normal.y, normal.z);
        this.normal.normalize();
        this.object3D.lookAt(new THREE.Vector3(this.object3D.position.x + this.normal.x * 100, this.object3D.position.y + this.normal.y * 100, this.object3D.position.z + this.normal.z * 100));
    };

    this.update_position_and_normal = function(position_vector, normal) {
        this.update_normal(normal);
        this.update_position(position_vector);
    };

    this.clear = function() {
        this._update_text('');
    };

    /* __  ___      ___  ___     __                  __   ___  __
      /__`  |   /\   |  |__     /  ` |__|  /\  |\ | / _` |__  /__`
      .__/  |  /~~\  |  |___    \__, |  | /~~\ | \| \__> |___ .__/ */
    this.state_change_look_at = function(being_looked_at) {
        if (being_looked_at) {
            if (this.hasOwnProperty('background_color')) {
                this.background_color = BACKGROUND_COLOR_FOCUS;
            }
            this.update_color(COLOR_HIGHLIGHT);
        } else {
            if (this.hasOwnProperty('background_color')) {
                this.background_color = COLOR_TRANSPARENT;
            }
            this.update_color(this.default_color);
        }
    };

    this.state_change_engage = function(being_engaged_with) {
        if (being_engaged_with) {
            if (this.type !== TYPE_BUTTON && this.type !== TYPE_CHECK_BOX) {
                CURRENT_PLAYER.engage();
            } else {
                this.being_engaged_with = false;
                CURRENT_PLAYER.disengage();
            }
        } else {
            CURRENT_PLAYER.disengage();
        }
    };
}<commit_msg>general updating 40<commit_after>'use strict';

function FloatingText(width, text, type, scene, current_color) {

    this.get_text_length = function() {
        if (this.is_2D_text) {
            return this.dynamic_texture.getTextLength(this.text);
        } else {
            return this.width;
        }
    };

    /*   __   __        __  ___  __        __  ___  __   __
        /  ` /  \ |\ | /__`  |  |__) |  | /  `  |  /  \ |__)
        \__, \__/ | \| .__/  |  |  \ \__/ \__,  |  \__/ |  \ */
    this.width         = width;
    this.type          = type;
    this.scene         = scene;
    this.object3D      = new THREE.Object3D();
    this.current_color = null;
    this.default_color = null;

    // Default value.
    this.normal_depth  = 1;

    if (is_defined(current_color)) {
        this.current_color = current_color;
        this.default_color = current_color;
    }
    // Convert to the correct color type.
    if (is_list(this.current_color)) {
        var temp = this.current_color;
        if (this.is_2D_text) {
            this.current_color = temp[COLOR_STRING_INDEX];
            this.default_color = temp[COLOR_STRING_INDEX];
        } else {
            this.current_color = temp[COLOR_HEX_INDEX];
            this.default_color = temp[COLOR_HEX_INDEX];
        }
    }

    if (this.type === TYPE_INPUT_PASSWORD) {
        this.text = '';
        for (var c = 0; c < text.length; c++) {
            this.text += '*';
        }
        this.hidden_text = text;
    } else {
        this.text = text;
    }

    // Call the child initialize functions.
    this.initialize();

    // Gets called from child functions.
    this.final_initialize = function() {
        this.is_in_interactive_list = false;
        if(!is_defined(this.current_color)) {
            switch (this.type) {
            case TYPE_BUTTON:
            case TYPE_CHECK_BOX:
                this.set_default_color(COLOR_TEXT_BUTTON);
                this.maintain_engage_when_tabbed_to = false;
                this.engable = false;
                break;
            case TYPE_CONSTANT_TEXT:
            case TYPE_TITLE_CONSTANT:
            case TYPE_SUPER_TITLE_CONSTANT:
                this.set_default_color(COLOR_TEXT_CONSTANT);
                this.engable = false;
                break;
            case TYPE_TITLE:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            default:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            }
        }
    };

    /*   ___            __  ___    __        __
        |__  |  | |\ | /  `  |  | /  \ |\ | /__`
        |    \__/ | \| \__,  |  | \__/ | \| .__/ */
    this.set_default_color = function(default_color) {
        if (is_list(default_color)) {
            if (this.is_2D_text) {
                this.default_color = default_color[COLOR_STRING_INDEX];
            } else {
                this.default_color = default_color[COLOR_HEX_INDEX];
            }
        } else {
            if (!this.is_2D_text) {
                if (default_color.toString().includes('#')) {
                    default_color = parseInt(default_color.replace('#', '0x'));
                }
            }
            this.default_color = default_color;
        }
        this.current_color = this.default_color;
        this._update_color();
    };

    // Gets called in constructor so defining this function first.
    this.update_color = function(color) {
        if (is_list(color)) {
            var color_to_set = null;
            if (this.is_2D_text) {
                color_to_set = color[COLOR_STRING_INDEX];
            } else {
                color_to_set = color[COLOR_HEX_INDEX];
            }
            this.current_color = color_to_set;
            this._update_color();
        } else {
            if (this.is_2D_text) {
                this.current_color = color;
                this._update_color();
            } else {
                if (color.toString().includes('#')) {
                    color = parseInt(color.replace('#', '0x'));
                    this.current_color = color;
                    this._update_color();
                }
            }
        }
    };

    this.update_text = function(text) {
        // TODO : This is currently assuming this function never gets called on a Password field.
        if (this.text !== text) {
            l('Updating text to : {' + text + '}')
            if (is_defined(this.value_changed_function)) {
                l('Value changed function is defined');
                this.value_changed_function(text);
            }
            this.text = text;
            this._update_text();
        }
    };

    this.get_text_as_value = function() {
        return parseInt(this.get_text());
    };

    this.get_text = function() {
        if (this.type === TYPE_INPUT_PASSWORD) {
            return this.hidden_text;
        }
        return this.text;
    };

    this._add_character = function(character) {
        this.update_text(this.text + character);
    };

    this._pop_character = function() {
        this.update_text(this.text.slice(0, -1));
    };

    this.parse_text = function(text) {
        for (var i = 0; i < text.length; i++) {
            if (this.type === TYPE_INPUT_PASSWORD) {
                this.hidden_text += text.charAt(i);
                this._add_character('*');
            } else {
                this._add_character(text.charAt(i));
            }
        }
    };

    this.parse_keycode = function(event) {
        var keycode = event.keyCode;

        if (keycode === KEY_CODE_DELETE) {
            if (this.text.length > 0) {
                this._pop_character();
                if (this.type === TYPE_INPUT_PASSWORD) {
                    this.hidden_text = this.hidden_text.slice(0, -1);
                }
                MANAGER_AUDIO.play_typing_sound();
            }
        } else if (event.key.length === 1) {
            if (this.type === TYPE_INPUT_PASSWORD) {
                this.hidden_text += event.key;
                this._add_character('*');
            } else if (this.type === TYPE_INPUT_REGULAR) {
                this._add_character(event.key);
            } else if (this.type === TYPE_TITLE) {
                this._add_character(event.key);
            }
            MANAGER_AUDIO.play_typing_sound();
        }
    };

    this.get_position = function() {
        return this.object3D.position;
    };

    this.update_position_and_look_at_origin = function(position_vector) {
        this.update_position_and_normal(position_vector, new THREE.Vector3(0 - position_vector.x, 0, 0 - position_vector.z));
    };

    this.update_position = function(position_vector) {
        // TODO : optimize

        this.object3D.position.x = position_vector.x + this.normal.x * this.normal_depth;
        this.object3D.position.y = position_vector.y + this.normal.y * this.normal_depth;
        this.object3D.position.z = position_vector.z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.update_position_with_offset_xyz = function(x, y, z) {
        // TODO : optimize

        this.object3D.position.x = this.x_without_normal + x + this.normal.x * this.normal_depth;
        this.object3D.position.y = this.y_without_normal + y + this.normal.y * this.normal_depth;
        this.object3D.position.z = this.z_without_normal + z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.set_normal_depth = function(depth) {
        if (depth <= 0) {
            this.normal_depth = 1;
        } else {
            this.normal_depth = depth;
        }
    };

    this.update_normal = function(normal) {
        this.normal = new THREE.Vector3(normal.x, normal.y, normal.z);
        this.normal.normalize();
        this.object3D.lookAt(new THREE.Vector3(this.object3D.position.x + this.normal.x * 100, this.object3D.position.y + this.normal.y * 100, this.object3D.position.z + this.normal.z * 100));
    };

    this.update_position_and_normal = function(position_vector, normal) {
        this.update_normal(normal);
        this.update_position(position_vector);
    };

    this.clear = function() {
        this._update_text('');
    };

    /* __  ___      ___  ___     __                  __   ___  __
      /__`  |   /\   |  |__     /  ` |__|  /\  |\ | / _` |__  /__`
      .__/  |  /~~\  |  |___    \__, |  | /~~\ | \| \__> |___ .__/ */
    this.state_change_look_at = function(being_looked_at) {
        if (being_looked_at) {
            if (this.hasOwnProperty('background_color')) {
                this.background_color = BACKGROUND_COLOR_FOCUS;
            }
            this.update_color(COLOR_HIGHLIGHT);
        } else {
            if (this.hasOwnProperty('background_color')) {
                this.background_color = COLOR_TRANSPARENT;
            }
            this.update_color(this.default_color);
        }
    };

    this.state_change_engage = function(being_engaged_with) {
        if (being_engaged_with) {
            if (this.type !== TYPE_BUTTON && this.type !== TYPE_CHECK_BOX) {
                CURRENT_PLAYER.engage();
            } else {
                this.being_engaged_with = false;
                CURRENT_PLAYER.disengage();
            }
        } else {
            CURRENT_PLAYER.disengage();
        }
    };
}<|endoftext|>


<commit_before>// @flow

const os = require('os')
// $FlowIssue flow doesn't find repl builtin?
const Repl = require('repl')
const { bootstrap } = require('../util')

module.exports = {
  command: 'repl',
  describe: 'start the aleph repl\n',
  builder: (yargs: Function) => {
    return yargs
      .option('dir', {
        'alias': 'd',
        'type': 'string',
        'describe': 'directory to connect to (multiaddress)',
        'demand': false
      })
      .help()
  },
  handler: (opts: {dir?: string, remotePeer?: string, identityPath: string}) => {
    const {remotePeer} = opts

    bootstrap(opts)
      .catch(err => {
        console.error(`Error setting up aleph node: ${err.message}`)
        process.exit(1)
      })
      .then(({node, remote}) => {
        let init
        if (remote != null) {
          init = node.start()
            .then(() => node.openConnection(remote.remotePeerInfo))
            .then(() => { console.log(`Connected to `, remotePeer) })
        } else {
          console.log('No remote peer specified, running in detached mode')
          // TODO: create dummy RemoteNode class that just throws
          init = node.start()
        }

        // TODO: directory stuff
        if (node.directory == null) {
          // TODO: get directory from remote peer (and amend message below)
          console.log('No directory specified, running without directory')
        }

        init.then(() => {
          const repl = Repl.start({
            'prompt': 'א > ',
            'useColors': true,
            'ignoreUndefined': true
          })
          repl.context.node = node
          repl.context.remote = remote
          const defaultEval = repl.eval
          repl.eval = promiseEval(defaultEval)
          repl.on('exit', () => {
            process.exit();
          });
        }).catch(err => {
          console.log(err)
        })
      })
  }
}

const EMPTY = '(' + os.EOL + ')'
const promiseEval = (defaultEval) => (cmd, context, filename, callback) => {
  if (cmd === EMPTY) return callback()
  defaultEval(cmd, context, filename, (err, result) => {
    if (err) { return callback(err) }

    if (result instanceof Promise) {
      result.then(
        asyncResult => { callback(null, asyncResult) },
        asyncErr => { callback(asyncErr) }
      )
    } else {
      callback(null, result)
    }
  })
}
<commit_msg>code style - rm semicolons<commit_after>// @flow

const os = require('os')
// $FlowIssue flow doesn't find repl builtin?
const Repl = require('repl')
const { bootstrap } = require('../util')

module.exports = {
  command: 'repl',
  describe: 'start the aleph repl\n',
  builder: (yargs: Function) => {
    return yargs
      .option('dir', {
        'alias': 'd',
        'type': 'string',
        'describe': 'directory to connect to (multiaddress)',
        'demand': false
      })
      .help()
  },
  handler: (opts: {dir?: string, remotePeer?: string, identityPath: string}) => {
    const {remotePeer} = opts

    bootstrap(opts)
      .catch(err => {
        console.error(`Error setting up aleph node: ${err.message}`)
        process.exit(1)
      })
      .then(({node, remote}) => {
        let init
        if (remote != null) {
          init = node.start()
            .then(() => node.openConnection(remote.remotePeerInfo))
            .then(() => { console.log(`Connected to `, remotePeer) })
        } else {
          console.log('No remote peer specified, running in detached mode')
          // TODO: create dummy RemoteNode class that just throws
          init = node.start()
        }

        // TODO: directory stuff
        if (node.directory == null) {
          // TODO: get directory from remote peer (and amend message below)
          console.log('No directory specified, running without directory')
        }

        init.then(() => {
          const repl = Repl.start({
            'prompt': 'א > ',
            'useColors': true,
            'ignoreUndefined': true
          })
          repl.context.node = node
          repl.context.remote = remote
          const defaultEval = repl.eval
          repl.eval = promiseEval(defaultEval)
          repl.on('exit', () => {
            process.exit()
          })
        }).catch(err => {
          console.log(err)
        })
      })
  }
}

const EMPTY = '(' + os.EOL + ')'
const promiseEval = (defaultEval) => (cmd, context, filename, callback) => {
  if (cmd === EMPTY) return callback()
  defaultEval(cmd, context, filename, (err, result) => {
    if (err) { return callback(err) }

    if (result instanceof Promise) {
      result.then(
        asyncResult => { callback(null, asyncResult) },
        asyncErr => { callback(asyncErr) }
      )
    } else {
      callback(null, result)
    }
  })
}
<|endoftext|>


<commit_before>define(["dojo/main", "ppwcode/contracts/doh",
        "../_Cache",
        "./mock/Person", "ppwcode/collections/StoreOfStateful",
        "ppwcode/oddsAndEnds/typeOf"],
    function(dojo, doh,
             _Cache,
             Person, StoreOfStateful,
             typeOf) {

      var personId1 = 898942;
      var personJson = {
        "name":"Pete Peeters",
        "street":"Avenue de rue 93",
        "zip":"1040 CAA",
        "city":"Cité de Beauté",
        "tel":"0322 44 442 22"
      };

      function createPerson(persistenceId) {
        var person = new Person();
        person.persistenceId = persistenceId;
        person.reload(personJson);
        return person;
      }

      doh.register("_Cache", [

        function testConstructor() {
          var subject = new _Cache();
          doh.invars(subject);
          doh.t(subject._data);
          doh.t(typeOf(subject._data) === "object");
          doh.is(0, Object.keys(subject._data).length);
        },

        {
          name: "trackPo once",
          setUp: function() {
            this.person = createPerson(personId1);
            this.subject = new _Cache();
          },
          runTest: function() {
            this.subject.trackPo(this.person, this);
            var tracked = this.subject.getPoByTypeAndId(this.person.get("persistenceType"), personId1);
            doh.is(this.person, tracked);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(1, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.person;
            delete this.subject;
          }
        },

        {
          name: "trackPo trice",
          setUp: function() {
            this.person = createPerson(personId1);
            this.subject = new _Cache();
          },
          runTest: function() {
            this.subject.trackPo(this.person, this);
            this.subject.trackPo(this.person, {});
            this.subject.trackPo(this.person, {});
            var tracked = this.subject.getPoByTypeAndId(this.person.get("persistenceType"), personId1);
            doh.is(this.person, tracked);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(3, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.person;
            delete this.subject;
          }
        },

        {
          name: "trackPo quatro",
          setUp: function() {
            this.person = createPerson(personId1);
            this.subject = new _Cache();
            this.referer1 = {};
            this.referer2 = {};
          },
          runTest: function() {
            this.subject.trackPo(this.person, this);
            this.subject.trackPo(this.person, this.referer1);
            this.subject.trackPo(this.person, this.referer1);
            this.subject.trackPo(this.person, this.referer2);
            var tracked = this.subject.getPoByTypeAndId(this.person.get("persistenceType"), personId1);
            doh.is(this.person, tracked);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(3, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.person;
            delete this.subject;
            delete this.referer1;
            delete this.referer2;
          }
        },

        {
          name: "stopTracking",
          setUp: function() {
            this.person = createPerson(personId1);
            this.subject = new _Cache();
            this.referer1 = {};
            this.referer2 = {};
          },
          runTest: function() {
            this.subject.trackPo(this.person, this);
            this.subject.trackPo(this.person, this.referer1);
            this.subject.trackPo(this.person, this.referer1);
            this.subject.trackPo(this.person, this.referer2);
            var tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(3, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.person, {});
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(3, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.person, this.referer1);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(2, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.person, this.referer2);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(1, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));

            this.subject.trackPo(this.person, this.referer1);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(2, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.person, this.referer1);
            tracked = this.subject.getPo(this.person);
            doh.is(this.person, tracked);
            // IDEA test breaks encapsulation -- whenever this fails, just remove the test
            doh.is(1, this.subject._data[this.person.get("persistenceType") + "@" + personId1].getNrOfReferers());
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.person, this);
            tracked = this.subject.getPo(this.person);
            doh.f(tracked);
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.person;
            delete this.subject;
            delete this.referer1;
            delete this.referer2;
          }
        },

        {
          name: "recursiveStopTracking",
          setUp: function() {
            this.person1 = createPerson(personId1);
            this.person2 = createPerson(85029859025);
            this.person3 = createPerson(752890);
            this.person4 = createPerson(578059230);
            this.person5 = createPerson(74924902890);
            this.person6 = createPerson(524523523);
            this.subject = new _Cache();
            this.referer1 = {};
            this.referer2 = {};
          },
          runTest: function() {
            this.subject.trackPo(this.person1, this);
            this.subject.trackPo(this.person1, this.referer1);
            this.subject.trackPo(this.person1, this.referer2);

            this.subject.trackPo(this.person2, this.referer1);
            this.subject.trackPo(this.person3, this.person2);
            this.subject.trackPo(this.person5, this.person4);
            this.subject.trackPo(this.person4, this.person1);
            this.subject.trackPo(this.person6, this.person5);
            this.subject.trackPo(this.person6, this.referer1);

            this.subject.stopTracking(this.person1, this.referer1);
            this.subject.stopTracking(this.person1, this.referer2);
            this.subject.stopTracking(this.person1, this);

            tracked = this.subject.getPo(this.person1);
            doh.f(tracked);
            tracked = this.subject.getPo(this.person4);
            doh.f(tracked);
            tracked = this.subject.getPo(this.person5);
            doh.f(tracked);
            tracked = this.subject.getPo(this.person2);
            doh.t(tracked);
            tracked = this.subject.getPo(this.person3);
            doh.t(tracked);
            tracked = this.subject.getPo(this.person6);
            doh.t(tracked);

            this.subject.stopTracking(this.person6, this.referer1);
            tracked = this.subject.getPo(this.person6);
            doh.f(tracked);
            tracked = this.subject.getPo(this.person2);
            doh.t(tracked);
            tracked = this.subject.getPo(this.person3);
            doh.t(tracked);

            this.subject.stopTracking(this.person2, this.referer1);
            tracked = this.subject.getPo(this.person2);
            doh.f(tracked);
            tracked = this.subject.getPo(this.person3);
            doh.f(tracked);

            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.person1;
            delete this.person2;
            delete this.person3;
            delete this.person4;
            delete this.person5;
            delete this.person6;
            delete this.subject;
            delete this.referer1;
            delete this.referer2;
          }
        }

      ]);
    }
);
<commit_msg>test generalized; now all tests for StoreOfStateful is next<commit_after>define(["dojo/main", "ppwcode/contracts/doh",
        "../_Cache",
        "./mock/Person", "ppwcode/collections/StoreOfStateful",
        "ppwcode/oddsAndEnds/typeOf"],
  function(dojo, doh,
           _Cache,
           Person, StoreOfStateful,
           typeOf) {

    var personId1 = 898942;
    var personJson = {
      "name":"Pete Peeters",
      "street":"Avenue de rue 93",
      "zip":"1040 CAA",
      "city":"Cité de Beauté",
      "tel":"0322 44 442 22"
    };

    function createPerson(persistenceId) {
      var person = new Person();
      person.persistenceId = persistenceId;
      person.reload(personJson);
      return person;
    }

    function getAndTestPersonEntry(cache, po, persistenceId, expectedNrOfReferers) {
      var tracked;
      if (expectedNrOfReferers) {
        tracked = cache.getPoByTypeAndId(po.get("persistenceType"), persistenceId);
        doh.is(po, tracked);
        tracked = cache.getPo(po);
        doh.is(po, tracked);
        // IDEA test breaks encapsulation -- whenever this fails, just remove the test
        doh.is(expectedNrOfReferers, cache._data[po.get("persistenceType") + "@" + persistenceId].getNrOfReferers());
      }
      else {
        tracked = cache.getPo(po);
        doh.f(tracked);
      }
    }

    function generateTests(what, payloadCreator, getAndTest) {
      return [
        {
          name: what + " track once",
          setUp: function() {
            this.payload = payloadCreator();
            this.subject = new _Cache();
          },
          runTest: function() {
            this.subject.trackPo(this.payload, this);
            getAndTest(this.subject, this.payload, 1);
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.payload;
            delete this.subject;
          }
        },

        {
          name: what + " track trice",
          setUp: function() {
            this.payload = payloadCreator();
            this.subject = new _Cache();
          },
          runTest: function() {
            this.subject.trackPo(this.payload, this);
            this.subject.trackPo(this.payload, {});
            this.subject.trackPo(this.payload, {});
            getAndTest(this.subject, this.payload, 3);
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.payload;
            delete this.subject;
          }
        },

        {
          name: what + " track quatro",
          setUp: function() {
            this.payload = payloadCreator();
            this.subject = new _Cache();
            this.referer1 = {};
            this.referer2 = {};
          },
          runTest: function() {
            this.subject.trackPo(this.payload, this);
            this.subject.trackPo(this.payload, this.referer1);
            this.subject.trackPo(this.payload, this.referer1);
            this.subject.trackPo(this.payload, this.referer2);
            getAndTest(this.subject, this.payload, 3);
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.payload;
            delete this.subject;
            delete this.referer1;
            delete this.referer2;
          }
        },

        {
          name: what + " stop tracking",
          setUp: function() {
            this.payload = payloadCreator();
            this.subject = new _Cache();
            this.referer1 = {};
            this.referer2 = {};
          },
          runTest: function() {
            this.subject.trackPo(this.payload, this);
            this.subject.trackPo(this.payload, this.referer1);
            this.subject.trackPo(this.payload, this.referer1);
            this.subject.trackPo(this.payload, this.referer2);
            getAndTest(this.subject, this.payload, 3);
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.payload, {});
            getAndTest(this.subject, this.payload, 3);
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.payload, this.referer1);
            getAndTest(this.subject, this.payload, 2);
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.payload, this.referer2);
            getAndTest(this.subject, this.payload, 1);
            console.log(JSON.stringify(this.subject.report()));

            this.subject.trackPo(this.payload, this.referer1);
            getAndTest(this.subject, this.payload, 2);
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.payload, this.referer1);
            getAndTest(this.subject, this.payload, 1);
            console.log(JSON.stringify(this.subject.report()));

            this.subject.stopTracking(this.payload, this);
            getAndTest(this.subject, this.payload, 0);
            console.log(JSON.stringify(this.subject.report()));
          },
          tearDown: function() {
            delete this.payload;
            delete this.subject;
            delete this.referer1;
            delete this.referer2;
          }
        }
      ]
    }

    doh.register("_Cache",

      [
        function testConstructor() {
          var subject = new _Cache();
          doh.invars(subject);
          doh.t(subject._data);
          doh.t(typeOf(subject._data) === "object");
          doh.is(0, Object.keys(subject._data).length);
        }
      ]
      .concat(
        generateTests(
          "PersistentObject",
          function() {
            return createPerson(personId1);
          },
          function(cache, payload, expectedNrOfReferers) {
            getAndTestPersonEntry(cache, payload, personId1, expectedNrOfReferers);
          }
        )
      )
      .concat([{
        name: "recursiveStopTracking",
        setUp: function() {
          this.person1 = createPerson(personId1);
          this.person2 = createPerson(85029859025);
          this.person3 = createPerson(752890);
          this.person4 = createPerson(578059230);
          this.person5 = createPerson(74924902890);
          this.person6 = createPerson(524523523);
          this.subject = new _Cache();
          this.referer1 = {};
          this.referer2 = {};
        },
        runTest: function() {
          this.subject.trackPo(this.person1, this);
          this.subject.trackPo(this.person1, this.referer1);
          this.subject.trackPo(this.person1, this.referer2);

          this.subject.trackPo(this.person2, this.referer1);
          this.subject.trackPo(this.person3, this.person2);
          this.subject.trackPo(this.person5, this.person4);
          this.subject.trackPo(this.person4, this.person1);
          this.subject.trackPo(this.person6, this.person5);
          this.subject.trackPo(this.person6, this.referer1);

          this.subject.stopTracking(this.person1, this.referer1);
          this.subject.stopTracking(this.person1, this.referer2);
          this.subject.stopTracking(this.person1, this);

          var tracked = this.subject.getPo(this.person1);
          doh.f(tracked);
          tracked = this.subject.getPo(this.person4);
          doh.f(tracked);
          tracked = this.subject.getPo(this.person5);
          doh.f(tracked);
          tracked = this.subject.getPo(this.person2);
          doh.t(tracked);
          tracked = this.subject.getPo(this.person3);
          doh.t(tracked);
          tracked = this.subject.getPo(this.person6);
          doh.t(tracked);

          this.subject.stopTracking(this.person6, this.referer1);
          tracked = this.subject.getPo(this.person6);
          doh.f(tracked);
          tracked = this.subject.getPo(this.person2);
          doh.t(tracked);
          tracked = this.subject.getPo(this.person3);
          doh.t(tracked);

          this.subject.stopTracking(this.person2, this.referer1);
          tracked = this.subject.getPo(this.person2);
          doh.f(tracked);
          tracked = this.subject.getPo(this.person3);
          doh.f(tracked);

          console.log(JSON.stringify(this.subject.report()));
        },
        tearDown: function() {
          delete this.person1;
          delete this.person2;
          delete this.person3;
          delete this.person4;
          delete this.person5;
          delete this.person6;
          delete this.subject;
          delete this.referer1;
          delete this.referer2;
        }
      }])

    );
  }
);
<|endoftext|>