<commit_before>import { shallowMount, createLocalVue } from '@vue/test-utils';
import createStore from '~/notes/stores';
import noteableDiscussion from '~/notes/components/noteable_discussion.vue';
import ReplyPlaceholder from '~/notes/components/discussion_reply_placeholder.vue';
import ResolveWithIssueButton from '~/notes/components/discussion_resolve_with_issue_button.vue';
import NoteForm from '~/notes/components/note_form.vue';
import '~/behaviors/markdown/render_gfm';
import { noteableDataMock, discussionMock, notesDataMock } from '../mock_data';
import mockDiffFile from '../../diffs/mock_data/diff_file';

const discussionWithTwoUnresolvedNotes = 'merge_requests/resolved_diff_discussion.json';

describe('noteable_discussion component', () => {
  let store;
  let wrapper;

  preloadFixtures(discussionWithTwoUnresolvedNotes);

  beforeEach(() => {
    window.mrTabs = {};
    store = createStore();
    store.dispatch('setNoteableData', noteableDataMock);
    store.dispatch('setNotesData', notesDataMock);

    const localVue = createLocalVue();
    wrapper = shallowMount(noteableDiscussion, {
      store,
      propsData: { discussion: discussionMock },
      localVue,
      sync: false,
    });
  });

  afterEach(() => {
    wrapper.destroy();
  });

  it('should render user avatar', () => {
    expect(wrapper.find('.user-avatar-link').exists()).toBe(true);
  });

  it('should not render thread header for non diff threads', () => {
    expect(wrapper.find('.discussion-header').exists()).toBe(false);
  });

  it('should render thread header', done => {
    const discussion = { ...discussionMock };
    discussion.diff_file = mockDiffFile;
    discussion.diff_discussion = true;

    wrapper.setProps({ discussion });

    wrapper.vm
      .$nextTick()
      .then(() => {
        expect(wrapper.find('.discussion-header').exists()).toBe(true);
      })
      .then(done)
      .catch(done.fail);
  });

  describe('actions', () => {
    it('should toggle reply form', done => {
      const replyPlaceholder = wrapper.find(ReplyPlaceholder);

      wrapper.vm
        .$nextTick()
        .then(() => {
          expect(wrapper.vm.isReplying).toEqual(false);

          replyPlaceholder.vm.$emit('onClick');
        })
        .then(() => wrapper.vm.$nextTick())
        .then(() => {
          expect(wrapper.vm.isReplying).toEqual(true);

          const noteForm = wrapper.find(NoteForm);

          expect(noteForm.exists()).toBe(true);

          const noteFormProps = noteForm.props();

          expect(noteFormProps.discussion).toBe(discussionMock);
          expect(noteFormProps.isEditing).toBe(false);
          expect(noteFormProps.line).toBe(null);
          expect(noteFormProps.saveButtonTitle).toBe('Comment');
          expect(noteFormProps.autosaveKey).toBe(`Note/Issue/${discussionMock.id}/Reply`);
        })
        .then(done)
        .catch(done.fail);
    });

    it('does not render jump to thread button', () => {
      expect(
        wrapper.find('*[data-original-title="Jump to next unresolved thread"]').exists(),
      ).toBe(false);
    });
  });

  describe('methods', () => {
    describe('jumpToNextDiscussion', () => {
      it('expands next unresolved thread', done => {
        const discussion2 = getJSONFixture(discussionWithTwoUnresolvedNotes)[0];
        discussion2.resolved = false;
        discussion2.active = true;
        discussion2.id = 'next'; // prepare this for being identified as next one (to be jumped to)
        store.dispatch('setInitialNotes', [discussionMock, discussion2]);
        window.mrTabs.currentAction = 'show';

        wrapper.vm
          .$nextTick()
          .then(() => {
            spyOn(wrapper.vm, 'expandDiscussion').and.stub();

            const nextDiscussionId = discussion2.id;

            setFixtures(`

            `);

            wrapper.vm.jumpToNextDiscussion();

            expect(wrapper.vm.expandDiscussion).toHaveBeenCalledWith({
              discussionId: nextDiscussionId,
            });
          })
          .then(done)
          .catch(done.fail);
      });
    });
  });

  describe('action text', () => {
    const commitId = 'razupaltuff';
    const truncatedCommitId = commitId.substr(0, 8);
    let commitElement;

    beforeEach(done => {
      store.state.diffs = {
        projectPath: 'something',
      };

      wrapper.setProps({
        discussion: {
          ...discussionMock,
          for_commit: true,
          commit_id: commitId,
          diff_discussion: true,
          diff_file: {
            ...mockDiffFile,
          },
        },
        renderDiffFile: true,
      });

      wrapper.vm
        .$nextTick()
        .then(() => {
          commitElement = wrapper.find('.commit-sha');
        })
        .then(done)
        .catch(done.fail);
    });

    describe('for commit threads', () => {
      it('should display a monospace started a thread on commit', () => {
        expect(wrapper.text()).toContain(`started a thread on commit ${truncatedCommitId}`);
        expect(commitElement.exists()).toBe(true);
        expect(commitElement.text()).toContain(truncatedCommitId);
      });
    });

    describe('for diff thread with a commit id', () => {
      it('should display started thread on commit header', done => {
        wrapper.vm.discussion.for_commit = false;

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain(`started a thread on commit ${truncatedCommitId}`);

          expect(commitElement).not.toBe(null);

          done();
        });
      });

      it('should display outdated change on commit header', done => {
        wrapper.vm.discussion.for_commit = false;
        wrapper.vm.discussion.active = false;

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain(
            `started a discussion on an outdated change in commit ${truncatedCommitId}`,
          );

          expect(commitElement).not.toBe(null);

          done();
        });
      });
    });

    describe('for diff threads without a commit id', () => {
      it('should show started a thread on the diff text', done => {
        Object.assign(wrapper.vm.discussion, {
          for_commit: false,
          commit_id: null,
        });

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain('started a thread on the diff');

          done();
        });
      });

      it('should show thread on older version text', done => {
        Object.assign(wrapper.vm.discussion, {
          for_commit: false,
          commit_id: null,
          active: false,
        });

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain('started a thread on an old version of the diff');

          done();
        });
      });
    });
  });

  describe('for resolved thread', () => {
    beforeEach(() => {
      const discussion = getJSONFixture(discussionWithTwoUnresolvedNotes)[0];
      wrapper.setProps({ discussion });
    });

    it('does not display a button to resolve with issue', () => {
      const button = wrapper.find(ResolveWithIssueButton);

      expect(button.exists()).toBe(false);
    });
  });

  describe('for unresolved thread', () => {
    beforeEach(done => {
      const discussion = {
        ...getJSONFixture(discussionWithTwoUnresolvedNotes)[0],
        expanded: true,
      };
      discussion.notes = discussion.notes.map(note => ({
        ...note,
        resolved: false,
      }));

      wrapper.setProps({ discussion });
      wrapper.vm
        .$nextTick()
        .then(done)
        .catch(done.fail);
    });

    it('displays a button to resolve with issue', () => {
      const button = wrapper.find(ResolveWithIssueButton);

      expect(button.exists()).toBe(true);
    });
  });
});
<commit_msg>updated karma test for noteable_discussion component<commit_after>import { shallowMount, createLocalVue } from '@vue/test-utils';
import createStore from '~/notes/stores';
import noteableDiscussion from '~/notes/components/noteable_discussion.vue';
import ReplyPlaceholder from '~/notes/components/discussion_reply_placeholder.vue';
import ResolveWithIssueButton from '~/notes/components/discussion_resolve_with_issue_button.vue';
import NoteForm from '~/notes/components/note_form.vue';
import '~/behaviors/markdown/render_gfm';
import { noteableDataMock, discussionMock, notesDataMock } from '../mock_data';
import mockDiffFile from '../../diffs/mock_data/diff_file';

const discussionWithTwoUnresolvedNotes = 'merge_requests/resolved_diff_discussion.json';

describe('noteable_discussion component', () => {
  let store;
  let wrapper;

  preloadFixtures(discussionWithTwoUnresolvedNotes);

  beforeEach(() => {
    window.mrTabs = {};
    store = createStore();
    store.dispatch('setNoteableData', noteableDataMock);
    store.dispatch('setNotesData', notesDataMock);

    const localVue = createLocalVue();
    wrapper = shallowMount(noteableDiscussion, {
      store,
      propsData: { discussion: discussionMock },
      localVue,
      sync: false,
    });
  });

  afterEach(() => {
    wrapper.destroy();
  });

  it('should render user avatar', () => {
    expect(wrapper.find('.user-avatar-link').exists()).toBe(true);
  });

  it('should not render thread header for non diff threads', () => {
    expect(wrapper.find('.discussion-header').exists()).toBe(false);
  });

  it('should render thread header', done => {
    const discussion = { ...discussionMock };
    discussion.diff_file = mockDiffFile;
    discussion.diff_discussion = true;

    wrapper.setProps({ discussion });

    wrapper.vm
      .$nextTick()
      .then(() => {
        expect(wrapper.find('.discussion-header').exists()).toBe(true);
      })
      .then(done)
      .catch(done.fail);
  });

  describe('actions', () => {
    it('should toggle reply form', done => {
      const replyPlaceholder = wrapper.find(ReplyPlaceholder);

      wrapper.vm
        .$nextTick()
        .then(() => {
          expect(wrapper.vm.isReplying).toEqual(false);

          replyPlaceholder.vm.$emit('onClick');
        })
        .then(() => wrapper.vm.$nextTick())
        .then(() => {
          expect(wrapper.vm.isReplying).toEqual(true);

          const noteForm = wrapper.find(NoteForm);

          expect(noteForm.exists()).toBe(true);

          const noteFormProps = noteForm.props();

          expect(noteFormProps.discussion).toBe(discussionMock);
          expect(noteFormProps.isEditing).toBe(false);
          expect(noteFormProps.line).toBe(null);
          expect(noteFormProps.saveButtonTitle).toBe('Comment');
          expect(noteFormProps.autosaveKey).toBe(`Note/Issue/${discussionMock.id}/Reply`);
        })
        .then(done)
        .catch(done.fail);
    });

    it('does not render jump to thread button', () => {
      expect(
        wrapper.find('*[data-original-title="Jump to next unresolved thread"]').exists(),
      ).toBe(false);
    });
  });

  describe('methods', () => {
    describe('jumpToNextDiscussion', () => {
      it('expands next unresolved thread', done => {
        const discussion2 = getJSONFixture(discussionWithTwoUnresolvedNotes)[0];
        discussion2.resolved = false;
        discussion2.active = true;
        discussion2.id = 'next'; // prepare this for being identified as next one (to be jumped to)
        store.dispatch('setInitialNotes', [discussionMock, discussion2]);
        window.mrTabs.currentAction = 'show';

        wrapper.vm
          .$nextTick()
          .then(() => {
            spyOn(wrapper.vm, 'expandDiscussion').and.stub();

            const nextDiscussionId = discussion2.id;

            setFixtures(`

            `);

            wrapper.vm.jumpToNextDiscussion();

            expect(wrapper.vm.expandDiscussion).toHaveBeenCalledWith({
              discussionId: nextDiscussionId,
            });
          })
          .then(done)
          .catch(done.fail);
      });
    });
  });

  describe('action text', () => {
    const commitId = 'razupaltuff';
    const truncatedCommitId = commitId.substr(0, 8);
    let commitElement;

    beforeEach(done => {
      store.state.diffs = {
        projectPath: 'something',
      };

      wrapper.setProps({
        discussion: {
          ...discussionMock,
          for_commit: true,
          commit_id: commitId,
          diff_discussion: true,
          diff_file: {
            ...mockDiffFile,
          },
        },
        renderDiffFile: true,
      });

      wrapper.vm
        .$nextTick()
        .then(() => {
          commitElement = wrapper.find('.commit-sha');
        })
        .then(done)
        .catch(done.fail);
    });

    describe('for commit threads', () => {
      it('should display a monospace started a thread on commit', () => {
        expect(wrapper.text()).toContain(`started a thread on commit ${truncatedCommitId}`);
        expect(commitElement.exists()).toBe(true);
        expect(commitElement.text()).toContain(truncatedCommitId);
      });
    });

    describe('for diff thread with a commit id', () => {
      it('should display started thread on commit header', done => {
        wrapper.vm.discussion.for_commit = false;

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain(`started a thread on commit ${truncatedCommitId}`);

          expect(commitElement).not.toBe(null);

          done();
        });
      });

      it('should display outdated change on commit header', done => {
        wrapper.vm.discussion.for_commit = false;
        wrapper.vm.discussion.active = false;

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain(
            `started a thread on an outdated change in commit ${truncatedCommitId}`,
          );

          expect(commitElement).not.toBe(null);

          done();
        });
      });
    });

    describe('for diff threads without a commit id', () => {
      it('should show started a thread on the diff text', done => {
        Object.assign(wrapper.vm.discussion, {
          for_commit: false,
          commit_id: null,
        });

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain('started a thread on the diff');

          done();
        });
      });

      it('should show thread on older version text', done => {
        Object.assign(wrapper.vm.discussion, {
          for_commit: false,
          commit_id: null,
          active: false,
        });

        wrapper.vm.$nextTick(() => {
          expect(wrapper.text()).toContain('started a thread on an old version of the diff');

          done();
        });
      });
    });
  });

  describe('for resolved thread', () => {
    beforeEach(() => {
      const discussion = getJSONFixture(discussionWithTwoUnresolvedNotes)[0];
      wrapper.setProps({ discussion });
    });

    it('does not display a button to resolve with issue', () => {
      const button = wrapper.find(ResolveWithIssueButton);

      expect(button.exists()).toBe(false);
    });
  });

  describe('for unresolved thread', () => {
    beforeEach(done => {
      const discussion = {
        ...getJSONFixture(discussionWithTwoUnresolvedNotes)[0],
        expanded: true,
      };
      discussion.notes = discussion.notes.map(note => ({
        ...note,
        resolved: false,
      }));

      wrapper.setProps({ discussion });
      wrapper.vm
        .$nextTick()
        .then(done)
        .catch(done.fail);
    });

    it('displays a button to resolve with issue', () => {
      const button = wrapper.find(ResolveWithIssueButton);

      expect(button.exists()).toBe(true);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var upstreamMergeTrees = require('broccoli-merge-trees');
var EMPTY_MERGE_TREE;

function overrideEmptyTree(tree) {
  EMPTY_MERGE_TREE = tree;
}

function getEmptyTree() {
  if (EMPTY_MERGE_TREE) {
    return EMPTY_MERGE_TREE;
  }

  return EMPTY_MERGE_TREE = upstreamMergeTrees([], {
    annotation: 'EMPTY_MERGE_TREE',
    description: 'EMPTY_MERGE_TREE'
  });
}

module.exports = function mergeTrees(_inputTrees, options) {
  var inputTrees = _inputTrees.filter(function(input) {
    return input && input !== getEmptyTree();
  });

  switch (inputTrees.length) {
  case 0:
    return getEmptyTree();
  case 1:
    return inputTrees[0];
  default:
    options = options || {};
    options.description = options.annotation;
    var tree = upstreamMergeTrees(inputTrees, options);

    tree.description = options && options.description;

    return tree;
  }
};

module.exports._overrideEmptyTree = overrideEmptyTree;
<commit_msg>Fix ESLint issues<commit_after>'use strict';

var upstreamMergeTrees = require('broccoli-merge-trees');
var EMPTY_MERGE_TREE;

function overrideEmptyTree(tree) {
  EMPTY_MERGE_TREE = tree;
}

function getEmptyTree() {
  if (EMPTY_MERGE_TREE) {
    return EMPTY_MERGE_TREE;
  }

  return EMPTY_MERGE_TREE = upstreamMergeTrees([], {
    annotation: 'EMPTY_MERGE_TREE',
    description: 'EMPTY_MERGE_TREE'
  });
}

module.exports = function mergeTrees(_inputTrees, options) {
  var inputTrees = _inputTrees.filter(function(input) {
    return input && input !== getEmptyTree();
  });

  switch (inputTrees.length) {
    case 0:
      return getEmptyTree();
    case 1:
      return inputTrees[0];
    default:
      options = options || {};
      options.description = options.annotation;
      var tree = upstreamMergeTrees(inputTrees, options);

      tree.description = options && options.description;

      return tree;
  }
};

module.exports._overrideEmptyTree = overrideEmptyTree;
<|endoftext|>


<commit_before>// Avatar application. Will handle switching logic between avatar & freelook camera (clientside), and
// spawning avatars for clients (serverside). Note: this is not a startup script, but is meant to be
// placed in an entity in a scene that wishes to implement avatar functionality.

var avatar_area_size = 10;
var avatar_area_x = 0;
var avatar_area_y = 0;
var avatar_area_z = 20;

var isserver = server.IsRunning();

if (isserver == false)
{
    var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
    inputmapper.SetTemporary(true);
    inputmapper.contextPriority = 102;
    inputmapper.RegisterMapping("Ctrl+Tab", "ToggleCamera", 1);

    me.Action("ToggleCamera").Triggered.connect(ClientHandleToggleCamera);
}
else
{
    server.UserAboutToConnect.connect(ServerHandleUserAboutToConnect);
    server.UserConnected.connect(ServerHandleUserConnected);
    server.UserDisconnected.connect(ServerHandleUserDisconnected);
}

function ClientHandleToggleCamera()
{
    // For camera switching to work, must have both the freelookcamera & avatarcamera in the scene
    var freelookcameraentity = scene.GetEntityByNameRaw("FreeLookCamera");
    var avatarcameraentity = scene.GetEntityByNameRaw("AvatarCamera");
    if ((freelookcameraentity == null) || (avatarcameraentity == null))
        return;
    var freelookcamera = freelookcameraentity.ogrecamera;
    var avatarcamera = avatarcameraentity.ogrecamera;

    if (avatarcamera.IsActive())
    {
        freelookcameraentity.placeable.transform = avatarcameraentity.placeable.transform;
        freelookcamera.SetActive();
    }
    else
    {
        avatarcamera.SetActive();
    }
}

function ServerHandleUserAboutToConnect(connectionID, user)
{
    // Uncomment to test access control
    //if (user.GetProperty("password") != "xxx")
    //    user.DenyConnection();
}

function ServerHandleUserConnected(connectionID, user)
{
    var avatarEntityName = "Avatar" + connectionID;
    var avatarEntity = scene.CreateEntityRaw(scene.NextFreeId(), ["EC_Script", "EC_Placeable", "EC_AnimationController"]);
    avatarEntity.SetName(avatarEntityName);
    avatarEntity.SetDescription(user.GetProperty("username"));

    print("Hai. Ur name is " + user.GetProperty("username"));

    var script = avatarEntity.script;
    script.type = "js";
    script.runOnLoad = true;
    var r = script.scriptRef;
    r.ref = "local://simpleavatar.js";
    script.scriptRef = r;

    var placeable = avatarEntity.placeable;
    // Set random starting position for avatar
    var transform = placeable.transform;
    transform.pos.x = (Math.random() - 0.5) * avatar_area_size + avatar_area_x;
    transform.pos.y = (Math.random() - 0.5) * avatar_area_size + avatar_area_y;
    transform.pos.z = avatar_area_z;
    placeable.transform = transform;

    scene.EmitEntityCreatedRaw(avatarEntity);
}

function ServerHandleUserDisconnected(connectionID, user)
{
    var avatarEntityName = "Avatar" + connectionID;
    var entityID = scene.GetEntityByNameRaw(avatarEntityName).Id;
    scene.RemoveEntityRaw(entityID);

    print("Kthxbye, " + user.GetProperty("username"));
}
<commit_msg>Make AvatarApplication generate avatar entities with temporary flag on to be able to save the scene without avatars messing with it.<commit_after>// Avatar application. Will handle switching logic between avatar & freelook camera (clientside), and
// spawning avatars for clients (serverside). Note: this is not a startup script, but is meant to be
// placed in an entity in a scene that wishes to implement avatar functionality.

var avatar_area_size = 10;
var avatar_area_x = 0;
var avatar_area_y = 0;
var avatar_area_z = 20;

var isserver = server.IsRunning();

if (isserver == false)
{
    var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
    inputmapper.SetTemporary(true);
    inputmapper.contextPriority = 102;
    inputmapper.RegisterMapping("Ctrl+Tab", "ToggleCamera", 1);

    me.Action("ToggleCamera").Triggered.connect(ClientHandleToggleCamera);
}
else
{
    server.UserAboutToConnect.connect(ServerHandleUserAboutToConnect);
    server.UserConnected.connect(ServerHandleUserConnected);
    server.UserDisconnected.connect(ServerHandleUserDisconnected);
}

function ClientHandleToggleCamera()
{
    // For camera switching to work, must have both the freelookcamera & avatarcamera in the scene
    var freelookcameraentity = scene.GetEntityByNameRaw("FreeLookCamera");
    var avatarcameraentity = scene.GetEntityByNameRaw("AvatarCamera");
    if ((freelookcameraentity == null) || (avatarcameraentity == null))
        return;
    var freelookcamera = freelookcameraentity.ogrecamera;
    var avatarcamera = avatarcameraentity.ogrecamera;

    if (avatarcamera.IsActive())
    {
        freelookcameraentity.placeable.transform = avatarcameraentity.placeable.transform;
        freelookcamera.SetActive();
    }
    else
    {
        avatarcamera.SetActive();
    }
}

function ServerHandleUserAboutToConnect(connectionID, user)
{
    // Uncomment to test access control
    //if (user.GetProperty("password") != "xxx")
    //    user.DenyConnection();
}

function ServerHandleUserConnected(connectionID, user)
{
    var avatarEntityName = "Avatar" + connectionID;
    var avatarEntity = scene.CreateEntityRaw(scene.NextFreeId(), ["EC_Script", "EC_Placeable", "EC_AnimationController"]);
    avatarEntity.SetTemporary(true); // We never want to save the avatar entities to disk.
    avatarEntity.SetName(avatarEntityName);
    avatarEntity.SetDescription(user.GetProperty("username"));

    print("Hai. Ur name is " + user.GetProperty("username"));

    var script = avatarEntity.script;
    script.type = "js";
    script.runOnLoad = true;
    var r = script.scriptRef;
    r.ref = "local://simpleavatar.js";
    script.scriptRef = r;

    var placeable = avatarEntity.placeable;
    // Set random starting position for avatar
    var transform = placeable.transform;
    transform.pos.x = (Math.random() - 0.5) * avatar_area_size + avatar_area_x;
    transform.pos.y = (Math.random() - 0.5) * avatar_area_size + avatar_area_y;
    transform.pos.z = avatar_area_z;
    placeable.transform = transform;

    scene.EmitEntityCreatedRaw(avatarEntity);
}

function ServerHandleUserDisconnected(connectionID, user)
{
    var avatarEntityName = "Avatar" + connectionID;
    var entityID = scene.GetEntityByNameRaw(avatarEntityName).Id;
    scene.RemoveEntityRaw(entityID);

    print("Kthxbye, " + user.GetProperty("username"));
}
<|endoftext|>


<commit_before>//     telegram-tl-node
//     Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
//     Released under the MIT License
//     https://github.com/enricostara/telegram-tl-node

/*jshint evil:true */

// Export the method
exports.buildType = buildType;
exports.buildTypeFunction = buildTypeFunction;
exports.buildTypes = buildTypes;
exports.inheritsTlSchema = inheritsTlSchema;
exports.registerTypeById = registerTypeById;
exports.requireTypeFromBuffer = requireTypeFromBuffer;
exports.registerTypeByName = registerTypeByName;
exports.requireTypeByName = requireTypeByName;

// Import dependencies
var ConstructorBuilder = require('./constructor-builder');
var util = require('util');
var utility = require('../utility');
var getLogger = require('get-log');
var logger = getLogger('TypeBuilder');

// Extends the 'constructor' with the Type generated by the 'superTLSchema'
function inheritsTlSchema(constructor, superTlSchema) {
    var NewType = buildType('abstract', superTlSchema);
    util.inherits(constructor, NewType);
    constructor.s_ = NewType;
    constructor.super_ = NewType.super_;
    constructor.util = NewType.util;
    constructor.requireTypeByName = NewType.requireTypeByName;
    constructor.requireTypeFromBuffer = NewType.requireTypeFromBuffer;
    constructor.logger = NewType.logger;
}

// Types builder
function buildTypes(schemas, types, targetModule, isTypeFunction) {
    for (var i = 0; i < schemas.length; i++) {
        var type = schemas[i];
        // Vector is already defined by class TypeVector
        if ('vector' !== type.predicate &&
            ( !types || types.indexOf(type[isTypeFunction ? 'method' : 'type']) > -1)) {
            var typeName, newType;
            if (isTypeFunction) {
                typeName = type.method;
                var newFunction = buildTypeFunction(targetModule._id, type);
                setType(typeName, targetModule, newFunction, true);
            } else {
                typeName = type.predicate;
                var newConstructor = buildType(targetModule._id, type);
                setType(typeName, targetModule, newConstructor, false);
            }
        }
    }
}
function setType(typeName, targetModule, type, isTypeFunction) {
    if (targetModule && typeName && typeName.length > 0) {
        var index = typeName.indexOf('.');
        if (index < 0) {
            typeName = isTypeFunction ? typeName : utility.capitalize(typeName);
            return targetModule[typeName] = type;
        } else if (index === 0) {
            setType(typeName.slice(1), targetModule, type, isTypeFunction);
        } else if (index === (typeName.length - 1)) {
            setType(typeName.slice(0, -1), targetModule, type, isTypeFunction);
        }
        else {
            var pkg = typeName.slice(0, index);
            targetModule[pkg] = targetModule[pkg] ? targetModule[pkg] : {};
            setType(typeName.slice(index + 1), targetModule[pkg], type, isTypeFunction);
        }
    }
}
// This function builds a new `TypeLanguage` type parsing the `TL-Schema constructor`
function buildType(module, tlSchema) {
    return new ConstructorBuilder(module, tlSchema).getType();
}

// This function builds a new `TypeLanguage` function parsing the `TL-Schema method`
function buildTypeFunction(module, tlSchema) {
    var methodName = tlSchema.method;
    // Start creating the body of the new Type function
    var body =
        '\tvar self = arguments.callee;\n' +
        '\tvar callback = options.callback;\n' +
        '\tvar channel = options.channel;\n' +
        '\tif (!channel) {\n' +
        '\t\tvar msg = \'The \\\'channel\\\' option is missing, it\\\'s mandatory\';\n' +
        '\t\tself.logger.error(msg);\n' +
        '\t\tif(callback) {\n' +
        '\t\t\tcallback(new TypeError(msg));\n' +
        '\t\t}\n' +
        '\t\treturn;\n' +
        '\t}\n';
    body +=
        '\tvar reqPayload = new self.Type(options);\n' +
        '\tchannel.callMethod(reqPayload, callback);\n';
    if (logger.isDebugEnabled()) {
        logger.debug('Body for %s type function:', methodName);
        logger.debug('\n' + body);
    }
    // Create the new Type function
    var typeFunction = new Function('options', body);
    typeFunction._name = methodName;
    typeFunction.requireTypeFromBuffer = ConstructorBuilder.requireTypeFromBuffer;
    // Create the function payload class re-calling TypeBuilder constructor.
    typeFunction.Type = new ConstructorBuilder(module, tlSchema, true).getType();
    typeFunction.logger = getLogger(module + '.' + methodName);
    return typeFunction;
}

function registerTypeById(type) {
    ConstructorBuilder.registerTypeById(type);
}

function requireTypeFromBuffer(buffer) {
    return ConstructorBuilder.requireTypeFromBuffer(buffer);
}

function registerTypeByName(name, type) {
    ConstructorBuilder.registerTypeByName(name, type);
}

function requireTypeByName(name, type) {
    return ConstructorBuilder.requireTypeByName(name, type);
}<commit_msg>Prune unused var<commit_after>//     telegram-tl-node
//     Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
//     Released under the MIT License
//     https://github.com/enricostara/telegram-tl-node

/*jshint evil:true */

// Export the method
exports.buildType = buildType;
exports.buildTypeFunction = buildTypeFunction;
exports.buildTypes = buildTypes;
exports.inheritsTlSchema = inheritsTlSchema;
exports.registerTypeById = registerTypeById;
exports.requireTypeFromBuffer = requireTypeFromBuffer;
exports.registerTypeByName = registerTypeByName;
exports.requireTypeByName = requireTypeByName;

// Import dependencies
var ConstructorBuilder = require('./constructor-builder');
var util = require('util');
var utility = require('../utility');
var getLogger = require('get-log');
var logger = getLogger('TypeBuilder');

// Extends the 'constructor' with the Type generated by the 'superTLSchema'
function inheritsTlSchema(constructor, superTlSchema) {
    var NewType = buildType('abstract', superTlSchema);
    util.inherits(constructor, NewType);
    constructor.s_ = NewType;
    constructor.super_ = NewType.super_;
    constructor.util = NewType.util;
    constructor.requireTypeByName = NewType.requireTypeByName;
    constructor.requireTypeFromBuffer = NewType.requireTypeFromBuffer;
    constructor.logger = NewType.logger;
}

// Types builder
function buildTypes(schemas, types, targetModule, isTypeFunction) {
    for (var i = 0; i < schemas.length; i++) {
        var type = schemas[i];
        // Vector is already defined by class TypeVector
        if ('vector' !== type.predicate &&
            ( !types || types.indexOf(type[isTypeFunction ? 'method' : 'type']) > -1)) {
            var typeName;
            if (isTypeFunction) {
                typeName = type.method;
                var newFunction = buildTypeFunction(targetModule._id, type);
                setType(typeName, targetModule, newFunction, true);
            } else {
                typeName = type.predicate;
                var newConstructor = buildType(targetModule._id, type);
                setType(typeName, targetModule, newConstructor, false);
            }
        }
    }
}
function setType(typeName, targetModule, type, isTypeFunction) {
    if (targetModule && typeName && typeName.length > 0) {
        var index = typeName.indexOf('.');
        if (index < 0) {
            typeName = isTypeFunction ? typeName : utility.capitalize(typeName);
            return targetModule[typeName] = type;
        } else if (index === 0) {
            setType(typeName.slice(1), targetModule, type, isTypeFunction);
        } else if (index === (typeName.length - 1)) {
            setType(typeName.slice(0, -1), targetModule, type, isTypeFunction);
        }
        else {
            var pkg = typeName.slice(0, index);
            targetModule[pkg] = targetModule[pkg] ? targetModule[pkg] : {};
            setType(typeName.slice(index + 1), targetModule[pkg], type, isTypeFunction);
        }
    }
}
// This function builds a new `TypeLanguage` type parsing the `TL-Schema constructor`
function buildType(module, tlSchema) {
    return new ConstructorBuilder(module, tlSchema).getType();
}

// This function builds a new `TypeLanguage` function parsing the `TL-Schema method`
function buildTypeFunction(module, tlSchema) {
    var methodName = tlSchema.method;
    // Start creating the body of the new Type function
    var body =
        '\tvar self = arguments.callee;\n' +
        '\tvar callback = options.callback;\n' +
        '\tvar channel = options.channel;\n' +
        '\tif (!channel) {\n' +
        '\t\tvar msg = \'The \\\'channel\\\' option is missing, it\\\'s mandatory\';\n' +
        '\t\tself.logger.error(msg);\n' +
        '\t\tif(callback) {\n' +
        '\t\t\tcallback(new TypeError(msg));\n' +
        '\t\t}\n' +
        '\t\treturn;\n' +
        '\t}\n';
    body +=
        '\tvar reqPayload = new self.Type(options);\n' +
        '\tchannel.callMethod(reqPayload, callback);\n';
    if (logger.isDebugEnabled()) {
        logger.debug('Body for %s type function:', methodName);
        logger.debug('\n' + body);
    }
    // Create the new Type function
    var typeFunction = new Function('options', body);
    typeFunction._name = methodName;
    typeFunction.requireTypeFromBuffer = ConstructorBuilder.requireTypeFromBuffer;
    // Create the function payload class re-calling TypeBuilder constructor.
    typeFunction.Type = new ConstructorBuilder(module, tlSchema, true).getType();
    typeFunction.logger = getLogger(module + '.' + methodName);
    return typeFunction;
}

function registerTypeById(type) {
    ConstructorBuilder.registerTypeById(type);
}

function requireTypeFromBuffer(buffer) {
    return ConstructorBuilder.requireTypeFromBuffer(buffer);
}

function registerTypeByName(name, type) {
    ConstructorBuilder.registerTypeByName(name, type);
}

function requireTypeByName(name, type) {
    return ConstructorBuilder.requireTypeByName(name, type);
}<|endoftext|>


<commit_before>/**
 * Multicolumn image gallery by Andreas Lorer
 * http://andreaslorer.de
 *
 * GNU General Public License, version 2
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Examples and documentation available on the project homepage
 * http://bithugger.github.io/MulticolumnGallery/
 *
 */

var requestResult = "";
var hasColumns = -1;
var columns = 0;
var names = "";
var resize = "";
var fadeIn = "";

/* ajax call for Gallery images*/
$.ajax({
		url: "php/Gallery.php",
		type: 'post',
		data: { width: $(window).width(), galleryWidth: $('.popup-gallery').innerWidth(),},
		cache: false,
		success: function(json) {
			var winWidth = $(window).width();
			var winHeight = $(window).height();
			requestResult = json;
			columns = requestResult['numOfColumns'];
			queries = requestResult['mediaQueries'];
			names = requestResult['columnNames'];
			resize = requestResult['resize'];
			fadeIn = requestResult['fadeIn'];

			for (var i = 0; i < columns; i++) {
				if(i == 0){
					buildColumn(names[i]);
					refreshScreen();
				}else{
					if(winWidth >= queries[i]){
						buildColumn(names[i]);
						refreshScreen();
					}
				}
			};

		},
		error: function(xhr, desc, err) {
			console.log(xhr + "\n" + err);
		}
	}); // end ajax call
<commit_msg>fix: typo<commit_after>/**
 * Multicolumn image gallery by Andreas Lorer
 * http://andreaslorer.de
 *
 * GNU General Public License, version 2
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Examples and documentation available on the project homepage
 * http://bithugger.github.io/MulticolumnGallery/
 *
 */

var requestResult = "";
var hasColumns = -1;
var columns = 0;
var names = "";
var resize = "";
var fadeIn = "";

/* ajax call for Gallery images*/
$.ajax({
		url: "php/Gallery.php",
		type: 'post',
		data: { width: $(window).width(), galleryWidth: $('.popup-gallery').innerWidth(),},
		cache: false,
		success: function(json) {
			var winWidth = $(window).width();
			var winHeight = $(window).height();
			requestResult = json;
			columns = requestResult['numOfColumns'];
			queries = requestResult['mediaQueries'];
			names = requestResult['columnNames'];
			resize = requestResult['resize'];
			fadeIn = requestResult['fadeIn'];

			for (var i = 0; i < columns; i++) {
				if(i == 0){
					buildColumn(names[i]);
					refreshScreen();
				}else{
					if(winWidth >= queries[i]){
						buildColumn(names[i]);
						refreshScreen();
					}
				}
			};

		},
		error: function(err) {
			console.log("Ajax Error: "+ err);
		}
	}); // end ajax call
<|endoftext|>


<commit_before>(function() {

    if (! jasmine) {
        throw new Exception("jasmine library does not exist in global namespace!");
    }

    function elapsed(startTime, endTime) {
        return (endTime - startTime)/1000;
    }

    function ISODateString(d) {
        function pad(n) { return n < 10 ? '0'+n : n; }

        return d.getFullYear() + '-'
            + pad(d.getMonth()+1) +'-'
            + pad(d.getDate()) + 'T'
            + pad(d.getHours()) + ':'
            + pad(d.getMinutes()) + ':'
            + pad(d.getSeconds());
    }

    function trim(str) {
        return str.replace(/^\s+/, "" ).replace(/\s+$/, "" );
    }

    function escapeInvalidXmlChars(str) {
        return str.replace(/\&/g, "&")
            .replace(/</g, "<")
            .replace(/\>/g, ">")
            .replace(/\"/g, """)
            .replace(/\'/g, "'");
    }

    /**
     * PhantomJS Reporter generates JUnit XML for the given spec run.
     * Allows the test results to be used in java based CI.
     * It appends some DOM elements/containers, so that a PhantomJS script can pick that up.
     *
     * @param {boolean} consolidate whether to save nested describes within the
     *                  same file as their parent; default: true
     * @param {boolean} useDotNotation whether to separate suite names with
     *                  dots rather than spaces (ie "Class.init" not
     *                  "Class init"); default: true
     */
    var PhantomJSReporter =  function(consolidate, useDotNotation) {
        this.consolidate = consolidate === jasmine.undefined ? true : consolidate;
        this.useDotNotation = useDotNotation === jasmine.undefined ? true : useDotNotation;
    };

    PhantomJSReporter.prototype = {
        reportRunnerStarting: function(runner) {
            this.log("Runner Started.");
        },

        reportSpecStarting: function(spec) {
            spec.startTime = new Date();

            if (! spec.suite.startTime) {
                spec.suite.startTime = spec.startTime;
            }

            this.log(spec.suite.description + ' : ' + spec.description + ' ... ');
        },

        reportSpecResults: function(spec) {
            var results = spec.results();
            spec.didFail = !results.passed();
            spec.status = spec.didFail ? 'Failed.' : 'Passed.';
            if (results.skipped) {
                spec.status = 'Skipped.';
            }
            this.log(spec.status);

            spec.duration = elapsed(spec.startTime, new Date());
            spec.output = '<testcase classname="' + this.getFullName(spec.suite) +
                '" name="' + escapeInvalidXmlChars(spec.description) + '" time="' + spec.duration + '">';

            var failure = "";
            var failures = 0;
            var resultItems = results.getItems();
            for (var i = 0; i < resultItems.length; i++) {
                var result = resultItems[i];

                if (result.type == 'expect' && result.passed && !result.passed()) {
                    failures += 1;
                    failure += (failures + ": " + escapeInvalidXmlChars(result.message) + " ");
                }
            }
            if (failure) {
                spec.output += "<failure>" + trim(failure) + "</failure>";
            }
            spec.output += "</testcase>";
        },

        reportSuiteResults: function(suite) {
            var results = suite.results();
            var specs = suite.specs();
            var specOutput = "";
            // for JUnit results, let's only include directly failed tests (not nested suites')
            var failedCount = 0;

            suite.status = results.passed() ? 'Passed.' : 'Failed.';
            suite.statusPassed = results.passed();
            if (results.totalCount === 0) { // todo: change this to check results.skipped
                suite.status = 'Skipped.';
            }

            // if a suite has no (active?) specs, reportSpecStarting is never called
            // and thus the suite has no startTime -- account for that here
            suite.startTime = suite.startTime || new Date();
            suite.duration = elapsed(suite.startTime, new Date());

            for (var i = 0; i < specs.length; i++) {
                failedCount += specs[i].didFail ? 1 : 0;
                specOutput += "\n  " + specs[i].output;
            }
            suite.output = '\n<testsuite name="' + this.getFullName(suite) +
                '" errors="0" tests="' + specs.length + '" failures="' + failedCount +
                '" time="' + suite.duration + '" timestamp="' + ISODateString(suite.startTime) + '">';
            suite.output += specOutput;
            suite.output += "\n</testsuite>";
            this.log(suite.description + ": " + results.passedCount + " of " + results.totalCount + " expectations passed.");
        },

        reportRunnerResults: function(runner) {
            this.log("Runner Finished.");
            var suites = runner.suites(),
                passed = true;
            for (var i = 0; i < suites.length; i++) {
                var suite = suites[i],
                    filename = 'TEST-' + this.getFullName(suite, true) + '.xml',
                    output = '<?xml version="1.0" encoding="UTF-8" ?>';

                passed = !suite.statusPassed ? false : passed;

                // if we are consolidating, only write out top-level suites
                if (this.consolidate && suite.parentSuite) {
                    continue;
                }
                else if (this.consolidate) {
                    output += "\n<testsuites>";
                    output += this.getNestedOutput(suite);
                    output += "\n</testsuites>";
                    this.createSuiteResultContainer(filename, output);
                }
                else {
                    output += suite.output;
                    this.createSuiteResultContainer(filename, output);
                }
            }
            this.createTestFinishedContainer(passed);
        },

        getNestedOutput: function(suite) {
            var output = suite.output;
            for (var i = 0; i < suite.suites().length; i++) {
                output += this.getNestedOutput(suite.suites()[i]);
            }
            return output;
        },

        createSuiteResultContainer: function(filename, xmloutput) {
            jasmine.phantomjsXMLReporterResults = jasmine.phantomjsXMLReporterResults || [];
            jasmine.phantomjsXMLReporterResults.push({
                "xmlfilename" : filename,
                "xmlbody" : xmloutput
            });
        },

        createTestFinishedContainer: function(passed) {
            jasmine.phantomjsXMLReporterPassed = passed
        },

        getFullName: function(suite, isFilename) {
            var fullName;
            if (this.useDotNotation) {
                fullName = suite.description;
                for (var parentSuite = suite.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
                    fullName = parentSuite.description + '.' + fullName;
                }
            }
            else {
                fullName = suite.getFullName();
            }

            // Either remove or escape invalid XML characters
            if (isFilename) {
                return fullName.replace(/[^\w]/g, "");
            }
            return escapeInvalidXmlChars(fullName);
        },

        log: function(str) {
            var console = jasmine.getGlobal().console;

            if (console && console.log) {
                console.log('JASMINE: ', str);
            }
        }
    };

    // export public
    jasmine.PhantomJSReporter = PhantomJSReporter;
})();
<commit_msg>better test result formatting<commit_after>(function() {

    if (! jasmine) {
        throw new Exception("jasmine library does not exist in global namespace!");
    }

    function elapsed(startTime, endTime) {
        return (endTime - startTime)/1000;
    }

    function ISODateString(d) {
        function pad(n) { return n < 10 ? '0'+n : n; }

        return d.getFullYear() + '-'
            + pad(d.getMonth()+1) +'-'
            + pad(d.getDate()) + 'T'
            + pad(d.getHours()) + ':'
            + pad(d.getMinutes()) + ':'
            + pad(d.getSeconds());
    }

    function trim(str) {
        return str.replace(/^\s+/, "" ).replace(/\s+$/, "" );
    }

    function escapeInvalidXmlChars(str) {
        return str.replace(/\&/g, "&")
            .replace(/</g, "<")
            .replace(/\>/g, ">")
            .replace(/\"/g, """)
            .replace(/\'/g, "'");
    }

    /**
     * PhantomJS Reporter generates JUnit XML for the given spec run.
     * Allows the test results to be used in java based CI.
     * It appends some DOM elements/containers, so that a PhantomJS script can pick that up.
     *
     * @param {boolean} consolidate whether to save nested describes within the
     *                  same file as their parent; default: true
     * @param {boolean} useDotNotation whether to separate suite names with
     *                  dots rather than spaces (ie "Class.init" not
     *                  "Class init"); default: true
     */
    var PhantomJSReporter =  function(consolidate, useDotNotation) {
        this.consolidate = consolidate === jasmine.undefined ? true : consolidate;
        this.useDotNotation = useDotNotation === jasmine.undefined ? true : useDotNotation;
    };

    PhantomJSReporter.prototype = {
        reportRunnerStarting: function(runner) {
            this.log("Runner Started.");
        },

        reportSpecStarting: function(spec) {
            spec.startTime = new Date();

            if (! spec.suite.startTime) {
                spec.suite.startTime = spec.startTime;
            }

            if (!spec.suite.descriptionLogged) {
                this.log(spec.suite.description);
                spec.suite.descriptionLogged = true;
            }

            this.log('    ' + spec.description + '.');
        },

        reportSpecResults: function(spec) {
            var results     = spec.results();
            var resultItems = results.getItems();
            spec.didFail    = !results.passed();

            if (results.skipped) {
                this.log('    Skipped.');
            } else if (!results.passed()) {
                for (var index in resultItems) {
                    var result = resultItems[index];
                    if (result && !result.passed()) {
                        this.log('        Failed: ' + result.message);
                    }
                }
            }

            spec.duration = elapsed(spec.startTime, new Date());
            spec.output = '<testcase classname="' + this.getFullName(spec.suite) +
                '" name="' + escapeInvalidXmlChars(spec.description) + '" time="' + spec.duration + '">';

            var failure = "";
            var failures = 0;
            for (var i = 0; i < resultItems.length; i++) {
                var result = resultItems[i];

                if (result.type == 'expect' && result.passed && !result.passed()) {
                    failures += 1;
                    failure += (failures + ": " + escapeInvalidXmlChars(result.message) + " ");
                }
            }
            if (failure) {
                spec.output += "<failure>" + trim(failure) + "</failure>";
            }
            spec.output += "</testcase>";
        },

        reportSuiteResults: function(suite) {
            var results = suite.results();
            var specs = suite.specs();
            var specOutput = "";
            // for JUnit results, let's only include directly failed tests (not nested suites')
            var failedCount = 0;

            suite.status = results.passed() ? 'Passed.' : 'Failed.';
            suite.statusPassed = results.passed();
            if (results.totalCount === 0) { // todo: change this to check results.skipped
                suite.status = 'Skipped.';
            }

            // if a suite has no (active?) specs, reportSpecStarting is never called
            // and thus the suite has no startTime -- account for that here
            suite.startTime = suite.startTime || new Date();
            suite.duration = elapsed(suite.startTime, new Date());

            for (var i = 0; i < specs.length; i++) {
                failedCount += specs[i].didFail ? 1 : 0;
                specOutput += "\n  " + specs[i].output;
            }
            suite.output = '\n<testsuite name="' + this.getFullName(suite) +
                '" errors="0" tests="' + specs.length + '" failures="' + failedCount +
                '" time="' + suite.duration + '" timestamp="' + ISODateString(suite.startTime) + '">';
            suite.output += specOutput;
            suite.output += "\n</testsuite>";
            this.log('    ' + results.passedCount + " of " + results.totalCount + " expectations passed. (" + suite.description + ")");
        },

        reportRunnerResults: function(runner) {
            this.log("Runner Finished.");
            var suites = runner.suites(),
                passed = true;
            for (var i = 0; i < suites.length; i++) {
                var suite = suites[i],
                    filename = 'TEST-' + this.getFullName(suite, true) + '.xml',
                    output = '<?xml version="1.0" encoding="UTF-8" ?>';

                passed = !suite.statusPassed ? false : passed;

                // if we are consolidating, only write out top-level suites
                if (this.consolidate && suite.parentSuite) {
                    continue;
                }
                else if (this.consolidate) {
                    output += "\n<testsuites>";
                    output += this.getNestedOutput(suite);
                    output += "\n</testsuites>";
                    this.createSuiteResultContainer(filename, output);
                }
                else {
                    output += suite.output;
                    this.createSuiteResultContainer(filename, output);
                }
            }
            this.createTestFinishedContainer(passed);
        },

        getNestedOutput: function(suite) {
            var output = suite.output;
            for (var i = 0; i < suite.suites().length; i++) {
                output += this.getNestedOutput(suite.suites()[i]);
            }
            return output;
        },

        createSuiteResultContainer: function(filename, xmloutput) {
            jasmine.phantomjsXMLReporterResults = jasmine.phantomjsXMLReporterResults || [];
            jasmine.phantomjsXMLReporterResults.push({
                "xmlfilename" : filename,
                "xmlbody" : xmloutput
            });
        },

        createTestFinishedContainer: function(passed) {
            jasmine.phantomjsXMLReporterPassed = passed
        },

        getFullName: function(suite, isFilename) {
            var fullName;
            if (this.useDotNotation) {
                fullName = suite.description;
                for (var parentSuite = suite.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
                    fullName = parentSuite.description + '.' + fullName;
                }
            }
            else {
                fullName = suite.getFullName();
            }

            // Either remove or escape invalid XML characters
            if (isFilename) {
                return fullName.replace(/[^\w]/g, "");
            }
            return escapeInvalidXmlChars(fullName);
        },

        log: function(str) {
            var console = jasmine.getGlobal().console;

            if (console && console.log) {
                console.log('JASMINE: ', str);
            }
        }
    };

    // export public
    jasmine.PhantomJSReporter = PhantomJSReporter;
})();
<|endoftext|>


<commit_before>class Cell{
    constructor(i,j){
        this.i = i;
        this.j = j;
        this.alive = false;
        this.survives = false; //Made so not to change alive variabe mid-loop, also controls birthing of new cells

    }

    update(grid){
        let neighbours = 0;
        //Variables to make the conditionals below shorter
        const top     = this.j - 1;
        const right   = this.i + 1;
        const bottom  = this.j + 1;
        const left    = this.i - 1;
        const middlei = this.i;
        const middlej = this.j;

        //Check all the cells around a given cell
        try{
            if(grid[left][top] && grid[left][top].alive) {neighbours++;} //Left top
            if(grid[middlei][top] && grid[middlei][top].alive) {neighbours++;} //Middlei top
            if(grid[right][top] && grid[right][top].alive) {neighbours++;} //Right top
            if(grid[left][middlej] && grid[left][middlej].alive) {neighbours++;} //Left middlej
            if(grid[right][middlej] && grid[right][middlej].alive) {neighbours++;} //Right middlej
            if(grid[left][bottom] && grid[left][bottom].alive) {neighbours++;} //Left bottom
            if(grid[middlei][bottom] && grid[middlei][bottom].alive) {neighbours++;} //Middlei bottom
            if(grid[right][bottom] && grid[right][bottom].alive) {neighbours++;} //Right bottom
        } catch(ArrayIndexOutOfBoundsException) {}

        //This is where the magic happens:
        if(this.alive && neighbours < 2) {this.survives = false;}
        else if(this.alive && (neighbours === 2 || this.neighbours === 3)) {this.survives = true;}
        else if(this.alive && neighbours > 3){this.survives = false;}
        else if(!this.alive && neighbours === 3){this.survives = true;}
    }

    render(size){
        if(this.alive){
            stroke(255);
            fill(255, 0, 50);
        }else{
            stroke(255);
            fill(180);
        }
        rect(this.i*size, this.j*size, size, size);
    }

}

<commit_msg>Changed render() to draw everything one size to the left and up because of zero padding<commit_after>class Cell{
    constructor(i,j){
        this.i = i;
        this.j = j;
        this.alive = false;
        this.survives = false; //Made so not to change alive variabe mid-loop, also controls birthing of new cells

    }

    update(grid){
        let neighbours = 0;
        //Variables to make the conditionals below shorter
        const top     = this.j - 1;
        const right   = this.i + 1;
        const bottom  = this.j + 1;
        const left    = this.i - 1;
        const middlei = this.i;
        const middlej = this.j;

        //Check all the cells around a given cell
        try{
            if(grid[left][top] && grid[left][top].alive) {neighbours++;} //Left top
            if(grid[middlei][top] && grid[middlei][top].alive) {neighbours++;} //Middlei top
            if(grid[right][top] && grid[right][top].alive) {neighbours++;} //Right top
            if(grid[left][middlej] && grid[left][middlej].alive) {neighbours++;} //Left middlej
            if(grid[right][middlej] && grid[right][middlej].alive) {neighbours++;} //Right middlej
            if(grid[left][bottom] && grid[left][bottom].alive) {neighbours++;} //Left bottom
            if(grid[middlei][bottom] && grid[middlei][bottom].alive) {neighbours++;} //Middlei bottom
            if(grid[right][bottom] && grid[right][bottom].alive) {neighbours++;} //Right bottom
        } catch(ArrayIndexOutOfBoundsException) {}

        //This is where the magic happens:
        if(this.alive && neighbours < 2) {this.survives = false;}
        else if(this.alive && (neighbours === 2 || this.neighbours === 3)) {this.survives = true;}
        else if(this.alive && neighbours > 3){this.survives = false;}
        else if(!this.alive && neighbours === 3){this.survives = true;}
    }

    render(size){
        if(this.alive){
            stroke(255);
            fill(255, 0, 50);
        }else{
            stroke(255);
            fill(180);
        }
        rect(this.i*size - (2*size), this.j*size - (2*size), size, size);
    }

}

<|endoftext|>


<commit_before>var mkdir = require("mkdirp")
  , assert = require("assert")
  , git = require("../utils/git.js")
  , once = require("once")
  , fs = require("graceful-fs")
  , log = require("npmlog")
  , path = require("path")
  , url = require("url")
  , chownr = require("chownr")
  , zlib = require("zlib")
  , crypto = require("crypto")
  , npm = require("../npm.js")
  , rm = require("../utils/gently-rm.js")
  , inflight = require("inflight")
  , locker = require("../utils/locker.js")
  , lock = locker.lock
  , unlock = locker.unlock
  , getCacheStat = require("./get-stat.js")
  , addLocalTarball = require("./add-local-tarball.js")

// 1. cacheDir = path.join(cache,'_git-remotes',sha1(u))
// 2. checkGitDir(cacheDir) ? 4. : 3. (rm cacheDir if necessary)
// 3. git clone --mirror u cacheDir
// 4. cd cacheDir && git fetch -a origin
// 5. git archive /tmp/random.tgz
// 6. addLocalTarball(/tmp/random.tgz) <gitref> --format=tar --prefix=package/
// silent flag is used if this should error quietly
module.exports = function addRemoteGit (u, silent, cb_) {
  assert(typeof u === "string", "must have git URL")
  assert(typeof cb_ === "function", "must have callback")

  function cb (er, data) {
    unlock(u, function () { cb_(er, data) })
  }

  cb_ = inflight(u, cb_)

  if (!cb_) return

  log.verbose("addRemoteGit", "u=%j silent=%j", u, silent)
  var parsed = url.parse(u, true)
  log.silly("addRemoteGit", "parsed", parsed)

  // git is so tricky!
  // if the path is like ssh://foo:22/some/path then it works, but
  // it needs the ssh://
  // If the path is like ssh://foo:some/path then it works, but
  // only if you remove the ssh://
  var origUrl = u
  u = u.replace(/^git\+/, "")
       .replace(/#.*$/, "")

  // ssh paths that are scp-style urls don't need the ssh://
  if (parsed.pathname.match(/^\/?:/)) {
    u = u.replace(/^ssh:\/\//, "")
  }

  lock(u, function (er) {
    if (er) return cb(er)

    // figure out what we should check out.
    var co = parsed.hash && parsed.hash.substr(1) || "master"

    var v = crypto.createHash("sha1").update(u).digest("hex").slice(0, 8)
    v = u.replace(/[^a-zA-Z0-9]+/g, "-")+"-"+v

    log.verbose("addRemoteGit", [u, co])

    var p = path.join(npm.config.get("cache"), "_git-remotes", v)

    checkGitDir(p, u, co, origUrl, silent, function(er, data) {
      addModeRecursive(p, npm.modes.file, function(erAddMode) {
        if (er) return cb(er, data)
        return cb(erAddMode, data)
      })
    })
  })
}

function checkGitDir (p, u, co, origUrl, silent, cb) {
  fs.stat(p, function (er, s) {
    if (er) return cloneGitRemote(p, u, co, origUrl, silent, cb)
    if (!s.isDirectory()) return rm(p, function (er){
      if (er) return cb(er)
      cloneGitRemote(p, u, co, origUrl, silent, cb)
    })

    var args = [ "config", "--get", "remote.origin.url" ]
    var env = gitEnv()

    // check for git
    git.whichAndExec(args, {cwd: p, env: env}, function (er, stdout, stderr) {
      var stdoutTrimmed = (stdout + "\n" + stderr).trim()
      if (er || u !== stdout.trim()) {
        log.warn( "`git config --get remote.origin.url` returned "
                + "wrong result ("+u+")", stdoutTrimmed )
        return rm(p, function (er){
          if (er) return cb(er)
          cloneGitRemote(p, u, co, origUrl, silent, cb)
        })
      }
      log.verbose("git remote.origin.url", stdoutTrimmed)
      archiveGitRemote(p, u, co, origUrl, cb)
    })
  })
}

function cloneGitRemote (p, u, co, origUrl, silent, cb) {
  mkdir(p, function (er) {
    if (er) return cb(er)

    var args = [ "clone", "--mirror", u, p ]
    var env = gitEnv()

    // check for git
    git.whichAndExec(args, {cwd: p, env: env}, function (er, stdout, stderr) {
      stdout = (stdout + "\n" + stderr).trim()
      if (er) {
        if (silent) {
          log.verbose("git clone " + u, stdout)
        } else {
          log.error("git clone " + u, stdout)
        }
        return cb(er)
      }
      log.verbose("git clone " + u, stdout)
      archiveGitRemote(p, u, co, origUrl, cb)
    })
  })
}

function archiveGitRemote (p, u, co, origUrl, cb) {
  var archive = [ "fetch", "-a", "origin" ]
  var resolve = [ "rev-list", "-n1", co ]
  var env = gitEnv()

  var resolved = null
  var tmp

  git.whichAndExec(archive, {cwd: p, env: env}, function (er, stdout, stderr) {
    stdout = (stdout + "\n" + stderr).trim()
    if (er) {
      log.error("git fetch -a origin ("+u+")", stdout)
      return cb(er)
    }
    log.verbose("git fetch -a origin ("+u+")", stdout)
    tmp = path.join(npm.tmp, Date.now()+"-"+Math.random(), "tmp.tgz")
    verifyOwnership()
  })

  function verifyOwnership() {
    if (process.platform === "win32") {
      log.silly("verifyOwnership", "skipping for windows")
      resolveHead()
    } else {
      getCacheStat(function(er, cs) {
        if (er) {
          log.error("Could not get cache stat")
          return cb(er)
        }
        chownr(p, cs.uid, cs.gid, function(er) {
          if (er) {
            log.error("Failed to change folder ownership under npm cache for %s", p)
            return cb(er)
          }
          resolveHead()
        })
      })
    }
  }

  function resolveHead () {
    git.whichAndExec(resolve, {cwd: p, env: env}, function (er, stdout, stderr) {
      stdout = (stdout + "\n" + stderr).trim()
      if (er) {
        log.error("Failed resolving git HEAD (" + u + ")", stderr)
        return cb(er)
      }
      log.verbose("git rev-list -n1 " + co, stdout)
      var parsed = url.parse(origUrl)
      parsed.hash = stdout
      resolved = url.format(parsed)

      // https://github.com/npm/npm/issues/3224
      // node incorrectly sticks a / at the start of the path
      // We know that the host won't change, so split and detect this
      var spo = origUrl.split(parsed.host)
      var spr = resolved.split(parsed.host)
      if (spo[1].charAt(0) === ":" && spr[1].charAt(0) === "/")
        spr[1] = spr[1].slice(1)
      resolved = spr.join(parsed.host)

      log.verbose("resolved git url", resolved)
      next()
    })
  }

  function next () {
    mkdir(path.dirname(tmp), function (er) {
      if (er) return cb(er)
      var gzip = zlib.createGzip({ level: 9 })
      var args = ["archive", co, "--format=tar", "--prefix=package/"]
      var out = fs.createWriteStream(tmp)
      var env = gitEnv()
      cb = once(cb)
      var cp = git.spawn(args, { env: env, cwd: p })
      cp.on("error", cb)
      cp.stderr.on("data", function(chunk) {
        log.silly(chunk.toString(), "git archive")
      })

      cp.stdout.pipe(gzip).pipe(out).on("close", function() {
        addLocalTarball(tmp, null, null, function(er, data) {
          if (data) data._resolved = resolved
          cb(er, data)
        })
      })
    })
  }
}

var gitEnv_
function gitEnv () {
  // git responds to env vars in some weird ways in post-receive hooks
  // so don't carry those along.
  if (gitEnv_) return gitEnv_
  gitEnv_ = {}
  for (var k in process.env) {
    if (!~["GIT_PROXY_COMMAND","GIT_SSH","GIT_SSL_NO_VERIFY"].indexOf(k) && k.match(/^GIT/)) continue
    gitEnv_[k] = process.env[k]
  }
  return gitEnv_
}

// similar to chmodr except it add permissions rather than overwriting them
// adapted from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function addModeRecursive(p, mode, cb) {
  fs.readdir(p, function (er, children) {
    // Any error other than ENOTDIR means it's not readable, or doesn't exist.
    // Give up.
    if (er && er.code !== "ENOTDIR") return cb(er)
    if (er || !children.length) return addMode(p, mode, cb)

    var len = children.length
    var errState = null
    children.forEach(function (child) {
      addModeRecursive(path.resolve(p, child), mode, then)
    })

    function then (er) {
      if (errState) return undefined
      if (er) return cb(errState = er)
      if (--len === 0) return addMode(p, dirMode(mode), cb)
    }
  })
}

function addMode(p, mode, cb) {
    fs.stat(p, function (er, stats) {
      if (er) return cb(er)
      mode = stats.mode | mode
      fs.chmod(p, mode, cb)
    })
}

// taken from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function dirMode(mode) {
  if (mode & parseInt("0400", 8)) mode |= parseInt("0100", 8)
  if (mode & parseInt( "040", 8)) mode |= parseInt( "010", 8)
  if (mode & parseInt(  "04", 8)) mode |= parseInt(  "01", 8)
  return mode
}

<commit_msg>Prepend the git+ to git urls if not found in _resolved<commit_after>var mkdir = require("mkdirp")
  , assert = require("assert")
  , git = require("../utils/git.js")
  , once = require("once")
  , fs = require("graceful-fs")
  , log = require("npmlog")
  , path = require("path")
  , url = require("url")
  , chownr = require("chownr")
  , zlib = require("zlib")
  , crypto = require("crypto")
  , npm = require("../npm.js")
  , rm = require("../utils/gently-rm.js")
  , inflight = require("inflight")
  , locker = require("../utils/locker.js")
  , lock = locker.lock
  , unlock = locker.unlock
  , getCacheStat = require("./get-stat.js")
  , addLocalTarball = require("./add-local-tarball.js")

// 1. cacheDir = path.join(cache,'_git-remotes',sha1(u))
// 2. checkGitDir(cacheDir) ? 4. : 3. (rm cacheDir if necessary)
// 3. git clone --mirror u cacheDir
// 4. cd cacheDir && git fetch -a origin
// 5. git archive /tmp/random.tgz
// 6. addLocalTarball(/tmp/random.tgz) <gitref> --format=tar --prefix=package/
// silent flag is used if this should error quietly
module.exports = function addRemoteGit (u, silent, cb_) {
  assert(typeof u === "string", "must have git URL")
  assert(typeof cb_ === "function", "must have callback")

  function cb (er, data) {
    unlock(u, function () { cb_(er, data) })
  }

  cb_ = inflight(u, cb_)

  if (!cb_) return

  log.verbose("addRemoteGit", "u=%j silent=%j", u, silent)
  var parsed = url.parse(u, true)
  log.silly("addRemoteGit", "parsed", parsed)

  // git is so tricky!
  // if the path is like ssh://foo:22/some/path then it works, but
  // it needs the ssh://
  // If the path is like ssh://foo:some/path then it works, but
  // only if you remove the ssh://
  var origUrl = u
  u = u.replace(/^git\+/, "")
       .replace(/#.*$/, "")

  // ssh paths that are scp-style urls don't need the ssh://
  if (parsed.pathname.match(/^\/?:/)) {
    u = u.replace(/^ssh:\/\//, "")
  }

  lock(u, function (er) {
    if (er) return cb(er)

    // figure out what we should check out.
    var co = parsed.hash && parsed.hash.substr(1) || "master"

    var v = crypto.createHash("sha1").update(u).digest("hex").slice(0, 8)
    v = u.replace(/[^a-zA-Z0-9]+/g, "-")+"-"+v

    log.verbose("addRemoteGit", [u, co])

    var p = path.join(npm.config.get("cache"), "_git-remotes", v)

    checkGitDir(p, u, co, origUrl, silent, function(er, data) {
      addModeRecursive(p, npm.modes.file, function(erAddMode) {
        if (er) return cb(er, data)
        return cb(erAddMode, data)
      })
    })
  })
}

function checkGitDir (p, u, co, origUrl, silent, cb) {
  fs.stat(p, function (er, s) {
    if (er) return cloneGitRemote(p, u, co, origUrl, silent, cb)
    if (!s.isDirectory()) return rm(p, function (er){
      if (er) return cb(er)
      cloneGitRemote(p, u, co, origUrl, silent, cb)
    })

    var args = [ "config", "--get", "remote.origin.url" ]
    var env = gitEnv()

    // check for git
    git.whichAndExec(args, {cwd: p, env: env}, function (er, stdout, stderr) {
      var stdoutTrimmed = (stdout + "\n" + stderr).trim()
      if (er || u !== stdout.trim()) {
        log.warn( "`git config --get remote.origin.url` returned "
                + "wrong result ("+u+")", stdoutTrimmed )
        return rm(p, function (er){
          if (er) return cb(er)
          cloneGitRemote(p, u, co, origUrl, silent, cb)
        })
      }
      log.verbose("git remote.origin.url", stdoutTrimmed)
      archiveGitRemote(p, u, co, origUrl, cb)
    })
  })
}

function cloneGitRemote (p, u, co, origUrl, silent, cb) {
  mkdir(p, function (er) {
    if (er) return cb(er)

    var args = [ "clone", "--mirror", u, p ]
    var env = gitEnv()

    // check for git
    git.whichAndExec(args, {cwd: p, env: env}, function (er, stdout, stderr) {
      stdout = (stdout + "\n" + stderr).trim()
      if (er) {
        if (silent) {
          log.verbose("git clone " + u, stdout)
        } else {
          log.error("git clone " + u, stdout)
        }
        return cb(er)
      }
      log.verbose("git clone " + u, stdout)
      archiveGitRemote(p, u, co, origUrl, cb)
    })
  })
}

function archiveGitRemote (p, u, co, origUrl, cb) {
  var archive = [ "fetch", "-a", "origin" ]
  var resolve = [ "rev-list", "-n1", co ]
  var env = gitEnv()

  var resolved = null
  var tmp

  git.whichAndExec(archive, {cwd: p, env: env}, function (er, stdout, stderr) {
    stdout = (stdout + "\n" + stderr).trim()
    if (er) {
      log.error("git fetch -a origin ("+u+")", stdout)
      return cb(er)
    }
    log.verbose("git fetch -a origin ("+u+")", stdout)
    tmp = path.join(npm.tmp, Date.now()+"-"+Math.random(), "tmp.tgz")
    verifyOwnership()
  })

  function verifyOwnership() {
    if (process.platform === "win32") {
      log.silly("verifyOwnership", "skipping for windows")
      resolveHead()
    } else {
      getCacheStat(function(er, cs) {
        if (er) {
          log.error("Could not get cache stat")
          return cb(er)
        }
        chownr(p, cs.uid, cs.gid, function(er) {
          if (er) {
            log.error("Failed to change folder ownership under npm cache for %s", p)
            return cb(er)
          }
          resolveHead()
        })
      })
    }
  }

  function resolveHead () {
    git.whichAndExec(resolve, {cwd: p, env: env}, function (er, stdout, stderr) {
      stdout = (stdout + "\n" + stderr).trim()
      if (er) {
        log.error("Failed resolving git HEAD (" + u + ")", stderr)
        return cb(er)
      }
      log.verbose("git rev-list -n1 " + co, stdout)
      var parsed = url.parse(origUrl)
      parsed.hash = stdout
      resolved = url.format(parsed)

      if (parsed.proto !== "git:") {
        resolved = "git+" + resolved
      }

      // https://github.com/npm/npm/issues/3224
      // node incorrectly sticks a / at the start of the path
      // We know that the host won't change, so split and detect this
      var spo = origUrl.split(parsed.host)
      var spr = resolved.split(parsed.host)
      if (spo[1].charAt(0) === ":" && spr[1].charAt(0) === "/")
        spr[1] = spr[1].slice(1)
      resolved = spr.join(parsed.host)

      log.verbose("resolved git url", resolved)
      next()
    })
  }

  function next () {
    mkdir(path.dirname(tmp), function (er) {
      if (er) return cb(er)
      var gzip = zlib.createGzip({ level: 9 })
      var args = ["archive", co, "--format=tar", "--prefix=package/"]
      var out = fs.createWriteStream(tmp)
      var env = gitEnv()
      cb = once(cb)
      var cp = git.spawn(args, { env: env, cwd: p })
      cp.on("error", cb)
      cp.stderr.on("data", function(chunk) {
        log.silly(chunk.toString(), "git archive")
      })

      cp.stdout.pipe(gzip).pipe(out).on("close", function() {
        addLocalTarball(tmp, null, null, function(er, data) {
          if (data) data._resolved = resolved
          cb(er, data)
        })
      })
    })
  }
}

var gitEnv_
function gitEnv () {
  // git responds to env vars in some weird ways in post-receive hooks
  // so don't carry those along.
  if (gitEnv_) return gitEnv_
  gitEnv_ = {}
  for (var k in process.env) {
    if (!~["GIT_PROXY_COMMAND","GIT_SSH","GIT_SSL_NO_VERIFY"].indexOf(k) && k.match(/^GIT/)) continue
    gitEnv_[k] = process.env[k]
  }
  return gitEnv_
}

// similar to chmodr except it add permissions rather than overwriting them
// adapted from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function addModeRecursive(p, mode, cb) {
  fs.readdir(p, function (er, children) {
    // Any error other than ENOTDIR means it's not readable, or doesn't exist.
    // Give up.
    if (er && er.code !== "ENOTDIR") return cb(er)
    if (er || !children.length) return addMode(p, mode, cb)

    var len = children.length
    var errState = null
    children.forEach(function (child) {
      addModeRecursive(path.resolve(p, child), mode, then)
    })

    function then (er) {
      if (errState) return undefined
      if (er) return cb(errState = er)
      if (--len === 0) return addMode(p, dirMode(mode), cb)
    }
  })
}

function addMode(p, mode, cb) {
    fs.stat(p, function (er, stats) {
      if (er) return cb(er)
      mode = stats.mode | mode
      fs.chmod(p, mode, cb)
    })
}

// taken from https://github.com/isaacs/chmodr/blob/master/chmodr.js
function dirMode(mode) {
  if (mode & parseInt("0400", 8)) mode |= parseInt("0100", 8)
  if (mode & parseInt( "040", 8)) mode |= parseInt( "010", 8)
  if (mode & parseInt(  "04", 8)) mode |= parseInt(  "01", 8)
  return mode
}

<|endoftext|>


<commit_before>/* global MO5 */

MO5("MO5.EventBus", "MO5.ajax", "WSE.Keys", "WSE.Interpreter", "WSE.tools", "WSE").
define("WSE.Game", function (EventBus, ajax, Keys, Interpreter, tools, WSE) {

    "use strict";

    /**
     * Constructor used to create instances of games.
     *
     * You can configure the game instance using the config object
     * that can be supplied as a parameter to the constructor function.
     *
     * The options are:
     *  - url: [string] The URL of the WebStory file.
     *  - debug: [bool] Should the game be run in debug mode? (not used yet)
     *  - host: [object] The HOST object for the LocalContainer
     *      version. Optional.
     *
     * @event wse.game.constructor@WSE.bus
     * @param args A config object. See above for details.
     */
    function Game (args) {

        var host;

        WSE.trigger("wse.game.constructor", {args: args, game: this});

        args = args || {};
        this.bus = new EventBus();
        this.url = args.url || "game.xml";
        this.ws = null;
        this.debug = args.debug === true ? true : false;

        host = args.host || false;
        this.host = host;

        if (host) {

            this.ws = (function (url) {

                var xml, parser;

                parser = new DOMParser();
                xml = host.get(url);

                return parser.parseFromString(xml, "application/xml");
            }(this.url));

            this.init();
        }
        else {
            this.load(this.url);
        }

        this.interpreter = new Interpreter(this);
        this.keys = new Keys();
        this.listenersSubscribed = false;
        //console.log("this.interpreter: ", this.interpreter);

        this.bus.subscribe(
            function (data)
            {
                console.log("Message: " + data);
            },
            "wse.interpreter.message"
        );

        this.bus.subscribe(
            function (data)
            {
                console.log("Error: " + data.message);
            },
            "wse.interpreter.error"
        );

        this.bus.subscribe(
            function (data)
            {
                console.log("Warning: " + data.message, data.element);
            },
            "wse.interpreter.warning"
        );
    };

    /**
     * Loads the WebStory file using the AJAX function and triggers
     * the game initialization.
     */
    Game.prototype.load = function () {

        //console.log("Loading game file...");
        var fn, self;

        self = this;

        fn = function (obj) {
            self.ws = obj.responseXML;
            //console.log("Response XML: " + obj.responseXML);
            self.init();
        };

        ajax("GET", this.url, null, fn);
    };

    /**
     * Initializes the game instance.
     */
    Game.prototype.init = function () {

        //console.log("Initializing game...");
        var ws, stage, stageElements, stageInfo, width, height, id, self, alignFn, resizeFn;

        self = this;
        ws = this.ws;

        try {
            stageElements = ws.getElementsByTagName("stage");
        }
        catch (e) {
            console.log(e);
        }

        width = "800px";
        height = "480px";
        id = "Stage";

        if (stageElements.length < 1) {
            throw new Error("No stage definition found!");
        }

        stageInfo = stageElements[0];
        width = stageInfo.getAttribute("width") || width;
        height = stageInfo.getAttribute("height") || height;
        id = stageInfo.getAttribute("id") || id;

        // Create the stage element or inject into existing one?
        if (stageInfo.getAttribute("create") === "yes") {
            stage = document.createElement("div");
            stage.setAttribute("id", id);
            document.body.appendChild(stage);
        }
        else {
            stage = document.getElementById(id);
        }

        stage.setAttribute("class", "WSEStage");

        stage.style.width = width;
        stage.style.height = height;

        // Aligns the stage to be always in the center of the browser window.
        // Must be specified in the game file.
        alignFn = function () {

            var dim = tools.getWindowDimensions();

            stage.style.left = (dim.width / 2) - (parseInt(width, 10) / 2) + 'px';
            stage.style.top = (dim.height / 2) - (parseInt(height, 10) / 2) + 'px';
        };

        if (stageInfo.getAttribute("center") === "yes") {
            tools.attachEventListener(window, 'resize', alignFn);
            alignFn();
        }

        // Resizes the stage to fit the browser window dimensions. Must be
        // specified in the game file.
        resizeFn = function () {
            console.log("Resizing...");
            tools.fitToWindow(stage, parseInt(width, 10), parseInt(height, 10));
        };

        if (stageInfo.getAttribute("resize") === "yes") {
            tools.attachEventListener(window, 'resize', resizeFn);
            resizeFn();
        }

        this.stage = stage;
        //     stage.onclick = function() { self.interpreter.next(); };

        this.applySettings();

        // This section only applies when the engine is used inside
        // the local container app.
        if (this.host) {

            this.host.window.width = parseInt(width, 10);
            this.host.window.height = parseInt(height, 10);

            (function (self) {

                var doResize = self.getSetting("host.stage.resize") === "true" ? true : false;

                if (!doResize) {
                    return;
                }

                window.addEventListener("resize", function () {
                    console.log("Resizing...");
                    tools.fitToWindow(stage, parseInt(width, 10), parseInt(height, 10));
                });
            }(this));
        }
    };

    /**
     * Returns the value of a setting as specified in the WebStory file.
     * @param name [string] The name of the setting.
     * @return [mixed] The value of the setting or null.
     */
    Game.prototype.getSetting = function (name)
    {
        var ret, settings, i, len, cur, curName;

        settings = this.ws.getElementsByTagName("setting");

        for (i = 0, len = settings.length; i < len; i += 1)
        {
            cur = settings[i];
            curName = cur.getAttribute("name") || null;

            if (curName !== null && curName === name)
            {
                ret = cur.getAttribute("value") || null;
                return ret;
            }
        }

        return null;
    };

    // FIXME: implement...
    Game.prototype.applySettings = function () {

        this.webInspectorEnabled =
            this.getSetting("host.inspector.enable") === "true" ? true : false;

        if (this.host) {

            if (this.webInspectorEnabled === true) {
                this.host.inspector.show();
            }
        }
    };

    /**
     * Use this method to start the game. The WebStory file must have
     * been successfully loaded for this to work.
     */
    Game.prototype.start = function () {

        var fn, contextmenu_proxy, self;

        self = this;

        if (this.ws === null) {

            return setTimeout(
                function () {
                    self.start();
                }
            );
        }

        // Listener that sets the interpreter's state machine to the next state
        // if the current state is not pause or wait mode.
        // This function gets executed when a user clicks on the stage.
        fn = function () {

            if (self.interpreter.state === "pause" || self.interpreter.waitCounter > 0) {
                return;
            }

            console.log("Next triggered by user...");
            self.interpreter.next(true);
        };

        contextmenu_proxy = function (e) {

            self.bus.trigger("contextmenu", {});

            // let's try to prevent real context menu showing
            if (e && typeof e.preventDefault === "function") {
                e.preventDefault();
            }

            return false;
        };

        this.subscribeListeners = function () {

            tools.attachEventListener(this.stage, 'contextmenu', contextmenu_proxy);
            tools.attachEventListener(this.stage, 'click', fn);

            this.listenersSubscribed = true;
        };

        this.unsubscribeListeners = function () {

            tools.removeEventListener(this.stage, 'contextmenu', contextmenu_proxy);
            tools.removeEventListener(this.stage, 'click', fn);

            this.listenersSubscribed = false;
        };

        this.interpreter.start();
    };

    return Game;

});<commit_msg>Fixed a potential problem in Game.prototype.init().<commit_after>/* global MO5 */

MO5("MO5.EventBus", "MO5.ajax", "WSE.Keys", "WSE.Interpreter", "WSE.tools", "WSE").
define("WSE.Game", function (EventBus, ajax, Keys, Interpreter, tools, WSE) {

    "use strict";

    /**
     * Constructor used to create instances of games.
     *
     * You can configure the game instance using the config object
     * that can be supplied as a parameter to the constructor function.
     *
     * The options are:
     *  - url: [string] The URL of the WebStory file.
     *  - debug: [bool] Should the game be run in debug mode? (not used yet)
     *  - host: [object] The HOST object for the LocalContainer
     *      version. Optional.
     *
     * @event wse.game.constructor@WSE.bus
     * @param args A config object. See above for details.
     */
    function Game (args) {

        var host;

        WSE.trigger("wse.game.constructor", {args: args, game: this});

        args = args || {};
        this.bus = new EventBus();
        this.url = args.url || "game.xml";
        this.ws = null;
        this.debug = args.debug === true ? true : false;

        host = args.host || false;
        this.host = host;

        if (host) {

            this.ws = (function (url) {

                var xml, parser;

                parser = new DOMParser();
                xml = host.get(url);

                return parser.parseFromString(xml, "application/xml");
            }(this.url));

            this.init();
        }
        else {
            this.load(this.url);
        }

        this.interpreter = new Interpreter(this);
        this.keys = new Keys();
        this.listenersSubscribed = false;
        //console.log("this.interpreter: ", this.interpreter);

        this.bus.subscribe(
            function (data)
            {
                console.log("Message: " + data);
            },
            "wse.interpreter.message"
        );

        this.bus.subscribe(
            function (data)
            {
                console.log("Error: " + data.message);
            },
            "wse.interpreter.error"
        );

        this.bus.subscribe(
            function (data)
            {
                console.log("Warning: " + data.message, data.element);
            },
            "wse.interpreter.warning"
        );
    };

    /**
     * Loads the WebStory file using the AJAX function and triggers
     * the game initialization.
     */
    Game.prototype.load = function () {

        //console.log("Loading game file...");
        var fn, self;

        self = this;

        fn = function (obj) {
            self.ws = obj.responseXML;
            //console.log("Response XML: " + obj.responseXML);
            self.init();
        };

        ajax("GET", this.url, null, fn);
    };

    /**
     * Initializes the game instance.
     */
    Game.prototype.init = function () {

        //console.log("Initializing game...");
        var ws, stage, stageElements, stageInfo, width, height, id, self, alignFn, resizeFn;

        self = this;
        ws = this.ws;

        try {
            stageElements = ws.getElementsByTagName("stage");
        }
        catch (e) {
            console.log(e);
        }

        width = "800px";
        height = "480px";
        id = "Stage";

        if (!stageElements || stageElements.length < 1) {
            throw new Error("No stage definition found!");
        }

        stageInfo = stageElements[0];
        width = stageInfo.getAttribute("width") || width;
        height = stageInfo.getAttribute("height") || height;
        id = stageInfo.getAttribute("id") || id;

        // Create the stage element or inject into existing one?
        if (stageInfo.getAttribute("create") === "yes") {
            stage = document.createElement("div");
            stage.setAttribute("id", id);
            document.body.appendChild(stage);
        }
        else {
            stage = document.getElementById(id);
        }

        stage.setAttribute("class", "WSEStage");

        stage.style.width = width;
        stage.style.height = height;

        // Aligns the stage to be always in the center of the browser window.
        // Must be specified in the game file.
        alignFn = function () {

            var dim = tools.getWindowDimensions();

            stage.style.left = (dim.width / 2) - (parseInt(width, 10) / 2) + 'px';
            stage.style.top = (dim.height / 2) - (parseInt(height, 10) / 2) + 'px';
        };

        if (stageInfo.getAttribute("center") === "yes") {
            tools.attachEventListener(window, 'resize', alignFn);
            alignFn();
        }

        // Resizes the stage to fit the browser window dimensions. Must be
        // specified in the game file.
        resizeFn = function () {
            console.log("Resizing...");
            tools.fitToWindow(stage, parseInt(width, 10), parseInt(height, 10));
        };

        if (stageInfo.getAttribute("resize") === "yes") {
            tools.attachEventListener(window, 'resize', resizeFn);
            resizeFn();
        }

        this.stage = stage;
        //     stage.onclick = function() { self.interpreter.next(); };

        this.applySettings();

        // This section only applies when the engine is used inside
        // the local container app.
        if (this.host) {

            this.host.window.width = parseInt(width, 10);
            this.host.window.height = parseInt(height, 10);

            (function (self) {

                var doResize = self.getSetting("host.stage.resize") === "true" ? true : false;

                if (!doResize) {
                    return;
                }

                window.addEventListener("resize", function () {
                    console.log("Resizing...");
                    tools.fitToWindow(stage, parseInt(width, 10), parseInt(height, 10));
                });
            }(this));
        }
    };

    /**
     * Returns the value of a setting as specified in the WebStory file.
     * @param name [string] The name of the setting.
     * @return [mixed] The value of the setting or null.
     */
    Game.prototype.getSetting = function (name)
    {
        var ret, settings, i, len, cur, curName;

        settings = this.ws.getElementsByTagName("setting");

        for (i = 0, len = settings.length; i < len; i += 1)
        {
            cur = settings[i];
            curName = cur.getAttribute("name") || null;

            if (curName !== null && curName === name)
            {
                ret = cur.getAttribute("value") || null;
                return ret;
            }
        }

        return null;
    };

    // FIXME: implement...
    Game.prototype.applySettings = function () {

        this.webInspectorEnabled =
            this.getSetting("host.inspector.enable") === "true" ? true : false;

        if (this.host) {

            if (this.webInspectorEnabled === true) {
                this.host.inspector.show();
            }
        }
    };

    /**
     * Use this method to start the game. The WebStory file must have
     * been successfully loaded for this to work.
     */
    Game.prototype.start = function () {

        var fn, contextmenu_proxy, self;

        self = this;

        if (this.ws === null) {

            return setTimeout(
                function () {
                    self.start();
                }
            );
        }

        // Listener that sets the interpreter's state machine to the next state
        // if the current state is not pause or wait mode.
        // This function gets executed when a user clicks on the stage.
        fn = function () {

            if (self.interpreter.state === "pause" || self.interpreter.waitCounter > 0) {
                return;
            }

            console.log("Next triggered by user...");
            self.interpreter.next(true);
        };

        contextmenu_proxy = function (e) {

            self.bus.trigger("contextmenu", {});

            // let's try to prevent real context menu showing
            if (e && typeof e.preventDefault === "function") {
                e.preventDefault();
            }

            return false;
        };

        this.subscribeListeners = function () {

            tools.attachEventListener(this.stage, 'contextmenu', contextmenu_proxy);
            tools.attachEventListener(this.stage, 'click', fn);

            this.listenersSubscribed = true;
        };

        this.unsubscribeListeners = function () {

            tools.removeEventListener(this.stage, 'contextmenu', contextmenu_proxy);
            tools.removeEventListener(this.stage, 'click', fn);

            this.listenersSubscribed = false;
        };

        this.interpreter.start();
    };

    return Game;

});<|endoftext|>