<commit_before>/**
 * io.SocketNamespace.prototype.*
 *
 * Additional functionality for the Sails.js framework
 * Extends Socket.io socket object with some convenience methods
 *
 */

 /**
 *
 * Simulate an HTTP request to the backend
 *   @param {String} url    ::    the request label (usually the destination URL)
 *   @param {Object} data   ::    data to pass with the request
 *   @param {Object} options::    optional callback or config object
 *   @param {String} method ::    HTTP method (aka verb)
 *
 *
 * Note:  This should really be a private method, but it is
 *        exposed for backwards compatibility with Sails 0.8.x.
 *        The preferred usage in Sails v0.9+ is verb-based; e.g.,
 *          *-> `connectedSocket.get()`
 *          *-> `connectedSocket.post()`
 *          *-> `connectedSocket.put()`
 *          *-> `connectedSocket.delete()`
 */

io.SocketNamespace.prototype.request = function (url, data, options, method) {

  // Remove trailing slashes and spaces
  url = url.replace(/\/*\s*$/, '');

  // If url is empty, use /
  if (url === '') url = '/';

  // If options is a function, treat it as a callback
  // Otherwise the "success" property will be treated as the callback
  var cb;
  if (typeof options === 'function') cb = options;
  else cb = options.success;

  var json = io.JSON.stringify({
    url: url,
    data: data,
    method: method || 'get'
  });

  this.emit('message', json, function (result) {

    var parsedResult = result
    try {
      parsedResult = io.JSON.parse(result);
    } catch (e) {
      if (typeof console !== 'undefined') {
        console.log("Could not parse:", result, e);
      }
      throw new Error("Server response could not be parsed!  " + result);
    }

    // TODO: Handle errors more effectively
    if (parsedResult === 404) throw new Error("404: Not found");
    if (parsedResult === 403) throw new Error("403: Forbidden");
    if (parsedResult === 500) throw new Error("500: Server error");

    cb(parsedResult);
  });
};

<commit_msg>added socket get, post, put, and delete functions client side<commit_after>/**
 * io.SocketNamespace.prototype.*
 *
 * Additional functionality for the Sails.js framework
 * Extends Socket.io socket object with some convenience methods
 *
 */

 /**
 *
 * Simulate an HTTP request to the backend
 *   @param {String} url    ::    the request label (usually the destination URL)
 *   @param {Object} data   ::    data to pass with the request
 *   @param {Object} options::    optional callback or config object
 *   @param {String} method ::    HTTP method (aka verb)
 *
 *
 * Note:  This should really be a private method, but it is
 *        exposed for backwards compatibility with Sails 0.8.x.
 *        The preferred usage in Sails v0.9+ is verb-based; e.g.,
 *          *-> `connectedSocket.get()`
 *          *-> `connectedSocket.post()`
 *          *-> `connectedSocket.put()`
 *          *-> `connectedSocket.delete()`
 */

io.SocketNamespace.prototype.request = function (url, data, options, method) {

  // Remove trailing slashes and spaces
  url = url.replace(/\/*\s*$/, '');

  // If url is empty, use /
  if (url === '') url = '/';

  // If options is a function, treat it as a callback
  // Otherwise the "success" property will be treated as the callback
  var cb;
  if (typeof options === 'function') cb = options;
  else cb = options.success;

  var json = io.JSON.stringify({
    url: url,
    data: data
  });

  this.emit(method || 'get', json, function (result) {

    var parsedResult = result
    try {
      parsedResult = io.JSON.parse(result);
    } catch (e) {
      if (typeof console !== 'undefined') {
        console.log("Could not parse:", result, e);
      }
      throw new Error("Server response could not be parsed!  " + result);
    }

    // TODO: Handle errors more effectively
    if (parsedResult === 404) throw new Error("404: Not found");
    if (parsedResult === 403) throw new Error("403: Forbidden");
    if (parsedResult === 500) throw new Error("500: Server error");

    cb(parsedResult);
  });
};

io.SocketNamespace.prototype.get = function(url, data, options){
  return this.request(url, data, options, 'get');
}

io.SocketNamespace.prototype.post = function(url, data, options){
  return this.request(url, data, options, 'post');
}

io.SocketNamespace.prototype.put = function(url, data, options){
  return this.request(url, data, options, 'put');
}

io.SocketNamespace.prototype.delete = function(url, data, options){
  return this.request(url, data, options, 'delete');
}<|endoftext|>


<commit_before>
/**
 *  InvertedIndex class constructor
 *  @class
 */

class InvertedIndex {
	/**
	 *  class constructor
	 *  @constructor
	 */
	constructor() {
		this.indexes = [];
	}

	/**
	 * coverts the string provided to lower case, strips the string of all special
	 * characters, extra spaces and converts the result into an Array
	 * @static
	 * @param {string} text the text to be converted
	 * @returns {Array} the result that will be returned after function call
	 */
	static textToArray(text) {
		const result = text.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/);
		return result;
	}

	/**
	 * loops through an array and removes duplicate elements
	 * @static
	 * @param {}
	 * @returns {Array}
	 */
	_sortIndex(bookName, arrayItem, element) {
		element = parseInt(element);
		for(let item in arrayItem) {
			if(!this.indexes[bookName].hasOwnProperty([arrayItem[item]])) {
				this.indexes[bookName][arrayItem[item]] = [];
				this.indexes[bookName][arrayItem[item]].push(element);
			} else if(
				this.indexes[bookName].hasOwnProperty([arrayItem[item]]) &&
				this.indexes[bookName][arrayItem[item]].indexOf(element) === -1) {
				this.indexes[bookName][arrayItem[item]].push(element);
			}
		}
	}

	/**
	 * @function takes a file path as argument and read the contents of the file
	 * @param {string} name the name of the file
	 * @param {Array} content the content of the file
	 * @returns {Array}
	 */
	createIndex(name, fileContent) {
		const indexArray = [];
		fileContent.forEach((item) => {
			let text = item.title + " " + item.content;
			let textArray = InvertedIndex.textToArray(text);
			indexArray.push(textArray);
		});

		if(!this.indexes[name]) {
			this.indexes[name] = {};
			for(let element in indexArray) {
				let textIndex = indexArray[element];
				this._sortIndex(name, textIndex, element);
			}
		}

		// return this.indexes;
	}

	/**
	 * @function takes an uploaded file as argument and read the contents of the file
   * @returns {Object}
   */
	getIndex(name = null) {
		if(Object.keys(this.indexes).length < 1 ) {
			return {};
		} else if(name === null) {
			return this.indexes;
		} else {
			if(this.indexes[name]) {
				return this.indexes[name];
			}
		}
	}

	/**
	 * @function return an object that contains the index of the search
	 * word and the files they can be found.
	 * @param {string} terms
	 * @returns {Object}
	 */

	_getTermResult(answer, term, name) {
		let indexFile = this.getIndex(name);
		if(name === null) {
			for(let key in indexFile) {
				if(term in indexFile[key] && answer[term] === undefined) {
					answer[term] = {};
					answer[term][key] = indexFile[key][term];
				} else if(term in indexFile[key] && answer.hasOwnProperty(term)) {
	 				answer[term][key] = indexFile[key][term];
	 			} else {
	 				return "Search text not found";
	 			}
			}
			return answer;
		} else if (indexFile !== undefined) {
			if(term in this.indexes[name]) {
				answer[term] = {};
				answer[term] = this.indexes[name][term];
				return answer;
			}
			return "Search text not found";
		}
	}

	/**
	 * @function takes an array of arguments and returns an array of numbers that represents
	 * the index of the words
	 * @param {string} terms
	 * @returns {Array}
	 */

	searchIndex(terms, name = null) {
	 	if (name && !this.indexes.hasOwnProperty(name)) {
	 		return "No such File";
	 	}
	 	terms = InvertedIndex.textToArray(terms);
	 	let result = [];
	 	terms.forEach((term) => {
	 		let fileResult = {};
	 		let answer = this._getTermResult(fileResult, term, name);
	 		result.push(answer);
	 	});
	 	return result;
	 }
}
<commit_msg>edited inverted-index.js file to use 2 tab-spaces<commit_after>/**
 *  InvertedIndex class constructor
 *  @class
 */

class InvertedIndex {
	/**
	 *  class constructor
	 *  @constructor
	 */
	constructor() {
		this.indexes = [];
	}

	/**
	 * coverts the string provided to lower case, strips the string of all special
	 * characters, extra spaces and converts the result into an Array
	 * @static
	 * @param {string} text the text to be converted
	 * @returns {Array} the result that will be returned after function call
	 */
	static textToArray(text) {
		const result = text.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/);
		return result;
	}

	/**
	 * loops through an array and removes duplicate elements
	 * @static
	 * @param {}
	 * @returns {Array}
	 */
	_sortIndex(bookName, arrayItem, element) {
		element = parseInt(element);
		for(let item in arrayItem) {
			if(!this.indexes[bookName].hasOwnProperty([arrayItem[item]])) {
				this.indexes[bookName][arrayItem[item]] = [];
				this.indexes[bookName][arrayItem[item]].push(element);
			} else if(
				this.indexes[bookName].hasOwnProperty([arrayItem[item]]) &&
				this.indexes[bookName][arrayItem[item]].indexOf(element) === -1) {
				this.indexes[bookName][arrayItem[item]].push(element);
			}
		}
	}

	/**
	 * @function takes a file path as argument and read the contents of the file
	 * @param {string} name the name of the file
	 * @param {Array} content the content of the file
	 * @returns {Array}
	 */
	createIndex(name, fileContent) {
		const indexArray = [];
		fileContent.forEach((item) => {
			let text = item.title + " " + item.content;
			let textArray = InvertedIndex.textToArray(text);
			indexArray.push(textArray);
		});

		if(!this.indexes[name]) {
			this.indexes[name] = {};
			for(let element in indexArray) {
				let textIndex = indexArray[element];
				this._sortIndex(name, textIndex, element);
			}
		}

		// return this.indexes;
	}

	/**
	 * @function takes an uploaded file as argument and read the contents of the file
   * @returns {Object}
   */
	getIndex(name = null) {
		if(Object.keys(this.indexes).length < 1 ) {
			return {};
		} else if(name === null) {
			return this.indexes;
		} else {
			if(this.indexes[name]) {
				return this.indexes[name];
			}
		}
	}

	/**
	 * @function return an object that contains the index of the search
	 * word and the files they can be found.
	 * @param {string} terms
	 * @returns {Object}
	 */

	_getTermResult(answer, term, name) {
		let indexFile = this.getIndex(name);
		if(name === null) {
			for(let key in indexFile) {
				if(term in indexFile[key] && answer[term] === undefined) {
					answer[term] = {};
					answer[term][key] = indexFile[key][term];
				} else if(term in indexFile[key] && answer.hasOwnProperty(term)) {
	 				answer[term][key] = indexFile[key][term];
	 			} else {
	 				return "Search text not found";
	 			}
			}
			return answer;
		} else if (indexFile !== undefined) {
			if(term in this.indexes[name]) {
				answer[term] = {};
				answer[term] = this.indexes[name][term];
				return answer;
			}
			return "Search text not found";
		}
	}

	/**
	 * @function takes an array of arguments and returns an array of numbers that represents
	 * the index of the words
	 * @param {string} terms
	 * @returns {Array}
	 */

	searchIndex(terms, name = null) {
	 	if (name && !this.indexes.hasOwnProperty(name)) {
	 		return "No such File";
	 	}
	 	terms = InvertedIndex.textToArray(terms);
	 	let result = [];
	 	terms.forEach((term) => {
	 		let fileResult = {};
	 		let answer = this._getTermResult(fileResult, term, name);
	 		result.push(answer);
	 	});
	 	return result;
	 }
}
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict'

const chai = require('chai')
const dirtyChai = require('dirty-chai')
const expect = chai.expect
chai.use(dirtyChai)
const waterfall = require('async/waterfall')
const series = require('async/series')
const parallel = require('async/parallel')
const CID = require('cids')

function spawnWithId (factory, callback) {
  waterfall([
    (cb) => factory.spawnNode(cb),
    (node, cb) => node.id((err, peerId) => {
      if (err) {
        return cb(err)
      }
      node.peerId = peerId
      cb(null, node)
    })
  ], callback)
}

module.exports = (common) => {
  describe('.dht', function () {
    this.timeout(20 * 1000)

    let nodeA
    let nodeB
    let nodeC

    before((done) => {
      common.setup((err, factory) => {
        expect(err).to.not.exist()
        series([
          (cb) => spawnWithId(factory, cb),
          (cb) => spawnWithId(factory, cb),
          (cb) => spawnWithId(factory, cb)
        ], (err, nodes) => {
          expect(err).to.not.exist()

          nodeA = nodes[0]
          nodeB = nodes[1]
          nodeC = nodes[2]

          parallel([
            (cb) => nodeA.swarm.connect(nodeB.peerId.addresses[0], cb),
            (cb) => nodeB.swarm.connect(nodeC.peerId.addresses[0], cb),
            (cb) => nodeC.swarm.connect(nodeA.peerId.addresses[0], cb)
          ], done)
        })
      })
    })

    after((done) => common.teardown(done))

    describe('callback API', () => {
      describe('.get and .put', () => {
        it('errors when getting a non-existent key from the DHT', (done) => {
          nodeA.dht.get('non-existing', { timeout: '100ms' }, (err, value) => {
            expect(err).to.be.an.instanceof(Error)
            done()
          })
        })

        // TODO: fix - go-ipfs errors with  Error: key was not found (type 6)
        // https://github.com/ipfs/go-ipfs/issues/3862
        it.skip('fetches value after it was put on another node', (done) => {
          waterfall([
            (cb) => nodeB.object.new('unixfs-dir', cb),
            (node, cb) => setTimeout(() => cb(null, node), 1000),
            (node, cb) => {
              const multihash = node.toJSON().multihash

              nodeA.dht.get(multihash, cb)
            },
            (result, cb) => {
              expect(result).to.eql('')
              cb()
            }
          ], done)
        })
      })

      describe('.findpeer', () => {
        it('finds other peers', (done) => {
          console.log(nodeC.peerId.id)

          nodeA.dht.findpeer(nodeC.peerId.id, (err, peer) => {
            expect(err).to.not.exist()
            // TODO upgrade the answer, format is weird
            expect(peer[0].Responses[0].ID).to.be.equal(nodeC.peerId.id)
            done()
          })
        })

        // TODO checking what is exactly go-ipfs returning
        // https://github.com/ipfs/go-ipfs/issues/3862#issuecomment-294168090
        it.skip('fails to find other peer, if peer doesnt exist()s', (done) => {
          nodeA.dht.findpeer('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ', (err, peer) => {
            expect(err).to.not.exist()
            expect(peer).to.be.equal(null)
            done()
          })
        })
      })

      describe('.provide', () => {
        it('regular', (done) => {
          // TODO recheck this test, should it provide or not if block is not available? go-ipfs does provide.
          const cid = new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ')

          nodeC.dht.provide(cid, done)
        })

        it.skip('recursive', () => {})
      })

      describe.skip('findprovs', () => {
        it('basic', (done) => {
          const cid = new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxxx')

          waterfall([
            (cb) => nodeB.dht.provide(cid, cb),
            (cb) => nodeC.dht.findprovs(cid, cb),
            (provs, cb) => {
              expect(provs.map((p) => p.toB58String()))
                .to.eql([nodeB.peerId.id])
              cb()
            }
          ], done)
        })
      })

      describe('.query', () => {
        it('returns the other node in the query', (done) => {
          nodeA.dht.query(nodeC.peerId.id, (err, peers) => {
            expect(err).to.not.exist()
            expect(peers.map((p) => p.ID)).to.include(nodeC.peerId.id)
            done()
          })
        })
      })
    })

    describe('promise API', () => {
      describe('.get', () => {
        it('errors when getting a non-existent key from the DHT', (done) => {
          nodeA.dht.get('non-existing', { timeout: '100ms' })
            .catch((err) => {
              expect(err).to.exist()
              done()
            })
        })
      })

      it.skip('.findprovs', (done) => {
        nodeB.dht.findprovs('Qma4hjFTnCasJ8PVp3mZbZK5g2vGDT4LByLJ7m8ciyRFZP')
          .then((res) => {
            expect(res).to.be.an('array')
            done()
          })
          .catch((err) => done(err))
      })
    })
  })
}
<commit_msg>chore: bump timeouts<commit_after>/* eslint-env mocha */
'use strict'

const chai = require('chai')
const dirtyChai = require('dirty-chai')
const expect = chai.expect
chai.use(dirtyChai)
const waterfall = require('async/waterfall')
const series = require('async/series')
const parallel = require('async/parallel')
const CID = require('cids')

function spawnWithId (factory, callback) {
  waterfall([
    (cb) => factory.spawnNode(cb),
    (node, cb) => node.id((err, peerId) => {
      if (err) {
        return cb(err)
      }
      node.peerId = peerId
      cb(null, node)
    })
  ], callback)
}

module.exports = (common) => {
  describe('.dht', function () {
    this.timeout(80 * 1000)

    let nodeA
    let nodeB
    let nodeC

    before((done) => {
      common.setup((err, factory) => {
        expect(err).to.not.exist()
        series([
          (cb) => spawnWithId(factory, cb),
          (cb) => spawnWithId(factory, cb),
          (cb) => spawnWithId(factory, cb)
        ], (err, nodes) => {
          expect(err).to.not.exist()

          nodeA = nodes[0]
          nodeB = nodes[1]
          nodeC = nodes[2]

          parallel([
            (cb) => nodeA.swarm.connect(nodeB.peerId.addresses[0], cb),
            (cb) => nodeB.swarm.connect(nodeC.peerId.addresses[0], cb),
            (cb) => nodeC.swarm.connect(nodeA.peerId.addresses[0], cb)
          ], done)
        })
      })
    })

    after((done) => common.teardown(done))

    describe('callback API', () => {
      describe('.get and .put', () => {
        it('errors when getting a non-existent key from the DHT', (done) => {
          nodeA.dht.get('non-existing', { timeout: '100ms' }, (err, value) => {
            expect(err).to.be.an.instanceof(Error)
            done()
          })
        })

        // TODO: fix - go-ipfs errors with  Error: key was not found (type 6)
        // https://github.com/ipfs/go-ipfs/issues/3862
        it.skip('fetches value after it was put on another node', (done) => {
          waterfall([
            (cb) => nodeB.object.new('unixfs-dir', cb),
            (node, cb) => setTimeout(() => cb(null, node), 1000),
            (node, cb) => {
              const multihash = node.toJSON().multihash

              nodeA.dht.get(multihash, cb)
            },
            (result, cb) => {
              expect(result).to.eql('')
              cb()
            }
          ], done)
        })
      })

      describe('.findpeer', () => {
        it('finds other peers', (done) => {
          console.log(nodeC.peerId.id)

          nodeA.dht.findpeer(nodeC.peerId.id, (err, peer) => {
            expect(err).to.not.exist()
            // TODO upgrade the answer, format is weird
            expect(peer[0].Responses[0].ID).to.be.equal(nodeC.peerId.id)
            done()
          })
        })

        // TODO checking what is exactly go-ipfs returning
        // https://github.com/ipfs/go-ipfs/issues/3862#issuecomment-294168090
        it.skip('fails to find other peer, if peer doesnt exist()s', (done) => {
          nodeA.dht.findpeer('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ', (err, peer) => {
            expect(err).to.not.exist()
            expect(peer).to.be.equal(null)
            done()
          })
        })
      })

      describe('.provide', () => {
        it('regular', (done) => {
          // TODO recheck this test, should it provide or not if block is not available? go-ipfs does provide.
          const cid = new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ')

          nodeC.dht.provide(cid, done)
        })

        it.skip('recursive', () => {})
      })

      describe.skip('findprovs', () => {
        it('basic', (done) => {
          const cid = new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxxx')

          waterfall([
            (cb) => nodeB.dht.provide(cid, cb),
            (cb) => nodeC.dht.findprovs(cid, cb),
            (provs, cb) => {
              expect(provs.map((p) => p.toB58String()))
                .to.eql([nodeB.peerId.id])
              cb()
            }
          ], done)
        })
      })

      describe('.query', () => {
        it('returns the other node in the query', (done) => {
          nodeA.dht.query(nodeC.peerId.id, (err, peers) => {
            expect(err).to.not.exist()
            expect(peers.map((p) => p.ID)).to.include(nodeC.peerId.id)
            done()
          })
        })
      })
    })

    describe('promise API', () => {
      describe('.get', () => {
        it('errors when getting a non-existent key from the DHT', (done) => {
          nodeA.dht.get('non-existing', { timeout: '100ms' })
            .catch((err) => {
              expect(err).to.exist()
              done()
            })
        })
      })

      it.skip('.findprovs', (done) => {
        nodeB.dht.findprovs('Qma4hjFTnCasJ8PVp3mZbZK5g2vGDT4LByLJ7m8ciyRFZP')
          .then((res) => {
            expect(res).to.be.an('array')
            done()
          })
          .catch((err) => done(err))
      })
    })
  })
}
<|endoftext|>


<commit_before>'use strict'; // eslint-disable-line strict

const awsURIencode = require('./awsURIencode');
const crypto = require('crypto');
const queryString = require('querystring');

/**
 * createCanonicalRequest - creates V4 canonical request
 * @param {object} params - contains pHttpVerb (request type),
 * pResource (parsed from URL), pQuery (request query),
 * pHeaders (request headers), pSignedHeaders (signed headers from request),
 * payloadChecksum (from request)
 * @returns {string} - canonicalRequest
 */
function createCanonicalRequest(params) {
    const pHttpVerb = params.pHttpVerb;
    const pResource = params.pResource;
    const pQuery = params.pQuery;
    const pHeaders = params.pHeaders;
    const pSignedHeaders = params.pSignedHeaders;
    const service = params.service;

    let payloadChecksum = params.payloadChecksum;

    if (!payloadChecksum) {
        if (pHttpVerb === 'GET') {
            payloadChecksum = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b' +
                '934ca495991b7852b855';
        } else if (pHttpVerb === 'POST') {
            let notEncodeStar = false;
            // The java sdk does not encode the '*' parameter to compute the
            // signature, if the user-agent is recognized, we need to keep
            // the plain '*' as well.
            if (/aws-sdk-java\/[0-9.]+/.test(pHeaders['user-agent'])) {
                notEncodeStar = true;
            }
            let payload = queryString.stringify(pQuery, null, null, {
                encodeURIComponent: input => awsURIencode(input, false,
                    notEncodeStar),
            });
            payload = payload.replace(/%20/g, '+');
            payloadChecksum = crypto.createHash('sha256')
                .update(payload, 'binary').digest('hex').toLowerCase();
        }
    }

    const canonicalURI = !!pResource ? awsURIencode(pResource, false) : '/';

    // canonical query string
    let canonicalQueryStr = '';
    if (pQuery && !((service === 'iam' || service === 'ring' ||
        service === 'sts') &&
        pHttpVerb === 'POST')) {
        const sortedQueryParams = Object.keys(pQuery).sort().map(key => {
            const encodedKey = awsURIencode(key);
            const value = pQuery[key] ? awsURIencode(pQuery[key]) : '';
            return `${encodedKey}=${value}`;
        });
        canonicalQueryStr = sortedQueryParams.join('&');
    }

    // signed headers
    const signedHeadersList = pSignedHeaders.split(';');
    signedHeadersList.sort((a, b) => a.localeCompare(b));
    const signedHeaders = signedHeadersList.join(';');

    // canonical headers
    const canonicalHeadersList = signedHeadersList.map(signedHeader => {
        if (pHeaders[signedHeader] !== undefined) {
            const trimmedHeader = pHeaders[signedHeader]
                .trim().replace(/\s+/g, ' ');
            return `${signedHeader}:${trimmedHeader}\n`;
        }
        // nginx will strip the actual expect header so add value of
        // header back here if it was included as a signed header
        if (signedHeader === 'expect') {
            return `${signedHeader}:100-continue\n`;
        }
        // handle case where signed 'header' is actually query param
        return `${signedHeader}:${pQuery[signedHeader]}\n`;
    });

    const canonicalHeaders = canonicalHeadersList.join('');

    const canonicalRequest = `${pHttpVerb}\n${canonicalURI}\n` +
        `${canonicalQueryStr}\n${canonicalHeaders}\n` +
        `${signedHeaders}\n${payloadChecksum}`;
    return canonicalRequest;
}

module.exports = createCanonicalRequest;
<commit_msg>FIX: Wrong parameter encode url<commit_after>'use strict'; // eslint-disable-line strict

const awsURIencode = require('./awsURIencode');
const crypto = require('crypto');
const queryString = require('querystring');

/**
 * createCanonicalRequest - creates V4 canonical request
 * @param {object} params - contains pHttpVerb (request type),
 * pResource (parsed from URL), pQuery (request query),
 * pHeaders (request headers), pSignedHeaders (signed headers from request),
 * payloadChecksum (from request)
 * @returns {string} - canonicalRequest
 */
function createCanonicalRequest(params) {
    const pHttpVerb = params.pHttpVerb;
    const pResource = params.pResource;
    const pQuery = params.pQuery;
    const pHeaders = params.pHeaders;
    const pSignedHeaders = params.pSignedHeaders;
    const service = params.service;

    let payloadChecksum = params.payloadChecksum;

    if (!payloadChecksum) {
        if (pHttpVerb === 'GET') {
            payloadChecksum = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b' +
                '934ca495991b7852b855';
        } else if (pHttpVerb === 'POST') {
            let notEncodeStar = false;
            // The java sdk does not encode the '*' parameter to compute the
            // signature, if the user-agent is recognized, we need to keep
            // the plain '*' as well.
            if (/aws-sdk-java\/[0-9.]+/.test(pHeaders['user-agent'])) {
                notEncodeStar = true;
            }
            let payload = queryString.stringify(pQuery, null, null, {
                encodeURIComponent: input => awsURIencode(input, true,
                    notEncodeStar),
            });
            payload = payload.replace(/%20/g, '+');
            payloadChecksum = crypto.createHash('sha256')
                .update(payload, 'binary').digest('hex').toLowerCase();
        }
    }

    const canonicalURI = !!pResource ? awsURIencode(pResource, false) : '/';

    // canonical query string
    let canonicalQueryStr = '';
    if (pQuery && !((service === 'iam' || service === 'ring' ||
        service === 'sts') &&
        pHttpVerb === 'POST')) {
        const sortedQueryParams = Object.keys(pQuery).sort().map(key => {
            const encodedKey = awsURIencode(key);
            const value = pQuery[key] ? awsURIencode(pQuery[key]) : '';
            return `${encodedKey}=${value}`;
        });
        canonicalQueryStr = sortedQueryParams.join('&');
    }

    // signed headers
    const signedHeadersList = pSignedHeaders.split(';');
    signedHeadersList.sort((a, b) => a.localeCompare(b));
    const signedHeaders = signedHeadersList.join(';');

    // canonical headers
    const canonicalHeadersList = signedHeadersList.map(signedHeader => {
        if (pHeaders[signedHeader] !== undefined) {
            const trimmedHeader = pHeaders[signedHeader]
                .trim().replace(/\s+/g, ' ');
            return `${signedHeader}:${trimmedHeader}\n`;
        }
        // nginx will strip the actual expect header so add value of
        // header back here if it was included as a signed header
        if (signedHeader === 'expect') {
            return `${signedHeader}:100-continue\n`;
        }
        // handle case where signed 'header' is actually query param
        return `${signedHeader}:${pQuery[signedHeader]}\n`;
    });

    const canonicalHeaders = canonicalHeadersList.join('');

    const canonicalRequest = `${pHttpVerb}\n${canonicalURI}\n` +
        `${canonicalQueryStr}\n${canonicalHeaders}\n` +
        `${signedHeaders}\n${payloadChecksum}`;
    return canonicalRequest;
}

module.exports = createCanonicalRequest;
<|endoftext|>


<commit_before>var time;

function toggleDiv (divId) {
    $('#' + divId).toggle();
};

function Sail () {
    g = new THREE.Geometry();
    w = 8;
    w2 = w/2;
    m = new THREE.MeshBasicMaterial({color : 0x444444, side : THREE.DoubleSide});
    g.vertices.push(
	new THREE.Vector3(0, 0, 0),
	new THREE.Vector3(w2, 0, 0),
	new THREE.Vector3(0, 0, w2),
	new THREE.Vector3(-w2, 0, 0),
	new THREE.Vector3(0, 0, -w2));
    g.faces.push(
	new THREE.Face3(0, 1, 2),
	new THREE.Face3(0, 2, 3),
	new THREE.Face3(0, 3, 4),
	new THREE.Face3(0, 4, 1));
    g.computeFaceNormals();
    g.computeBoundingSphere();
    return new THREE.Mesh(g, m);
};

function onWindowResize () {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.lookAt(origin);
    //if (controls) {
    //controls.handleResize();
    //}
    render();
}

function init() {
    scene = new THREE.Scene();
    origin = new THREE.Vector3(0,0,0);
    plotDiv = document.getElementById('plot');
    if (window.WebGLRenderingContext) {
	renderer = new THREE.WebGLRenderer({ antialias : true })
    } else {
	renderer = new THREE.CanvasRenderer();
    };
    renderer.setSize(window.innerWidth, window.innerHeight);
    plotDiv.appendChild(renderer.domElement);
    camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
    camera.position.set(2, -6, 3);
    camera.lookAt(origin);
    scene.add(camera);
    sail = new Sail();
    scene.add(sail);
    window.addEventListener('resize', onWindowResize, false);
    toggleDiv('helpText');
    vel = 0;
    pos = 0;
};

function render () {
    renderer.render(scene, camera);
};

function update () {
    now = (new Date()).getTime();
    dt = now - (time || now);
    accel = 1e-7;
    time = now;
    vel += accel * dt;
    pos += vel * dt;
    sail.position.y = pos;
};

function initTiltControls () {
    incidence = 0;
    rotation = 0;
    absorbed = 1;
    $(document.body).on(
	'keydown',
	function (e) {
	    switch (e.which) {
	    case 37: return left();
	    case 39: return right();
	    case 38: return up();
	    case 40: return down();
	    };
	});
    $('#up').click(function (e) { return up(); });
    $('#down').click(function (e) { return down(); });
    $('#left').click(function (e) { return left(); });
    $('#right').click(function (e) { return right(); });
};

function calcAbsorbed(incidence) {
    return Math.abs(Math.round(100 * Math.cos(incidence * (Math.PI / 180))));
};

function rotateGlobalY(object, rad) {
    var gy = new THREE.Vector3(0, 1, 0);
    var ly = object.worldToLocal(gy);
    return object.rotateOnAxis(ly, rad);
};

function up() {
    sail.rotateZ(Math.PI / 36);
    incidence += 5;
    if (incidence > 180) {
        incidence -= 360;
    };
    absorbed = calcAbsorbed(incidence);
    sail.updateMatrixWorld();
};

function down() {
    sail.rotateZ(Math.PI / -36);
    incidence -= 5;
    if (incidence < -180) {
        incidence = 360 + incidence;
    };
    absorbed = calcAbsorbed(incidence);
    sail.updateMatrixWorld();
};

function left() {
    rotateGlobalY(sail, Math.PI / 36);
    rotation -= 5;
    if (rotation < -180) {
        rotation = 360 + rotation;
    };
    sail.updateMatrixWorld();
};

function right() {
    rotateGlobalY(sail, Math.PI / -36);
    rotation += 5;
    if (rotation > 180) {
        rotation -= 360;
    };
    sail.updateMatrixWorld();
};

function animate () {
    requestAnimationFrame(animate);
    update();
    render();
};
<commit_msg>Fix local variable definitions<commit_after>var time;

function toggleDiv (divId) {
    $('#' + divId).toggle();
};

function Sail () {
    var g = new THREE.Geometry(),
	w = 8,
	w2 = w/2,
	m = new THREE.MeshBasicMaterial({color : 0x444444, side : THREE.DoubleSide});
    g.vertices.push(
	new THREE.Vector3(0, 0, 0),
	new THREE.Vector3(w2, 0, 0),
	new THREE.Vector3(0, 0, w2),
	new THREE.Vector3(-w2, 0, 0),
	new THREE.Vector3(0, 0, -w2));
    g.faces.push(
	new THREE.Face3(0, 1, 2),
	new THREE.Face3(0, 2, 3),
	new THREE.Face3(0, 3, 4),
	new THREE.Face3(0, 4, 1));
    g.computeFaceNormals();
    g.computeBoundingSphere();
    return new THREE.Mesh(g, m);
};

function onWindowResize () {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.lookAt(origin);
    //if (controls) {
    //controls.handleResize();
    //}
    render();
}

function init() {
    scene = new THREE.Scene();
    origin = new THREE.Vector3(0,0,0);
    plotDiv = document.getElementById('plot');
    if (window.WebGLRenderingContext) {
	renderer = new THREE.WebGLRenderer({ antialias : true })
    } else {
	renderer = new THREE.CanvasRenderer();
    };
    renderer.setSize(window.innerWidth, window.innerHeight);
    plotDiv.appendChild(renderer.domElement);
    camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
    camera.position.set(2, -6, 3);
    camera.lookAt(origin);
    scene.add(camera);
    sail = new Sail();
    scene.add(sail);
    window.addEventListener('resize', onWindowResize, false);
    toggleDiv('helpText');
    vel = 0;
    pos = 0;
};

function render () {
    renderer.render(scene, camera);
};

function update () {
    now = (new Date()).getTime();
    dt = now - (time || now);
    accel = 1e-7;
    time = now;
    vel += accel * dt;
    pos += vel * dt;
    sail.position.y = pos;
};

function initTiltControls () {
    incidence = 0;
    rotation = 0;
    absorbed = 1;
    $(document.body).on(
	'keydown',
	function (e) {
	    switch (e.which) {
	    case 37: return left();
	    case 39: return right();
	    case 38: return up();
	    case 40: return down();
	    };
	});
    $('#up').click(function (e) { return up(); });
    $('#down').click(function (e) { return down(); });
    $('#left').click(function (e) { return left(); });
    $('#right').click(function (e) { return right(); });
};

function calcAbsorbed(incidence) {
    return Math.abs(Math.round(100 * Math.cos(incidence * (Math.PI / 180))));
};

function rotateGlobalY(object, rad) {
    var gy = new THREE.Vector3(0, 1, 0);
    var ly = object.worldToLocal(gy);
    return object.rotateOnAxis(ly, rad);
};

function up() {
    sail.rotateZ(Math.PI / 36);
    incidence += 5;
    if (incidence > 180) {
        incidence -= 360;
    };
    absorbed = calcAbsorbed(incidence);
    sail.updateMatrixWorld();
};

function down() {
    sail.rotateZ(Math.PI / -36);
    incidence -= 5;
    if (incidence < -180) {
        incidence = 360 + incidence;
    };
    absorbed = calcAbsorbed(incidence);
    sail.updateMatrixWorld();
};

function left() {
    rotateGlobalY(sail, Math.PI / 36);
    rotation -= 5;
    if (rotation < -180) {
        rotation = 360 + rotation;
    };
    sail.updateMatrixWorld();
};

function right() {
    rotateGlobalY(sail, Math.PI / -36);
    rotation += 5;
    if (rotation > 180) {
        rotation -= 360;
    };
    sail.updateMatrixWorld();
};

function animate () {
    requestAnimationFrame(animate);
    update();
    render();
};
<|endoftext|>


<commit_before>const debug = require("debug")("contract:utils");
const web3Utils = require("web3-utils");
const bigNumberify = require("ethers/utils/bignumber").bigNumberify;
const abi = require("web3-eth-abi");
const BlockchainUtils = require("truffle-blockchain-utils");
const reformat = require("./reformat");
const ENS = require("ethereum-ens");

const Utils = {
  is_object(val) {
    return typeof val === "object" && !Array.isArray(val);
  },

  is_big_number(val) {
    if (typeof val !== "object") return false;

    return web3Utils.isBN(val) || web3Utils.isBigNumber(val);
  },

  is_tx_params(val) {
    if (!Utils.is_object(val)) return false;
    if (Utils.is_big_number(val)) return false;

    const allowed_fields = {
      from: true,
      to: true,
      gas: true,
      gasPrice: true,
      value: true,
      data: true,
      nonce: true,
      privateFor: true
    };

    for (field_name of Object.keys(val)) {
      if (allowed_fields[field_name]) return true;
    }

    return false;
  },

  decodeLogs(_logs, isSingle) {
    const constructor = this;
    const logs = Utils.toTruffleLog(_logs, isSingle);

    return logs
      .map(log => {
        const logABI = constructor.events[log.topics[0]];

        if (logABI == null) {
          return null;
        }

        const copy = Utils.merge({}, log);

        copy.event = logABI.name;
        copy.topics = logABI.anonymous ? copy.topics : copy.topics.slice(1);

        if (copy.data === "0x") {
          copy.data = "";
        }

        const logArgs = abi.decodeLog(logABI.inputs, copy.data, copy.topics);
        copy.args = reformat.numbers.call(constructor, logArgs, logABI.inputs);

        delete copy.data;
        delete copy.topics;

        return copy;
      })
      .filter(log => log != null);
  },

  toTruffleLog(events, isSingle) {
    // Transform singletons (from event listeners) to the kind of
    // object we find on the receipt
    if (isSingle && typeof isSingle === "boolean") {
      const temp = [];
      temp.push(events);
      return temp.map(log => {
        log.data = log.raw.data;
        log.topics = log.raw.topics;
        return log;
      });
    }

    // Or reformat items in the existing array
    events.forEach(event => {
      if (event.raw) {
        event.data = event.raw.data;
        event.topics = event.raw.topics;
      }
    });

    return events;
  },

  merge() {
    const merged = {};
    const args = Array.prototype.slice.call(arguments);

    for (let i = 0; i < args.length; i++) {
      const object = args[i];
      const keys = Object.keys(object);
      for (let j = 0; j < keys.length; j++) {
        const key = keys[j];
        const value = object[key];
        merged[key] = value;
      }
    }

    return merged;
  },
  parallel(arr, callback = () => {}) {
    if (!arr.length) {
      return callback(null, []);
    }
    let index = 0;
    const results = new Array(arr.length);
    arr.forEach((fn, position) => {
      fn((err, result) => {
        if (err) {
          callback(err);
          callback = () => {};
        } else {
          index++;
          results[position] = result;
          if (index >= arr.length) {
            callback(null, results);
          }
        }
      });
    });
  },

  linkBytecode(bytecode, links) {
    Object.keys(links).forEach(library_name => {
      const library_address = links[library_name];
      const regex = new RegExp(`__${library_name}_+`, "g");

      bytecode = bytecode.replace(regex, library_address.replace("0x", ""));
    });

    return bytecode;
  },

  // Extracts optional tx params from a list of fn arguments
  getTxParams(methodABI, args) {
    const constructor = this;

    const expected_arg_count = methodABI ? methodABI.inputs.length : 0;

    tx_params = {};
    const last_arg = args[args.length - 1];

    if (
      args.length === expected_arg_count + 1 &&
      Utils.is_tx_params(last_arg)
    ) {
      tx_params = args.pop();
    }

    return Utils.merge(constructor.class_defaults, tx_params);
  },

  // Verifies that a contracts libraries have been linked correctly.
  // Throws on error
  checkLibraries() {
    const constructor = this;
    const regex = /__[^_]+_+/g;
    let unlinked_libraries = constructor.binary.match(regex);

    if (unlinked_libraries !== null) {
      unlinked_libraries = unlinked_libraries
        .map((
          name // Remove underscores
        ) => name.replace(/_/g, ""))
        .sort()
        .filter((name, index, arr) => {
          // Remove duplicates
          if (index + 1 >= arr.length) {
            return true;
          }

          return name !== arr[index + 1];
        })
        .join(", ");

      const error = `${
        constructor.contractName
      } contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of ${
        constructor.contractName
      }: ${unlinked_libraries}`;

      throw new Error(error);
    }
  },

  convertENSNames(args, methodABI, web3) {
    const { isAddress } = web3.utils;
    const ens = new ENS(web3.currentProvider);
    const convertedNames = args.map((argument, index) => {
      if (methodABI.inputs[index].type === "address") {
        // Check all address args for ENS names
        const argIsAddress = isAddress(argument);
        if (argIsAddress) return argument;
        return ens.resolver(argument).addr();
      } else if (index === methodABI.inputs.length) {
        // Check the from field on the last argument if present
        if (argument.from && !isAddress(argument.from)) {
          return ens.resolver(argument).addr();
        }
        return argument;
      } else {
        return argument;
      }
    });
    return Promise.all(convertedNames);
  },

  convertToEthersBN(original) {
    const converted = [];
    original.forEach(item => {
      // Recurse for arrays
      if (Array.isArray(item)) {
        converted.push(Utils.convertToEthersBN(item));

        // Convert Web3 BN / BigNumber
      } else if (Utils.is_big_number(item)) {
        const ethersBN = bigNumberify(item.toString());
        converted.push(ethersBN);
      } else {
        converted.push(item);
      }
    });
    return converted;
  },

  bigNumberify,

  /**
   * Multiplies an ethers.js BigNumber and a number with decimal places using
   * integer math rather than using an arbitrary floating-point library like
   * `bignumber.js`.
   * @param  {BigNumber} bignum            an ethers.js BigNumber (use bigNumberify)
   * @param  {Number}    decimal           a number which has 0+ decimal places
   * @param  {Number}    [maxPrecision=5]  the max number of signficant figures
   *                                       `decimal` can have. (default: 5)
   * @return {BigNumber}                   floor(bignum * decimal)
   */
  multiplyBigNumberByDecimal(bignum, decimal, maxPrecision) {
    if (typeof maxPrecision === "undefined") {
      maxPrecision = 5;
    }

    const significantFigures = Math.min(
      decimal.toString().length - 1, // length less one because `.`
      maxPrecision
    );

    const denominator = bigNumberify(10).pow(significantFigures);
    const numerator = Math.round(decimal * denominator);
    const secondOperand = bigNumberify(numerator).div(denominator);

    return bignum.mul(secondOperand);
  },

  // checks if given contract instance has a set provider
  checkProvider({ currentProvider, contractName }) {
    if (!currentProvider)
      throw new Error(
        `${contractName} error: Please call setProvider() first before calling new().`
      );
  },

  // verifies current network has been assigned to contract instance
  checkNetworkArtifactMatch({ networks, network_id, contractName }) {
    if (networks[network_id] == null)
      throw new Error(
        `${contractName} has not been deployed to detected network (network/artifact mismatch)`
      );
  },

  // verifies contract instance has been deployed
  checkDeployment({ isDeployed, contractName, network_id }) {
    if (!isDeployed())
      throw new Error(
        `${contractName} has not been deployed to detected network (${network_id})`
      );
  },

  // checks if provided contract address has on-chain code
  checkCode(onChainCode, contractName, address) {
    if (!onChainCode || onChainCode.replace("0x", "").replace(/0/g, "") === "")
      throw new Error(
        `Cannot create instance of ${contractName}; no code at address ${address}`
      );
  },

  // parses known contract instance networks
  parseKnownNetworks(
    { networks, currentProvider, setNetwork, network_id },
    gasLimit
  ) {
    // wrap uri matching in a promise to allow provider.send time to resolve
    // (.send call happens in BlockchainUtils.matches)
    return new Promise((accept, reject) => {
      // go through all the networks that are listed as
      // blockchain uris and see if they match
      const uris = Object.keys(networks).filter(
        network => network.indexOf("blockchain://") === 0
      );
      const matches = uris.map(uri =>
        BlockchainUtils.matches.bind(BlockchainUtils, uri, currentProvider)
      );

      Utils.parallel(matches, (err, results) => {
        if (err) reject(err);

        for (let i = 0; i < results.length; i++) {
          if (results[i]) {
            setNetwork(uris[i]);
            accept({
              id: network_id,
              blockLimit: gasLimit
            });
          }
        }
        // no match found!
        accept(false);
      });
    });
  },

  // sets a contract instance network ID
  async setInstanceNetworkID(
    TruffleContractInstance,
    chainNetworkID,
    gasLimit
  ) {
    // if chainNetworkID already present as network configuration, use it
    if (TruffleContractInstance.hasNetwork(chainNetworkID)) {
      TruffleContractInstance.setNetwork(chainNetworkID);
      return {
        id: TruffleContractInstance.network_id,
        blockLimit: gasLimit
      };
    }
    // chainNetworkID not present,
    // parse all known networks
    const matchedNetwork = await Utils.parseKnownNetworks(
      TruffleContractInstance,
      gasLimit
    );
    if (matchedNetwork) return matchedNetwork;

    // network unknown, trust the provider and use given chainNetworkID
    TruffleContractInstance.setNetwork(chainNetworkID);
    return { id: TruffleContractInstance.network_id, blockLimit: gasLimit };
  }
};

module.exports = Utils;
<commit_msg>Correctly return the options object with the changed from field in the case that the from address is an ENS name<commit_after>const debug = require("debug")("contract:utils");
const web3Utils = require("web3-utils");
const bigNumberify = require("ethers/utils/bignumber").bigNumberify;
const abi = require("web3-eth-abi");
const BlockchainUtils = require("truffle-blockchain-utils");
const reformat = require("./reformat");
const ENS = require("ethereum-ens");

const Utils = {
  is_object(val) {
    return typeof val === "object" && !Array.isArray(val);
  },

  is_big_number(val) {
    if (typeof val !== "object") return false;

    return web3Utils.isBN(val) || web3Utils.isBigNumber(val);
  },

  is_tx_params(val) {
    if (!Utils.is_object(val)) return false;
    if (Utils.is_big_number(val)) return false;

    const allowed_fields = {
      from: true,
      to: true,
      gas: true,
      gasPrice: true,
      value: true,
      data: true,
      nonce: true,
      privateFor: true
    };

    for (field_name of Object.keys(val)) {
      if (allowed_fields[field_name]) return true;
    }

    return false;
  },

  decodeLogs(_logs, isSingle) {
    const constructor = this;
    const logs = Utils.toTruffleLog(_logs, isSingle);

    return logs
      .map(log => {
        const logABI = constructor.events[log.topics[0]];

        if (logABI == null) {
          return null;
        }

        const copy = Utils.merge({}, log);

        copy.event = logABI.name;
        copy.topics = logABI.anonymous ? copy.topics : copy.topics.slice(1);

        if (copy.data === "0x") {
          copy.data = "";
        }

        const logArgs = abi.decodeLog(logABI.inputs, copy.data, copy.topics);
        copy.args = reformat.numbers.call(constructor, logArgs, logABI.inputs);

        delete copy.data;
        delete copy.topics;

        return copy;
      })
      .filter(log => log != null);
  },

  toTruffleLog(events, isSingle) {
    // Transform singletons (from event listeners) to the kind of
    // object we find on the receipt
    if (isSingle && typeof isSingle === "boolean") {
      const temp = [];
      temp.push(events);
      return temp.map(log => {
        log.data = log.raw.data;
        log.topics = log.raw.topics;
        return log;
      });
    }

    // Or reformat items in the existing array
    events.forEach(event => {
      if (event.raw) {
        event.data = event.raw.data;
        event.topics = event.raw.topics;
      }
    });

    return events;
  },

  merge() {
    const merged = {};
    const args = Array.prototype.slice.call(arguments);

    for (let i = 0; i < args.length; i++) {
      const object = args[i];
      const keys = Object.keys(object);
      for (let j = 0; j < keys.length; j++) {
        const key = keys[j];
        const value = object[key];
        merged[key] = value;
      }
    }

    return merged;
  },
  parallel(arr, callback = () => {}) {
    if (!arr.length) {
      return callback(null, []);
    }
    let index = 0;
    const results = new Array(arr.length);
    arr.forEach((fn, position) => {
      fn((err, result) => {
        if (err) {
          callback(err);
          callback = () => {};
        } else {
          index++;
          results[position] = result;
          if (index >= arr.length) {
            callback(null, results);
          }
        }
      });
    });
  },

  linkBytecode(bytecode, links) {
    Object.keys(links).forEach(library_name => {
      const library_address = links[library_name];
      const regex = new RegExp(`__${library_name}_+`, "g");

      bytecode = bytecode.replace(regex, library_address.replace("0x", ""));
    });

    return bytecode;
  },

  // Extracts optional tx params from a list of fn arguments
  getTxParams(methodABI, args) {
    const constructor = this;

    const expected_arg_count = methodABI ? methodABI.inputs.length : 0;

    tx_params = {};
    const last_arg = args[args.length - 1];

    if (
      args.length === expected_arg_count + 1 &&
      Utils.is_tx_params(last_arg)
    ) {
      tx_params = args.pop();
    }

    return Utils.merge(constructor.class_defaults, tx_params);
  },

  // Verifies that a contracts libraries have been linked correctly.
  // Throws on error
  checkLibraries() {
    const constructor = this;
    const regex = /__[^_]+_+/g;
    let unlinked_libraries = constructor.binary.match(regex);

    if (unlinked_libraries !== null) {
      unlinked_libraries = unlinked_libraries
        .map((
          name // Remove underscores
        ) => name.replace(/_/g, ""))
        .sort()
        .filter((name, index, arr) => {
          // Remove duplicates
          if (index + 1 >= arr.length) {
            return true;
          }

          return name !== arr[index + 1];
        })
        .join(", ");

      const error = `${
        constructor.contractName
      } contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of ${
        constructor.contractName
      }: ${unlinked_libraries}`;

      throw new Error(error);
    }
  },

  convertENSNames(args, methodABI, web3) {
    const { isAddress } = web3.utils;
    const ens = new ENS(web3.currentProvider);
    const convertedNames = args.map((argument, index) => {
      if (methodABI.inputs[index].type === "address") {
        // Check all address args for ENS names
        const argIsAddress = isAddress(argument);
        if (argIsAddress) return argument;
        return ens.resolver(argument).addr();
      } else if (index === methodABI.inputs.length) {
        // Check the from field on the last argument if present
        if (argument.from && !isAddress(argument.from)) {
          return ens
            .resolver(argument.from)
            .addr()
            .then(fromAddress => {
              return Object.assign({}, { from: fromAddress }, argument);
            })
            .catch(error => {
              throw error;
            });
        }
        return argument;
      } else {
        return argument;
      }
    });
    return Promise.all(convertedNames);
  },

  convertToEthersBN(original) {
    const converted = [];
    original.forEach(item => {
      // Recurse for arrays
      if (Array.isArray(item)) {
        converted.push(Utils.convertToEthersBN(item));

        // Convert Web3 BN / BigNumber
      } else if (Utils.is_big_number(item)) {
        const ethersBN = bigNumberify(item.toString());
        converted.push(ethersBN);
      } else {
        converted.push(item);
      }
    });
    return converted;
  },

  bigNumberify,

  /**
   * Multiplies an ethers.js BigNumber and a number with decimal places using
   * integer math rather than using an arbitrary floating-point library like
   * `bignumber.js`.
   * @param  {BigNumber} bignum            an ethers.js BigNumber (use bigNumberify)
   * @param  {Number}    decimal           a number which has 0+ decimal places
   * @param  {Number}    [maxPrecision=5]  the max number of signficant figures
   *                                       `decimal` can have. (default: 5)
   * @return {BigNumber}                   floor(bignum * decimal)
   */
  multiplyBigNumberByDecimal(bignum, decimal, maxPrecision) {
    if (typeof maxPrecision === "undefined") {
      maxPrecision = 5;
    }

    const significantFigures = Math.min(
      decimal.toString().length - 1, // length less one because `.`
      maxPrecision
    );

    const denominator = bigNumberify(10).pow(significantFigures);
    const numerator = Math.round(decimal * denominator);
    const secondOperand = bigNumberify(numerator).div(denominator);

    return bignum.mul(secondOperand);
  },

  // checks if given contract instance has a set provider
  checkProvider({ currentProvider, contractName }) {
    if (!currentProvider)
      throw new Error(
        `${contractName} error: Please call setProvider() first before calling new().`
      );
  },

  // verifies current network has been assigned to contract instance
  checkNetworkArtifactMatch({ networks, network_id, contractName }) {
    if (networks[network_id] == null)
      throw new Error(
        `${contractName} has not been deployed to detected network (network/artifact mismatch)`
      );
  },

  // verifies contract instance has been deployed
  checkDeployment({ isDeployed, contractName, network_id }) {
    if (!isDeployed())
      throw new Error(
        `${contractName} has not been deployed to detected network (${network_id})`
      );
  },

  // checks if provided contract address has on-chain code
  checkCode(onChainCode, contractName, address) {
    if (!onChainCode || onChainCode.replace("0x", "").replace(/0/g, "") === "")
      throw new Error(
        `Cannot create instance of ${contractName}; no code at address ${address}`
      );
  },

  // parses known contract instance networks
  parseKnownNetworks(
    { networks, currentProvider, setNetwork, network_id },
    gasLimit
  ) {
    // wrap uri matching in a promise to allow provider.send time to resolve
    // (.send call happens in BlockchainUtils.matches)
    return new Promise((accept, reject) => {
      // go through all the networks that are listed as
      // blockchain uris and see if they match
      const uris = Object.keys(networks).filter(
        network => network.indexOf("blockchain://") === 0
      );
      const matches = uris.map(uri =>
        BlockchainUtils.matches.bind(BlockchainUtils, uri, currentProvider)
      );

      Utils.parallel(matches, (err, results) => {
        if (err) reject(err);

        for (let i = 0; i < results.length; i++) {
          if (results[i]) {
            setNetwork(uris[i]);
            accept({
              id: network_id,
              blockLimit: gasLimit
            });
          }
        }
        // no match found!
        accept(false);
      });
    });
  },

  // sets a contract instance network ID
  async setInstanceNetworkID(
    TruffleContractInstance,
    chainNetworkID,
    gasLimit
  ) {
    // if chainNetworkID already present as network configuration, use it
    if (TruffleContractInstance.hasNetwork(chainNetworkID)) {
      TruffleContractInstance.setNetwork(chainNetworkID);
      return {
        id: TruffleContractInstance.network_id,
        blockLimit: gasLimit
      };
    }
    // chainNetworkID not present,
    // parse all known networks
    const matchedNetwork = await Utils.parseKnownNetworks(
      TruffleContractInstance,
      gasLimit
    );
    if (matchedNetwork) return matchedNetwork;

    // network unknown, trust the provider and use given chainNetworkID
    TruffleContractInstance.setNetwork(chainNetworkID);
    return { id: TruffleContractInstance.network_id, blockLimit: gasLimit };
  }
};

module.exports = Utils;
<|endoftext|>


<commit_before>const cme = chrome.management;
const getI18N = chrome.i18n.getMessage;

// Generate page
const $searchField = $(`<input placeholder="${ getI18N('searchTxt') }">`);
const eul = $('
');
const $options = $('
');
const $disableAllButton = $(`<button>${ getI18N('disAll') }</button>`);
const $extensionPageButton = $(`<button>${ getI18N('extensionPage') }</button>`);

$options
	.append($disableAllButton)
	.append($extensionPageButton);

$('body')
	.append($searchField)
	.append($options)
	.append(eul);

$searchField.focus();
window.scrollTo(0, 0); // fix overscroll caused by autofocus

// Generate extension list
cme.getAll(ets => {
	const listHTML = ets
	.filter(extension => extension.id !== 'pbgjpgbpljobkekbhnnmlikbbfhbhmem')
	.sort((a, b) => {
		if (a.enabled === b.enabled) {
			return a.name.localeCompare(b.name); // sort by name
		}
		return a.enabled  {
	const $extension = $(e.currentTarget).parent();
	const id = $extension.attr('id');
	const wasEnabled = !$extension.hasClass('disabled');

	cme.setEnabled(id, !wasEnabled, () => {
		$extension.toggleClass('disabled', wasEnabled);
		$extension.find('.extName').attr('title', getI18N(wasEnabled ? 'clkEnable' : 'clkDisable'));
	})
}).on('mouseup', '.ext', e => {
	if (e.which == 3) {
		cme.uninstall(e.currentTarget.id);
	}
});

cme.onUninstalled.addListener(id => {
	$(`#${id}`).remove();
});

$searchField.on('input', function () {
	const extensions = $('#extList li');
	const keywords = this.value.split(' ').filter(s => s.length);
	const hiddenExtensions = extensions.not((i, el) => {
		return keywords.every(word => el.dataset.name.includes(word));
	});
	hiddenExtensions.hide();
	extensions.not(hiddenExtensions).show();
});

// disable the default context menu
eul.on('contextmenu', () => false);

$disableAllButton.click(() => {
	if (confirm(getI18N('disableAll'))) {
		disableAll();
	}
});

$extensionPageButton.click(() => {
	chrome.tabs.create({url: 'chrome://extensions'});
});

/**
 * FUNCTIONS
 */
function getIcon(icons, size = 16) {
	// Set fallback icon
	let selectedIcon = chrome.extension.getURL('icon-puzzle.svg');

	// Get retina size if necessary
	size *= window.devicePixelRatio;

	if (icons && icons.length) {
		// Get a large icon closest to the desired size
		icons.reverse().some(icon => {
			if (icon.size < size) {
				return false;
			}
			selectedIcon = icon.url;
		});
	}
	return selectedIcon;
}

function createList(e) {
	return `

				${e.name}

			${
				e.optionsUrl ? `

				` : ``
			}

	`;
}

function disableAll() {
	cme.getAll(ets => {
		const myid = getI18N('@@extension_id');
		ets.forEach(extension => {
			if(extension.enabled && extension.id !== myid) {
				cme.setEnabled(extension.id, false);
			}
		});
		$('.ext').addClass('disabled');
	});
}
<commit_msg>Hide apps<commit_after>const cme = chrome.management;
const getI18N = chrome.i18n.getMessage;

// Generate page
const $searchField = $(`<input placeholder="${ getI18N('searchTxt') }">`);
const eul = $('
');
const $options = $('
');
const $disableAllButton = $(`<button>${ getI18N('disAll') }</button>`);
const $extensionPageButton = $(`<button>${ getI18N('extensionPage') }</button>`);

$options
	.append($disableAllButton)
	.append($extensionPageButton);

$('body')
	.append($searchField)
	.append($options)
	.append(eul);

$searchField.focus();
window.scrollTo(0, 0); // fix overscroll caused by autofocus

// Generate extension list
cme.getAll(ets => {
	const listHTML = ets
	.filter(ext => !ext.isApp && ext.id !== 'pbgjpgbpljobkekbhnnmlikbbfhbhmem')
	.sort((a, b) => {
		if (a.enabled === b.enabled) {
			return a.name.localeCompare(b.name); // sort by name
		}
		return a.enabled  {
	const $extension = $(e.currentTarget).parent();
	const id = $extension.attr('id');
	const wasEnabled = !$extension.hasClass('disabled');

	cme.setEnabled(id, !wasEnabled, () => {
		$extension.toggleClass('disabled', wasEnabled);
		$extension.find('.extName').attr('title', getI18N(wasEnabled ? 'clkEnable' : 'clkDisable'));
	})
}).on('mouseup', '.ext', e => {
	if (e.which == 3) {
		cme.uninstall(e.currentTarget.id);
	}
});

cme.onUninstalled.addListener(id => {
	$(`#${id}`).remove();
});

$searchField.on('input', function () {
	const extensions = $('#extList li');
	const keywords = this.value.split(' ').filter(s => s.length);
	const hiddenExtensions = extensions.not((i, el) => {
		return keywords.every(word => el.dataset.name.includes(word));
	});
	hiddenExtensions.hide();
	extensions.not(hiddenExtensions).show();
});

// disable the default context menu
eul.on('contextmenu', () => false);

$disableAllButton.click(() => {
	if (confirm(getI18N('disableAll'))) {
		disableAll();
	}
});

$extensionPageButton.click(() => {
	chrome.tabs.create({url: 'chrome://extensions'});
});

/**
 * FUNCTIONS
 */
function getIcon(icons, size = 16) {
	// Set fallback icon
	let selectedIcon = chrome.extension.getURL('icon-puzzle.svg');

	// Get retina size if necessary
	size *= window.devicePixelRatio;

	if (icons && icons.length) {
		// Get a large icon closest to the desired size
		icons.reverse().some(icon => {
			if (icon.size < size) {
				return false;
			}
			selectedIcon = icon.url;
		});
	}
	return selectedIcon;
}

function createList(e) {
	return `

				${e.name}

			${
				e.optionsUrl ? `

				` : ``
			}

	`;
}

function disableAll() {
	cme.getAll(ets => {
		const myid = getI18N('@@extension_id');
		ets.forEach(extension => {
			if(extension.enabled && extension.id !== myid) {
				cme.setEnabled(extension.id, false);
			}
		});
		$('.ext').addClass('disabled');
	});
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016, Geomatics and Cartographic Research Centre, Carleton
University
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 - Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 - Neither the name of the Geomatics and Cartographic Research Centre,
   Carleton University nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

;(function($,$n2) {
"use strict";

var
 _loc = function(str,args){ return $n2.loc(str,'nunaliit2',args); }
 ,DH = 'n2.widgetLayer'
 ,ALL_LAYERS = '__ALL_LAYERS__'
 ;

//--------------------------------------------------------------------------
var LayerSelectionWidget = $n2.Class({

	dispatchService: null,

	showService: null,

	sourceModelId: null,

	elemId: null,

	selectedLayersChangeEventName: null,

	selectedLayersSetEventName: null,

	availableLayersChangeEventName: null,

	availableLayers: null,

	lastSelectedLayerId: null,

	initialize: function(opts_){
		var opts = $n2.extend({
			containerId: null
			,dispatchService: null
			,showService: null
			,sourceModelId: null
		},opts_);

		var _this = this;

		this.dispatchService = opts.dispatchService;
		this.showService = opts.showService;
		this.sourceModelId = opts.sourceModelId;

		this.availableLayers = [];
		this.lastSelectedLayerId = ALL_LAYERS;

		// Set up model listener
		if( this.dispatchService ){
			// Get model info
			var modelInfoRequest = {
				type: 'modelGetInfo'
				,modelId: this.sourceModelId
				,modelInfo: null
			};
			this.dispatchService.synchronousCall(DH, modelInfoRequest);
			var sourceModelInfo = modelInfoRequest.modelInfo;

			if( sourceModelInfo
			 && sourceModelInfo.parameters
			 && sourceModelInfo.parameters.availableLayers ){
				var paramInfo = sourceModelInfo.parameters.availableLayers;
				this.availableLayersChangeEventName = paramInfo.changeEvent;

				if( paramInfo.value ){
					this.availableLayers = paramInfo.value;
				};
			};

			if( sourceModelInfo
			 && sourceModelInfo.parameters
			 && sourceModelInfo.parameters.selectedLayers ){
				var paramInfo = sourceModelInfo.parameters.selectedLayers;
				this.selectedLayersChangeEventName = paramInfo.changeEvent;
				this.selectedLayersSetEventName = paramInfo.setEvent;

				if( paramInfo.value ){
					this.selectedLayers = paramInfo.value;
				};
			};

			var fn = function(m, addr, dispatcher){
				_this._handle(m, addr, dispatcher);
			};

			if( this.availableLayersChangeEventName ){
				this.dispatchService.register(DH, this.availableLayersChangeEventName, fn);
			};

			if( this.selectedLayersChangeEventName ){
				this.dispatchService.register(DH, this.selectedLayersChangeEventName, fn);
			};
		};

		// Get container
		var containerId = opts.containerId;
		if( !containerId ){
			throw new Error('containerId must be specified');
		};
		var $container = $('#'+containerId);

		this.elemId = $n2.getUniqueId();

		$('<div>')
			.attr('id',this.elemId)
			.addClass('n2layerSelectionWidget')
			.appendTo($container);

		this._availableLayersUpdated();

		$n2.log('LayerSelectionWidget', this);
	},

	_getElem: function(){
		return $('#'+this.elemId);
	},

	_availableLayersUpdated: function(){
		var _this = this;

		var $elem = this._getElem();
		$elem.empty();

		var $selector = $('<select>')
			.appendTo($elem)
			.change(function(){
				_this._selectionChanged();
			});

		$('<option>')
			.text( _loc('All Layers') )
			.val(ALL_LAYERS)
			.appendTo($selector);

		var currentFound = null;
		for(var i=0,e=this.availableLayers.length; i<e; ++i){
			var layerId = this.availableLayers[i];

			var $option = $('<option>')
				.text(layerId)
				.val(layerId)
				.appendTo($selector);

			if( layerId === this.lastSelectedLayerId ){
				currentFound = layerId;
			};

			if( this.showService ){
				this.showService.printLayerName($option, layerId);
			};
		};

		if( currentFound ){
			$selector.val(currentFound);
			//$n2.log('selector => '+currentFound);
		} else {
			$selector.val(ALL_LAYERS);
			//$n2.log('selector => empty');
		};

		// Select current
		this._selectionChanged();
	},

	// This is called when the selected option within <select> is changed
	_selectionChanged: function(){
		var $elem = this._getElem();
		var $selector = $elem.find('select');
		var val = $selector.val();
		if( ALL_LAYERS === val ){
			var selectedLayerIds = [];
			this.availableLayers.forEach(function(layerId){
				selectedLayerIds.push(layerId);
			});

			this.dispatchService.send(DH,{
				type: this.selectedLayersSetEventName
				,value: selectedLayerIds
			});

		} else {
			var selectedLayerIds = [];
			selectedLayerIds.push(val);

			this.dispatchService.send(DH,{
				type: this.selectedLayersSetEventName
				,value: selectedLayerIds
			});
		};
	},

	_selectedLayersUpdated: function(){
		var $elem = this._getElem();
		var $selector = $elem.find('select');
		$selector.val( this.lastSelectedLayerId );
	},

	_handle: function(m, addr, dispatcher){
		var _this = this;

		if( this.availableLayersChangeEventName === m.type ){
			if( m.value ){
				this.availableLayers = m.value;

				this._availableLayersUpdated();
			};

		} else if( this.selectedLayersChangeEventName === m.type ){
			if( m.value ){
				var selectedMap = {};
				var selectedLayerId = undefined;
				m.value.forEach(function(layerId){
					selectedMap[layerId] = true;
					selectedLayerId = layerId;
				});

				// Detect all layers
				var allLayers = true;
				this.availableLayers.forEach(function(layerId){
					if( !selectedMap[layerId] ){
						allLayers = false;
					};
				});

				if( allLayers ){
					this.lastSelectedLayerId = ALL_LAYERS;
				} else {
					this.lastSelectedLayerId = selectedLayerId;
				};

				this._selectedLayersUpdated();
			};
		};
	}
});

//--------------------------------------------------------------------------
function HandleWidgetAvailableRequests(m){
	if( m.widgetType === 'layerSelectionWidget' ){
		if( $.fn.slider ) {
			m.isAvailable = true;
		};
    };
};

//--------------------------------------------------------------------------
function HandleWidgetDisplayRequests(m){
	if( m.widgetType === 'layerSelectionWidget' ){
		var widgetOptions = m.widgetOptions;
		var containerId = m.containerId;
		var config = m.config;

		var options = {};

		if( widgetOptions ){
			for(var key in widgetOptions){
				var value = widgetOptions[key];
				options[key] = value;
			};
		};

		options.containerId = containerId;

		if( config && config.directory ){
			options.dispatchService = config.directory.dispatchService;
			options.showService = config.directory.showService;
		};

		new LayerSelectionWidget(options);
    };
};

//--------------------------------------------------------------------------
$n2.widgetTime = {
	LayerSelectionWidget: LayerSelectionWidget
	,HandleWidgetAvailableRequests: HandleWidgetAvailableRequests
	,HandleWidgetDisplayRequests: HandleWidgetDisplayRequests
};

})(jQuery,nunaliit2);
<commit_msg>timeline widget bug fix<commit_after>/*
Copyright (c) 2016, Geomatics and Cartographic Research Centre, Carleton
University
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 - Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 - Neither the name of the Geomatics and Cartographic Research Centre,
   Carleton University nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

;(function($,$n2) {
"use strict";

var
 _loc = function(str,args){ return $n2.loc(str,'nunaliit2',args); }
 ,DH = 'n2.widgetLayer'
 ,ALL_LAYERS = '__ALL_LAYERS__'
 ;

//--------------------------------------------------------------------------
var LayerSelectionWidget = $n2.Class({

	dispatchService: null,

	showService: null,

	sourceModelId: null,

	elemId: null,

	selectedLayersChangeEventName: null,

	selectedLayersSetEventName: null,

	availableLayersChangeEventName: null,

	availableLayers: null,

	lastSelectedLayerId: null,

	initialize: function(opts_){
		var opts = $n2.extend({
			containerId: null
			,dispatchService: null
			,showService: null
			,sourceModelId: null
		},opts_);

		var _this = this;

		this.dispatchService = opts.dispatchService;
		this.showService = opts.showService;
		this.sourceModelId = opts.sourceModelId;

		this.availableLayers = [];
		this.lastSelectedLayerId = ALL_LAYERS;

		// Set up model listener
		if( this.dispatchService ){
			// Get model info
			var modelInfoRequest = {
				type: 'modelGetInfo'
				,modelId: this.sourceModelId
				,modelInfo: null
			};
			this.dispatchService.synchronousCall(DH, modelInfoRequest);
			var sourceModelInfo = modelInfoRequest.modelInfo;

			if( sourceModelInfo
			 && sourceModelInfo.parameters
			 && sourceModelInfo.parameters.availableLayers ){
				var paramInfo = sourceModelInfo.parameters.availableLayers;
				this.availableLayersChangeEventName = paramInfo.changeEvent;

				if( paramInfo.value ){
					this.availableLayers = paramInfo.value;
				};
			};

			if( sourceModelInfo
			 && sourceModelInfo.parameters
			 && sourceModelInfo.parameters.selectedLayers ){
				var paramInfo = sourceModelInfo.parameters.selectedLayers;
				this.selectedLayersChangeEventName = paramInfo.changeEvent;
				this.selectedLayersSetEventName = paramInfo.setEvent;

				if( paramInfo.value ){
					this.selectedLayers = paramInfo.value;
				};
			};

			var fn = function(m, addr, dispatcher){
				_this._handle(m, addr, dispatcher);
			};

			if( this.availableLayersChangeEventName ){
				this.dispatchService.register(DH, this.availableLayersChangeEventName, fn);
			};

			if( this.selectedLayersChangeEventName ){
				this.dispatchService.register(DH, this.selectedLayersChangeEventName, fn);
			};
		};

		// Get container
		var containerId = opts.containerId;
		if( !containerId ){
			throw new Error('containerId must be specified');
		};
		var $container = $('#'+containerId);

		this.elemId = $n2.getUniqueId();

		$('<div>')
			.attr('id',this.elemId)
			.addClass('n2layerSelectionWidget')
			.appendTo($container);

		this._availableLayersUpdated();

		$n2.log('LayerSelectionWidget', this);
	},

	_getElem: function(){
		return $('#'+this.elemId);
	},

	_availableLayersUpdated: function(){
		var _this = this;

		var $elem = this._getElem();
		$elem.empty();

		var $selector = $('<select>')
			.appendTo($elem)
			.change(function(){
				_this._selectionChanged();
			});

		$('<option>')
			.text( _loc('All Layers') )
			.val(ALL_LAYERS)
			.appendTo($selector);

		var currentFound = null;
		for(var i=0,e=this.availableLayers.length; i<e; ++i){
			var layerId = this.availableLayers[i];

			var $option = $('<option>')
				.text(layerId)
				.val(layerId)
				.appendTo($selector);

			if( layerId === this.lastSelectedLayerId ){
				currentFound = layerId;
			};

			if( this.showService ){
				this.showService.printLayerName($option, layerId);
			};
		};

		if( currentFound ){
			$selector.val(currentFound);
			//$n2.log('selector => '+currentFound);
		} else {
			$selector.val(ALL_LAYERS);
			//$n2.log('selector => empty');
		};

		// Select current
		this._selectionChanged();
	},

	// This is called when the selected option within <select> is changed
	_selectionChanged: function(){
		var $elem = this._getElem();
		var $selector = $elem.find('select');
		var val = $selector.val();
		if( ALL_LAYERS === val ){
			var selectedLayerIds = [];
			this.availableLayers.forEach(function(layerId){
				selectedLayerIds.push(layerId);
			});

			this.dispatchService.send(DH,{
				type: this.selectedLayersSetEventName
				,value: selectedLayerIds
			});

		} else {
			var selectedLayerIds = [];
			selectedLayerIds.push(val);

			this.dispatchService.send(DH,{
				type: this.selectedLayersSetEventName
				,value: selectedLayerIds
			});
		};
	},

	_selectedLayersUpdated: function(){
		var $elem = this._getElem();
		var $selector = $elem.find('select');
		$selector.val( this.lastSelectedLayerId );
	},

	_handle: function(m, addr, dispatcher){
		var _this = this;

		if( this.availableLayersChangeEventName === m.type ){
			if( m.value ){
				this.availableLayers = m.value;

				this._availableLayersUpdated();
			};

		} else if( this.selectedLayersChangeEventName === m.type ){
			if( m.value ){
				var selectedMap = {};
				var selectedLayerId = undefined;
				m.value.forEach(function(layerId){
					selectedMap[layerId] = true;
					selectedLayerId = layerId;
				});

				// Detect all layers
				var allLayers = true;
				this.availableLayers.forEach(function(layerId){
					if( !selectedMap[layerId] ){
						allLayers = false;
					};
				});

				if( allLayers ){
					this.lastSelectedLayerId = ALL_LAYERS;
				} else {
					this.lastSelectedLayerId = selectedLayerId;
				};

				this._selectedLayersUpdated();
			};
		};
	}
});

//--------------------------------------------------------------------------
function HandleWidgetAvailableRequests(m){
	if( m.widgetType === 'layerSelectionWidget' ){
		if( $.fn.slider ) {
			m.isAvailable = true;
		};
    };
};

//--------------------------------------------------------------------------
function HandleWidgetDisplayRequests(m){
	if( m.widgetType === 'layerSelectionWidget' ){
		var widgetOptions = m.widgetOptions;
		var containerId = m.containerId;
		var config = m.config;

		var options = {};

		if( widgetOptions ){
			for(var key in widgetOptions){
				var value = widgetOptions[key];
				options[key] = value;
			};
		};

		options.containerId = containerId;

		if( config && config.directory ){
			options.dispatchService = config.directory.dispatchService;
			options.showService = config.directory.showService;
		};

		new LayerSelectionWidget(options);
    };
};

//--------------------------------------------------------------------------
$n2.widgetLayer = {
	LayerSelectionWidget: LayerSelectionWidget
	,HandleWidgetAvailableRequests: HandleWidgetAvailableRequests
	,HandleWidgetDisplayRequests: HandleWidgetDisplayRequests
};

})(jQuery,nunaliit2);
<|endoftext|>


<commit_before>app.factory('User', function($firebase, FIREBASE_URL, Auth) {
  var firebaseRef = new Firebase(FIREBASE_URL + 'users');
  var users = $firebaseSimpleLogin(firebaseRef);

  var User = {
    create : function(authUser, userInfo) {

    }
  }

});<commit_msg>Deleted users.js service<commit_after><|endoftext|>


<commit_before>Ajax.InPlaceCollectionEditor.prototype.__createEditField = Ajax.InPlaceCollectionEditor.prototype.createEditField;
Ajax.InPlaceCollectionEditor.prototype.__onSubmit = Ajax.InPlaceCollectionEditor.prototype.onSubmit;
Ajax.InPlaceCollectionEditor.prototype = Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
    createEditField: function() {
        if (this.options.callback) { var callbackSet = this.options.callback };
        this.__createEditField();
        if (callbackSet) { this.options.callback = callbackSet;    };
    },
    onSubmit: function(){
		if(this.editField.value=="" && this.options.requiredIndicator!=null && this.options.requiredIndicator==true){
			alert("Its a required field. Please enter a value.");
			if (arguments.length > 1) {
		      Event.stop(arguments[0]);
		    }
		    return false;
		}else{
        	this.__onSubmit();
        }
    },

});

//InPlaceEditor extension that adds a 'click to edit' text when the field is
//empty.
Ajax.InPlaceEditor.prototype.__onSubmit = Ajax.InPlaceEditor.prototype.onSubmit;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {
    onSubmit: function(){
		if(this.editField.value=="" && this.options.requiredIndicator!=null && this.options.requiredIndicator==true){
			alert("Its a required field. Please enter a value.");
			if (arguments.length > 1) {
		      Event.stop(arguments[0]);
		    }
		    return false;
		}else{
        	this.__onSubmit();
        }
    },
});

Autocompleter.Base.prototype.__onBlur = Autocompleter.Base.prototype.onBlur;
Autocompleter.Base.prototype = Object.extend(Autocompleter.Base.prototype, {
	onBlur: function(){
		//getting the id of the elmt...replacing"-input" with "-hidden" to get the hidden var
		//and re-setting the entered text with "" if the hidden var contains no value.
		//the hidden value will contain a val only if something is selected
		//from the auto-completer drop-down.
		//so when the user enters junk literals in the auto-completer
		//and tries to submit or clicks elsewhere the onblur clears the textbox.
		if(!this.options.isFreeTextAllowed){
			var hiddenElmtId = this.element.id.substring(0, this.element.id.lastIndexOf('-input')) + "-hidden";
			if($(hiddenElmtId) != null ){
				if($(hiddenElmtId).value == null || $(hiddenElmtId).value == '')
					$(this.element.id).value="Invalid Text Entered";
			}
		}

		this.__onBlur();
	},
});

Autocompleter.Base.prototype.__onKeyPress = Autocompleter.Base.prototype.onKeyPress;
Autocompleter.Base.prototype = Object.extend(Autocompleter.Base.prototype, {
	onKeyPress: function(event) {
	    if(this.active)
	      switch(event.keyCode) {
	       case Event.KEY_TAB:
	       case Event.KEY_RETURN:
	         this.selectEntry();
	         Event.stop(event);
	       case Event.KEY_ESC:
	         this.hide();
	         this.active = false;
	         Event.stop(event);
	         return;
	       case Event.KEY_LEFT:
	       case Event.KEY_RIGHT:
	         return;
	       case Event.KEY_UP:
	         this.markPrevious();
	         this.render();
	         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
	         return;
	       case Event.KEY_DOWN:
	         this.markNext();
	         this.render();
	         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
	         return;
	      }
	     else
	       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
	         (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;

	    this.changed = true;
	    this.hasFocus = true;

	    //getting the id of the elmt...replacing"-input" with "-hidden" to get the hidden var
	    //and re-setting it to "" so that the user cannot select something from the autocompleter
	    //drop down and then modify it and submit the changed text with the
	    //previously selected id.
		if(this.options.isFreeTextAllowed != null && !this.options.isFreeTextAllowed){
			var hiddenElmtId = this.element.id.substring(0, this.element.id.lastIndexOf('-input')) + "-hidden";
			if($(hiddenElmtId) != null ){
				$(hiddenElmtId).value="";
	    	}
	    }

	    if(this.observer) clearTimeout(this.observer);
	      this.observer =
	        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
	  },
});

<commit_msg>Changed the message to blank so the validators can catch the empty field<commit_after>Ajax.InPlaceCollectionEditor.prototype.__createEditField = Ajax.InPlaceCollectionEditor.prototype.createEditField;
Ajax.InPlaceCollectionEditor.prototype.__onSubmit = Ajax.InPlaceCollectionEditor.prototype.onSubmit;
Ajax.InPlaceCollectionEditor.prototype = Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
    createEditField: function() {
        if (this.options.callback) { var callbackSet = this.options.callback };
        this.__createEditField();
        if (callbackSet) { this.options.callback = callbackSet;    };
    },
    onSubmit: function(){
		if(this.editField.value=="" && this.options.requiredIndicator!=null && this.options.requiredIndicator==true){
			alert("Its a required field. Please enter a value.");
			if (arguments.length > 1) {
		      Event.stop(arguments[0]);
		    }
		    return false;
		}else{
        	this.__onSubmit();
        }
    },

});

//InPlaceEditor extension that adds a 'click to edit' text when the field is
//empty.
Ajax.InPlaceEditor.prototype.__onSubmit = Ajax.InPlaceEditor.prototype.onSubmit;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {
    onSubmit: function(){
		if(this.editField.value=="" && this.options.requiredIndicator!=null && this.options.requiredIndicator==true){
			alert("Its a required field. Please enter a value.");
			if (arguments.length > 1) {
		      Event.stop(arguments[0]);
		    }
		    return false;
		}else{
        	this.__onSubmit();
        }
    },
});

Autocompleter.Base.prototype.__onBlur = Autocompleter.Base.prototype.onBlur;
Autocompleter.Base.prototype = Object.extend(Autocompleter.Base.prototype, {
	onBlur: function(){
		//getting the id of the elmt...replacing"-input" with "-hidden" to get the hidden var
		//and re-setting the entered text with "" if the hidden var contains no value.
		//the hidden value will contain a val only if something is selected
		//from the auto-completer drop-down.
		//so when the user enters junk literals in the auto-completer
		//and tries to submit or clicks elsewhere the onblur clears the textbox.
		if(!this.options.isFreeTextAllowed){
			var hiddenElmtId = this.element.id.substring(0, this.element.id.lastIndexOf('-input')) + "-hidden";
			if($(hiddenElmtId) != null ){
				if($(hiddenElmtId).value == null || $(hiddenElmtId).value == '')
					$(this.element.id).value="";
			}
		}

		this.__onBlur();
	},
});

Autocompleter.Base.prototype.__onKeyPress = Autocompleter.Base.prototype.onKeyPress;
Autocompleter.Base.prototype = Object.extend(Autocompleter.Base.prototype, {
	onKeyPress: function(event) {
	    if(this.active)
	      switch(event.keyCode) {
	       case Event.KEY_TAB:
	       case Event.KEY_RETURN:
	         this.selectEntry();
	         Event.stop(event);
	       case Event.KEY_ESC:
	         this.hide();
	         this.active = false;
	         Event.stop(event);
	         return;
	       case Event.KEY_LEFT:
	       case Event.KEY_RIGHT:
	         return;
	       case Event.KEY_UP:
	         this.markPrevious();
	         this.render();
	         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
	         return;
	       case Event.KEY_DOWN:
	         this.markNext();
	         this.render();
	         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
	         return;
	      }
	     else
	       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
	         (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;

	    this.changed = true;
	    this.hasFocus = true;

	    //getting the id of the elmt...replacing"-input" with "-hidden" to get the hidden var
	    //and re-setting it to "" so that the user cannot select something from the autocompleter
	    //drop down and then modify it and submit the changed text with the
	    //previously selected id.
		if(this.options.isFreeTextAllowed != null && !this.options.isFreeTextAllowed){
			var hiddenElmtId = this.element.id.substring(0, this.element.id.lastIndexOf('-input')) + "-hidden";
			if($(hiddenElmtId) != null ){
				$(hiddenElmtId).value="";
	    	}
	    }

	    if(this.observer) clearTimeout(this.observer);
	      this.observer =
	        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
	  },
});

<|endoftext|>


<commit_before>// var messageService = new ChromeExtensionMessageService(true);

/*angular.module('podstationBackgroundApp').factory('messageService', function() {
	return messageService;
});*/<commit_msg>Removal of unused code<commit_after><|endoftext|>


<commit_before>const Join = () => {
  return (

Bli med i linjeforeningen!

Alle informatikere er med i linjeforeningen. Gå videre til hovedsiden for å lage din brukerkonto på Online sine systemer.

Har du lyst til å gjøre studietiden til informatikere enda bedre? Som komitemedlem i Online blir du del av en familie du aldri vil glemme. Vi tilbyr utfordrende og spennende verv i et meget sosialt miljø med stor takhøyde.

Les mer om de ulike komiteene, linjeforeningen og mye mer på vår Wiki.

  );
};

export default Join;
<commit_msg>Update join link text<commit_after>const Join = () => {
  return (

Bli med i linjeforeningen!

Alle informatikere er med i linjeforeningen. Gå videre til hovedsiden for å lage din brukerkonto på Online sine systemer.

Har du lyst til å gjøre studietiden til informatikere enda bedre? Som komitemedlem i Online blir du del av en familie du aldri vil glemme. Vi tilbyr utfordrende og spennende verv i et meget sosialt miljø med stor takhøyde.

Les mer om de ulike komiteene, linjeforeningen og mye mer på nettsidene våre.

  );
};

export default Join;
<|endoftext|>


<commit_before>var net = require('net');

var tcpServer = net.createServer(),
    clientList = [];

tcpServer.on('connection', function(client) {
  client.name = client.remoteAddress + ':' + client.remotePort
  client.write('Hi ' + client.name + '!\n');

  clientList.push(client);

  client.on('data', function(data) {
    var buffer = Date.now() + data;
    broadcast(buffer, client);
  });

  client.on('end', function() {
    clientList.splice(clientList.indexOf(client), 1);
  });
});

function broadcast(message, client) {
  var cleanup = [];
  for (var i = 0;i < clientList.length; i += 1) {
    if (client !== clientList[i]) {
      if (clientList[i].writable) {
        clientList[i].write(client.name + " says " + message);
      } else {
        cleanup.push(clientList[i]);
        clientList[i].destroy();
      }
    }
  }
  for (i = 0;i < cleanup.length; i += 1) {
    clientList.splice(clientList.indexOf(cleanup[i]), 1);
  }
}

tcpServer.listen(3000);<commit_msg>self write<commit_after>var net = require('net');

var tcpServer = net.createServer(),
    clientList = [];

tcpServer.on('connection', function(client) {
  client.name = client.remoteAddress + ':' + client.remotePort
  client.write('Hi ' + client.name + '!\n');

  clientList.push(client);

  client.on('data', function(data) {
    var buffer = Date.now() + data;
    broadcast(buffer, client);
  });

  client.on('end', function() {
    clientList.splice(clientList.indexOf(client), 1);
  });
});

function broadcast(message, client) {
  var cleanup = [];
  for (var i = 0;i < clientList.length; i += 1) {
    if (client !== clientList[i]) {
      if (clientList[i].writable) {
        clientList[i].write(message);
      } else {
        cleanup.push(clientList[i]);
        clientList[i].destroy();
      }
    }
    else {
      client.write(message);
    }
  }
  for (i = 0;i < cleanup.length; i += 1) {
    clientList.splice(clientList.indexOf(cleanup[i]), 1);
  }
}

tcpServer.listen(3000);<|endoftext|>


<commit_before>
goog.provide('colab.install');

/**
 * OAuth 2.0 scope for installing Drive Apps.
 * @const
 */
colab.install.OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive.install';

/** @const */
colab.install.FILE_SCOPE = 'https://www.googleapis.com/auth/drive';

/**
 * Google cloud services client id. Found in the project console for CoLab
 * Sandbox.
 *
 * @type {string}
 */
colab.install.CLIENT_ID = '26410270374-q0d0ap400g3mescci580rj5449tg2iq9' +
    '.apps.googleusercontent.com';

/**
 * Installs the Colaboratory App on Google Drive.
 * @param {boolean} immediate Whether to return immediately or show prompt
 * @param {Function} callback Callback for success or failure
 */
colab.install.install = function(immediate, callback) {
  gapi.load('auth:client', function() {
    // Special procedure for when in Chrome App mode.
    if (colab.app.appMode) {
      colab.app.authorize(immediate, callback);
      return;
    }

    // Otherwise, using standard OAuth flow.
    gapi.auth.authorize({
      client_id: colab.install.CLIENT_ID,
      scope: [colab.install.OAUTH_SCOPE,
              colab.install.FILE_SCOPE],
      immediate: immediate
    }, callback);
  });
};
<commit_msg>Update install.js<commit_after>
goog.provide('colab.install');

/**
 * OAuth 2.0 scope for installing Drive Apps.
 * @const
 */
colab.install.OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive.install';

/** @const */
colab.install.FILE_SCOPE = 'https://www.googleapis.com/auth/drive';

/**
 * Google cloud services client id. Found in the project console for CoLab
 * Sandbox.
 *
 * @type {string}
 */
colab.install.CLIENT_ID = '24495343215-m2uip5p987oi948dikp8khomucgt1b5h' +
    '.apps.googleusercontent.com';

/**
 * Installs the Colaboratory App on Google Drive.
 * @param {boolean} immediate Whether to return immediately or show prompt
 * @param {Function} callback Callback for success or failure
 */
colab.install.install = function(immediate, callback) {
  gapi.load('auth:client', function() {
    // Special procedure for when in Chrome App mode.
    if (colab.app.appMode) {
      colab.app.authorize(immediate, callback);
      return;
    }

    // Otherwise, using standard OAuth flow.
    gapi.auth.authorize({
      client_id: colab.install.CLIENT_ID,
      scope: [colab.install.OAUTH_SCOPE,
              colab.install.FILE_SCOPE],
      immediate: immediate
    }, callback);
  });
};
<|endoftext|>