<commit_before>import Party from './party.js'
import { Address, Email, PhoneNumber } from '../Children'
import { Comment, Reference } from '../../children'
import PartyLink from '../../children/Link/PartyLink'

describe('Party', () => {
  describe('serialization', () => {
    it('should serialize properly', () => {
      const test = new Party({ partyId: 'test' })
      expect(JSON.parse(JSON.stringify(test)).partyId).toBeDefined()
      expect(JSON.parse(JSON.stringify(test)).partyId).toEqual('test')
    })
  })
  describe('constructor', () => {
    it('should set url', () => {
      const party = new Party({ url: 'testURL' })
      expect(party.url).toEqual('testURL')
    })

    it('should set displayName', () => {
      const party = new Party({ displayName: 'testDisplayName' })
      expect(party.displayName).toEqual('testDisplayName')
    })

    it('should set legalName', () => {
      const party = new Party({ legalName: 'testLegalName' })
      expect(party.legalName).toEqual('testLegalName')
    })

    it('should throw if attempting to set invalid partyStatus', () => {
      let party
      function construct() {
        party = new Party({ partyStatus: 'notAType' })
      }
      expect(construct).toThrowError(
        new Error('Invalid Party Status: notAType')
      )
    })

    it('should set addresses to empty object if class is instantiated without contacts', () => {
      const testParty = new Party({})
      expect(testParty.addresses).toEqual({})
    })

    it('should set references correctly', () => {
      const party = new Party({})
      party.references = {
        INT: { referenceValue: 'Internal1', referencePrimary: true },
        EXT: new Reference({ referenceValue: 'External1' })
      }
      expect(party.references.INT).toBeDefined()
      expect(party.references.INT).toBeInstanceOf(Reference)
      expect(party.references.INT.referenceValue).toEqual('Internal1')
      expect(party.references.INT.referencePrimary).toBeTruthy()
      expect(party.references.EXT).toBeDefined()
      expect(party.references.EXT.referenceValue).toEqual('External1')
      expect(party.references.EXT.referencePrimary).toBeFalsy()
    })

    it('should throw if setting invalid number of primary references', () => {
      const params = {
        references: {
          noPrimary: { referenceValue: '1' }
        }
      }
      const willThrow = () => {
        const party = new Party(params)
      }
      expect(willThrow).toThrowError(
        'Exactly 1 primary Reference must be supplied - found: 0'
      )
    })

    it('should set comments correctly', () => {
      const party = new Party({})
      party.comments = {
        TRADER: { commentValue: 'Strategy1' },
        BACKOFFICE: new Comment({ commentValue: 'Reconciled' })
      }
      expect(party.comments.TRADER).toBeDefined()
      expect(party.comments.TRADER).toBeInstanceOf(Comment)
      expect(party.comments.TRADER.commentValue).toEqual('Strategy1')
      expect(party.comments.BACKOFFICE).toBeDefined()
      expect(party.comments.BACKOFFICE.commentValue).toEqual('Reconciled')
    })

    it('should set links correctly', () => {
      const party = new Party({})
      party.links = {
        SINGLE1: [{ linkedPartyId: 'ID-S1-1' }],
        SINGLE2: [new PartyLink({ linkedPartyId: 'ID-S2-1' })],
        MULTI1: [
          { linkedPartyId: 'ID-M1-1' },
          new PartyLink({ linkedPartyId: 'ID-M1-2' })
        ]
      }
      expect(party.links.SINGLE1[0]).toBeDefined()
      expect(party.links.SINGLE1[0].linkedPartyId).toEqual('ID-S1-1')
      expect(party.links.SINGLE2[0]).toBeDefined()
      expect(party.links.SINGLE2[0].linkedPartyId).toEqual('ID-S2-1')
      expect(party.links.MULTI1[0]).toBeDefined()
      expect(party.links.MULTI1[0].linkedPartyId).toEqual('ID-M1-1')
      expect(party.links.MULTI1[1]).toBeDefined()
      expect(party.links.MULTI1[1].linkedPartyId).toEqual('ID-M1-2')
    })
  })
  describe('addresses', () => {
    it('should set addressPrimary of existing addresses to false when supplying new primary address', () => {
      const primaryOne = new Address({ addressPrimary: true })
      const primaryTwo = new Address({ addressPrimary: true })
      const primaryThree = new Address({ addressPrimary: true })
      const testParty = new Party({
        addresses: { add1: primaryOne, add2: primaryTwo }
      })
      testParty.upsertAddress('add3', primaryThree)
      expect(testParty.addresses.add1.addressPrimary).toBeFalsy()
      expect(testParty.addresses.add2.addressPrimary).toBeFalsy()
    })
    it('should throw if attempting to add primary address without primary address', () => {
      // const primaryOne = new Address({ addressPrimary: true })
      const primaryTwo = new Address({ addressPrimary: false })
      const testParty = new Party({})
      function tester() {
        testParty.upsertAddress('new', primaryTwo)
      }
      expect(tester).toThrowError('At least 1 primary address must be supplied')
    })
    it('should add address and preserve existing ones on upsert', () => {
      const primaryOne = new Address({
        addressPrimary: true,
        lineOne: 'testRoad'
      })
      const primaryTwo = new Address({
        addressPrimary: false,
        lineOne: 'testStreet'
      })
      const testParty = new Party({ addresses: { primaryOne } })
      testParty.upsertAddress('primaryTwo', primaryTwo)
      expect(testParty.addresses).toEqual({ primaryOne, primaryTwo })
    })
  })

  describe('emails', () => {
    it('should set emails to empty object if class is instantiated without emails', () => {
      const testParty = new Party({})
      expect(testParty.emails).toEqual({})
    })
    it('should throw if Email contains invalid email', () => {
      const testParty = new Party({})
      const testEmails = new Email({ email: 'not an email' })
      function tester() {
        testParty.upsertEmail('test', testEmails)
      }
      expect(tester).toThrowError('Not a valid email')
    })
    it('should set emailPrimary of existing emails to false when supplying new primary email', () => {
      const primaryOne = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const primaryTwo = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const primaryThree = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const testParty = new Party({
        emails: { e1: primaryOne, e2: primaryTwo }
      })
      testParty.upsertEmail('e3', primaryThree)
      expect(testParty.emails.e1.emailPrimary).toBeFalsy()
      expect(testParty.emails.e2.emailPrimary).toBeFalsy()
    })
    it('should throw if attempting to add primary email without primary email', () => {
      const primaryTwo = new Email({
        emailPrimary: false,
        email: 'test@test.com'
      })
      const testParty = new Party({})
      function tester() {
        testParty.upsertEmail('new', primaryTwo)
      }
      expect(tester).toThrowError('At least 1 primary email must be supplied')
    })
    it('should add email and preserve existing ones on upsert', () => {
      const primaryOne = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const primaryTwo = new Email({
        emailPrimary: false,
        email: 'test@test.com'
      })
      const testParty = new Party({ emails: { primaryOne } })
      testParty.upsertEmail('primaryTwo', primaryTwo)
      expect(testParty.emails).toEqual({ primaryOne, primaryTwo })
    })
  })

    describe('phoneNumbers', () => {
    it('should set phoneNumbers to empty object if class is instantiated without phoneNumbers', () => {
      const testParty = new Party({})
      expect(testParty.phoneNumbers).toEqual({})
    })
    it('should throw if phone number contains invalid phone number', () => {
      const testParty = new Party({})
      const testPhoneNumbers = new PhoneNumber({
        phoneNumber: '(123)456789'
      })
      function tester() {
        testParty.upsertPhoneNumber(12345678, testPhoneNumbers)
      }
      expect(tester).toThrowError('Not a valid Phone Number')
    })
    it('should set phoneNumberPrimary of existing phoneNumbers to false when supplying new primary phoneNumber', () => {
      const primaryOne = new PhoneNumber({
        phoneNumberPrimary: true,
        phoneNumber: '(123)456789'
      })
      const primaryTwo = new PhoneNumber({
        phoneNumberPrimary: true,
        phoneNumber: '(123)456789'
      })
      const primaryThree = new PhoneNumber({
        phoneNumberPrimary: true,
        phoneNumber: '(123)456789'
      })
      const testParty = new Party({
        phoneNumbers: { e1: primaryOne, e2: primaryTwo }
      })
      testParty.upsertPhoneNumber('e3', primaryThree)
      expect(testParty.phoneNumbers.e1.phoneNumberPrimary).toBeFalsy()
      expect(testParty.phoneNumbers.e2.phoneNumberPrimary).toBeFalsy()
    })
    it('should throw if attempting to add primary phone number without primary phone number', () => {
      const primaryTwo = new PhoneNumber({
        phoneNumberPrimary: false,
        phoneNumber: '(123)456789'
      })
      const testParty = new Party({})
      function tester() {
        testParty.upsertPhoneNumber('new', primaryTwo)
      }
      expect(tester).toThrowError(
        'At least 1 primary Phone Number must be supplied'
      )
    })
    it('should add Phone number and preserve existing ones on upsert', () => {
      const primaryOne = new PhoneNumber({
        phoneNumberPrimary: true,
        phoneNumber: '(123)456789'
      })
      const primaryTwo = new PhoneNumber({
        phoneNumberPrimary: false,
        phoneNumber: '(123)456789'
      })
      const testParty = new Party({ phoneNumbers: { primaryOne } })
      testParty.upsertPhoneNumber('primaryTwo', primaryTwo)
      expect(testParty.phoneNumbers).toEqual({ primaryOne, primaryTwo })
    })
  })
})
<commit_msg>Update party.test.js<commit_after>import Party from './party.js'
import { Address, Email, PhoneNumber } from '../Children'
import { Comment, Reference } from '../../children'
import PartyLink from '../../children/Link/PartyLink'

describe('Party', () => {
  describe('serialization', () => {
    it('should serialize properly', () => {
      const test = new Party({ partyId: 'test' })
      expect(JSON.parse(JSON.stringify(test)).partyId).toBeDefined()
      expect(JSON.parse(JSON.stringify(test)).partyId).toEqual('test')
    })
  })
  describe('constructor', () => {
    it('should set url', () => {
      const party = new Party({ url: 'testURL' })
      expect(party.url).toEqual('testURL')
    })

    it('should set displayName', () => {
      const party = new Party({ displayName: 'testDisplayName' })
      expect(party.displayName).toEqual('testDisplayName')
    })

    it('should set legalName', () => {
      const party = new Party({ legalName: 'testLegalName' })
      expect(party.legalName).toEqual('testLegalName')
    })

    it('should throw if attempting to set invalid partyStatus', () => {
      let party
      function construct() {
        party = new Party({ partyStatus: 'notAType' })
      }
      expect(construct).toThrowError(
        new Error('Invalid Party Status: notAType')
      )
    })

    it('should set addresses to empty object if class is instantiated without contacts', () => {
      const testParty = new Party({})
      expect(testParty.addresses).toEqual({})
    })

    it('should set references correctly', () => {
      const party = new Party({})
      party.references = {
        INT: { referenceValue: 'Internal1', referencePrimary: true },
        EXT: new Reference({ referenceValue: 'External1' })
      }
      expect(party.references.INT).toBeDefined()
      expect(party.references.INT).toBeInstanceOf(Reference)
      expect(party.references.INT.referenceValue).toEqual('Internal1')
      expect(party.references.INT.referencePrimary).toBeTruthy()
      expect(party.references.EXT).toBeDefined()
      expect(party.references.EXT.referenceValue).toEqual('External1')
      expect(party.references.EXT.referencePrimary).toBeFalsy()
    })

    it('should throw if setting invalid number of primary references', () => {
      const params = {
        references: {
          noPrimary: { referenceValue: '1' }
        }
      }
      const willThrow = () => {
        const party = new Party(params)
      }
      expect(willThrow).toThrowError(
        'Exactly 1 primary Reference must be supplied - found: 0'
      )
    })

    it('should set comments correctly', () => {
      const party = new Party({})
      party.comments = {
        TRADER: { commentValue: 'Strategy1' },
        BACKOFFICE: new Comment({ commentValue: 'Reconciled' })
      }
      expect(party.comments.TRADER).toBeDefined()
      expect(party.comments.TRADER).toBeInstanceOf(Comment)
      expect(party.comments.TRADER.commentValue).toEqual('Strategy1')
      expect(party.comments.BACKOFFICE).toBeDefined()
      expect(party.comments.BACKOFFICE.commentValue).toEqual('Reconciled')
    })

    it('should set links correctly', () => {
      const party = new Party({})
      party.links = {
        SINGLE1: [{ linkedPartyId: 'ID-S1-1' }],
        SINGLE2: [new PartyLink({ linkedPartyId: 'ID-S2-1' })],
        MULTI1: [
          { linkedPartyId: 'ID-M1-1' },
          new PartyLink({ linkedPartyId: 'ID-M1-2' })
        ]
      }
      expect(party.links.SINGLE1[0]).toBeDefined()
      expect(party.links.SINGLE1[0].linkedPartyId).toEqual('ID-S1-1')
      expect(party.links.SINGLE2[0]).toBeDefined()
      expect(party.links.SINGLE2[0].linkedPartyId).toEqual('ID-S2-1')
      expect(party.links.MULTI1[0]).toBeDefined()
      expect(party.links.MULTI1[0].linkedPartyId).toEqual('ID-M1-1')
      expect(party.links.MULTI1[1]).toBeDefined()
      expect(party.links.MULTI1[1].linkedPartyId).toEqual('ID-M1-2')
    })
  })
  describe('addresses', () => {
    it('should set addressPrimary of existing addresses to false when supplying new primary address', () => {
      const primaryOne = new Address({ addressPrimary: true })
      const primaryTwo = new Address({ addressPrimary: true })
      const primaryThree = new Address({ addressPrimary: true })
      const testParty = new Party({
        addresses: { add1: primaryOne, add2: primaryTwo }
      })
      testParty.upsertAddress('add3', primaryThree)
      expect(testParty.addresses.add1.addressPrimary).toBeFalsy()
      expect(testParty.addresses.add2.addressPrimary).toBeFalsy()
    })
    it('should throw if attempting to add primary address without primary address', () => {
      // const primaryOne = new Address({ addressPrimary: true })
      const primaryTwo = new Address({ addressPrimary: false })
      const testParty = new Party({})
      function tester() {
        testParty.upsertAddress('new', primaryTwo)
      }
      expect(tester).toThrowError('At least 1 primary address must be supplied')
    })
    it('should add address and preserve existing ones on upsert', () => {
      const primaryOne = new Address({
        addressPrimary: true,
        lineOne: 'testRoad'
      })
      const primaryTwo = new Address({
        addressPrimary: false,
        lineOne: 'testStreet'
      })
      const testParty = new Party({ addresses: { primaryOne } })
      testParty.upsertAddress('primaryTwo', primaryTwo)
      expect(testParty.addresses).toEqual({ primaryOne, primaryTwo })
    })
  })

  describe('emails', () => {
    it('should set emails to empty object if class is instantiated without emails', () => {
      const testParty = new Party({})
      expect(testParty.emails).toEqual({})
    })
    it('should throw if Email contains invalid email', () => {
      const testParty = new Party({})
      const testEmails = new Email({ email: 'not an email' })
      function tester() {
        testParty.upsertEmail('test', testEmails)
      }
      expect(tester).toThrowError('Not a valid email')
    })
    it('should set emailPrimary of existing emails to false when supplying new primary email', () => {
      const primaryOne = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const primaryTwo = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const primaryThree = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const testParty = new Party({
        emails: { e1: primaryOne, e2: primaryTwo }
      })
      testParty.upsertEmail('e3', primaryThree)
      expect(testParty.emails.e1.emailPrimary).toBeFalsy()
      expect(testParty.emails.e2.emailPrimary).toBeFalsy()
    })
    it('should throw if attempting to add primary email without primary email', () => {
      const primaryTwo = new Email({
        emailPrimary: false,
        email: 'test@test.com'
      })
      const testParty = new Party({})
      function tester() {
        testParty.upsertEmail('new', primaryTwo)
      }
      expect(tester).toThrowError('At least 1 primary email must be supplied')
    })
    it('should add email and preserve existing ones on upsert', () => {
      const primaryOne = new Email({
        emailPrimary: true,
        email: 'test@test.com'
      })
      const primaryTwo = new Email({
        emailPrimary: false,
        email: 'test@test.com'
      })
      const testParty = new Party({ emails: { primaryOne } })
      testParty.upsertEmail('primaryTwo', primaryTwo)
      expect(testParty.emails).toEqual({ primaryOne, primaryTwo })
    })
  })

    describe('phoneNumbers', () => {
    it('should set phoneNumbers to empty object if class is instantiated without phoneNumbers', () => {
      const testParty = new Party({})
      expect(testParty.phoneNumbers).toEqual({})
    })

  })
})
<|endoftext|>


<commit_before>
define(function () {
  return function (c) {
    c.c('Tile', {

//
// Tile component
//
// Responsible for:
//  moving itself down;
//  exploding and removing itself;
//  position existing

      init: function () {
        this.addComponent('2D, Canvas');

        this.w = TILE_WIDTH;
        this.h = TILE_HEIGHT;
      },

//
// Unique ID of the component instance (entity)

      id: function () {
        return this[0];
      },

//
// Tiles can move downwards or sideways
// Presumably, this function will be called on every game loop

      moveTo: function (row, col) {
        console.log(this.id(), 'moveTo', arguments);

        this._tile.row = row;
        this._tile.col = col;

        this.z = row;
        this.attr(this.position());
      },

//
// Explode and remove the tile

      explode: function () {
        console.log(this.id(), 'explode', arguments);
        this.destroy();
      },

//
// Get pixel position based on given ROW/COL

      position: function () {
        var x = this._tile.col * TILE_INNER_WIDTH;
            y = this._tile.row * TILE_INNER_HEIGHT;

        return {
          x: x + 1,
          y: y
        };
      },

//
// Convinient function to create a new component

      create: function (tile) {
        this._tile = tile;

        this.addComponent(tile.ctype());
        this.moveTo(tile.row, tile.col);
        return this;
      }
    });
  };
});

<commit_msg>tile now works with board offset<commit_after>
define(function () {
  var TILE_OFFSET_WIDTH = ((TILE_WIDTH - TILE_INNER_WIDTH) / 2),
      TILE_OFFSET_HEIGHT = ((TILE_HEIGHT - TILE_INNER_HEIGHT) / 2);

  return function (c) {
    c.c('Tile', {

//
// Tile component
//
// Responsible for:
//  moving itself down;
//  exploding and removing itself;
//  position existing

      init: function () {
        this.addComponent('2D, Canvas');

        this.w = TILE_WIDTH;
        this.h = TILE_HEIGHT;
      },

//
// Unique ID of the component instance (entity)

      id: function () {
        return this[0];
      },

//
// Tiles can move downwards or sideways
// Presumably, this function will be called on every game loop

      moveTo: function (row, col) {
        this._tile.row = row;
        this._tile.col = col;

        this.z = row;
        this.attr(this.position());
      },

//
// Explode and remove the tile

      explode: function () {
        this.destroy();
      },

//
// Get pixel position based on given ROW/COL

      position: function () {
        var x = TILE_GAP + this._offset.x + (this._tile.col * (TILE_INNER_WIDTH + TILE_GAP)) - TILE_OFFSET_WIDTH,
            y = this._offset.y + (this._tile.row * (TILE_INNER_HEIGHT + TILE_GAP)) - TILE_OFFSET_HEIGHT;

        return {
          x: x,
          y: y
        };
      },

//
// Convinient function to create a new component
//
// @param {tile|object}   tile data model
// @param {x|number}      board offset x
// @param {y|number}      board offset y

      create: function (tile, x, y) {
        this._offset = {
          x: x,
          y: y
        };
        this._tile = tile;

        this.addComponent(tile.ctype());
        this.moveTo(tile.row, tile.col);
        return this;
      }
    });
  };
});

<|endoftext|>


<commit_before>
define(function () {
  return function (c) {
    c.c('Tile', {

//
// Tile component
//
// Responsible for:
//  moving itself down;
//  exploding and removing itself;
//  position existing

      init: function () {
        this.addComponent('2D, Canvas');

        this.z = 3;
        this.w = TILE_WIDTH;
        this.h = TILE_HEIGHT;
      },

//
// Unique ID of the component instance (entity)

      id: function () {
        return this[0];
      },

//
// Tiles can move downwards or sideways
// Presumably, this function will be called on every game loop

      moveTo: function (row, col) {
        this._tile.row = row;
        this._tile.col = col;

        this.attr(this.position());
      },

//
// Explode and remove the tile

      explode: function () {
        console.log(this.id(), 'Explode!!');
        this.destroy();
      },

//
// Get pixel position based on given ROW/COL

      position: function () {
        return {
          x: 0,
          y: 0
        };
      },

//
// Convinient function to create a new component

      create: function (tile) {
        this._tile = tile;
        this.addComponent(tile.ctype());
        this.moveTo(tile.row, tile.col);
        return this;
      }
    });
  };
});
<commit_msg>moveTo works<commit_after>
define(function () {
  return function (c) {
    c.c('Tile', {

//
// Tile component
//
// Responsible for:
//  moving itself down;
//  exploding and removing itself;
//  position existing

      init: function () {
        this.addComponent('2D, Canvas');

        this.z = 3;
        this.w = TILE_WIDTH;
        this.h = TILE_HEIGHT;
      },

//
// Unique ID of the component instance (entity)

      id: function () {
        return this[0];
      },

//
// Tiles can move downwards or sideways
// Presumably, this function will be called on every game loop

      moveTo: function (row, col) {
        console.log(this.id(), 'moveTo', arguments);

        this._tile.row = row;
        this._tile.col = col;

        this.attr(this.position());
      },

//
// Explode and remove the tile

      explode: function () {
        console.log(this.id(), 'explode', arguments);
        this.destroy();
      },

//
// Get pixel position based on given ROW/COL

      position: function () {
        var x = this._tile.col * 31,
            y = this._tile.row * 31;

        return {
          x: x,
          y: y
        };
      },

//
// Convinient function to create a new component

      create: function (tile) {
        this._tile = tile;

        this.addComponent(tile.ctype());
        this.moveTo(tile.row, tile.col);
        return this;
      }
    });
  };
});
<|endoftext|>


<commit_before>
/*
 * Copyright (c) 2008, John Mettraux, jmettraux@gmail.com
 *
 * 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.
 */

//
// Reshell
//
// Made in Japan
//

var Reshell = function (prefix) {

  this.prefix = prefix;
  //this.count = 0;
  this.env = {};

  this.stdin = document.getElementById(this.prefix+"_stdin");
  this.stdout = document.getElementById(this.prefix+"_stdin");

  this.history_offset = -1;
  this.history = [];

  this.puts = function (text, type) {

    type = type || "out";

    var tp = document.createElement('pre');

    //tp.setAttribute('id', this.prefix+"_"+type+"_"+this.count);
    tp.setAttribute('class', this.prefix+"_"+type);

    var tt = document.createTextNode(text);

    tp.appendChild(tt);

    document.getElementById(this.prefix+"_stdout").appendChild(tp);

    return tp;
  }

  this.eval = function () {

    this.history_offset = -1;

    var code = this.stdin.value;
    this.stdin.value = "";
    this.stdin.focus();

    this.puts("$ "+code, "in");

    if (code == '') return;

    var cmd = code.split(" ");
      // TODO : use regex for quote oriented splits

    var f = this.env[cmd[0]];

    if (f) {

      this.history.unshift(code);
      while(this.history.length > 63) this.history.pop;

      f(this, cmd);
    }
    else {
      this.puts("unknow command '"+cmd[0]+"'");
    }
  }

  //
  // history inc
  //
  this.hinc = function (count) {

    var code = this.history[this.history_offset + count];
    if ( ! code) return;
    this.stdin.value = code;
    this.history_offset += count;
  }

  this.onkey = function (evt) {

    var e = evt || window.event;
    var c = e.charCode || e.keyCode;

    if (c == 38) {

      this.hinc(1);
    }
    else if (c == 40) {

      this.hinc(-1);
    }
    return false;
  }

  this.focus = function () {

    this.stdin.focus();
  }

  this.clear = function () {

    while(this.stdout.removeChild(this.stdout.lastChild)) {}
      // not very snappy :(
  }

  this.def = function (name, func) {

    this.env[name] = func;
  }

  //
  // some basic commands

  this.def('clear', this.clear);

  this.def('env', function (shell, args) {

    var out = "";
    for (var key in shell.env) {
      var val = shell.env[key];
      if ((typeof val) == 'function') val = "command";
      out += (""+key+"="+val+"\n");
    }
    shell.puts(out);
  });

  this.def('echo', function (shell, args) {

    shell.puts(args.slice(1).join(" "));
  });

  this.def('history', function (shell, args) {

    shell.puts(shell.history.join("\n"));
  });

  // TODO : implement 'alias'
  // TODO : implement 'set' or 'export'

}

<commit_msg>added variable setting<commit_after>
/*
 * Copyright (c) 2008, John Mettraux, jmettraux@gmail.com
 *
 * 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.
 */

//
// Reshell
//
// Made in Japan
//

var Reshell = function (prefix) {

  this.prefix = prefix;
  //this.count = 0;
  this.env = {};

  this.stdin = document.getElementById(this.prefix+"_stdin");
  this.stdout = document.getElementById(this.prefix+"_stdin");

  this.history_offset = -1;
  this.history = [];

  this.puts = function (text, type) {

    type = type || "out";

    var tp = document.createElement('pre');

    //tp.setAttribute('id', this.prefix+"_"+type+"_"+this.count);
    tp.setAttribute('class', this.prefix+"_"+type);

    var tt = document.createTextNode(text);

    tp.appendChild(tt);

    document.getElementById(this.prefix+"_stdout").appendChild(tp);

    return tp;
  }

  this.eval = function () {

    this.history_offset = -1;

    var code = this.stdin.value;
    this.stdin.value = "";
    this.stdin.focus();

    this.puts("$ "+code, "in");

    if (code == '') return;

    var equality = code.match(/(\S*) *= *(.*)/);

    if (equality) {

      this.env[equality[1]] = equality[2];
      return;
    }

    var cmd = code.split(/ /);
      // TODO : use regex for quote oriented splits

    var f = this.env[cmd[0]];

    if (f) {

      this.history.unshift(code);
      while(this.history.length > 63) this.history.pop;

      f(this, cmd);
    }
    else {
      this.puts("unknow command '"+cmd[0]+"'");
    }
  }

  //
  // history inc
  //
  this.hinc = function (count) {

    var code = this.history[this.history_offset + count];
    if ( ! code) return;
    this.stdin.value = code;
    this.history_offset += count;
  }

  this.onkey = function (evt) {

    var e = evt || window.event;
    var c = e.charCode || e.keyCode;

    if (c == 38) {

      this.hinc(1);
    }
    else if (c == 40) {

      this.hinc(-1);
    }
    return false;
  }

  this.focus = function () {

    this.stdin.focus();
  }

  this.clear = function () {

    while(this.stdout.removeChild(this.stdout.lastChild)) {}
      // not very snappy :(
  }

  this.def = function (name, func) {

    this.env[name] = func;
  }

  //
  // some basic commands

  this.def('clear', this.clear);

  this.def('env', function (shell, args) {

    var out = "";
    for (var key in shell.env) {
      var val = shell.env[key];
      if ((typeof val) == 'function') val = "command";
      out += (""+key+"="+val+"\n");
    }
    shell.puts(out);
  });

  this.def('echo', function (shell, args) {

    shell.puts(args.slice(1).join(" "));
  });

  this.def('history', function (shell, args) {

    shell.puts(shell.history.join("\n"));
  });

  // TODO : implement 'alias'
  // TODO : implement 'set' or 'export'

}

<|endoftext|>


<commit_before>$(document).ready(function() {
  var rid = location.hash.substring(1);
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  var formToJSON = function(form){
    var json = {};
    $.each($(form).serializeArray(), function(key, elm){
      json[elm.name] = elm.value;
    });
    return json;
  };
$.getJSON("/api/db-dump", function(db_dump){
  var srcFromEnabled = function(rid) {
    var rs_info = get(db_dump.rulesets,["enabled",rid],undefined);
    if (rs_info) {
      return get(db_dump.rulesets,["krl",rs_info.hash,"src"],undefined);
    } else {
      return undefined;
    }
  }
  var srcFromVersions = function(rid,ifnone) {
    var hashobj;
    for (var vds in db_dump.rulesets.versions[rid]) {
      hashobj = db_dump.rulesets.versions[rid][vds];
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return db_dump.rulesets.krl[hash].src;
      }
    }
    return ifnone;
  }
  var hashFromVersions = function(rid,ifnone) {
    var hashobj;
    for (var vds in db_dump.rulesets.versions[rid]) {
      hashobj = db_dump.rulesets.versions[rid][vds];
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return hash;
      }
    }
    return ifnone;
  }
  var krlSrcInvite = "//click on a ruleset name to see its source here";
  var displayKrl = function() {
    $(this).parent().siblings(".krl-showing").toggleClass("krl-showing");
    if($(this).parent().hasClass("krl-showing")) {
      $(".krlsrc textarea").html(krlSrcInvite);
    } else {
      var rid = $(this).html();
      var src = srcFromEnabled(rid);
      if (src) {
        $(this).parent().removeClass("disabled");
      } else {
        $(this).parent().addClass("disabled");
        src = srcFromVersions(rid,"N/A");
      }
      if (location.hash.substring(1) === rid) {
        $(".krlsrc textarea").html(src);
      } else {
        location.hash = rid;
        location.reload();
      }
    }
    $(this).parent().toggleClass("krl-showing");
    $("pre#feedback").html("");
  }
  var renderContent =
    function(data){
      var mpl = Handlebars.compile($('#the-template').html());
      $('body').html(mpl(data));
      document.title = $('body h1').html();
      $(".krlrid span").click(displayKrl);
      $(".krlsrc input").val(rid);
      $(".lined").linedtextarea();
      if(rid){
        $(".krlrid").filter(function(){
          return $(this).find('span').text() === rid;
        }).toggleClass("krl-showing");
      }
    };
  var rs_data = {};
  rs_data.title = "Engine Rulesets";
  rs_data.descr = "These picos are hosted on this pico engine.";
  if(rid){
    rs_data.src = srcFromVersions(rid,krlSrcInvite);
  } else {
    rs_data.src = krlSrcInvite;
  }
  rs_data.rulesets = {};
  if (db_dump.rulesets && db_dump.rulesets.versions) {
    for(var aRid in db_dump.rulesets.versions) {
      rs_data.rulesets[aRid] = {};
      if (get(db_dump.rulesets,["enabled",aRid],undefined)) {
        rs_data.rulesets[aRid].enabled = true;
      }
    }
  }
  var ridRE = /^[a-zA-Z][a-zA-Z0-9_.-]*$/;
  rs_data.ridRE = ridRE.toString();
  renderContent(rs_data);
  $("form.ruleset-new").submit(function(e){
    e.preventDefault();
    var rid = this.rid.value;
    if (ridRE.test(rid)) {
      if (get(db_dump,["rulesets","versions",rid],undefined)) {
        location.hash = rid;
        location.reload();
      } else {
        $("pre#feedback").html("Registering...");
        var src = "ruleset "+rid+" {\n}";
        $.getJSON("/api/ruleset/register",{"src":src},function(result){
          location.hash = rid;
          location.reload();
        });
      }
    } else {
      alert("invalid ruleset id");
    }
  });
  $("div.krlsrc form button").click(function(){
    $(this).siblings(".clicked").toggleClass("clicked")
    $(this).toggleClass("clicked");
  });
  $("div.krlsrc").on("submit","form.ruleset-action",function(e){
    e.preventDefault();
    var $feedback = $("pre#feedback");
    $feedback.html("working...");
    var formAction = $(".clicked").attr("formaction");
    $(".clicked").toggleClass("clicked");
    var not_implemented = function(fa) {
      $feedback.html("use UI at localhost:8080/old");
      alert("not implemented: "+fa);
      $feedback.html("");
    };
    if (formAction === "/api/ruleset/enable") {
      var rsHash = hashFromVersions(this.rid.value,undefined);
      if (rsHash) {
        formAction += "/" + rsHash;
      }
    }
    if (formAction === "/api/ruleset/install") {
      formAction += "/" + this.rid.value;
    }
    $.getJSON(formAction,formToJSON(this),function(result){
      if(result.error){
        $feedback.html(result.error);
      } else if(result.code || result.ok){
        $feedback.html("ok");
        if (!formAction.startsWith("/api/ruleset/compile")) {
          location.reload();
        }
      } else {
        $feedback.html(JSON.stringify(result));
      }
    });
  });
});
});
<commit_msg>display empty Engine Rulesets page when database is empty<commit_after>$(document).ready(function() {
  var rid = location.hash.substring(1);
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  var formToJSON = function(form){
    var json = {};
    $.each($(form).serializeArray(), function(key, elm){
      json[elm.name] = elm.value;
    });
    return json;
  };
$.getJSON("/api/db-dump", function(db_dump){
  var srcFromEnabled = function(rid) {
    var rs_info = get(db_dump.rulesets,["enabled",rid],undefined);
    if (rs_info) {
      return get(db_dump.rulesets,["krl",rs_info.hash,"src"],undefined);
    } else {
      return undefined;
    }
  }
  var srcFromVersions = function(rid,ifnone) {
    var hashobj;
    if (db_dump.rulesets) {
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return db_dump.rulesets.krl[hash].src;
      }
    }
    return ifnone;
  }
  var hashFromVersions = function(rid,ifnone) {
    var hashobj;
    if (db_dump.rulesets) {
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return hash;
      }
    }
    return ifnone;
  }
  var krlSrcInvite = "//click on a ruleset name to see its source here";
  var displayKrl = function() {
    $(this).parent().siblings(".krl-showing").toggleClass("krl-showing");
    if($(this).parent().hasClass("krl-showing")) {
      $(".krlsrc textarea").html(krlSrcInvite);
    } else {
      var rid = $(this).html();
      var src = srcFromEnabled(rid);
      if (src) {
        $(this).parent().removeClass("disabled");
      } else {
        $(this).parent().addClass("disabled");
        src = srcFromVersions(rid,"N/A");
      }
      if (location.hash.substring(1) === rid) {
        $(".krlsrc textarea").html(src);
      } else {
        location.hash = rid;
        location.reload();
      }
    }
    $(this).parent().toggleClass("krl-showing");
    $("pre#feedback").html("");
  }
  var renderContent =
    function(data){
      var mpl = Handlebars.compile($('#the-template').html());
      $('body').html(mpl(data));
      document.title = $('body h1').html();
      $(".krlrid span").click(displayKrl);
      $(".krlsrc input").val(rid);
      $(".lined").linedtextarea();
      if(rid){
        $(".krlrid").filter(function(){
          return $(this).find('span').text() === rid;
        }).toggleClass("krl-showing");
      }
    };
  var rs_data = {};
  rs_data.title = "Engine Rulesets";
  rs_data.descr = "These picos are hosted on this pico engine.";
  if(rid){
    rs_data.src = srcFromVersions(rid,krlSrcInvite);
  } else {
    rs_data.src = krlSrcInvite;
  }
  rs_data.rulesets = {};
  if (db_dump.rulesets && db_dump.rulesets.versions) {
    for(var aRid in db_dump.rulesets.versions) {
      rs_data.rulesets[aRid] = {};
      if (get(db_dump.rulesets,["enabled",aRid],undefined)) {
        rs_data.rulesets[aRid].enabled = true;
      }
    }
  }
  var ridRE = /^[a-zA-Z][a-zA-Z0-9_.-]*$/;
  rs_data.ridRE = ridRE.toString();
  renderContent(rs_data);
  $("form.ruleset-new").submit(function(e){
    e.preventDefault();
    var rid = this.rid.value;
    if (ridRE.test(rid)) {
      if (get(db_dump,["rulesets","versions",rid],undefined)) {
        location.hash = rid;
        location.reload();
      } else {
        $("pre#feedback").html("Registering...");
        var src = "ruleset "+rid+" {\n}";
        $.getJSON("/api/ruleset/register",{"src":src},function(result){
          location.hash = rid;
          location.reload();
        });
      }
    } else {
      alert("invalid ruleset id");
    }
  });
  $("div.krlsrc form button").click(function(){
    $(this).siblings(".clicked").toggleClass("clicked")
    $(this).toggleClass("clicked");
  });
  $("div.krlsrc").on("submit","form.ruleset-action",function(e){
    e.preventDefault();
    var $feedback = $("pre#feedback");
    $feedback.html("working...");
    var formAction = $(".clicked").attr("formaction");
    $(".clicked").toggleClass("clicked");
    var not_implemented = function(fa) {
      $feedback.html("use UI at localhost:8080/old");
      alert("not implemented: "+fa);
      $feedback.html("");
    };
    if (formAction === "/api/ruleset/enable") {
      var rsHash = hashFromVersions(this.rid.value,undefined);
      if (rsHash) {
        formAction += "/" + rsHash;
      }
    }
    if (formAction === "/api/ruleset/install") {
      formAction += "/" + this.rid.value;
    }
    $.getJSON(formAction,formToJSON(this),function(result){
      if(result.error){
        $feedback.html(result.error);
      } else if(result.code || result.ok){
        $feedback.html("ok");
        if (!formAction.startsWith("/api/ruleset/compile")) {
          location.reload();
        }
      } else {
        $feedback.html(JSON.stringify(result));
      }
    });
  });
});
});
<|endoftext|>


<commit_before>var socket = io.connect('http://localhost:1337');
socket.on('connect', addUser);
socket.on('updatechat', processMessage);
socket.on('updateusers', updateUserList);

// Add the addUser function, which clals the emit method on the socket to call
// the adduser method on the chat server.
function addUser() {
    var userNamePromt = swal({
        title: "Please enter your username",
        type: "input",
        showCancelButton: false,
        closeOnConfirm: false,
        animation: "slide-from-top",
        inputPlaceholder: "e.g Gavin Belson or Mr.Robot"
    }, function(inputValue){
        if (inputValue === false) return false;
        if (inputValue === "") {
             swal.showInputError("Hey, we need you to enter your username!");
             return false
         }
         inputValue = inputValue.replace(/<(?:.|\n)*?>/gm, '');
         swal("Nice!", "Your username is " + inputValue, "success");
         socket.emit('adduser', inputValue);
     });

    // Checks if the user is connected
    var userConnected;

    if(socket.socket.connected) {
        userConnected = true;
    } else {
        userConnected = false;
    }

}

// Get the current timestamp to display in the chat next to the message.
function getCurrentTime() {
    var datetime = new Date();
    var hours = datetime.getHours();
    var minutes = datetime.getMinutes();
    var seconds = datetime.getSeconds();

    if (hours < 10) hours = '0' + hours;
    if (minutes < 10) minutes = '0' + minutes;
    if (seconds < 10) seconds = '0' + seconds;

    return hours + ':' + minutes + ':' + seconds;
}

// processMessage function is called when the chat service sends a message.
// jQuery object with the response and insert message after converstaion.
function processMessage(username, data) {
    $('' + '[' + getCurrentTime() + '] ' + '' + username + ': ' + data + '
').insertAfter($('#conversation'));
}

// updateUserList function is called when server sends an updated user list.
function updateUserList(data) {
    $('#users').empty();
    $.each(data, function(key, value) {
        $('#users').append('
 ' + key + '
');
    });
}

var TopBarBox = React.createClass({
  render: function() {
    return (

Chat Server

Menu

 GitHub

 Download

 Twitter

    );
  }
});

var ChatNoticeBox = React.createClass({
    render: function() {
        return (

Bonsua! Chat Server is built with React, Node.js, Express.js and Socket.io

        )
    }
});

var MessageBox = React.createClass({
    getInitialState: function() {
        return {
            message: ''
        };
    },
    handleMessageChange: function(e) {
        this.setState({message: e.target.value});
    },
    handleClick: function() {
        var message = this.state.message;
        var data = document.getElementById('data');
        message = message.replace(/<(?:.|\n)*?>/gm, '');
        if(!message) {
            sweetAlert("Oops...", "You've didn\'t entered a message!", "error");
        } else {
            socket.emit('sendchat', message);
        }
        this.state.message = this.setState({message: ''});
        data.value = '';
        data.focus();
    },
    handleKeyPress: function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            $(this).blur();
            $('#datasend').focus().click();
        }
    },
    render: function() {
        return (

                <input id="data" placeholder="Message.." onChange={this.handleMessageChange} onKeyUp={this.handleKeyPress} />
                <input id="datasend" className="button send-msg" type="button" onClick={this.handleClick} value="Send message" />

        )
    },
});

var UserListBox = React.createClass({
    render: function() {
        return (

Users

        )
    }
});

ReactDOM.render(<TopBarBox />, document.getElementById('nav-wrap'));
ReactDOM.render(<ChatNoticeBox />, document.getElementById('chat-notice'));
ReactDOM.render(<MessageBox />, document.getElementById('message-wrap'));
ReactDOM.render(<UserListBox />, document.getElementById('users-wrap'));
<commit_msg>Http is replaced with https<commit_after>var socket = io.connect('https://localhost:1337');
socket.on('connect', addUser);
socket.on('updatechat', processMessage);
socket.on('updateusers', updateUserList);

// Add the addUser function, which clals the emit method on the socket to call
// the adduser method on the chat server.
function addUser() {
    var userNamePromt = swal({
        title: "Please enter your username",
        type: "input",
        showCancelButton: false,
        closeOnConfirm: false,
        animation: "slide-from-top",
        inputPlaceholder: "e.g Gavin Belson or Mr.Robot"
    }, function(inputValue){
        if (inputValue === false) return false;
        if (inputValue === "") {
             swal.showInputError("Hey, we need you to enter your username!");
             return false
         }
         inputValue = inputValue.replace(/<(?:.|\n)*?>/gm, '');
         swal("Nice!", "Your username is " + inputValue, "success");
         socket.emit('adduser', inputValue);
     });

    // Checks if the user is connected
    var userConnected;

    if(socket.socket.connected) {
        userConnected = true;
    } else {
        userConnected = false;
    }

}

// Get the current timestamp to display in the chat next to the message.
function getCurrentTime() {
    var datetime = new Date();
    var hours = datetime.getHours();
    var minutes = datetime.getMinutes();
    var seconds = datetime.getSeconds();

    if (hours < 10) hours = '0' + hours;
    if (minutes < 10) minutes = '0' + minutes;
    if (seconds < 10) seconds = '0' + seconds;

    return hours + ':' + minutes + ':' + seconds;
}

// processMessage function is called when the chat service sends a message.
// jQuery object with the response and insert message after converstaion.
function processMessage(username, data) {
    $('' + '[' + getCurrentTime() + '] ' + '' + username + ': ' + data + '
').insertAfter($('#conversation'));
}

// updateUserList function is called when server sends an updated user list.
function updateUserList(data) {
    $('#users').empty();
    $.each(data, function(key, value) {
        $('#users').append('
 ' + key + '
');
    });
}

var TopBarBox = React.createClass({
  render: function() {
    return (

Chat Server

Menu

 GitHub

 Download

 Twitter

    );
  }
});

var ChatNoticeBox = React.createClass({
    render: function() {
        return (

Bonsua! Chat Server is built with React, Node.js, Express.js and Socket.io

        )
    }
});

var MessageBox = React.createClass({
    getInitialState: function() {
        return {
            message: ''
        };
    },
    handleMessageChange: function(e) {
        this.setState({message: e.target.value});
    },
    handleClick: function() {
        var message = this.state.message;
        var data = document.getElementById('data');
        message = message.replace(/<(?:.|\n)*?>/gm, '');
        if(!message) {
            sweetAlert("Oops...", "You've didn\'t entered a message!", "error");
        } else {
            socket.emit('sendchat', message);
        }
        this.state.message = this.setState({message: ''});
        data.value = '';
        data.focus();
    },
    handleKeyPress: function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            $(this).blur();
            $('#datasend').focus().click();
        }
    },
    render: function() {
        return (

                <input id="data" placeholder="Message.." onChange={this.handleMessageChange} onKeyUp={this.handleKeyPress} />
                <input id="datasend" className="button send-msg" type="button" onClick={this.handleClick} value="Send message" />

        )
    },
});

var UserListBox = React.createClass({
    render: function() {
        return (

Users

        )
    }
});

ReactDOM.render(<TopBarBox />, document.getElementById('nav-wrap'));
ReactDOM.render(<ChatNoticeBox />, document.getElementById('chat-notice'));
ReactDOM.render(<MessageBox />, document.getElementById('message-wrap'));
ReactDOM.render(<UserListBox />, document.getElementById('users-wrap'));
<|endoftext|>


<commit_before>define([
  'pex/materials/Material',
  'pex/gl/Context',
  'pex/gl/Program',
  'pex/geom/Vec4',
  'pex/utils/ObjectUtils',
  'lib/text!pex/materials/SolidColor.glsl'
  ], function(Material, Context, Program, Vec4, ObjectUtils, SolidColorGLSL) {

  function SolidColor(uniforms) {
    this.gl = Context.currentContext.gl;
    var program = new Program(SolidColorGLSL);

    var defaults = {
     color : Vec4.fromValues(1, 1, 1, 1),
     pointSize : 1
    };

    var uniforms = ObjectUtils.mergeObjects(defaults, uniforms);

    Material.call(this, program, uniforms);
  }

  SolidColor.prototype = Object.create(Material.prototype);

  return SolidColor;
});<commit_msg>Updated SolidColor material to use Color<commit_after>define([
  'pex/materials/Material',
  'pex/gl/Context',
  'pex/gl/Program',
  'pex/color/Color',
  'pex/utils/ObjectUtils',
  'lib/text!pex/materials/SolidColor.glsl'
  ], function(Material, Context, Program, Color, ObjectUtils, SolidColorGLSL) {

  function SolidColor(uniforms) {
    this.gl = Context.currentContext.gl;
    var program = new Program(SolidColorGLSL);

    var defaults = {
     color : Color.create(1, 1, 1, 1),
     pointSize : 1
    };

    var uniforms = ObjectUtils.mergeObjects(defaults, uniforms);

    Material.call(this, program, uniforms);
  }

  SolidColor.prototype = Object.create(Material.prototype);

  return SolidColor;
});<|endoftext|>


<commit_before>var support_email = "support@yourdomain.com";
var endpoint = "/feedback";

$(function() {

	var container = $("

feedback

").appendTo("body");

	container.click(function() {
		var overlay = $("

").appendTo("body");
		overlay.css("width", $(window).width() + "px").css("height", $(window).height() + "px");
		var dialog = $("

").appendTo("body");
		dialog.css("top", $(window).height() / 2 - 200 + "px").css("left", $(window).width() / 2 - 200 + "px");

		dialog.append("
Leave Feedback
");
		dialog.append("
Please leave us feedback using the form below. Your feedback will be sent directly to our development team.
");
		dialog.append("Type of feedback<select id='waterslide_type' name='type'><option value='bug'>Bug</option></select>");
		dialog.append("Please provide a title for the feedback<input type='text' id='waterslide_short' name='short' />");
		dialog.append("Please provide a detailed description of the idea or problem<textarea id='waterslide_long' name='long'></textarea>");
		dialog.append("<button id='waterslide_send'>Send Feedback</button>");
	});

	$("#waterslide_send").live("click", function() {
		$("#waterslide_send").addClass("disabled").text("Sending...");
		$.post(endpoint, {
			type: $("#waterslide_type").val(),
			short: $("#waterslide_short").val(),
			long: $("#waterslide_long").val()
		}, function(data) {
			if(data == "success") {
				$("#waterslide_dialog").html("
Leave Feedback

Thanks! Your feedback was sent successfully! We'll review it and take your suggestions into consideration. Please note that we do not respond \
				individiually to all requests received via the feedback form. If you need immediate support, please email us at " + support_email + "
");
			}

			else {
				$("#waterslide_dialog").html("
Leave Feedback

Oh no! Something went wrong! Please get in touch with us at " + support_email + " instead. Sorry for the inconvenience!
");
			}
		});

	});

});<commit_msg>Receiving validation errors<commit_after>var support_email = "support@yourdomain.com";
var endpoint = "/feedback";

$(function() {

	var container = $("

feedback

").appendTo("body");

	container.click(function() {
		var overlay = $("

").appendTo("body");
		overlay.css("width", $(window).width() + "px").css("height", $(window).height() + "px");
		var dialog = $("

").appendTo("body");
		dialog.css("top", $(window).height() / 2 - 200 + "px").css("left", $(window).width() / 2 - 200 + "px");

		dialog.append("
Leave Feedback
");
		dialog.append("
Please leave us feedback using the form below. Your feedback will be sent directly to our development team.
");
		dialog.append("Type of feedback<select id='waterslide_type' name='type'><option value='bug'>Bug</option></select>");
		dialog.append("Please provide a title for the feedback<input type='text' id='waterslide_short' name='short' />");
		dialog.append("Please provide a detailed description of the idea or problem<textarea id='waterslide_long' name='long'></textarea>");
		dialog.append("<button id='waterslide_send'>Send Feedback</button>");
	});

	$("#waterslide_send").live("click", function() {
		$("#waterslide_send").addClass("disabled").text("Sending...");
		$.post(endpoint, {
			type: $("#waterslide_type").val(),
			short: $("#waterslide_short").val(),
			long: $("#waterslide_long").val()
		}, function(data) {
			if(data == "success") {
				$("#waterslide_dialog").html("
Leave Feedback

Thanks! Your feedback was sent successfully! We'll review it and take your suggestions into consideration.

Please note that we do not respond \
				individiually to all requests received via the feedback form. If you need immediate support, please email us at " + support_email + "
");
			}

			else {
				$("#waterslide_dialog").html("
Leave Feedback

Oh no! Something went wrong! Please get in touch with us at " + support_email + " instead. Sorry for the inconvenience!
");
			}
		});

	});

});<|endoftext|>


<commit_before>/*    Copyright 2020 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 /*
  * Box (collect the following info)
  *   box states: just rebooted, this process crashed and connect, reconnected the socket io, scheduled update
  *   memory size
  *   mac addresses of ethX
  *   speed of each ethX
  *   Bluetooth mac address
  *   uptime
  *   uname -m
  *   box eid (if have)
  *   box license (8 char prefix only)
  *   gateway mac address (the first three bytes)
  *   cpu temp
  *   current timestamp
  *   hash of firerouter (if applicable)
  *   hash of firewalla
  */

'use strict';

const exec = require('child-process-promise').exec;
const fs = require('fs');
const io2 = require('socket.io-client');
const os = require('os');
const socket = io2(
  "https://api.firewalla.com",
  { path: "/socket",
    transports: ['websocket'],
    'upgrade': false }
);
const Promise = require('bluebird');
Promise.promisifyAll(fs);

const launchTime = Math.floor(new Date() / 1000);

let uid = null;

function getUniqueID(info) {
  const randomNumber = Math.floor(Math.random(1000000));
  if(info.mac) {
    return `${info.mac.toUpperCase()}-${launchTime}-${randomNumber}`;
  } else {
    return `INVALID_MAC-${launchTime}-${randomNumber}`;
  }
}

function log(message) {
  console.log(new Date(), message);
}

async function getShellOutput(cmd) {
  try {
    const result = await exec(cmd, { encoding: 'utf8' });
    return result && result.stdout && result.stdout.replace(/\n$/,'');
  } catch(err) {
    log("ERROR: "+err);
    return "";
  }
}

async function isBooted() {
  const fwHeartbeatFile = '/dev/shm/fw_heartbeat';
  try{
    await fs.accessAsync(fwHeartbeatFile, fs.constants.F_OK);
    return false;
  } catch (err) {
    log("System was booted.");
    await exec(`touch ${fwHeartbeatFile}`);
    return true;
  }
}

async function getCpuTemperature() {
  return await getShellOutput("cat /sys/class/thermal/thermal_zone0/temp");
}

function getEthernets() {
    const ifs = os.networkInterfaces();
    const eths = {};
    const ethsNames = Object.keys(ifs).filter(name => name.match(/^eth/));
    ethsNames.forEach(e => eths[e]=ifs[e]);
    return eths;
}

async function getEthernetSpeed(ethsNames) {
    const ethSpeed = {};
    for (const eth of ethsNames) {
      ethSpeed[eth] = await getShellOutput(`sudo ethtool ${eth} | awk '/Speed:/ {print $2}'`);
    }
    return ethSpeed;
}

async function getGatewayMac() {
  const gwIP = await getShellOutput("route -n | awk '$1 == \"0.0.0.0\" {print $2}'");
  if ( gwIP ) {
    const gwMac = await getShellOutput(`arp -a -n | grep ${gwIP} -w | awk '{print $4}'`);
    return gwMac;
  } else {
    return '';
  }
}

async function getLatestCommitHash(cwd) {
  try {
    const result = await exec("git rev-parse HEAD", { cwd: cwd, encoding: 'utf8' });
    return result && result.stdout && result.stdout.trim();
  } catch(err) {
    //log(`ERROR: failed to get latest commit hash in ${cwd}`+err);
    return '';
  }
}

async function getLicenseInfo() {
  const licenseFile = "/home/pi/.firewalla/license";
  const SUUID = (await getShellOutput(`awk '/SUUID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  const EID = (await getShellOutput(`awk '/EID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  return { SUUID,EID };
}

async function getSysinfo(status) {
  const eths = getEthernets();
  const memory = os.totalmem()
  const timestamp = Date.now();
  const uptime = os.uptime();
  const [arch, booted, btMac, cpuTemp, ethSpeed, gatewayMac, hashRouter, hashWalla, licenseInfo, mac] =
    await Promise.all([
      getShellOutput("uname -m"),
      isBooted(),
      getShellOutput("hcitool dev | awk '/hci0/ {print $2}'"),
      getCpuTemperature(),
      getEthernetSpeed(Object.keys(eths)),
      getGatewayMac(),
      getLatestCommitHash("/home/pi/firerouter"),
      getLatestCommitHash("/home/pi/firewalla"),
      getLicenseInfo(),
      getShellOutput("cat /sys/class/net/eth0/address")
    ]);
  return {
    arch,
    booted,
    btMac,
    cpuTemp,
    eths,
    ethSpeed,
    licenseInfo,
    gatewayMac,
    hashRouter,
    hashWalla,
    mac,
    memory,
    status,
    timestamp,
    uptime
  };
}

function update(status) {
  const info = await getSysinfo(status);
  if(uid) {
    info.id = uid;
  }
  //log(`DEBUG: ${JSON.stringify(info,null,2)}`);
  socket.emit('update', info);
  return info;
}

const job = setTimeout(() => {
  update("schedule");
}, 30 * 3600 * 1000);

socket.on('connect', async () => {
  log("Connected to heartbeat server.");
  uid = getUniqueID(info);
  update('connect');
});

socket.on('disconnect', () => {
  log("Disconnected from heartbeat server.");
});

socket.on('update', () => {
  update("cloud");
});

socket.on('reconnect', () => {
  log("Reconnected to heartbeat server.");
  update('reconnect');
});
<commit_msg>bug fix<commit_after>/*    Copyright 2020 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 /*
  * Box (collect the following info)
  *   box states: just rebooted, this process crashed and connect, reconnected the socket io, scheduled update
  *   memory size
  *   mac addresses of ethX
  *   speed of each ethX
  *   Bluetooth mac address
  *   uptime
  *   uname -m
  *   box eid (if have)
  *   box license (8 char prefix only)
  *   gateway mac address (the first three bytes)
  *   cpu temp
  *   current timestamp
  *   hash of firerouter (if applicable)
  *   hash of firewalla
  */

'use strict';

const exec = require('child-process-promise').exec;
const fs = require('fs');
const io2 = require('socket.io-client');
const os = require('os');
const socket = io2(
  "https://api.firewalla.com",
  { path: "/socket",
    transports: ['websocket'],
    'upgrade': false }
);
const Promise = require('bluebird');
Promise.promisifyAll(fs);

const launchTime = Math.floor(new Date() / 1000);

let uid = null;

function getUniqueID(info) {
  const randomNumber = Math.floor(Math.random(1000000));
  if(info.mac) {
    return `${info.mac.toUpperCase()}-${launchTime}-${randomNumber}`;
  } else {
    return `INVALID_MAC-${launchTime}-${randomNumber}`;
  }
}

function log(message) {
  console.log(new Date(), message);
}

async function getShellOutput(cmd) {
  try {
    const result = await exec(cmd, { encoding: 'utf8' });
    return result && result.stdout && result.stdout.replace(/\n$/,'');
  } catch(err) {
    log("ERROR: "+err);
    return "";
  }
}

async function isBooted() {
  const fwHeartbeatFile = '/dev/shm/fw_heartbeat';
  try{
    await fs.accessAsync(fwHeartbeatFile, fs.constants.F_OK);
    return false;
  } catch (err) {
    log("System was booted.");
    await exec(`touch ${fwHeartbeatFile}`);
    return true;
  }
}

async function getCpuTemperature() {
  return await getShellOutput("cat /sys/class/thermal/thermal_zone0/temp");
}

function getEthernets() {
    const ifs = os.networkInterfaces();
    const eths = {};
    const ethsNames = Object.keys(ifs).filter(name => name.match(/^eth/));
    ethsNames.forEach(e => eths[e]=ifs[e]);
    return eths;
}

async function getEthernetSpeed(ethsNames) {
    const ethSpeed = {};
    for (const eth of ethsNames) {
      ethSpeed[eth] = await getShellOutput(`sudo ethtool ${eth} | awk '/Speed:/ {print $2}'`);
    }
    return ethSpeed;
}

async function getGatewayMac() {
  const gwIP = await getShellOutput("route -n | awk '$1 == \"0.0.0.0\" {print $2}'");
  if ( gwIP ) {
    const gwMac = await getShellOutput(`arp -a -n | grep ${gwIP} -w | awk '{print $4}'`);
    return gwMac;
  } else {
    return '';
  }
}

async function getLatestCommitHash(cwd) {
  try {
    const result = await exec("git rev-parse HEAD", { cwd: cwd, encoding: 'utf8' });
    return result && result.stdout && result.stdout.trim();
  } catch(err) {
    //log(`ERROR: failed to get latest commit hash in ${cwd}`+err);
    return '';
  }
}

async function getLicenseInfo() {
  const licenseFile = "/home/pi/.firewalla/license";
  const SUUID = (await getShellOutput(`awk '/SUUID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  const EID = (await getShellOutput(`awk '/EID/ {print $NF}' ${licenseFile}`)).replace(/[",]/g,'');
  return { SUUID,EID };
}

async function getSysinfo(status) {
  const eths = getEthernets();
  const memory = os.totalmem()
  const timestamp = Date.now();
  const uptime = os.uptime();
  const [arch, booted, btMac, cpuTemp, ethSpeed, gatewayMac, hashRouter, hashWalla, licenseInfo, mac] =
    await Promise.all([
      getShellOutput("uname -m"),
      isBooted(),
      getShellOutput("hcitool dev | awk '/hci0/ {print $2}'"),
      getCpuTemperature(),
      getEthernetSpeed(Object.keys(eths)),
      getGatewayMac(),
      getLatestCommitHash("/home/pi/firerouter"),
      getLatestCommitHash("/home/pi/firewalla"),
      getLicenseInfo(),
      getShellOutput("cat /sys/class/net/eth0/address")
    ]);
  return {
    arch,
    booted,
    btMac,
    cpuTemp,
    eths,
    ethSpeed,
    licenseInfo,
    gatewayMac,
    hashRouter,
    hashWalla,
    mac,
    memory,
    status,
    timestamp,
    uptime
  };
}

async function update(status) {
  const info = await getSysinfo(status);
  if(uid) {
    info.id = uid;
  }
  //log(`DEBUG: ${JSON.stringify(info,null,2)}`);
  socket.emit('update', info);
  return info;
}

const job = setTimeout(() => {
  update("schedule");
}, 30 * 3600 * 1000);

socket.on('connect', async () => {
  log("Connected to heartbeat server.");
  uid = getUniqueID(info);
  update('connect');
});

socket.on('disconnect', () => {
  log("Disconnected from heartbeat server.");
});

socket.on('update', () => {
  update("cloud");
});

socket.on('reconnect', () => {
  log("Reconnected to heartbeat server.");
  update('reconnect');
});
<|endoftext|>


<commit_before>/*    Copyright 2020 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 /*
  * Box (collect the following info)
  *   box states: just rebooted, this process crashed and connect, reconnected the socket io, scheduled update
  *   memory size
  *   mac addresses of ethX
  *   speed of each ethX
  *   Bluetooth mac address
  *   uptime
  *   uname -m
  *   box eid (if have)
  *   box license (8 char prefix only)
  *   gateway mac address (the first three bytes)
  *   cpu temp
  *   current timestamp
  *   hash of firerouter (if applicable)
  *   hash of firewalla
  */

'use strict';

const io2 = require('socket.io-client');
const url = "https://api.firewalla.com";
const path = "/socket";

const fs = require('fs');
const cp = require('child_process');
const mac = getShellOutput("cat /sys/class/net/eth0/address").toUpperCase();
const memory = getShellOutput("free -h | awk '/Mem:/ {print $2}'");

function getShellOutput(cmd) {
  try {
    const result = cp.execSync(cmd, { encoding: 'utf8' });
    return result && result.trim();
  } catch(err) {
    return "";
  }
}

const socket = io2(url, { path: path, transports: ['websocket'], 'upgrade': false });

function log(message) {
  console.log(new Date(), message);
}

function isBooted() {
  const fwHeartbeatFile = '/dev/shm/fw_heartbeat';
  try{
    if (fs.existsSync(fwHeartbeatFile)) {
      return false;
    } else {
      log("System was booted.");
      cp.execSync(`touch ${fwHeartbeatFile}`)
      return true;
    }
  } catch (err) {
    return false;
  }
}

function getEthernets() {
    const ifs = require('os').networkInterfaces()
    const eths = {}
    const ethsNames = Object.keys(ifs).filter(name => name.match(/^eth/));
    ethsNames.forEach(e => eths[e]=ifs[e])
    return eths
}

function getEthernetSpeed(ethsNames) {
    const ethspeed = {}
    ethsNames.forEach( eth => {
      ethspeed[eth] = getShellOutput(`sudo ethtool ${eth} | awk '/Speed:/ {print $2}'`);
    })
    return ethspeed
}

function getSysinfo(status) {
  const booted = isBooted();
  const uptime = require('os').uptime()
  const eths = getEthernets();
  const ethspeed = getEthernetSpeed(Object.keys(eths));
  return {booted, eths, ethspeed, mac, memory, status, uptime};
}

function update(status) {
  const info = getSysinfo(status);
  log(`DEBUG: ${JSON.stringify(info,null,2)}`);
  socket.emit('update', info);
}

const job = setTimeout(() => {
  update("schedule");
}, 30 * 3600 * 1000);

socket.on('connect', () => {
  log("Connected to heartbeat server.");
  update('connect');
});

socket.on('disconnect', () => {
  log("Disconnected from heartbeat server.");
});

socket.on("update", (data) => {
  update("cloud");
});

socket.on('reconnect', () => {
  log("Reconnected to heartbeat server.");
  update('reconnect');
});<commit_msg>add model<commit_after>/*    Copyright 2020 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 /*
  * Box (collect the following info)
  *   box states: just rebooted, this process crashed and connect, reconnected the socket io, scheduled update
  *   memory size
  *   mac addresses of ethX
  *   speed of each ethX
  *   Bluetooth mac address
  *   uptime
  *   uname -m
  *   box eid (if have)
  *   box license (8 char prefix only)
  *   gateway mac address (the first three bytes)
  *   cpu temp
  *   current timestamp
  *   hash of firerouter (if applicable)
  *   hash of firewalla
  */

'use strict';

const cp = require('child_process');
const fs = require('fs');
const io2 = require('socket.io-client');
const os = require('os');
const socket = io2(
  "https://api.firewalla.com",
  { path: "/socket",
    transports: ['websocket'],
    'upgrade': false }
);

// private modules
const platformLoader = require('../platform/PlatformLoader.js');

// persistent system info
const arch = os.arch();
const btmac = getShellOutput("hcitool dev  | awk '/hci0/ {print $2}'");
const mac = getShellOutput("cat /sys/class/net/eth0/address").toUpperCase();
const memory = os.totalmem()
const platform = platformLoader.getPlatform();
const model = platform.getName();

function log(message) {
  console.log(new Date(), message);
}

function getShellOutput(cmd) {
  try {
    const result = cp.execSync(cmd, { encoding: 'utf8' });
    return result && result.trim();
  } catch(err) {
    return "";
  }
}

function isBooted() {
  const fwHeartbeatFile = '/dev/shm/fw_heartbeat';
  try{
    if (fs.existsSync(fwHeartbeatFile)) {
      return false;
    } else {
      log("System was booted.");
      cp.execSync(`touch ${fwHeartbeatFile}`)
      return true;
    }
  } catch (err) {
    return false;
  }
}

function getEthernets() {
    const ifs = os.networkInterfaces()
    const eths = {}
    const ethsNames = Object.keys(ifs).filter(name => name.match(/^eth/));
    ethsNames.forEach(e => eths[e]=ifs[e])
    return eths
}

function getEthernetSpeed(ethsNames) {
    const ethspeed = {}
    ethsNames.forEach( eth => {
      ethspeed[eth] = getShellOutput(`sudo ethtool ${eth} | awk '/Speed:/ {print $2}'`);
    })
    return ethspeed
}

function getSysinfo(status) {
  const booted = isBooted();
  const eths = getEthernets();
  const ethspeed = getEthernetSpeed(Object.keys(eths));
  const uptime = os.uptime()
  return {arch, booted, btmac, eths, ethspeed, mac, memory, model, status, uptime};
}

function update(status) {
  const info = getSysinfo(status);
  log(`DEBUG: ${JSON.stringify(info,null,2)}`);
  socket.emit('update', info);
}

const job = setTimeout(() => {
  update("schedule");
}, 30 * 3600 * 1000);

socket.on('connect', () => {
  log("Connected to heartbeat server.");
  update('connect');
});

socket.on('disconnect', () => {
  log("Disconnected from heartbeat server.");
});

socket.on("update", (data) => {
  update("cloud");
});

socket.on('reconnect', () => {
  log("Reconnected to heartbeat server.");
  update('reconnect');
});<|endoftext|>


<commit_before>/*
posh 0.1
by http://vvvv.org
*/

var ws;
var sessionID = "session";
var ups;

window.onload = function()
{
	hideConfig();

	// connect to WAMP server
	ab.connect("ws://LOCALIP:WEBSOCKETPORT",
	// WAMP session was established
	function (session)
	{
		ws = session;
		sessionID = session.sessionid();
		$('#sessionID').text('Session ID: ' + sessionID);

		ws.subscribe("add", onAdd);
		ws.subscribe("update", onUpdate);
		ws.subscribe("remove", onRemove);
		ws.call("dump").then(dumpResult);

		//load configs now that session is established
		var val = getCookie('ups');
		if (!val)
			val = parseInt($('#ups').val());
		setUpdatesPerSecond(val);
		ups = 1000 / val;

		var name = getCookie('sessionName');
		if (name)
			sendSessionName(name);
		else
			name = sessionID;
		setSessionName(name);

		$('#config').css('color', 'black');
	},

	// WAMP session is gone
	function (code, reason)
	{
		// things to do once the session fails
		log(reason);
		ws = null;

		$('#config').css('color', 'red');
	});
}

var editorTargetCall, overTargetCall;
$(document).ready(function()
{
	$(document).on("contextmenu", function(e){
		  return false;
	});

	//todo: svgterminal needs api to register shortcuts for which the default should be prevented
	//if simply preventing for all we cut ourselves out of default browser shortcuts

	$(document).on('keydown', function(e)
	{
		//e.originalEvent.preventDefault();
		ws.call('keydown', e.ctrlKey, e.shiftKey, e.altKey, e.which);
	});

	$(document).on('keyup', function(e)
	{
		//e.originalEvent.preventDefault();
		ws.call('keyup', e.ctrlKey, e.shiftKey, e.altKey, e.which);
	});

	//vvvv hosted IE does not send keydown/up, only keypress?
	$(document).on('keypress', function(e)
	{
		//e.originalEvent.preventDefault();
		ws.call('keypress', e.ctrlKey, e.shiftKey, e.altKey, String.fromCharCode(e.which));

		//don't scroll the page down on space
		if (e.keyCode == 32)
			e.originalEvent.preventDefault();
	});

	$('#svg').on('mousewheel', function(e)
	{
		if (overTargetCall)
		{
			ws.call(overTargetCall, e.originalEvent.wheelDelta / 120 + 100, sessionID);
			//prevent page fom scrolling
			return false;
		}

		return true;
	});

	$('#svg').on('mousedown', function(e)
	{
		hideConfig();
		$('#editor').blur();
	});

	$('#editor').on('keyup', function(e)
	{
		if (editorTargetCall)
		{
			if (e.keyCode == 13)
			{
				//execute
				$('#editor').blur();
			}
			else if (e.keyCode == 27)
			{
				//just hide the editor
				$('#editor').hide();
			}

			//get cursor position
			var c = $('#editor').caret();
			//adapt width of editor
			$('#editor').width($('#editor').textWidth() + 20);
			//set cursor back in place
			$('#editor').caret(c);
		}
	});

	$('#editor').blur(function(e)
	{
		//if value now different than before call(newvalue)
		var $ed = $('#editor');
		if ($ed.data('before') !== $ed.html())
		{
			ws.call(editorTargetCall, $ed.text().trim(), sessionID);
			editorTargetCall = null;
		}
		log('blurred');
		//hide editor
		$ed.hide();
		//re-show original text
		$ed.data('target').show();
	});

	$('#ups').bind('change', function(e) {
		e.preventDefault();
		var val = $(this).val();
		$('#upsdisp').text('Max updates/second: ' + val);
		setCookie('ups', val);

		ups = 1000 / val;
	});

	//ie hack
	if (navigator.userAgent.match('Trident') )
	{
		$('<link rel="stylesheet" type="text/css" href="ie.css" />').appendTo("head");
	}
});

function showConfig()
{
	$('#config').css('transform', 'translateY(0px)');
}

function hideConfig()
{
	var off = - $('#config').height() + 12;
	$('#config').css('transform', 'translateY(' + off + 'px)');
}

function setSessionName(name)
{
	$('#sessionName').val(name);
}

function setUpdatesPerSecond(ups)
{
	$('#ups').val(ups);
	$('#upsdisp').text('Max updates/second: ' + ups);
}

function setLastChangeName(name)
{
	$('#lastChange').text('Last Change: ' + name);
}

function sessionNameKeyUp(e)
{
	if (e.keyCode == 13)
	{
		var name = $('#sessionName').val().trim();
		sendSessionName(name);
		setCookie('sessionName', name, 10);
	}
}

function sendSessionName(name)
{
	ws.call('setSessionName', sessionID, name).then(setSessionName);
}

function dumpResult(data)
{
	//log(data);
	//remove doctype
	data = removeFirstLine(data);

	//$('#svg').empty();
	var svg = document.getElementById('svg');
	while (svg.lastChild)
	{
		svg.removeChild(svg.lastChild);
	}
	svg.appendChild(parseSVG(data));

	updateEvents(document);

	//reset the lookup after every dump
	//specifically necessary for startup
	$elementLookup = {};
}

function updateEvents(doc)
{
	var now, last, diff;
	//replace events
	$('[onclick]', doc).each(function()
	{
		var call = $(this).attr('onclick');
		$(this).on('click', function(e)
		{
			ws.call(call, mouseX(e), mouseY(e), e.which, 1, sessionID);
		});

		$(this).on('dblclick', function(e)
		{
			ws.call(call, mouseX(e), mouseY(e), e.which, 2, sessionID);
			log('dbl');
		});
		$(this).removeAttr('onclick');
	});

	$('[onmousedown]', doc).each(function()
	{
		var call = $(this).attr('onmousedown');
		$(this).on('mousedown', function(e)
		{
			e.originalEvent.preventDefault();
			mouseDownTarget = e.target;
			ws.call(call, mouseX(e), mouseY(e), e.which, 1, sessionID);
			//log(call + ': ' + e.which + ': ' + mouseDownTarget);
		});
		$(this).removeAttr('onmousedown');
	});

	$('[onmouseup]', doc).each(function()
	{
		var call = $(this).attr('onmouseup');
		$(this).on('mouseup', function(e)
		{
			ws.call(call, mouseX(e), mouseY(e), e.which, sessionID);
			mouseDownTarget = null;
			log(call + ': ' + e.which);
		});
		$(this).removeAttr('onmouseup');
	});

	$('[onmousemove]', doc).each(function()
	{
		var call = $(this).attr('onmousemove');
		$(this).on('mousemove', function(e)
		{
			now = e.timeStamp;
			diff = now - last;
			if (diff < ups)
				return;
			last = now;

			ws.call(call, mouseX(e), mouseY(e), sessionID);
		});
		$(this).removeAttr('onmousemove');
	});

	$('[onmouseover]', doc).each(function()
	{
		var call = $(this).attr('onmouseover');
		$(this).on('mouseover', function(e)
		{
			var to = call.lastIndexOf("/");
			overTargetCall = call.substring(0, to) + "/onmousescroll";
			ws.call(call, sessionID);
		});
		$(this).removeAttr('onmouseover');
	});

	$('[onmouseout]', doc).each(function()
	{
		var call = $(this).attr('onmouseout');
		$(this).on('mouseout', function(e)
		{
			overTargetCall = null;
			ws.call(call, sessionID);
		});
		$(this).removeAttr('onmouseout');
	});

	$('[onchange]', doc).each(function()
	{
		var call = $(this).attr('onchange');
		$(this).on('mousedown', function(e)
		{
			if (e.which == 1)
				return true;
			var $this = $(this);
			var $ed = $('#editor');

			//set call msg
			var to = call.lastIndexOf("/");
			editorTargetCall = call.substring(0, to) + "/onchange";

			//save current value
			$ed.data('before', $this.text());
			$ed.data('target', $(this));

			//show editor
			$ed.css({left: $(this).offset().left, top: $(this).offset().top});
			$ed.css('font-family', $(this).attr('font-family'));
			var size = $(this).attr('font-size');
			$ed.css('font-size', 12);
			var w, h;
			if ($this.width() != 0)
			{
				//this works only in chrome
				w = $this.width() + 20;
				h = $this.height();
			}
			else
			{
				//ie, ff
				var rect = this.getBoundingClientRect();
				w = rect.width + 20;
				h = rect.height;
			}

			$ed.width(w);
			$ed.height(h);
			$ed.html($this.text());
			$ed.show(100);
			$ed.focus();
			$ed.selectText();

			//now hide text under editor
			$(this).hide();

			//don't bubble the mousedown further:
			return false;
		});
		$(this).removeAttr('onchange');
	});
}

function onAdd(topicUri, event)
{
	//log(event);
	var doc = $.parseXML(event);
	var svgSnippet = $(doc);

	updateEvents(svgSnippet);

	startTimer();
	$('#add', $(svgSnippet)).children().each(function()
	{
		//id to insert
		var id = $(this).attr('id');
		var insertBeforeID = $(this).attr('insertBeforeID');

		//check if id already exists in document
		if (document.getElementById(id))
			console.log('ignoring existing element: ' + id);
		else
		{
			//get parent id
			var parentID = id.substring(0, id.lastIndexOf("/"));
			var parent;

			//if parentID = "" append to root
			if (parentID == '')
				parent = document.getElementById('svg');
			else
				parent = document.getElementById(parentID);

			if (insertBeforeID)
			{
				$(this).removeAttr('insertBeforeID');
				var sibling = document.getElementById(insertBeforeID);
				parent.insertBefore(this, sibling);
			}
			else
			{
				parent.appendChild(this);
			}
		}
	});

	var name = $('#add', $(svgSnippet)).attr('sessionName');
	setLastChangeName(name + ": add");
	stopTimer();
}

var $elementLookup = {};
function onUpdate(topicUri, event)
{
	//log(event);
	startTimer();

	var data = JSON.parse(event);
	var $element, i, update;

	i = data.Updates.length;
	while ( i-- )
	{
		update = data.Updates[i];
		//caching updates
		$element = $elementLookup[update.id] || ($elementLookup[update.id] = $(document.getElementById(update.id)));

		//setting all attributes at once
		//$element.attr(update.Attributes);

		//setting attributes one after the other
		for (var name in update.attributes)
		{
			if (name)
				$element.attr(name, update.attributes[name]);
			else //hack: no attribute name means innerhtml
				$element.text(update.attributes[name]);
		}
	}

	setLastChangeName(data.SessionName + ": update");
	stopTimer();
}

function onRemove(topicUri, event)
{
	log(event);
	startTimer();
	var data = JSON.parse(event);

	for (var i = 0; i < data.RemoveIDList.length; i++)
	{
		var elementToRemove = document.getElementById(data.RemoveIDList[i]);
		log(data.RemoveIDList[i]);
		$(elementToRemove).remove();
	}

	setLastChangeName(data.SessionName + ": remove");
	stopTimer();
}

	<commit_msg>updated for new topic: update-content<commit_after>/*
posh 0.1
brought to you by http://vvvv.org
*/

var ws;
var sessionID = "session";
var ups;

window.onload = function()
{
	hideConfig();

	// connect to WAMP server
	ab.connect("ws://LOCALIP:WEBSOCKETPORT",
	// WAMP session was established
	function (session)
	{
		ws = session;
		sessionID = session.sessionid();
		$('#sessionID').text('Session ID: ' + sessionID);

		ws.subscribe("add", onAdd);
		ws.subscribe("update-attribute", onUpdateAttribute);
		ws.subscribe("update-content", onUpdateContent);
		ws.subscribe("remove", onRemove);
		ws.call("dump").then(dumpResult);

		//load configs now that session is established
		var val = getCookie('ups');
		if (!val)
			val = parseInt($('#ups').val());
		setUpdatesPerSecond(val);
		ups = 1000 / val;

		var name = getCookie('sessionName');
		if (name)
			sendSessionName(name);
		else
			name = sessionID;
		setSessionName(name);

		$('#config').css('color', 'black');
	},

	// WAMP session is gone
	function (code, reason)
	{
		// things to do once the session fails
		log(reason);
		ws = null;

		$('#config').css('color', 'red');
	});
}

var editorTargetCall, overTargetCall;
$(document).ready(function()
{
	$(document).on("contextmenu", function(e){
		  return false;
	});

	//todo: svgterminal needs api to register shortcuts for which the default should be prevented
	//if simply preventing for all we cut ourselves out of default browser shortcuts

	$(document).on('keydown', function(e)
	{
		//e.originalEvent.preventDefault();
		ws.call('keydown', e.ctrlKey, e.shiftKey, e.altKey, e.which);
	});

	$(document).on('keyup', function(e)
	{
		//e.originalEvent.preventDefault();
		ws.call('keyup', e.ctrlKey, e.shiftKey, e.altKey, e.which);
	});

	//vvvv hosted IE does not send keydown/up, only keypress?
	$(document).on('keypress', function(e)
	{
		//e.originalEvent.preventDefault();
		ws.call('keypress', e.ctrlKey, e.shiftKey, e.altKey, String.fromCharCode(e.which));

		//don't scroll the page down on space
		if (e.keyCode == 32)
			e.originalEvent.preventDefault();
	});

	$('#svg').on('mousewheel', function(e)
	{
		if (overTargetCall)
		{
			ws.call(overTargetCall, e.originalEvent.wheelDelta / 120 + 100, sessionID);
			//prevent page fom scrolling
			return false;
		}

		return true;
	});

	$('#svg').on('mousedown', function(e)
	{
		hideConfig();
		$('#editor').blur();
	});

	$('#editor').on('keyup', function(e)
	{
		if (editorTargetCall)
		{
			if (e.keyCode == 13)
			{
				//execute
				$('#editor').blur();
			}
			else if (e.keyCode == 27)
			{
				//just hide the editor
				$('#editor').hide();
			}

			//get cursor position
			var c = $('#editor').caret();
			//adapt width of editor
			$('#editor').width($('#editor').textWidth() + 20);
			//set cursor back in place
			$('#editor').caret(c);
		}
	});

	$('#editor').blur(function(e)
	{
		//if value now different than before call(newvalue)
		var $ed = $('#editor');
		if ($ed.data('before') !== $ed.html())
		{
			ws.call(editorTargetCall, $ed.text().trim(), sessionID);
			editorTargetCall = null;
		}
		log('blurred');
		//hide editor
		$ed.hide();
		//re-show original text
		$ed.data('target').show();
	});

	$('#ups').bind('change', function(e) {
		e.preventDefault();
		var val = $(this).val();
		$('#upsdisp').text('Max updates/second: ' + val);
		setCookie('ups', val);

		ups = 1000 / val;
	});

	//ie hack
	if (navigator.userAgent.match('Trident') )
	{
		$('<link rel="stylesheet" type="text/css" href="ie.css" />').appendTo("head");
	}
});

function showConfig()
{
	$('#config').css('transform', 'translateY(0px)');
}

function hideConfig()
{
	var off = - $('#config').height() + 12;
	$('#config').css('transform', 'translateY(' + off + 'px)');
}

function setSessionName(name)
{
	$('#sessionName').val(name);
}

function setUpdatesPerSecond(ups)
{
	$('#ups').val(ups);
	$('#upsdisp').text('Max updates/second: ' + ups);
}

function setLastChangeName(name)
{
	$('#lastChange').text('Last Change: ' + name);
}

function sessionNameKeyUp(e)
{
	if (e.keyCode == 13)
	{
		var name = $('#sessionName').val().trim();
		sendSessionName(name);
		setCookie('sessionName', name, 10);
	}
}

function sendSessionName(name)
{
	ws.call('setSessionName', sessionID, name).then(setSessionName);
}

function dumpResult(data)
{
	//log(data);
	//remove doctype
	data = removeFirstLine(data);

	//$('#svg').empty();
	var svg = document.getElementById('svg');
	while (svg.lastChild)
	{
		svg.removeChild(svg.lastChild);
	}
	svg.appendChild(parseSVG(data));

	updateEvents(document);

	//reset the lookup after every dump
	//specifically necessary for startup
	$elementLookup = {};
}

function updateEvents(doc)
{
	var now, last, diff;
	//replace events
	$('[onclick]', doc).each(function()
	{
		var call = $(this).attr('onclick');
		$(this).on('click', function(e)
		{
			ws.call(call, mouseX(e), mouseY(e), e.which, 1, sessionID);
		});

		$(this).on('dblclick', function(e)
		{
			ws.call(call, mouseX(e), mouseY(e), e.which, 2, sessionID);
			log('dbl');
		});
		$(this).removeAttr('onclick');
	});

	$('[onmousedown]', doc).each(function()
	{
		var call = $(this).attr('onmousedown');
		$(this).on('mousedown', function(e)
		{
			e.originalEvent.preventDefault();
			mouseDownTarget = e.target;
			ws.call(call, mouseX(e), mouseY(e), e.which, 1, sessionID);
			//log(call + ': ' + e.which + ': ' + mouseDownTarget);
		});
		$(this).removeAttr('onmousedown');
	});

	$('[onmouseup]', doc).each(function()
	{
		var call = $(this).attr('onmouseup');
		$(this).on('mouseup', function(e)
		{
			ws.call(call, mouseX(e), mouseY(e), e.which, sessionID);
			mouseDownTarget = null;
			log(call + ': ' + e.which);
		});
		$(this).removeAttr('onmouseup');
	});

	$('[onmousemove]', doc).each(function()
	{
		var call = $(this).attr('onmousemove');
		$(this).on('mousemove', function(e)
		{
			now = e.timeStamp;
			diff = now - last;
			if (diff < ups)
				return;
			last = now;

			ws.call(call, mouseX(e), mouseY(e), sessionID);
		});
		$(this).removeAttr('onmousemove');
	});

	$('[onmouseover]', doc).each(function()
	{
		var call = $(this).attr('onmouseover');
		$(this).on('mouseover', function(e)
		{
			var to = call.lastIndexOf("/");
			overTargetCall = call.substring(0, to) + "/onmousescroll";
			ws.call(call, sessionID);
		});
		$(this).removeAttr('onmouseover');
	});

	$('[onmouseout]', doc).each(function()
	{
		var call = $(this).attr('onmouseout');
		$(this).on('mouseout', function(e)
		{
			overTargetCall = null;
			ws.call(call, sessionID);
		});
		$(this).removeAttr('onmouseout');
	});

	$('[onchange]', doc).each(function()
	{
		var call = $(this).attr('onchange');
		$(this).on('mousedown', function(e)
		{
			if (e.which == 1)
				return true;
			var $this = $(this);
			var $ed = $('#editor');

			//set call msg
			var to = call.lastIndexOf("/");
			editorTargetCall = call.substring(0, to) + "/onchange";

			//save current value
			$ed.data('before', $this.text());
			$ed.data('target', $(this));

			//show editor
			$ed.css({left: $(this).offset().left, top: $(this).offset().top});
			$ed.css('font-family', $(this).attr('font-family'));
			var size = $(this).attr('font-size');
			$ed.css('font-size', 12);
			var w, h;
			if ($this.width() != 0)
			{
				//this works only in chrome
				w = $this.width() + 20;
				h = $this.height();
			}
			else
			{
				//ie, ff
				var rect = this.getBoundingClientRect();
				w = rect.width + 20;
				h = rect.height;
			}

			$ed.width(w);
			$ed.height(h);
			$ed.html($this.text());
			$ed.show(100);
			$ed.focus();
			$ed.selectText();

			//now hide text under editor
			$(this).hide();

			//don't bubble the mousedown further:
			return false;
		});
		$(this).removeAttr('onchange');
	});
}

function onAdd(topicUri, event)
{
	//log(event);
	var doc = $.parseXML(event);
	var svgSnippet = $(doc);

	updateEvents(svgSnippet);

	startTimer();
	$('#add', $(svgSnippet)).children().each(function()
	{
		//id to insert
		var id = $(this).attr('id');
		var insertBeforeID = $(this).attr('insertBeforeID');

		//check if id already exists in document
		if (document.getElementById(id))
			console.log('ignoring existing element: ' + id);
		else
		{
			//get parent id
			var parentID = id.substring(0, id.lastIndexOf("/"));
			var parent;

			//if parentID = "" append to root
			if (parentID == '')
				parent = document.getElementById('svg');
			else
				parent = document.getElementById(parentID);

			if (insertBeforeID)
			{
				$(this).removeAttr('insertBeforeID');
				var sibling = document.getElementById(insertBeforeID);
				parent.insertBefore(this, sibling);
			}
			else
			{
				parent.appendChild(this);
			}
		}
	});

	var name = $('#add', $(svgSnippet)).attr('sessionName');
	setLastChangeName(name + ": add");
	stopTimer();
}

var $elementLookup = {};
function onUpdateAttribute(topicUri, event)
{
	//log(event);
	startTimer();

	var data = JSON.parse(event);
	var $element, i, update;

	i = data.Updates.length;
	while ( i-- )
	{
		update = data.Updates[i];

		//get (cached) element
		$element = $elementLookup[update.id] || ($elementLookup[update.id] = $(document.getElementById(update.id)));

		//setting all attributes at once
		$element.attr(update.attributes);
	}

	setLastChangeName(data.SessionName + ": update");
	stopTimer();
}

function onUpdateContent(topicUri, event)
{
	//log(event);
	startTimer();

	var data = JSON.parse(event);
	var $element, i, update;

	i = data.Updates.length;
	while ( i-- )
	{
		update = data.Updates[i];

		//get (cached) element
		$element = $elementLookup[update.id] || ($elementLookup[update.id] = $(document.getElementById(update.id)));

		//setting elements text content
		$element.text(update.text);
	}

	setLastChangeName(data.SessionName + ": update");
	stopTimer();
}

function onRemove(topicUri, event)
{
	log(event);
	startTimer();
	var data = JSON.parse(event);

	for (var i = 0; i < data.RemoveIDList.length; i++)
	{
		var elementToRemove = document.getElementById(data.RemoveIDList[i]);
		log(data.RemoveIDList[i]);
		$(elementToRemove).remove();
	}

	setLastChangeName(data.SessionName + ": remove");
	stopTimer();
}

	<|endoftext|>


<commit_before>

var BasicAuthenticateContextHelper = function($, handler, cb){
  //  if handler has an authenticate defined, call it.
  console.log("in helper");
  console.log('handler', handler);
  if (!!handler.basicAuthenticate && (typeof(handler.basicAuthenticate) == 'function')){
    console.log("in handler");
    var header = $.req.headers.authorization;

    if (!header){
      return $.status.unauthenticated();
    }

    var pieces = header.split(" ");
    var scheme = pieces[0];

    if (scheme !== 'Basic'){
      return $.status.unauthenticated();
    }
    var credentials = new Buffer(pieces[1], 'base64').toString('utf8').split(":");

    handler.basicAuthenticate(credentials[0], credentials[1], function(err, authenticated){
      if (err === true){
        // if it returns an error, throw a 401
        return $.status.unauthenticated();
      }
      if (!!err){
        return $.status.internalServerError(err);
      }
      // if it returns an object set handler.authenticated
      $.authenticated = authenticated;
      cb();  // no error
    });
  } else {
    cb();  // no error if no authenticate()
  }
};

module.exports = BasicAuthenticateContextHelper;

<commit_msg>fixed basic auth prompt<commit_after>

var BasicAuthenticateContextHelper = function($, handler, cb){
  //  if handler has an authenticate defined, call it.
  console.log("in helper");
  console.log('handler', handler);
  if (!!handler.basicAuthenticate && (typeof(handler.basicAuthenticate) == 'function')){
    console.log("in handler");
    var header = $.req.headers.authorization;

    if (!header){
      $.res.setHeader('WWW-Authenticate', 'Basic');
      return $.status.unauthenticated({scheme : 'Basic'});
    }

    var pieces = header.split(" ");
    var scheme = pieces[0];

    if (scheme !== 'Basic'){
      $.res.setHeader('WWW-Authenticate', 'Basic');
      return $.status.unauthenticated({scheme : 'Basic'});
    }
    var credentials = new Buffer(pieces[1], 'base64').toString('utf8').split(":");

    handler.basicAuthenticate(credentials[0], credentials[1], function(err, authenticated){
      if (err === true){
        // if it returns an error, throw a 401
        $.res.setHeader('WWW-Authenticate', 'Basic');
        return $.status.unauthenticated({scheme : 'Basic'});
      }
      if (!!err){
        return $.status.internalServerError(err);
      }
      // if it returns an object set handler.authenticated
      $.authenticated = authenticated;
      cb();  // no error
    });
  } else {
    cb();  // no error if no authenticate()
  }
};

module.exports = BasicAuthenticateContextHelper;

<|endoftext|>