<commit_before>'use strict';

var expect = require('chai').expect;
var AIPlayer = require('../app/scripts/models/ai-player');
var Game = require('../app/scripts/models/game');
var Chip = require('../app/scripts/models/chip');

describe('AI player', function () {

  // Place chips at the given columns with the given players
  function placeChips(args) {
    var currentPlayer = args.game.players[0];
    args.columns.forEach(function (column) {
      var chip = new Chip({player: currentPlayer});
      args.game.grid.placeChip({column: column, chip: chip});
      if (currentPlayer == args.game.players[0]) {
        currentPlayer = args.game.players[1];
      } else {
        currentPlayer = args.game.players[0];
      }
    });
  }

  it('should initialize', function () {
    var aiPlayer = new AIPlayer({
      name: 'HAL',
      color: 'red'
    });
    expect(aiPlayer).to.have.property('name', 'HAL');
    expect(aiPlayer).to.have.property('color', 'red');
    expect(aiPlayer).to.have.property('score', 0);
    expect(aiPlayer).to.have.property('type', 'ai');
  });

  it('should block horizontal opponent win', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [3, 2, 5, 2, 6]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(4);
  });

  it('should block vertical opponent win', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [3, 2, 3, 2, 3]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(3);
  });

  it('should block diagonal opponent win', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [4, 3, 3, 2, 1, 2, 2, 1, 1]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(1);
  });

  it('should win vertically on turn', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [3, 2, 3, 2, 5, 2, 4]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(2);
  });

});
<commit_msg>Add AI tests for winning horizontally and diagonally<commit_after>'use strict';

var expect = require('chai').expect;
var AIPlayer = require('../app/scripts/models/ai-player');
var Game = require('../app/scripts/models/game');
var Chip = require('../app/scripts/models/chip');

describe('AI player', function () {

  // Place chips at the given columns with the given players
  function placeChips(args) {
    var currentPlayer = args.game.players[0];
    args.columns.forEach(function (column) {
      var chip = new Chip({player: currentPlayer});
      args.game.grid.placeChip({column: column, chip: chip});
      if (currentPlayer == args.game.players[0]) {
        currentPlayer = args.game.players[1];
      } else {
        currentPlayer = args.game.players[0];
      }
    });
  }

  it('should initialize', function () {
    var aiPlayer = new AIPlayer({
      name: 'HAL',
      color: 'red'
    });
    expect(aiPlayer).to.have.property('name', 'HAL');
    expect(aiPlayer).to.have.property('color', 'red');
    expect(aiPlayer).to.have.property('score', 0);
    expect(aiPlayer).to.have.property('type', 'ai');
  });

  it('should block horizontal opponent win', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [3, 2, 5, 2, 6]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(4);
  });

  it('should block vertical opponent win', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [3, 2, 3, 2, 3]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(3);
  });

  it('should block diagonal opponent win', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [4, 3, 3, 2, 1, 2, 2, 1, 1]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(1);
  });

  it('should win horizontally on turn', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [1, 2, 1, 3, 1, 1, 2, 4, 2]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(5);
  });

  it('should win vertically on turn', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [3, 2, 3, 2, 5, 2, 4]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(2);
  });

  it('should win diagonally on turn', function () {
    var game = new Game();
    game.setPlayers(1);
    game.startGame();
    placeChips({
      game: game,
      columns: [2, 3, 3, 5, 5, 5, 4, 4, 4]
    });
    expect(game.players[1].computeNextMove(game)).to.equal(5);
  });

});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */

/** extension to generate JSDoc annotations for functions */
define(function (require, exports, module) {

    'use strict';

    var CommandManager      = brackets.getModule("command/CommandManager"),
        EditorManager       = brackets.getModule("editor/EditorManager"),
        KeyBindingManager   = brackets.getModule("command/KeyBindingManager"),
        Menus               = brackets.getModule("command/Menus");

    var EMPTY_MSG   = "No function found";
    var COMMAND_ID  = "annotate.annotate";
    var MENU_NAME   = "Annotate function";

    function insert(input) {

        var editor = EditorManager.getCurrentFullEditor();
        var pos    = editor.getCursorPos();
        pos.ch = 0;

        editor._codeMirror.replaceRange(input, pos);

        EditorManager.focusEditor();

    }

    /**
     * get the whitespace characters from line start to beginning of function def
     * @param string input lines from start of the function definition
     * @param string match function definition start
     */
    function getPrefix(input, match) {

        var indexOf = input.indexOf(match),
            prefix  = "";
        if (indexOf !== -1) {
            prefix = input.substr(0, indexOf);
        }

        return prefix;

    }

    function getTarget() {

        var editor = EditorManager.getCurrentFullEditor();
        var pos    = editor.getCursorPos();
        pos.ch = 0;

        // Take the text of the document, starting with the current cursor line
        var txtFrom = editor._codeMirror.getRange(pos, {line: editor._codeMirror.lineCount() });

        // For now, we generate annotations from the signature only (missing return statements)
        txtFrom = txtFrom.substr(0, txtFrom.indexOf("{"));

        // Look for words
        var re = /[$,\w]+/g;
        var results = txtFrom.match(re);

        // The first word found should be "function", and next ones parameters

        if (results[0] === "function") {
            return {
                name: results[1],
                params: results.slice(2),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "private" && results[1] === "function") {
            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "public" && results[1] === "function") {
            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "static" && results[1] === "function") {
            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "var" && results[2] === "function") {

            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if(results[0] === "this" && results[2] === "function"){

            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[1] === "function") {

            return {
                name: results[0],
                params: results.slice(2),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[1] === "function") {
            return {
                name: results[0],
                params: results.slice(2),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else {
            return null;
        }

    }

    /**
     * Generate comment block
     * @param string fname function name
     * @param string params function parameters
     * @param string prefix whitespace prefix for comment block lines
     */
    function generateComment(fname, params, prefix) {

        var output = [];
        output.push("/**");

        // Assume function is private if it starts with an underscore
        if (fname.charAt(0) === "_") {
            output.push(" * @private");
        }

        // Add description
        output.push(" * Description");

        // Add parameters
        if (params.length > 0) {
            var i;
            for (i = 0; i < params.length; i++) {
                var param = params[i];
                output.push(" * @param {type} " + param + " Description");
            }
        }

        // TODO use if 'return' is found in the function body?
        //output += " * @return {type} ???\n";
        output.push(" */");

        return prefix + output.join(prefix);
    }

    function annotate() {

        var target = getTarget();

        if (target === null) {
            window.alert(EMPTY_MSG);
            return;
        }

        var comment = generateComment(target.name, target.params, target.prefix);

        insert(comment);
    }

    CommandManager.register(MENU_NAME, COMMAND_ID, annotate);
    KeyBindingManager.addBinding(COMMAND_ID, "Ctrl-Alt-A");

    var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    menu.addMenuDivider();
    menu.addMenuItem(COMMAND_ID);//"menu-edit-annotate",

});
<commit_msg>Support for functions added to prototype<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */

/** extension to generate JSDoc annotations for functions */
define(function (require, exports, module) {

    'use strict';

    var CommandManager      = brackets.getModule("command/CommandManager"),
        EditorManager       = brackets.getModule("editor/EditorManager"),
        KeyBindingManager   = brackets.getModule("command/KeyBindingManager"),
        Menus               = brackets.getModule("command/Menus");

    var EMPTY_MSG   = "No function found";
    var COMMAND_ID  = "annotate.annotate";
    var MENU_NAME   = "Annotate function";

    function insert(input) {

        var editor = EditorManager.getCurrentFullEditor();
        var pos    = editor.getCursorPos();
        pos.ch = 0;

        editor._codeMirror.replaceRange(input, pos);

        EditorManager.focusEditor();

    }

    /**
     * get the whitespace characters from line start to beginning of function def
     * @param string input lines from start of the function definition
     * @param string match function definition start
     */
    function getPrefix(input, match) {

        var indexOf = input.indexOf(match),
            prefix  = "";
        if (indexOf !== -1) {
            prefix = input.substr(0, indexOf);
        }

        return prefix;

    }

    function getTarget() {

        var editor = EditorManager.getCurrentFullEditor();
        var pos    = editor.getCursorPos();
        pos.ch = 0;

        // Take the text of the document, starting with the current cursor line
        var txtFrom = editor._codeMirror.getRange(pos, {line: editor._codeMirror.lineCount() });

        // For now, we generate annotations from the signature only (missing return statements)
        txtFrom = txtFrom.substr(0, txtFrom.indexOf("{"));

        // Look for words
        var re = /[$,\w]+/g;
        var results = txtFrom.match(re);

        // The first word found should be "function", and next ones parameters

        if (results[0] === "function") {
            return {
                name: results[1],
                params: results.slice(2),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "private" && results[1] === "function") {
            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "public" && results[1] === "function") {
            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "static" && results[1] === "function") {
            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[0] === "var" && results[2] === "function") {

            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if(results[0] === "this" && results[2] === "function"){

            return {
                name: results[1],
                params: results.slice(3),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[1] === "function") {

            return {
                name: results[0],
                params: results.slice(2),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if (results[1] === "function") {
            return {
                name: results[0],
                params: results.slice(2),
                prefix: getPrefix(txtFrom, results[0])
            };
        } else if(txtFrom.indexOf('.prototype.')){
            var i = 1;
            for(;i<results.length; i+=1){
                if(results[i] === 'function'){
                    return {
                        name: results[i-1],
                        params: results.slice(i+1),
                        prefix: getPrefix(txtFrom, results[0])
                    };
                }
            }
        } else {
            return null;
        }

    }

    /**
     * Generate comment block
     * @param string fname function name
     * @param string params function parameters
     * @param string prefix whitespace prefix for comment block lines
     */
    function generateComment(fname, params, prefix) {

        var output = [];
        output.push("/**");

        // Assume function is private if it starts with an underscore
        if (fname.charAt(0) === "_") {
            output.push(" * @private");
        }

        // Add description
        output.push(" * Description");

        // Add parameters
        if (params.length > 0) {
            var i;
            for (i = 0; i < params.length; i++) {
                var param = params[i];
                output.push(" * @param {type} " + param + " Description");
            }
        }

        // TODO use if 'return' is found in the function body?
        //output += " * @return {type} ???\n";
        output.push(" */");

        return prefix + output.join(prefix);
    }

    function annotate() {

        var target = getTarget();

        if (target === null) {
            window.alert(EMPTY_MSG);
            return;
        }

        var comment = generateComment(target.name, target.params, target.prefix);

        insert(comment);
    }

    CommandManager.register(MENU_NAME, COMMAND_ID, annotate);
    KeyBindingManager.addBinding(COMMAND_ID, "Ctrl-Alt-A");

    var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
    menu.addMenuDivider();
    menu.addMenuItem(COMMAND_ID);//"menu-edit-annotate",

});
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright 2009-2012 Eucalyptus Systems, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
 * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
 * additional information or have any questions.
 ************************************************************************/

(function($, eucalyptus) {
  $.widget('eucalyptus.maincontainer', {
    options : {
        default_selected : 'dashboard',
    },

    _curSelected : null,

    _init : function() {
      this.updateSelected(this.options.default_selected);
      this.element.show();
    },

    _create : function() {
    },

    _destroy : function() {
    },

    // event receiver for menu selection
    changeSelected : function (evt, ui) {
        this.updateSelected(ui.selected, ui.filter, ui.options);
    },

    updateSelected : function (selected, filter, options) {
      if(this._curSelected === selected){
        //$('html body').trigger('click'); // Manage resources --> uncomment this line
        return;
      }

      if(this._curSelected !== null){
        var $curInstance = this.element.data(this._curSelected);
        if($curInstance !== undefined && options != OPEN_NEW_WINDOW){
          $curInstance.close();
        }
      }
      var $container = $('html body').find(DOM_BINDING['main']);
      if (options != OPEN_NEW_WINDOW)
        $container.children().detach();
     // $('html body').eucaevent('unclick_all'); // this will close menus that's pulled down
     // Manage resources-->uncomment above
      switch(selected){
        case 'dashboard':
          this.element.dashboard({select: function(evt, ui){$container.maincontainer("changeSelected", evt, ui)}});
          break;
        case 'instance':
          this.element.instance({'state_filter': filter});
          break;
        case 'keypair':
          this.element.keypair();
          break;
        case 'sgroup':
          this.element.sgroup();
          break;
        case 'volume':
          this.element.volume();
          break;
        case 'snapshot':
          this.element.snapshot();
          break;
        case 'eip':
          this.element.eip();
          break;
        case 'launcher':
          var option = {};
          if(filter && filter['image'])
            option['image'] = filter['image'];
          if(filter && filter['type'])
            option['type'] = filter['type'];
          if(filter && filter['security'])
            option['security'] = filter['security'];
          if(filter && filter['advanced'])
            option['advanced'] = filter['advanced'];
          this.element.launcher(option);
          break;
        case 'image':
          this.element.image();
          break;
        case 'logout':
          logout();
          break;
        case 'documentation':
          window.open('http://www.eucalyptus.com/eucalyptus-cloud/documentation', '_blank');
          break;
        case 'forum':
          window.open('https://engage.eucalyptus.com', '_blank');
          break;
        default:
          $('html body').find(DOM_BINDING['notification']).notification('error', 'internal error', selected+' not yet implemented', 1);
      }
      if (options != OPEN_NEW_WINDOW)
        this._curSelected = selected;
    },

    clearSelected : function (){
      var $curInstance = this.element.data(this._curSelected);
      if($curInstance !== undefined){
        $curInstance.close();
      }
      this._curSelected = null;
    },

    getSelected : function () {
      return this._curSelected;
    }
  });
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});
<commit_msg>Added link to 'report an issue'<commit_after>/*************************************************************************
 * Copyright 2009-2012 Eucalyptus Systems, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
 * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
 * additional information or have any questions.
 ************************************************************************/

(function($, eucalyptus) {
  $.widget('eucalyptus.maincontainer', {
    options : {
        default_selected : 'dashboard',
    },

    _curSelected : null,

    _init : function() {
      this.updateSelected(this.options.default_selected);
      this.element.show();
    },

    _create : function() {
    },

    _destroy : function() {
    },

    // event receiver for menu selection
    changeSelected : function (evt, ui) {
        this.updateSelected(ui.selected, ui.filter, ui.options);
    },

    updateSelected : function (selected, filter, options) {
      if(this._curSelected === selected){
        //$('html body').trigger('click'); // Manage resources --> uncomment this line
        return;
      }

      if(this._curSelected !== null){
        var $curInstance = this.element.data(this._curSelected);
        if($curInstance !== undefined && options != OPEN_NEW_WINDOW){
          $curInstance.close();
        }
      }
      var $container = $('html body').find(DOM_BINDING['main']);
      if (options != OPEN_NEW_WINDOW)
        $container.children().detach();
     // $('html body').eucaevent('unclick_all'); // this will close menus that's pulled down
     // Manage resources-->uncomment above
      switch(selected){
        case 'dashboard':
          this.element.dashboard({select: function(evt, ui){$container.maincontainer("changeSelected", evt, ui)}});
          break;
        case 'instance':
          this.element.instance({'state_filter': filter});
          break;
        case 'keypair':
          this.element.keypair();
          break;
        case 'sgroup':
          this.element.sgroup();
          break;
        case 'volume':
          this.element.volume();
          break;
        case 'snapshot':
          this.element.snapshot();
          break;
        case 'eip':
          this.element.eip();
          break;
        case 'launcher':
          var option = {};
          if(filter && filter['image'])
            option['image'] = filter['image'];
          if(filter && filter['type'])
            option['type'] = filter['type'];
          if(filter && filter['security'])
            option['security'] = filter['security'];
          if(filter && filter['advanced'])
            option['advanced'] = filter['advanced'];
          this.element.launcher(option);
          break;
        case 'image':
          this.element.image();
          break;
        case 'logout':
          logout();
          break;
        case 'documentation':
          window.open('http://www.eucalyptus.com/eucalyptus-cloud/documentation', '_blank');
          break;
        case 'forum':
          window.open('https://engage.eucalyptus.com', '_blank');
          break;
        case 'report':
          window.open('https://eucalyptus.atlassian.net', '_blank');
          break;
        default:
          $('html body').find(DOM_BINDING['notification']).notification('error', 'internal error', selected+' not yet implemented', 1);
      }
      if (options != OPEN_NEW_WINDOW)
        this._curSelected = selected;
    },

    clearSelected : function (){
      var $curInstance = this.element.data(this._curSelected);
      if($curInstance !== undefined){
        $curInstance.close();
      }
      this._curSelected = null;
    },

    getSelected : function () {
      return this._curSelected;
    }
  });
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});
<|endoftext|>


<commit_before>var deliveryBoy = {
    name: "",
}

deliveryBoy.receive();<commit_msg>[UPDATE] Arros Functions Delivery Boy<commit_after>var deliveryBoy = {

    name: "John",

    handleMessage: function (message, handle) {
        hendler(message);
    },

    receive: function() {
        var that = this;

        this.handleMessage("Message: ", function (message) {
            that.name; //get the proper name

            console.log(message + that.name);
        })
    }

}

deliveryBoy.receive();<|endoftext|>


<commit_before>'use strict';

var async = require('async');

module.exports = {
  loadPriority:  430,
  initialize: function(api, next){

    api.actionProcessor = function(connection, callback){
      if(!connection){
        throw new Error('data.connection is required');
      }

      this.connection      = connection;
      this.action          = null;
      this.toProcess       = true;
      this.toRender        = true;
      this.messageCount    = connection.messageCount;
      this.params          = connection.params;
      this.callback        = callback;
      this.missingParams   = [];
      this.validatorErrors = [];
      this.actionStartTime = null;
      this.actionTemplate  = null;
      this.working         = false;
      this.response        = {};
      this.duration        = null;
      this.actionStatus    = null;
    };

    api.actionProcessor.prototype.incrementTotalActions = function(count){
      var self = this;
      if(!count){ count = 1; }
      self.connection.totalActions = self.connection.totalActions + count;
    };

    api.actionProcessor.prototype.incrementPendingActions = function(count){
      var self = this;
      if(!count){ count = 1; }
      self.connection.pendingActions = self.connection.pendingActions + count;
    };

    api.actionProcessor.prototype.getPendingActionCount = function(){
      var self = this;
      return self.connection.pendingActions;
    };

    api.actionProcessor.prototype.completeAction = function(status){
      var self = this;
      var error = null;
      self.actionStatus = String(status);

      if(status instanceof Error){
        error = status;
      }else if(status === 'server_shutting_down'){
        error = api.config.errors.serverShuttingDown(self);
      }else if(status === 'too_many_requests'){
        error = api.config.errors.tooManyPendingActions(self);
      }else if(status === 'unknown_action'){
        error = api.config.errors.unknownAction(self);
      }else if(status === 'unsupported_server_type'){
        error = api.config.errors.unsupportedServerType(self);
      }else if(status === 'missing_params'){
        error = api.config.errors.missingParams(self, self.missingParams);
      }else if(status === 'validator_errors'){
        error = api.config.errors.invalidParams(self, self.validatorErrors);
      }else if(status){
        error = status;
      }

      if(error && typeof error === 'string'){
        error = new Error(error);
      }
      if(error && !self.response.error){
        self.response.error = error;
      }

      self.incrementPendingActions(-1);
      self.duration = new Date().getTime() - self.actionStartTime;

      process.nextTick(function(){
        if(typeof self.callback === 'function'){
          self.callback(self);
        }
      });

      self.working = false;
      self.logAction(error);
    };

    api.actionProcessor.prototype.logAction = function(error){
      var self = this;

      // logging
      var logLevel = 'info';
      if(self.actionTemplate && self.actionTemplate.logLevel){
        logLevel = self.actionTemplate.logLevel;
      }

      var filteredParams = {};
      for(var i in self.params){
        if(api.config.general.filteredParams && api.config.general.filteredParams.indexOf(i) >= 0){
          filteredParams[i] = '[FILTERED]';
        }else if(typeof self.params[i] === 'string'){
          filteredParams[i] = self.params[i].substring(0, api.config.logger.maxLogStringLength);
        }else{
          filteredParams[i] = self.params[i];
        }
      }

      var logLine = {
        to: self.connection.remoteIP,
        action: self.action,
        params: JSON.stringify(filteredParams),
        duration: self.duration,
      };

      if(error){
        if(error instanceof Error){
          logLine.error = String(error);
        }else{
          try{
            logLine.error = JSON.stringify(error);
          }catch(e){
            logLine.error = String(error);
          }
        }
      }

      api.log(['[ action @ %s ]', self.connection.type], logLevel, logLine);
    };

    api.actionProcessor.prototype.preProcessAction = function(callback){
      var self = this;
      var processors     = [];
      var processorNames = api.actions.globalMiddleware.slice(0);

      if(self.actionTemplate.middleware){
        self.actionTemplate.middleware.forEach(function(m){ processorNames.push(m); });
      }

      processorNames.forEach(function(name){
        if(typeof api.actions.middleware[name].preProcessor === 'function'){
          processors.push(function(next){ api.actions.middleware[name].preProcessor(self, next); });
        }
      });

      async.series(processors, callback);
    };

    api.actionProcessor.prototype.postProcessAction = function(callback){
      var self = this;
      var processors     = [];
      var processorNames = api.actions.globalMiddleware.slice(0);

      if(self.actionTemplate.middleware){
        self.actionTemplate.middleware.forEach(function(m){ processorNames.push(m); });
      }

      processorNames.forEach(function(name){
        if(typeof api.actions.middleware[name].postProcessor === 'function'){
          processors.push(function(next){ api.actions.middleware[name].postProcessor(self, next); });
        }
      });

      async.series(processors, callback);
    };

    api.actionProcessor.prototype.reduceParams = function(){
      var self = this;
      var inputNames = [];
      if(self.actionTemplate.inputs){
        inputNames = Object.keys(self.actionTemplate.inputs);
      }

      if(api.config.general.disableParamScrubbing !== true){
        for(var p in self.params){
          if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
            delete self.params[p];
          }
        }
      }
    };

    api.actionProcessor.prototype.validateParams = function(){
      var self = this;

      for(var key in self.actionTemplate.inputs){
        var props = self.actionTemplate.inputs[key];

        // default
        if(self.params[key] === undefined && props['default'] !== undefined){
          if(typeof props['default'] === 'function'){
            self.params[key] = props['default'].call(api, self.params[key], self);
          }else{
            self.params[key] = props['default'];
          }
        }

        // formatter
        if(self.params[key] !== undefined && props.formatter !== undefined){
          if(!Array.isArray(props.formatter)){ props.formatter = [props.formatter]; }

          props.formatter.forEach(function(formatter){
            if(typeof formatter === 'function'){
              self.params[key] = formatter.call(api, self.params[key], self);
            }else{
              var method = api.utils.stringToHash(formatter);
              self.params[key] = method.call(api, self.params[key], self);
            }
          });
        }

        // validator
        if(self.params[key] !== undefined && props.validator !== undefined){
          if(!Array.isArray(props.validator)){ props.validator = [props.validator]; }

          props.validator.forEach(function(validator){
            var validatorResponse;
            if(typeof validator === 'function'){
              validatorResponse = validator.call(api, self.params[key], self);
            }else{
              var method = api.utils.stringToHash(validator);
              validatorResponse = method.call(api, self.params[key], self);
            }
            if(validatorResponse !== true){ self.validatorErrors.push(validatorResponse); }
          });
        }

        // required
        if(props.required === true){
          if(api.config.general.missingParamChecks.indexOf(self.params[key]) >= 0){
            self.missingParams.push(key);
          }
        }
      }
    };

    api.actionProcessor.prototype.processAction = function(){
      var self = this;
      self.actionStartTime = new Date().getTime();
      self.working = true;
      self.incrementTotalActions();
      self.incrementPendingActions();
      self.action = self.params.action;

      if(api.actions.versions[self.action]){
        if(!self.params.apiVersion){
          self.params.apiVersion = api.actions.versions[self.action][api.actions.versions[self.action].length - 1];
        }
        self.actionTemplate = api.actions.actions[self.action][self.params.apiVersion];
      }

      if(api.running !== true){
        self.completeAction('server_shutting_down');
      }else if(self.getPendingActionCount(self.connection) > api.config.general.simultaneousActions){
        self.completeAction('too_many_requests');
      }else if(!self.action || !self.actionTemplate){
        self.completeAction('unknown_action');
      }else if(self.actionTemplate.blockedConnectionTypes && self.actionTemplate.blockedConnectionTypes.indexOf(self.connection.type) >= 0){
        self.completeAction('unsupported_server_type');
      }else{
        self.runAction();
      }
    };

    api.actionProcessor.prototype.runAction = function(){
      var self = this;

      self.preProcessAction(function(error){
        self.reduceParams();
        self.validateParams();

        if(error){
          self.completeAction(error);
        }else if(self.missingParams.length > 0){
          self.completeAction('missing_params');
        }else if(self.validatorErrors.length > 0){
          self.completeAction('validator_errors');
        }else if(self.toProcess === true && !error){
          self.actionTemplate.run(api, self, function(error){
            if(error){
              self.completeAction(error);
            }else{
              self.postProcessAction(function(error){
                self.completeAction(error);
              });
            }
          });
        }else{
          self.completeAction();
        }
      });
    };

    next();
  }
};
<commit_msg>better support for named methods<commit_after>'use strict';

var async = require('async');

module.exports = {
  loadPriority:  430,
  initialize: function(api, next){

    var prepareStringMethod = function(method){
      var cmdParts = method.split('.');
      var cmd = cmdParts.shift();
      if(cmd !== 'api'){ throw new Error('cannot operate on a method outside of the api object'); }
      return api.utils.stringToHash(cmdParts.join('.'));
    };

    api.actionProcessor = function(connection, callback){
      if(!connection){
        throw new Error('data.connection is required');
      }

      this.connection      = connection;
      this.action          = null;
      this.toProcess       = true;
      this.toRender        = true;
      this.messageCount    = connection.messageCount;
      this.params          = connection.params;
      this.callback        = callback;
      this.missingParams   = [];
      this.validatorErrors = [];
      this.actionStartTime = null;
      this.actionTemplate  = null;
      this.working         = false;
      this.response        = {};
      this.duration        = null;
      this.actionStatus    = null;
    };

    api.actionProcessor.prototype.incrementTotalActions = function(count){
      var self = this;
      if(!count){ count = 1; }
      self.connection.totalActions = self.connection.totalActions + count;
    };

    api.actionProcessor.prototype.incrementPendingActions = function(count){
      var self = this;
      if(!count){ count = 1; }
      self.connection.pendingActions = self.connection.pendingActions + count;
    };

    api.actionProcessor.prototype.getPendingActionCount = function(){
      var self = this;
      return self.connection.pendingActions;
    };

    api.actionProcessor.prototype.completeAction = function(status){
      var self = this;
      var error = null;
      self.actionStatus = String(status);

      if(status instanceof Error){
        error = status;
      }else if(status === 'server_shutting_down'){
        error = api.config.errors.serverShuttingDown(self);
      }else if(status === 'too_many_requests'){
        error = api.config.errors.tooManyPendingActions(self);
      }else if(status === 'unknown_action'){
        error = api.config.errors.unknownAction(self);
      }else if(status === 'unsupported_server_type'){
        error = api.config.errors.unsupportedServerType(self);
      }else if(status === 'missing_params'){
        error = api.config.errors.missingParams(self, self.missingParams);
      }else if(status === 'validator_errors'){
        error = api.config.errors.invalidParams(self, self.validatorErrors);
      }else if(status){
        error = status;
      }

      if(error && typeof error === 'string'){
        error = new Error(error);
      }
      if(error && !self.response.error){
        self.response.error = error;
      }

      self.incrementPendingActions(-1);
      self.duration = new Date().getTime() - self.actionStartTime;

      process.nextTick(function(){
        if(typeof self.callback === 'function'){
          self.callback(self);
        }
      });

      self.working = false;
      self.logAction(error);
    };

    api.actionProcessor.prototype.logAction = function(error){
      var self = this;

      // logging
      var logLevel = 'info';
      if(self.actionTemplate && self.actionTemplate.logLevel){
        logLevel = self.actionTemplate.logLevel;
      }

      var filteredParams = {};
      for(var i in self.params){
        if(api.config.general.filteredParams && api.config.general.filteredParams.indexOf(i) >= 0){
          filteredParams[i] = '[FILTERED]';
        }else if(typeof self.params[i] === 'string'){
          filteredParams[i] = self.params[i].substring(0, api.config.logger.maxLogStringLength);
        }else{
          filteredParams[i] = self.params[i];
        }
      }

      var logLine = {
        to: self.connection.remoteIP,
        action: self.action,
        params: JSON.stringify(filteredParams),
        duration: self.duration,
      };

      if(error){
        if(error instanceof Error){
          logLine.error = String(error);
        }else{
          try{
            logLine.error = JSON.stringify(error);
          }catch(e){
            logLine.error = String(error);
          }
        }
      }

      api.log(['[ action @ %s ]', self.connection.type], logLevel, logLine);
    };

    api.actionProcessor.prototype.preProcessAction = function(callback){
      var self = this;
      var processors     = [];
      var processorNames = api.actions.globalMiddleware.slice(0);

      if(self.actionTemplate.middleware){
        self.actionTemplate.middleware.forEach(function(m){ processorNames.push(m); });
      }

      processorNames.forEach(function(name){
        if(typeof api.actions.middleware[name].preProcessor === 'function'){
          processors.push(function(next){ api.actions.middleware[name].preProcessor(self, next); });
        }
      });

      async.series(processors, callback);
    };

    api.actionProcessor.prototype.postProcessAction = function(callback){
      var self = this;
      var processors     = [];
      var processorNames = api.actions.globalMiddleware.slice(0);

      if(self.actionTemplate.middleware){
        self.actionTemplate.middleware.forEach(function(m){ processorNames.push(m); });
      }

      processorNames.forEach(function(name){
        if(typeof api.actions.middleware[name].postProcessor === 'function'){
          processors.push(function(next){ api.actions.middleware[name].postProcessor(self, next); });
        }
      });

      async.series(processors, callback);
    };

    api.actionProcessor.prototype.reduceParams = function(){
      var self = this;
      var inputNames = [];
      if(self.actionTemplate.inputs){
        inputNames = Object.keys(self.actionTemplate.inputs);
      }

      if(api.config.general.disableParamScrubbing !== true){
        for(var p in self.params){
          if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
            delete self.params[p];
          }
        }
      }
    };

    api.actionProcessor.prototype.validateParams = function(){
      var self = this;

      for(var key in self.actionTemplate.inputs){
        var props = self.actionTemplate.inputs[key];

        // default
        if(self.params[key] === undefined && props['default'] !== undefined){
          if(typeof props['default'] === 'function'){
            self.params[key] = props['default'].call(api, self.params[key], self);
          }else{
            self.params[key] = props['default'];
          }
        }

        // formatter
        if(self.params[key] !== undefined && props.formatter !== undefined){
          if(!Array.isArray(props.formatter)){ props.formatter = [props.formatter]; }

          props.formatter.forEach(function(formatter){
            if(typeof formatter === 'function'){
              self.params[key] = formatter.call(api, self.params[key], self);
            }else{
              var method = prepareStringMethod(formatter);
              self.params[key] = method.call(api, self.params[key], self);
            }
          });
        }

        // validator
        if(self.params[key] !== undefined && props.validator !== undefined){
          if(!Array.isArray(props.validator)){ props.validator = [props.validator]; }

          props.validator.forEach(function(validator){
            var validatorResponse;
            if(typeof validator === 'function'){
              validatorResponse = validator.call(api, self.params[key], self);
            }else{
              var method = prepareStringMethod(validator);
              validatorResponse = method.call(api, self.params[key], self);
            }
            if(validatorResponse !== true){ self.validatorErrors.push(validatorResponse); }
          });
        }

        // required
        if(props.required === true){
          if(api.config.general.missingParamChecks.indexOf(self.params[key]) >= 0){
            self.missingParams.push(key);
          }
        }
      }
    };

    api.actionProcessor.prototype.processAction = function(){
      var self = this;
      self.actionStartTime = new Date().getTime();
      self.working = true;
      self.incrementTotalActions();
      self.incrementPendingActions();
      self.action = self.params.action;

      if(api.actions.versions[self.action]){
        if(!self.params.apiVersion){
          self.params.apiVersion = api.actions.versions[self.action][api.actions.versions[self.action].length - 1];
        }
        self.actionTemplate = api.actions.actions[self.action][self.params.apiVersion];
      }

      if(api.running !== true){
        self.completeAction('server_shutting_down');
      }else if(self.getPendingActionCount(self.connection) > api.config.general.simultaneousActions){
        self.completeAction('too_many_requests');
      }else if(!self.action || !self.actionTemplate){
        self.completeAction('unknown_action');
      }else if(self.actionTemplate.blockedConnectionTypes && self.actionTemplate.blockedConnectionTypes.indexOf(self.connection.type) >= 0){
        self.completeAction('unsupported_server_type');
      }else{
        self.runAction();
      }
    };

    api.actionProcessor.prototype.runAction = function(){
      var self = this;

      self.preProcessAction(function(error){
        self.reduceParams();
        self.validateParams();

        if(error){
          self.completeAction(error);
        }else if(self.missingParams.length > 0){
          self.completeAction('missing_params');
        }else if(self.validatorErrors.length > 0){
          self.completeAction('validator_errors');
        }else if(self.toProcess === true && !error){
          self.actionTemplate.run(api, self, function(error){
            if(error){
              self.completeAction(error);
            }else{
              self.postProcessAction(function(error){
                self.completeAction(error);
              });
            }
          });
        }else{
          self.completeAction();
        }
      });
    };

    next();
  }
};
<|endoftext|>


<commit_before><commit_msg>Fix BuildableModel.clear()<commit_after><|endoftext|>


<commit_before>import React from 'react'
import {translate, Trans} from 'react-i18next'
import PropTypes from 'prop-types'

import PlusIcon from 'react-icons/lib/fa/plus-circle'
import MinusIcon from 'react-icons/lib/fa/minus-circle'

import licenses from '../../../lib/licenses'
import {isDistributable} from '../../../lib/distribution'

import Success from '../../success'
import Info from '../../info'
import Warning from '../../warning'

import LicenseCheck from './license-check'
import ProducerCheck from './producer-check'
import ResourcesCheck from './resources-check'

class Datagouv extends React.Component {
  static propTypes = {
    license: PropTypes.string,
    organizations: PropTypes.array.isRequired,
    resources: PropTypes.array.isRequired,

    publication: PropTypes.shape({
      remoteUrl: PropTypes.string.isRequired
    }),

    t: PropTypes.func.isRequired
  }

  static defaultProps = {
    license: null,
    publication: null
  }

  state = {
    expanded: false
  }

  toggleDetails = () => {
    this.setState(state => ({
      expanded: !state.expanded
    }))
  }

  getPublishableProperties = () => {
    const {license, organizations, resources} = this.props

    return {
      hasLicense: Object.prototype.hasOwnProperty.call(licenses, license),
      hasOrganizations: organizations && organizations.length > 0,
      isDistributable: isDistributable(resources)
    }
  }

  render() {
    const {publication, license, organizations, resources, t} = this.props
    const {expanded} = this.state

    const {hasLicense, hasOrganizations, isDistributable} = this.getPublishableProperties()

    if (hasLicense && hasOrganizations && isDistributable) {
      if (publication) {
        return (
          <Success>
            <Trans i18nKey='datagouv.published'>
              This dataset is published on data.gouv.fr.
            </Trans>
          </Success>
        )
      }

      return (
        <Info>{t('datagouv.producerActionNeeded')}</Info>
      )
    }

    return (

        <Warning>
          {t('datagouv.unpublishable')}
        </Warning>

          {expanded && (

              <LicenseCheck isValid={hasLicense} license={license} />
              <ProducerCheck isValid={hasOrganizations} organizations={organizations} />
              <ResourcesCheck isValid={isDistributable} resources={resources} />

          )}

            {expanded ? (

                <MinusIcon style={{verticalAlign: -2}} /> {t('common:displayLess')}

            ) : (

                <PlusIcon style={{verticalAlign: -2}} /> {t('datagouv.showDetails')}

            )}

    )
  }
}

export default translate('dataset')(Datagouv)
<commit_msg>Prioritize already pulished datasets in dataset<commit_after>import React from 'react'
import {translate, Trans} from 'react-i18next'
import PropTypes from 'prop-types'

import PlusIcon from 'react-icons/lib/fa/plus-circle'
import MinusIcon from 'react-icons/lib/fa/minus-circle'

import licenses from '../../../lib/licenses'
import {isDistributable} from '../../../lib/distribution'

import Success from '../../success'
import Info from '../../info'
import Warning from '../../warning'

import LicenseCheck from './license-check'
import ProducerCheck from './producer-check'
import ResourcesCheck from './resources-check'

class Datagouv extends React.Component {
  static propTypes = {
    license: PropTypes.string,
    organizations: PropTypes.array.isRequired,
    resources: PropTypes.array.isRequired,

    publication: PropTypes.shape({
      remoteUrl: PropTypes.string.isRequired
    }),

    t: PropTypes.func.isRequired
  }

  static defaultProps = {
    license: null,
    publication: null
  }

  state = {
    expanded: false
  }

  toggleDetails = () => {
    this.setState(state => ({
      expanded: !state.expanded
    }))
  }

  getPublishableProperties = () => {
    const {license, organizations, resources} = this.props

    return {
      hasLicense: Object.prototype.hasOwnProperty.call(licenses, license),
      hasOrganizations: organizations && organizations.length > 0,
      isDistributable: isDistributable(resources)
    }
  }

  render() {
    const {publication, license, organizations, resources, t} = this.props
    const {expanded} = this.state
    const {hasLicense, hasOrganizations, isDistributable} = this.getPublishableProperties()

    if (publication) {
      return (
        <Success>
          <Trans i18nKey='datagouv.published'>
            This dataset is published on data.gouv.fr.
          </Trans>
        </Success>
      )
    }

    if (hasLicense && hasOrganizations && isDistributable) {
      return (
        <Info>{t('datagouv.producerActionNeeded')}</Info>
      )
    }

    return (

        <Warning>
          {t('datagouv.unpublishable')}
        </Warning>

          {expanded && (

              <LicenseCheck isValid={hasLicense} license={license} />
              <ProducerCheck isValid={hasOrganizations} organizations={organizations} />
              <ResourcesCheck isValid={isDistributable} resources={resources} />

          )}

            {expanded ? (

                <MinusIcon style={{verticalAlign: -2}} /> {t('common:displayLess')}

            ) : (

                <PlusIcon style={{verticalAlign: -2}} /> {t('datagouv.showDetails')}

            )}

    )
  }
}

export default translate('dataset')(Datagouv)
<|endoftext|>


<commit_before>'use strict';

// -----------------------------------------------------------------------------
// Dependencies
// -----------------------------------------------------------------------------

var fs = require('fs');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var packageInfo = require('./package.json');
var sassdoc = require('sassdoc');
var path = require('path');
var gh = require('gh-pages');
var yaml = require('js-yaml');

// -----------------------------------------------------------------------------
// Dist
// -----------------------------------------------------------------------------

gulp.task('build', function () {
  return gulp
    .src([
      'src/_config.scss',
      'src/helpers/*.scss',
      'src/plugins/*.scss',
      'src/_media.scss'
    ])
    .pipe(plugins.concat('_include-media.scss'))
    .pipe(plugins.header(fs.readFileSync('./banner.txt', 'utf-8')))
    .pipe(plugins.replace(/@version@/, packageInfo.version))
    .pipe(gulp.dest('./dist'));
});

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

gulp.task('test:libsass', function () {
  return gulp
    .src(['./tests/*.scss'])
    .pipe(plugins.sass());
});

gulp.task('test:rubysass', function () {
  return plugins
    .rubySass('./tests', { stopOnError: true })
    .on('error', function (err) {
      process.exit(1);
    });
});

gulp.task('test', ['build'], function () {
  gulp.start('test:libsass');
  gulp.start('test:rubysass');
});

// -----------------------------------------------------------------------------
// Sass API documentation
// -----------------------------------------------------------------------------

gulp.task('sassdoc', function () {
  var options = yaml.safeLoad(fs.readFileSync('.sassdocrc', 'utf-8'));
  options.dest = './sassdoc/documentation';
  options.verbose = true;

  return gulp
    .src('src/**/*.scss')
    .pipe(sassdoc(options))
    .resume();
});

// -----------------------------------------------------------------------------
// GH-pages task
// -----------------------------------------------------------------------------

gulp.task('gh-pages', ['build', 'sassdoc'], function () {
  gh.publish(path.join(__dirname, 'sassdoc'), {
    add: true,
    message: 'Automatic SassDoc update from Gulp',
    logger: function(message) {
      console.log(message);
    }
  }, function(err) {
    if (err) console.log(err);
  });
});

// -----------------------------------------------------------------------------
// Default task
// -----------------------------------------------------------------------------

gulp.task('default', ['build', 'test']);

// -----------------------------------------------------------------------------
// Deploy documentation task
// -----------------------------------------------------------------------------

gulp.task('deploy', ['gh-pages']);
<commit_msg>Fixed an issue with SassDoc not reading package.json correctly<commit_after>'use strict';

// -----------------------------------------------------------------------------
// Dependencies
// -----------------------------------------------------------------------------

var fs = require('fs');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var packageInfo = require('./package.json');
var sassdoc = require('sassdoc');
var path = require('path');
var gh = require('gh-pages');
var yaml = require('js-yaml');

// -----------------------------------------------------------------------------
// Dist
// -----------------------------------------------------------------------------

gulp.task('build', function () {
  return gulp
    .src([
      'src/_config.scss',
      'src/helpers/*.scss',
      'src/plugins/*.scss',
      'src/_media.scss'
    ])
    .pipe(plugins.concat('_include-media.scss'))
    .pipe(plugins.header(fs.readFileSync('./banner.txt', 'utf-8')))
    .pipe(plugins.replace(/@version@/, packageInfo.version))
    .pipe(gulp.dest('./dist'));
});

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

gulp.task('test:libsass', function () {
  return gulp
    .src(['./tests/*.scss'])
    .pipe(plugins.sass());
});

gulp.task('test:rubysass', function () {
  return plugins
    .rubySass('./tests', { stopOnError: true })
    .on('error', function (err) {
      process.exit(1);
    });
});

gulp.task('test', ['build'], function () {
  gulp.start('test:libsass');
  gulp.start('test:rubysass');
});

// -----------------------------------------------------------------------------
// Sass API documentation
// -----------------------------------------------------------------------------

gulp.task('sassdoc', function () {
  var options = yaml.safeLoad(fs.readFileSync('.sassdocrc', 'utf-8'));
  options.dest = './sassdoc/documentation';
  options.verbose = true;
  options.package = require('./package.json');

  return gulp
    .src('src/**/*.scss')
    .pipe(sassdoc(options))
    .resume();
});

// -----------------------------------------------------------------------------
// GH-pages task
// -----------------------------------------------------------------------------

gulp.task('gh-pages', ['build', 'sassdoc'], function () {
  gh.publish(path.join(__dirname, 'sassdoc'), {
    add: true,
    message: 'Automatic SassDoc update from Gulp',
    logger: function(message) {
      console.log(message);
    }
  }, function(err) {
    if (err) console.log(err);
  });
});

// -----------------------------------------------------------------------------
// Default task
// -----------------------------------------------------------------------------

gulp.task('default', ['build', 'test']);

// -----------------------------------------------------------------------------
// Deploy documentation task
// -----------------------------------------------------------------------------

gulp.task('deploy', ['gh-pages']);
<|endoftext|>


<commit_before>/**
 * @author Edouard Demotes-Mainard <https://github.com/EdouardDem>
 * @license http://opensource.org/licenses/BSD-2-Clause BSD 2-Clause License
 */

/**
 * Object djs for namespace
 */
window.djs = window.djs || {};

/**
 * This object manages window's resizing event.
 * It detects the end of the resizing events suite and trigger callbacks.
 * It also allows to manage callbacks order through the class djs.Callstack
 *
 * @see https://github.com/EdouardDem/djs-resize
 * @requires djs.CallStack <https://github.com/EdouardDem/djs-call-stack>
 */
djs.resize = {

	/* ========================================================================
	 * 	PROPERTIES
	 * ====================================================================== */
	/**
	 * Delay used to detect the end of the resize.
	 * For example, if we define delay = 100, then if a resize starts and no resize's event is recorded for 100ms,
	 * we will consider the resizing is done and run the callbacks.
	 * To disables this feature, delay should be set to 0.
	 *
	 * @var {Integer}
	 */
    delay: 0,

	/**
	 * CSS classes used to tag the body while processing
	 *
	 * @var {Object}
	 */
    classes: {
        resizing: 'resizing'
    },

	/**
	 * Names and order of the call stacks used by this object
	 *
	 * @var {Object}
	 */
    stacks: {
        core: 'core',
        main: 'main',
        last: 'last'
    },

	/**
	 * Namespace used to bind events
	 *
	 * @var {String}
	 */
	namespace: 'djs-resize',

	/**
	 * Flag used to determine if the object is initialized
	 *
	 * @var {Boolean}
	 */
	initialized: false,

	/**
	 * The jQuery window object
	 *
	 * @var {Object}
	 */
	$window: null,

	/**
	 * The jQuery body object
	 *
	 * @var {Object}
	 */
	$body: null,

	/**
	 * Object containing the instances of djs.Callstack
	 *
	 * @var {Object}
	 */
    _stacks: {},

	/**
	 * Shortcut to _stack.main
	 *
	 * @var {Object}
	 */
    stack: null,

	/**
	 * Object used to get inactivity delay
	 *
	 * @var {Object}
	 */
    timeout: null,

	/* ========================================================================
	 * 	INITIALIZATION
	 * ====================================================================== */
	/**
	 * Initialize the object
	 *
	 * @return {Object}
	 */
	init: function() {

		// Check if already initialized
		if (this.initialized) return this;

		// Objects
		this.$window = $(window);
		this.$body = $('body');

		// Initialize the call stacks
		$.each(this.stacks, function(i,e) {
            this._stacks[e] = new djs.CallStack();
        }.bind(this));

		// Short cut to the main stack
        this.stack = this._stacks.main;

		// Bind the resize event
        this.$window.bind('resize.'+this.namespace, function() {

			// Check if initialized
			if (this.initialized) {

                // If a delay is defined, we set a timeout to trigger call stacks
                if (this.delay>0) {

                    // Clear timeout of previous resize's event
                    clearTimeout(this.timeout);

                    // Set new timeout
                    this.timeout = setTimeout(function () {

						// Call the refresh
                        this.refresh();

                    }.bind(this), this.delay);

                }

				// If no delay, just call the refresh function
				else {
                    this.refresh();
                }

            }

		}.bind(this));

		// Set the flag to prevent another initialization
		this.initialized = true;

		// Return self
		return this;
	},

	/**
	 * Destroy the object (if initialized)
 	 *
	 * @return {Object}
	 */
    destroy: function() {

		// Check if already initialized
		if (!this.initialized) return this;

		// Unbind the events
		this.$window.unbind('resize.'+this.namespace);

		// Reset the stacks
        this.stack = null;
        this._stacks = {};

		// Unset the flag
		this.initialized = false;

		// Return self
 		return this;
   	},
	/**
	 * Re-initialize the object
 	 *
	 * @return {Object}
	 */
    reinit: function() {
		// Destroy and init
		return this.destroy().init();
   	},

	/* ========================================================================
	 * 	BINDING
	 * ====================================================================== */
	/**
	 * Add a callback to a stack. Default, to the main stack
	 *
     * @param {String} namespace
     * @param {Function} callback
     * @param {String} stackName (default : djs.resize.stacks.main)
	 * @return {Object}
	 */
	bind: function(namespace, callback, stackName) {

		// Default value for stackName
        if (stackName==null) stackName = this.stacks.main;

		// Push the callback to the stack
		this._stacks[stackName].add(namespace, callback);

		// Return self
		return this;
	},
	/**
	 * Remove a callback to a stack. Default, from the main stack
	 *
     * @param {String} namespace
     * @param {String} stackName (default : djs.resize.stacks.main)
	 * @return {Object}
	 */
    unbind: function(namespace, stackName) {

		// Default value for stackName
        if (stackName==null) stackName = this.stacks.main;

        //Delete callback from the stack
		this._stacks[stackName].delete(namespace);

		// Return self
 		return this;
    },

	/* ========================================================================
	 * 	METHODS
	 * ====================================================================== */

	/**
	 * Runs all the stacks.
	 * Subroutine of the resize event.
	 * Call this function to force refresh
 	 *
	 * @return {Object}
	 */
	refresh: function() {

        // Add flag to body (for CSS use)
        this.$body.addClass(this.classes.resizing);

        // Run all stacks
        $.each(this.stacks, function(i,e) {
            this._stacks[e].run();
        }.bind(this));

        // Remove flag from body
        this.$body.removeClass(this.classes.resizing);

		// Return self
        return this;
	}
};
<commit_msg>Tabs for distribution<commit_after>/**
 * @author Edouard Demotes-Mainard <https://github.com/EdouardDem>
 * @license http://opensource.org/licenses/BSD-2-Clause BSD 2-Clause License
 */

/**
 * Object djs for namespace
 */
window.djs = window.djs || {};

/**
 * This object manages window's resizing event.
 * It detects the end of the resizing events suite and trigger callbacks.
 * It also allows to manage callbacks order through the class djs.Callstack
 *
 * @see https://github.com/EdouardDem/djs-resize
 * @requires djs.CallStack <https://github.com/EdouardDem/djs-call-stack>
 */
djs.resize = {

	/* ========================================================================
	 * 	PROPERTIES
	 * ====================================================================== */
	/**
	 * Delay used to detect the end of the resize.
	 * For example, if we define delay = 100, then if a resize starts and no resize's event is recorded for 100ms,
	 * we will consider the resizing is done and run the callbacks.
	 * To disables this feature, delay should be set to 0.
	 *
	 * @var {Integer}
	 */
	delay: 0,

	/**
	 * CSS classes used to tag the body while processing
	 *
	 * @var {Object}
	 */
	classes: {
		resizing: 'resizing'
	},

	/**
	 * Names and order of the call stacks used by this object
	 *
	 * @var {Object}
	 */
	stacks: {
		core: 'core',
		main: 'main',
		last: 'last'
	},

	/**
	 * Namespace used to bind events
	 *
	 * @var {String}
	 */
	namespace: 'djs-resize',

	/**
	 * Flag used to determine if the object is initialized
	 *
	 * @var {Boolean}
	 */
	initialized: false,

	/**
	 * The jQuery window object
	 *
	 * @var {Object}
	 */
	$window: null,

	/**
	 * The jQuery body object
	 *
	 * @var {Object}
	 */
	$body: null,

	/**
	 * Object containing the instances of djs.Callstack
	 *
	 * @var {Object}
	 */
	_stacks: {},

	/**
	 * Shortcut to _stack.main
	 *
	 * @var {Object}
	 */
	stack: null,

	/**
	 * Object used to get inactivity delay
	 *
	 * @var {Object}
	 */
	timeout: null,

	/* ========================================================================
	 * 	INITIALIZATION
	 * ====================================================================== */
	/**
	 * Initialize the object
	 *
	 * @return {Object}
	 */
	init: function () {

		// Check if already initialized
		if (this.initialized) return this;

		// Objects
		this.$window = $(window);
		this.$body = $('body');

		// Initialize the call stacks
		$.each(this.stacks, function (i, e) {
			this._stacks[e] = new djs.CallStack();
		}.bind(this));

		// Short cut to the main stack
		this.stack = this._stacks.main;

		// Bind the resize event
		this.$window.bind('resize.' + this.namespace, function () {

			// Check if initialized
			if (this.initialized) {

				// If a delay is defined, we set a timeout to trigger call stacks
				if (this.delay > 0) {

					// Clear timeout of previous resize's event
					clearTimeout(this.timeout);

					// Set new timeout
					this.timeout = setTimeout(function () {

						// Call the refresh
						this.refresh();

					}.bind(this), this.delay);

				}

				// If no delay, just call the refresh function
				else {
					this.refresh();
				}

			}

		}.bind(this));

		// Set the flag to prevent another initialization
		this.initialized = true;

		// Return self
		return this;
	},

	/**
	 * Destroy the object (if initialized)
	 *
	 * @return {Object}
	 */
	destroy: function () {

		// Check if already initialized
		if (!this.initialized) return this;

		// Unbind the events
		this.$window.unbind('resize.' + this.namespace);

		// Reset the stacks
		this.stack = null;
		this._stacks = {};

		// Unset the flag
		this.initialized = false;

		// Return self
		return this;
	},
	/**
	 * Re-initialize the object
	 *
	 * @return {Object}
	 */
	reinit: function () {
		// Destroy and init
		return this.destroy().init();
	},

	/* ========================================================================
	 * 	BINDING
	 * ====================================================================== */
	/**
	 * Add a callback to a stack. Default, to the main stack
	 *
	 * @param {String} namespace
	 * @param {Function} callback
	 * @param {String} stackName (default : djs.resize.stacks.main)
	 * @return {Object}
	 */
	bind: function (namespace, callback, stackName) {

		// Default value for stackName
		if (stackName == null) stackName = this.stacks.main;

		// Push the callback to the stack
		this._stacks[stackName].add(namespace, callback);

		// Return self
		return this;
	},
	/**
	 * Remove a callback to a stack. Default, from the main stack
	 *
	 * @param {String} namespace
	 * @param {String} stackName (default : djs.resize.stacks.main)
	 * @return {Object}
	 */
	unbind: function (namespace, stackName) {

		// Default value for stackName
		if (stackName == null) stackName = this.stacks.main;

		//Delete callback from the stack
		this._stacks[stackName].delete(namespace);

		// Return self
		return this;
	},

	/* ========================================================================
	 * 	METHODS
	 * ====================================================================== */

	/**
	 * Runs all the stacks.
	 * Subroutine of the resize event.
	 * Call this function to force refresh
	 *
	 * @return {Object}
	 */
	refresh: function () {

		// Add flag to body (for CSS use)
		this.$body.addClass(this.classes.resizing);

		// Run all stacks
		$.each(this.stacks, function (i, e) {
			this._stacks[e].run();
		}.bind(this));

		// Remove flag from body
		this.$body.removeClass(this.classes.resizing);

		// Return self
		return this;
	}
};
<|endoftext|>


<commit_before>'use strict';

var lib = {
  Graph: {
    topologicalSort: require('./algorithms/graph/topological_sort'),
    dijkstra: require('./algorithms/graph/dijkstra'),
    SPFA: require('./algorithms/graph/SPFA'),
    bellmanFord: require('./algorithms/graph/bellman_ford'),
    eulerPath: require('./algorithms/graph/euler_path'),
    depthFirstSearch: require('./algorithms/graph/depth_first_search'),
    kruskal: require('./algorithms/graph/kruskal'),
    breadthFirstSearch: require('./algorithms/graph/breadth_first_search'),
    bfsShortestPath: require('./algorithms/graph/bfs_shortest_path'),
  },
  Math: {
    fibonacci: require('./algorithms/math/fibonacci'),
    fisherYates: require('./algorithms/math/fisher_yates'),
    gcd: require('./algorithms/math/gcd'),
    extendedEuclidean: require('./algorithms/math/extended_euclidean'),
    newtonSqrt: require('./algorithms/math/newton_sqrt'),
    reservoirSampling: require('./algorithms/math/reservoir_sampling'),
    fastPower: require('./algorithms/math/fast_power'),
    nextPermutation: require('./algorithms/math/next_permutation'),
    powerSet: require('./algorithms/math/power_set')
  },
  Search: {
    bfs: require('./algorithms/searching/bfs'),
    binarySearch: require('./algorithms/searching/binarysearch'),
    dfs: require('./algorithms/searching/dfs')
  },
  Sort: {
    bubbleSort: require('./algorithms/sorting/bubble_sort'),
    countingSort: require('./algorithms/sorting/counting_sort'),
    heapSort: require('./algorithms/sorting/heap_sort'),
    mergeSort: require('./algorithms/sorting/merge_sort'),
    quicksort: require('./algorithms/sorting/quicksort'),
    selectionSort: require('./algorithms/sorting/selection_sort'),
    radixSort: require('./algorithms/sorting/radix_sort'),
    insertionSort: require('./algorithms/sorting/insertion_sort')
  },
  String: {
    levenshtein: require('./algorithms/string/levenshtein'),
    rabinKarp: require('./algorithms/string/rabin_karp'),
    knuthMorrisPratt: require('./algorithms/string/knuth_morris_pratt'),
    huffman: require('./algorithms/string/huffman'),
    hamming: require('./algorithms/string/hamming'),
    longestCommonSubsequence: require(
      './algorithms/string/longest_common_subsequence')
  },
  DataStructure: {
    BST: require('./data_structures/bst'),
    Graph: require('./data_structures/graph'),
    HashTable: require('./data_structures/hash_table'),
    Heap: require('./data_structures/heap'),
    LinkedList: require('./data_structures/linked_list'),
    PriorityQueue: require('./data_structures/priority_queue'),
    Queue: require('./data_structures/queue'),
    Stack: require('./data_structures/stack'),
    Set: require('./data_structures/set'),
    DisjointSetForest: require('./data_structures/disjoint_set_forest')
  }
};

module.exports = lib;
<commit_msg>Include Prim's algorithm in main.js<commit_after>'use strict';

var lib = {
  Graph: {
    topologicalSort: require('./algorithms/graph/topological_sort'),
    dijkstra: require('./algorithms/graph/dijkstra'),
    SPFA: require('./algorithms/graph/SPFA'),
    bellmanFord: require('./algorithms/graph/bellman_ford'),
    eulerPath: require('./algorithms/graph/euler_path'),
    depthFirstSearch: require('./algorithms/graph/depth_first_search'),
    kruskal: require('./algorithms/graph/kruskal'),
    breadthFirstSearch: require('./algorithms/graph/breadth_first_search'),
    bfsShortestPath: require('./algorithms/graph/bfs_shortest_path'),
    prim: require('./algorithms/graph/prim'),
  },
  Math: {
    fibonacci: require('./algorithms/math/fibonacci'),
    fisherYates: require('./algorithms/math/fisher_yates'),
    gcd: require('./algorithms/math/gcd'),
    extendedEuclidean: require('./algorithms/math/extended_euclidean'),
    newtonSqrt: require('./algorithms/math/newton_sqrt'),
    reservoirSampling: require('./algorithms/math/reservoir_sampling'),
    fastPower: require('./algorithms/math/fast_power'),
    nextPermutation: require('./algorithms/math/next_permutation'),
    powerSet: require('./algorithms/math/power_set')
  },
  Search: {
    bfs: require('./algorithms/searching/bfs'),
    binarySearch: require('./algorithms/searching/binarysearch'),
    dfs: require('./algorithms/searching/dfs')
  },
  Sort: {
    bubbleSort: require('./algorithms/sorting/bubble_sort'),
    countingSort: require('./algorithms/sorting/counting_sort'),
    heapSort: require('./algorithms/sorting/heap_sort'),
    mergeSort: require('./algorithms/sorting/merge_sort'),
    quicksort: require('./algorithms/sorting/quicksort'),
    selectionSort: require('./algorithms/sorting/selection_sort'),
    radixSort: require('./algorithms/sorting/radix_sort'),
    insertionSort: require('./algorithms/sorting/insertion_sort')
  },
  String: {
    levenshtein: require('./algorithms/string/levenshtein'),
    rabinKarp: require('./algorithms/string/rabin_karp'),
    knuthMorrisPratt: require('./algorithms/string/knuth_morris_pratt'),
    huffman: require('./algorithms/string/huffman'),
    hamming: require('./algorithms/string/hamming'),
    longestCommonSubsequence: require(
      './algorithms/string/longest_common_subsequence')
  },
  DataStructure: {
    BST: require('./data_structures/bst'),
    Graph: require('./data_structures/graph'),
    HashTable: require('./data_structures/hash_table'),
    Heap: require('./data_structures/heap'),
    LinkedList: require('./data_structures/linked_list'),
    PriorityQueue: require('./data_structures/priority_queue'),
    Queue: require('./data_structures/queue'),
    Stack: require('./data_structures/stack'),
    Set: require('./data_structures/set'),
    DisjointSetForest: require('./data_structures/disjoint_set_forest')
  }
};

module.exports = lib;
<|endoftext|>


<commit_before>$(document).ready(function() {

  module("underscore.array.builders");

  test("cat", function() {
    // no args
    deepEqual(_.cat(), [], 'should return an empty array when given no args');

    // one arg
    deepEqual(_.cat([]), [], 'should concatenate one empty array');
    deepEqual(_.cat([1,2,3]), [1,2,3], 'should concatenate one homogenious array');
    var result = _.cat([1, "2", [3], {n: 4}]);
    deepEqual(result, [1, "2", [3], {n: 4}], 'should concatenate one heterogenious array');
    result = (function(){ return _.cat(arguments); })(1, 2, 3);
    deepEqual(result, [1, 2, 3], 'should concatenate the arguments object');

    // two args
    deepEqual(_.cat([1,2,3],[4,5,6]), [1,2,3,4,5,6], 'should concatenate two arrays');
    result = (function(){ return _.cat(arguments, [4,5,6]); })(1,2,3);
    deepEqual(result, [1,2,3,4,5,6], 'should concatenate an array and an arguments object');

    // > 2 args
    var a = [1,2,3];
    var b = [4,5,6];
    var c = [7,8,9];
    var d = [0,0,0];
    deepEqual(_.cat(a,b,c), [1,2,3,4,5,6,7,8,9], 'should concatenate three arrays');
    deepEqual(_.cat(a,b,c,d), [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays');
    result = (function(){ return _.cat(arguments,b,c,d); }).apply(null, a);
    deepEqual(result, [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays, including an arguments object');

    // heterogenious types
    deepEqual(_.cat([1],2), [1,2], 'should concatenate mixed types');
    deepEqual(_.cat([1],2,3), [1,2,3], 'should concatenate mixed types');
    deepEqual(_.cat(1,2,3), [1,2,3], 'should concatenate mixed types');
    result = (function(){ return _.cat(arguments, 4,5,6); })(1,2,3);
    deepEqual(result, [1,2,3,4,5,6], 'should concatenate mixed types, including an arguments object');
  });

  test("cons", function() {
    deepEqual(_.cons(0, []), [0], 'should insert the first arg into the array given as the second arg');
    deepEqual(_.cons(1, [2]), [1,2], 'should insert the first arg into the array given as the second arg');
    deepEqual(_.cons([0], [1,2,3]), [[0],1,2,3], 'should insert the first arg into the array given as the second arg');
    deepEqual(_.cons(1, 2), [1,2], 'should create a pair if the second is not an array');
    deepEqual(_.cons([1], 2), [[1],2], 'should create a pair if the second is not an array');
    result = (function(){ return _.cons(0, arguments); })(1,2,3);
    deepEqual(result, [0,1,2,3], 'should construct an array given an arguments object as the tail');

    var a = [1,2,3];
    var result = _.cons(0,a);

    deepEqual(a, [1,2,3], 'should not modify the original tail');
  });

  test("partition", function() {
    var a = _.range(4);
    var b = _.range(5);
    var c = _.range(7);

    deepEqual(_.partition(a, 2), [[0,1],[2,3]], 'should partition into the size given');
    deepEqual(_.partition(b, 2), [[0,1],[2,3]], 'should partition into the size given. Extras are dropped');

    var result = _.partition(a, 2);
    deepEqual(a, _.range(4), 'should not modify the original array');

    deepEqual(_.partition(c, 3, [7,8]), [[0,1,2],[3,4,5],[6,7,8]], 'should allow one to specify a padding array');
    deepEqual(_.partition(b, 3, 9), [[0,1,2],[3,4,9]], 'should allow one to specify a padding value');
  });

  test("partitionAll", function() {
    var a = _.range(4);
    var b = _.range(10);

    deepEqual(_.partitionAll(a, 2), [[0,1],[2,3]], 'should partition into the size given');
    deepEqual(_.partitionAll(b, 4), [[0,1,2,3],[4,5,6,7],[8,9]], 'should partition into the size given, with a small end');

    var result = _.partitionAll(a, 2);
    deepEqual(a, _.range(4), 'should not modify the original array');

    deepEqual(_.partitionAll(b, 2, 4), [[0,1],[4,5],[8,9]], 'should partition into the size given, with skips');
    deepEqual(_.partitionAll(b, 3, 4), [[0,1,2],[4,5,6],[8,9]], 'should partition into the size given, with skips and a small end');
  });

  test("mapcat", function() {
    var a = [1,2,3];
    var commaize = function(e) { return _.cons(e, [","]); };

    deepEqual(_.mapcat(a, commaize), [1, ",", 2, ",", 3, ","], 'should return an array with all intermediate mapped arrays concatenated');
  });

  test("interpose", function() {
    var a = [1,2,3];
    var b = [1,2];
    var c = [1];

    deepEqual(_.interpose(a, 0), [1,0,2,0,3], 'should put the 2nd arg between the elements of the array given');
    deepEqual(_.interpose(b, 0), [1,0,2], 'should put the 2nd arg between the elements of the array given');
    deepEqual(_.interpose(c, 0), [1], 'should return the array given if nothing to interpose');
    deepEqual(_.interpose([], 0), [], 'should return an empty array given an empty array');

    var result = _.interpose(b,0);
    deepEqual(b, [1,2], 'should not modify the original array');
  });

  test("weave", function() {
    var a = [1,2,3];
    var b = [1,2];
    var c = ['a', 'b', 'c'];
    var d = [1, [2]];

    // zero
    deepEqual(_.weave(), [], 'should weave zero arrays');

    // one
    deepEqual(_.weave([]), [], 'should weave one array');
    deepEqual(_.weave([1,[2]]), [1,[2]], 'should weave one array');

    // two
    deepEqual(_.weave(a,b), [1,1,2,2,3], 'should weave two arrays');
    deepEqual(_.weave(a,a), [1,1,2,2,3,3], 'should weave two arrays');
    deepEqual(_.weave(c,a), ['a',1,'b',2,'c',3], 'should weave two arrays');
    deepEqual(_.weave(a,d), [1,1,2,[2],3], 'should weave two arrays');

    // > 2
    deepEqual(_.weave(a,b,c), [1,1,'a',2,2,'b',3,'c'], 'should weave more than two arrays');
    deepEqual(_.weave(a,b,c,d), [1,1,'a',1,2,2,'b',[2],3,'c'], 'should weave more than two arrays');
  });

  test("repeat", function() {
    deepEqual(_.repeat(3,1), [1,1,1], 'should build an array of size n with the specified element in each slot');
    deepEqual(_.repeat(0), [], 'should return an empty array if given zero and no repeat arg');
    deepEqual(_.repeat(0,9999), [], 'should return an empty array if given zero and some repeat arg');
  });

  test("cycle", function() {
    var a = [1,2,3];

    deepEqual(_.cycle(3, a), [1,2,3,1,2,3,1,2,3], 'should build an array with the specified array contents repeated n times');
    deepEqual(_.cycle(0, a), [], 'should return an empty array if told to repeat zero times');
    deepEqual(_.cycle(-1000, a), [], 'should return an empty array if told to repeat negative times');
  });

  test("splitAt", function() {
    var a = [1,2,3,4,5];

    deepEqual(_.splitAt(a, 2), [[1,2],[3,4,5]], 'should bifurcate an array at a given index');
    deepEqual(_.splitAt(a, 0), [[], [1,2,3,4,5]], 'should bifurcate an array at a given index');
    deepEqual(_.splitAt(a, 5), [[1,2,3,4,5],[]], 'should bifurcate an array at a given index');
    deepEqual(_.splitAt([], 5), [[],[]], 'should bifurcate an array at a given index');
  });

});
<commit_msg>Initial tests for _.iterateUntil in place<commit_after>$(document).ready(function() {

  module("underscore.array.builders");

  test("cat", function() {
    // no args
    deepEqual(_.cat(), [], 'should return an empty array when given no args');

    // one arg
    deepEqual(_.cat([]), [], 'should concatenate one empty array');
    deepEqual(_.cat([1,2,3]), [1,2,3], 'should concatenate one homogenious array');
    var result = _.cat([1, "2", [3], {n: 4}]);
    deepEqual(result, [1, "2", [3], {n: 4}], 'should concatenate one heterogenious array');
    result = (function(){ return _.cat(arguments); })(1, 2, 3);
    deepEqual(result, [1, 2, 3], 'should concatenate the arguments object');

    // two args
    deepEqual(_.cat([1,2,3],[4,5,6]), [1,2,3,4,5,6], 'should concatenate two arrays');
    result = (function(){ return _.cat(arguments, [4,5,6]); })(1,2,3);
    deepEqual(result, [1,2,3,4,5,6], 'should concatenate an array and an arguments object');

    // > 2 args
    var a = [1,2,3];
    var b = [4,5,6];
    var c = [7,8,9];
    var d = [0,0,0];
    deepEqual(_.cat(a,b,c), [1,2,3,4,5,6,7,8,9], 'should concatenate three arrays');
    deepEqual(_.cat(a,b,c,d), [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays');
    result = (function(){ return _.cat(arguments,b,c,d); }).apply(null, a);
    deepEqual(result, [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays, including an arguments object');

    // heterogenious types
    deepEqual(_.cat([1],2), [1,2], 'should concatenate mixed types');
    deepEqual(_.cat([1],2,3), [1,2,3], 'should concatenate mixed types');
    deepEqual(_.cat(1,2,3), [1,2,3], 'should concatenate mixed types');
    result = (function(){ return _.cat(arguments, 4,5,6); })(1,2,3);
    deepEqual(result, [1,2,3,4,5,6], 'should concatenate mixed types, including an arguments object');
  });

  test("cons", function() {
    deepEqual(_.cons(0, []), [0], 'should insert the first arg into the array given as the second arg');
    deepEqual(_.cons(1, [2]), [1,2], 'should insert the first arg into the array given as the second arg');
    deepEqual(_.cons([0], [1,2,3]), [[0],1,2,3], 'should insert the first arg into the array given as the second arg');
    deepEqual(_.cons(1, 2), [1,2], 'should create a pair if the second is not an array');
    deepEqual(_.cons([1], 2), [[1],2], 'should create a pair if the second is not an array');
    result = (function(){ return _.cons(0, arguments); })(1,2,3);
    deepEqual(result, [0,1,2,3], 'should construct an array given an arguments object as the tail');

    var a = [1,2,3];
    var result = _.cons(0,a);

    deepEqual(a, [1,2,3], 'should not modify the original tail');
  });

  test("partition", function() {
    var a = _.range(4);
    var b = _.range(5);
    var c = _.range(7);

    deepEqual(_.partition(a, 2), [[0,1],[2,3]], 'should partition into the size given');
    deepEqual(_.partition(b, 2), [[0,1],[2,3]], 'should partition into the size given. Extras are dropped');

    var result = _.partition(a, 2);
    deepEqual(a, _.range(4), 'should not modify the original array');

    deepEqual(_.partition(c, 3, [7,8]), [[0,1,2],[3,4,5],[6,7,8]], 'should allow one to specify a padding array');
    deepEqual(_.partition(b, 3, 9), [[0,1,2],[3,4,9]], 'should allow one to specify a padding value');
  });

  test("partitionAll", function() {
    var a = _.range(4);
    var b = _.range(10);

    deepEqual(_.partitionAll(a, 2), [[0,1],[2,3]], 'should partition into the size given');
    deepEqual(_.partitionAll(b, 4), [[0,1,2,3],[4,5,6,7],[8,9]], 'should partition into the size given, with a small end');

    var result = _.partitionAll(a, 2);
    deepEqual(a, _.range(4), 'should not modify the original array');

    deepEqual(_.partitionAll(b, 2, 4), [[0,1],[4,5],[8,9]], 'should partition into the size given, with skips');
    deepEqual(_.partitionAll(b, 3, 4), [[0,1,2],[4,5,6],[8,9]], 'should partition into the size given, with skips and a small end');
  });

  test("mapcat", function() {
    var a = [1,2,3];
    var commaize = function(e) { return _.cons(e, [","]); };

    deepEqual(_.mapcat(a, commaize), [1, ",", 2, ",", 3, ","], 'should return an array with all intermediate mapped arrays concatenated');
  });

  test("interpose", function() {
    var a = [1,2,3];
    var b = [1,2];
    var c = [1];

    deepEqual(_.interpose(a, 0), [1,0,2,0,3], 'should put the 2nd arg between the elements of the array given');
    deepEqual(_.interpose(b, 0), [1,0,2], 'should put the 2nd arg between the elements of the array given');
    deepEqual(_.interpose(c, 0), [1], 'should return the array given if nothing to interpose');
    deepEqual(_.interpose([], 0), [], 'should return an empty array given an empty array');

    var result = _.interpose(b,0);
    deepEqual(b, [1,2], 'should not modify the original array');
  });

  test("weave", function() {
    var a = [1,2,3];
    var b = [1,2];
    var c = ['a', 'b', 'c'];
    var d = [1, [2]];

    // zero
    deepEqual(_.weave(), [], 'should weave zero arrays');

    // one
    deepEqual(_.weave([]), [], 'should weave one array');
    deepEqual(_.weave([1,[2]]), [1,[2]], 'should weave one array');

    // two
    deepEqual(_.weave(a,b), [1,1,2,2,3], 'should weave two arrays');
    deepEqual(_.weave(a,a), [1,1,2,2,3,3], 'should weave two arrays');
    deepEqual(_.weave(c,a), ['a',1,'b',2,'c',3], 'should weave two arrays');
    deepEqual(_.weave(a,d), [1,1,2,[2],3], 'should weave two arrays');

    // > 2
    deepEqual(_.weave(a,b,c), [1,1,'a',2,2,'b',3,'c'], 'should weave more than two arrays');
    deepEqual(_.weave(a,b,c,d), [1,1,'a',1,2,2,'b',[2],3,'c'], 'should weave more than two arrays');
  });

  test("repeat", function() {
    deepEqual(_.repeat(3,1), [1,1,1], 'should build an array of size n with the specified element in each slot');
    deepEqual(_.repeat(0), [], 'should return an empty array if given zero and no repeat arg');
    deepEqual(_.repeat(0,9999), [], 'should return an empty array if given zero and some repeat arg');
  });

  test("cycle", function() {
    var a = [1,2,3];

    deepEqual(_.cycle(3, a), [1,2,3,1,2,3,1,2,3], 'should build an array with the specified array contents repeated n times');
    deepEqual(_.cycle(0, a), [], 'should return an empty array if told to repeat zero times');
    deepEqual(_.cycle(-1000, a), [], 'should return an empty array if told to repeat negative times');
  });

  test("splitAt", function() {
    var a = [1,2,3,4,5];

    deepEqual(_.splitAt(a, 2), [[1,2],[3,4,5]], 'should bifurcate an array at a given index');
    deepEqual(_.splitAt(a, 0), [[], [1,2,3,4,5]], 'should bifurcate an array at a given index');
    deepEqual(_.splitAt(a, 5), [[1,2,3,4,5],[]], 'should bifurcate an array at a given index');
    deepEqual(_.splitAt([], 5), [[],[]], 'should bifurcate an array at a given index');
  });

  test("iterateUntil", function() {
    var dec = function(n) { return n - 1; };
    var isPos = function(n) { return n > 0; };

    deepEqual(_.iterateUntil(dec, isPos, 6), [5,4,3,2,1], 'should build an array, decrementing a number while positive.');
  });
});
<|endoftext|>