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

'use strict';

var test = require('tape');
var path = require('path');
var exec = require('child_process').exec;

test('running example1.js', function t(assert) {
    spawnExample('example1.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');

        assert.ok(stdout.indexOf(
            'func1 responding with a small delay { arg2: \'arg 1\', arg3: \'arg 2\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'err res:  { ok: false, message: \'it failed\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'normal res: { arg2: \'result\', arg3: \'indeed it did\' }'
        ) >= 0);

        assert.end();
    }
});

test('running example2.js', function t(assert) {
    spawnExample('example2.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');

        assert.ok(stdout.indexOf(
            'server got ping req from { remoteAddr: \'127.0.0.1:4041\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'ping res from server { arg2: \'pong\', arg3: \'\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'client got ping req from { remoteAddr: \'127.0.0.1:4040\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'ping res from client { arg2: \'pong\', arg3: \'\' }'
        ) >= 0);

        assert.end();
    }
});

test('running as_example.js', function t(assert) {
    spawnExample('as_example1.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');

        assert.ok(stdout.indexOf(
            'got resp { ok: true,'
        ) >= 0);
        assert.ok(stdout.indexOf(
            '  head: { head: \'object\' },'
        ) >= 0);
        assert.ok(stdout.indexOf(
            '  body: { body: \'object\' },'
        ) >= 0);
        assert.ok(stdout.indexOf(
            '  headers: { as: \'json\' } }'
        ) >= 0);

        assert.end();
    }
});

test('running send_test.js', function t(assert) {
    spawnExample('send_test.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');
        [
            'server got ping req from 127.0.0.1:',
            'func 3 starting response timer',
            'func 1 responding immediately',
            'ping res from client: pong',
            '1 fast res: arg2=result arg3=indeed it did',
            'client got ping req from 127.0.0.1:',
            'ping res server: pong',
            '2 slow res: err=request timed out after',
            'func 3 starting response timer',
            'func 3 starting response timer',
            'func 3 responding now',
            '3 slow res: err=request timed out after',
            '4 slow res: err=request timed out after',
            'func 3 responding now',
            'func 3 responding now'
        ].forEach(function each(str) {
            assert.ok(stdout.indexOf(
                str
            ) >= 0);
        });

        assert.end();
    }
});

function spawnExample(exampleName, cb) {
    var file = path.join(__dirname, '..', 'examples', exampleName);

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

'use strict';

var test = require('tape');
var path = require('path');
var exec = require('child_process').exec;

test('running example1.js', function t(assert) {
    spawnExample('example1.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');

        assert.ok(stdout.indexOf(
            'func1 responding with a small delay { arg2: \'arg 1\', arg3: \'arg 2\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'err res:  { ok: false, message: \'it failed\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'normal res: { arg2: \'result\', arg3: \'indeed it did\' }'
        ) >= 0);

        assert.end();
    }
});

test('running example2.js', function t(assert) {
    spawnExample('example2.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');

        assert.ok(stdout.indexOf(
            'server got ping req from { remoteAddr: \'127.0.0.1:4041\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'ping res from server { arg2: \'pong\', arg3: \'\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'client got ping req from { remoteAddr: \'127.0.0.1:4040\' }'
        ) >= 0);
        assert.ok(stdout.indexOf(
            'ping res from client { arg2: \'pong\', arg3: \'\' }'
        ) >= 0);

        assert.end();
    }
});

test('running as_example.js', function t(assert) {
    spawnExample('as_example1.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');

        assert.ok(stdout.indexOf(
            'got resp { ok: true,'
        ) >= 0);
        assert.ok(stdout.indexOf(
            '  head: { head: \'object\' },'
        ) >= 0);
        assert.ok(stdout.indexOf(
            '  body: { body: \'object\' },'
        ) >= 0);
        assert.ok(stdout.indexOf(
            '  headers: { as: \'json\' } }'
        ) >= 0);

        assert.end();
    }
});

test('running send_test.js', function t(assert) {
    spawnExample('send_test.js', onChild);

    function onChild(err, stdout, stderr) {
        assert.ifError(err);
        assert.equal(stderr, '');
        [
            'server got ping req from 127.0.0.1:',
            'func 3 starting response timer',
            'func 1 responding immediately',
            'ping res from client: pong',
            '1 fast res: arg2=result arg3=indeed it did',
            'client got ping req from 127.0.0.1:',
            'ping res server: pong',
            '2 slow res: err=request timed out after',
            'func 3 starting response timer',
            'func 3 starting response timer',
            'func 3 responding now',
            '3 slow res: err=request timed out after',
            '4 slow res: err=request timed out after',
            'func 3 responding now',
            'func 3 responding now'
        ].forEach(function each(str) {
            assert.ok(stdout.indexOf(
                str
            ) >= 0);
        });

        assert.end();
    }
});

function spawnExample(exampleName, cb) {
    var file = path.join(__dirname, '..', 'examples', exampleName);

    exec('node ' + file, cb);
}
<|endoftext|>


<commit_before>/* global describe, it, before, after */
'use strict';
const InstanceManager = require('../InstanceManager.js');
const expect = require('chai').expect;
const arangojs = require('arangojs');
const rp = require('request-promise');
const fs = require('fs');

describe('Failover', function () {
  let instanceManager = new InstanceManager('failover');
  let db;

  let getLeader = function() {
    return rp({
      method: 'POST',
      url: instanceManager.getEndpointUrl(instanceManager.agents()[0]) + '/_api/agency/read',
      json: true,
      body: [['/']],
    })
    .then(data => {
      let plan    = data[0].arango.Plan;

      let plannedCollection = Object.keys(plan.Collections['_system']).reduce((result, cid) => {
        if (result) {
          return result;
        }

        if (plan.Collections['_system'][cid].name == 'testcollection') {
          return plan.Collections['_system'][cid];
        }
        return undefined;
      }, undefined);
      let shardName = Object.keys(plannedCollection.shards)[0];
      let leaderId = plannedCollection.shards[shardName][0];
      let leaderEndpoint = data[0].arango.Current.ServersRegistered[leaderId].endpoint;
      return instanceManager.dbServers().reduce((found, server) => {
        if (found) {
          return found;
        }

        if (server.endpoint == leaderEndpoint) {
          return server;
        }

        return undefined;
      }, undefined);
    })
  }
  before(function () {
    return instanceManager.startCluster(1, 2, 2)
    .then(() => {
      db = arangojs({
        url: instanceManager.getEndpointUrl(),
        databaseName: '_system'
      });
      return db.collection('testcollection').create({shards: 4, replicationFactor: 2})
      .then(() => {
        return Promise.all([
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()})
        ]);
      })
      .then(() => {
        let maxTime = Date.now() + 30000;
        let waitForSyncRepl = function() {
          if (Date.now() >= maxTime) {
            return Promise.reject(new Error('Lousy replication didn\'t come into sync after 30s for 7 documents. That is lol'));
          }
          return rp({
            method: 'POST',
            url: instanceManager.getEndpointUrl(instanceManager.agents()[0]) + '/_api/agency/read',
            json: true,
            body: [['/']],
          })
          .then(data => {
            let plan    = data[0].arango.Plan;
            let current = data[0].arango.Current;
            let plannedCollection = Object.keys(plan.Collections['_system']).reduce((result, cid) => {
              if (result) {
                return result;
              }

              if (plan.Collections['_system'][cid].name == 'testcollection') {
                return plan.Collections['_system'][cid];
              }
              return undefined;
            }, undefined);

            let done = Object.keys(plannedCollection.shards).every(shardName => {
              return current.Collections['_system'][plannedCollection.id][shardName].servers.length == 2;
            });
            if (!done) {
              return new Promise((resolve, reject) => {
                setTimeout(resolve, 100);
              })
              .then(() => {
                return waitForSyncRepl();
              });
            }
          });
        };

        return waitForSyncRepl();
      })
    })
  });

  it('should fail over to another replica when a server goes down', function () {
    return getLeader()
    .then(dbServer => {
      return instanceManager.kill(dbServer);
    })
    .then(() => {
      return db.collection('testcollection').save({'testung': Date.now()});
    })
    .then(() => {
      return db.collection('testcollection').count();
    })
    .then(count => {
      expect(count.count).to.equal(8);
    })
  });

  it('should allow importing even when a leader fails', function() {
    let docs = [...Array(10000)].map(function(_,key) {
      return {
        _key: "k" + key,
        'hans': 'kanns',
      }
    });
    return getLeader()
    .then(dbServer => {
      let slicedImport = function(index) {
        let count = 10;
        if (index < docs.length - 1) {
          return db.collection('testcollection').import(docs.slice(index, index + count))
          .then(result => {
            return new Promise((resolve, reject) => {
              setTimeout(resolve, 100);
            })
            .then(() => {
              return slicedImport(index + count);
            });
          });
        } else {
          return Promise.resolve();
        }
      }
      return Promise.all([
        slicedImport(0),
        instanceManager.kill(dbServer),
      ]);
    })
    .then(() => {
      return db.collection('testcollection').count();
    })
    .then(count => {
      expect(count.count).to.equal(10007);
    })
    .then(() => {
      return db.collection('testcollection').all();
    })
    .then(cursor => {
      return cursor.all();
    })
    .then(savedDocs => {
      expect(savedDocs.length).to.equal(10007);
    });
  });

  after(function () {
    return instanceManager.cleanup();
  });

  afterEach(function() {
    return Promise.all(
      instanceManager.instances.filter(instance => instance.status != 'RUNNING')
      .map(instance => instanceManager.restart(instance))
    );
    if (this.currentTest.state === 'failed') {
      this.currentTest.err.message = instanceManager.currentLog + '\n\n' + this.currentTest.err.message;
    }
  });
});
<commit_msg>removed failover test until fix<commit_after>/* global describe, it, before, after */
'use strict';
const InstanceManager = require('../InstanceManager.js');
const expect = require('chai').expect;
const arangojs = require('arangojs');
const rp = require('request-promise');
const fs = require('fs');

describe('Failover', function () {
  let instanceManager = new InstanceManager('failover');
  let db;

  let getLeader = function() {
    return rp({
      method: 'POST',
      url: instanceManager.getEndpointUrl(instanceManager.agents()[0]) + '/_api/agency/read',
      json: true,
      body: [['/']],
    })
    .then(data => {
      let plan    = data[0].arango.Plan;

      let plannedCollection = Object.keys(plan.Collections['_system']).reduce((result, cid) => {
        if (result) {
          return result;
        }

        if (plan.Collections['_system'][cid].name == 'testcollection') {
          return plan.Collections['_system'][cid];
        }
        return undefined;
      }, undefined);
      let shardName = Object.keys(plannedCollection.shards)[0];
      let leaderId = plannedCollection.shards[shardName][0];
      let leaderEndpoint = data[0].arango.Current.ServersRegistered[leaderId].endpoint;
      return instanceManager.dbServers().reduce((found, server) => {
        if (found) {
          return found;
        }

        if (server.endpoint == leaderEndpoint) {
          return server;
        }

        return undefined;
      }, undefined);
    })
  }
  before(function () {
    return instanceManager.startCluster(1, 2, 2)
    .then(() => {
      db = arangojs({
        url: instanceManager.getEndpointUrl(),
        databaseName: '_system'
      });
      return db.collection('testcollection').create({shards: 4, replicationFactor: 2})
      .then(() => {
        return Promise.all([
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()}),
          db.collection('testcollection').save({'testung': Date.now()})
        ]);
      })
      .then(() => {
        let maxTime = Date.now() + 30000;
        let waitForSyncRepl = function() {
          if (Date.now() >= maxTime) {
            return Promise.reject(new Error('Lousy replication didn\'t come into sync after 30s for 7 documents. That is lol'));
          }
          return rp({
            method: 'POST',
            url: instanceManager.getEndpointUrl(instanceManager.agents()[0]) + '/_api/agency/read',
            json: true,
            body: [['/']],
          })
          .then(data => {
            let plan    = data[0].arango.Plan;
            let current = data[0].arango.Current;
            let plannedCollection = Object.keys(plan.Collections['_system']).reduce((result, cid) => {
              if (result) {
                return result;
              }

              if (plan.Collections['_system'][cid].name == 'testcollection') {
                return plan.Collections['_system'][cid];
              }
              return undefined;
            }, undefined);

            let done = Object.keys(plannedCollection.shards).every(shardName => {
              return current.Collections['_system'][plannedCollection.id][shardName].servers.length == 2;
            });
            if (!done) {
              return new Promise((resolve, reject) => {
                setTimeout(resolve, 100);
              })
              .then(() => {
                return waitForSyncRepl();
              });
            }
          });
        };

        return waitForSyncRepl();
      })
    })
  });

  it('should fail over to another replica when a server goes down', function () {
    return getLeader()
    .then(dbServer => {
      return instanceManager.kill(dbServer);
    })
    .then(() => {
      return db.collection('testcollection').save({'testung': Date.now()});
    })
    .then(() => {
      return db.collection('testcollection').count();
    })
    .then(count => {
      expect(count.count).to.equal(8);
    })
  });

  /*
  it('should allow importing even when a leader fails', function() {
    let docs = [...Array(10000)].map(function(_,key) {
      return {
        _key: "k" + key,
        'hans': 'kanns',
      }
    });
    return getLeader()
    .then(dbServer => {
      let slicedImport = function(index) {
        let count = 10;
        if (index < docs.length - 1) {
          return db.collection('testcollection').import(docs.slice(index, index + count))
          .then(result => {
            return new Promise((resolve, reject) => {
              setTimeout(resolve, 100);
            })
            .then(() => {
              return slicedImport(index + count);
            });
          });
        } else {
          return Promise.resolve();
        }
      }
      return Promise.all([
        slicedImport(0),
        instanceManager.kill(dbServer),
      ]);
    })
    .then(() => {
      return db.collection('testcollection').count();
    })
    .then(count => {
      expect(count.count).to.equal(10007);
    })
    .then(() => {
      return db.collection('testcollection').all();
    })
    .then(cursor => {
      return cursor.all();
    })
    .then(savedDocs => {
      expect(savedDocs.length).to.equal(10007);
    });
  });*/

  after(function () {
    return instanceManager.cleanup();
  });

  afterEach(function() {
    return Promise.all(
      instanceManager.instances.filter(instance => instance.status != 'RUNNING')
      .map(instance => instanceManager.restart(instance))
    );
    if (this.currentTest.state === 'failed') {
      this.currentTest.err.message = instanceManager.currentLog + '\n\n' + this.currentTest.err.message;
    }
  });
});
<|endoftext|>


<commit_before>import { addPlugin, getPlugins } from '../config';
import installPlugins from '../plugins';

/**
 * Registers the `plugins` commands.
 *
 * @param vorpal The Vorpal instance.
 */
export default function pluginsFactory(vorpal) {
  const { chalk } = vorpal;
  vorpal
    .command('plugins install <plugin>')
    .description('Installs a plugin.')
    .action(async function (args, callback) {
      const { plugin } = args;
      addPlugin(plugin);
      try {
        await installPlugins();
      } catch (err) {
        this.log(chalk.red(err.message));
      }
      callback();
    });
  vorpal
    .command('plugins list')
    .alias('plugins ls')
    .description('Lists installed plugins.')
    .action(function (args, callback) {
      const plugins = getPlugins();
      this.log(`Installed Plugins (${plugins.length}):`);
      this.log(plugins.map(plugin => `    * ${plugin}`).join('\n'));
      callback();
    });
  vorpal
    .command('plugins remove <plugin>')
    .alias('plugins rm <plugin>')
    .description('Removes a plugin.')
    .action(async function (args, callback) {
      const { plugin } = args;
      removePlugin(plugin);
      try {
        await installPlugins();
      } catch (err) {
        this.log(chalk.red(err.message));
      }
      callback();
    });
}
<commit_msg>Add command aliases<commit_after>import { addPlugin, removePlugin, getPlugins } from '../config';
import installPlugins from '../plugins';

/**
 * Registers the `plugins` commands.
 *
 * @param vorpal The Vorpal instance.
 */
export default function pluginsFactory(vorpal) {
  const { chalk } = vorpal;
  vorpal
    .command('plugins install <plugin>')
    .alias('plugins i')
    .description('Installs a plugin.')
    .action(async function (args, callback) {
      const { plugin } = args;
      addPlugin(plugin);
      try {
        await installPlugins();
      } catch (err) {
        this.log(chalk.red(err.message));
      }
      callback();
    });
  vorpal
    .command('plugins list')
    .alias('plugins ls')
    .description('Lists installed plugins.')
    .action(function (args, callback) {
      const plugins = getPlugins();
      this.log(`Installed Plugins (${plugins.length}):`);
      this.log(plugins.map(plugin => `    * ${plugin}`).join('\n'));
      callback();
    });
  vorpal
    .command('plugins remove <plugin>')
    .alias('plugins rm')
    .description('Removes a plugin.')
    .action(async function (args, callback) {
      const { plugin } = args;
      removePlugin(plugin);
      try {
        await installPlugins();
      } catch (err) {
        this.log(chalk.red(err.message));
      }
      callback();
    });
}
<|endoftext|>


<commit_before>/**
 * Offset key parser regex.
 *
 * @type {RegExp}
 */

const PARSER = /^(\w+)(?::(\d+))?$/

/**
 * Parse an offset key `string`.
 *
 * @param {String} string
 * @return {Object}
 */

function parse(string) {
  const matches = PARSER.exec(string)

  if (!matches) {
    throw new Error(`Invalid offset key string "${string}".`)
  }

  const [original, key, index] = matches // eslint-disable-line no-unused-vars
  return {
    key,
    index: parseInt(index, 10),
  }
}

/**
 * Stringify an offset key `object`.
 *
 * @param {Object} object
 *   @property {String} key
 *   @property {Number} index
 * @return {String}
 */

function stringify(object) {
  return `${object.key}:${object.index}`
}

/**
 * Export.
 *
 * @type {Object}
 */

export default {
  parse,
  stringify,
}
<commit_msg>Fix #474 (#1700)<commit_after>/**
 * Offset key parser regex.
 *
 * @type {RegExp}
 */

const PARSER = /^([\w-]+)(?::(\d+))?$/

/**
 * Parse an offset key `string`.
 *
 * @param {String} string
 * @return {Object}
 */

function parse(string) {
  const matches = PARSER.exec(string)

  if (!matches) {
    throw new Error(`Invalid offset key string "${string}".`)
  }

  const [original, key, index] = matches // eslint-disable-line no-unused-vars
  return {
    key,
    index: parseInt(index, 10),
  }
}

/**
 * Stringify an offset key `object`.
 *
 * @param {Object} object
 *   @property {String} key
 *   @property {Number} index
 * @return {String}
 */

function stringify(object) {
  return `${object.key}:${object.index}`
}

/**
 * Export.
 *
 * @type {Object}
 */

export default {
  parse,
  stringify,
}
<|endoftext|>


<commit_before>/*global angular, d3, _*/
'use strict';

angular.module('mean.system')
.controller('BattleController', ['$scope', 'Global', 'socket', function ($scope, Global, socket) {
    $scope.global = Global;
    console.log( 'Battle started' );

    // Game state is contiained in this structure, which is synchronized between devices
    var gameState,
        fire,
        updateArena;
    // Create SVG to hold game arena
    var width = 800;
    var height = 600;
    var creatureSize = 50; // How big creatures should be
    var shotSize = 10; // How big shots should be
    var arena = d3.select('#arena').append('svg')
      .attr('width', width)
      .attr('height', height)
      .style('fill', '#000000')
      .append('g');

    var init = function() {
      // TODO do not hardcode
      //if ( !shift ) {
        //arena.attr( 'transform', 'translate(0, ' + height / 2 + ')' );
      //}
    };

    // Helper functions and behaviours for creatures
    var positionCreature = function( creature ) {
      creature
        .attr( 'xlink:href', function(d) {
          var uniqueName = d.player + d.id;
          // TODO Massive security hole!!!!!
          return 'http://robohash.org/' + uniqueName;
        } )
        .attr('x', function(d) { return d.position.x - 64; })
        .attr('y', function(d) { return d.position.y - 64; })
        .attr('width', 128)
        .attr('height', 128);
    };

    // Add behaviour for dragging, to shoot
    var drag = d3.behavior.drag()
      .origin(function(d) { return d.position; })
      .on('dragstart', function( d ) {
        // Stash away drag points
        d._dragPoints = [];
      })
      .on('drag', function( d ) {
        // Stash
        var point = {
          x: d3.event.x,
          y: d3.event.y
        };
        d._dragPoints.push( point );
      })
      .on('dragend', function( d ) {
        var start = d._dragPoints[0];
        var end = d._dragPoints[d._dragPoints.length - 1];
        console.log( d._dragPoints );
        console.log( start );
        console.log( end );
        var dragDirection = {
          x: end.x - start.x,
          y: end.y - start.y
        };
        console.log( 'Dragged in direction:' );
        console.log( dragDirection );
        var shot = {
          position: start,
          direction: dragDirection,
          creature: d
        };

        fire( shot );
      });

    fire = function( shot ) {
      // Normalize direction
      var factor = shot.direction.y > 0 ? ( height - shot.position.y - 50 ) / shot.direction.y : ( 50 - shot.position.y ) / shot.direction.y;
      shot.direction.x *= factor;
      shot.direction.y *= factor;
      gameState.shots.push( shot );
      updateArena();
      $scope.sendData(gameState);
    };

    // Rendering, binds actions to SVG elements using d3
    updateArena = function() {
      // Add creatures for player one (assuming it's `me`)
      var creatures = arena.selectAll( 'image.creature' )
        .data( gameState.creatures ); // Bind creatures data set to selection

      // Create new creatures
      creatures.enter().append( 'image' )
          .classed('creature', true)
          .call( drag );

      // Update creatures
      creatures
          .call( positionCreature );

      // Add health labels
      var health = arena.selectAll( 'text.health' )
        .data( gameState.creatures );

      health
        .enter().append( 'text' )
          .classed('health', true)
          .style('fill', '#ff4100')
          .attr('x', function(d) { return d.position.x + 30; })
          .attr('y', function(d) { return d.position.y - 20; });

      health
        .text( function( d ) { return d.health; } );

      // Bind drag behaviour to creatures

      // Add shots
      arena.selectAll( 'circle.shot' )
        .data( gameState.shots )
        .enter().append( 'circle' )
          .classed('shot', true)
          .attr('r', shotSize)
          .attr('cx', function(d) { return d.position.x; })
          .attr('cy', function(d) { return d.position.y; })
        .transition()
          .ease( 'linear' )
          .attr('cx', function(d) { return d.position.x + d.direction.x; })
          .attr('cy', function(d) { return d.position.y + d.direction.y; })
          .each( 'end', function( d, i ) {
            // Remove shot at end of animation
            gameState.shots.splice( i, 1 );

            // Check if we hit something (pretty terrible hit-testing, should use line/circle intersection)
            for ( var c in gameState.creatures ) {
              if( gameState.creatures.hasOwnProperty( c ) ) {
                var creature = gameState.creatures[c];
                if ( Math.abs( d.position.x + d.direction.x - creature.position.x ) < 1.1 * creatureSize &&
                     Math.abs( d.position.y + d.direction.y - creature.position.y ) < 2.0 * creatureSize) {
                  creature.health -= 10;
                  updateArena();
                  break;
                }
              }
            }
          })
          .remove();
    };

    //d3.json('system/data.json', function(error, json) {
    //  if (error) {
    //    return console.warn(error);
    //  }
    //  gameState = json;
    //  init();
    //  updateArena();
    //});

	$scope.sendData = function (data) {
		var dataReady = {room: window.gameConnection.room};
    dataReady.data = data;
    socket.emit('gameConnection', dataReady);
	};

	socket.on('gameConnection', function (data) {
		gameState = data.data;
		updateArena();
	});

  // Receive/send data
  $scope.sendData = function (data) {
    var dataReady = window.gameConnection;
    if ( dataReady ) {
      dataReady.data = data;
      socket.emit('gameConnection', dataReady);
    }
  };

  socket.on('gameConnection', function (data) {
    mergeState( data );
    console.log( gameState );
    updateArena();
  });

  // Generate game data (mock out data for now)
  gameState = {
    'creatures': [],
    'shots': []
  };
  for( var a = 0; a < 3; a++ ) {
    var creature = {
      'id': 'creature_' + a,
      'player': window.user.username,
      'health': 100,
      'attack': 7,
      'defense': 4,
      'type': 'fire',
      'position': {
        'x': 50 + 350 * a,
        'y': 50
      }
    };
    gameState.creatures.push( creature );
  }
  console.log( gameState );
  $scope.sendData( gameState );
  init();
  //updateArena();

  var mergeState = function( data ) {
    console.log( 'Merging state' );
    if ( data.data ) {
      // Combine all creatures
      gameState.creatures = gameState.creatures.concat( data.data.creatures );
      gameState.creatures = _.uniq( gameState.creatures, false, function( d ) { return d.player + d.id; } );

      // Combine all shots
      gameState.shots = gameState.shots.concat( data.data.shots );
      gameState.shots = _.uniq( gameState.shots, false, function( d ) { return d.creature.player + d.creature.id; } );

      // Get players to figure out who to put at bottom
      var players = _.uniq( _.pluck( gameState.creatures, 'player' ) );
      players.sort();

      // Shift bottom player's creatures to bottom of screen
      var bottomPlayer = players[0];
      console.log( 'players ' + players);
      console.log( 'Bottom ' + bottomPlayer);
      _.each( gameState.creatures, function( creature ) {
        if ( creature.player === bottomPlayer ) {
          creature.position.y = 550;
        }
      } );
      //if ( bottomPlayer === me ) {
      //  // Do something...
      //}
    }
  };
}]);
<commit_msg>Fix merge cockups<commit_after>/*global angular, d3, _*/
'use strict';

angular.module('mean.system')
.controller('BattleController', ['$scope', 'Global', 'socket', function ($scope, Global, socket) {
    $scope.global = Global;
    console.log( 'Battle started' );
    console.log( window.user.battleCreatures );

    // Game state is contiained in this structure, which is synchronized between devices
    var gameState,
        fire,
        updateArena;
    // Create SVG to hold game arena
    var width = 800;
    var height = 600;
    var creatureSize = 50; // How big creatures should be
    var shotSize = 10; // How big shots should be
    var arena = d3.select('#arena').append('svg')
      .attr('width', width)
      .attr('height', height)
      .style('fill', '#000000')
      .append('g');

    var init = function() {
      // TODO do not hardcode
      //if ( !shift ) {
        //arena.attr( 'transform', 'translate(0, ' + height / 2 + ')' );
      //}
    };

    // Helper functions and behaviours for creatures
    var positionCreature = function( creature ) {
      creature
        .attr( 'xlink:href', function(d) {
          var uniqueName = d.player + d.id;
          // TODO Massive security hole!!!!!
          return 'http://robohash.org/' + uniqueName;
        } )
        .attr('x', function(d) { return d.position.x - 64; })
        .attr('y', function(d) { return d.position.y - 64; })
        .attr('width', 128)
        .attr('height', 128);
    };

    // Add behaviour for dragging, to shoot
    var drag = d3.behavior.drag()
      .origin(function(d) { return d.position; })
      .on('dragstart', function( d ) {
        // Stash away drag points
        d._dragPoints = [];
      })
      .on('drag', function( d ) {
        // Stash
        var point = {
          x: d3.event.x,
          y: d3.event.y
        };
        d._dragPoints.push( point );
      })
      .on('dragend', function( d ) {
        var start = d._dragPoints[0];
        var end = d._dragPoints[d._dragPoints.length - 1];
        console.log( d._dragPoints );
        console.log( start );
        console.log( end );
        var dragDirection = {
          x: end.x - start.x,
          y: end.y - start.y
        };
        console.log( 'Dragged in direction:' );
        console.log( dragDirection );
        var shot = {
          position: start,
          direction: dragDirection,
          creature: d
        };

        fire( shot );
      });

    fire = function( shot ) {
      // Normalize direction
      var factor = shot.direction.y > 0 ? ( height - shot.position.y - 50 ) / shot.direction.y : ( 50 - shot.position.y ) / shot.direction.y;
      shot.direction.x *= factor;
      shot.direction.y *= factor;
      gameState.shots.push( shot );
      updateArena();
      $scope.sendData(gameState);
    };

    // Rendering, binds actions to SVG elements using d3
    updateArena = function() {
      // Add creatures for player one (assuming it's `me`)
      var creatures = arena.selectAll( 'image.creature' )
        .data( gameState.creatures ); // Bind creatures data set to selection

      // Create new creatures
      creatures.enter().append( 'image' )
          .classed('creature', true)
          .call( drag );

      // Update creatures
      creatures
          .call( positionCreature );

      // Add health labels
      var health = arena.selectAll( 'text.health' )
        .data( gameState.creatures );

      health
        .enter().append( 'text' )
          .classed('health', true)
          .style('fill', '#ff4100')
          .attr('x', function(d) { return d.position.x + 30; })
          .attr('y', function(d) { return d.position.y - 20; });

      health
        .text( function( d ) { return d.health; } );

      // Bind drag behaviour to creatures

      // Add shots
      arena.selectAll( 'circle.shot' )
        .data( gameState.shots )
        .enter().append( 'circle' )
          .classed('shot', true)
          .attr('r', shotSize)
          .attr('cx', function(d) { return d.position.x; })
          .attr('cy', function(d) { return d.position.y; })
        .transition()
          .ease( 'linear' )
          .attr('cx', function(d) { return d.position.x + d.direction.x; })
          .attr('cy', function(d) { return d.position.y + d.direction.y; })
          .each( 'end', function( d, i ) {
            // Remove shot at end of animation
            gameState.shots.splice( i, 1 );

            // Check if we hit something (pretty terrible hit-testing, should use line/circle intersection)
            for ( var c in gameState.creatures ) {
              if( gameState.creatures.hasOwnProperty( c ) ) {
                var creature = gameState.creatures[c];
                if ( Math.abs( d.position.x + d.direction.x - creature.position.x ) < 1.1 * creatureSize &&
                     Math.abs( d.position.y + d.direction.y - creature.position.y ) < 2.0 * creatureSize) {
                  creature.health -= 10;
                  updateArena();
                  break;
                }
              }
            }
          })
          .remove();
    };

    //d3.json('system/data.json', function(error, json) {
    //  if (error) {
    //    return console.warn(error);
    //  }
    //  gameState = json;
    //  init();
    //  updateArena();
    //});

  // Receive/send data
	$scope.sendData = function (data) {
		var dataReady = {room: window.gameConnection.room};
    dataReady.data = data;
    socket.emit('gameConnection', dataReady);
	};

  socket.on('gameConnection', function (data) {
    mergeState( data );
    console.log( gameState );
    updateArena();
  });

  // Generate game data (mock out data for now)
  gameState = {
    'creatures': [],
    'shots': []
  };
  for( var a = 0; a < 3; a++ ) {
    var creature = {
      'id': 'creature_' + a,
      'player': window.user.username,
      'health': 100,
      'attack': 7,
      'defense': 4,
      'type': 'fire',
      'position': {
        'x': 50 + 350 * a,
        'y': 50
      }
    };
    gameState.creatures.push( creature );
  }
  console.log( gameState );
  $scope.sendData( gameState );
  init();

  var mergeState = function( data ) {
    console.log( 'Merging state' );
    if ( data.data ) {
      // Combine all creatures
      gameState.creatures = gameState.creatures.concat( data.data.creatures );
      gameState.creatures = _.uniq( gameState.creatures, false, function( d ) { return d.player + d.id; } );

      // Combine all shots
      gameState.shots = gameState.shots.concat( data.data.shots );
      gameState.shots = _.uniq( gameState.shots, false, function( d ) { return d.creature.player + d.creature.id; } );

      // Get players to figure out who to put at bottom
      var players = _.uniq( _.pluck( gameState.creatures, 'player' ) );
      players.sort();

      // Shift bottom player's creatures to bottom of screen
      var bottomPlayer = players[0];
      console.log( 'players ' + players);
      console.log( 'Bottom ' + bottomPlayer);
      _.each( gameState.creatures, function( creature ) {
        if ( creature.player === bottomPlayer ) {
          creature.position.y = 550;
        }
      } );
      //if ( bottomPlayer === me ) {
      //  // Do something...
      //}
    }
  };
}]);
<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: link_module.js
 */

module.exports = {
    malloc: function (root_object_val, my_name_val, link_id_val) {
        return new FabricLinkClass(root_object_val, my_name_val, link_id_val);
    },
};

function FabricLinkClass(root_object_val, my_name_val, link_id_val) {
    "use strict";

    this.init__ = function (root_object_val, my_name_val, link_id_val) {
        this.theRootObject  = root_object_val;
        this.theLinkId = link_id_val;
        this.theMyName = my_name_val;
        this.theJointObject = this.importListMgr().malloc_joint(link_id_val, my_name_val);
        this.theSessionListObject = this.importListMgr().malloc_mgr(this, 10000);
        this.up_seq = 0;
        this.down_seq = 0;
        this.theReceiveQueue = this.importObject().mallocQueue();
        this.thePendingSessionSetupQueue = this.importObject().mallocQueue();
        this.theNameListChanged = true;
        this.theKeepAliveTimer = null;
        this.thePrev = null;
        this.theNext = null;
        this.debug(true, "init__", "link_id=" + this.linkId());
    };

    this.linkTimeoutInterval = function () {
        return 30000;
    };

    this.objectName = function () {
        return "FabricLinkClass";
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.jointObject = function () {
        return this.theJointObject;
    };

    this.importObject = function () {
        return this.rootObject().importObject();
    };

    this.linkMgrObject = function () {
        return this.rootObject().linkMgrObject();
    };

    this.importListMgr = function () {
        return this.importObject().importListMgr();
    };

    this.sessionListObject = function () {
        return this.theSessionListObject;
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.linkId = function () {
        return this.theLinkId;
    };

    this.setLinkId = function (val) {
        this.theLinkId = val;
    };

    this.myName = function () {
        return this.theMyName;
    };

    this.setMyName = function (val) {
        this.theMyName = val;
    };

    this.keepAliveTimer = function () {
        return this.theKeepAliveTimer;
    };

    this.setKeepAliveTimer = function (val) {
        this.theKeepAliveTimer = val;
    };

    this.receiveQueue = function () {
        return this.theReceiveQueue;
    };

    this.receiveRing = function () {
        return this.theReceiveRing;
    };

    this.pendingSessionSetupQueue = function () {
        return this.thePendingSessionSetupQueue;
    };

    this.nameListChanged = function () {
        return this.theNameListChanged;
    };

    this.setNameListChanged = function () {
        this.theNameListChanged = true;
    };

    this.clearNameListChanged = function () {
        this.theNameListChanged = false;
    };

    this.resetKeepAliveTimer = function () {
        this.debug(false, "keepAlive", "my_name=" + this.my_name + " link_id=" + this.link_id);
        this.setKeepAliveTimer(this.resetTimeout());
    };

    this.resetTimeout = function () {
        if (this.keepAliveTimer()) {
            clearTimeout(this.keepAliveTimer());
        }
        this.debug(false, "resetTimeout", "my_name=" + this.my_name + " link_id=" + this.link_id);
        var time_out = setTimeout(function (link_val) {
            console.log("resetTimeout(***timeout occurs)", "my_name=" + link_val.myName() + " link_id=" + link_val.linkId());
            link_val.linkMgrObject().unQueueLink(link_val);
        }, this.linkTimeoutInterval(), this);
        return time_out;
    };

    this.searchSessionBySessionId = function (session_id_val) {
        return this.sessionListObject().searchId(session_id_val);
    };

    this.mallocSession = function () {
        var session = this.importObject().importSession().malloc(this, this.sessionListObject().allocId());
        this.sessionListObject().enQueue(session);
        return session;
    };

    this.getPendingSessionData = function () {
        var data = [];
        var i = 0;
        var session = this.importListMgr().head(this.sessionListObject());
        while (session) {
            if (session.transmitQueue().size() > 0) {
                data[i] =  session.sessionId();
                i += 1;
            }
            session = this.importListMgr().next(session);
        }
        if (i === 0) {
            return null;
        }
        else {
            return data;
        }
    };

    this.getPendingSessionSetup = function () {
        return this.pendingSessionSetupQueue().deQueue();
    };

    this.setPendingSessionSetup = function (session_val, topic_data_val) {
        this.pendingSessionSetupQueue().enQueue(JSON.stringify({session_id: session_val.sessionId(),
                                                                topic_data: topic_data_val
                                                                }));
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.rootObject().LOG_IT(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.rootObject().ABEND(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__(root_object_val, my_name_val, link_id_val);
}
<commit_msg>matrix<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: link_module.js
 */

module.exports = {
    malloc: function (root_object_val, my_name_val, link_id_val) {
        return new FabricLinkClass(root_object_val, my_name_val, link_id_val);
    },
};

function FabricLinkClass(root_object_val, my_name_val, link_id_val) {
    "use strict";

    this.init__ = function (root_object_val, my_name_val, link_id_val) {
        this.theRootObject  = root_object_val;
        this.theLinkId = link_id_val;
        this.theMyName = my_name_val;
        this.theJointObject = this.importListMgr().malloc_joint(link_id_val, my_name_val);
        this.theSessionListObject = this.importListMgr().malloc_mgr(this, 10000);
        this.up_seq = 0;
        this.down_seq = 0;
        this.theReceiveQueue = this.importObject().mallocQueue();
        this.thePendingSessionSetupQueue = this.importObject().mallocQueue();
        this.theNameListChanged = true;
        this.theKeepAliveTimer = null;
        this.debug(true, "init__", "linkId=" + this.linkId());
    };

    this.linkTimeoutInterval = function () {
        return 30000;
    };

    this.objectName = function () {
        return "FabricLinkClass";
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.jointObject = function () {
        return this.theJointObject;
    };

    this.importObject = function () {
        return this.rootObject().importObject();
    };

    this.linkMgrObject = function () {
        return this.rootObject().linkMgrObject();
    };

    this.importListMgr = function () {
        return this.importObject().importListMgr();
    };

    this.sessionListObject = function () {
        return this.theSessionListObject;
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.linkId = function () {
        return this.theLinkId;
    };

    this.setLinkId = function (val) {
        this.theLinkId = val;
    };

    this.myName = function () {
        return this.theMyName;
    };

    this.setMyName = function (val) {
        this.theMyName = val;
    };

    this.keepAliveTimer = function () {
        return this.theKeepAliveTimer;
    };

    this.setKeepAliveTimer = function (val) {
        this.theKeepAliveTimer = val;
    };

    this.receiveQueue = function () {
        return this.theReceiveQueue;
    };

    this.receiveRing = function () {
        return this.theReceiveRing;
    };

    this.pendingSessionSetupQueue = function () {
        return this.thePendingSessionSetupQueue;
    };

    this.nameListChanged = function () {
        return this.theNameListChanged;
    };

    this.setNameListChanged = function () {
        this.theNameListChanged = true;
    };

    this.clearNameListChanged = function () {
        this.theNameListChanged = false;
    };

    this.resetKeepAliveTimer = function () {
        this.debug(false, "keepAlive", "my_name=" + this.my_name + " link_id=" + this.link_id);
        this.setKeepAliveTimer(this.resetTimeout());
    };

    this.resetTimeout = function () {
        if (this.keepAliveTimer()) {
            clearTimeout(this.keepAliveTimer());
        }
        this.debug(false, "resetTimeout", "my_name=" + this.my_name + " link_id=" + this.link_id);
        var time_out = setTimeout(function (link_val) {
            console.log("resetTimeout(***timeout occurs)", "my_name=" + link_val.myName() + " link_id=" + link_val.linkId());
            link_val.linkMgrObject().unQueueLink(link_val);
        }, this.linkTimeoutInterval(), this);
        return time_out;
    };

    this.searchSessionBySessionId = function (session_id_val) {
        return this.sessionListObject().searchId(session_id_val);
    };

    this.mallocSession = function () {
        var session = this.importObject().importSession().malloc(this, this.sessionListObject().allocId());
        this.sessionListObject().enQueue(session);
        return session;
    };

    this.getPendingSessionData = function () {
        var data = [];
        var i = 0;
        var session = this.importListMgr().head(this.sessionListObject());
        while (session) {
            if (session.transmitQueue().size() > 0) {
                data[i] =  session.sessionId();
                i += 1;
            }
            session = this.importListMgr().next(session);
        }
        if (i === 0) {
            return null;
        }
        else {
            return data;
        }
    };

    this.getPendingSessionSetup = function () {
        return this.pendingSessionSetupQueue().deQueue();
    };

    this.setPendingSessionSetup = function (session_val, topic_data_val) {
        this.pendingSessionSetupQueue().enQueue(JSON.stringify({session_id: session_val.sessionId(),
                                                                topic_data: topic_data_val
                                                                }));
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.rootObject().LOG_IT(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.rootObject().ABEND(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__(root_object_val, my_name_val, link_id_val);
}
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.asset.versions");
pimcore.asset.versions = Class.create({

    initialize: function(asset) {
        this.asset = asset;
    },

    getLayout: function () {

        if (this.layout == null) {

            var modelName = 'pimcore.model.assetversions';
            if (!Ext.ClassManager.get(modelName)) {
                Ext.define(modelName, {
                    extend: 'Ext.data.Model',
                    fields: ['id', 'date', 'scheduled', 'note', {
                        name: 'name', convert: function (v, rec) {
                            if (rec.data) {
                                if (rec.data.user) {
                                    if (rec.data.user.name) {
                                        return rec.data.user.name;
                                    }
                                }
                            }
                            return null;
                        }
                    }]
                });
            }

            this.store = new Ext.data.Store({
                model: modelName,
                sorters: [{
                    property: 'date',
                    direction: 'DESC'
                }],
                proxy: {
                    type: 'ajax',
                    url: "/admin/asset/get-versions",
                    extraParams: {
                        id: this.asset.id
                    },
                    // Reader is now on the proxy, as the message was explaining
                    reader: {
                        type: 'json',
                        rootProperty: 'versions'

                        //totalProperty:'total',            // default
                        //successProperty:'success'         // default
                    }
                    //,                                     // default
                    //writer: {
                    //    type: 'json'
                    //}
                }

            });

            var grid = Ext.create('Ext.grid.Panel', {
                store: this.store,
                columns: [
                    {header: t("date"), width:130, sortable: true, dataIndex: 'date', renderer: function(d) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    }},
                    {header: t("user"), sortable: true, dataIndex: 'name'},
                    {header: t("scheduled"), width:130, sortable: true, dataIndex: 'scheduled', renderer: function(d) {
                        if (d != null){
                        	var date = new Date(d * 1000);
                            return Ext.Date.format(date, "Y-m-d H:i:s");
                    	}
                    }, editable: false}
                    // Not used {header: t("note"), sortable: true, dataIndex: 'note'}
                ],
                stripeRows: true,
                width:360,
                title: t('available_versions'),
                region: "west",
                viewConfig: {
                    getRowClass: function(record, rowIndex, rp, ds) {
                        if (record.data.date == this.asset.data.modificationDate) {
                            return "version_published";
                        }
                        return "";
                    }.bind(this)
                }
            });

            grid.on("rowclick", this.onRowClick.bind(this));
            grid.on("rowcontextmenu", this.onRowContextmenu.bind(this));
            grid.on("beforerender", function () {
                this.store.load();
            }.bind(this));

            grid.reference = this;

            var preview = new Ext.Panel({
                title: t("preview"),
                region: "center",
                bodyStyle: "-webkit-overflow-scrolling:touch;",
                html: ''
            });

            this.layout = new Ext.Panel({
                title: t('versions'),
                bodyStyle:'padding:20px 5px 20px 5px;',
                border: false,
                layout: "border",
                iconCls: "pimcore_icon_tab_versions",
                items: [grid,preview]
            });

            preview.on("resize", this.onLayoutResize.bind(this));
        }

        return this.layout;
    },

    onLayoutResize: function (el, width, height, rWidth, rHeight) {
        this.setLayoutFrameDimensions(width, height);
    },

    setLayoutFrameDimensions: function (width, height) {
        Ext.get("asset_version_iframe_" + this.asset.id).setStyle({
            width: width + "px",
            height: (height - 25) + "px"
        });
    },

    onRowClick: function(grid, record, tr, rowIndex, e, eOpts ) {
        var data = grid.getStore().getAt(rowIndex).data;

        var versionId = data.id;
        var path = "/admin/asset/show-version/id/" + versionId;
        Ext.get("asset_version_iframe_" + this.asset.id).dom.src = path;
    },

    onRowContextmenu: function (grid, record, tr, rowIndex, e, eOpts ) {

        //$(grid.getView().getRow(rowIndex)).animate(
        //            { backgroundColor: '#E0EAEE' }, 100).animate( { backgroundColor: '#fff' }, 400);

        var menu = new Ext.menu.Menu();

        if (this.asset.isAllowed("publish")) {
            menu.add(new Ext.menu.Item({
                text: t('publish'),
                iconCls: "pimcore_icon_publish",
                handler: this.publishVersion.bind(this, rowIndex, grid)
            }));
        }

        menu.add(new Ext.menu.Item({
            text: t('delete'),
            iconCls: "pimcore_icon_delete",
            handler: this.removeVersion.bind(this, rowIndex, grid)
        }));

        e.stopEvent();
        menu.showAt(e.pageX, e.pageY);
    },

    removeVersion: function (index, grid) {

        var data = grid.getStore().getAt(index).data;
        var versionId = data.id;

        Ext.Ajax.request({
            url: "/admin/asset/delete-version",
            params: {id: versionId}
        });

        grid.getStore().removeAt(index);
    },

    publishVersion: function (index, grid) {
        var data = grid.getStore().getAt(index).data;
        var versionId = data.id;

        Ext.Ajax.request({
            url: "/admin/asset/publish-version",
            params: {id: versionId},
            success: this.asset.reload.bind(this.asset)
        });
    },

    reload: function () {
        this.store.reload();
    }

});<commit_msg>extjs6 - misc<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.asset.versions");
pimcore.asset.versions = Class.create({

    initialize: function(asset) {
        this.asset = asset;
    },

    getLayout: function () {

        if (this.layout == null) {

            var modelName = 'pimcore.model.assetversions';
            if (!Ext.ClassManager.get(modelName)) {
                Ext.define(modelName, {
                    extend: 'Ext.data.Model',
                    fields: ['id', 'date', 'scheduled', 'note', {
                        name: 'name', convert: function (v, rec) {
                            if (rec.data) {
                                if (rec.data.user) {
                                    if (rec.data.user.name) {
                                        return rec.data.user.name;
                                    }
                                }
                            }
                            return null;
                        }
                    }]
                });
            }

            this.store = new Ext.data.Store({
                model: modelName,
                sorters: [{
                    property: 'date',
                    direction: 'DESC'
                }],
                proxy: {
                    type: 'ajax',
                    url: "/admin/asset/get-versions",
                    extraParams: {
                        id: this.asset.id
                    },
                    // Reader is now on the proxy, as the message was explaining
                    reader: {
                        type: 'json',
                        rootProperty: 'versions'
                    }
                }

            });

            var grid = Ext.create('Ext.grid.Panel', {
                store: this.store,
                columns: [
                    {header: t("date"), width:130, sortable: true, dataIndex: 'date', renderer: function(d) {
                        var date = new Date(d * 1000);
                        return Ext.Date.format(date, "Y-m-d H:i:s");
                    }},
                    {header: t("user"), sortable: true, dataIndex: 'name'},
                    {header: t("scheduled"), width:130, sortable: true, dataIndex: 'scheduled', renderer: function(d) {
                        if (d != null){
                        	var date = new Date(d * 1000);
                            return Ext.Date.format(date, "Y-m-d H:i:s");
                    	}
                    }, editable: false}
                ],
                stripeRows: true,
                width:370,
                title: t('available_versions'),
                region: "west",
                viewConfig: {
                    getRowClass: function(record, rowIndex, rp, ds) {
                        if (record.data.date == this.asset.data.modificationDate) {
                            return "version_published";
                        }
                        return "";
                    }.bind(this)
                }
            });

            grid.on("rowclick", this.onRowClick.bind(this));
            grid.on("rowcontextmenu", this.onRowContextmenu.bind(this));
            grid.on("beforerender", function () {
                this.store.load();
            }.bind(this));

            grid.reference = this;

            var preview = new Ext.Panel({
                title: t("preview"),
                region: "center",
                bodyStyle: "-webkit-overflow-scrolling:touch;",
                html: ''
            });

            this.layout = new Ext.Panel({
                title: t('versions'),
                bodyStyle:'padding:20px 5px 20px 5px;',
                border: false,
                layout: "border",
                iconCls: "pimcore_icon_tab_versions",
                items: [grid,preview]
            });

            preview.on("resize", this.onLayoutResize.bind(this));
        }

        return this.layout;
    },

    onLayoutResize: function (el, width, height, rWidth, rHeight) {
        this.setLayoutFrameDimensions(width, height);
    },

    setLayoutFrameDimensions: function (width, height) {
        Ext.get("asset_version_iframe_" + this.asset.id).setStyle({
            width: width + "px",
            height: (height - 25) + "px"
        });
    },

    onRowClick: function(grid, record, tr, rowIndex, e, eOpts ) {
        var data = grid.getStore().getAt(rowIndex).data;

        var versionId = data.id;
        var path = "/admin/asset/show-version/id/" + versionId;
        Ext.get("asset_version_iframe_" + this.asset.id).dom.src = path;
    },

    onRowContextmenu: function (grid, record, tr, rowIndex, e, eOpts ) {

        //$(grid.getView().getRow(rowIndex)).animate(
        //            { backgroundColor: '#E0EAEE' }, 100).animate( { backgroundColor: '#fff' }, 400);

        var menu = new Ext.menu.Menu();

        if (this.asset.isAllowed("publish")) {
            menu.add(new Ext.menu.Item({
                text: t('publish'),
                iconCls: "pimcore_icon_publish",
                handler: this.publishVersion.bind(this, rowIndex, grid)
            }));
        }

        menu.add(new Ext.menu.Item({
            text: t('delete'),
            iconCls: "pimcore_icon_delete",
            handler: this.removeVersion.bind(this, rowIndex, grid)
        }));

        e.stopEvent();
        menu.showAt(e.pageX, e.pageY);
    },

    removeVersion: function (index, grid) {

        var data = grid.getStore().getAt(index).data;
        var versionId = data.id;

        Ext.Ajax.request({
            url: "/admin/asset/delete-version",
            params: {id: versionId}
        });

        grid.getStore().removeAt(index);
    },

    publishVersion: function (index, grid) {
        var data = grid.getStore().getAt(index).data;
        var versionId = data.id;

        Ext.Ajax.request({
            url: "/admin/asset/publish-version",
            params: {id: versionId},
            success: this.asset.reload.bind(this.asset)
        });
    },

    reload: function () {
        this.store.reload();
    }

});<|endoftext|>


<commit_before>var publicMethods = [
	'setViewport',
  'startAutoslide',
  'stopAutoslide',
  'moveToSlide',
  'next',
  'prev',
  'bindAll',
  'unbindAll'
];

describe('jQuery.GI.Carousel (simple) tests', function () {

  var carousel;

  it('$.fn.GICarousel function exsists', function () {
    expect($.fn.GICarousel).is.not.undefined;
  });

  it('The next, prev,moveToSlide methods work as expected', function (done) {
  	var callback = sinon.spy();
  	this.timeout(10000);
    carousel = $('.GICarousel').GICarousel({
    	carousel:true,
    	onItemChange: callback,
    	onReady: function () {
    		var self = this;
    		setTimeout(function(){
    			self.next();
    		},1000);

        setTimeout($.proxy(this.next, this), 2000);
        setTimeout(function(){
        	self.moveToSlide(4);
        	expect(self.currentIndex).to.be.equal(4);

        }, 3000);
        setTimeout(function () {
        	console.log(callback);
        	expect(callback).to.have.calledThrice;
        	expect($('.GICarousel ul li.current').data('index')).to.be.equal(4);
          done();
        }, 5000);
    	}
    });
  });

  it('the carousel gets created', function () {
    carousel = $('.GICarousel').GICarousel();
    expect(carousel).is.not.undefined;
  });

  it('The public api created and the callback get called', function () {
  	var callbacks = [sinon.spy(),sinon.spy()],
    carousel = $('.GICarousel').GICarousel({
    	onBeforeInit: callbacks[0],
    	onReady: function(){
    		$.each(callbacks,function(i,callback){
		    	expect(callback).to.have.been.called;
		    });
    	},
    	onViewPortUpdate: callbacks[1]
    });

  });

  it('The destroy method works as expected', function (done) {
  	var itemLenght = $('.GICarousel ul li').length;
    carousel = $('.GICarousel').GICarousel({
    	carousel:true,
    	onDestroy: done
    });
    expect($('.GICarousel ul li')).length.to.be(itemLenght * 2);
    carousel.destroy();
    carousel = null;
    expect($('.GICarousel ul li')).length.to.be(itemLenght);
  });

  afterEach(function () {
    if (carousel)
      carousel.destroy();
    carousel = null;
  });

});<commit_msg>console log removed<commit_after>var publicMethods = [
	'setViewport',
  'startAutoslide',
  'stopAutoslide',
  'moveToSlide',
  'next',
  'prev',
  'bindAll',
  'unbindAll'
];

describe('jQuery.GI.Carousel (simple) tests', function () {

  var carousel;

  it('$.fn.GICarousel function exsists', function () {
    expect($.fn.GICarousel).is.not.undefined;
  });

  it('The next, prev,moveToSlide methods work as expected', function (done) {
  	var callback = sinon.spy();
  	this.timeout(10000);
    carousel = $('.GICarousel').GICarousel({
    	carousel:true,
    	onItemChange: callback,
    	onReady: function () {
    		var self = this;
    		setTimeout(function(){
    			self.next();
    		},1000);

        setTimeout($.proxy(this.next, this), 2000);
        setTimeout(function(){
        	self.moveToSlide(4);
        	expect(self.currentIndex).to.be.equal(4);

        }, 3000);
        setTimeout(function () {
        	expect(callback).to.have.calledThrice;
        	expect($('.GICarousel ul li.current').data('index')).to.be.equal(4);
          done();
        }, 5000);
    	}
    });
  });

  it('the carousel gets created', function () {
    carousel = $('.GICarousel').GICarousel();
    expect(carousel).is.not.undefined;
  });

  it('The public api created and the callback get called', function () {
  	var callbacks = [sinon.spy(),sinon.spy()],
    carousel = $('.GICarousel').GICarousel({
    	onBeforeInit: callbacks[0],
    	onReady: function(){
    		$.each(callbacks,function(i,callback){
		    	expect(callback).to.have.been.called;
		    });
    	},
    	onViewPortUpdate: callbacks[1]
    });

  });

  it('The destroy method works as expected', function (done) {
  	var itemLenght = $('.GICarousel ul li').length;
    carousel = $('.GICarousel').GICarousel({
    	carousel:true,
    	onDestroy: done
    });
    expect($('.GICarousel ul li')).length.to.be(itemLenght * 2);
    carousel.destroy();
    carousel = null;
    expect($('.GICarousel ul li')).length.to.be(itemLenght);
  });

  afterEach(function () {
    if (carousel)
      carousel.destroy();
    carousel = null;
  });

});<|endoftext|>


<commit_before>const {
  createDefaultEnvironment,
  destroyDefaultEnvironment
} = require('@cardstack/test-support/env');

describe('hub/indexers', function() {
  let env;

  before(async function () {
    env = await createDefaultEnvironment(`${__dirname}/..`);
  });

  after(async function() {
    await destroyDefaultEnvironment(env);
  });

  it("indexes seed models", async function() {
    let response = await env.lookup('hub:searchers').search('master', { filter: { type: 'plugin-configs' }});
    expect(response.models.map(m => m.attributes.module)).includes('@cardstack/hub');
  });

  it("indexes bootstrap models", async function() {
    let response = await env.lookup('hub:searchers').search('master', { filter: { type: 'plugin-configs' }});
    expect(response.models.map(m => m.attributes.module)).includes('@cardstack/core-types');
  });

});
<commit_msg>documenting a think I had forgotten<commit_after>const {
  createDefaultEnvironment,
  destroyDefaultEnvironment
} = require('@cardstack/test-support/env');

describe('hub/indexers', function() {
  let env;

  before(async function () {
    env = await createDefaultEnvironment(`${__dirname}/..`);
  });

  after(async function() {
    await destroyDefaultEnvironment(env);
  });

  it("indexes seed models", async function() {
    // this seed model comes from createDefaultEnvironment
    let response = await env.lookup('hub:searchers').search('master', { filter: { type: 'plugin-configs' }});
    expect(response.models.map(m => m.attributes.module)).includes('@cardstack/hub');
  });

  it("indexes bootstrap models", async function() {
    let response = await env.lookup('hub:searchers').search('master', { filter: { type: 'plugin-configs' }});
    expect(response.models.map(m => m.attributes.module)).includes('@cardstack/core-types');
  });

});
<|endoftext|>


<commit_before>var should = require('should')
  , parser = require('../../lib/atom')
  , ltx    = require('ltx')

var ATOM_NS = "http://www.w3.org/2005/Atom"

describe('Parsing posts with \'atom\'', function() {

    var topLevelElements = {
        title: 'Back to the future',
        id: 'film1',
        updated: '1985-10-26 01:22',
        published: '1955-11-05 01:21',
        summary: 'A great series of films about time travel'
    }

    it('shouldn\'t act if no ATOM namespace', function() {
        var entity = { not: 'empty' }
        var item   = ltx.parse('')
        parser.parse(item, entity)
        entity.should.eql({ not: 'empty' })
    })

    it('adds top level elements', function() {

        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<id>' + topLevelElements.id + '</id>'
          + '<updated>' + topLevelElements.updated + '</updated>'
          + '<published>' + topLevelElements.published + '</published>'
          + '' + topLevelElements.summary + ''
          + '<title>' + topLevelElements.title + '</title>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql(topLevelElements)
    })

    it('Adds content', function() {
        var entity = {}
        var content = 'Great Scott!'
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<content>' + content + '</content>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql({ content: { type: 'text', content: content } })
    })

    it('Adds XHTML content with language', function() {
        var entity = {}
        var content = '
Great Scott!
'
        var language = 'en_GB'
        var type = 'xhtml'
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<content xml:lang="' + language + '" type="' + type + '">'
          + content
          + '</content>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql({
            content: { type: 'xhtml', lang: 'en_GB', content: content }
        })
    })

    it('Adds links to the entry', function() {
        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<link title="A link" rel="alternative" '
              + 'href="http://bttf.net/film-1" type="text/html" />'
          + '<link hreflang="en_GB" length="64" '
              + 'href="http://bttf.net/film-2" />'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.links.length.should.equal(2)
        entity.links[0].should.eql({
            title: 'A link',
            rel: 'alternative',
            href: 'http://bttf.net/film-1',
            type: 'text/html'
        })
        entity.links[1].should.eql({
            href: 'http://bttf.net/film-2',
            hreflang: 'en_GB',
            length: '64'
        })
    })

    it('Adds author details', function() {
        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<author>'
              + '<name>Marty McFly</name>'
              + '<email>marty@mcfly.net</email>'
              + '<uri>http://notchick.en</uri>'
              + '<id>1</id>'
          + '</author>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql({
            author: {
                name: 'Marty McFly',
                email: 'marty@mcfly.net',
                uri: 'http://notchick.en',
                id: '1'
            }
        })
    })

    it('Adds contributor details', function() {
        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<contributor>'
              + '<name>Marty McFly</name>'
              + '<email>marty@mcfly.net</email>'
          + '</contributor>'
          + '<contributor>'
              + '<name>Doc Brown</name>'
              + '<id>1</id>'
          + '</contributor>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.contributors.length.should.equal(2)
        entity.contributors[0].should.eql({
            name: 'Marty McFly',
            email: 'marty@mcfly.net'
        })
        entity.contributors[1].should.eql({
            name: 'Doc Brown',
            id: '1'
        })
    })

})

describe('Building stanzas with \'atom\'', function() {

    it('Doesn\'t touch stanza if no \'atom\' attribute', function() {
       var stanza = ltx.parse('<item/>')
       var original = ltx.parse(stanza.toString())
       var entity = {}
       parser.build(entity, stanza)
       stanza.root().toString().should.equal(original.toString())
    })

    it('Adds atom namespace and <entry> element', function() {
       var stanza = ltx.parse('<item/>')
       var entity = { atom: {} }
       parser.build(entity, stanza)
       stanza.getChild('entry', ATOM_NS).should.exist
    })

    it('Adds atom namespace with existing <entry> element', function() {
        var stanza = ltx.parse('<item><entry/></item>')
        var entity = { atom: {} }
        parser.build(entity, stanza)
        stanza.getChild('entry', ATOM_NS).should.exist
    })

    it('Adds simple elements', function() {
        var entity = {
            atom: {
                id: 'id-value',
                title: 'title-value',
                updated: 'updated-value',
                summary: 'summary-value',
                published: 'published-value'
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildText('id').should.equal(entity.atom.id)
        entry.getChildText('title').should.equal(entity.atom.title)
        entry.getChildText('updated').should.equal(entity.atom.updated)
        entry.getChildText('summary').should.equal(entity.atom.summary)
        entry.getChildText('published').should.equal(entity.atom.published)
    })

    it('Can add a single author', function() {
        var entity = {
            atom: {
                author: {
                    name: 'Doc Brown',
                    email: 'doc@outtatime.org'
                }
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildren('author').length.should.equal(1)
        entry.getChild('author').getChildText('name')
            .should.equal(entity.atom.author.name)
        entry.getChild('author').getChildText('email')
            .should.equal(entity.atom.author.email)
        should.not.exist(entry.getChild('author').getChildText('uri'))
    })

    it('Can add multiple authors', function() {
        var entity = {
            atom: {
                author: [
                    { name: 'Doc Brown', email: 'doc@outtatime.org' },
                    { name: 'Marty McFly', uri: 'http://notachick.en' }
                ]
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildren('author').length.should.equal(2)
        var authors = entry.getChildren('author')
        authors[0].getChildText('name')
            .should.equal(entity.atom.author[0].name)
        authors[0].getChildText('email')
            .should.equal(entity.atom.author[0].email)
        should.not.exist(authors[0].getChildText('uri'))
        authors[1].getChildText('name')
            .should.equal(entity.atom.author[1].name)
        authors[1].getChildText('uri')
            .should.equal(entity.atom.author[1].uri)
        should.not.exist(authors[1].getChildText('email'))
    })

    it('Can add contributors', function() {

    })

})
<commit_msg>Added tests for <contributor><commit_after>var should = require('should')
  , parser = require('../../lib/atom')
  , ltx    = require('ltx')

var ATOM_NS = "http://www.w3.org/2005/Atom"

describe('Parsing posts with \'atom\'', function() {

    var topLevelElements = {
        title: 'Back to the future',
        id: 'film1',
        updated: '1985-10-26 01:22',
        published: '1955-11-05 01:21',
        summary: 'A great series of films about time travel'
    }

    it('shouldn\'t act if no ATOM namespace', function() {
        var entity = { not: 'empty' }
        var item   = ltx.parse('')
        parser.parse(item, entity)
        entity.should.eql({ not: 'empty' })
    })

    it('adds top level elements', function() {

        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<id>' + topLevelElements.id + '</id>'
          + '<updated>' + topLevelElements.updated + '</updated>'
          + '<published>' + topLevelElements.published + '</published>'
          + '' + topLevelElements.summary + ''
          + '<title>' + topLevelElements.title + '</title>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql(topLevelElements)
    })

    it('Adds content', function() {
        var entity = {}
        var content = 'Great Scott!'
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<content>' + content + '</content>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql({ content: { type: 'text', content: content } })
    })

    it('Adds XHTML content with language', function() {
        var entity = {}
        var content = '
Great Scott!
'
        var language = 'en_GB'
        var type = 'xhtml'
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<content xml:lang="' + language + '" type="' + type + '">'
          + content
          + '</content>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql({
            content: { type: 'xhtml', lang: 'en_GB', content: content }
        })
    })

    it('Adds links to the entry', function() {
        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<link title="A link" rel="alternative" '
              + 'href="http://bttf.net/film-1" type="text/html" />'
          + '<link hreflang="en_GB" length="64" '
              + 'href="http://bttf.net/film-2" />'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.links.length.should.equal(2)
        entity.links[0].should.eql({
            title: 'A link',
            rel: 'alternative',
            href: 'http://bttf.net/film-1',
            type: 'text/html'
        })
        entity.links[1].should.eql({
            href: 'http://bttf.net/film-2',
            hreflang: 'en_GB',
            length: '64'
        })
    })

    it('Adds author details', function() {
        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<author>'
              + '<name>Marty McFly</name>'
              + '<email>marty@mcfly.net</email>'
              + '<uri>http://notchick.en</uri>'
              + '<id>1</id>'
          + '</author>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.should.eql({
            author: {
                name: 'Marty McFly',
                email: 'marty@mcfly.net',
                uri: 'http://notchick.en',
                id: '1'
            }
        })
    })

    it('Adds contributor details', function() {
        var entity = {}
        var item = ltx.parse(
            '<item><entry xmlns="' + ATOM_NS + '">'
          + '<contributor>'
              + '<name>Marty McFly</name>'
              + '<email>marty@mcfly.net</email>'
          + '</contributor>'
          + '<contributor>'
              + '<name>Doc Brown</name>'
              + '<id>1</id>'
          + '</contributor>'
          + '</entry></item>'
        )
        parser.parse(item, entity)
        entity.contributors.length.should.equal(2)
        entity.contributors[0].should.eql({
            name: 'Marty McFly',
            email: 'marty@mcfly.net'
        })
        entity.contributors[1].should.eql({
            name: 'Doc Brown',
            id: '1'
        })
    })

})

describe('Building stanzas with \'atom\'', function() {

    it('Doesn\'t touch stanza if no \'atom\' attribute', function() {
       var stanza = ltx.parse('<item/>')
       var original = ltx.parse(stanza.toString())
       var entity = {}
       parser.build(entity, stanza)
       stanza.root().toString().should.equal(original.toString())
    })

    it('Adds atom namespace and <entry> element', function() {
       var stanza = ltx.parse('<item/>')
       var entity = { atom: {} }
       parser.build(entity, stanza)
       stanza.getChild('entry', ATOM_NS).should.exist
    })

    it('Adds atom namespace with existing <entry> element', function() {
        var stanza = ltx.parse('<item><entry/></item>')
        var entity = { atom: {} }
        parser.build(entity, stanza)
        stanza.getChild('entry', ATOM_NS).should.exist
    })

    it('Adds simple elements', function() {
        var entity = {
            atom: {
                id: 'id-value',
                title: 'title-value',
                updated: 'updated-value',
                summary: 'summary-value',
                published: 'published-value'
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildText('id').should.equal(entity.atom.id)
        entry.getChildText('title').should.equal(entity.atom.title)
        entry.getChildText('updated').should.equal(entity.atom.updated)
        entry.getChildText('summary').should.equal(entity.atom.summary)
        entry.getChildText('published').should.equal(entity.atom.published)
    })

    it('Can add a single author', function() {
        var entity = {
            atom: {
                author: {
                    name: 'Doc Brown',
                    email: 'doc@outtatime.org'
                }
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildren('author').length.should.equal(1)
        entry.getChild('author').getChildText('name')
            .should.equal(entity.atom.author.name)
        entry.getChild('author').getChildText('email')
            .should.equal(entity.atom.author.email)
        should.not.exist(entry.getChild('author').getChildText('uri'))
    })

    it('Can add multiple authors', function() {
        var entity = {
            atom: {
                author: [
                    { name: 'Doc Brown', email: 'doc@outtatime.org' },
                    { name: 'Marty McFly', uri: 'http://notachick.en' }
                ]
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildren('author').length.should.equal(2)
        var authors = entry.getChildren('author')
        authors[0].getChildText('name')
            .should.equal(entity.atom.author[0].name)
        authors[0].getChildText('email')
            .should.equal(entity.atom.author[0].email)
        should.not.exist(authors[0].getChildText('uri'))
        authors[1].getChildText('name')
            .should.equal(entity.atom.author[1].name)
        authors[1].getChildText('uri')
            .should.equal(entity.atom.author[1].uri)
        should.not.exist(authors[1].getChildText('email'))
    })

    it('Can add contributors', function() {
        var entity = {
            atom: {
                contributors: [
                    { name: 'Doc Brown', email: 'doc@outtatime.org' },
                    { name: 'Marty McFly', uri: 'http://notachick.en' }
                ]
            }
        }
        var stanza = ltx.parse('<item/>')
        parser.build(entity, stanza)
        var entry = stanza.getChild('entry')
        entry.getChildren('contributor').length.should.equal(2)
        var contributors = entry.getChildren('contributor')
        contributors[0].getChildText('name')
            .should.equal(entity.atom.contributors[0].name)
        contributors[1].getChildText('name')
            .should.equal(entity.atom.contributors[1].name)
    })

})
<|endoftext|>


<commit_before>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

// TODO
// navigation screws page lifecycle events
//

describe("navigation", function suite() {
	it("should emit navigate event when navigation is true and allow redirection", function(done) {
		var counter = 0;
		var navcount = 0;
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 200;
			res.end("ok" + counter++);
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, {
				navigation: true
			}, function(err, w) {
				w.run(function(done) {
					document.location = '/anotherpage';
					done();
				}, function() {
					setTimeout(function() {
						server.close();
						expect(counter).to.be(2);
						expect(navcount).to.be(1);
						done();
					}, 100);
				});
			}).on('navigate', function(url) {
				navcount++;
				expect(url).to.be(this.uri + 'anotherpage');
			});
		});
	});
	it("should emit navigate event when navigation is false and disallow redirection", function(done) {
		var counter = 0;
		var navcount = 0;
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 200;
			res.end("ok" + counter++);
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, {
				navigation: false
			}, function(err, w) {
				w.run(function(done) {
					document.location = '/anotherpage';
					done();
				}, function() {
					setTimeout(function() {
						server.close();
						expect(counter).to.be(1);
						expect(navcount).to.be(1);
						done();
					}, 100);
				});
			}).on('navigate', function(url) {
				navcount++;
				expect(url).to.be(this.uri + 'anotherpage');
			});
		});
	});
});
<commit_msg>Improve navigate test to check load fix<commit_after>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

// TODO
// navigation screws page lifecycle events
//

describe("navigation", function suite() {
	it("should emit navigate event when navigation is true and allow redirection", function(done) {
		var counter = 0;
		var navcount = 0;
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 200;
			res.end("ok" + counter++);
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, {
				navigation: true
			}, function(err, w) {
				w.run(function(done) {
					document.location = '/anotherpage';
					done();
				}, function() {
					setTimeout(function() {
						server.close();
						expect(counter).to.be(2);
						expect(navcount).to.be(1);
						done();
					}, 100);
				});
			}).on('navigate', function(url) {
				navcount++;
				expect(url).to.be(this.uri + 'anotherpage');
			});
		});
	});
	it("should emit navigate event when navigation is false and disallow redirection", function(done) {
		var counter = 0;
		var navcount = 0;
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 200;
			if (req.url == "/") {
				counter++;
				res.end(`
					<html><body>
					<script type="text/javascript" src="/delay.js"></script>
					<script type="text/javascript">
					document.location = "/anotherpage";
					</script>
					</body></html>
				`);
			} else if (req.url == "/anotherpage") {
				counter++;
				res.end("ok" + counter++);
			} else if (req.url == "/delay.js") {
				setTimeout(function() {
					res.end("console.log('delayed');");
				}, 500);
			}
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, {
				navigation: false
			}).on('navigate', function(url) {
				navcount++;
				expect(url).to.be(this.uri + 'anotherpage');
			}).when('idle', function(cb) {
				expect(counter).to.be(1);
				expect(navcount).to.be(1);
				cb();
				server.close();
				done();
			});
		});
	});
});
<|endoftext|>


<commit_before>const { Menu } = require('electron')

const selectionMenu = Menu.buildFromTemplate([
  { role: 'copy' },
])

const inputMenu = Menu.buildFromTemplate([
  { role: 'undo' },
  { role: 'redo' },
  { type: 'separator' },
  { role: 'cut' },
  { role: 'copy' },
  { role: 'paste' },
  { type: 'separator' },
  { role: 'selectall' },
])

module.exports = (window) => {
  window.webContents.on('context-menu', (e, props) => {
    const { selectionText, isEditable } = props
    if (isEditable) {
      inputMenu.popup(window)
    } else if (selectionText && selectionText.trim() !== '') {
      selectionMenu.popup(window)
    }
  })
}
<commit_msg>format<commit_after>const { Menu } = require('electron')

const selectionMenu = Menu.buildFromTemplate([{ role: 'copy' }])

const inputMenu = Menu.buildFromTemplate([
  { role: 'undo' },
  { role: 'redo' },
  { type: 'separator' },
  { role: 'cut' },
  { role: 'copy' },
  { role: 'paste' },
  { type: 'separator' },
  { role: 'selectall' },
])

module.exports = (window) => {
  window.webContents.on('context-menu', (e, props) => {
    const { selectionText, isEditable } = props
    if (isEditable) {
      inputMenu.popup(window)
    } else if (selectionText && selectionText.trim() !== '') {
      selectionMenu.popup(window)
    }
  })
}
<|endoftext|>


<commit_before>'use strict';

// Requirements.
var docopt = require("docopt");
var log4js = require('log4js');
var logpost = require('./../lib/logpost.js');

// Get commandline arguments.
var doc = 'Usage: ' +
  'sumo-logpost --run <run-millis> --batch <batchsize> ' +
  '--host <host> --path <path> [--buffer <messages>] ' +
  '[--timeout <timeout-millis>] [--gzip] [--max-sockets <max-sockets>] ' +
  '[--debug] [--skip-cert-validation] ' +
  'sumo-logpost -h | --help | --version';
var options = docopt.docopt(doc, {
  argv: process.argv.slice(2),
  help: true,
  version: "0.0.0"
});
var runMillis = options['<run-millis>'];
var batchSize = options['<batchsize>'];
var host = options['<host>'];
var path = options['<path>'];
var gzip = options['--gzip'] === true;
var maxMessages = options['<messages>'] || 100;
var timeoutMillis = options['<timeout-millis>'] || 1000;
var maxSockets = options['<max-sockets>'] || 32;

// Drop cert validation if requested.
var nonStrict = options['--skip-cert-validation'];
if (nonStrict) {
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}

// Setup logging.
var logger = log4js.getLogger();
var log_level = (options['--debug'] === true) ? "DEBUG" : "INFO";
logger.setLevel(log_level);
logger.debug("Debug logging enabled");

// Helper functions.
function makeGuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }

  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

// Create test messages.
var log = logpost.new({
  logger: logger,
  host: host,
  path: path,
  gzip: gzip,
  cookies: false,
  maxMessages: maxMessages,
  timeoutMillis: timeoutMillis,
  maxSockets: maxSockets
});

// Make a unique ID so we can query for messages in this run.
var guid = makeGuid();

// Create 320 bytes of padding to get message in the standard length.
var padding = "123456789 ";
for (var i = 0; i < 5; i++) {
  padding += padding;
}

// Create messages on an interval.
var counter = 1;
var interval = setInterval(function () {
  for (var i = 0; i < batchSize; i++) {
    log.message(
      new Date().toISOString() + " " + guid + " " + padding + counter);
    counter += 1;
  }
}, 0);

// After done, initiate shutdown.
setTimeout(function () {
  clearInterval(interval);
  log.shutdown(true);
  logger.debug(
    "DONE with " + (counter - 1) + " messages, " +
    log.messageCount() + " messages sent, token: " + guid);
  logger.debug(
    "DONE with status code counts: " + JSON.stringify(log.statusCodes()));
}, runMillis);<commit_msg>Update...<commit_after>'use strict';

// Requirements.
var docopt = require("docopt");
var log4js = require('log4js');
var logpost = require('./../lib/logpost.js');

// Get commandline arguments.
var doc = 'Usage: ' +
  'sumo-logpost --run <run-millis> --batch <batchsize> ' +
  '[--grace <grace-millis>] ' +
  '--host <host> --path <path> [--buffer <messages>] ' +
  '[--timeout <timeout-millis>] [--gzip] [--max-sockets <max-sockets>] ' +
  '[--debug] [--skip-cert-validation] ' +
  'sumo-logpost -h | --help | --version';
var options = docopt.docopt(doc, {
  argv: process.argv.slice(2),
  help: true,
  version: "0.0.0"
});
var runMillis = options['<run-millis>'];
var batchSize = options['<batchsize>'];
var graceMillis = options['<grace-millis>'] || 0;
var host = options['<host>'];
var path = options['<path>'];
var gzip = options['--gzip'] === true;
var maxMessages = options['<messages>'] || 100;
var timeoutMillis = options['<timeout-millis>'] || 1000;
var maxSockets = options['<max-sockets>'] || 32;

// Drop cert validation if requested.
var nonStrict = options['--skip-cert-validation'];
if (nonStrict) {
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}

// Setup logging.
var logger = log4js.getLogger();
var log_level = (options['--debug'] === true) ? "DEBUG" : "INFO";
logger.setLevel(log_level);
logger.debug("Debug logging enabled");

// Helper functions.
function makeGuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }

  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

// Create test messages.
var log = logpost.new({
  logger: logger,
  host: host,
  path: path,
  gzip: gzip,
  cookies: false,
  maxMessages: maxMessages,
  timeoutMillis: timeoutMillis,
  maxSockets: maxSockets
});

// Make a unique ID so we can query for messages in this run.
var guid = makeGuid();

// Create 320 bytes of padding to get message in the standard length.
var padding = "123456789 ";
for (var i = 0; i < 5; i++) {
  padding += padding;
}

// Create messages on an interval.
var counter = 1;
var interval = setInterval(function () {
  for (var i = 0; i < batchSize; i++) {
    log.message(
      new Date().toISOString() + " " + guid + " " + padding + counter);
    counter += 1;
  }
}, graceMillis);

// After done, initiate shutdown.
setTimeout(function () {
  clearInterval(interval);
  log.shutdown(true);
  logger.debug(
    "DONE with " + (counter - 1) + " messages, " +
    log.messageCount() + " messages sent, token: " + guid);
  logger.debug(
    "DONE with status code counts: " + JSON.stringify(log.statusCodes()));
}, runMillis);<|endoftext|>