<commit_before>/*!
    Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
    Created By: brad@reciprocitylabs.com
    Maintained By: brad@reciprocitylabs.com
*/

!function($) {

  "use strict"; // jshint ;_;

  /* MODAL_FORM PUBLIC CLASS DEFINITION
   * =============================== */

  var ModalForm = function ( element, options, trigger ) {

    this.options = options;
    this.$element = $(element);
    this.$trigger = $(trigger);

    this.init();
  }

  /* NOTE: MODAL_FORM EXTENDS BOOTSTRAP-MODAL.js
   * ========================================== */

  ModalForm.prototype = new $.fn.modal.Constructor(null, { remote : false });

  $.extend(ModalForm.prototype, {

    init: function() {
      var that = this
        , $form;
      this.$element
        .on('preload', function() {
          that.is_form_dirty(true);
        })
        .on('keypress', 'form', $.proxy(this.keypress_submit, this))
        .on('keyup', 'form', $.proxy(this.keyup_escape, this))
        .on('click.modal-form.close', '[data-dismiss="modal"]', $.proxy(this.hide, this))
        .on('click.modal-form.reset', 'input[type=reset], [data-dismiss="modal-reset"]', $.proxy(this.reset, this))
        .on('click.modal-form.submit', 'input[type=submit], [data-toggle="modal-submit"]', $.proxy(this.submit, this))
        .on('shown.modal-form', $.proxy(this.focus_first_input, this))
        .on('loaded.modal-form', $.proxy(this.focus_first_input, this))
        .on('loaded.modal-form', function(ev) {
          $("a[data-wysihtml5-command], a[data-wysihtml5-action]", ev.target).attr('tabindex', "-1");
          $form = that.$form();
          $(this).trigger("shown"); //this will reposition the modal stack
        })
        .on('delete-object', $.proxy(this.delete_object, this))
        .draggable({ handle: '.modal-header' });
        ;
    }

  , doNothing: function(e) {
    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();
  }

  , delete_object: function(e, data, xhr) {
      // If this modal is contained within another modal, pass the event onward
      var $trigger_modal = this.$trigger.closest('.modal')
        , delete_target
        ;

      if ($trigger_modal.length > 0) {
        $trigger_modal.trigger('delete-object', [data, xhr]);
      } else {
        delete_target = this.$trigger.data('delete-target');
        if (delete_target == 'refresh') {
          // Refresh the page
          GGRC.navigate(window.location.href.replace(/#.*/, ''));
        } else if (xhr && xhr.getResponseHeader('location')) {
          // Otherwise redirect if possible
          GGRC.navigate(xhr.getResponseHeader('location'));
        } else {
          // Otherwise refresh the page
          GGRC.navigate(window.location.href.replace(/#.*/, ''));
        }
      }
    }

  , $form: function() {
      return this.$element.find('form').first();
    }

  , is_form_dirty: function(cache_values) {
      var that = this
        , cache = {}
        , dirty = false
        ;

      // Generate a hash of the form values
      can.each(this.$form().serializeArray(), function(field) {
        cache[field.name] = cache[field.name] ? cache[field.name] + ',' + field.value : field.value;
      });

      // Cache the initial form values as requested
      if (cache_values || !this._cached_values) {
        this._cached_values = cache;
      }
      // Otherwise compute a diff to determine whether the form is dirty
      else {
        can.each(cache, function(value, key) {
          dirty = dirty || (value !== that._cached_values[key] && (!!value || that._cached_values[key] !== undefined));
        });
      }

      return dirty;
    }

  , submit: function(e) {
      var $form = this.$form()
      , that = this;

      if(!$form.data("submitpending")) {
        $("[data-toggle=modal-submit]", $form)
          .each(function() { $(this).data("origText", $(this).text()); })
          .addClass("disabled pending-ajax")
          .attr("disabled", true);

        $form.data("submitpending", true)
        .one("ajax:beforeSend", function(ev, _xhr){
          that.xhr = _xhr;
        })
        .submit();
      }
      if (e.type == 'click')
        e.preventDefault();
    }

  , keypress_submit: function(e) {
      if (e.which == 13 && !$(e.target).is('textarea')) {
        if (!e.isDefaultPrevented()) {
          e.preventDefault();
          this.$form().submit();
        }
      }
    }

  , keyup_escape : function(e) {
     if($(document.activeElement).is("select, [data-toggle=datepicker]") && e.which === 27) {
        this.$element.attr("tabindex", -1).focus();
        e.stopPropagation();
      }
    }

  , reset: function(e) {
      var form = this.$form()[0];
      form && form.reset();
      this.hide(e);
    }

  , hide: function(e) {
      var that = this,
          options = this.$element.control().options;

      // If the hide was initiated by the backdrop, check for dirty form data before continuing
      if (e && $(e.target).is('.modal-backdrop')) {

        if($(e.target).is(".disabled")) {
          // In the case of a disabled modal backdrop, treat it like any other disabled data-dismiss,
          //  i.e. do nothing.
          e.stopPropagation();
          return;
        }
        if (this.is_form_dirty()) {
          // Confirm that the user wants to lose the data prior to hiding
          GGRC.Controllers.Modals.confirm({
            modal_title : "Discard Changes"
            , modal_description : "Are you sure that you want to discard your changes?"
            , modal_confirm : "Discard"
            , instance : options.instance
            , model : options.model
            , skip_refresh : true
          }, function() {
            can.trigger(options.instance, "modal:dismiss");
            that.$element.find("[data-dismiss='modal'], [data-dismiss='modal-reset']").trigger("click");
            that.hide();
          });
          return;
        }
      }

      // Hide the modal like normal
      can.trigger(options.instance, "modal:dismiss");
      $.fn.modal.Constructor.prototype.hide.apply(this, [e]);
      this.$element.off('modal_form');
    }

  , focus_first_input: function(ev) {
      var that = this;
      setTimeout(function() {
        var $first_input;
        $first_input = that.$element.find('*[autofocus]');
        if ($first_input.length == 0) {
          $first_input = that.$element
            .find('input[type="text"], input[type="checkbox"], select, textarea')
            .not('[placeholder*=autofill], label:contains(autofill) + *, [disabled]')
            .first();
        }
        if ($first_input.length > 0 && (!ev || that.$element.is(ev.target))) {
          $first_input.get(0).focus();
        }
      }, 100);
    }
  });

  $.fn.modal_form = function(option, trigger) {
    return this.each(function() {
      var $this = $(this)
        , data = $this.data('modal_form')
        , options = $.extend({}, $.fn.modal_form.defaults, $this.data(), typeof option == 'object' && option);
      if (!data) $this.data('modal_form', (data = new ModalForm(this, options, trigger)));
      if (typeof option == 'string') data[option]();
      else if (options.show) data.show();
    });
  }

  $.fn.modal_form.Constructor = ModalForm;

  $.fn.modal_form.defaults = $.extend({}, $.fn.modal.defaults, {

  });

  /* MODAL-FORM DATA-API
   * =================== */

  $(function () {
    $('body').on('click.modal-form.data-api', '[data-toggle="modal-form"]', function ( e ) {
      var $this = $(this), href
        , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
        , option = $target.data('modal-form') ? 'toggle' : $.extend({}, $target.data(), $this.data());

      e.preventDefault();
      $target.modal_form(option);
    });
  });

  // Default flash handler
  $(function() {
    // Default form complete handler
    $('body').on('ajax:complete', function(e, xhr, status) {
      var data = null;
      try {
        data = JSON.parse(xhr.responseText);
      } catch (exc) {
        //console.debug('exc', exc);
      }

      if (!e.stopRedirect) {
        // Maybe handle AJAX/JSON redirect or refresh
        if (xhr.status == 278) {
          // Handle 278 redirect (AJAX redirect)
          GGRC.navigate(xhr.getResponseHeader('location'));
        } else if (xhr.status == 279) {
          // Handle 279 page refresh
          GGRC.navigate(window.location.href.replace(/#.*/, ''));
        }
        else {
          var modal_form = $(".modal:visible:last").data("modal_form");
          if(modal_form && xhr === modal_form.xhr) {
            delete modal_form.xhr;
            $("[data-toggle=modal-submit]", modal_form.$element)
            .removeAttr("disabled")
            .removeClass("disabled pending-ajax")
            .each(function() {
              $(this).text($(this).data("origText"));
            });
            $("form", modal_form.$element).data("submitpending", false);
          }
        }
      }

      if (data) {
        // Parse and dispatch JSON object
        $(e.target).trigger('ajax:json', [data, xhr]);
      } else if(xhr.responseText) {
        // Dispatch as html, if there is html to dispatch.  (no result should not blank out forms)
        $(e.target).trigger('ajax:html', [xhr.responseText, xhr]);
      }

      if (!e.stopFlash) {
        // Maybe handle AJAX flash messages
        var flash_types = ["error", "alert", "notice", "warning"]
          , type_i, message
          , flash;

        for (type_i in flash_types) {
          message = xhr.getResponseHeader('x-flash-' + flash_types[type_i]);
          message = JSON.parse(message);
          if (message) {
            if (!flash)
              flash = {};
            flash[flash_types[type_i]] = message;
          }
        }

        if (flash) {
          $(document.body).trigger('ajax:flash', flash);
        }
      }
    });

    $('body').on('ajax:flash', function(e, flash) {
      var $target, $flash_holder
        , type, message_i
        , flash_class
        , flash_class_mappings = { notice: "success" }
        , html
        , got_message = _.some(_.values(flash),
                               function (msg) { return !!msg; });

      if (!got_message) {
        // sometimes ajax:flash is triggered with bad data
        return;
      }

      // Find or create the flash-message holder
      $target = $(e.target);
      if($target.has(".modal-body").length < 1)
        $target = $('body');
      $flash_holder = $target.find('.flash');

      if ($flash_holder.length == 0) {
        $flash_holder = $('

');
        $target.find('.modal-body').prepend($flash_holder);
      } else {
        $flash_holder.empty();
      }

      for (type in flash) {
        if (flash[type]) {
          if (typeof(flash[type]) == "string")
            flash[type] = [flash[type]];

          flash_class = flash_class_mappings[type] || type;

          html =
            [ '
'
            ,   'x'
            ];
          for (message_i in flash[type]) {
            html.push('' + flash[type][message_i] + '');
          }
          html.push('
');
          $flash_holder.append(html.join(''));
        }
      }
    });

    $('body').on('ajax:html', '.modal > form', function(e, html, xhr) {
      var sel = "script[type='text/javascript'], script[language='javascript'], script:not([type])";
      var $frag = $(html);
      $frag.filter(sel).add($frag.find(sel)).each(function() {
        $(this).remove();
        setTimeout($(this).html(), 10);
      });
      $(this).find('.modal-body').html($frag);
    });

  });
}(window.jQuery);
<commit_msg>Trigger dismiss on instance, only if it exists<commit_after>/*!
    Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
    Created By: brad@reciprocitylabs.com
    Maintained By: brad@reciprocitylabs.com
*/

!function($) {

  "use strict"; // jshint ;_;

  /* MODAL_FORM PUBLIC CLASS DEFINITION
   * =============================== */

  var ModalForm = function ( element, options, trigger ) {

    this.options = options;
    this.$element = $(element);
    this.$trigger = $(trigger);

    this.init();
  }

  /* NOTE: MODAL_FORM EXTENDS BOOTSTRAP-MODAL.js
   * ========================================== */

  ModalForm.prototype = new $.fn.modal.Constructor(null, { remote : false });

  $.extend(ModalForm.prototype, {

    init: function() {
      var that = this
        , $form;
      this.$element
        .on('preload', function() {
          that.is_form_dirty(true);
        })
        .on('keypress', 'form', $.proxy(this.keypress_submit, this))
        .on('keyup', 'form', $.proxy(this.keyup_escape, this))
        .on('click.modal-form.close', '[data-dismiss="modal"]', $.proxy(this.hide, this))
        .on('click.modal-form.reset', 'input[type=reset], [data-dismiss="modal-reset"]', $.proxy(this.reset, this))
        .on('click.modal-form.submit', 'input[type=submit], [data-toggle="modal-submit"]', $.proxy(this.submit, this))
        .on('shown.modal-form', $.proxy(this.focus_first_input, this))
        .on('loaded.modal-form', $.proxy(this.focus_first_input, this))
        .on('loaded.modal-form', function(ev) {
          $("a[data-wysihtml5-command], a[data-wysihtml5-action]", ev.target).attr('tabindex', "-1");
          $form = that.$form();
          $(this).trigger("shown"); //this will reposition the modal stack
        })
        .on('delete-object', $.proxy(this.delete_object, this))
        .draggable({ handle: '.modal-header' });
        ;
    }

  , doNothing: function(e) {
    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();
  }

  , delete_object: function(e, data, xhr) {
      // If this modal is contained within another modal, pass the event onward
      var $trigger_modal = this.$trigger.closest('.modal')
        , delete_target
        ;

      if ($trigger_modal.length > 0) {
        $trigger_modal.trigger('delete-object', [data, xhr]);
      } else {
        delete_target = this.$trigger.data('delete-target');
        if (delete_target == 'refresh') {
          // Refresh the page
          GGRC.navigate(window.location.href.replace(/#.*/, ''));
        } else if (xhr && xhr.getResponseHeader('location')) {
          // Otherwise redirect if possible
          GGRC.navigate(xhr.getResponseHeader('location'));
        } else {
          // Otherwise refresh the page
          GGRC.navigate(window.location.href.replace(/#.*/, ''));
        }
      }
    }

  , $form: function() {
      return this.$element.find('form').first();
    }

  , is_form_dirty: function(cache_values) {
      var that = this
        , cache = {}
        , dirty = false
        ;

      // Generate a hash of the form values
      can.each(this.$form().serializeArray(), function(field) {
        cache[field.name] = cache[field.name] ? cache[field.name] + ',' + field.value : field.value;
      });

      // Cache the initial form values as requested
      if (cache_values || !this._cached_values) {
        this._cached_values = cache;
      }
      // Otherwise compute a diff to determine whether the form is dirty
      else {
        can.each(cache, function(value, key) {
          dirty = dirty || (value !== that._cached_values[key] && (!!value || that._cached_values[key] !== undefined));
        });
      }

      return dirty;
    }

  , submit: function(e) {
      var $form = this.$form()
      , that = this;

      if(!$form.data("submitpending")) {
        $("[data-toggle=modal-submit]", $form)
          .each(function() { $(this).data("origText", $(this).text()); })
          .addClass("disabled pending-ajax")
          .attr("disabled", true);

        $form.data("submitpending", true)
        .one("ajax:beforeSend", function(ev, _xhr){
          that.xhr = _xhr;
        })
        .submit();
      }
      if (e.type == 'click')
        e.preventDefault();
    }

  , keypress_submit: function(e) {
      if (e.which == 13 && !$(e.target).is('textarea')) {
        if (!e.isDefaultPrevented()) {
          e.preventDefault();
          this.$form().submit();
        }
      }
    }

  , keyup_escape : function(e) {
     if($(document.activeElement).is("select, [data-toggle=datepicker]") && e.which === 27) {
        this.$element.attr("tabindex", -1).focus();
        e.stopPropagation();
      }
    }

  , reset: function(e) {
      var form = this.$form()[0];
      form && form.reset();
      this.hide(e);
    }

  , hide: function(e) {
      var that = this,
          control = this.$element.control(),
          options = control && control.options;

      // If the hide was initiated by the backdrop, check for dirty form data before continuing
      if (e && $(e.target).is('.modal-backdrop')) {

        if($(e.target).is(".disabled")) {
          // In the case of a disabled modal backdrop, treat it like any other disabled data-dismiss,
          //  i.e. do nothing.
          e.stopPropagation();
          return;
        }
        if (this.is_form_dirty()) {
          // Confirm that the user wants to lose the data prior to hiding
          GGRC.Controllers.Modals.confirm({
            modal_title : "Discard Changes"
            , modal_description : "Are you sure that you want to discard your changes?"
            , modal_confirm : "Discard"
            , instance : options.instance
            , model : options.model
            , skip_refresh : true
          }, function() {
            can.trigger(options.instance, "modal:dismiss");
            that.$element.find("[data-dismiss='modal'], [data-dismiss='modal-reset']").trigger("click");
            that.hide();
          });
          return;
        }
      }

      // Hide the modal like normal
      if (options) {
        can.trigger(options.instance, "modal:dismiss");
      }
      $.fn.modal.Constructor.prototype.hide.apply(this, [e]);
      this.$element.off('modal_form');
    }

  , focus_first_input: function(ev) {
      var that = this;
      setTimeout(function() {
        var $first_input;
        $first_input = that.$element.find('*[autofocus]');
        if ($first_input.length == 0) {
          $first_input = that.$element
            .find('input[type="text"], input[type="checkbox"], select, textarea')
            .not('[placeholder*=autofill], label:contains(autofill) + *, [disabled]')
            .first();
        }
        if ($first_input.length > 0 && (!ev || that.$element.is(ev.target))) {
          $first_input.get(0).focus();
        }
      }, 100);
    }
  });

  $.fn.modal_form = function(option, trigger) {
    return this.each(function() {
      var $this = $(this)
        , data = $this.data('modal_form')
        , options = $.extend({}, $.fn.modal_form.defaults, $this.data(), typeof option == 'object' && option);
      if (!data) $this.data('modal_form', (data = new ModalForm(this, options, trigger)));
      if (typeof option == 'string') data[option]();
      else if (options.show) data.show();
    });
  }

  $.fn.modal_form.Constructor = ModalForm;

  $.fn.modal_form.defaults = $.extend({}, $.fn.modal.defaults, {

  });

  /* MODAL-FORM DATA-API
   * =================== */

  $(function () {
    $('body').on('click.modal-form.data-api', '[data-toggle="modal-form"]', function ( e ) {
      var $this = $(this), href
        , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
        , option = $target.data('modal-form') ? 'toggle' : $.extend({}, $target.data(), $this.data());

      e.preventDefault();
      $target.modal_form(option);
    });
  });

  // Default flash handler
  $(function() {
    // Default form complete handler
    $('body').on('ajax:complete', function(e, xhr, status) {
      var data = null;
      try {
        data = JSON.parse(xhr.responseText);
      } catch (exc) {
        //console.debug('exc', exc);
      }

      if (!e.stopRedirect) {
        // Maybe handle AJAX/JSON redirect or refresh
        if (xhr.status == 278) {
          // Handle 278 redirect (AJAX redirect)
          GGRC.navigate(xhr.getResponseHeader('location'));
        } else if (xhr.status == 279) {
          // Handle 279 page refresh
          GGRC.navigate(window.location.href.replace(/#.*/, ''));
        }
        else {
          var modal_form = $(".modal:visible:last").data("modal_form");
          if(modal_form && xhr === modal_form.xhr) {
            delete modal_form.xhr;
            $("[data-toggle=modal-submit]", modal_form.$element)
            .removeAttr("disabled")
            .removeClass("disabled pending-ajax")
            .each(function() {
              $(this).text($(this).data("origText"));
            });
            $("form", modal_form.$element).data("submitpending", false);
          }
        }
      }

      if (data) {
        // Parse and dispatch JSON object
        $(e.target).trigger('ajax:json', [data, xhr]);
      } else if(xhr.responseText) {
        // Dispatch as html, if there is html to dispatch.  (no result should not blank out forms)
        $(e.target).trigger('ajax:html', [xhr.responseText, xhr]);
      }

      if (!e.stopFlash) {
        // Maybe handle AJAX flash messages
        var flash_types = ["error", "alert", "notice", "warning"]
          , type_i, message
          , flash;

        for (type_i in flash_types) {
          message = xhr.getResponseHeader('x-flash-' + flash_types[type_i]);
          message = JSON.parse(message);
          if (message) {
            if (!flash)
              flash = {};
            flash[flash_types[type_i]] = message;
          }
        }

        if (flash) {
          $(document.body).trigger('ajax:flash', flash);
        }
      }
    });

    $('body').on('ajax:flash', function(e, flash) {
      var $target, $flash_holder
        , type, message_i
        , flash_class
        , flash_class_mappings = { notice: "success" }
        , html
        , got_message = _.some(_.values(flash),
                               function (msg) { return !!msg; });

      if (!got_message) {
        // sometimes ajax:flash is triggered with bad data
        return;
      }

      // Find or create the flash-message holder
      $target = $(e.target);
      if($target.has(".modal-body").length < 1)
        $target = $('body');
      $flash_holder = $target.find('.flash');

      if ($flash_holder.length == 0) {
        $flash_holder = $('

');
        $target.find('.modal-body').prepend($flash_holder);
      } else {
        $flash_holder.empty();
      }

      for (type in flash) {
        if (flash[type]) {
          if (typeof(flash[type]) == "string")
            flash[type] = [flash[type]];

          flash_class = flash_class_mappings[type] || type;

          html =
            [ '
'
            ,   'x'
            ];
          for (message_i in flash[type]) {
            html.push('' + flash[type][message_i] + '');
          }
          html.push('
');
          $flash_holder.append(html.join(''));
        }
      }
    });

    $('body').on('ajax:html', '.modal > form', function(e, html, xhr) {
      var sel = "script[type='text/javascript'], script[language='javascript'], script:not([type])";
      var $frag = $(html);
      $frag.filter(sel).add($frag.find(sel)).each(function() {
        $(this).remove();
        setTimeout($(this).html(), 10);
      });
      $(this).find('.modal-body').html($frag);
    });

  });
}(window.jQuery);
<|endoftext|>


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

  function createTable(source, target) {
    var ajaxRequest = new XMLHttpRequest();
    var tableRows, tableData, output, targetNode;

    targetNode = document.querySelector(target);
    ajaxRequest.onload = function(e) {
      tableRows = e.target.responseText.split('\r');
      output = '
';

      for (var row = 0; row < tableRows.length; row++) {
        tableData = tableRows[row].split(',');
        output += '
';

        for (var cell = 0; cell < tableData.length; cell++) {
          if (row===0) {
            output+= ''+ tableData[cell] + '	';
          } else {
            output+= ''+ tableData[cell] + '	';
          } // row 0
        } // go through cells

      } // go through rows

      output += '
';
      targetNode.innerHTML = output;
    }; //ajaxRequest

    ajaxRequest.open('GET', source, true);
    ajaxRequest.responseType = 'text';
    ajaxRequest.send();
  } //create Table

  createTable('_assets/first_semester.csv', '#one');
  createTable('_assets/second_semester.csv', '#two');

})();
<commit_msg>06_03begin<commit_after><|endoftext|>


<commit_before>// Configuration
var host = "http://localhost:3000/";
var squareSize = 5;

// Globals
var snakeA = [];
var snakeB = [];
var players = null;

var gameDiv = d3.select("#game");
var mainSvg = gameDiv.append("svg").attr("id", "gameSvg");
var levelG = mainSvg.append("g").attr("id", "level");
var appleG = mainSvg.append("g").attr("id", "apple");
var snakeAG = mainSvg.append("g").attr("id", "snakeA");
var snakeBG = mainSvg.append("g").attr("id", "snakeB");

var socket = io(host);
socket.on('connect', function () {
    console.log("Connection");

    socket.on('start', function(data) {
        players = data.players;
        console.log("Start. Players 1: " + players[0].name + ' Player 2: ' + players[1].name);
        d3.select("#player1Name").text(players[0].name);
        d3.select("#player2Name").text(players[1].name);
        d3.select("#player1Winner").classed("hidden", true);
        d3.select("#player2Winner").classed("hidden", true);
        console.log(data);
        var level = data.level;
        refreshLevel(level);
    });

    socket.on('positions', function (snakes) {
        snakeA = snakes[0].body;
        snakeB = snakes[1].body;
        refreshSnakes();

        if(!snakes[0].alive && !snakes[1].alive)  {
            console.log("TIE.");
            d3.select("#player1Winner").classed("hidden", false).text("TIE!");
            d3.select("#player2Winner").classed("hidden", false).text("TIE!");
        } else if(!snakes[0].alive) {
            console.log(players[1].name + " won! (Player 2)");
            d3.select("#player2Winner").text("WINNER!").classed("hidden", false);
        } else if(!snakes[1].alive) {
            console.log(players[0].name + " won! (Player 1)");
            d3.select("#player1Winner").text("WINNER!").classed("hidden", false);
        }
    });

    socket.on('apple', function(apple) {
        console.log("Apple: " + apple);
        refreshApple(apple);
    });

    socket.on('end', function() {
        console.log("END");
    })

});

/**
 * Refresh level
 * @param level {Object}    Level data
 */
function refreshLevel(level) {

    mainSvg.attr("width", level.width * squareSize)
           .attr("height", level.height * squareSize);

    var map = level.map;
    var rowG = levelG.selectAll("g")
        .data(map);

    var gameLevelRect = rowG.enter()
        .append("g")
        .selectAll(".gameLevelRect")
        .data( function(d,i) {return d;});

        gameLevelRect.enter()
            .append("rect")
            .attr("class", "gameLevelRect")
            .attr("x", function(d, i, j) { return i*squareSize; })
            .attr("y", function(d, i, j) { return j*squareSize; })
            .attr("width", squareSize+0.5)
            .attr("height", squareSize+0.5)
            .attr("style", function(d, i, j) {
                var blue = (d == 0) ? 0 : 255;
                return "fill:rgb(0,0, " + blue + ");";
            });
        gameLevelRect.exit().remove();

    rowG.exit().remove();
}

/**
 * Refresh snake DIV elements
 */
function refreshSnakes() {
    refreshSnake("snakeA", snakeA, "rgb(255,255,0)", snakeAG);
    refreshSnake("snakeB", snakeB, "rgb(0,255,255)", snakeBG);
}

/**
 * Refresh specified snake DOM elements
 * @param snakeClass {String}   Name of the CSS class which is used for the DOM elements of specified snake
 * @param snake {Object}        Snake data
 * @param colorFill {String}    CSS color fill value of the snake. E.g. "rgb(255,255,0)"
 * @param element {Object}      Parent DIV element where to add snake DIV elements
 */
function refreshSnake(snakeClass, snake, colorFill, element) {

    var refreshCommonSnakeAttr = function(elem) {
        elem.attr("x", function(d) { return d[0]*squareSize;})
            .attr("y", function(d) { return d[1]*squareSize;});
    };

    var rect = element.selectAll("." + snakeClass)
        .data(snake);

    // Update
    refreshCommonSnakeAttr(rect);

    // Enter
    var enterRect = rect.enter()
        .append("rect")
        .attr("class", snakeClass)
        .attr("width", squareSize)
        .attr("height", squareSize)
        .attr("style", "fill:" + colorFill + ";");
    refreshCommonSnakeAttr(enterRect);

    // Exit
    rect.exit().remove();
}

/**
 * Refresh apple DOM elements
 * @param apple {Object}    Apple data
 */
function refreshApple(apple) {
    var element = appleG;
    var appleClass = "apple";
    var appleRadius = squareSize/2.0;
    var circle = element.selectAll("." + appleClass)
        .data([0]);

    var refreshCommonAppleAttr = function(elem) {
        elem.attr("cx", apple[0]*squareSize + appleRadius)
            .attr("cy", apple[1]*squareSize + appleRadius);
    };

    // UPDATE
    refreshCommonAppleAttr(circle);

    // ENTER
    var enterCircle = circle.enter()
        .append("circle")
        .attr("class", appleClass)
        .attr("r", appleRadius)
        .attr("fill", "red");
    refreshCommonAppleAttr(enterCircle);

    // EXIT
    circle.exit().remove();
}<commit_msg>Get rid of global snake arrays<commit_after>// Configuration
var host = "http://localhost:3000/";
var squareSize = 5;

// Globals
var players = null;

var gameDiv = d3.select("#game");
var mainSvg = gameDiv.append("svg").attr("id", "gameSvg");
var levelG = mainSvg.append("g").attr("id", "level");
var appleG = mainSvg.append("g").attr("id", "apple");
var snakeAG = mainSvg.append("g").attr("id", "snakeA");
var snakeBG = mainSvg.append("g").attr("id", "snakeB");

var socket = io(host);
socket.on('connect', function () {
    console.log("Connection");

    socket.on('start', function(data) {
        players = data.players;
        console.log("Start. Players 1: " + players[0].name + ' Player 2: ' + players[1].name);
        d3.select("#player1Name").text(players[0].name);
        d3.select("#player2Name").text(players[1].name);
        d3.select("#player1Winner").classed("hidden", true);
        d3.select("#player2Winner").classed("hidden", true);
        console.log(data);
        var level = data.level;
        refreshLevel(level);
    });

    socket.on('positions', function (snakes) {
        refreshSnakes(snakes);

        if(!snakes[0].alive && !snakes[1].alive)  {
            console.log("TIE.");
            d3.select("#player1Winner").classed("hidden", false).text("TIE!");
            d3.select("#player2Winner").classed("hidden", false).text("TIE!");
        } else if(!snakes[0].alive) {
            console.log(players[1].name + " won! (Player 2)");
            d3.select("#player2Winner").text("WINNER!").classed("hidden", false);
        } else if(!snakes[1].alive) {
            console.log(players[0].name + " won! (Player 1)");
            d3.select("#player1Winner").text("WINNER!").classed("hidden", false);
        }
    });

    socket.on('apple', function(apple) {
        console.log("Apple: " + apple);
        refreshApple(apple);
    });

    socket.on('end', function() {
        console.log("END");
    })

});

/**
 * Refresh level
 * @param level {Object}    Level data
 */
function refreshLevel(level) {

    mainSvg.attr("width", level.width * squareSize)
           .attr("height", level.height * squareSize);

    var map = level.map;
    var rowG = levelG.selectAll("g")
        .data(map);

    var gameLevelRect = rowG.enter()
        .append("g")
        .selectAll(".gameLevelRect")
        .data( function(d,i) {return d;});

        gameLevelRect.enter()
            .append("rect")
            .attr("class", "gameLevelRect")
            .attr("x", function(d, i, j) { return i*squareSize; })
            .attr("y", function(d, i, j) { return j*squareSize; })
            .attr("width", squareSize+0.5)
            .attr("height", squareSize+0.5)
            .attr("style", function(d, i, j) {
                var blue = (d == 0) ? 0 : 255;
                return "fill:rgb(0,0, " + blue + ");";
            });
        gameLevelRect.exit().remove();

    rowG.exit().remove();
}

/**
 * Refresh snake DIV elements
 */
function refreshSnakes(snakes) {
    refreshSnake("snakeA", snakes[0].body, "rgb(255,255,0)", snakeAG);
    refreshSnake("snakeB", snakes[1].body, "rgb(0,255,255)", snakeBG);
}

/**
 * Refresh specified snake DOM elements
 * @param snakeClass {String}   Name of the CSS class which is used for the DOM elements of specified snake
 * @param snake {Object}        Snake data
 * @param colorFill {String}    CSS color fill value of the snake. E.g. "rgb(255,255,0)"
 * @param element {Object}      Parent DIV element where to add snake DIV elements
 */
function refreshSnake(snakeClass, snake, colorFill, element) {

    var refreshCommonSnakeAttr = function(elem) {
        elem.attr("x", function(d) { return d[0]*squareSize;})
            .attr("y", function(d) { return d[1]*squareSize;});
    };

    var rect = element.selectAll("." + snakeClass)
        .data(snake);

    // Update
    refreshCommonSnakeAttr(rect);

    // Enter
    var enterRect = rect.enter()
        .append("rect")
        .attr("class", snakeClass)
        .attr("width", squareSize)
        .attr("height", squareSize)
        .attr("style", "fill:" + colorFill + ";");
    refreshCommonSnakeAttr(enterRect);

    // Exit
    rect.exit().remove();
}

/**
 * Refresh apple DOM elements
 * @param apple {Object}    Apple data
 */
function refreshApple(apple) {
    var element = appleG;
    var appleClass = "apple";
    var appleRadius = squareSize/2.0;
    var circle = element.selectAll("." + appleClass)
        .data([0]);

    var refreshCommonAppleAttr = function(elem) {
        elem.attr("cx", apple[0]*squareSize + appleRadius)
            .attr("cy", apple[1]*squareSize + appleRadius);
    };

    // UPDATE
    refreshCommonAppleAttr(circle);

    // ENTER
    var enterCircle = circle.enter()
        .append("circle")
        .attr("class", appleClass)
        .attr("r", appleRadius)
        .attr("fill", "red");
    refreshCommonAppleAttr(enterCircle);

    // EXIT
    circle.exit().remove();
}<|endoftext|>


<commit_before>/**
 * grunt-webfont: fontforge engine
 *
 * @requires fontforge, ttfautohint 1.00+ (optional), eotlitetool.py
 * @author Artem Sapegin (http://sapegin.me)
 */

module.exports = function(o, allDone) {
	'use strict';

	var fs = require('fs');
	var path = require('path');
	var temp = require('temp');
	var async = require('async');
	var exec = require('exec');
	var chalk = require('chalk');
	var _ = require('lodash');
	var logger = o.logger || require('winston');
	var wf = require('../util/util');

	// Copy source files to temporary directory
	var tempDir = temp.mkdirSync();
	o.files.forEach(function(file) {
		fs.writeFileSync(path.join(tempDir, o.rename(file)), fs.readFileSync(file));
	});

	// Run Fontforge
	var args = [
		'fontforge',
		'-script',
		path.join(__dirname, 'fontforge/generate.py')
	];

	var proc = exec(args, function(err, out, code) {
		if (err instanceof Error && err.code === 'ENOENT') {
			return fontforgeNotFound();
		}
		else if (err) {
			if (err instanceof Error) {
				return error(err.message);
			}

			// Skip some fontforge output such as copyrights. Show warnings only when no font files was created
			// or in verbose mode.
			var success = !!wf.generatedFontFiles(o);
			var notError = /(Copyright|License |with many parts BSD |Executable based on sources from|Library based on sources from|Based on source from git)/;
			var version = /(Executable based on sources from|Library based on sources from)/;
			var lines = err.split('\n');

			var warn = [];
			lines.forEach(function(line) {
				if (!line.match(notError) && !success) {
					warn.push(line);
				}
				else {
					logger.verbose(chalk.grey('fontforge: ') + line);
				}
				if (line.match(version) && success) {
					o.fontforgeVersion.push(line);
				}
			});

			if (warn.length) {
				return error(warn.join('\n'));
			}
		}

		// Trim fontforge result
		var json = out.replace(/^[^{]+/, '').replace(/[^}]+$/, '');

		// Parse json
		var result;
		try {
			result = JSON.parse(json);
		}
		catch (e) {
			logger.verbose('Webfont did not receive a proper JSON result from Python script: ' + e);
			return error(
				'Something went wrong when running fontforge. Probably one of your SVGs is too complicated for fontforge.\n\n' +
				'1. Try to use “node” engine instead of “fontforge”. (See “engine” option in the Readme.)\n\n' +
				'2. To find “bad” icon try to remove SVGs one by one until error disappears. Then try to simplify this SVG in Sketch, Illustrator, etc.\n\n'
			);
		}

		allDone({
			fontName: path.basename(result.file)
		});
	});

	// Send JSON with params
	if (!proc) return;
	proc.stdin.on('error', function(err) {
		if (err.code === 'EPIPE') {
			fontforgeNotFound();
		}
	});
	var params = _.extend(o, {
		inputDir: tempDir
	});
	proc.stdin.write(JSON.stringify(params));
	proc.stdin.end();

	function error() {
		logger.error.apply(null, arguments);
		allDone(false);
		return false;
	}

	function fontforgeNotFound() {
		error('fontforge not found. Please install fontforge and all other requirements.');
	}

};
<commit_msg>Do not store fontforge version in options object.<commit_after>/**
 * grunt-webfont: fontforge engine
 *
 * @requires fontforge, ttfautohint 1.00+ (optional), eotlitetool.py
 * @author Artem Sapegin (http://sapegin.me)
 */

module.exports = function(o, allDone) {
	'use strict';

	var fs = require('fs');
	var path = require('path');
	var temp = require('temp');
	var async = require('async');
	var exec = require('exec');
	var chalk = require('chalk');
	var _ = require('lodash');
	var logger = o.logger || require('winston');
	var wf = require('../util/util');

	// Copy source files to temporary directory
	var tempDir = temp.mkdirSync();
	o.files.forEach(function(file) {
		fs.writeFileSync(path.join(tempDir, o.rename(file)), fs.readFileSync(file));
	});

	// Run Fontforge
	var args = [
		'fontforge',
		'-script',
		path.join(__dirname, 'fontforge/generate.py')
	];

	var proc = exec(args, function(err, out, code) {
		if (err instanceof Error && err.code === 'ENOENT') {
			return fontforgeNotFound();
		}
		else if (err) {
			if (err instanceof Error) {
				return error(err.message);
			}

			// Skip some fontforge output such as copyrights. Show warnings only when no font files was created
			// or in verbose mode.
			var success = !!wf.generatedFontFiles(o);
			var notError = /(Copyright|License |with many parts BSD |Executable based on sources from|Library based on sources from|Based on source from git)/;
			var version = /(Executable based on sources from|Library based on sources from)/;
			var lines = err.split('\n');

			var warn = [];
			lines.forEach(function(line) {
				if (!line.match(notError) && !success) {
					warn.push(line);
				}
				else {
					logger.verbose(chalk.grey('fontforge: ') + line);
				}
			});

			if (warn.length) {
				return error(warn.join('\n'));
			}
		}

		// Trim fontforge result
		var json = out.replace(/^[^{]+/, '').replace(/[^}]+$/, '');

		// Parse json
		var result;
		try {
			result = JSON.parse(json);
		}
		catch (e) {
			logger.verbose('Webfont did not receive a proper JSON result from Python script: ' + e);
			return error(
				'Something went wrong when running fontforge. Probably one of your SVGs is too complicated for fontforge.\n\n' +
				'1. Try to use “node” engine instead of “fontforge”. (See “engine” option in the Readme.)\n\n' +
				'2. To find “bad” icon try to remove SVGs one by one until error disappears. Then try to simplify this SVG in Sketch, Illustrator, etc.\n\n'
			);
		}

		allDone({
			fontName: path.basename(result.file)
		});
	});

	// Send JSON with params
	if (!proc) return;
	proc.stdin.on('error', function(err) {
		if (err.code === 'EPIPE') {
			fontforgeNotFound();
		}
	});
	var params = _.extend(o, {
		inputDir: tempDir
	});
	proc.stdin.write(JSON.stringify(params));
	proc.stdin.end();

	function error() {
		logger.error.apply(null, arguments);
		allDone(false);
		return false;
	}

	function fontforgeNotFound() {
		error('fontforge not found. Please install fontforge and all other requirements.');
	}

};
<|endoftext|>


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

var should = require('should');

var cli = require('../cli');
var capture = require('../util').capture;

var fs = require('fs');
var pathUtil = require('path');
if (!fs.existsSync) {
    fs.existsSync = pathUtil.existsSync;
};

var baseTestTempDir = "__temp";
var testDirBase = "test";
var testDirIndex = 0;
var testDir = "";

suite('cli', function () {
    suite('site deploymentscript', function () {
        setup(function () {
            // Reset site deploymentscript command
            for (var i in cli.categories.site.commands) {
                var command = cli.categories.site.commands[i];
                if (command.name == 'deploymentscript') {
                    delete command.php;
                    delete command.basic;
                    delete command.aspWAP;
                    delete command.aspWebSite;
                    delete command.python;
                    delete command.node;
                    delete command.repositoryRoot;
                    delete command.suppressPrompt;
                    delete command.scriptType;
                    delete command.solutionFile;
                }
            }

            testDirIndex++;
            testDir = pathUtil.join(baseTestTempDir, testDirBase + testDirIndex);
            ensurePathExists(testDir);
        });

        teardown(function () {
            removePath(testDir);
        });

        test('generate basic deployment script (--basic -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --basic -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate php deployment script (--php -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --php -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate python deployment script (--python -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --python -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate python deployment script twice with -y (--python -y -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --python -y -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, function () {
                runBasicSiteDeploymentScriptScenario(cmd, done);
            });
        });

        test('generate basic aspWebSite deployment script (--aspWebSite -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --aspWebSite -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('using exclusion flags together should fail (--aspWebSite --python ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --aspWebSite --python -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('using exclusion flags together should fail (--node --php ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node --php -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('using exclusion flags together should fail (--aspWAP . --basic ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --aspWAP . --basic -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('using exclusion flags together should fail (--basic --php ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --basic --php -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('--aspWAP requires project file path argument', function (done) {
            var cmd = ('node cli.js site deploymentscript -r ' + testDir + ' --aspWAP').split(' ');

            runErrorScenario(cmd, 'argument missing', done);
        });

        test('--node requires directory to contain server.js file (--node)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'Missing server.js/app.js file', done);
        });

        test('generate node deployment script (--node -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node -r ' + testDir).split(' ');

            runNodeSiteDeploymentScriptScenario(cmd, done);
        });
    });
});

function runBasicSiteDeploymentScriptScenario(cmd, callback) {
    runSiteDeploymentScriptScenario(
        cmd,
        ['Generating deployment script for Web Site', 'Generated deployment script (deploy.cmd and .deployment)'],
        ['echo Handling Basic Web Site deployment.'],
        'deploy.cmd',
        callback);
}

function runNodeSiteDeploymentScriptScenario(cmd, callback) {
    generateServerJsFile();

    runSiteDeploymentScriptScenario(
        cmd,
        ['Generating deployment script for node', 'Generated deployment script (deploy.cmd and .deployment)'],
        ['echo Handling node.js deployment.'],
        'deploy.cmd',
        callback);
}

function runSiteDeploymentScriptScenario(cmd, outputContains, scriptContains, scriptFileName, callback) {
    runCommand(cmd, function (result, e) {
        if (e) {
            callback(e);
            return;
        }

        result.exitStatus.should.equal(0, 'Received an error status exit code');

        for (var i = 0; i < outputContains.length; i++) {
            result.text.should.include(outputContains[i]);
        }

        var deployCmdContent = getFileContent(scriptFileName);
        for (var i = 0; i < scriptContains.length; i++) {
            deployCmdContent.should.include(scriptContains[i]);
        }

        var deploymentFileContent = getFileContent('.deployment');
        deploymentFileContent.should.include(scriptFileName);

        callback();
    });
}

function runErrorScenario(cmd, errorText, callback) {
    runCommand(cmd, function (result, e) {
        if (e) {
            callback(e);
            return;
        }

        result.exitStatus.should.equal(1, 'Received success status exit code');
        result.errorText.should.include(errorText);
        callback();
    });
}

function runCommand(cmd, callback) {
    capture(function () {
        cli.parse(cmd);
    }, function (result) {
        if (result.error) {
            // To avoid calling done twice
            return;
        }

        try {
            console.log('\n' + result.text);
            console.log(result.errorText);
            callback(result);
        }
        catch (e) {
            callback(result, e);
        }
    });
}

function generateServerJsFile() {
    fs.writeFileSync(pathUtil.join(testDir, 'server.js'), '//do nothing', 'utf8');
}

function getFileContent(path) {
    path = pathUtil.join(testDir, path);
    fs.existsSync(path).should.equal(true, "File doesn't exist: " + path);
    return fs.readFileSync(path, 'utf8');
}

function removePath(path) {
    var stat = tryGetFileStat(path);
    if (stat) {
        if (!stat.isDirectory()) {
            tryRemoveFile(path);
        }
        else {
            var files = fs.readdirSync(path);
            for (var index in files) {
                var file = files[index];
                var filePath = pathUtil.join(path, file);
                removePath(filePath);
            }

            tryRemoveDir(path);
        }
    }
}

function tryGetFileStat(path) {
    try {
        return fs.statSync(path);
    }
    catch (e) {
        if (e.errno == 34) {
            // Return null if path doesn't exist
            return null;
        }

        throw e;
    }
}

function tryRemoveFile(path) {
    try {
        fs.unlinkSync(path);
    }
    catch (e) {
        console.log(e);
    }
}

function tryRemoveDir(path) {
    try {
        fs.rmdirSync(path);
    }
    catch (e) {
    }
}

function ensurePathExists(path) {
    if (!fs.existsSync(path)) {
        ensurePathExists(pathUtil.dirname(path));
        fs.mkdirSync(path);
    }
}
<commit_msg>Added several bash script generation tests.<commit_after>/**
* Copyright 2012 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var should = require('should');

var cli = require('../cli');
var capture = require('../util').capture;

var fs = require('fs');
var pathUtil = require('path');
if (!fs.existsSync) {
    fs.existsSync = pathUtil.existsSync;
};

var baseTestTempDir = "__temp";
var testDirBase = "test";
var testDirIndex = 0;
var testDir = "";

suite('cli', function () {
    suite('site deploymentscript', function () {
        setup(function () {
            // Reset site deploymentscript command
            for (var i in cli.categories.site.commands) {
                var command = cli.categories.site.commands[i];
                if (command.name == 'deploymentscript') {
                    delete command.php;
                    delete command.basic;
                    delete command.aspWAP;
                    delete command.aspWebSite;
                    delete command.python;
                    delete command.node;
                    delete command.repositoryRoot;
                    delete command.suppressPrompt;
                    delete command.scriptType;
                    delete command.solutionFile;
                }
            }

            testDirIndex++;
            testDir = pathUtil.join(baseTestTempDir, testDirBase + testDirIndex);
            ensurePathExists(testDir);
        });

        teardown(function () {
            removePath(testDir);
        });

        test('generate batch basic deployment script (--basic -t batch -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --basic -t batch -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done, /*bash*/false);
        });

        test('generate bash basic deployment script (--basic -t bash -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --basic -t bash -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done, /*bash*/true);
        });

        test('generate batch php deployment script (--php -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --php -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate bash php deployment script (--php -t bash -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --php -t bash -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done, /*bash*/true);
        });

        test('generate batch python deployment script (--python -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --python -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate batch python deployment script twice with -y (--python -y -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --python -y -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, function () {
                runBasicSiteDeploymentScriptScenario(cmd, done);
            });
        });

        test('generate bash python deployment script (--python --scriptType bash -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --python --scriptType bash -r ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done, /*bash*/true);
        });

        test('generate batch basic aspWebSite deployment script (--aspWebSite --repositoryRoot)', function (done) {
            var cmd = ('node cli.js site deploymentscript --aspWebSite --repositoryRoot ' + testDir).split(' ');

            runBasicSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate node deployment script (--node -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node -r ' + testDir).split(' ');

            runNodeSiteDeploymentScriptScenario(cmd, done);
        });

        test('generate bash node deployment script (--node -t bash -r)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node -t bash -r ' + testDir).split(' ');

            runNodeSiteDeploymentScriptScenario(cmd, done, /*bash*/true);
        });

        test('using exclusion flags together should fail (--aspWebSite --python ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --aspWebSite --python -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('using exclusion flags together should fail (--node --php ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node --php -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('using exclusion flags together should fail (--aspWAP . --basic ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --aspWAP . --basic -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('using exclusion flags together should fail (--basic --php ...)', function (done) {
            var cmd = ('node cli.js site deploymentscript --basic --php -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'specify only one of these flags', done);
        });

        test('--aspWAP requires project file path argument', function (done) {
            var cmd = ('node cli.js site deploymentscript -r ' + testDir + ' --aspWAP').split(' ');

            runErrorScenario(cmd, 'argument missing', done);
        });

        test('--node requires directory to contain server.js file (--node)', function (done) {
            var cmd = ('node cli.js site deploymentscript --node -r ' + testDir).split(' ');

            runErrorScenario(cmd, 'Missing server.js/app.js file', done);
        });
    });
});

function runBasicSiteDeploymentScriptScenario(cmd, callback, bash) {
    var scriptFileName = bash ? 'deploy.sh' : 'deploy.cmd';
    var scriptExtraInclue = bash ? '#!/bin/bash' : '@echo off';

    runSiteDeploymentScriptScenario(
        cmd,
        ['Generating deployment script for Web Site', 'Generated deployment script (' + scriptFileName + ' and .deployment)'],
        ['echo Handling Basic Web Site deployment.', scriptExtraInclue],
        scriptFileName,
        callback);
}

function runNodeSiteDeploymentScriptScenario(cmd, callback, bash) {
    generateServerJsFile();

    var scriptFileName = bash ? 'deploy.sh' : 'deploy.cmd';
    var scriptExtraInclue = bash ? '#!/bin/bash' : '@echo off';

    runSiteDeploymentScriptScenario(
        cmd,
        ['Generating deployment script for node', 'Generated deployment script (' + scriptFileName + ' and .deployment)'],
        ['echo Handling node.js deployment.', scriptExtraInclue],
        scriptFileName,
        callback);
}

function runSiteDeploymentScriptScenario(cmd, outputContains, scriptContains, scriptFileName, callback) {
    runCommand(cmd, function (result, e) {
        if (e) {
            callback(e);
            return;
        }

        result.exitStatus.should.equal(0, 'Received an error status exit code');

        for (var i = 0; i < outputContains.length; i++) {
            result.text.should.include(outputContains[i]);
        }

        var deployCmdContent = getFileContent(scriptFileName);
        for (var i = 0; i < scriptContains.length; i++) {
            deployCmdContent.should.include(scriptContains[i]);
        }

        var deploymentFileContent = getFileContent('.deployment');
        deploymentFileContent.should.include(scriptFileName);

        callback();
    });
}

function runErrorScenario(cmd, errorText, callback) {
    runCommand(cmd, function (result, e) {
        if (e) {
            callback(e);
            return;
        }

        result.exitStatus.should.equal(1, 'Received success status exit code');
        result.errorText.should.include(errorText);
        callback();
    });
}

function runCommand(cmd, callback) {
    capture(function () {
        cli.parse(cmd);
    }, function (result) {
        if (result.error) {
            // To avoid calling done twice
            return;
        }

        try {
            console.log('\n' + result.text);
            console.log(result.errorText);
            callback(result);
        }
        catch (e) {
            callback(result, e);
        }
    });
}

function generateServerJsFile() {
    fs.writeFileSync(pathUtil.join(testDir, 'server.js'), '//do nothing', 'utf8');
}

function getFileContent(path) {
    path = pathUtil.join(testDir, path);
    fs.existsSync(path).should.equal(true, "File doesn't exist: " + path);
    return fs.readFileSync(path, 'utf8');
}

function removePath(path) {
    var stat = tryGetFileStat(path);
    if (stat) {
        if (!stat.isDirectory()) {
            tryRemoveFile(path);
        }
        else {
            var files = fs.readdirSync(path);
            for (var index in files) {
                var file = files[index];
                var filePath = pathUtil.join(path, file);
                removePath(filePath);
            }

            tryRemoveDir(path);
        }
    }
}

function tryGetFileStat(path) {
    try {
        return fs.statSync(path);
    }
    catch (e) {
        if (e.errno == 34) {
            // Return null if path doesn't exist
            return null;
        }

        throw e;
    }
}

function tryRemoveFile(path) {
    try {
        fs.unlinkSync(path);
    }
    catch (e) {
        console.log(e);
    }
}

function tryRemoveDir(path) {
    try {
        fs.rmdirSync(path);
    }
    catch (e) {
    }
}

function ensurePathExists(path) {
    if (!fs.existsSync(path)) {
        ensurePathExists(pathUtil.dirname(path));
        fs.mkdirSync(path);
    }
}
<|endoftext|>


<commit_before>function median(values) {
  values.sort( function(a,b) { return a - b; });
  var half = Math.floor(values.length/2);

  if(values.length % 2)
    return values[half];
  else
    return (Number(values[half - 1]) + Number(values[half]))/2.0;
}

var checkDouble = function (stat) {
  if ( stat >= 10 ) {
    return 1;
  } else {
    return 0;
  }
}

var checkBonus = function (x) {
  if ( x == 2 ) {
    return 1.5;
  }
  if (x >= 3 ) {
    return 3;
  }
  else {
    return 0;
  }
}
$(document).ready(function() {
  $('#per_minute thead tr, #per_game thead tr, #pgl_basic thead tr, #stats thead tr').append('FD	DS	DK	SS	');
  $('#per_minute tbody tr, #per_minute tfoot tr, #per_game tbody tr, #per_game tfoot tr').each(function(index){
    var pts = Number($(this).find('td:nth-last-child(1)').text());
    var ast = Number($(this).find('td:nth-last-child(6)').text());
    var stl = Number($(this).find('td:nth-last-child(5)').text());
    var blk = Number($(this).find('td:nth-last-child(4)').text());
    var tov = Number($(this).find('td:nth-last-child(3)').text());
    var reb = Number($(this).find('td:nth-last-child(7)').text());
    var fga = Number($(this).find('td:nth-last-child(20)').text());
    var fgm = Number($(this).find('td:nth-last-child(21)').text());
    var fta = Number($(this).find('td:nth-last-child(11)').text());
    var ftm = Number($(this).find('td:nth-last-child(12)').text());
    var tpt = Number($(this).find('td:nth-last-child(18)').text());
    var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
    var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
    var stats = [pts, ast, stl, blk, reb];
    var doubles = stats.map(checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = checkBonus(doublesSum);
    var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
    var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });

  var tableHeading = $('.table_heading h2').text();

  $('#stats tbody tr').each(function(index){
    if(tableHeading == "Career Splits") {
      var pts = Number($(this).find('td:nth-last-child(12)').text());
      var ast = Number($(this).find('td:nth-last-child(17)').text());
      var stl = Number($(this).find('td:nth-last-child(16)').text());
      var blk = Number($(this).find('td:nth-last-child(15)').text());
      var tov = Number($(this).find('td:nth-last-child(14)').text());
      var reb = Number($(this).find('td:nth-last-child(18)').text());
      var fga = Number($(this).find('td:nth-last-child(24)').text());
      var fgm = Number($(this).find('td:nth-last-child(25)').text());
      var fta = Number($(this).find('td:nth-last-child(20)').text());
      var ftm = Number($(this).find('td:nth-last-child(21)').text());
      var tpt = Number($(this).find('td:nth-last-child(23)').text());
      var games = Number($(this).find('td:nth-last-child(28)').text());
    }

    else {
      var pts = Number($(this).find('td:nth-last-child(13)').text());
      var ast = Number($(this).find('td:nth-last-child(18)').text());
      var stl = Number($(this).find('td:nth-last-child(17)').text());
      var blk = Number($(this).find('td:nth-last-child(16)').text());
      var tov = Number($(this).find('td:nth-last-child(15)').text());
      var reb = Number($(this).find('td:nth-last-child(19)').text());
      var fga = Number($(this).find('td:nth-last-child(25)').text());
      var fgm = Number($(this).find('td:nth-last-child(26)').text());
      var fta = Number($(this).find('td:nth-last-child(21)').text());
      var ftm = Number($(this).find('td:nth-last-child(22)').text());
      var tpt = Number($(this).find('td:nth-last-child(24)').text());
      var games = Number($(this).find('td:nth-last-child(29)').text());
    }
    var fd = ((pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb))/games).toFixed(2);
    var ds = ((pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm)))/games).toFixed(2);
    var stats = [pts/games, ast/games, stl/games, blk/games, reb/games];
    var doubles = stats.map(checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = checkBonus(doublesSum);
    var dk = ((pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus)/games).toFixed(2);
    var ss = ((pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov)/games).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });
  var fd_vals = [];
  var ds_vals = [];
  var dk_vals = [];
  var ss_vals = [];
  $("#pgl_basic tbody tr").not(".thead").each(function(index){
      var pts = Number($(this).find('td:nth-last-child(3)').text());
      var ast = Number($(this).find('td:nth-last-child(8)').text());
      var stl = Number($(this).find('td:nth-last-child(7)').text());
      var blk = Number($(this).find('td:nth-last-child(6)').text());
      var tov = Number($(this).find('td:nth-last-child(5)').text());
      var reb = Number($(this).find('td:nth-last-child(9)').text());
      var fga = Number($(this).find('td:nth-last-child(19)').text());
      var fgm = Number($(this).find('td:nth-last-child(20)').text());
      var fta = Number($(this).find('td:nth-last-child(13)').text());
      var ftm = Number($(this).find('td:nth-last-child(14)').text());
      var tpt = Number($(this).find('td:nth-last-child(17)').text());
      var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
      fd_vals.push(fd);
      var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
      ds_vals.push(ds);
      var stats = [pts, ast, stl, blk, reb];
      var doubles = stats.map(checkDouble);
      var doublesSum = doubles.reduce(function (a,b) { return a + b });
      var dkBonus = checkBonus(doublesSum);
      var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
      dk_vals.push(dk);
      var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
      ss_vals.push(ss);
      $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });
  $("#pgl_basic tbody").append("
FD	 Median	" + median(fd_vals) + "		Min	" + Math.min.apply(Math,fd_vals) + "		Max	" + Math.max.apply(Math,fd_vals) + "
");
  $("#pgl_basic tbody").append("
DS	 Median	" + median(ds_vals) + "		Min	" + Math.min.apply(Math,ds_vals) + "		Max	" + Math.max.apply(Math,ds_vals) + "
");
  $("#pgl_basic tbody").append("
DK	 Median	" + median(dk_vals) + "		Min	" + Math.min.apply(Math,dk_vals) + "		Max	" + Math.max.apply(Math,dk_vals) + "
");
  $("#pgl_basic tbody").append("
SS	 Median	" + median(ss_vals) + "		Min	" + Math.min.apply(Math,ss_vals) + "		Max	" + Math.max.apply(Math,ss_vals) + "
");
  var url = document.URL;
  if ( url.split('/')[3] == "boxscores" ) {
    $('table').each(function() {
      if ( $(this).attr('id') != undefined && $(this).attr('id').split('_')[1] == "basic" ) {
        $(this).find('thead tr').not('.over_header').append('FD	DS	DK	SS	');
        $(this).find('tbody tr, tfoot tr').not('.thead').each(function(index){
          var pts = Number($(this).find('td:nth-last-child(2)').text());
          var ast = Number($(this).find('td:nth-last-child(7)').text());
          var stl = Number($(this).find('td:nth-last-child(6)').text());
          var blk = Number($(this).find('td:nth-last-child(5)').text());
          var tov = Number($(this).find('td:nth-last-child(4)').text());
          var reb = Number($(this).find('td:nth-last-child(8)').text());
          var fga = Number($(this).find('td:nth-last-child(18)').text());
          var fgm = Number($(this).find('td:nth-last-child(19)').text());
          var fta = Number($(this).find('td:nth-last-child(12)').text());
          var ftm = Number($(this).find('td:nth-last-child(13)').text());
          var tpt = Number($(this).find('td:nth-last-child(16)').text());
          var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
          var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
          var stats = [pts, ast, stl, blk, reb];
          var doubles = stats.map(checkDouble);
          var doublesSum = doubles.reduce(function (a,b) { return a + b });
          var dkBonus = checkBonus(doublesSum);
          var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
          var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
      });
    }
  });
  }
});

<commit_msg>use data-stat to get column index instead of hardcoding index<commit_after>function median(values) {
  values.sort( function(a,b) { return a - b; });
  var half = Math.floor(values.length/2);

  if(values.length % 2)
    return values[half];
  else
    return (Number(values[half - 1]) + Number(values[half]))/2.0;
}

var checkDouble = function (stat) {
  if ( stat >= 10 ) {
    return 1;
  } else {
    return 0;
  }
}

var checkBonus = function (x) {
  if ( x == 2 ) {
    return 1.5;
  }
  if (x >= 3 ) {
    return 3;
  }
  else {
    return 0;
  }
}
$(document).ready(function() {
  $('#per_minute thead tr, #per_game thead tr, #pgl_basic thead tr, #stats thead tr').append('FD	DS	DK	SS	');
  $('#per_minute tbody tr, #per_minute tfoot tr, #per_game tbody tr, #per_game tfoot tr').each(function(index){
    var pts = Number($(this).find('td:nth-last-child(1)').text());
    var ast = Number($(this).find('td:nth-last-child(6)').text());
    var stl = Number($(this).find('td:nth-last-child(5)').text());
    var blk = Number($(this).find('td:nth-last-child(4)').text());
    var tov = Number($(this).find('td:nth-last-child(3)').text());
    var reb = Number($(this).find('td:nth-last-child(7)').text());
    var fga = Number($(this).find('td:nth-last-child(20)').text());
    var fgm = Number($(this).find('td:nth-last-child(21)').text());
    var fta = Number($(this).find('td:nth-last-child(11)').text());
    var ftm = Number($(this).find('td:nth-last-child(12)').text());
    var tpt = Number($(this).find('td:nth-last-child(18)').text());
    var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
    var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
    var stats = [pts, ast, stl, blk, reb];
    var doubles = stats.map(checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = checkBonus(doublesSum);
    var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
    var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });

  var tableHeading = $('.table_heading h2').text();

  $('#stats tbody tr').each(function(index){
    if(tableHeading == "Career Splits") {
      var pts = Number($(this).find('td:nth-last-child(12)').text());
      var ast = Number($(this).find('td:nth-last-child(17)').text());
      var stl = Number($(this).find('td:nth-last-child(16)').text());
      var blk = Number($(this).find('td:nth-last-child(15)').text());
      var tov = Number($(this).find('td:nth-last-child(14)').text());
      var reb = Number($(this).find('td:nth-last-child(18)').text());
      var fga = Number($(this).find('td:nth-last-child(24)').text());
      var fgm = Number($(this).find('td:nth-last-child(25)').text());
      var fta = Number($(this).find('td:nth-last-child(20)').text());
      var ftm = Number($(this).find('td:nth-last-child(21)').text());
      var tpt = Number($(this).find('td:nth-last-child(23)').text());
      var games = Number($(this).find('td:nth-last-child(28)').text());
    }

    else {
      var pts = Number($(this).find('td:nth-last-child(13)').text());
      var ast = Number($(this).find('td:nth-last-child(18)').text());
      var stl = Number($(this).find('td:nth-last-child(17)').text());
      var blk = Number($(this).find('td:nth-last-child(16)').text());
      var tov = Number($(this).find('td:nth-last-child(15)').text());
      var reb = Number($(this).find('td:nth-last-child(19)').text());
      var fga = Number($(this).find('td:nth-last-child(25)').text());
      var fgm = Number($(this).find('td:nth-last-child(26)').text());
      var fta = Number($(this).find('td:nth-last-child(21)').text());
      var ftm = Number($(this).find('td:nth-last-child(22)').text());
      var tpt = Number($(this).find('td:nth-last-child(24)').text());
      var games = Number($(this).find('td:nth-last-child(29)').text());
    }
    var fd = ((pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb))/games).toFixed(2);
    var ds = ((pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm)))/games).toFixed(2);
    var stats = [pts/games, ast/games, stl/games, blk/games, reb/games];
    var doubles = stats.map(checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = checkBonus(doublesSum);
    var dk = ((pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus)/games).toFixed(2);
    var ss = ((pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov)/games).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });
  var fd_vals = [];
  var ds_vals = [];
  var dk_vals = [];
  var ss_vals = [];
  $("#pgl_basic tbody tr").not(".thead").each(function(index){
      var pts = Number($(this).find('td:nth-last-child(3)').text());
      var ast = Number($(this).find('td:nth-last-child(8)').text());
      var stl = Number($(this).find('td:nth-last-child(7)').text());
      var blk = Number($(this).find('td:nth-last-child(6)').text());
      var tov = Number($(this).find('td:nth-last-child(5)').text());
      var reb = Number($(this).find('td:nth-last-child(9)').text());
      var fga = Number($(this).find('td:nth-last-child(19)').text());
      var fgm = Number($(this).find('td:nth-last-child(20)').text());
      var fta = Number($(this).find('td:nth-last-child(13)').text());
      var ftm = Number($(this).find('td:nth-last-child(14)').text());
      var tpt = Number($(this).find('td:nth-last-child(17)').text());
      var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
      fd_vals.push(fd);
      var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
      ds_vals.push(ds);
      var stats = [pts, ast, stl, blk, reb];
      var doubles = stats.map(checkDouble);
      var doublesSum = doubles.reduce(function (a,b) { return a + b });
      var dkBonus = checkBonus(doublesSum);
      var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
      dk_vals.push(dk);
      var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
      ss_vals.push(ss);
      $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });
  $("#pgl_basic tbody").append("
FD	 Median	" + median(fd_vals) + "		Min	" + Math.min.apply(Math,fd_vals) + "		Max	" + Math.max.apply(Math,fd_vals) + "
");
  $("#pgl_basic tbody").append("
DS	 Median	" + median(ds_vals) + "		Min	" + Math.min.apply(Math,ds_vals) + "		Max	" + Math.max.apply(Math,ds_vals) + "
");
  $("#pgl_basic tbody").append("
DK	 Median	" + median(dk_vals) + "		Min	" + Math.min.apply(Math,dk_vals) + "		Max	" + Math.max.apply(Math,dk_vals) + "
");
  $("#pgl_basic tbody").append("
SS	 Median	" + median(ss_vals) + "		Min	" + Math.min.apply(Math,ss_vals) + "		Max	" + Math.max.apply(Math,ss_vals) + "
");
  var url = document.URL;
  if ( url.split('/')[3] == "boxscores" ) {
    $('table').each(function() {
      if ( $(this).attr('id') != undefined && $(this).attr('id').split('_')[1] == "basic" ) {
        $table = $(this);
        var getIndex = function(category) {
            var selector = 'th[data-stat=' + category + ']';
            return $table.find('thead tr:not(.over_header)').first().find(selector).index();
        }
        var getValue = function($row, category) {
            return Number($row.find('td').eq(getIndex(category)).text());
        }
        $(this).find('thead tr').not('.over_header').append('FD	DS	DK	SS	');
        $(this).find('tbody tr, tfoot tr').not('.thead').each(function(index){
          var $row = $(this);
          var pts = getValue($row, 'pts');
          var ast = getValue($row, 'ast');
          var stl = getValue($row, 'stl');
          var blk = getValue($row, 'blk');
          var tov = getValue($row, 'tov');
          var reb = getValue($row, 'trb');
          var fga = getValue($row, 'fga');
          var fgm = getValue($row, 'fg');
          var fta = getValue($row, 'fta');
          var ftm = getValue($row, 'ft');
          var tpt = getValue($row, 'fg3');
          var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
          var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
          var stats = [pts, ast, stl, blk, reb];
          var doubles = stats.map(checkDouble);
          var doublesSum = doubles.reduce(function (a,b) { return a + b });
          var dkBonus = checkBonus(doublesSum);
          var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
          var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
      });
    }
  });
  }
});

<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-region-score-lead@hansolo669
// @name           IITC plugin: region score lead
// @category       Tweaks
// @version        0.2.3
// @namespace      https://github.com/hansolo669/iitc-tweaks
// @updateURL      https://iitc.reallyawesomedomain.com/region-score-lead.meta.js
// @downloadURL    https://iitc.reallyawesomedomain.com/region-score-lead.user.js
// @description    Small modification to the region scores to show the current mu lead.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==
<commit_msg>Fix for intel routing changes<commit_after>// ==UserScript==
// @id             iitc-plugin-region-score-lead@hansolo669
// @name           IITC plugin: region score lead
// @category       Tweaks
// @version        0.2.4
// @namespace      https://github.com/hansolo669/iitc-tweaks
// @updateURL      https://iitc.reallyawesomedomain.com/region-score-lead.meta.js
// @downloadURL    https://iitc.reallyawesomedomain.com/region-score-lead.user.js
// @description    Small modification to the region scores to show the current mu lead.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==
<|endoftext|>


<commit_before>var templates = [
    "root/externallib/text!root/plugins/mootes14/login.html",

];

define(templates, function (loginForm) {
    var plugin = {
        settings: {
            name: "mootes14",
            type: "general",
            menuURL: "#mootes14",
            icon: "plugins/events/icon.png",
            lang: {
                component: "core"
            }
        },

    };

    // Replace the sign-up form with our custom template.
    $("#add-site_template").html(loginForm);

    // Automatically use the URL of the moodle moot without further checks.
    MM.checkSite = function(e) {
        MM.addSite(e);
    };

    // Do not display the manage accounts page.
    MM._displayManageAccounts = function() {
        MM._displayAddSite();
    };

    MM.registerPlugin(plugin);

});<commit_msg>errores cometidos<commit_after>var templates = [
    "root/externallib/text!root/plugins/mootes14/login.html",

];

define(templates, function (loginForm) {
    var plugin = {
        settings: {
            name: "mootes14",
            type: "general",
            menuURL: "#mootes14",
            icon: "plugins/events/icon.png",
            lang: {
                component: "core"
            }
        }

    };

    // Replace the sign-up form with our custom template.
    $("#add-site_template").html(loginForm);

    // Automatically use the URL of the moodle moot without further checks.
    MM.checkSite = function(e) {
        MM.addSite(e);
    };

    // Do not display the manage accounts page.
    MM._displayManageAccounts = function() {
        MM._displayAddSite();
    };

    MM.registerPlugin(plugin);

});<|endoftext|>


<commit_before>'use strict'
var test = require('tap').test
var Gauge = require('../index')
var stream = require('readable-stream')
var util = require('util')
var EventEmitter = require('event-emitter')

function Sink () {
  stream.Writable.call(this, arguments)
}
util.inherits(Sink, stream.Writable)
Sink.prototype._write = function (data, enc, cb) { cb() }

var results = new EventEmitter()
function MockPlumbing (theme, template, columns) {
  results.theme = theme
  results.template = template
  results.columns = columns
  results.emit('new', theme, template, columns)
}
MockPlumbing.prototype = {}

function RecordCall (name) {
  return function () {
    var args = Array.prototype.slice.call(arguments)
    results.emit('called:' + name, args)
    return ''
  }
}

;['setTheme', 'setTemplate', 'setWidth', 'hide', 'show', 'hideCursor', 'showCursor'].forEach(function (fn) {
  MockPlumbing.prototype[fn] = RecordCall(fn)
})

test('defaults', function (t) {
  var gauge = new Gauge(process.stdout)
  t.is(gauge.disabled, false, 'disabled')
  t.is(gauge.updateInterval, 50, 'updateInterval')
  if (process.stdout.isTTY) {
    t.is(gauge.tty, process.stdout, 'tty')
    gauge.disable()
    gauge = new Gauge(process.stderr)
    t.is(gauge.tty, process.stdout, 'tty is stdout when writeTo is stderr')
  }
  gauge.disable()
  gauge = new Gauge(new Sink())
  t.is(gauge.tty, undefined, 'non-tty stream is not tty')
  gauge.disable()
  t.end()
})

test('construct', function (t) {
  var output = new Sink()
  output.isTTY = true
  output.columns = 16
  var gauge = new Gauge(output, {
    Plumbing: MockPlumbing,
    theme: 'THEME',
    template: 'TEMPLATE',
    enabled: false
  })
  t.ok(gauge)
  t.is(results.columns, 15, 'width passed through')
  t.is(results.theme, 'THEME', 'theme passed through')
  t.is(results.template, 'TEMPLATE', 'template passed through')
  t.done()
})

test('show & pulse: fixedframerate', function (t) {
  t.plan(3)
  // this helps us abort if something never emits an event
  // it also keeps things alive long enough to actually get output =D
  var testtimeout = setTimeout(function () {
    t.end()
  }, 1000)
  var output = new Sink()
  output.isTTY = true
  output.columns = 16
  var gauge = new Gauge(output, {
    Plumbing: MockPlumbing,
    updateInterval: 10,
    fixedFramerate: true
  })
  gauge.show('NAME', 0.1)
  results.once('called:show', checkBasicShow)
  function checkBasicShow (args) {
    t.isDeeply(args, [{ spun: 0, section: 'NAME', subsection: '', completed: 0.1 }], 'check basic show')

    gauge.show('S')
    gauge.pulse()
    results.once('called:show', checkPulse)
  }
  function checkPulse (args) {
    t.isDeeply(args, [
      { spun: 1, section: 'S', subsection: '', completed: 0.1 }
    ], 'check pulse')

    gauge.pulse('P')
    results.once('called:show', checkPulseWithArg)
  }
  function checkPulseWithArg (args) {
    t.isDeeply(args, [
      { spun: 2, section: 'S', subsection: 'P', completed: 0.1 }
    ], 'check pulse w/ arg')

    gauge.disable()
    clearTimeout(testtimeout)
    t.done()
  }
})

test('window resizing', function (t) {
  var testtimeout = setTimeout(function () {
    t.end()
  }, 1000)
  var output = new Sink()
  output.isTTY = true
  output.columns = 32

  var gauge = new Gauge(output, {
    Plumbing: MockPlumbing,
    updateInterval: 0,
    fixedFramerate: true
  })
  gauge.show('NAME', 0.1)

  results.once('called:show', function (args) {
    t.isDeeply(args, [{
      section: 'NAME',
      subsection: '',
      completed: 0.1,
      spun: 0
    }])

    results.once('called:setWidth', lookForResize)

    output.columns = 16
    output.emit('resize')
    gauge.show('NAME', 0.5)
  })
  function lookForResize (args) {
    t.isDeeply(args, [15])
    results.once('called:show', lookForShow)
  }
  function lookForShow (args) {
    t.isDeeply(args, [{
      section: 'NAME',
      subsection: '',
      completed: 0.5,
      spun: 0
    }])
    gauge.disable()
    clearTimeout(testtimeout)
    t.done()
  }
})
<commit_msg>doc tests yet to be written for 100% coverage<commit_after>'use strict'
var test = require('tap').test
var Gauge = require('../index')
var stream = require('readable-stream')
var util = require('util')
var EventEmitter = require('event-emitter')

function Sink () {
  stream.Writable.call(this, arguments)
}
util.inherits(Sink, stream.Writable)
Sink.prototype._write = function (data, enc, cb) { cb() }

var results = new EventEmitter()
function MockPlumbing (theme, template, columns) {
  results.theme = theme
  results.template = template
  results.columns = columns
  results.emit('new', theme, template, columns)
}
MockPlumbing.prototype = {}

function RecordCall (name) {
  return function () {
    var args = Array.prototype.slice.call(arguments)
    results.emit('called:' + name, args)
    return ''
  }
}

;['setTheme', 'setTemplate', 'setWidth', 'hide', 'show', 'hideCursor', 'showCursor'].forEach(function (fn) {
  MockPlumbing.prototype[fn] = RecordCall(fn)
})

test('defaults', function (t) {
  var gauge = new Gauge(process.stdout)
  t.is(gauge.disabled, false, 'disabled')
  t.is(gauge.updateInterval, 50, 'updateInterval')
  if (process.stdout.isTTY) {
    t.is(gauge.tty, process.stdout, 'tty')
    gauge.disable()
    gauge = new Gauge(process.stderr)
    t.is(gauge.tty, process.stdout, 'tty is stdout when writeTo is stderr')
  }
  gauge.disable()
  gauge = new Gauge(new Sink())
  t.is(gauge.tty, undefined, 'non-tty stream is not tty')
  gauge.disable()
  t.end()
})

test('construct', function (t) {
  var output = new Sink()
  output.isTTY = true
  output.columns = 16
  var gauge = new Gauge(output, {
    Plumbing: MockPlumbing,
    theme: 'THEME',
    template: 'TEMPLATE',
    enabled: false
  })
  t.ok(gauge)
  t.is(results.columns, 15, 'width passed through')
  t.is(results.theme, 'THEME', 'theme passed through')
  t.is(results.template, 'TEMPLATE', 'template passed through')
  t.done()
})

test('show & pulse: fixedframerate', function (t) {
  t.plan(3)
  // this helps us abort if something never emits an event
  // it also keeps things alive long enough to actually get output =D
  var testtimeout = setTimeout(function () {
    t.end()
  }, 1000)
  var output = new Sink()
  output.isTTY = true
  output.columns = 16
  var gauge = new Gauge(output, {
    Plumbing: MockPlumbing,
    updateInterval: 10,
    fixedFramerate: true
  })
  gauge.show('NAME', 0.1)
  results.once('called:show', checkBasicShow)
  function checkBasicShow (args) {
    t.isDeeply(args, [{ spun: 0, section: 'NAME', subsection: '', completed: 0.1 }], 'check basic show')

    gauge.show('S')
    gauge.pulse()
    results.once('called:show', checkPulse)
  }
  function checkPulse (args) {
    t.isDeeply(args, [
      { spun: 1, section: 'S', subsection: '', completed: 0.1 }
    ], 'check pulse')

    gauge.pulse('P')
    results.once('called:show', checkPulseWithArg)
  }
  function checkPulseWithArg (args) {
    t.isDeeply(args, [
      { spun: 2, section: 'S', subsection: 'P', completed: 0.1 }
    ], 'check pulse w/ arg')

    gauge.disable()
    clearTimeout(testtimeout)
    t.done()
  }
})

test('window resizing', function (t) {
  var testtimeout = setTimeout(function () {
    t.end()
  }, 1000)
  var output = new Sink()
  output.isTTY = true
  output.columns = 32

  var gauge = new Gauge(output, {
    Plumbing: MockPlumbing,
    updateInterval: 0,
    fixedFramerate: true
  })
  gauge.show('NAME', 0.1)

  results.once('called:show', function (args) {
    t.isDeeply(args, [{
      section: 'NAME',
      subsection: '',
      completed: 0.1,
      spun: 0
    }])

    results.once('called:setWidth', lookForResize)

    output.columns = 16
    output.emit('resize')
    gauge.show('NAME', 0.5)
  })
  function lookForResize (args) {
    t.isDeeply(args, [15])
    results.once('called:show', lookForShow)
  }
  function lookForShow (args) {
    t.isDeeply(args, [{
      section: 'NAME',
      subsection: '',
      completed: 0.5,
      spun: 0
    }])
    gauge.disable()
    clearTimeout(testtimeout)
    t.done()
  }
})

/* todo missing:

constructor with hideCursor value

  writeTo: process.stderr & process.stdout IS A TTY (or isn't)
  cleanupOnExit: explicitly set to true

disable while showing then enable

enable while fixedFramerate is false

enable while fixedFramerate is true & redrawTracker.unref is false (0.8)

disable while fixedFramerate is false

hide()

show() while disabled

show() with object args

show() with neither string nor object (undefined? number?)

show() with fixedFramerate == false

pulse() while disabled
pulse while _showing == false
pulse where fixedFramerate == false

implicit:
  _doRedraw will get called with fixedFramerate = false if we test the above
  trigger a show + redraw with hideCursor = true
  trigger a hide + redraw with hideCursor = true

trigger a _doRedraw when _needsRedraw is false

TEST BACKPRESSURE

*/
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import {Link} from 'react-router'
import {Injectable, Injector} from 'react-injectables'

import SearchBar from 'components/SearchBar.js'
import CreateButton from 'components/CreateButton.js'

import logo from 'resources/logo.png'

const backgroundCss = {
	position: 'fixed',
	top: 0,
	left: 0,
	right: 0,
	background: '#fff',
	paddingTop: '58px',
	height: '132px',
	boxShadow: '0 4px 3px 0 rgba(0,0,0,0.1)',
	zIndex: 100
}

const logoCss = {
	width: '164px',
}

class Header extends Component {
	render() {
		let leftContent, middleContent, rightContent
		this.props.injections.forEach(injection => {
			let content = injection.props.children

			if (content && content.props) {
				if (content.props.left)
					return leftContent = injection
				else if (content.props.right)
					return rightContent = injection
			}
			return middleContent = injection
		})

		return (

					{leftContent || <Link to="/" className="pull-left">

					</Link>}

						{middleContent || <SearchBar />}

						{rightContent || <CreateButton />}

		)
	}
}

let InjectableHeader = null
let ContentForHeader = null
if (process.env.NODE_ENV === 'test') {
	ContentForHeader = function(props) {
		return

	}
} else {
	// this is some magic around the Injectable library to allow
	// components further down the tree to inject children into the header
	InjectableHeader = Injectable(Header)

	const HeaderInjector = Injector({into: InjectableHeader})
	ContentForHeader = function(props) {
		let {children, ...childProps} = props
		let Component = HeaderInjector(function() { return children })
		return <Component {...childProps} />
	}
}

export default InjectableHeader
export {ContentForHeader}
<commit_msg>Move Header components into a grid<commit_after>import React, {Component} from 'react'
import {Link} from 'react-router'
import {Grid, Row, Col} from 'react-bootstrap'
import {Injectable, Injector} from 'react-injectables'

import SearchBar from 'components/SearchBar.js'
import CreateButton from 'components/CreateButton.js'

import logo from 'resources/logo.png'

const backgroundCss = {
	position: 'fixed',
	top: 0,
	left: 0,
	right: 0,
	background: '#fff',
	paddingTop: '58px',
	height: '132px',
	boxShadow: '0 4px 3px 0 rgba(0,0,0,0.1)',
	zIndex: 100
}

const logoCss = {
	width: '164px',
}

class Header extends Component {
	render() {
		let leftContent, middleContent, rightContent
		this.props.injections.forEach(injection => {
			let content = injection.props.children

			if (content && content.props) {
				if (content.props.left)
					return leftContent = injection
				else if (content.props.right)
					return rightContent = injection
			}
			return middleContent = injection
		})

		return (

				<Grid>
					<Row>
						<Col xs={3}>
							{leftContent || <Link to="/">

							</Link>}
						</Col>

						<Col xs={7}>
							{middleContent || <SearchBar />}
						</Col>

						<Col xs={2}>

								{rightContent || <CreateButton />}

						</Col>
					</Row>
				</Grid>

		)
	}
}

let InjectableHeader = null
let ContentForHeader = null
if (process.env.NODE_ENV === 'test') {
	ContentForHeader = function(props) {
		return

	}
} else {
	// this is some magic around the Injectable library to allow
	// components further down the tree to inject children into the header
	InjectableHeader = Injectable(Header)

	const HeaderInjector = Injector({into: InjectableHeader})
	ContentForHeader = function(props) {
		let {children, ...childProps} = props
		let Component = HeaderInjector(function() { return children })
		return <Component {...childProps} />
	}
}

export default InjectableHeader
export {ContentForHeader}
<|endoftext|>


<commit_before>const normalizeSchema = require('./normalizeSchema');

const define = Object.defineProperty;
const createAttrs = () => Object.create(null);

const SCHEMA = Symbol('schema');
const ATTRIBUTES = Symbol('attributes');

const attributesDescriptor = {
  get() {

    if(!this[ATTRIBUTES]) {
      const attributes = createAttrs();

      define(this, ATTRIBUTES, {
        configurable: true,
        value: attributes
      });
    }

    return this[ATTRIBUTES];
  },

  set(newAttributes) {
    const attributes = createAttrs();
    const schema = this[SCHEMA];
    const attrNames = Object.keys(schema);

    for(let i = 0; i < attrNames.length; i++) {
      attributes[attrNames[i]] = schema[attrNames[i]].coerce(newAttributes[attrNames[i]]);
    }

    define(this, ATTRIBUTES, {
      configurable: true,
      value: attributes
    });
  }
};

function attributesDecorator(declaredSchema, ErroneousPassedClass) {
  if(ErroneousPassedClass) {
    const errorMessage = `You passed the entity class as the second parameter of entity(). The expected usage is \`entity(schema)(${ ErroneousPassedClass.name || 'EntityClass' })\`.`;

    throw new Error(errorMessage);
  }

  return function decorator(Class) {
    const WrapperClass = new Proxy(Class, {
      construct(target, constructorArgs, newTarget) {
        const instance = Reflect.construct(target, constructorArgs, newTarget);
        const passedAttributes = constructorArgs[0];
        const schema = newTarget[SCHEMA];

        instance.attributes = passedAttributes;

        return instance;
      }
    });

    if(SCHEMA in WrapperClass) {
      declaredSchema = Object.assign({}, WrapperClass[SCHEMA], declaredSchema);
    }

    declaredSchema = normalizeSchema(declaredSchema);

    define(WrapperClass, SCHEMA, {
      value: declaredSchema
    });

    define(WrapperClass.prototype, SCHEMA, {
      value: declaredSchema
    });

    define(WrapperClass.prototype, 'attributes', attributesDescriptor);

    Object.keys(declaredSchema).forEach((attr) => {
      define(WrapperClass.prototype, attr, {
        get() {
          return this.attributes[attr];
        },

        set(value) {
          this.attributes[attr] = value;
        }
      });
    });

    return WrapperClass;
  };
}

module.exports = attributesDecorator;
<commit_msg>Remove unused variable<commit_after>const normalizeSchema = require('./normalizeSchema');

const define = Object.defineProperty;
const createAttrs = () => Object.create(null);

const SCHEMA = Symbol('schema');
const ATTRIBUTES = Symbol('attributes');

const attributesDescriptor = {
  get() {

    if(!this[ATTRIBUTES]) {
      const attributes = createAttrs();

      define(this, ATTRIBUTES, {
        configurable: true,
        value: attributes
      });
    }

    return this[ATTRIBUTES];
  },

  set(newAttributes) {
    const attributes = createAttrs();
    const schema = this[SCHEMA];
    const attrNames = Object.keys(schema);

    for(let i = 0; i < attrNames.length; i++) {
      attributes[attrNames[i]] = schema[attrNames[i]].coerce(newAttributes[attrNames[i]]);
    }

    define(this, ATTRIBUTES, {
      configurable: true,
      value: attributes
    });
  }
};

function attributesDecorator(declaredSchema, ErroneousPassedClass) {
  if(ErroneousPassedClass) {
    const errorMessage = `You passed the entity class as the second parameter of entity(). The expected usage is \`entity(schema)(${ ErroneousPassedClass.name || 'EntityClass' })\`.`;

    throw new Error(errorMessage);
  }

  return function decorator(Class) {
    const WrapperClass = new Proxy(Class, {
      construct(target, constructorArgs, newTarget) {
        const instance = Reflect.construct(target, constructorArgs, newTarget);
        const passedAttributes = constructorArgs[0];

        instance.attributes = passedAttributes;

        return instance;
      }
    });

    if(SCHEMA in WrapperClass) {
      declaredSchema = Object.assign({}, WrapperClass[SCHEMA], declaredSchema);
    }

    declaredSchema = normalizeSchema(declaredSchema);

    define(WrapperClass, SCHEMA, {
      value: declaredSchema
    });

    define(WrapperClass.prototype, SCHEMA, {
      value: declaredSchema
    });

    define(WrapperClass.prototype, 'attributes', attributesDescriptor);

    Object.keys(declaredSchema).forEach((attr) => {
      define(WrapperClass.prototype, attr, {
        get() {
          return this.attributes[attr];
        },

        set(value) {
          this.attributes[attr] = value;
        }
      });
    });

    return WrapperClass;
  };
}

module.exports = attributesDecorator;
<|endoftext|>