<commit_before>import React from 'react';
import Immutable from 'immutable';

import { mount } from 'enzyme';
import chai, { expect } from 'chai';

import sinon from 'sinon';
import sinonChai from 'sinon-chai';

chai.use(sinonChai);

import GeoJSONTransform from '../../../../src/notebook/components/transforms/geojson';

const geojson = Immutable.fromJS({
  "type": "FeatureCollection",
  "features": [
      {
          "type": "Feature",
          "properties": {
              "popupContent": "18th & California Light Rail Stop"
          },
          "geometry": {
              "type": "Point",
              "coordinates": [-104.98999178409576, 39.74683938093904]
          }
      },{
          "type": "Feature",
          "properties": {
              "popupContent": "20th & Welton Light Rail Stop"
          },
          "geometry": {
              "type": "Point",
              "coordinates": [-104.98689115047453, 39.747924136466565]
          }
      }
  ]
});

describe('GeoJSONTransform', () => {
  it('renders a map', () => {
    const geoComponent = mount(
      <GeoJSONTransform
        data={geojson}
      />
    );

    expect(geoComponent.instance().shouldComponentUpdate({
      theme: 'light',
      data: geojson,
    })).to.be.false;
    expect(geoComponent.find('.leaflet-container')).to.have.length(1);

  });
});
<commit_msg>test: update the geojson map<commit_after>import React from 'react';
import Immutable from 'immutable';

import { mount } from 'enzyme';
import chai, { expect } from 'chai';

import sinon from 'sinon';
import sinonChai from 'sinon-chai';

chai.use(sinonChai);

import GeoJSONTransform from '../../../../src/notebook/components/transforms/geojson';

const geojson = Immutable.fromJS({
  "type": "FeatureCollection",
  "features": [
      {
          "type": "Feature",
          "properties": {
              "popupContent": "18th & California Light Rail Stop"
          },
          "geometry": {
              "type": "Point",
              "coordinates": [-104.98999178409576, 39.74683938093904]
          }
      },{
          "type": "Feature",
          "properties": {
              "popupContent": "20th & Welton Light Rail Stop"
          },
          "geometry": {
              "type": "Point",
              "coordinates": [-104.98689115047453, 39.747924136466565]
          }
      }
  ]
});

describe('GeoJSONTransform', () => {
  it('renders a map', () => {
    const geoComponent = mount(
      <GeoJSONTransform
        data={geojson}
      />
    );

    expect(geoComponent.instance().shouldComponentUpdate({
      theme: 'light',
      data: geojson,
    })).to.be.false;
    expect(geoComponent.find('.leaflet-container')).to.have.length(1);
  });

  it('updates the map', () => {
    const geoComponent = mount(
      <GeoJSONTransform
        data={geojson}
      />
    );

    const instance = geoComponent.instance();

    expect(instance.shouldComponentUpdate({
      theme: 'light',
      data: geojson,
    })).to.be.false;

    expect(geoComponent.find('.leaflet-container')).to.have.length(1);

    geoComponent.setProps({
      data: geojson.setIn(["features", 0, "properties", "popupContent"], "somewhere"),
      theme: 'dark',
    })

  });
});
<|endoftext|>


<commit_before>"use strict";
var assign = require('../../../../lib/utils').assign;

exports['Should correctly timeout socket operation and then correctly re-execute'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var Server = configuration.require.Server,
      ObjectId = configuration.require.BSON.ObjectId,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var server = null;
    var running = true;
    // Current index for the ismaster
    var currentStep = 0;
    // Primary stop responding
    var stopRespondingPrimary = false;

    // Default message fields
    var defaultFields = {
      "ismaster" : true,
      "maxBsonObjectSize" : 16777216,
      "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000,
      "localTime" : new Date(),
      "maxWireVersion" : 3,
      "minWireVersion" : 0,
      "ok" : 1
    }

    // Primary server states
    var serverIsMaster = [assign({}, defaultFields)];
    var timeoutPromise = function(timeout) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve();
        }, timeout);
      });
    }

    // Boot the mock
    co(function*() {
      server = yield mockupdb.createServer(37019, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield server.receive();

          // Get the document
          var doc = request.document;
          if(doc.ismaster && currentStep == 0) {
            request.reply(serverIsMaster[0]);
            currentStep += 1;
          } else if(doc.insert && currentStep == 1) {
            // Stop responding to any calls (emulate dropping packets on the floor)
            if(stopRespondingPrimary) {
              yield timeoutPromise(3000);
              continue;
            }

            currentStep += 1;
          } else if(doc.ismaster && currentStep == 2) {
            request.reply(serverIsMaster[0]);
          } else if(doc.insert && currentStep == 2) {
            request.reply({ok:1, n:doc.documents, lastOp: new Date()});
          }
        }
      });

      // Start dropping the packets
      setTimeout(function() {
        stopRespondingPrimary = true;
      }, 5000);
    });

    // Attempt to connect
    var replset = new Server({
      host: 'localhost',
      port: '37019',
      connectionTimeout: 5000,
      socketTimeout: 1000,
      size: 1
    });

    // Not done
    var done = false;
    // console.log("--------- -1")

    // Add event listeners
    replset.once('connect', function(_server) {
      // console.log("--------- 0")
      _server.insert('test.test', [{created:new Date()}], function(err, r) {
        // console.log("--------- 1")
        test.ok(err != null);
        // console.dir(err)

        function wait() {
          setTimeout(function() {
            _server.insert('test.test', [{created:new Date()}], function(err, r) {
              if(r && !done) {
                done = true;
                test.equal(37019, r.connection.port);
                replset.destroy({force:true});
                running = false;
                test.done();
              } else {
                wait();
              }
            });
          }, 500);
        }

        wait();
      });
    });

    replset.on('error', function(){});
    setTimeout(function() { replset.connect(); }, 100);
  }
}

exports['Should correctly recover from an immediate shutdown mid insert'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var Server = configuration.require.Server,
      ObjectId = configuration.require.BSON.ObjectId,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var server = null;
    var running = true;
    // Current index for the ismaster
    var currentStep = 0;
    // Should fail due to broken pipe
    var brokenPipe = false;

    // Default message fields
    var defaultFields = {
      "ismaster" : true,
      "maxBsonObjectSize" : 16777216,
      "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000,
      "localTime" : new Date(),
      "maxWireVersion" : 3,
      "minWireVersion" : 0,
      "ok" : 1
    }

    // Primary server states
    var serverIsMaster = [assign({}, defaultFields)];

    var timeoutPromise = function(timeout) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve();
        }, timeout);
      });
    }

    // Boot the mock
    var __server;
    co(function*() {
      __server = yield mockupdb.createServer(37017, 'localhost', {
        onRead: function(server, connection, buffer, bytesRead) {
          // Force EPIPE error
          if(currentStep == 1)  {
            // Destroy connection mid write
            connection.destroy();
            // Reset the mock to accept ismasters
            setTimeout(function() {
              currentStep += 1;
            }, 10);
            // Return connection was destroyed
            return true;
          }
        }
      });

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield __server.receive();
          // Get the document
          var doc = request.document;
          if(doc.ismaster && currentStep == 0) {
            currentStep += 1;
            request.reply(serverIsMaster[0]);
          } else if(doc.insert && currentStep == 2) {
            currentStep += 1;
            request.reply({ok:1, n:doc.documents, lastOp: new Date()});
          } else if(doc.ismaster) {
            request.reply(serverIsMaster[0]);
          }
        }
      });
    });

    // Attempt to connect
    var server = new Server({
      host: 'localhost',
      port: '37017',
      connectionTimeout: 3000,
      socketTimeout: 2000,
      size: 1
    });

    // console.log("!!!! server connect")
    var docs = [];
    // Create big insert message
    for(var i = 0; i < 1000; i++) {
      docs.push({
        a:i,
        string: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string1: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string2: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string3: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string4: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string5: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string6: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string7: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string8: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string9: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string10: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string11: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string12: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string13: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string14: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string15: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string16: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string17: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string18: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string19: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string20: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string21: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string22: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string23: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string24: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string25: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string26: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string27: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
        string28: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
      });
    }

    // Add event listeners
    server.once('connect', function(_server) {
      // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 0")
      _server.insert('test.test', docs, function(err, r) {
        // console.log("!!!! insert")
        test.ok(err != null);
        brokenPipe = true;
      });
    });

    // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1")

    server.once('reconnect', function(_server) {
      _server.insert('test.test', [{created:new Date()}], function(err, r) {
        test.ok(brokenPipe);
        _server.destroy();
        running = false;
        __server.destroy();
        test.done();
      });
    });

    server.on('error', function(){});
    setTimeout(function() { server.connect(); }, 100);
  }
}

// exports['Should not start double reconnect timeouts due to socket timeout during attemptReconnect'] = {
//   metadata: {
//     requires: {
//       generators: true,
//       topology: "single"
//     }
//   },
//
//   test: function(configuration, test) {
//     var Server = configuration.require.Server,
//       ObjectId = configuration.require.BSON.ObjectId,
//       co = require('co'),
//       mockupdb = require('../../../mock');
//
//     // Contain mock server
//     var server = null;
//     var running = true;
//     // Current index for the ismaster
//     var currentStep = 0;
//     // Primary stop responding
//     var stopRespondingPrimary = false;
//
//     // Default message fields
//     var defaultFields = {
//       "ismaster" : true,
//       "maxBsonObjectSize" : 16777216,
//       "maxMessageSizeBytes" : 48000000,
//       "maxWriteBatchSize" : 1000,
//       "localTime" : new Date(),
//       "maxWireVersion" : 3,
//       "minWireVersion" : 0,
//       "ok" : 1
//     }
//
//     // Primary server states
//     var serverIsMaster = [assign({}, defaultFields)];
//     var timeoutPromise = function(timeout) {
//       return new Promise(function(resolve, reject) {
//         setTimeout(function() {
//           resolve();
//         }, timeout);
//       });
//     }
//
//     // Boot the mock
//     co(function*() {
//       server = yield mockupdb.createServer(37019, 'localhost');
//
//       // Primary state machine
//       co(function*() {
//         while(running) {
//           if(currentStep == 1) {
//             console.log("--- timeout 0")
//             yield timeoutPromise(5000);
//             console.log("--- timeout 1")
//             continue;
//           }
//
//           var request = yield server.receive();
//
//           // Get the document
//           var doc = request.document;
//           if(doc.ismaster && currentStep == 0) {
//             request.reply(serverIsMaster[0]);
//             currentStep += 1;
//           }
//         }
//       });
//
//       // // Start dropping the packets
//       // setTimeout(function() {
//       //   stopRespondingPrimary = true;
//       // }, 5000);
//     });
//
//     // Attempt to connect
//     var server = new Server({
//       host: 'localhost',
//       port: 37019,
//       connectionTimeout: 2000,
//       socketTimeout: 1000,
//       size: 1
//     });
//
//     // Not done
//     var done = false;
//
//     // Add event listeners
//     server.once('connect', function(_server) {
//       console.log("=============== connect")
//       // _server.insert('test.test', [{created:new Date()}], function(err, r) {
//       //   test.ok(err != null);
//       //   // console.dir(err)
//       //
//       //   function wait() {
//       //     setTimeout(function() {
//       //       _server.insert('test.test', [{created:new Date()}], function(err, r) {
//       //         if(r && !done) {
//       //           done = true;
//       //           test.equal(37019, r.connection.port);
//       //           replset.destroy();
//       //           running = false;
//       //           test.done();
//       //         } else {
//       //           wait();
//       //         }
//       //       });
//       //     }, 500);
//       //   }
//       //
//       //   wait();
//       // });
//     });
//
//     server.on('error', function(){});
//     server.connect();
//   }
// }
<commit_msg>test(single_mocks): converted `timeout` tests to mocha style<commit_after>'use strict';
var expect = require('chai').expect,
    assign = require('../../../../lib/utils').assign,
    co = require('co');

var timeoutPromise = function(timeout) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() { resolve(); }, timeout);
  });
};

describe('Single Timeout (mocks)', function() {
  it('Should correctly timeout socket operation and then correctly re-execute', {
    metadata: {
      requires: {
        generators: true,
        topology: 'single'
      }
    },

    test: function(done) {
      var Server = this.configuration.mongo.Server,
          mockupdb = require('../../../mock');

      // Contain mock server
      var server = null;
      var running = true;
      // Current index for the ismaster
      var currentStep = 0;
      // Primary stop responding
      var stopRespondingPrimary = false;

      // Default message fields
      var defaultFields = {
        'ismaster': true,
        'maxBsonObjectSize': 16777216,
        'maxMessageSizeBytes': 48000000,
        'maxWriteBatchSize': 1000,
        'localTime': new Date(),
        'maxWireVersion': 3,
        'minWireVersion': 0,
        'ok': 1
      };

      // Primary server states
      var serverIsMaster = [assign({}, defaultFields)];

      // Boot the mock
      co(function*() {
        server = yield mockupdb.createServer(37019, 'localhost');

        // Primary state machine
        co(function*() {
          while (running) {
            var request = yield server.receive();

            // Get the document
            var doc = request.document;
            if (doc.ismaster && currentStep === 0) {
              request.reply(serverIsMaster[0]);
              currentStep += 1;
            } else if (doc.insert && currentStep === 1) {
              // Stop responding to any calls (emulate dropping packets on the floor)
              if (stopRespondingPrimary) {
                yield timeoutPromise(3000);
                continue;
              }

              currentStep += 1;
            } else if (doc.ismaster && currentStep === 2) {
              request.reply(serverIsMaster[0]);
            } else if (doc.insert && currentStep === 2) {
              request.reply({ok: 1, n: doc.documents, lastOp: new Date()});
            }
          }
        });

        // Start dropping the packets
        setTimeout(function() {
          stopRespondingPrimary = true;
        }, 5000);
      });

      // Attempt to connect
      var replset = new Server({
        host: 'localhost',
        port: '37019',
        connectionTimeout: 5000,
        socketTimeout: 1000,
        size: 1
      });

      // Not done
      var finished = false;

      // Add event listeners
      replset.once('connect', function(_server) {
        _server.insert('test.test', [{ created: new Date() }], function(err, r) {
          expect(err).to.exist;

          function wait() {
            setTimeout(function() {
              _server.insert('test.test', [{ created: new Date() }], function(_err, _r) {
                if (_r && !finished) {
                  finished = true;
                  expect(_r.connection.port).to.equal('37019');
                  replset.destroy({ force: true });
                  running = false;
                  done();
                } else {
                  wait();
                }
              });
            }, 500);
          }

          wait();
        });
      });

      replset.on('error', done);
      setTimeout(function() { replset.connect(); }, 100);
    }
  });

  it('Should correctly recover from an immediate shutdown mid insert', {
    metadata: {
      requires: {
        generators: true,
        topology: 'single'
      }
    },

    test: function(done) {
      var Server = this.configuration.mongo.Server,
          mockupdb = require('../../../mock');

      // Contain mock server
      var server = null;
      var running = true;
      // Current index for the ismaster
      var currentStep = 0;
      // Should fail due to broken pipe
      var brokenPipe = false;

      // Default message fields
      var defaultFields = {
        'ismaster': true,
        'maxBsonObjectSize': 16777216,
        'maxMessageSizeBytes': 48000000,
        'maxWriteBatchSize': 1000,
        'localTime': new Date(),
        'maxWireVersion': 3,
        'minWireVersion': 0,
        'ok': 1
      };

      // Primary server states
      var serverIsMaster = [assign({}, defaultFields)];

      // Boot the mock
      var __server;
      co(function*() {
        __server = yield mockupdb.createServer(37017, 'localhost', {
          onRead: function(_server, connection, buffer, bytesRead) {
            // Force EPIPE error
            if (currentStep === 1)  {
              // Destroy connection mid write
              connection.destroy();
              // Reset the mock to accept ismasters
              setTimeout(function() {
                currentStep += 1;
              }, 10);
              // Return connection was destroyed
              return true;
            }
          }
        });

        // Primary state machine
        co(function*() {
          while (running) {
            var request = yield __server.receive();
            // Get the document
            var doc = request.document;
            if (doc.ismaster && currentStep === 0) {
              currentStep += 1;
              request.reply(serverIsMaster[0]);
            } else if (doc.insert && currentStep === 2) {
              currentStep += 1;
              request.reply({ok: 1, n: doc.documents, lastOp: new Date()});
            } else if (doc.ismaster) {
              request.reply(serverIsMaster[0]);
            }
          }
        });
      });

      // Attempt to connect
      server = new Server({
        host: 'localhost',
        port: '37017',
        connectionTimeout: 3000,
        socketTimeout: 2000,
        size: 1
      });

      // console.log('!!!! server connect')
      var docs = [];
      // Create big insert message
      for (var i = 0; i < 1000; i++) {
        docs.push({
          a: i,
          string: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string1: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string2: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string3: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string4: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string5: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string6: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string7: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string8: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string9: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string10: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string11: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string12: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string13: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string14: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string15: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string16: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string17: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string18: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string19: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string20: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string21: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string22: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string23: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string24: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string25: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string26: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string27: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world',
          string28: 'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world'
        });
      }

      // Add event listeners
      server.once('connect', function(_server) {
        _server.insert('test.test', docs, function(err, r) {
          expect(err).to.exist;
          brokenPipe = true;
        });
      });

      server.once('reconnect', function(_server) {
        _server.insert('test.test', [{ created: new Date() }], function(err, r) {
          expect(brokenPipe).to.equal(true);
          _server.destroy();
          running = false;
          __server.destroy();
          done();
        });
      });

      server.on('error', done);
      setTimeout(function() { server.connect(); }, 100);
    }
  });

  /* change to `it.skip` when it's supported in metamocha
  it('Should not start double reconnect timeouts due to socket timeout during attemptReconnect', {
    metadata: {
      requires: {
        generators: true,
        topology: 'single'
      }
    },

    test: function(done) {
      var Server = this.configuration.mongo.Server,
          mockupdb = require('../../../mock');

      // Contain mock server
      var server = null;
      var running = true;
      // Current index for the ismaster
      var currentStep = 0;

      // Default message fields
      var defaultFields = {
        'ismaster': true,
        'maxBsonObjectSize': 16777216,
        'maxMessageSizeBytes': 48000000,
        'maxWriteBatchSize': 1000,
        'localTime': new Date(),
        'maxWireVersion': 3,
        'minWireVersion': 0,
        'ok': 1
      };

      // Primary server states
      var serverIsMaster = [assign({}, defaultFields)];

      // Boot the mock
      co(function*() {
        server = yield mockupdb.createServer(37019, 'localhost');

        // Primary state machine
        co(function*() {
          while (running) {
            if (currentStep === 1) {
              yield timeoutPromise(5000);
              continue;
            }

            var request = yield server.receive();

            // Get the document
            var doc = request.document;
            if (doc.ismaster && currentStep === 0) {
              request.reply(serverIsMaster[0]);
              currentStep += 1;
            }
          }
        });
      });

      // Attempt to connect
      server = new Server({
        host: 'localhost',
        port: 37019,
        connectionTimeout: 2000,
        socketTimeout: 1000,
        size: 1
      });

      // Add event listeners
      server.once('connect', function(_server) {
        // _server.insert('test.test', [{created:new Date()}], function(err, r) {
        //   test.ok(err != null);
        //   // console.dir(err)
        //
        //   function wait() {
        //     setTimeout(function() {
        //       _server.insert('test.test', [{created:new Date()}], function(err, r) {
        //         if (r && !done) {
        //           done = true;
        //           test.equal(37019, r.connection.port);
        //           replset.destroy();
        //           running = false;
        //           test.done();
        //         } else {
        //           wait();
        //         }
        //       });
        //     }, 500);
        //   }
        //
        //   wait();
        // });
      });

      server.on('error', done);
      server.connect();
    }
  });
  */
});
<|endoftext|>


<commit_before>$(document).ready(function(){
		draw();
});

//function draw
function draw() {
	//triangle 1
	var x11 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y11 = Math.floor(Math.random() * (200 - 100 + 10)) + 10
		var x12 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y12 = Math.floor(Math.random() * (200 - 100 + 10)) + 10

		//triangle 2
		var x21 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y21 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		var x22 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y22 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		//triangle 3
		var x31 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y31 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		var x32 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y32 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		//triangle 4
		var x41 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y41 = Math.floor(Math.random() * (700 - 650 + 10)) + 20
		var x42 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y42 = Math.floor(Math.random() * (700 - 650 + 10)) + 20

    var maxAngle = 0;
    var maxAngleAnswer = "";
    var minAngle = 360;
    var minAngleAnswer = "";
    //calculate angle A
    var A12 = Math.sqrt(Math.pow((x11 - 100), 2) + Math.pow((y11 - 15), 2));
	var A13 = Math.sqrt(Math.pow((x11 - x12), 2) + Math.pow((y11 - y12), 2));
	var A23 = Math.sqrt(Math.pow((100 - x12), 2) + Math.pow((15 - y12), 2));
	var resultDegreeA = Math.acos(((Math.pow(A12, 2)) + (Math.pow(A13, 2)) - (Math.pow(A23, 2))) / (2 * A12 * A13)) * 180 / Math.PI;

	document.getElementById('A').innerHTML = "A = " + (resultDegreeA.toFixed(2))

    if(resultDegreeA > maxAngle){
        maxAngleAnswer = "A"
        maxAngle = resultDegreeA
    }

    if(resultDegreeA < minAngle){
        minAngleAnswer = "A"
        minAngle = resultDegreeA
    }

    //calculate angle B

    var B12 = Math.sqrt(Math.pow((x21 - 300), 2) + Math.pow((y21 - 50), 2));
	var B13 = Math.sqrt(Math.pow((x21 - x22), 2) + Math.pow((y21 - y22), 2));
	var B23 = Math.sqrt(Math.pow((300 - x22), 2) + Math.pow((50 - y22), 2));
	var resultDegreeB = Math.acos(((Math.pow(B12, 2)) + (Math.pow(B13, 2)) - (Math.pow(B23, 2))) / (2 * B12 * B13)) * 180 / Math.PI;

	document.getElementById('B').innerHTML = "B = " + (resultDegreeB.toFixed(2))

    if(resultDegreeB > maxAngle){
        maxAngleAnswer = "B"
        maxAngle = resultDegreeB
    }

    if(resultDegreeB < minAngle){
        minAngleAnswer = "B"
        minAngle = resultDegreeB
    }

		//calculate angle C

		var C12 = Math.sqrt(Math.pow((x31 - 500), 2) + Math.pow((y31 - 50), 2));
	var C13 = Math.sqrt(Math.pow((x31 - x32), 2) + Math.pow((y31 - y32), 2));
	var C23 = Math.sqrt(Math.pow((500 - x32), 2) + Math.pow((50 - y32), 2));
	var resultDegreeC = Math.acos(((Math.pow(C12, 2)) + (Math.pow(C13, 2)) - (Math.pow(C23, 2))) / (2 * C12 * C13)) * 180 / Math.PI;

	document.getElementById('C').innerHTML = "C = " + (resultDegreeC.toFixed(2))

    if(resultDegreeC > maxAngle){
        maxAngleAnswer = "C"
        maxAngle = resultDegreeC
    }

    if(resultDegreeC < minAngle){
        minAngleAnswer = "C"
        minAngle = resultDegreeC
    }

		//calculate angle D

    var D12 = Math.sqrt(Math.pow((x41 - 700), 2) + Math.pow((y41 - 50), 2));
	var D13 = Math.sqrt(Math.pow((x41 - x42), 2) + Math.pow((y41 - y42), 2));
	var D23 = Math.sqrt(Math.pow((700 - x42), 2) + Math.pow((50 - y42), 2));
	var resultDegreeD = Math.acos(((Math.pow(D12, 2)) + (Math.pow(D13, 2)) - (Math.pow(D23, 2))) / (2 * D12 * D13)) * 180 / Math.PI;

	document.getElementById('D').innerHTML = "D = " + (resultDegreeD.toFixed(2))

    if(resultDegreeD > maxAngle){
        maxAngleAnswer = "D"
        maxAngle = resultDegreeD
    }

    if(resultDegreeD < minAngle){
        minAngleAnswer = "D"
        minAngle = resultDegreeD
    }

    var canvas = document.getElementById('canvas');
	if (canvas.getContext) {
		var ctx = canvas.getContext('2d');

		ctx.beginPath();
		ctx.moveTo(250, 0);
		ctx.lineTo(250, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(450, 0);
		ctx.lineTo(450, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(650, 0);
		ctx.lineTo(650, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(100, 15);
		ctx.lineTo(x11, y11);
		ctx.lineTo(x12, y12);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(300, 50);
		ctx.lineTo(x21, y21);
		ctx.lineTo(x22, y22);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(500, 50);
		ctx.lineTo(x31, y31);
		ctx.lineTo(x32, y32);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(700, 50);
		ctx.lineTo(x41, y41);
		ctx.lineTo(x42, y42);
		ctx.stroke();

	}

    var choices = ["A", "B", "C", "D"]
    var choiceToDegree = {};
    choiceToDegree["A"] = resultDegreeA
    choiceToDegree["B"] = resultDegreeB
    choiceToDegree["C"] = resultDegreeC
    choiceToDegree["D"] = resultDegreeD

    var indexToRemove1 = choices.indexOf(maxAngleAnswer)
    choices.splice(indexToRemove1, 1)
    var indexToRemove2 = choices.indexOf(minAngleAnswer)
        choices.splice(indexToRemove2, 1)

    var answer1;
    var answer2;
    var answer3;
    var answer4;

    var correctAnswer;
    if(choiceToDegree[choices[0]] < choiceToDegree[choices[1]]){
        correctAnswer = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer1 = choices[0] +"< "+ minAngleAnswer + "< " + choices[1] + "< " +maxAngleAnswer
        answer2 = choices[0] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[1]
        answer3 = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[0] + "< " + maxAngleAnswer + "< " + choices[1]
    }
    else{
        correctAnswer = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer1 = choices[1] +"< "+ minAngleAnswer + "< " + choices[0] + "< " +maxAngleAnswer
        answer2 = choices[1] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[0]
        answer3 = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[1] + "< " + maxAngleAnswer + "< " + choices[0]
    }

    var answers = [answer1, answer2, answer3, answer4]
    var shuffledAnswers = shuffle(answers)

    createAnswers(shuffledAnswers, correctAnswer);

}

 // Creates a list of the answer choices as radio inputs
function createAnswers(answers, correctanswer) {
    var radioList = $('
');
    var item;
    var input = '';
    for (var i = 0; i < answers.length; i++) {
      item = $('
');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += answers[i];
	input += '<button onclick="checkAnswer()">Submit Answer</button>';
      item.append(input);
      radioList.append(item);
    }
    $("#choices").append(radioList);

    var correctAnswer = '
' +"Correct Answer is "+ correctanswer + "
"
    $("#choices").append(correctAnswer);
}

//Implementation of the Fisher Yates Shuffle Algorithm
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

///////////////////Sort array//////////////////////

 var array = [5,7,8,2,3,1,6];
 var temp;
 function sort(array) {
 	for(var i=0; i<array.length; i++) {
 		for (var j=0; j<array.length; j++) {
 			if (array[i] < array[j] && i!=j) {
 				temp = array[j];
 				array[j] = array[i];
 				array[i] = temp;

 			}

 		}
 	}
 	return array;
 }

 var sortedArray = sort(array);
document.getElementById('results').innerHTML += sortedArray;

function showAnswer() {
	var x = document.getElementById('showResult');
	if (x.style.display === 'none') {
		x.style.display = 'block';
	} else {
		x.style.display = 'none';
 	}
}
<commit_msg>Update angles.js<commit_after>$(document).ready(function(){
		draw();
});

//function draw
function draw() {
	//triangle 1
	var x11 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y11 = Math.floor(Math.random() * (200 - 100 + 10)) + 10
		var x12 = Math.floor(Math.random() * (200 - 150 + 10)) + 150
		var y12 = Math.floor(Math.random() * (200 - 100 + 10)) + 10

		//triangle 2
		var x21 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y21 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		var x22 = Math.floor(Math.random() * (400 - 350 + 10)) + 350
		var y22 = Math.floor(Math.random() * (200 - 100 + 10)) + 20
		//triangle 3
		var x31 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y31 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		var x32 = Math.floor(Math.random() * (800 - 750 + 10)) + 500
		var y32 = Math.floor(Math.random() * (600 - 500 + 10)) + 20
		//triangle 4
		var x41 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y41 = Math.floor(Math.random() * (700 - 650 + 10)) + 20
		var x42 = Math.floor(Math.random() * (950 - 880 + 10)) + 700
		var y42 = Math.floor(Math.random() * (700 - 650 + 10)) + 20

    var maxAngle = 0;
    var maxAngleAnswer = "";
    var minAngle = 360;
    var minAngleAnswer = "";
    //calculate angle A
    var A12 = Math.sqrt(Math.pow((x11 - 100), 2) + Math.pow((y11 - 15), 2));
	var A13 = Math.sqrt(Math.pow((x11 - x12), 2) + Math.pow((y11 - y12), 2));
	var A23 = Math.sqrt(Math.pow((100 - x12), 2) + Math.pow((15 - y12), 2));
	var resultDegreeA = Math.acos(((Math.pow(A12, 2)) + (Math.pow(A13, 2)) - (Math.pow(A23, 2))) / (2 * A12 * A13)) * 180 / Math.PI;

	document.getElementById('A').innerHTML = "A = " + (resultDegreeA.toFixed(2))

    if(resultDegreeA > maxAngle){
        maxAngleAnswer = "A"
        maxAngle = resultDegreeA
    }

    if(resultDegreeA < minAngle){
        minAngleAnswer = "A"
        minAngle = resultDegreeA
    }

    //calculate angle B

    var B12 = Math.sqrt(Math.pow((x21 - 300), 2) + Math.pow((y21 - 50), 2));
	var B13 = Math.sqrt(Math.pow((x21 - x22), 2) + Math.pow((y21 - y22), 2));
	var B23 = Math.sqrt(Math.pow((300 - x22), 2) + Math.pow((50 - y22), 2));
	var resultDegreeB = Math.acos(((Math.pow(B12, 2)) + (Math.pow(B13, 2)) - (Math.pow(B23, 2))) / (2 * B12 * B13)) * 180 / Math.PI;

	document.getElementById('B').innerHTML = "B = " + (resultDegreeB.toFixed(2))

    if(resultDegreeB > maxAngle){
        maxAngleAnswer = "B"
        maxAngle = resultDegreeB
    }

    if(resultDegreeB < minAngle){
        minAngleAnswer = "B"
        minAngle = resultDegreeB
    }

		//calculate angle C

		var C12 = Math.sqrt(Math.pow((x31 - 500), 2) + Math.pow((y31 - 50), 2));
	var C13 = Math.sqrt(Math.pow((x31 - x32), 2) + Math.pow((y31 - y32), 2));
	var C23 = Math.sqrt(Math.pow((500 - x32), 2) + Math.pow((50 - y32), 2));
	var resultDegreeC = Math.acos(((Math.pow(C12, 2)) + (Math.pow(C13, 2)) - (Math.pow(C23, 2))) / (2 * C12 * C13)) * 180 / Math.PI;

	document.getElementById('C').innerHTML = "C = " + (resultDegreeC.toFixed(2))

    if(resultDegreeC > maxAngle){
        maxAngleAnswer = "C"
        maxAngle = resultDegreeC
    }

    if(resultDegreeC < minAngle){
        minAngleAnswer = "C"
        minAngle = resultDegreeC
    }

		//calculate angle D

    var D12 = Math.sqrt(Math.pow((x41 - 700), 2) + Math.pow((y41 - 50), 2));
	var D13 = Math.sqrt(Math.pow((x41 - x42), 2) + Math.pow((y41 - y42), 2));
	var D23 = Math.sqrt(Math.pow((700 - x42), 2) + Math.pow((50 - y42), 2));
	var resultDegreeD = Math.acos(((Math.pow(D12, 2)) + (Math.pow(D13, 2)) - (Math.pow(D23, 2))) / (2 * D12 * D13)) * 180 / Math.PI;

	document.getElementById('D').innerHTML = "D = " + (resultDegreeD.toFixed(2))

    if(resultDegreeD > maxAngle){
        maxAngleAnswer = "D"
        maxAngle = resultDegreeD
    }

    if(resultDegreeD < minAngle){
        minAngleAnswer = "D"
        minAngle = resultDegreeD
    }

    var canvas = document.getElementById('canvas');
	if (canvas.getContext) {
		var ctx = canvas.getContext('2d');

		ctx.beginPath();
		ctx.moveTo(250, 0);
		ctx.lineTo(250, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(450, 0);
		ctx.lineTo(450, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(650, 0);
		ctx.lineTo(650, 150);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(100, 15);
		ctx.lineTo(x11, y11);
		ctx.lineTo(x12, y12);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(300, 50);
		ctx.lineTo(x21, y21);
		ctx.lineTo(x22, y22);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(500, 50);
		ctx.lineTo(x31, y31);
		ctx.lineTo(x32, y32);
		ctx.stroke();

		ctx.beginPath();
		ctx.moveTo(700, 50);
		ctx.lineTo(x41, y41);
		ctx.lineTo(x42, y42);
		ctx.stroke();

	}

    var choices = ["A", "B", "C", "D"]
    var choiceToDegree = {};
    choiceToDegree["A"] = resultDegreeA
    choiceToDegree["B"] = resultDegreeB
    choiceToDegree["C"] = resultDegreeC
    choiceToDegree["D"] = resultDegreeD

    var indexToRemove1 = choices.indexOf(maxAngleAnswer)
    choices.splice(indexToRemove1, 1)
    var indexToRemove2 = choices.indexOf(minAngleAnswer)
        choices.splice(indexToRemove2, 1)

    var answer1;
    var answer2;
    var answer3;
    var answer4;

    var correctAnswer;
    if(choiceToDegree[choices[0]] < choiceToDegree[choices[1]]){
        correctAnswer = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer1 = choices[0] +"< "+ minAngleAnswer + "< " + choices[1] + "< " +maxAngleAnswer
        answer2 = choices[0] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[1]
        answer3 = minAngleAnswer +"< "+ choices[0] + "< " + choices[1] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[0] + "< " + maxAngleAnswer + "< " + choices[1]
    }
    else{
        correctAnswer = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer1 = choices[1] +"< "+ minAngleAnswer + "< " + choices[0] + "< " +maxAngleAnswer
        answer2 = choices[1] +"< "+ minAngleAnswer + "< " + maxAngleAnswer  + "< " + choices[0]
        answer3 = minAngleAnswer +"< "+ choices[1] + "< " + choices[0] + "< " + maxAngleAnswer
        answer4 = minAngleAnswer +"< "+ choices[1] + "< " + maxAngleAnswer + "< " + choices[0]
    }

    var answers = [answer1, answer2, answer3, answer4]
    var shuffledAnswers = shuffle(answers)

    createAnswers(shuffledAnswers, correctAnswer);

}

 // Creates a list of the answer choices as radio inputs
function createAnswers(answers, correctanswer) {
    var radioList = $('
');
    var item;
    var input = '';
    for (var i = 0; i < answers.length; i++) {
      item = $('
');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += answers[i];
	input += '<button onclick="checkAnswer()">Submit Answer</button>';
      item.append(input);
      radioList.append(item);
    }
    $("#choices").append(radioList);

    var correctAnswer = '
' +"Correct Answer is "+ correctanswer + "
"
    $("#choices").append(correctAnswer);
}

function checkAnswer() {
	alert ("OK GOOD!");

//Implementation of the Fisher Yates Shuffle Algorithm
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

///////////////////Sort array//////////////////////

 var array = [5,7,8,2,3,1,6];
 var temp;
 function sort(array) {
 	for(var i=0; i<array.length; i++) {
 		for (var j=0; j<array.length; j++) {
 			if (array[i] < array[j] && i!=j) {
 				temp = array[j];
 				array[j] = array[i];
 				array[i] = temp;

 			}

 		}
 	}
 	return array;
 }

 var sortedArray = sort(array);
document.getElementById('results').innerHTML += sortedArray;

function showAnswer() {
	var x = document.getElementById('showResult');
	if (x.style.display === 'none') {
		x.style.display = 'block';
	} else {
		x.style.display = 'none';
 	}
}
<|endoftext|>


<commit_before>var asteriskAttack = (function(aa) {

  function increaseAttackSpeed() {
    aa.game.generationSpeed -= 50;
    window.clearInterval(aa.loops.attack);
    aa.loops.attack = setInterval(attack, aa.game.generationSpeed);
  }

  function buildAsterisk() {
    var colors = ['yellow', 'gold', 'orange', 'orangered', 'red', 'deeppink', 'hotpink', 'fuchsia', 'lightskyblue', 'dodgerblue', 'blue']
      , smallestSize = 12
      , largestSize = 42;

    return '
*
'
  }

  function attack() {
    var asterisk = $(buildAsterisk())
      , speed    = aa.randomInRange(aa.game.asteriskSpeed, aa.game.asteriskSpeed + 5000);

    aa.game.asterisks[aa.game.asteriskCount] = asterisk;
    aa.dom.attackZone.prepend(asterisk);

    asterisk.animate({ top: "700px" }, speed, "linear");
  }

  function completeAttack(asteriskId, thwarted) {
    var a
      , pos
      , clone;

    a = aa.game.asterisks[asteriskId];

    if (thwarted) {
      aa.stats.score++;

      clone = a.clone();
      clone.insertAfter(a).animate({
        'opacity': '0', 'top': (a.position().top - 50)
      }, 150, function() {
        clone.remove();
      })
    }

    if (thwarted && aa.stats.score % 5 === 0) {
      increaseAttackSpeed();
    }
    else if (!thwarted) {
      aa.dom.background.effect("bounce", {}, 500);
    }

    a.remove();
    delete aa.game.asterisks[asteriskId];

    aa.updateScore();
  }

  aa.attack = attack;
  aa.completeAttack = completeAttack;
  aa.increaseAttackSpeed = increaseAttackSpeed;

  return aa;

})(asteriskAttack);

<commit_msg>Slow down background bounce at game over<commit_after>var asteriskAttack = (function(aa) {

  function increaseAttackSpeed() {
    aa.game.generationSpeed -= 50;
    window.clearInterval(aa.loops.attack);
    aa.loops.attack = setInterval(attack, aa.game.generationSpeed);
  }

  function buildAsterisk() {
    var colors = ['yellow', 'gold', 'orange', 'orangered', 'red', 'deeppink', 'hotpink', 'fuchsia', 'lightskyblue', 'dodgerblue', 'blue']
      , smallestSize = 12
      , largestSize = 42;

    return '
*
'
  }

  function attack() {
    var asterisk = $(buildAsterisk())
      , speed    = aa.randomInRange(aa.game.asteriskSpeed, aa.game.asteriskSpeed + 5000);

    aa.game.asterisks[aa.game.asteriskCount] = asterisk;
    aa.dom.attackZone.prepend(asterisk);

    asterisk.animate({ top: "700px" }, speed, "linear");
  }

  function completeAttack(asteriskId, thwarted) {
    var a
      , pos
      , clone;

    a = aa.game.asterisks[asteriskId];

    if (thwarted) {
      aa.stats.score++;

      clone = a.clone();
      clone.insertAfter(a).animate({
        'opacity': '0', 'top': (a.position().top - 50)
      }, 150, function() {
        clone.remove();
      })
    }

    if (thwarted && aa.stats.score % 5 === 0) {
      increaseAttackSpeed();
    }
    else if (!thwarted) {
      aa.dom.background.effect("bounce", {}, 750);
    }

    a.remove();
    delete aa.game.asterisks[asteriskId];

    aa.updateScore();
  }

  aa.attack = attack;
  aa.completeAttack = completeAttack;
  aa.increaseAttackSpeed = increaseAttackSpeed;

  return aa;

})(asteriskAttack);

<|endoftext|>


<commit_before>const format = require('kindred-shader-formatter')
const staticModule = require('static-module')
const isRequire = require('is-require')()
const combine = require('stream-combiner')
const through = require('through2')
const glslify = require('glslify')
const shortid = require('shortid')
const falafel = require('falafel')
const xtend = require('xtend')
const path = require('path')

const parseOptions = {
  ecmaVersion: 6,
  sourceType: 'module',
  allowReserved: true,
  allowReturnOutsideFunction: true,
  allowHashBang: true
}

module.exports = transform

function transform (filename, opts) {
  return combine(
    templateTransform(filename, opts),
    fileTransform(filename, opts)
  )
}

function templateTransform (filename, transformOpts) {
  var stream = through(write, flush)
  var cwd = path.dirname(filename)
  var buffer = []

  return stream

  function write (chunk, _, next) {
    buffer.push(chunk)
    next()
  }

  function flush () {
    var src = buffer.join('')
    var requires = []
    var queue = 0

    if (src.indexOf('kindred-shader') === -1) {
      this.push(src)
      this.push(null)
      return
    }

    try {
      src = falafel(src, parseOptions, function (node) {
        scrapeRequires(node)
        scrapeTemplates(node)
      })
    } catch (e) {
      return stream.emit('error', e)
    }

    checkQueue()

    function scrapeRequires (node) {
      if (!isRequire(node)) return

      var args = node.arguments
      if (args.length < 1) return

      var target = args[0]
      if (target.type !== 'Literal') return

      var value = target.value
      if (value !== 'kindred-shader') return
      if (node.parent.type !== 'VariableDeclarator') return
      if (node.parent.id.type !== 'Identifier') return

      var varName = node.parent.id.name
      requires.push(varName)
    }

    function scrapeTemplates (node) {
      if (node.type !== 'TaggedTemplateExpression') return
      if (node.tag.type !== 'Identifier') return
      if (requires.indexOf(node.tag.name) === -1) return

      var textBits = node.quasi.quasis
      var expressions = node.quasi.expressions
      var replaceMap = []
      var combined = []

      for (var i = 0; i + 1 < textBits.length; i++) {
        var mapping = '_' + shortid.generate()
        var expr = expressions[i].source().trim()
        replaceMap[expr] = replaceMap[expr] || mapping
        combined.push(textBits[i].source())
        combined.push(mapping)
      }

      combined.push(textBits[textBits.length - 1].source())
      combined = combined.join('')
      queue++

      glslify.bundle(combined, {
        cwd: cwd,
        inline: true
      }, function (err, source) {
        if (err) return stream.emit('error', err)

        var jsReplacement = splitAndFormat(source, replaceMap)
        node.update(jsReplacement)
        checkQueue(queue--)
      }).on('file', function (file) {
        stream.emit('file', file)
      })
    }

    function checkQueue () {
      if (queue) return

      stream.push(src.toString())
      stream.push(null)
    }
  }
}

function fileTransform (filename, transformOpts) {
  var cwd = path.dirname(filename)
  var stream = staticModule({
    'kindred-shader': {
      file: replaceStream,
      raw: function (vert, frag) {
        var prefix = '(require("kindred-shader/raw")('
        var args = [JSON.stringify(vert), JSON.stringify(frag)]
        return prefix + args.join(',') + '))'
      }
    }
  }, {
    vars: {
      __dirname: cwd,
      __filename: filename
    },
    varModules: {
      path: path
    }
  })

  return stream

  function replaceStream (glslFile, opts) {
    var replacer = through()

    opts = xtend({
      basedir: cwd
    }, transformOpts || {}, opts || {})

    glslify.bundle(glslFile, opts, function (err, bundled) {
      if (err) return stream.emit('error', err)

      var jsReplacement = splitAndFormat(bundled)
      replacer.push(jsReplacement)
      replacer.push(null)
    }).on('file', function (file) {
      stream.emit('file', file)
    })

    return replacer
  }
}

function splitAndFormat (source, replaceMap) {
  var vert = JSON.stringify(format.vert(source))
  var frag = JSON.stringify(format.frag(source))
  var bundled = ''

  if (replaceMap) {
    Object.keys(replaceMap).forEach(function (value) {
      var key = replaceMap[value]

      vert = vert.replace(new RegExp(key, 'g'), '"+(' + value + ')+"')
      frag = frag.replace(new RegExp(key, 'g'), '"+(' + value + ')+"')
    })
  }

  bundled += 'require("kindred-shader/raw")('
  bundled += vert
  bundled += ','
  bundled += frag
  bundled += ')'

  return bundled
}
<commit_msg>fix: resolve glslify dirs correctly<commit_after>const format = require('kindred-shader-formatter')
const staticModule = require('static-module')
const isRequire = require('is-require')()
const combine = require('stream-combiner')
const through = require('through2')
const glslify = require('glslify')
const shortid = require('shortid')
const falafel = require('falafel')
const xtend = require('xtend')
const path = require('path')

const parseOptions = {
  ecmaVersion: 6,
  sourceType: 'module',
  allowReserved: true,
  allowReturnOutsideFunction: true,
  allowHashBang: true
}

module.exports = transform

function transform (filename, opts) {
  return combine(
    templateTransform(filename, opts),
    fileTransform(filename, opts)
  )
}

function templateTransform (filename, transformOpts) {
  var stream = through(write, flush)
  var cwd = path.dirname(filename)
  var buffer = []

  return stream

  function write (chunk, _, next) {
    buffer.push(chunk)
    next()
  }

  function flush () {
    var src = buffer.join('')
    var requires = []
    var queue = 0

    if (src.indexOf('kindred-shader') === -1) {
      this.push(src)
      this.push(null)
      return
    }

    try {
      src = falafel(src, parseOptions, function (node) {
        scrapeRequires(node)
        scrapeTemplates(node)
      })
    } catch (e) {
      return stream.emit('error', e)
    }

    checkQueue()

    function scrapeRequires (node) {
      if (!isRequire(node)) return

      var args = node.arguments
      if (args.length < 1) return

      var target = args[0]
      if (target.type !== 'Literal') return

      var value = target.value
      if (value !== 'kindred-shader') return
      if (node.parent.type !== 'VariableDeclarator') return
      if (node.parent.id.type !== 'Identifier') return

      var varName = node.parent.id.name
      requires.push(varName)
    }

    function scrapeTemplates (node) {
      if (node.type !== 'TaggedTemplateExpression') return
      if (node.tag.type !== 'Identifier') return
      if (requires.indexOf(node.tag.name) === -1) return

      var textBits = node.quasi.quasis
      var expressions = node.quasi.expressions
      var replaceMap = []
      var combined = []

      for (var i = 0; i + 1 < textBits.length; i++) {
        var mapping = '_' + shortid.generate()
        var expr = expressions[i].source().trim()
        replaceMap[expr] = replaceMap[expr] || mapping
        combined.push(textBits[i].source())
        combined.push(mapping)
      }

      combined.push(textBits[textBits.length - 1].source())
      combined = combined.join('')
      queue++

      glslify.bundle(combined, {
        basedir: cwd,
        inline: true
      }, function (err, source) {
        if (err) return stream.emit('error', err)

        var jsReplacement = splitAndFormat(source, replaceMap)
        node.update(jsReplacement)
        checkQueue(queue--)
      }).on('file', function (file) {
        stream.emit('file', file)
      })
    }

    function checkQueue () {
      if (queue) return

      stream.push(src.toString())
      stream.push(null)
    }
  }
}

function fileTransform (filename, transformOpts) {
  var cwd = path.dirname(filename)
  var stream = staticModule({
    'kindred-shader': {
      file: replaceStream,
      raw: function (vert, frag) {
        var prefix = '(require("kindred-shader/raw")('
        var args = [JSON.stringify(vert), JSON.stringify(frag)]
        return prefix + args.join(',') + '))'
      }
    }
  }, {
    vars: {
      __dirname: cwd,
      __filename: filename
    },
    varModules: {
      path: path
    }
  })

  return stream

  function replaceStream (glslFile, opts) {
    var replacer = through()

    opts = xtend({
      basedir: cwd
    }, transformOpts || {}, opts || {})

    glslify.bundle(glslFile, opts, function (err, bundled) {
      if (err) return stream.emit('error', err)

      var jsReplacement = splitAndFormat(bundled)
      replacer.push(jsReplacement)
      replacer.push(null)
    }).on('file', function (file) {
      stream.emit('file', file)
    })

    return replacer
  }
}

function splitAndFormat (source, replaceMap) {
  var vert = JSON.stringify(format.vert(source))
  var frag = JSON.stringify(format.frag(source))
  var bundled = ''

  if (replaceMap) {
    Object.keys(replaceMap).forEach(function (value) {
      var key = replaceMap[value]

      vert = vert.replace(new RegExp(key, 'g'), '"+(' + value + ')+"')
      frag = frag.replace(new RegExp(key, 'g'), '"+(' + value + ')+"')
    })
  }

  bundled += 'require("kindred-shader/raw")('
  bundled += vert
  bundled += ','
  bundled += frag
  bundled += ')'

  return bundled
}
<|endoftext|>


<commit_before>'use strict';

function EntityWall(world, entity) {
    this.__init__(world, entity);
}

EntityWall.prototype = {

    delete_entity_wall_button_pressed: function() {
        this.wall_are_you_sure.show();
    },

    create_new_entity: function() {
        l('TODO: !!! Create this new entity');
        l(this.create_entity_dictionary);

        var entity_data = {};
        for (var key in this.create_entity_dictionary) {
            if (this.create_entity_dictionary.hasOwnProperty(key)) {
                entity_data[key] = this.create_entity_dictionary[key].get_text();
            }
        }

        var new_entity = new Entity(entity_data);
        this.load_entity(new_entity);
        this.create_entity_wall.hide();
    },

    create_entity_button_pressed: function() {
        this.entity_type_selector_wall.show();
    },

    add_new_attribute_pressed: function() {
        this.wall_select_attribute.show();
    },

    attribute_selected: function(attribute) {
        this.wall_select_attribute.hide();

        // TODO : Make sure to only list attributes that are not already added.

        this._add_label_and_input_for_create_entity_wall(attribute);
    },

    _add_label_and_input_for_create_entity_wall: function(label) {
        this.create_entity_wall.add_floating_2d_text(0, 1 / 3, label, TYPE_CONSTANT_TEXT, this.current_create_entity_wall_row_index);
        // TODO : Make the first click clear the value here text.
        this.create_entity_dictionary[label] = this.create_entity_wall.add_floating_2d_text(1 / 3, 1, 'value here', TYPE_INPUT_REGULAR, this.current_create_entity_wall_row_index);
        this.current_create_entity_wall_row_index += 1;
    },

    entity_type_selected: function(selected_type) {
        this.entity_type_selector_wall.hide();

        this.create_entity_wall.clear_floating_2d_texts();

        this.create_entity_wall.add_floating_2d_text(.05, .95, 'Create New ' + selected_type, TYPE_TITLE, 0);

        // Select new attribute.
        this.current_add_new_attribute_button = this.create_entity_wall.add_floating_2d_text(.05, .95, 'add new attribute', TYPE_BUTTON, 3);
        if (!is_defined(this.wall_select_attribute)) {
            this.init_select_new_attribute_wall();
        } else {
            this.wall_select_attribute.pfw_button = this.current_add_new_attribute_button;
        }
        this.current_add_new_attribute_button.set_engage_function(this.add_new_attribute_pressed.bind(this));

        // Entity data.
        this.current_create_entity_wall_row_index = 5;
        this.create_entity_dictionary = {};
        this._add_label_and_input_for_create_entity_wall(ENTITY_PROPERTY_NAME);

        // Create new entity button.
        this.create_new_entity_button = this.create_entity_wall.add_floating_2d_text(.05, .95, 'create entity', TYPE_BUTTON, -1);
        this.create_new_entity_button.set_engage_function(this.create_new_entity.bind(this));

        this.create_entity_wall.add_close_button();
        this.create_entity_wall.show();
    },

    no_button_pressed: function() {
        this.wall_are_you_sure.hide();
    },

    yes_button_pressed: function() {
        this.wall_are_you_sure.hide();
        // TODO : Not everything is getting fully removed!
        this.wall.remove_from_scene();

        var all_walls = MANAGER_WORLD.world_home.entity_walls;
        var index_to_remove = -1;
        for (var i = 0; i < all_walls.length; i++) {
            if (all_walls[i].entity === this.entity) {
                index_to_remove = i;
            }
        }
        // TODO : Test if this was the solution.
        if (index_to_remove !== NOT_FOUND) {
            MANAGER_WORLD.world_home.entity_walls.splice(index_to_remove, 1);
        }
        // Now also delete the entity!
        MANAGER_ENTITY.delete_entity(this.entity);
    },

    __init__: function(world, entity) {
        this.world = world;
        this.entity = entity;

        this.position = this.get_value(ENTITY_PROPERTY_POSITION);
        this.normal = this.get_value(ENTITY_PROPERTY_NORMAL);
        this.width = this.get_value(ENTITY_PROPERTY_WIDTH);
        this.height = this.get_value(ENTITY_PROPERTY_HEIGHT);

        this.entities = [];

        this.init_base_wall();
        this.init_are_you_sure_wall();
        this.init_create_entity_wall();
        this.init_select_entity_type_wall();
        this.wall_select_attribute = null;
    },

    load_entity: function(entity) {
        l('Need to load the following entity in');
        this.entity.add_child(entity);
        l(entity);
    },

    update: function() {
        this.wall.update();

        // TODO: Optimize later.
        if (this.title.get_text() !== this.get_value(ENTITY_PROPERTY_NAME)) {
            this.update_value(ENTITY_PROPERTY_NAME, this.title.get_text());
        }
    },

    /*                        __   __   ___      ___    __
      |  |  /\  |    |       /  ` |__) |__   /\   |  | /  \ |\ |
      |/\| /~~\ |___ |___    \__, |  \ |___ /~~\  |  | \__/ | \| */
    init_are_you_sure_wall: function() {
        this.wall_are_you_sure = this.wall.add_floating_wall_off_of_button(200, 70, this.delete_entity_wall_button, false);
        this.wall_are_you_sure.add_floating_2d_text(0, 1, 'Are you sure?', TYPE_CONSTANT_TEXT, 0);
        this.no_button = this.wall_are_you_sure.add_floating_2d_text(0, .5, 'No', TYPE_BUTTON, 2);
        this.no_button.set_engage_function(this.no_button_pressed.bind(this));
        this.no_button.set_color(COLOR_RED);
        this.yes_button = this.wall_are_you_sure.add_floating_2d_text(.5, 1, 'Yes', TYPE_BUTTON, 2);
        this.yes_button.set_engage_function(this.yes_button_pressed.bind(this));
        this.yes_button.set_color(COLOR_GREEN);
        this.wall_are_you_sure.hide();
    },

    init_create_entity_wall: function() {
        this.create_entity_wall = this.wall.add_floating_wall_off_of_button(400, 500, this.create_entity_button, false);
        this.create_entity_wall.add_close_button();
        this.create_entity_wall.hide();
    },

    init_base_wall: function() {
        this.wall = new FloatingWall(this.width, this.height, this.position, this.normal, this.world, true, this.normal_depth);

        this.wall.entity_wall_to_update = this;

        this.title = this.wall.add_floating_2d_text(.25, .75, 'Default Entity Wall Name', TYPE_INPUT_REGULAR, 0);
        this.create_entity_button = this.wall.add_floating_2d_text(.25, .75, 'Create New Entity', TYPE_BUTTON, 1);
        this.create_entity_button.set_engage_function(this.create_entity_button_pressed.bind(this));

        this.delete_entity_wall_button = this.wall.add_floating_2d_text(.05, .95, 'Delete Entity Wall', TYPE_BUTTON, -1);
        this.delete_entity_wall_button.set_engage_function(this.delete_entity_wall_button_pressed.bind(this));
        this.delete_entity_wall_button.set_color(COLOR_RED);
    },

    init_select_entity_type_wall: function() {
        this.entity_type_selector_wall = this.wall.add_floating_wall_off_of_button(400, 250, this.create_entity_button, false);
        this.entity_type_selector_wall.add_floating_2d_text(0, 1, 'Select Entity Type', TYPE_TITLE, 0);
        var entity_type_row_index = 3;
        for (var et = 0; et < ENTITY_TYPE_ALL.length; et++) {
            if (ENTITY_TYPE_ALL[et] !== ENTITY_TYPE_TIME && ENTITY_TYPE_ALL[et] !== ENTITY_TYPE_OWNER && ENTITY_TYPE_ALL[et] !== ENTITY_TYPE_WALL) {
                var entity_type_row = this.entity_type_selector_wall.add_floating_2d_text(0, 1, ENTITY_TYPE_ALL[et], TYPE_BUTTON, entity_type_row_index, 0);
                entity_type_row_index += 1;
                entity_type_row.set_engage_function(this.entity_type_selected.bind(this, ENTITY_TYPE_ALL[et]));
            }
        }
        this.entity_type_selector_wall.add_close_button();
        this.entity_type_selector_wall.hide();
    },

    init_select_new_attribute_wall: function() {
        this.wall_select_attribute = this.wall.add_floating_wall_off_of_button(400, 250, this.current_add_new_attribute_button, false);

        this.wall_select_attribute.add_floating_2d_text(.05, .95, 'Select Entity Attribute', TYPE_TITLE, 0);

        var a0 = this.wall_select_attribute.add_floating_2d_text(0, 1, ENTITY_PROPERTY_DUE_DATE, TYPE_BUTTON, 3);
        var a1 = this.wall_select_attribute.add_floating_2d_text(0, 1, ENTITY_PROPERTY_DUE_TIME, TYPE_BUTTON, 4);
        var a2 = this.wall_select_attribute.add_floating_2d_text(0, 1, ENTITY_PROPERTY_COMPLETED, TYPE_BUTTON, 5);

        a0.set_engage_function(this.attribute_selected.bind(this, ENTITY_PROPERTY_DUE_DATE));
        a1.set_engage_function(this.attribute_selected.bind(this, ENTITY_PROPERTY_DUE_TIME));
        a2.set_engage_function(this.attribute_selected.bind(this, ENTITY_PROPERTY_COMPLETED));

        this.wall_select_attribute.add_close_button();
        this.wall_select_attribute.hide();
    },

    /* ___      ___   ___                             ___  __
      |__  |\ |  |  |  |  \ /    \  /  /\  |    |  | |__  /__`
      |___ | \|  |  |  |   |      \/  /~~\ |___ \__/ |___ .__/ */

    update_value: function(value_name, value) {
        if (value_name === ENTITY_PROPERTY_POSITION) {
            value = '[' + value.x + ',' + value.y + ',' + value.z + ']';
        }
        this.entity.set_property(value_name, value);
    },

    get_value: function(value_name) {
        var value;
        switch(value_name) {
        case ENTITY_PROPERTY_HORIZONTAL_OFFSET:
        case ENTITY_PROPERTY_VERTICAL_OFFSET:
        case ENTITY_PROPERTY_WIDTH:
        case ENTITY_PROPERTY_HEIGHT:
            return parseInt(this.entity.get_value(value_name));
        case ENTITY_PROPERTY_NORMAL:
            value = this.entity.get_value(value_name);
            value = value.replace('[', '').replace(']', '').split(',');
            return new THREE.Vector3(parseFloat(value[0]), parseFloat(value[1]), parseFloat(value[2]));
        case ENTITY_PROPERTY_POSITION:
            value = this.entity.get_value(value_name);
            value = value.replace('[', '').replace(']', '').split(',');
            return new THREE.Vector3(parseInt(value[0]), parseInt(value[1]), parseInt(value[2]));
        }
    }

};
<commit_msg>general updating 88<commit_after>'use strict';

function EntityWall(world, entity) {
    this.__init__(world, entity);
}

EntityWall.prototype = {

    delete_entity_wall_button_pressed: function() {
        this.wall_are_you_sure.show();
    },

    create_new_entity: function() {
        l('TODO: !!! Create this new entity');
        l(this.create_entity_dictionary);

        var entity_data = {};
        for (var key in this.create_entity_dictionary) {
            if (this.create_entity_dictionary.hasOwnProperty(key)) {
                entity_data[key] = this.create_entity_dictionary[key].get_text();
            }
        }

        var new_entity = new Entity(entity_data);
        this.load_entity(new_entity);
        this.create_entity_wall.hide();
    },

    create_entity_button_pressed: function() {
        this.entity_type_selector_wall.show();
    },

    add_new_attribute_pressed: function() {
        this.wall_select_attribute.show();
    },

    attribute_selected: function(attribute) {
        this.wall_select_attribute.hide();

        // TODO : Make sure to only list attributes that are not already added.

        this._add_label_and_input_for_create_entity_wall(attribute);
    },

    _add_label_and_input_for_create_entity_wall: function(label) {
        this.create_entity_wall.add_floating_2d_text(0, 1 / 3, label, TYPE_CONSTANT_TEXT, this.current_create_entity_wall_row_index);
        // TODO : Make the first click clear the value here text.
        this.create_entity_dictionary[label] = this.create_entity_wall.add_floating_2d_text(1 / 3, 1, 'value here', TYPE_INPUT_REGULAR, this.current_create_entity_wall_row_index);
        this.current_create_entity_wall_row_index += 1;
    },

    entity_type_selected: function(selected_type) {
        this.entity_type_selector_wall.hide();

        this.create_entity_wall.clear_floating_2d_texts();

        this.create_entity_wall.add_floating_2d_text(.05, .95, 'Create New ' + selected_type, TYPE_TITLE, 0);

        // Select new attribute.
        this.current_add_new_attribute_button = this.create_entity_wall.add_floating_2d_text(.05, .95, 'add new attribute', TYPE_BUTTON, 3);
        if (!is_defined(this.wall_select_attribute)) {
            this.init_select_new_attribute_wall();
        } else {
            this.wall_select_attribute.pfw_button = this.current_add_new_attribute_button;
        }
        this.current_add_new_attribute_button.set_engage_function(this.add_new_attribute_pressed.bind(this));

        // Entity data.
        this.current_create_entity_wall_row_index = 5;
        this.create_entity_dictionary = {};
        this._add_label_and_input_for_create_entity_wall(ENTITY_PROPERTY_NAME);

        // Create new entity button.
        this.create_new_entity_button = this.create_entity_wall.add_floating_2d_text(.05, .95, 'create entity', TYPE_BUTTON, -1);
        this.create_new_entity_button.set_engage_function(this.create_new_entity.bind(this));

        this.create_entity_wall.add_close_button();
        this.create_entity_wall.show();
    },

    no_button_pressed: function() {
        this.wall_are_you_sure.hide();
    },

    yes_button_pressed: function() {
        this.wall_are_you_sure.hide();
        // TODO : Not everything is getting fully removed!
        this.wall.remove_from_scene();

        var all_walls = MANAGER_WORLD.world_home.entity_walls;
        var index_to_remove = -1;
        for (var i = 0; i < all_walls.length; i++) {
            if (all_walls[i].entity === this.entity) {
                index_to_remove = i;
            }
        }
        // TODO : Test if this was the solution.
        if (index_to_remove !== NOT_FOUND) {
            MANAGER_WORLD.world_home.entity_walls.splice(index_to_remove, 1);
        }
        // Now also delete the entity!
        MANAGER_ENTITY.delete_entity(this.entity);
    },

    __init__: function(world, entity) {
        this.world = world;
        this.entity = entity;

        this.position = this.get_value(ENTITY_PROPERTY_POSITION);
        this.normal = this.get_value(ENTITY_PROPERTY_NORMAL);
        this.width = this.get_value(ENTITY_PROPERTY_WIDTH);
        this.height = this.get_value(ENTITY_PROPERTY_HEIGHT);

        this.entity_rows = [];

        this.init_base_wall();
        this.init_are_you_sure_wall();
        this.init_create_entity_wall();
        this.init_select_entity_type_wall();
        this.wall_select_attribute = null;
    },

    load_entity: function(entity) {
        l('Need to load the following entity in');
        this.entity.add_child(entity);
        l(entity);

        this.entity_rows.push([this.wall.add_floating_2d_text(.1, .9, entity.get_value(ENTITY_PROPERTY_NAME), TYPE_BUTTON, 3 + this.entity_rows.length), entity]);
    },

    update: function() {
        this.wall.update();

        // TODO: Optimize later.
        if (this.title.get_text() !== this.get_value(ENTITY_PROPERTY_NAME)) {
            this.update_value(ENTITY_PROPERTY_NAME, this.title.get_text());
        }
    },

    /*                        __   __   ___      ___    __
      |  |  /\  |    |       /  ` |__) |__   /\   |  | /  \ |\ |
      |/\| /~~\ |___ |___    \__, |  \ |___ /~~\  |  | \__/ | \| */
    init_are_you_sure_wall: function() {
        this.wall_are_you_sure = this.wall.add_floating_wall_off_of_button(200, 70, this.delete_entity_wall_button, false);
        this.wall_are_you_sure.add_floating_2d_text(0, 1, 'Are you sure?', TYPE_CONSTANT_TEXT, 0);
        this.no_button = this.wall_are_you_sure.add_floating_2d_text(0, .5, 'No', TYPE_BUTTON, 2);
        this.no_button.set_engage_function(this.no_button_pressed.bind(this));
        this.no_button.set_color(COLOR_RED);
        this.yes_button = this.wall_are_you_sure.add_floating_2d_text(.5, 1, 'Yes', TYPE_BUTTON, 2);
        this.yes_button.set_engage_function(this.yes_button_pressed.bind(this));
        this.yes_button.set_color(COLOR_GREEN);
        this.wall_are_you_sure.hide();
    },

    init_create_entity_wall: function() {
        this.create_entity_wall = this.wall.add_floating_wall_off_of_button(400, 500, this.create_entity_button, false);
        this.create_entity_wall.add_close_button();
        this.create_entity_wall.hide();
    },

    init_base_wall: function() {
        this.wall = new FloatingWall(this.width, this.height, this.position, this.normal, this.world, true, this.normal_depth);

        this.wall.entity_wall_to_update = this;

        this.title = this.wall.add_floating_2d_text(.25, .75, 'Default Entity Wall Name', TYPE_INPUT_REGULAR, 0);
        this.create_entity_button = this.wall.add_floating_2d_text(.25, .75, 'Create New Entity', TYPE_BUTTON, 1);
        this.create_entity_button.set_engage_function(this.create_entity_button_pressed.bind(this));

        this.delete_entity_wall_button = this.wall.add_floating_2d_text(.05, .95, 'Delete Entity Wall', TYPE_BUTTON, -1);
        this.delete_entity_wall_button.set_engage_function(this.delete_entity_wall_button_pressed.bind(this));
        this.delete_entity_wall_button.set_color(COLOR_RED);
    },

    init_select_entity_type_wall: function() {
        this.entity_type_selector_wall = this.wall.add_floating_wall_off_of_button(400, 250, this.create_entity_button, false);
        this.entity_type_selector_wall.add_floating_2d_text(0, 1, 'Select Entity Type', TYPE_TITLE, 0);
        var entity_type_row_index = 3;
        for (var et = 0; et < ENTITY_TYPE_ALL.length; et++) {
            if (ENTITY_TYPE_ALL[et] !== ENTITY_TYPE_TIME && ENTITY_TYPE_ALL[et] !== ENTITY_TYPE_OWNER && ENTITY_TYPE_ALL[et] !== ENTITY_TYPE_WALL) {
                var entity_type_row = this.entity_type_selector_wall.add_floating_2d_text(0, 1, ENTITY_TYPE_ALL[et], TYPE_BUTTON, entity_type_row_index, 0);
                entity_type_row_index += 1;
                entity_type_row.set_engage_function(this.entity_type_selected.bind(this, ENTITY_TYPE_ALL[et]));
            }
        }
        this.entity_type_selector_wall.add_close_button();
        this.entity_type_selector_wall.hide();
    },

    init_select_new_attribute_wall: function() {
        this.wall_select_attribute = this.wall.add_floating_wall_off_of_button(400, 250, this.current_add_new_attribute_button, false);

        this.wall_select_attribute.add_floating_2d_text(.05, .95, 'Select Entity Attribute', TYPE_TITLE, 0);

        var a0 = this.wall_select_attribute.add_floating_2d_text(0, 1, ENTITY_PROPERTY_DUE_DATE, TYPE_BUTTON, 3);
        var a1 = this.wall_select_attribute.add_floating_2d_text(0, 1, ENTITY_PROPERTY_DUE_TIME, TYPE_BUTTON, 4);
        var a2 = this.wall_select_attribute.add_floating_2d_text(0, 1, ENTITY_PROPERTY_COMPLETED, TYPE_BUTTON, 5);

        a0.set_engage_function(this.attribute_selected.bind(this, ENTITY_PROPERTY_DUE_DATE));
        a1.set_engage_function(this.attribute_selected.bind(this, ENTITY_PROPERTY_DUE_TIME));
        a2.set_engage_function(this.attribute_selected.bind(this, ENTITY_PROPERTY_COMPLETED));

        this.wall_select_attribute.add_close_button();
        this.wall_select_attribute.hide();
    },

    /* ___      ___   ___                             ___  __
      |__  |\ |  |  |  |  \ /    \  /  /\  |    |  | |__  /__`
      |___ | \|  |  |  |   |      \/  /~~\ |___ \__/ |___ .__/ */

    update_value: function(value_name, value) {
        if (value_name === ENTITY_PROPERTY_POSITION) {
            value = '[' + value.x + ',' + value.y + ',' + value.z + ']';
        }
        this.entity.set_property(value_name, value);
    },

    get_value: function(value_name) {
        var value;
        switch(value_name) {
        case ENTITY_PROPERTY_HORIZONTAL_OFFSET:
        case ENTITY_PROPERTY_VERTICAL_OFFSET:
        case ENTITY_PROPERTY_WIDTH:
        case ENTITY_PROPERTY_HEIGHT:
            return parseInt(this.entity.get_value(value_name));
        case ENTITY_PROPERTY_NORMAL:
            value = this.entity.get_value(value_name);
            value = value.replace('[', '').replace(']', '').split(',');
            return new THREE.Vector3(parseFloat(value[0]), parseFloat(value[1]), parseFloat(value[2]));
        case ENTITY_PROPERTY_POSITION:
            value = this.entity.get_value(value_name);
            value = value.replace('[', '').replace(']', '').split(',');
            return new THREE.Vector3(parseInt(value[0]), parseInt(value[1]), parseInt(value[2]));
        }
    }

};
<|endoftext|>


<commit_before>opera.isReady(function() {
    var win = null, tab = null;
    var tests = {}, // Asynchronous tests
    eventsReceived = [], // List of received events
    eventsExpected = [ // List of expected events
    // Step 1
    {
        target : "tab",
        type : "close"
    },

    // Step 2
    {
        target : "browserWindow",
        type : "close"
    } ];

    tests["close"] = async_test("Tab Group close event");
    tests["order"] = async_test("Order of events");

    function getHandler(type) {
        return function(evt) {
            tests[type].step(function() {
                assert_equals(evt.type, type, "Event type should be '" + type + "'");
                assert_exists(evt, "tab", "The event object should have a tabGroup property");
                assert_equals(evt.tab.id, tab.id, "The event should refer to the created tab group");
            });
            tests[type].done();
        }
    }

    function eventOrder(evt) {
        var evtTarget = evt.browserWindow ? "browserWindow" : evt.tabGroup ? "tabGroup" : evt.tab ? "tab" : "unknown"

        eventsReceived.push({
            target : evtTarget,
            type : evt.type
        });

        if (eventsReceived.length === eventsExpected.length) {
            setTimeout(function() {
                tests["order"].step(function() {
                    // for (i = 0; i < eventsReceived.length; i++) {
                    // opera.postError(eventsReceived[i].target + ": " +
                    // eventsReceived[i].type)
                    // }

                    for (i = 0; i < eventsReceived.length; i++) {
                        assert_equals("{" + eventsReceived[i].target + ", " + eventsReceived[i].type + "}", "{" + eventsExpected[i].target + ", " + eventsExpected[i].type + "}",
                                "The event order, type and target should match. Event number: " + i)
                    }
                });
                tests["order"].done();
            }, 500); // Wait, incase new unexpected events fire
        }
    }

    // Setup
    try {
        win = createWindow({}, {
            focused : true
        }); // Create a window
    } catch (e) {
        for ( var n in tests)
            tests[n].step(function() {
                assert_unreached("Couldn't create new window")
            });
    }
    tab = win.tabs.getAll()[0];

    tabs.addEventListener("close", getHandler("close"), false);

    windows.addEventListener("create", eventOrder, false);
    windows.addEventListener("close", eventOrder, false);
    groups.addEventListener("create", eventOrder, false);
    groups.addEventListener("move", eventOrder, false);
    groups.addEventListener("close", eventOrder, false);
    tabs.addEventListener("create", eventOrder, false);
    tabs.addEventListener("move", eventOrder, false);
    tabs.addEventListener("close", eventOrder, false);

    setTimeout(function() {
        // Step 1
        tab.close(); // Close the tab and its tabs, fire close events

        // Step 2
        win.close(); // Close the window, if it didn't close automatically
    }, 100);
});
<commit_msg>fixed testcase, added timeout before attaching events, removed parts of tab-groups<commit_after>opera.isReady(function() {
    var win = null, tab = null;
    var tests = {}, // Asynchronous tests
    eventsReceived = [], // List of received events
    eventsExpected = [ // List of expected events
    // Step 1
    {
        target : "tab",
        type : "close"
    },

    // Step 2
    {
        target : "browserWindow",
        type : "close"
    } ];

    tests["close"] = async_test("Tab Window close event");
    tests["order"] = async_test("Order of events");

    function getHandler(type) {
        return function(evt) {
            tests[type].step(function() {
                assert_equals(evt.type, type, "Event type should be '" + type + "'");
                assert_exists(evt, "tab", "The event object should have a tab property");
                assert_equals(evt.tab.id, tab.id, "The event should refer to the created tab");
            });
            tests[type].done();
        }
    }

    function eventOrder(evt) {
        var evtTarget = evt.browserWindow ? "browserWindow" : evt.tab ? "tab" : "unknown";

        eventsReceived.push({
            target : evtTarget,
            type : evt.type
        });

        if (eventsReceived.length === eventsExpected.length) {
            setTimeout(function() {
                tests["order"].step(function() {
                    // for (i = 0; i < eventsReceived.length; i++) {
                    // opera.postError(eventsReceived[i].target + ": " +
                    // eventsReceived[i].type)
                    // }

                    for (i = 0; i < eventsReceived.length; i++) {
                        assert_equals("{" + eventsReceived[i].target + ", " + eventsReceived[i].type + "}", "{" + eventsExpected[i].target + ", " + eventsExpected[i].type + "}",
                                "The event order, type and target should match. Event number: " + i)
                    }
                });
                tests["order"].done();
            }, 500); // Wait, incase new unexpected events fire
        }
    }

    // Setup

    try {
        win = createWindow({}, {
            focused : true
        }); // Create a window
    } catch (e) {
        for ( var n in tests)
            tests[n].step(function() {
                assert_unreached("Couldn't create new window")
            });
    }
    tab = win.tabs.getAll()[0];

    //window create-event may be delayed
    setTimeout(function() {
	tabs.addEventListener("close", getHandler("close"), false);
	windows.addEventListener("create", eventOrder, false);
	windows.addEventListener("close", eventOrder, false);
	    //groups.addEventListener("create", eventOrder, false);
	    //groups.addEventListener("move", eventOrder, false);
	    //groups.addEventListener("close", eventOrder, false);
	tabs.addEventListener("create", eventOrder, false);
	tabs.addEventListener("move", eventOrder, false);
	tabs.addEventListener("close", eventOrder, false);

	setTimeout(function() {
            // Step 1
            tab.close(); // Close the tab and its tabs, fire close events

            // Step 2
            win.close(); // Close the window, if it didn't close automatically
        }, 100);
    }, 100);
});
<|endoftext|>


<commit_before>app.controller("jobseekerCtrl", function($scope, $http, $timeout) {
	$scope.job = {};
	$scope.sorted = {};
	$scope.filter = {};
	var editedJob = {};

	$scope.init = function() {
		$scope.job.date = new Date();
		$scope.joblist = [];

		$scope.getJobList();
	};

	$scope.submitForm = function() {
		if ($scope.job._id)
			$scope.editJob();
		else
			$scope.addJob();
	};

	$scope.getJobList = function() {
		$http({
			url: "http://127.0.0.1:8000/jobs",
			method: "GET"})
		.then(function successCallback(response) {
			$scope.joblist = response.data;
		}, function errorCallback(response) {
			console.log(response.statusText);
		});
	};

	$scope.addJob = function() {
		$http({
			url: "http://127.0.0.1:8000/jobs",
			method: "POST",
			data: $.param($scope.job),
			headers: { "Content-Type": "application/x-www-form-urlencoded"}})
		.then(function successCallback(response) {
			$scope.joblist.push(response.data);
		}, function errorCallback(response) {
			console.log(response.statusText);
		});

		$scope.resetForm();
	};

	$scope.editJob = function() {
		var id = $scope.job._id;
		var job = {
			date :  $scope.job.date,
			title : $scope.job.title,
			company : $scope.job.company,
			location : $scope.job.location,
			via : $scope.job.via
		};

		$http({
			url: "http://127.0.0.1:8000/jobs/" + id,
			method: "PUT",
			data: $.param(job),
			headers: { "Content-Type": "application/x-www-form-urlencoded"}})
		.then(function successCallback(response) {
			return;
		}, function errorCallback(response) {
			console.log(response.statusText);
		});
	};

	$scope.openEditModal = function(index) {
		$scope.job = $scope.joblist[index];
		$scope.job.date = $scope.getDateString($scope.job.date);
		editedJob = {
			_id : $scope.job._id,
			date :  $scope.job.date,
			title : $scope.job.title,
			company : $scope.job.company,
			location : $scope.job.location,
			via : $scope.job.via
		};
	};

	$scope.deleteJob = function(id, index) {
		$http({
			url: "http://127.0.0.1:8000/jobs/" + id,
			method: "DELETE" })
		.then(function(response) {
			$scope.joblist.splice(index, 1);
		}, function(response) {
			console.log(response.statusText);
		});
	};

	$scope.resetForm = function() {
		if ($scope.job._id)
			$scope.revertForm();
		else
			$scope.clearForm();
	};

	$scope.clearForm = function() {
		$scope.job = {};
		$scope.job.date = $scope.getDateString(new Date());
	};

	$scope.revertForm = function() {
		$scope.job._id = editedJob._id;
		$scope.job.date = editedJob.date;
		$scope.job.title = editedJob.title;
		$scope.job.company = editedJob.company;
		$scope.job.location = editedJob.location;
		$scope.job.via = editedJob.via;
	};

	$scope.getDateString = function(date) {
		var dt = new Date(date);
		return (dt.getMonth()+1) + "/" + dt.getDate() + "/" + dt.getFullYear();
	};

	$scope.sort = function(colname) {
		if ($scope.sorted.column !== colname) {
			$scope.sorted.column = colname;
			$scope.sorted.order = "asc";
			$scope.joblist.sort(function(a, b) {
					var x = a[colname].toLowerCase();
					var y = b[colname].toLowerCase();
					if (x < y) { return -1; }
					if (x > y) { return 1; }
					return 0;
				});
		} else {
			$scope.joblist.reverse();
			$scope.sorted.order === "asc" ? $scope.sorted.order = "desc" : $scope.sorted.order = "asc";
		}
	};

	$scope.isSortedBy = function(colname) {
		return $scope.sorted.column === colname;
	};

	$scope.getSortedClass = function(colname) {
		if ($scope.sorted.column === colname)
			return "text-muted";
		else
			return "";
	};

	$scope.getSortedIcon = function(colname) {
		if ($scope.isSortedBy(colname))
			return "fa-sort-" + $scope.sorted.order;
		else
			return "fa-sort";
	};

	$("#addJobModal").on("hide.bs.modal", function (e) {
		$timeout(function () {
			$scope.clearForm();
		});
	});

	$scope.applyFilters = function() {
		var fromDate = new Date($scope.filter.fromDate);
		var toDate = new Date($scope.filter.toDate);

		if ($scope.filter.searchTerm)
			var term = $scope.filter.searchTerm.trim().toLowerCase();

		if (fromDate != "Invalid Date" && toDate != "Invalid Date")
		{
			var result = $scope.joblist.filter(job =>
				new Date(job.date) >= fromDate &&
				new Date(job.date) <= toDate);

			$scope.joblist = result;
		}

		if (term)
		{
			var result = $scope.joblist.filter(job =>
				job.title.toLowerCase().includes(term) ||
				job.company.toLowerCase().includes(term) ||
				job.location.toLowerCase().includes(term) ||
				job.via.toLowerCase().includes(term));

			$scope.joblist = result;
		}

	}

	$scope.resetFilters = function() {
		$scope.getJobList();
		$scope.filter = {};
		$scope.sorted = {};
	};

});
<commit_msg>cleaning up init<commit_after>app.controller("jobseekerCtrl", function($scope, $http, $timeout) {
	$scope.job = {};
	$scope.sorted = {};
	$scope.filter = {};
	$scope.job.date = new Date();
	$scope.joblist = [];
	var editedJob = {};

	$scope.init = function() {
		$scope.getJobList();
	};

	$scope.submitForm = function() {
		if ($scope.job._id)
			$scope.editJob();
		else
			$scope.addJob();
	};

	$scope.getJobList = function() {
		$http({
			url: "http://127.0.0.1:8000/jobs",
			method: "GET"})
		.then(function successCallback(response) {
			$scope.joblist = response.data;
		}, function errorCallback(response) {
			console.log(response.statusText);
		});
	};

	$scope.addJob = function() {
		$http({
			url: "http://127.0.0.1:8000/jobs",
			method: "POST",
			data: $.param($scope.job),
			headers: { "Content-Type": "application/x-www-form-urlencoded"}})
		.then(function successCallback(response) {
			$scope.joblist.push(response.data);
		}, function errorCallback(response) {
			console.log(response.statusText);
		});

		$scope.resetForm();
	};

	$scope.editJob = function() {
		var id = $scope.job._id;
		var job = {
			date :  $scope.job.date,
			title : $scope.job.title,
			company : $scope.job.company,
			location : $scope.job.location,
			via : $scope.job.via
		};

		$http({
			url: "http://127.0.0.1:8000/jobs/" + id,
			method: "PUT",
			data: $.param(job),
			headers: { "Content-Type": "application/x-www-form-urlencoded"}})
		.then(function successCallback(response) {
			return;
		}, function errorCallback(response) {
			console.log(response.statusText);
		});
	};

	$scope.openEditModal = function(index) {
		$scope.job = $scope.joblist[index];
		$scope.job.date = $scope.getDateString($scope.job.date);
		editedJob = {
			_id : $scope.job._id,
			date :  $scope.job.date,
			title : $scope.job.title,
			company : $scope.job.company,
			location : $scope.job.location,
			via : $scope.job.via
		};
	};

	$scope.deleteJob = function(id, index) {
		$http({
			url: "http://127.0.0.1:8000/jobs/" + id,
			method: "DELETE" })
		.then(function(response) {
			$scope.joblist.splice(index, 1);
		}, function(response) {
			console.log(response.statusText);
		});
	};

	$scope.resetForm = function() {
		if ($scope.job._id)
			$scope.revertForm();
		else
			$scope.clearForm();
	};

	$scope.clearForm = function() {
		$scope.job = {};
		$scope.job.date = $scope.getDateString(new Date());
	};

	$scope.revertForm = function() {
		$scope.job._id = editedJob._id;
		$scope.job.date = editedJob.date;
		$scope.job.title = editedJob.title;
		$scope.job.company = editedJob.company;
		$scope.job.location = editedJob.location;
		$scope.job.via = editedJob.via;
	};

	$scope.getDateString = function(date) {
		var dt = new Date(date);
		return (dt.getMonth()+1) + "/" + dt.getDate() + "/" + dt.getFullYear();
	};

	$scope.sort = function(colname) {
		if ($scope.sorted.column !== colname) {
			$scope.sorted.column = colname;
			$scope.sorted.order = "asc";
			$scope.joblist.sort(function(a, b) {
					var x = a[colname].toLowerCase();
					var y = b[colname].toLowerCase();
					if (x < y) { return -1; }
					if (x > y) { return 1; }
					return 0;
				});
		} else {
			$scope.joblist.reverse();
			$scope.sorted.order === "asc" ? $scope.sorted.order = "desc" : $scope.sorted.order = "asc";
		}
	};

	$scope.isSortedBy = function(colname) {
		return $scope.sorted.column === colname;
	};

	$scope.getSortedClass = function(colname) {
		if ($scope.sorted.column === colname)
			return "text-muted";
		else
			return "";
	};

	$scope.getSortedIcon = function(colname) {
		if ($scope.isSortedBy(colname))
			return "fa-sort-" + $scope.sorted.order;
		else
			return "fa-sort";
	};

	$("#addJobModal").on("hide.bs.modal", function (e) {
		$timeout(function () {
			$scope.clearForm();
		});
	});

	$scope.applyFilters = function() {
		var fromDate = new Date($scope.filter.fromDate);
		var toDate = new Date($scope.filter.toDate);

		if ($scope.filter.searchTerm)
			var term = $scope.filter.searchTerm.trim().toLowerCase();

		if (fromDate != "Invalid Date" && toDate != "Invalid Date")
		{
			var result = $scope.joblist.filter(job =>
				new Date(job.date) >= fromDate &&
				new Date(job.date) <= toDate);

			$scope.joblist = result;
		}

		if (term)
		{
			var result = $scope.joblist.filter(job =>
				job.title.toLowerCase().includes(term) ||
				job.company.toLowerCase().includes(term) ||
				job.location.toLowerCase().includes(term) ||
				job.via.toLowerCase().includes(term));

			$scope.joblist = result;
		}

	}

	$scope.resetFilters = function() {
		$scope.getJobList();
		$scope.filter = {};
		$scope.sorted = {};
	};

});
<|endoftext|>