<commit_before>$(document).ready(function(){
  var arrayOfColumnNames = [
    "c0",
    "c1",
    "c2",
    "c3",
    "c4",
    "c5",
    "c6",
  ];

  for (var i=0; i<7; i++) {
    $("#board").append("

");

    // console.log($('#' + arrayOfColumnNames[i]));
    var thisColumn = $('#' + arrayOfColumnNames[i]);

    for (var j=5; j>=0; j--) {
      $('#' + arrayOfColumnNames[i]).append("

");
    }
  }

  var board = [
    [],
    [],
    [],
    [],
    [],
    [],
    []
  ];

  var turns = 0;

  $('.column-div').on('click', function(){
    //gives us column that was clicked on
    var column = parseInt($(this).attr('id').slice(-1));
    //alternates red and black pieces depending on turn count
    if (board[column].length < 6){
      turns += 1;
      var color = (turns % 2) ? "red" : "black";
      //adds piece to board
      board[column].push(color);
      var row = board[column].length - 1;
      $('#c' + column + '-' + row).css('background-color', color);

    }
    console.log(column);
    console.log(row);
    diagonalBaseLeft(column, row);
    diagonalBaseRight(column,row);
    console.log(board);
  });

  var diagonalBaseLeft = function(c, r){
    var column = c;
    var row = r;
    while ((column > 0) && (row > 0)){
      column -= 1;
      row -= 1;
    }
    console.log('column=' + column + 'row=' + row + 'base left');
    var arrayString = diagonalLeftArray(column, row);
    checkRed(arrayString);
    checkBlack(arrayString);

  }

   var diagonalLeftArray = function(c, r) {
    var column = c;
    var row = r;
    var valueArray = []
    do {
      valueArray.push(board[column][row]);
      column += 1;
      row += 1;
    }
    while((column < 7) && (row < 6));
    console.log(valueArray);
    return String(valueArray);
  };

  var diagonalBaseRight = function(c, r){
    var column = c;
    var row = r;
    while ((column < 6) && (row > 0)){
      column += 1;
      row -= 1;
    }
    console.log('column=' + column + 'row=' + row +'base right')
    var arrayString = diagonalRightArray(column, row);
    checkRed(arrayString);
    checkBlack(arrayString);
  };

  var diagonalRightArray = function(c, r) {
    var column = c;
    var row = r;
    var valueArray = []
    do {
      valueArray.push(board[column][row]);
      column -= 1;
      row += 1;
    }
    while((column > -1) && (row < 6));
    console.log(valueArray);
    return String(valueArray);
  };

  var checkRed = function(string) {
    if(string.match('red,red,red,red')){
      alert("RED WINNNNSSSSS!!!!!");
    }
  };

  var checkBlack = function(string) {
    if(string.match('black,black,black,black')){
      alert("BLACK WINNNNSSSSS!!!!!")
    }
  };
});

<commit_msg>Refactor code to generate board.<commit_after>$(document).ready(function(){

  for (var i=0; i<7; i++) {
    $("#board").append("

");

    var thisColumn = '#c' + i;

    for (var j=5; j>=0; j--) {
      $('#c' + i).append("

");
    }
  }

  var board = [
    [],
    [],
    [],
    [],
    [],
    [],
    []
  ];

  var turns = 0;

  $('.column-div').on('click', function(){
    //gives us column that was clicked on
    var column = parseInt($(this).attr('id').slice(-1));
    //alternates red and black pieces depending on turn count
    if (board[column].length < 6){
      turns += 1;
      var color = (turns % 2) ? "red" : "black";
      //adds piece to board
      board[column].push(color);
      var row = board[column].length - 1;
      $('#c' + column + '-' + row).css('background-color', color);

    }
    console.log(column);
    console.log(row);
    diagonalBaseLeft(column, row);
    diagonalBaseRight(column,row);
    console.log(board);
  });

  var diagonalBaseLeft = function(c, r){
    var column = c;
    var row = r;
    while ((column > 0) && (row > 0)){
      column -= 1;
      row -= 1;
    }
    console.log('column=' + column + 'row=' + row + 'base left');
    var arrayString = diagonalLeftArray(column, row);
    checkRed(arrayString);
    checkBlack(arrayString);

  }

   var diagonalLeftArray = function(c, r) {
    var column = c;
    var row = r;
    var valueArray = []
    do {
      valueArray.push(board[column][row]);
      column += 1;
      row += 1;
    }
    while((column < 7) && (row < 6));
    console.log(valueArray);
    return String(valueArray);
  };

  var diagonalBaseRight = function(c, r){
    var column = c;
    var row = r;
    while ((column < 6) && (row > 0)){
      column += 1;
      row -= 1;
    }
    console.log('column=' + column + 'row=' + row +'base right')
    var arrayString = diagonalRightArray(column, row);
    checkRed(arrayString);
    checkBlack(arrayString);
  };

  var diagonalRightArray = function(c, r) {
    var column = c;
    var row = r;
    var valueArray = []
    do {
      valueArray.push(board[column][row]);
      column -= 1;
      row += 1;
    }
    while((column > -1) && (row < 6));
    console.log(valueArray);
    return String(valueArray);
  };

  var checkRed = function(string) {
    if(string.match('red,red,red,red')){
      alert("RED WINNNNSSSSS!!!!!");
    }
  };

  var checkBlack = function(string) {
    if(string.match('black,black,black,black')){
      alert("BLACK WINNNNSSSSS!!!!!")
    }
  };
});

<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');

var connection = mongoose.createConnection(mongoURI);
autoIncrement.initialize(connection);

var ApplicationSchema = new Schema({
  name: String,
  description: String,
  updated_at: { type: Date, default: Date.now },
});
ApplicationSchema.plugin(autoIncrement.plugin, 'Application');

var BuildSchema = new Schema ({
  application : { type: Schema.ObjectId, ref: 'Application' },
  gitRepo: String,
  gitBranch: String,
  gitSHA: String,
  dockerDigest: String,
  created_at: { type: Date, default: Date.now },

});
BuildSchema.plugin(autoIncrement.plugin, 'Build');

var DeploymentSchema = new Schema({
  created_at: { type: Date, default: Date.now },
  build : { type: Schema.ObjectId, ref: 'Build' },
  targetEnvironment: String,
  qaResult: String,

});
DeploymentSchema.plugin(autoIncrement.plugin, 'Deployment');

module.exports.Application = connection.model('Application', ApplicationSchema);
module.exports.Build = connection.model('Build', BuildSchema);
module.exports.Deployment = connection.model('Deployment', DeploymentSchema);
// module.exports.Application = mongoose.model('Application', ApplicationSchema);
// module.exports.Build = mongoose.model('Build', BuildSchema);
// module.exports.Deployment = mongoose.model('Deployment', DeploymentSchema);
<commit_msg>update ref data type for autoIncrement plugin<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');

var connection = mongoose.createConnection(mongoURI);
autoIncrement.initialize(connection);

var ApplicationSchema = new Schema({
  name: String,
  description: String,
  updated_at: { type: Date, default: Date.now },
});
ApplicationSchema.plugin(autoIncrement.plugin, 'Application');

var BuildSchema = new Schema ({
  application : { type: Number, ref: 'Application' },
  gitRepo: String,
  gitBranch: String,
  gitSHA: String,
  dockerDigest: String,
  created_at: { type: Date, default: Date.now },

});
BuildSchema.plugin(autoIncrement.plugin, 'Build');

var DeploymentSchema = new Schema({
  created_at: { type: Date, default: Date.now },
  build : { type: Number, ref: 'Build' },
  targetEnvironment: String,
  qaResult: String,

});
DeploymentSchema.plugin(autoIncrement.plugin, 'Deployment');

module.exports.Application = connection.model('Application', ApplicationSchema);
module.exports.Build = connection.model('Build', BuildSchema);
module.exports.Deployment = connection.model('Deployment', DeploymentSchema);
// module.exports.Application = mongoose.model('Application', ApplicationSchema);
// module.exports.Build = mongoose.model('Build', BuildSchema);
// module.exports.Deployment = mongoose.model('Deployment', DeploymentSchema);
<|endoftext|>


<commit_before>'use strict';

var pluginPath = '../index';
var unused = require(pluginPath);
var gulp = require('gulp');
var gutil = require('gulp-util');
var fs = require('fs-extra');
var path = require('path');
var should = require('should');
var assert = require('assert');
var sassert = require('stream-assert');
require('mocha');

var fixtures = function(glob) { return path.join(__dirname, './.tmp', glob); }

function fileExists(filePath) {
  try {
    return fs.statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
}

describe('gulp-unused', function() {

  var tmpFolder = path.join(__dirname, '.tmp');

  beforeEach(function(done) {
    var folder = path.join(__dirname, './fixtures/');
    fs.copy(folder, tmpFolder, function(err) {
      done();
    });
  });

  // We'll delete it when we're done.
  afterEach(function(done) {
    fs.remove(tmpFolder, done);
  });

  it('1) should find and remove images, CSS and JavaScript not used in the project', function(done) {
    var options = {
      reference: 'img/',
      remove: true
    };

    var expected = path.join(__dirname, './.tmp/img/bg_foot.png');

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.length(1))
      .pipe(sassert.first(function() {
        fileExists(expected).should.equal(false);
      }))
      .pipe(sassert.end(done));

  });

  xit('2) should find images, CSS and JavaScript not used in the project', function() {
    assert.equal(1, 2);
  });

  it('3) should remove files after some days', function(done) {
    var options = {
      reference: 'img/',
      remove: true,
      days: 2
    };

    var expected = path.join(__dirname, './.tmp/img/foobar.txt');
    var expected2 = path.join(__dirname, './.tmp/img/bg_foot.png');
    var dateTemp = new Date();
    var dateToTest = dateTemp.setDate(dateTemp.getDate() - options.days);

    fs.writeFileSync(expected, 'foobar test');
    fs.utimesSync(expected, dateToTest, dateToTest);

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.first(function(d) {
        fileExists(expected).should.equal(false);
        fileExists(expected2).should.equal(true);
      }))
      .pipe(sassert.end(done));

  });

  it('4) create output report', function(done) {

    var options = {
      reference: 'img/',
      reportOutput: 'report.txt'
    };
    var expected = path.join(__dirname, './.tmp/report.txt');

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.first(function(d) {
        fs.readFileSync(expected).toString().should.equal('bg_foot.png');
        fileExists(expected).should.equal(true);
      }))
      .pipe(sassert.end(done));
  });

});
<commit_msg>test(test.js): activate test for report using stream-assert<commit_after>'use strict';

var pluginPath = '../index';
var unused = require(pluginPath);
var gulp = require('gulp');
var gutil = require('gulp-util');
var fs = require('fs-extra');
var path = require('path');
var should = require('should');
var assert = require('assert');
var sassert = require('stream-assert');
require('mocha');

var fixtures = function(glob) { return path.join(__dirname, './.tmp', glob); }

function fileExists(filePath) {
  try {
    return fs.statSync(filePath).isFile();
  } catch (err) {
    return false;
  }
}

describe('gulp-unused', function() {

  var tmpFolder = path.join(__dirname, '.tmp');

  beforeEach(function(done) {
    var folder = path.join(__dirname, './fixtures/');
    fs.copy(folder, tmpFolder, function(err) {
      done();
    });
  });

  // We'll delete it when we're done.
  afterEach(function(done) {
    fs.remove(tmpFolder, done);
  });

  it('1) should find and remove images, CSS and JavaScript not used in the project', function(done) {
    var options = {
      reference: 'img/',
      remove: true
    };

    var expected = path.join(__dirname, './.tmp/img/bg_foot.png');

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.length(1))
      .pipe(sassert.first(function() {
        fileExists(expected).should.equal(false);
      }))
      .pipe(sassert.end(done));

  });

  it('2) should find images, CSS and JavaScript not used in the project', function(done) {
    var options = {
      reference: 'img/'
    };

    var expected = path.join(__dirname, './.tmp/img/bg_foot.png');

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.length(1))
      .pipe(sassert.first(function() {
        fileExists(expected).should.equal(true);
      }))
      .pipe(sassert.end(done));
  });

  it('3) should remove files after some days', function(done) {
    var options = {
      reference: 'img/',
      remove: true,
      days: 2
    };

    var expected = path.join(__dirname, './.tmp/img/foobar.txt');
    var expected2 = path.join(__dirname, './.tmp/img/bg_foot.png');
    var dateTemp = new Date();
    var dateToTest = dateTemp.setDate(dateTemp.getDate() - options.days);

    fs.writeFileSync(expected, 'foobar test');
    fs.utimesSync(expected, dateToTest, dateToTest);

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.first(function(d) {
        fileExists(expected).should.equal(false);
        fileExists(expected2).should.equal(true);
      }))
      .pipe(sassert.end(done));

  });

  it('4) create output report', function(done) {

    var options = {
      reference: 'img/',
      reportOutput: 'report.txt'
    };
    var expected = path.join(__dirname, './.tmp/report.txt');

    gulp.src(fixtures('index.html'))
      .pipe(unused(options))
      .pipe(sassert.first(function(d) {
        fs.readFileSync(expected).toString().should.equal('bg_foot.png');
        fileExists(expected).should.equal(true);
      }))
      .pipe(sassert.end(done));
  });

});
<|endoftext|>


<commit_before>// Copyright 2015, University of Colorado Boulder

/**
 * A scenery node that looks like a key pad and allows the user to enter digits.  The entered digits are not displayed
 * by this node - it is intended to be used in conjunction with a separate display of some sort.
 *
 * @author John Blanco
 * @author Andrey Zelenkov (MLearner)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var Text = require( 'SCENERY/nodes/Text' );
  var VBox = require( 'SCENERY/nodes/VBox' );
  var BackspaceIcon = require( 'SCENERY_PHET/BackspaceIcon' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function NumberKeypad( options ) {

    options = _.extend( {
      buttonFont: new PhetFont( { size: 20 } ),
      minButtonWidth: 35,
      minButtonHeight: 35,
      decimalPointKey: false,
      xSpacing: 10,
      ySpacing: 10,
      keyColor: 'white',
      maxDigits: 8, // Maximum number of digits that the user may enter
      digitStringProperty: new Property( '' ) // create a digit string property or use the one supplied by the client
    }, options );

    var self = this;

    // @public, read only - string of digits entered by the user
    this.digitStringProperty = options.digitStringProperty;

    // @private - flag used when arming the keypad to start over on the next key stroke
    this.armedForNewEntry = false;

    // bundle the various options that control the button appearance into a "button specification" or buttonKeySpec
    var buttonKeySpec = {
      minWidth: options.minButtonWidth,
      minHeight: options.minButtonHeight,
      baseColor: options.keyColor,
      font: options.buttonFont,
      maxDigits: options.maxDigits
    };

    // create the backspace button
    var backspaceIcon = new BackspaceIcon();
    backspaceIcon.scale( Math.min( options.minButtonWidth / backspaceIcon.width * 0.7, ( options.minButtonHeight * 0.65 ) / backspaceIcon.height ) );
    var backspaceButton = new RectangularPushButton( {
      content: backspaceIcon,
      minWidth: buttonKeySpec.minWidth,
      minHeight: buttonKeySpec.minHeight,
      xMargin: 1,
      baseColor: buttonKeySpec.baseColor,
      listener: function() {
        if ( self.digitStringProperty.value.length > 0 ) {

          // remove the last digit from the current digit string
          var shortenedDigitString = self.digitStringProperty.value.slice( 0, -1 );

          if ( self.armedForNewEntry ) {
            self.digitStringProperty.reset(); // this reset will trigger the state change that we want in the game
            self.armedForNewEntry = false;
          }

          // set the new shortened value
          self.digitStringProperty.value = shortenedDigitString;
        }
      }
    } );

    // create the bottom row of buttons, which can vary based on options
    var bottomButtonRowChildren = [];
    if ( options.decimalPointKey ) {
      // add a decimal point key plus a normal width zero key
      bottomButtonRowChildren.push( createNumberKey( '.', this, buttonKeySpec ) );
      bottomButtonRowChildren.push( createNumberKey( 0, this, buttonKeySpec ) );
    }
    else {
      // add a double-width zero key instead of the decimal point key
      var doubleRowButtonKeySpec = _.extend( {}, buttonKeySpec, { minWidth: buttonKeySpec.minWidth * 2 + options.xSpacing } );
      bottomButtonRowChildren.push( createNumberKey( 0, this, doubleRowButtonKeySpec ) );
    }
    bottomButtonRowChildren.push( backspaceButton );

    // add the rest of the keys
    VBox.call( this, {
      spacing: options.ySpacing, children: [
        new HBox( {
          spacing: options.xSpacing, children: [
            createNumberKey( 7, this, buttonKeySpec ),
            createNumberKey( 8, this, buttonKeySpec ),
            createNumberKey( 9, this, buttonKeySpec )
          ]
        } ),
        new HBox( {
          spacing: options.xSpacing, children: [
            createNumberKey( 4, this, buttonKeySpec ),
            createNumberKey( 5, this, buttonKeySpec ),
            createNumberKey( 6, this, buttonKeySpec )
          ]
        } ),
        new HBox( {
          spacing: options.xSpacing, children: [
            createNumberKey( 1, this, buttonKeySpec ),
            createNumberKey( 2, this, buttonKeySpec ),
            createNumberKey( 3, this, buttonKeySpec )
          ]
        } ),
        new HBox( { spacing: options.xSpacing, children: bottomButtonRowChildren } )
      ]
    } );

    // Pass options through to parent class
    this.mutate( options );
  }

  sceneryPhet.register( 'NumberKeypad', NumberKeypad );

  // convenience function for creating the buttons that act as the individual keys
  function createNumberKey( number, parentKeypad, buttonSpec ) {
    return new RectangularPushButton( {
      content: new Text( number.toString(), { font: buttonSpec.font } ),
      baseColor: buttonSpec.baseColor,
      minWidth: buttonSpec.minWidth,
      minHeight: buttonSpec.minHeight,
      xMargin: 5,
      yMargin: 5,
      listener: function() {

        // If armed for new entry, clear the existing string.
        if ( parentKeypad.armedForNewEntry ) {
          parentKeypad.digitStringProperty.reset();
          parentKeypad.armedForNewEntry = false;
        }

        // the new key entry
        var numberString = number.toString();

        // Add the digit to the string, but limit the length and prevent multiple leading zeros.
        if ( parentKeypad.digitStringProperty.value === '0' ) {
          if ( numberString !== 0 ) {
            // Replace the leading 0 with this digit.
            parentKeypad.digitStringProperty.value = numberString;
          }
          // else ignore the additional zero
        }
        else if ( parentKeypad.digitStringProperty.value.length < buttonSpec.maxDigits ) {

          // only allow a single decimal point
          if ( numberString !== '.' || parentKeypad.digitStringProperty.value.indexOf( '.' ) === -1 ) {
            parentKeypad.digitStringProperty.value += numberString;
          }
        }
      }
    } );
  }

  return inherit( VBox, NumberKeypad, {

    /**
     * Clear anything that has been accumulated in the digitString field.
     * @public
     */
    clear: function() {
      this.digitStringProperty.reset();
    },

    /**
     * Set the keypad such that any new digit entry will clear the existing string and start over.
     * @public
     */
    armForNewEntry: function() {
      this.armedForNewEntry = true;
    }
  } );
} );
<commit_msg>Fixed maxDigits w/ decimal point bug<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 * A scenery node that looks like a key pad and allows the user to enter digits.  The entered digits are not displayed
 * by this node - it is intended to be used in conjunction with a separate display of some sort.
 *
 * @author John Blanco
 * @author Andrey Zelenkov (MLearner)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  var Text = require( 'SCENERY/nodes/Text' );
  var VBox = require( 'SCENERY/nodes/VBox' );
  var BackspaceIcon = require( 'SCENERY_PHET/BackspaceIcon' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function NumberKeypad( options ) {

    options = _.extend( {
      buttonFont: new PhetFont( { size: 20 } ),
      minButtonWidth: 35,
      minButtonHeight: 35,
      decimalPointKey: false,
      xSpacing: 10,
      ySpacing: 10,
      keyColor: 'white',
      maxDigits: 8, // Maximum number of digits that the user may enter
      digitStringProperty: new Property( '' ) // create a digit string property or use the one supplied by the client
    }, options );

    var self = this;

    // @public, read only - string of digits entered by the user
    this.digitStringProperty = options.digitStringProperty;

    // @private - flag used when arming the keypad to start over on the next key stroke
    this.armedForNewEntry = false;

    // bundle the various options that control the button appearance into a "button specification" or buttonKeySpec
    var buttonKeySpec = {
      minWidth: options.minButtonWidth,
      minHeight: options.minButtonHeight,
      baseColor: options.keyColor,
      font: options.buttonFont,
      maxDigits: options.maxDigits
    };

    // create the backspace button
    var backspaceIcon = new BackspaceIcon();
    backspaceIcon.scale( Math.min( options.minButtonWidth / backspaceIcon.width * 0.7, ( options.minButtonHeight * 0.65 ) / backspaceIcon.height ) );
    var backspaceButton = new RectangularPushButton( {
      content: backspaceIcon,
      minWidth: buttonKeySpec.minWidth,
      minHeight: buttonKeySpec.minHeight,
      xMargin: 1,
      baseColor: buttonKeySpec.baseColor,
      listener: function() {
        if ( self.digitStringProperty.value.length > 0 ) {

          // remove the last digit from the current digit string
          var shortenedDigitString = self.digitStringProperty.value.slice( 0, -1 );

          if ( self.armedForNewEntry ) {
            self.digitStringProperty.reset(); // this reset will trigger the state change that we want in the game
            self.armedForNewEntry = false;
          }

          // set the new shortened value
          self.digitStringProperty.value = shortenedDigitString;
        }
      }
    } );

    // create the bottom row of buttons, which can vary based on options
    var bottomButtonRowChildren = [];
    if ( options.decimalPointKey ) {
      // add a decimal point key plus a normal width zero key
      bottomButtonRowChildren.push( createNumberKey( '.', this, buttonKeySpec ) );
      bottomButtonRowChildren.push( createNumberKey( 0, this, buttonKeySpec ) );
    }
    else {
      // add a double-width zero key instead of the decimal point key
      var doubleRowButtonKeySpec = _.extend( {}, buttonKeySpec, { minWidth: buttonKeySpec.minWidth * 2 + options.xSpacing } );
      bottomButtonRowChildren.push( createNumberKey( 0, this, doubleRowButtonKeySpec ) );
    }
    bottomButtonRowChildren.push( backspaceButton );

    // add the rest of the keys
    VBox.call( this, {
      spacing: options.ySpacing, children: [
        new HBox( {
          spacing: options.xSpacing, children: [
            createNumberKey( 7, this, buttonKeySpec ),
            createNumberKey( 8, this, buttonKeySpec ),
            createNumberKey( 9, this, buttonKeySpec )
          ]
        } ),
        new HBox( {
          spacing: options.xSpacing, children: [
            createNumberKey( 4, this, buttonKeySpec ),
            createNumberKey( 5, this, buttonKeySpec ),
            createNumberKey( 6, this, buttonKeySpec )
          ]
        } ),
        new HBox( {
          spacing: options.xSpacing, children: [
            createNumberKey( 1, this, buttonKeySpec ),
            createNumberKey( 2, this, buttonKeySpec ),
            createNumberKey( 3, this, buttonKeySpec )
          ]
        } ),
        new HBox( { spacing: options.xSpacing, children: bottomButtonRowChildren } )
      ]
    } );

    // Pass options through to parent class
    this.mutate( options );
  }

  sceneryPhet.register( 'NumberKeypad', NumberKeypad );

  // convenience function for creating the buttons that act as the individual keys
  function createNumberKey( number, parentKeypad, buttonSpec ) {
    return new RectangularPushButton( {
      content: new Text( number.toString(), { font: buttonSpec.font } ),
      baseColor: buttonSpec.baseColor,
      minWidth: buttonSpec.minWidth,
      minHeight: buttonSpec.minHeight,
      xMargin: 5,
      yMargin: 5,
      listener: function() {

        var decimalIndex = parentKeypad.digitStringProperty.value.indexOf( '.' );
        var digitLength = ( decimalIndex === -1 ? parentKeypad.digitStringProperty.value.length :
                                                  parentKeypad.digitStringProperty.value.length -1 );

        // If armed for new entry, clear the existing string.
        if ( parentKeypad.armedForNewEntry ) {
          parentKeypad.digitStringProperty.reset();
          parentKeypad.armedForNewEntry = false;
        }

        // the new key entry
        var numberString = number.toString();

        // Add the digit to the string, but limit the length and prevent multiple leading zeros.
        if ( parentKeypad.digitStringProperty.value === '0' ) {
          if ( numberString !== 0 ) {
            // Replace the leading 0 with this digit.
            parentKeypad.digitStringProperty.value = numberString;
          }
          // else ignore the additional zero
        }
        else if ( digitLength < buttonSpec.maxDigits ) {

          // only allow a single decimal point
          if ( numberString !== '.' || parentKeypad.digitStringProperty.value.indexOf( '.' ) === -1 ) {
            parentKeypad.digitStringProperty.value += numberString;
          }
        }
      }
    } );
  }

  return inherit( VBox, NumberKeypad, {

    /**
     * Clear anything that has been accumulated in the digitString field.
     * @public
     */
    clear: function() {
      this.digitStringProperty.reset();
    },

    /**
     * Set the keypad such that any new digit entry will clear the existing string and start over.
     * @public
     */
    armForNewEntry: function() {
      this.armedForNewEntry = true;
    }
  } );
} );
<|endoftext|>


<commit_before>/* ========================================================================
 * ScrollPos-Styler v0.6
 * https://github.com/acch/scrollpos-styler
 * ========================================================================
 * Copyright 2015 Achim Christ
 * Licensed under MIT (https://github.com/acch/scrollpos-styler/blob/master/LICENSE)
 * ======================================================================== */

// JSHint directives
/* exported ScrollPosStyler */

var ScrollPosStyler = (function(document, window) {
  "use strict";

  /* ====================
   * private variables
   * ==================== */
  var scrollPosY = 0,
      busy = false,
      onTop = true,

      // toggle style / class when scrolling below this position (in px)
      scrollOffsetY = 1,

      // choose elements to apply style / class to
      elements = document.getElementsByClassName("sps");

  /* ====================
   * private funcion to check scroll position
   * ==================== */
  function onScroll() {
    // ensure that events don't stack
    if (!busy) {
      // get current scroll position from window
      scrollPosY = window.pageYOffset;

      // if we were above, and are now below scroll position...
      if (onTop && scrollPosY > scrollOffsetY) {
        // suspend accepting scroll events
        busy = true;

        // remember that we are below scroll position
        onTop = false;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(belowScrollPos);

      // if we were below, and are now above scroll position...
      } else if (!onTop && scrollPosY <= scrollOffsetY) {
        // suspend accepting scroll events
        busy = true;

        // remember that we are above scroll position
        onTop = true;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(aboveScrollPos);
      }
    }
  }

  /* ====================
   * private function to style elements when above scroll position
   * ==================== */
  function aboveScrollPos() {
    // iterate over elements
    // for (var elem of elements) {
    for (var i = 0; elements[i]; ++i) { // chrome workaround
      // add style / class to element
      elements[i].classList.add("sps--abv");
      elements[i].classList.remove("sps--blw");
    }

    // resume accepting scroll events
    busy = false;
  }

  /* ====================
   * private function to style elements when below scroll position
   * ==================== */
  function belowScrollPos() {
    // iterate over elements
    // for (var elem of elements) {
    for (var i = 0; elements[i]; ++i) { // chrome workaround
      // add style / class to element
      elements[i].classList.add("sps--blw");
      elements[i].classList.remove("sps--abv");
    }

    // resume accepting scroll events
    busy = false;
  }

  /* ====================
   * public function to initially style elements based on scroll position
   * ==================== */
  var pub = {
    init: function() {
      // suspend accepting scroll events
      busy = true;

      // get current scroll position from window
      scrollPosY = window.pageYOffset;

      // if we are below scroll position...
      if (scrollPosY > scrollOffsetY) {
        // remember that we are below scroll position
        onTop = false;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(belowScrollPos);

      // if we are above scroll position...
      } else { // (scrollPosY <= scrollOffsetY)
        // remember that we are above scroll position
        onTop = true;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(aboveScrollPos);
      }
    }
  };

  /* ====================
   * main initialization
   * ==================== */
  // add initial style / class to elements when DOM is ready
  document.addEventListener("DOMContentLoaded", function() {
    // defer initialization to allow browser to restore scroll position
    window.setTimeout(pub.init, 1);
  });

  // register for window scroll events
  window.addEventListener("scroll", onScroll);

  return pub;
})(document, window);
<commit_msg>Add private variables to allow customizing style / class to apply to elements<commit_after>/* ========================================================================
 * ScrollPos-Styler v0.6
 * https://github.com/acch/scrollpos-styler
 * ========================================================================
 * Copyright 2015 Achim Christ
 * Licensed under MIT (https://github.com/acch/scrollpos-styler/blob/master/LICENSE)
 * ======================================================================== */

// JSHint directives
/* exported ScrollPosStyler */

var ScrollPosStyler = (function(document, window) {
  "use strict";

  /* ====================
   * private variables
   * ==================== */
  var scrollPosY = 0,
      busy = false,
      onTop = true,

      // toggle style / class when scrolling below this position (in px)
      scrollOffsetY = 1,

      // choose elements to apply style / class to
      elements = document.getElementsByClassName("sps"),

      // style / class to apply to elements when above scroll position
      classAbove = "sps--abv",

      // style / class to apply to elements when below scroll position
      classBelow = "sps--blw";

  /* ====================
   * private funcion to check scroll position
   * ==================== */
  function onScroll() {
    // ensure that events don't stack
    if (!busy) {
      // get current scroll position from window
      scrollPosY = window.pageYOffset;

      // if we were above, and are now below scroll position...
      if (onTop && scrollPosY > scrollOffsetY) {
        // suspend accepting scroll events
        busy = true;

        // remember that we are below scroll position
        onTop = false;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(belowScrollPos);

      // if we were below, and are now above scroll position...
      } else if (!onTop && scrollPosY <= scrollOffsetY) {
        // suspend accepting scroll events
        busy = true;

        // remember that we are above scroll position
        onTop = true;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(aboveScrollPos);
      }
    }
  }

  /* ====================
   * private function to style elements when above scroll position
   * ==================== */
  function aboveScrollPos() {
    // iterate over elements
    // for (var elem of elements) {
    for (var i = 0; elements[i]; ++i) { // chrome workaround
      // add style / class to element
      elements[i].classList.add(classAbove);
      elements[i].classList.remove(classBelow);
    }

    // resume accepting scroll events
    busy = false;
  }

  /* ====================
   * private function to style elements when below scroll position
   * ==================== */
  function belowScrollPos() {
    // iterate over elements
    // for (var elem of elements) {
    for (var i = 0; elements[i]; ++i) { // chrome workaround
      // add style / class to element
      elements[i].classList.add(classBelow);
      elements[i].classList.remove(classAbove);
    }

    // resume accepting scroll events
    busy = false;
  }

  /* ====================
   * public function to initially style elements based on scroll position
   * ==================== */
  var pub = {
    init: function() {
      // suspend accepting scroll events
      busy = true;

      // get current scroll position from window
      scrollPosY = window.pageYOffset;

      // if we are below scroll position...
      if (scrollPosY > scrollOffsetY) {
        // remember that we are below scroll position
        onTop = false;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(belowScrollPos);

      // if we are above scroll position...
      } else { // (scrollPosY <= scrollOffsetY)
        // remember that we are above scroll position
        onTop = true;

        // asynchronuously add style / class to elements
        window.requestAnimationFrame(aboveScrollPos);
      }
    }
  };

  /* ====================
   * main initialization
   * ==================== */
  // add initial style / class to elements when DOM is ready
  document.addEventListener("DOMContentLoaded", function() {
    // defer initialization to allow browser to restore scroll position
    window.setTimeout(pub.init, 1);
  });

  // register for window scroll events
  window.addEventListener("scroll", onScroll);

  return pub;
})(document, window);
<|endoftext|>


<commit_before>$(document).ready(function() {
	console.log("READY");
});<commit_msg>Added Cup Objects<commit_after>$(document).ready(function() {
  //cup holder(har har har)
  var cupArray = [];

  //cup functions
  function cup(name,position,hasBall) {
    name = name || "tempCup";
    position = position || 0;
    hasBall = hasBall || false;
    this.name = name;
    this.position = position;
    this.hasBall = hasBall;
    this.getKeyFromValue = function(value) {
      for(var keys in this) {
        if (this[keys]==value) {
          return this;
        }
      }
    }
  }

  //generate cups
  for (var i = 0; i < 3; i++) {
    cupArray.push(new cup("cup" + eval('i+1'),i,false));
  }

  console.log(cupArray);

  //Pick a cup
  console.log("Where to insert ball");
  var cupSelected = prompt();
  //set cup selected
  cupArray[cupSelected].hasBall = true;

});<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * IO type for PhetButton, to interface with phet-io api.
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanIO = require( 'TANDEM/types/BooleanIO' );
  var joist = require( 'JOIST/joist' );
  var NodeProperty = require( 'SCENERY/util/NodeProperty' );
  var NullableIO = require( 'TANDEM/types/NullableIO' );
  var ObjectIO = require( 'TANDEM/types/ObjectIO' );
  var phetioInherit = require( 'TANDEM/phetioInherit' );
  var PropertyIO = require( 'AXON/PropertyIO' );

  /**
   * IO type for phet/joist's PhetButton
   * @param {PhetButton} phetButton
   * @param {string} phetioID
   * @constructor
   */
  function PhetButtonIO( phetButton, phetioID ) {
    ObjectIO.call( this, phetButton, phetioID );

    // The PhetButtonIO acts as the main phet-io branding/logo in the sim. It doesn't inherit from NodeIO because we don't
    // all of NodeIO's interactive methods, nor do we want to support maintaining overriding no-ops in this file
    // see https://github.com/phetsims/scenery/issues/711 for more info.
    // Note that this code is duplicated with similar code in NodeIO
    var pickableProperty = new NodeProperty( phetButton, 'pickability', 'pickable', {

      // pick the following values from the parent Node
      phetioReadOnly: phetButton.phetioReadOnly,
      tandem: phetButton.tandem.createTandem( 'pickableProperty' ),
      phetioType: PropertyIO( NullableIO( BooleanIO ) ),
      phetioDocumentation: 'Set whether the phetButton will be pickable (and hence interactive), see the NodeIO documentation for more details'
    } );

    // @private
    this.disposePhetButtonIO = function() {
      pickableProperty.dispose();
    };
  }

  phetioInherit( ObjectIO, 'PhetButtonIO', PhetButtonIO, {

    /**
     * @public - called by PhetioObject when the wrapper is done
     */
    dispose: function() {
      this.disposePhetButtonIO();
    }
  }, {
    documentation: 'The PhET Button in the bottom right of the screen',
    validator: { isValidValue: v => v instanceof phet.joist.PhetButton },

    /**
     * See NodeIO.toStateObject
     * @returns {undefined} - We don't use null because other types want that value in the state, see `NullableIO` for example.
     * @override
     */
    toStateObject: function() {
      return undefined;
    },

    /**
     * See NodeIO.fromStateObject
     * @param {Node} o
     * @returns {Object}
     * @override - to prevent attempted JSON serialization of circular Node
     */
    fromStateObject: function( o ) {
      return o; // Pass through values defined by subclasses
    }
  } );

  joist.register( 'PhetButtonIO', PhetButtonIO );

  class X {}

  X.hello = 'true';

  return PhetButtonIO;
} );

<commit_msg>Move documentation, see https://github.com/phetsims/phet-io/issues/1486<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * IO type for PhetButton, to interface with phet-io api.  The PhetButtonIO acts as the main phet-io branding/logo in
 * the sim. It doesn't inherit from NodeIO because we don't all of NodeIO's interactive methods, nor do we want to
 * support maintaining overriding no-ops in this file see https://github.com/phetsims/scenery/issues/711 for more info.
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanIO = require( 'TANDEM/types/BooleanIO' );
  var joist = require( 'JOIST/joist' );
  var NodeProperty = require( 'SCENERY/util/NodeProperty' );
  var NullableIO = require( 'TANDEM/types/NullableIO' );
  var ObjectIO = require( 'TANDEM/types/ObjectIO' );
  var phetioInherit = require( 'TANDEM/phetioInherit' );
  var PropertyIO = require( 'AXON/PropertyIO' );

  /**
   * IO type for phet/joist's PhetButton
   * @param {PhetButton} phetButton
   * @param {string} phetioID
   * @constructor
   */
  function PhetButtonIO( phetButton, phetioID ) {
    ObjectIO.call( this, phetButton, phetioID );

    // This code is similar to code in NodeIO, but it is not customizable through phetioComponentOptions because all
    // instances have the same level of instrumentation.
    var pickableProperty = new NodeProperty( phetButton, 'pickability', 'pickable', {

      // pick the following values from the parent Node
      phetioReadOnly: phetButton.phetioReadOnly,
      tandem: phetButton.tandem.createTandem( 'pickableProperty' ),
      phetioType: PropertyIO( NullableIO( BooleanIO ) ),
      phetioDocumentation: 'Set whether the phetButton will be pickable (and hence interactive), see the NodeIO documentation for more details'
    } );

    // @private
    this.disposePhetButtonIO = function() {
      pickableProperty.dispose();
    };
  }

  phetioInherit( ObjectIO, 'PhetButtonIO', PhetButtonIO, {

    /**
     * @public - called by PhetioObject when the wrapper is done
     */
    dispose: function() {
      this.disposePhetButtonIO();
    }
  }, {
    documentation: 'The PhET Button in the bottom right of the screen',
    validator: { isValidValue: v => v instanceof phet.joist.PhetButton },

    /**
     * See NodeIO.toStateObject
     * @returns {undefined} - We don't use null because other types want that value in the state, see `NullableIO` for example.
     * @override
     */
    toStateObject: function() {
      return undefined;
    },

    /**
     * See NodeIO.fromStateObject
     * @param {Node} o
     * @returns {Object}
     * @override - to prevent attempted JSON serialization of circular Node
     */
    fromStateObject: function( o ) {
      return o; // Pass through values defined by subclasses
    }
  } );

  joist.register( 'PhetButtonIO', PhetButtonIO );

  class X {}

  X.hello = 'true';

  return PhetButtonIO;
} );

<|endoftext|>


<commit_before>'use strict';

function create_fish(){
    // Determine fish class.
    var fish_class = Math.random();

    var fish_size = 0;
    // 60% chance to be normal sized fish...
    if(fish_class < .6){
        fish_size = random_integer({
          'max': 25,
        }) + 25;

    // 88% chance to be a small fish...
    }else if(fish_class < .88){
        fish_size = random_integer({
          'max': 10,
        }) + 5;

    // ...else is a giant fish.
    }else{
        fish_size = random_integer({
          'max': 500,
        }) + 50;
    }

    fish.push({
      'angle': 0,
      'color': random_hex(),
      'dx': 0,
      'dy': 0,
      'size': fish_size,
      'x': 0,
      'y': 0,
    });

    randomize_fish_movement(fish.length - 1);
}

function draw_logic(){
    canvas_buffer.fillStyle = '#003';
    canvas_buffer.fillRect(
      pillar,
      0,
      100,
      canvas_height
    );

    // Save the current buffer state.
    canvas_buffer.save();

    // Draw stuff relative to center of canvas.
    canvas_buffer.translate(
      -camera_x,
      -camera_y
    );

    for(var id in fish){
        canvas_buffer.save();

        // Translate and rotate fish.
        canvas_buffer.translate(
          fish[id]['x'],
          fish[id]['y']
        );
        canvas_buffer.rotate(fish[id]['angle']);

        // Determine movement direction based on dx.
        var direction = fish[id]['dx'] > 0
          ? 1
          : -1;

        // Draw fish.
        canvas_draw_path({
          'properties': {
            'fillStyle': fish[id]['color'],
          },
          'vertices': [
            {
              'type': 'moveTo',
              'x': 0,
              'y': fish[id]['size'] / 2,
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * direction,
              'y': 0,
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * 3 * direction,
              'y': fish[id]['size'],
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * 3 * direction,
              'y': 0,
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * direction,
              'y': fish[id]['size'],
            },
          ],
        });

        canvas_buffer.restore();
    }

    // Restore the buffer state.
    canvas_buffer.restore();

    // Draw current camera position.
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.fillText(
      camera_x + 'x ' + camera_y + 'y',
      0,
      25
    );
    canvas_buffer.fillText(
      fish.length,
      0,
      50
    );
}

function logic(){
    camera_speed = input_keys[16]['state']
      ? 10
      : 5;

    if(input_keys[65]['state']){
        camera_x -= camera_speed;
        move_pillar(camera_speed);
    }
    if(input_keys[68]['state']){
        camera_x += camera_speed;
        move_pillar(-camera_speed);
    }
    if(input_keys[83]['state']){
        camera_y += camera_speed;
    }
    if(input_keys[87]['state']){
        camera_y -= camera_speed;
    }

    for(var id in fish){
        // Fish move in the direction they are facing.
        fish[id]['x'] -= fish[id]['dx'];
        fish[id]['y'] -= fish[id]['dy'];

        // If a fish travels past the edge of the screen,
        //   move it to the other side.
        var size = fish[id]['size'] * 4;
        if(fish[id]['x'] > camera_x + canvas_width + size
          || fish[id]['x'] < camera_x - size){
            fish[id]['x'] += fish[id]['dx'] < 0
              ? -canvas_width - size
              : canvas_width + size;
            fish[id]['y'] = camera_y + random_integer({
              'max': canvas_height,
            });

            randomize_fish_movement(id);
        }
    }
}

function move_pillar(amount){
    pillar += amount;

    if(pillar > canvas_width){
        pillar -= canvas_width + 100;

    }else if(pillar < -100){
        pillar += canvas_width + 100;
    }
}

function randomize_fish_movement(fish_id){
    fish[fish_id]['dx'] = Math.random() * 10 - 5;
    fish[fish_id]['dy'] = Math.random() * (fish[fish_id]['dx'] / 2) - fish[fish_id]['dx'] / 4;
    fish[fish_id]['x'] = fish[fish_id]['dx'] < 0
      ? camera_x - fish[fish_id]['size']
      : camera_x + fish[fish_id]['size'] + canvas_width;
    fish[fish_id]['y'] = camera_y + random_integer({
      'max': canvas_height,
    });

    fish[fish_id]['angle'] = math_movement_speed({
      'x0': fish[fish_id]['x'],
      'x1': fish[fish_id]['x'] + fish[fish_id]['dx'],
      'y0': fish[fish_id]['y'],
      'y1': fish[fish_id]['y'] + fish[fish_id]['dy'],
    })[2];

    if(fish[fish_id]['dx'] > 0
      || fish[fish_id]['dy'] > 0){
        fish[fish_id]['angle'] *= -1;
    }

    if(fish[fish_id]['dx'] > 0
      && fish[fish_id]['dy'] > 0){
        fish[fish_id]['angle'] *= -1;
    }
}

function resize_logic(){
    move_pillar(random_integer({
      'max': canvas_width,
    }));
}

var camera_speed = 5;
var camera_x = 0;
var camera_y = 0;
var fish = [];
var pillar = 0;

window.onload = function(){
    canvas_init();
    input_init({
      'keybinds': {
        16: {},
        27: {
          'todo': function(){
              fish.length = 0;
          },
        },
        65: {},
        68: {},
        70: {
          'todo': create_fish,
        },
        72: {
          'todo': function(){
              move_pillar(camera_x);
              camera_x = 0;
              camera_y = 0;
          },
        },
        83: {},
        87: {},
      },
    });

    document.getElementById('canvas').style.background = '#004';

    // Create 10 randomly placed fish.
    var loop_counter = 9;
    do{
        create_fish();
    }while(loop_counter--);
};
<commit_msg>renamed math_movement_speed() to math_move_2d()<commit_after>'use strict';

function create_fish(){
    // Determine fish class.
    var fish_class = Math.random();

    var fish_size = 0;
    // 60% chance to be normal sized fish...
    if(fish_class < .6){
        fish_size = random_integer({
          'max': 25,
        }) + 25;

    // 88% chance to be a small fish...
    }else if(fish_class < .88){
        fish_size = random_integer({
          'max': 10,
        }) + 5;

    // ...else is a giant fish.
    }else{
        fish_size = random_integer({
          'max': 500,
        }) + 50;
    }

    fish.push({
      'angle': 0,
      'color': random_hex(),
      'dx': 0,
      'dy': 0,
      'size': fish_size,
      'x': 0,
      'y': 0,
    });

    randomize_fish_movement(fish.length - 1);
}

function draw_logic(){
    canvas_buffer.fillStyle = '#003';
    canvas_buffer.fillRect(
      pillar,
      0,
      100,
      canvas_height
    );

    // Save the current buffer state.
    canvas_buffer.save();

    // Draw stuff relative to center of canvas.
    canvas_buffer.translate(
      -camera_x,
      -camera_y
    );

    for(var id in fish){
        canvas_buffer.save();

        // Translate and rotate fish.
        canvas_buffer.translate(
          fish[id]['x'],
          fish[id]['y']
        );
        canvas_buffer.rotate(fish[id]['angle']);

        // Determine movement direction based on dx.
        var direction = fish[id]['dx'] > 0
          ? 1
          : -1;

        // Draw fish.
        canvas_draw_path({
          'properties': {
            'fillStyle': fish[id]['color'],
          },
          'vertices': [
            {
              'type': 'moveTo',
              'x': 0,
              'y': fish[id]['size'] / 2,
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * direction,
              'y': 0,
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * 3 * direction,
              'y': fish[id]['size'],
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * 3 * direction,
              'y': 0,
            },
            {
              'type': 'lineTo',
              'x': fish[id]['size'] * direction,
              'y': fish[id]['size'],
            },
          ],
        });

        canvas_buffer.restore();
    }

    // Restore the buffer state.
    canvas_buffer.restore();

    // Draw current camera position.
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.fillText(
      camera_x + 'x ' + camera_y + 'y',
      0,
      25
    );
    canvas_buffer.fillText(
      fish.length,
      0,
      50
    );
}

function logic(){
    camera_speed = input_keys[16]['state']
      ? 10
      : 5;

    if(input_keys[65]['state']){
        camera_x -= camera_speed;
        move_pillar(camera_speed);
    }
    if(input_keys[68]['state']){
        camera_x += camera_speed;
        move_pillar(-camera_speed);
    }
    if(input_keys[83]['state']){
        camera_y += camera_speed;
    }
    if(input_keys[87]['state']){
        camera_y -= camera_speed;
    }

    for(var id in fish){
        // Fish move in the direction they are facing.
        fish[id]['x'] -= fish[id]['dx'];
        fish[id]['y'] -= fish[id]['dy'];

        // If a fish travels past the edge of the screen,
        //   move it to the other side.
        var size = fish[id]['size'] * 4;
        if(fish[id]['x'] > camera_x + canvas_width + size
          || fish[id]['x'] < camera_x - size){
            fish[id]['x'] += fish[id]['dx'] < 0
              ? -canvas_width - size
              : canvas_width + size;
            fish[id]['y'] = camera_y + random_integer({
              'max': canvas_height,
            });

            randomize_fish_movement(id);
        }
    }
}

function move_pillar(amount){
    pillar += amount;

    if(pillar > canvas_width){
        pillar -= canvas_width + 100;

    }else if(pillar < -100){
        pillar += canvas_width + 100;
    }
}

function randomize_fish_movement(fish_id){
    fish[fish_id]['dx'] = Math.random() * 10 - 5;
    fish[fish_id]['dy'] = Math.random() * (fish[fish_id]['dx'] / 2) - fish[fish_id]['dx'] / 4;
    fish[fish_id]['x'] = fish[fish_id]['dx'] < 0
      ? camera_x - fish[fish_id]['size']
      : camera_x + fish[fish_id]['size'] + canvas_width;
    fish[fish_id]['y'] = camera_y + random_integer({
      'max': canvas_height,
    });

    fish[fish_id]['angle'] = math_move_2d({
      'x0': fish[fish_id]['x'],
      'x1': fish[fish_id]['x'] + fish[fish_id]['dx'],
      'y0': fish[fish_id]['y'],
      'y1': fish[fish_id]['y'] + fish[fish_id]['dy'],
    })[2];

    if(fish[fish_id]['dx'] > 0
      || fish[fish_id]['dy'] > 0){
        fish[fish_id]['angle'] *= -1;
    }

    if(fish[fish_id]['dx'] > 0
      && fish[fish_id]['dy'] > 0){
        fish[fish_id]['angle'] *= -1;
    }
}

function resize_logic(){
    move_pillar(random_integer({
      'max': canvas_width,
    }));
}

var camera_speed = 5;
var camera_x = 0;
var camera_y = 0;
var fish = [];
var pillar = 0;

window.onload = function(){
    canvas_init();
    input_init({
      'keybinds': {
        16: {},
        27: {
          'todo': function(){
              fish.length = 0;
          },
        },
        65: {},
        68: {},
        70: {
          'todo': create_fish,
        },
        72: {
          'todo': function(){
              move_pillar(camera_x);
              camera_x = 0;
              camera_y = 0;
          },
        },
        83: {},
        87: {},
      },
    });

    document.getElementById('canvas').style.background = '#004';

    // Create 10 randomly placed fish.
    var loop_counter = 9;
    do{
        create_fish();
    }while(loop_counter--);
};
<|endoftext|>


<commit_before>var request = require("request");
var fs = require("fs");
var toMarkdown = require('to-markdown');
var htmlparser = require("htmlparser2");

var articleModule = require('../model/article.js');
var blogModule = require('../model/blog.js');

var async = require('async');

// For Translation:

categoryTranslation =
{
  "[Aktuelle Kategorie]":"[Actual Category]",
  "In eigener Sache":"About us",
  "Wochenaufruf":"Weekly exerciseEN:",
  "Mapping":"Mapping",
  "Community":"Community",
  "Importe":"Imports",
  "OpenStreetMap Foundation":"OpenStreetMap Foundation",
  "Veranstaltungen":"Events",
  "Humanitarian OSM":"Humanitarian OSM",
  "Karten":"Maps",
  "switch2OSM":"#switch2OSM",
  "Open-Data":"Open Data",
  "Lizenzen":"Licences",
  "Programme":"Software",
  "Programmierung":"Programming",
  "Kennst Du schon …":"Did you know …",
  "Weitere Themen mit Geo-Bezug":'Other “geo” things',
  "Wochenvorschau" :"Weekly Preview",
  "ODbL":"ODbL",
  "Humanitarian OpenStreetMap":"Humanitarian OpenStreetMap",
  "Humanitarian OpenStreetMap Team":"Humanitarian OpenStreetMap Team",
  "Weltweit":"Global",
  "Sonstiges":"Other",
  "Talk, Forum, Wiki & Blog":"Talk, Forum, Wiki & Blog",
  "Talk, Forum, Wiki":"Talk, Forum, Wiki",
  "Blog & Twitter":"Blog & Twitter",
  "Import":"Import",
  "Tagging":"Tagging",
  "Open Data & ODbL":"Open Data & ODbL",
  "Konferenzen & Treffen":"Conferences",
  "und sonst":"Other",
  "Karten & Programme":"Maps & Programs",
  "#switch2osm":"#switch2osm",
  "Weltweit & sonstiges":"Global & Other"

}

// This is the simple HTML Parser for the WN

var currentCategory = new Category();
var currentElement = "";

var status = null;
var result = [];
var categoryList = [];

var parser = new htmlparser.Parser({
    onopentag: function(name, attribs){
        // ignore everything in comment mode
        if (status == "finished") return;

        if(name == "h2" ){
            status = "category";

        }
        if (name == "li") {
          status = "list";
        }
        if (name == "a" && status == "list") {
            currentElement += "";

        }
        if (name == "div") {
          if (attribs.id == "entry-author-info") {
            status = "finished";
            result.push(currentCategory);
          }
        }
    },
    ontext: function(text){
        if (status == "finished") return;

        if (status == "category" && text != currentCategory.title) {
          text = text.replace("&","&")
          result.push(currentCategory);
          currentCategory =new Category();
          currentCategory.title = text;
          categoryList.push(text);
        }
        if (status == "list") {
          currentElement += text;
        }

    },
    onclosetag: function(tagname){
        if (status == "finished") return;
        if(tagname === "h2"){
           status = "";
        }
        if(tagname === "li"){
           status = "";
           currentCategory.element.push(currentElement);
           currentElement = "";
        }
        if (tagname == "a" && status == "list") {
            currentElement += "";

        }

    }
}, {decodeEntities: false});

 function Category() {
    this.title = null;
    this.element = [];
  }

 function importBlog(nr,callback) {
   var number = "000"+nr;

   var blogName = "WN"+number.substring(number.length-3,99);
   console.log("Import WN "+blogName);

   blogModule.findOne({name:blogName},function (err,b) {
    if (b) {
      console.log(blogName+" allready exists");
      return callback();
    }

    var body = null;
    var url = null;
    async.parallel([
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      },
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/osm-wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      }

      ],
      function loadedWN(err){
        website = body;
        if (body) {
          status = null;
          result = [];
          categoryList = [];
          parser.write(body);
          console.log("Loaded Url:",url);
          //console.log("Articles: ",result);
          var blog = blogModule.create();

          //fs.writeFileSync(blogName,body,"utf8");

          var cat =[];
          for (var i=0;i<categoryList.length;i++) {
            var c = {DE:categoryList[i]};
            if (c.DE in categoryTranslation) {
              c.EN = categoryTranslation[c.DE];
            }
            else
            {
              c.EN = c.DE+"Not Translated";
              console.log(c.EN);
            }
            cat.push(c);
          }

          blog.setAndSave("IMPORT",{name:blogName,status:"published",categories:cat},function(err,erg){
            console.log("Blog Saved Error("+err+")");
            async.each(result,function iterator(item,cb) {
              var category = item.title;
              //console.dir("ITEM"+item);
              if (category == null) return cb();
              //console.dir("Import Category: "+category);
              //console.dir(item.element.length+" Elements in Category");
              async.each(item.element,function eachArticle(articleProto,cba) {
                //console.log(articleProto);
                var markdown = toMarkdown(articleProto);
                var article = articleModule.create();
                article.setAndSave("IMPORT",{blog:blogName,category:category,markdown:markdown},function(err){
                  //console.log("Article Saved");
                  cba(err);
                });

              }, function done() {cb();}
              )

            }, function(done) {
              console.log("Blog "+blogName+ " imported");
              callback();
            }
            )
          })
        }
      })

    });
  }

async.timesLimit(268,1,function (n,next){
  importBlog(n,next);

})
<commit_msg>Quickfix for import.<commit_after>var request = require("request");
var fs = require("fs");
var toMarkdown = require('to-markdown');
var htmlparser = require("htmlparser2");

var articleModule = require('../model/article.js');
var blogModule = require('../model/blog.js');
var config=require('../config.js')

var async = require('async');

// For Translation:

categoryTranslation =
{
  "[Aktuelle Kategorie]":"[Actual Category]",
  "In eigener Sache":"About us",
  "Wochenaufruf":"Weekly exerciseEN:",
  "Mapping":"Mapping",
  "Community":"Community",
  "Importe":"Imports",
  "OpenStreetMap Foundation":"OpenStreetMap Foundation",
  "Veranstaltungen":"Events",
  "Humanitarian OSM":"Humanitarian OSM",
  "Karten":"Maps",
  "switch2OSM":"#switch2OSM",
  "Open-Data":"Open Data",
  "Lizenzen":"Licences",
  "Programme":"Software",
  "Programmierung":"Programming",
  "Kennst Du schon …":"Did you know …",
  "Weitere Themen mit Geo-Bezug":'Other “geo” things',
  "Wochenvorschau" :"Weekly Preview",
  "ODbL":"ODbL",
  "Humanitarian OpenStreetMap":"Humanitarian OpenStreetMap",
  "Humanitarian OpenStreetMap Team":"Humanitarian OpenStreetMap Team",
  "Weltweit":"Global",
  "Sonstiges":"Other",
  "Talk, Forum, Wiki & Blog":"Talk, Forum, Wiki & Blog",
  "Talk, Forum, Wiki":"Talk, Forum, Wiki",
  "Blog & Twitter":"Blog & Twitter",
  "Import":"Import",
  "Tagging":"Tagging",
  "Open Data & ODbL":"Open Data & ODbL",
  "Konferenzen & Treffen":"Conferences",
  "und sonst":"Other",
  "Karten & Programme":"Maps & Programs",
  "#switch2osm":"#switch2osm",
  "Weltweit & sonstiges":"Global & Other"

}

// This is the simple HTML Parser for the WN

var currentCategory = new Category();
var currentElement = "";

var status = null;
var result = [];
var categoryList = [];

var parser = new htmlparser.Parser({
    onopentag: function(name, attribs){
        // ignore everything in comment mode
        if (status == "finished") return;

        if(name == "h2" ){
            status = "category";

        }
        if (name == "li") {
          status = "list";
        }
        if (name == "a" && status == "list") {
            currentElement += "";

        }
        if (name == "div") {
          if (attribs.id == "entry-author-info") {
            status = "finished";
            result.push(currentCategory);
          }
        }
    },
    ontext: function(text){
        if (status == "finished") return;

        if (status == "category" && text != currentCategory.title) {
          text = text.replace("&","&")
          result.push(currentCategory);
          currentCategory =new Category();
          currentCategory.title = text;
          categoryList.push(text);
        }
        if (status == "list") {
          currentElement += text;
        }

    },
    onclosetag: function(tagname){
        if (status == "finished") return;
        if(tagname === "h2"){
           status = "";
        }
        if(tagname === "li"){
           status = "";
           currentCategory.element.push(currentElement);
           currentElement = "";
        }
        if (tagname == "a" && status == "list") {
            currentElement += "";

        }

    }
}, {decodeEntities: false});

 function Category() {
    this.title = null;
    this.element = [];
  }

 function importBlog(nr,callback) {
   var number = "000"+nr;

   var blogName = "WN"+number.substring(number.length-3,99);
   console.log("Import WN "+blogName);

   blogModule.findOne({name:blogName},function (err,b) {
    if (b) {
      console.log(blogName+" allready exists");
      return callback();
    }

    var body = null;
    var url = null;
    async.parallel([
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      },
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/osm-wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      }

      ],
      function loadedWN(err){
        website = body;
        if (body) {
          status = null;
          result = [];
          categoryList = [];
          parser.write(body);
          console.log("Loaded Url:",url);
          //console.log("Articles: ",result);
          var blog = blogModule.create();

          //fs.writeFileSync(blogName,body,"utf8");

          var cat =[];
          for (var i=0;i<categoryList.length;i++) {
            var c = {DE:categoryList[i]};
            if (c.DE in categoryTranslation) {
              c.EN = categoryTranslation[c.DE];
            }
            else
            {
              c.EN = c.DE+"Not Translated";
              console.log(c.EN);
            }
            cat.push(c);
          }

          blog.setAndSave("IMPORT",{name:blogName,status:"published",categories:cat},function(err,erg){
            console.log("Blog Saved Error("+err+")");
            async.each(result,function iterator(item,cb) {
              var category = item.title;
              //console.dir("ITEM"+item);
              if (category == null) return cb();
              //console.dir("Import Category: "+category);
              //console.dir(item.element.length+" Elements in Category");
              async.each(item.element,function eachArticle(articleProto,cba) {
                //console.log(articleProto);
                var markdown = toMarkdown(articleProto);
                var article = articleModule.create();
                article.setAndSave("IMPORT",{blog:blogName,category:category,markdown:markdown},function(err){
                  //console.log("Article Saved");
                  cba(err);
                });

              }, function done() {cb();}
              )

            }, function(done) {
              console.log("Blog "+blogName+ " imported");
              callback();
            }
            )
          })
        }
      })

    });
  }

config.initialise();

importBlog(268,function(){console.log("Ready.")});
importBlog(269,function(){console.log("Ready.")});
importBlog(270,function(){console.log("Ready.")});
importBlog(271,function(){console.log("Ready.")});
/*
async.timesLimit(1,1,function (n,next){
  console.log("Start Import for "+n);
  importBlog(n,next);

})*/
<|endoftext|>


<commit_before>describe('dirty fields', function () {

    var Pouch, RawQuery, Collection, RelationshipType, RelatedObjectProxy, RestObject, $rootScope, CollectionRegistry;
    var collection, carMapping;

    beforeEach(function () {
        module('restkit.mapping', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });
        module('restkit.relationship', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });

        inject(function (_Pouch_, _RawQuery_, _RestObject_, _Collection_, _RelationshipType_, _RelatedObjectProxy_, _$rootScope_, _CollectionRegistry_) {
            Pouch = _Pouch_;
            RawQuery = _RawQuery_;
            Collection = _Collection_;
            RelationshipType = _RelationshipType_;
            RelatedObjectProxy = _RelatedObjectProxy_;
            RestObject = _RestObject_;
            $rootScope = _$rootScope_;
            CollectionRegistry = _CollectionRegistry_;
        });

        Pouch.reset();

    });

    afterEach(function () {
        inject(function (Operation) {
            // If operations are still running after a test, they are going to interfere with other tests.
            assert.notOk(Operation.operationsAreRunning);
        })
    });

    describe.only('attributes', function () {

        describe('standard', function () {
            var car, doc;

            beforeEach(function (done) {
                collection = new Collection('myCollection', function (err, version) {
                    if (err) done(err);
                    carMapping = collection.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colour', 'name']
                    });
                }, function (err) {
                    if (err) done(err);
                    carMapping.map({name: 'Aston Martin', colour: 'black'}, function (err, _car) {
                        if (err) done(err);
                        car = _car;
                        Pouch.getPouch().get(car._id, function (err, _doc) {
                            if (err) done(err);
                            doc = _doc;
                            done();
                        });
                    });
                });
            });

            it('car should not be dirty when first mapped', function () {
                assert.notOk(car.isDirty);
            });

            it('type should not be dirty when first mapped', function () {
                assert.notOk(collection.Car.isDirty);
            });

            it('collection should not be dirty when first mapped', function () {
                assert.notOk(collection.isDirty);
            });

            it('global should not be dirty when first mapped', function () {
                assert.notOk(Collection.isDirty);
            });

            it('when first mapped, should have all the same fields', function () {
                assert.equal(doc._id, car._id);
                assert.equal(doc.name, car.name);
                assert.equal(doc.colour, car.colour);
            });

            describe('change attributes', function () {

                beforeEach(function () {
                    car.name = 'Bentley';
                });

                it('car should be dirty', function () {
                    assert.ok(car.isDirty);
                });

                describe('save', function () {

                    beforeEach(function (done) {
                        car.save(done);
                    });

                    it('car should no longer be dirty', function () {
                        assert.notOk(car.isDirty);
                    });

                    it('car collection should no longer be dirty', function () {
                        assert.notOk(collection.Car.isDirty);
                    });

                    it('collection should no longer be dirty', function () {
                        assert.notOk(collection.isDirty);
                    });

                    it('global should no longer be dirty', function () {
                        assert.notOk(Collection.isDirty);
                    });

                });

                it('car collection should be dirty', function () {
                    assert.ok(collection.Car.isDirty);
                });

                it('collection should be dirty', function () {
                    assert.ok(collection.isDirty);
                });

                it('global should be dirty', function () {
                    assert.ok(Collection.isDirty);
                });

            });
        });

        describe('arrays', function () {

            var car, doc;

            beforeEach(function (done) {
                collection = new Collection('myCollection', function (err, version) {
                    if (err) done(err);
                    carMapping = collection.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colours', 'name']
                    });
                }, function (err) {
                    if (err) done(err);
                    carMapping.map({name: 'Aston Martin', colours: ['black', 'red', 'green']}, function (err, _car) {
                        if (err) done(err);
                        car = _car;
                        Pouch.getPouch().get(car._id, function (err, _doc) {
                            if (err) done(err);
                            doc = _doc;
                            done();
                        });
                    });
                });
            });

            it('car should not be dirty when first mapped', function () {
                assert.notOk(car.isDirty);
            });

            it('type should not be dirty when first mapped', function () {
                assert.notOk(collection.Car.isDirty);
            });

            it('collection should not be dirty when first mapped', function () {
                assert.notOk(collection.isDirty);
            });

            it('global should not be dirty when first mapped', function () {
                assert.notOk(Collection.isDirty);
            });

            it('when first mapped, should have all the same fields', function () {
                assert.equal(doc._id, car._id);
                assert.equal(doc.name, car.name);
                _.each(car.colours, function (c) {
                    assert.include(doc.colours, c);
                })
            });

            describe('change attributes', function () {
                describe('push element', function () {
                    beforeEach(function () {
                        car.colours.push('purple');
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('pop element', function () {
                    beforeEach(function () {
                        car.colours.pop();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('shift element', function () {
                    beforeEach(function () {
                        car.colours.shift();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('unshift element', function () {
                    beforeEach(function () {
                        car.colours.unshift('purple');
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('sort array', function () {
                    beforeEach(function () {
                        car.colours.sort();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });

                });

                describe('reverse array', function () {
                    beforeEach(function () {
                        car.colours.reverse();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('set object at index', function () {
                    beforeEach(function () {
                        car.colours.setObjectAtIndex('purple', 1);
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('splice', function () {
                    beforeEach(function () {
                        car.colours.splice(1, 1, 'purple');
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

            });

        });

    })

});<commit_msg>Tidied up<commit_after>describe('dirty fields', function () {

    var Pouch, RawQuery, Collection, RelationshipType, RelatedObjectProxy, RestObject, $rootScope, CollectionRegistry;
    var collection, carMapping;

    var car;

    beforeEach(function () {
        module('restkit.mapping', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });
        module('restkit.relationship', function ($provide) {
            $provide.value('$log', console);
            $provide.value('$q', Q);
        });

        inject(function (_Pouch_, _RawQuery_, _RestObject_, _Collection_, _RelationshipType_, _RelatedObjectProxy_, _$rootScope_, _CollectionRegistry_) {
            Pouch = _Pouch_;
            RawQuery = _RawQuery_;
            Collection = _Collection_;
            RelationshipType = _RelationshipType_;
            RelatedObjectProxy = _RelatedObjectProxy_;
            RestObject = _RestObject_;
            $rootScope = _$rootScope_;
            CollectionRegistry = _CollectionRegistry_;
        });

        Pouch.reset();

    });

    afterEach(function () {
        inject(function (Operation) {
            // If operations are still running after a test, they are going to interfere with other tests.
            assert.notOk(Operation.operationsAreRunning);
        })
    });

    function assertNoLongerDirty() {
        it('car should no longer be dirty', function () {
            assert.notOk(car.isDirty);
        });

        it('car collection should no longer be dirty', function () {
            assert.notOk(collection.Car.isDirty);
        });

        it('collection should no longer be dirty', function () {
            assert.notOk(collection.isDirty);
        });

        it('global should no longer be dirty', function () {
            assert.notOk(Collection.isDirty);
        });
    }

    describe.only('attributes', function () {

        describe('standard', function () {
            var doc;

            beforeEach(function (done) {
                collection = new Collection('myCollection', function (err, version) {
                    if (err) done(err);
                    carMapping = collection.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colour', 'name']
                    });
                }, function (err) {
                    if (err) done(err);
                    carMapping.map({name: 'Aston Martin', colour: 'black'}, function (err, _car) {
                        if (err) done(err);
                        car = _car;
                        Pouch.getPouch().get(car._id, function (err, _doc) {
                            if (err) done(err);
                            doc = _doc;
                            done();
                        });
                    });
                });
            });

            it('car should not be dirty when first mapped', function () {
                assert.notOk(car.isDirty);
            });

            it('type should not be dirty when first mapped', function () {
                assert.notOk(collection.Car.isDirty);
            });

            it('collection should not be dirty when first mapped', function () {
                assert.notOk(collection.isDirty);
            });

            it('global should not be dirty when first mapped', function () {
                assert.notOk(Collection.isDirty);
            });

            it('when first mapped, should have all the same fields', function () {
                assert.equal(doc._id, car._id);
                assert.equal(doc.name, car.name);
                assert.equal(doc.colour, car.colour);
            });

            describe('change attributes', function () {

                beforeEach(function () {
                    car.name = 'Bentley';
                });

                it('car should be dirty', function () {
                    assert.ok(car.isDirty);
                });

                describe('save', function () {

                    beforeEach(function (done) {
                        car.save(done);
                    });

                    assertNoLongerDirty();

                });

                it('car collection should be dirty', function () {
                    assert.ok(collection.Car.isDirty);
                });

                it('collection should be dirty', function () {
                    assert.ok(collection.isDirty);
                });

                it('global should be dirty', function () {
                    assert.ok(Collection.isDirty);
                });

            });
        });

        describe('arrays', function () {

            var doc;

            beforeEach(function (done) {
                collection = new Collection('myCollection', function (err, version) {
                    if (err) done(err);
                    carMapping = collection.registerMapping('Car', {
                        id: 'id',
                        attributes: ['colours', 'name']
                    });
                }, function (err) {
                    if (err) done(err);
                    carMapping.map({name: 'Aston Martin', colours: ['black', 'red', 'green']}, function (err, _car) {
                        if (err) done(err);
                        car = _car;
                        Pouch.getPouch().get(car._id, function (err, _doc) {
                            if (err) done(err);
                            doc = _doc;
                            done();
                        });
                    });
                });
            });

            it('car should not be dirty when first mapped', function () {
                assert.notOk(car.isDirty);
            });

            it('type should not be dirty when first mapped', function () {
                assert.notOk(collection.Car.isDirty);
            });

            it('collection should not be dirty when first mapped', function () {
                assert.notOk(collection.isDirty);
            });

            it('global should not be dirty when first mapped', function () {
                assert.notOk(Collection.isDirty);
            });

            it('when first mapped, should have all the same fields', function () {
                assert.equal(doc._id, car._id);
                assert.equal(doc.name, car.name);
                _.each(car.colours, function (c) {
                    assert.include(doc.colours, c);
                })
            });

            describe('change attributes', function () {
                describe('push element', function () {
                    beforeEach(function () {
                        car.colours.push('purple');
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });

                    describe('save', function () {

                        beforeEach(function (done) {
                            car.save(done);
                        });

                        assertNoLongerDirty();

                        it('should have made the change', function (done) {
                            Pouch.getPouch().get(car._id, function (err, doc) {
                                assert.include(doc.colours, 'purple');
                                assert.equal(doc.colours.length, 4);
                                done();
                            });
                        });

                    });

                });

                describe('pop element', function () {
                    beforeEach(function () {
                        car.colours.pop();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('shift element', function () {
                    beforeEach(function () {
                        car.colours.shift();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('unshift element', function () {
                    beforeEach(function () {
                        car.colours.unshift('purple');
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('sort array', function () {
                    beforeEach(function () {
                        car.colours.sort();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });

                });

                describe('reverse array', function () {
                    beforeEach(function () {
                        car.colours.reverse();
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('set object at index', function () {
                    beforeEach(function () {
                        car.colours.setObjectAtIndex('purple', 1);
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

                describe('splice', function () {
                    beforeEach(function () {
                        car.colours.splice(1, 1, 'purple');
                    });

                    it('car collection should be dirty', function () {
                        assert.ok(collection.Car.isDirty);
                    });

                    it('collection should be dirty', function () {
                        assert.ok(collection.isDirty);
                    });

                    it('global should be dirty', function () {
                        assert.ok(Collection.isDirty);
                    });
                });

            });

        });

    })

});<|endoftext|>


<commit_before>'use strict'

module.exports = (connection, DataTypes) => {
    let Position = connection.define('position', {
        bodyUniqueId: {
            type: DataTypes.STRING,
            required: true
        },
        name: {
            type: DataTypes.STRING,
            required: true
        },
        voting: {
            type: DataTypes.BOOLEAN,
            default: false
        },
        officer: {
            type: DataTypes.BOOLEAN,
            default: false
        },
        presidingOfficer: {
            type: DataTypes.BOOLEAN,
            default: false
        }
    })

    Position.associate = models => {
        Position.belongsTo(models['body'], {
            targetKey: 'uniqueId',
            foreignKey: 'bodyUniqueId'
        })

        Position.hasMany(models['membership'], {
            foreignKey: 'positionId'
        })
    }

    Position.queryIncludes = (connection) => {
        return [
            { model: connection.model('body') },
            { model: connection.model('membership') }
        ]
    }

    return Position
}
<commit_msg>Fixed typo<commit_after>'use strict'

module.exports = (connection, DataTypes) => {
    let Position = connection.define('position', {
        bodyUniqueId: {
            type: DataTypes.STRING,
            required: true
        },
        name: {
            type: DataTypes.STRING,
            required: true
        },
        voting: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        },
        officer: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        },
        presidingOfficer: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        }
    })

    Position.associate = models => {
        Position.belongsTo(models['body'], {
            targetKey: 'uniqueId',
            foreignKey: 'bodyUniqueId'
        })

        Position.hasMany(models['membership'], {
            foreignKey: 'positionId'
        })
    }

    Position.queryIncludes = (connection) => {
        return [
            { model: connection.model('body') },
            { model: connection.model('membership') }
        ]
    }

    return Position
}
<|endoftext|>