<commit_before>/*
 Copyright 2016 - 2018 by Jan Dockx

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict'

const ContractError = require('./ContractError')
const util = require('../_private/util')

const displayNamePrefix = 'contract function '

// noinspection ParameterNamingConventionJS
/**
 * Abstract definition of a function contract.
 *
 * An AbstractContract consists of an array of preconditions, an array of nominal postconditions,
 * and an array of exceptional postconditions.
 *
 * The conditions are functions whose result is interpreted as a booleany value.
 * The conditions are called with the same `this` and arguments as the functional call in which they are
 * verified. When verifying nominal postconditions, the result of the function call is added as extra argument.
 * When verifying exceptional postconditions, the exception thrown by the function call is added as extra argument.
 * Finally, a version of the contract function bound to `this` is supplied as final parameter when verifying
 * nominal and exceptional postconditions. This function reference can be used in contracts that use recursion.
 *
 * Furthermore, an instance contains a `location` property, which is a line of text
 * that refers to the source code where the contract was created. For internal contracts, this is
 * `AbstractContract.internalLocation.
 *
 * The `_location` argument is for internal use, and might be removed.
 *
 * @constructor
 */
function AbstractContract (kwargs, /* Object? */ _location) {
  util.pre(() => !!kwargs)
  util.pre(() => !kwargs.pre || util.typeOf(kwargs.pre) === 'array')
  util.pre(() => !kwargs.post || util.typeOf(kwargs.post) === 'array')
  util.pre(() => !kwargs.exception || util.typeOf(kwargs.exception) === 'array')
  util.pre(() =>
    !_location ||
    _location === AbstractContract.internalLocation ||
    typeof _location === 'string'
  )

  const self = this

  /* This cannot be defined in the prototype. The `self` is the contract, not the `this`. When this function is called
     as a method of a random object, that random object is the `this`, not this contract. */
  function abstract () { throw new AbstractContract.AbstractError(self, util.callerStack()) }

  const location = _location || util.callerLocation(1)
  AbstractContract.bless(abstract, self, abstract, location)
  util.setAndFreezeProperty(self, '_pre', Object.freeze(kwargs.pre ? kwargs.pre.slice() : []))
  util.setAndFreezeProperty(self, '_post', Object.freeze(kwargs.post ? kwargs.post.slice() : []))
  util.setAndFreezeProperty(self, '_exception', Object.freeze(kwargs.exception ? kwargs.exception.slice() : []))
  util.setAndFreezeProperty(self, 'location', Object.freeze(location))
  util.setAndFreezeProperty(self, 'abstract', abstract)
}

/**
 * Object to be used as location for contracts and implementations that are generated inside this library.
 */
AbstractContract.internalLocation = Object.freeze({
  toString: function () { return 'INTERNAL' }
})

AbstractContract.prototype = {
  constructor: AbstractContract,
  _pre: null,
  _post: null,
  _exception: null,
  isImplementedBy: function (f) {
    return AbstractContract.isAGeneralContractFunction(f) && f.contract === this
  }
}
util.defineFrozenReadOnlyArrayProperty(AbstractContract.prototype, 'pre', '_pre')
util.defineFrozenReadOnlyArrayProperty(AbstractContract.prototype, 'post', '_post')
util.defineFrozenReadOnlyArrayProperty(AbstractContract.prototype, 'exception', '_exception')
util.setAndFreezeProperty(AbstractContract.prototype, 'location', AbstractContract.internalLocation)
util.setAndFreezeProperty(AbstractContract.prototype, 'abstract', null)

AbstractContract.displayNamePrefix = displayNamePrefix

/**
 * Return a string that is a sensible display name for the given function as a contract function.
 */
AbstractContract.contractFunctionDisplayName = function (f) {
  util.pre(() => util.typeOf(f) === 'function')

  return displayNamePrefix +
         (f.name ||
            (f.implementation && (f.implementation.displayName || f.implementation.name)) ||
            '<<anonymous>>')
}

/**
 * This function is intended to be used as the bind function of contract functions. It makes sure
 * that, when applied to a contract function, the result
 * [is also a contract function]{@linkplain AbstractContract#isAContractFunction}.
 * The bind aspect of the functionality is the same as {@link Function#prototype#bind}.
 * The implementation of the resulting contract function is also bound in the same
 * way as the resulting contract function itself.
 */
AbstractContract.bindContractFunction = function bind () {
  util.pre(() => AbstractContract.isAGeneralContractFunction(this))

  const bound = Function.prototype.bind.apply(this, arguments)
  const boundImplementation = Function.prototype.bind.apply(this.implementation, arguments)
  AbstractContract.bless(bound, this.contract, boundImplementation, this.location)
  return bound
}

/**
 * A General Contract Function is an implementation of an AbstractContract. This function verifies whether a function
 * given as a parameter is a General Contract Function.
 *
 * To be a General Contract Function, the subject must
 *

 *
be a function,

 *
have a frozen `contract` property that refers to a AbstractContract,

 *
have a frozen `implementation` property that refers to a function (which realizes the contract),

 *
have a frozen `location` property, that has a value,

 *
have a frozen `bind` property, which is {@link AbstractContract.bindContractFunction}, and

 *
have a `displayName` that is a contract function display name, which is a string that gives
 *     information for a programmer to understand which contract function this is, and

 *
if the `implementation` function has a `prototype`, have a `prototype` property,
 *

 *
that is an object,

 *
that has a `constructor` property that is the contract function, and

 *
that has `f.implementation.prototype` in its prototype chain, or is equal to it.
 *

 *

 */
AbstractContract.isAGeneralContractFunction = function (f) {
  // Apart from this, we expect f to have a name. But it is controlled by the JavaScript engine, and we cannot
  // freeze it, and not guaranteed in all engines.
  return util.typeOf(f) === 'function' &&
         util.isFrozenOwnProperty(f, 'contract') &&
         f.contract instanceof AbstractContract &&
         util.isFrozenOwnProperty(f, 'implementation') &&
         util.typeOf(f.implementation) === 'function' &&
         util.isFrozenOwnProperty(f, 'location') &&
         util.isAStackLocation(f.location) &&
         f.displayName === AbstractContract.contractFunctionDisplayName(f) &&
         util.isFrozenOwnProperty(f, 'bind') &&
         f.bind === AbstractContract.bindContractFunction &&
         (!f.implementation.hasOwnProperty('prototype') ||
             (util.typeOf(f.prototype) === 'object' &&
                 f.prototype.constructor === f &&
                 (f.prototype === f.implementation.prototype || f.prototype instanceof f.implementation)))
}

/**
 * A Contract Function is an implementation of a Contract. This function verifies whether a function
 * given as a parameter is a Contract Function.
 *
 * To be a Contract Function, the subject must
 *

 *
be a [general contract function]{@linkplain #isAGeneralContractFunction()},

 *
have a frozen `location` property, which is a string that represents a location in source code,
 *     outside this library.

 *

 */
AbstractContract.isAContractFunction = function (f) {
  return AbstractContract.isAGeneralContractFunction(f) && util.isAStackLocation(f.location)
}

/**
 * Helper function that transforms any function given as contractFunction
 * into a [contract function]{@linkplain AbstractContract#isAContractFunction}
 * for the given parameters.
 * If {@code implFunction.prototype} exists, the {@code contractFunction.prototype} is changed to
 * an object that refers to {@code contractFunction} as {@code contractFunction.prototype.constructor},
 * is otherwise empty, and has {@code implFunction.prototype} as prototype.
 *
 * @param contractFunction {Function} the regular {Function} to be transformed into a contract function
 * @param contract {AbstractContract} the contract contractFunction is a realisation of
 * @param implFunction {Function} the function that is used in contractFunction
 *                     to realize the postconditions of contract under its preconditions
 * @param location {String} the location outside this library that the resulting
 *                          [contract function]{@linkplain AbstractContract#isAContractFunction} will carry,
 *                          that says where it is defined.
 */
AbstractContract.bless = function bless (contractFunction, contract, implFunction, location) {
  util.pre(() => util.typeOf(contractFunction) === 'function')
  // noinspection JSUnresolvedVariable
  util.pre(() => !contractFunction.contract)
  // noinspection JSUnresolvedVariable
  util.pre(() => !contractFunction.implementation)
  // noinspection JSUnresolvedVariable
  util.pre(() => !contractFunction.location)
  util.pre(() => contractFunction.bind === Function.prototype.bind)
  util.pre(() => contract instanceof AbstractContract)
  util.pre(() => util.typeOf(implFunction) === 'function')
  util.pre(() => location === AbstractContract.internalLocation || util.isAStackLocation(location))

  util.setAndFreezeProperty(contractFunction, 'contract', contract)
  util.setAndFreezeProperty(contractFunction, 'implementation', implFunction)
  util.setAndFreezeProperty(contractFunction, 'location', location)
  util.setAndFreezeProperty(contractFunction, 'bind', AbstractContract.bindContractFunction)
  if (implFunction.hasOwnProperty('prototype')) {
    contractFunction.prototype = Object.create(implFunction.prototype)
    util.setAndFreezeProperty(contractFunction.prototype, 'constructor', contractFunction)
  }
  util.defineFrozenDerivedProperty(
    contractFunction,
    'displayName',
    function () { return AbstractContract.contractFunctionDisplayName(this) }
  )
}

/**
 * Function that always returns false.
 */
AbstractContract.falseCondition = function () { return false }

/**
 * Singleton array of {@linkplain AbstractContract#falseCondition}. Can be used the clearly signal
 * that a function should never throw exceptions, or never end nominally, or should never be called,
 * because the preconditions will always fail.
 */
AbstractContract.mustNotHappen = [AbstractContract.falseCondition]

/**
 * The most general function AbstractContract. This has the most strict preconditions (nothing is allowed), which can
 * be weakened by specializations, and the most general nominal and exceptional postconditions (anything goes),
 * which can be strengthened by specializations.
 */
AbstractContract.root = new AbstractContract(
  {
    pre: AbstractContract.mustNotHappen,
    post: [],
    exception: []
  },
  AbstractContract.internalLocation
)

const message = 'an abstract function cannot be executed'

/**
 * Thrown when an abstract method is called. You shouldn't.
 *
 * @constructor
 */
function AbstractError (contract, rawStack) {
  util.pre(() => contract instanceof AbstractContract)
  util.pre(() => util.isAStack(rawStack))

  ContractError.call(this, rawStack)
  util.setAndFreezeProperty(this, 'name', AbstractError.name)
  util.setAndFreezeProperty(this, 'message', message)
  util.setAndFreezeProperty(this, 'contract', contract)
}

AbstractError.prototype = new ContractError(util.callerStack())
AbstractError.prototype.constructor = AbstractError
util.setAndFreezeProperty(AbstractError.prototype, 'name', AbstractError.name)
util.setAndFreezeProperty(AbstractError.prototype, 'message', message)
util.setAndFreezeProperty(AbstractError.prototype, 'contract', null)

AbstractError.message = message

AbstractContract.AbstractError = AbstractError

module.exports = AbstractContract
<commit_msg>Oops. Re-establish the difference between a general contract function and a contract function<commit_after>/*
 Copyright 2016 - 2018 by Jan Dockx

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict'

const ContractError = require('./ContractError')
const util = require('../_private/util')

const displayNamePrefix = 'contract function '

// noinspection ParameterNamingConventionJS
/**
 * Abstract definition of a function contract.
 *
 * An AbstractContract consists of an array of preconditions, an array of nominal postconditions,
 * and an array of exceptional postconditions.
 *
 * The conditions are functions whose result is interpreted as a booleany value.
 * The conditions are called with the same `this` and arguments as the functional call in which they are
 * verified. When verifying nominal postconditions, the result of the function call is added as extra argument.
 * When verifying exceptional postconditions, the exception thrown by the function call is added as extra argument.
 * Finally, a version of the contract function bound to `this` is supplied as final parameter when verifying
 * nominal and exceptional postconditions. This function reference can be used in contracts that use recursion.
 *
 * Furthermore, an instance contains a `location` property, which is a line of text
 * that refers to the source code where the contract was created. For internal contracts, this is
 * `AbstractContract.internalLocation.
 *
 * The `_location` argument is for internal use, and might be removed.
 *
 * @constructor
 */
function AbstractContract (kwargs, /* Object? */ _location) {
  util.pre(() => !!kwargs)
  util.pre(() => !kwargs.pre || util.typeOf(kwargs.pre) === 'array')
  util.pre(() => !kwargs.post || util.typeOf(kwargs.post) === 'array')
  util.pre(() => !kwargs.exception || util.typeOf(kwargs.exception) === 'array')
  util.pre(() =>
    !_location ||
    _location === AbstractContract.internalLocation ||
    typeof _location === 'string'
  )

  const self = this

  /* This cannot be defined in the prototype. The `self` is the contract, not the `this`. When this function is called
     as a method of a random object, that random object is the `this`, not this contract. */
  function abstract () { throw new AbstractContract.AbstractError(self, util.callerStack()) }

  const location = _location || util.callerLocation(1)
  AbstractContract.bless(abstract, self, abstract, location)
  util.setAndFreezeProperty(self, '_pre', Object.freeze(kwargs.pre ? kwargs.pre.slice() : []))
  util.setAndFreezeProperty(self, '_post', Object.freeze(kwargs.post ? kwargs.post.slice() : []))
  util.setAndFreezeProperty(self, '_exception', Object.freeze(kwargs.exception ? kwargs.exception.slice() : []))
  util.setAndFreezeProperty(self, 'location', Object.freeze(location))
  util.setAndFreezeProperty(self, 'abstract', abstract)
}

/**
 * Object to be used as location for contracts and implementations that are generated inside this library.
 */
AbstractContract.internalLocation = Object.freeze({
  toString: function () { return 'INTERNAL' }
})

AbstractContract.prototype = {
  constructor: AbstractContract,
  _pre: null,
  _post: null,
  _exception: null,
  isImplementedBy: function (f) {
    return AbstractContract.isAGeneralContractFunction(f) && f.contract === this
  }
}
util.defineFrozenReadOnlyArrayProperty(AbstractContract.prototype, 'pre', '_pre')
util.defineFrozenReadOnlyArrayProperty(AbstractContract.prototype, 'post', '_post')
util.defineFrozenReadOnlyArrayProperty(AbstractContract.prototype, 'exception', '_exception')
util.setAndFreezeProperty(AbstractContract.prototype, 'location', AbstractContract.internalLocation)
util.setAndFreezeProperty(AbstractContract.prototype, 'abstract', null)

AbstractContract.displayNamePrefix = displayNamePrefix

/**
 * Return a string that is a sensible display name for the given function as a contract function.
 */
AbstractContract.contractFunctionDisplayName = function (f) {
  util.pre(() => util.typeOf(f) === 'function')

  return displayNamePrefix +
         (f.name ||
            (f.implementation && (f.implementation.displayName || f.implementation.name)) ||
            '<<anonymous>>')
}

/**
 * This function is intended to be used as the bind function of contract functions. It makes sure
 * that, when applied to a contract function, the result
 * [is also a contract function]{@linkplain AbstractContract#isAContractFunction}.
 * The bind aspect of the functionality is the same as {@link Function#prototype#bind}.
 * The implementation of the resulting contract function is also bound in the same
 * way as the resulting contract function itself.
 */
AbstractContract.bindContractFunction = function bind () {
  util.pre(() => AbstractContract.isAGeneralContractFunction(this))

  const bound = Function.prototype.bind.apply(this, arguments)
  const boundImplementation = Function.prototype.bind.apply(this.implementation, arguments)
  AbstractContract.bless(bound, this.contract, boundImplementation, this.location)
  return bound
}

/**
 * A General Contract Function is an implementation of an AbstractContract. This function verifies whether a function
 * given as a parameter is a General Contract Function.
 *
 * To be a General Contract Function, the subject must
 *

 *
be a function,

 *
have a frozen `contract` property that refers to a AbstractContract,

 *
have a frozen `implementation` property that refers to a function (which realizes the contract),

 *
have a frozen `location` property, that has a value,

 *
have a frozen `bind` property, which is {@link AbstractContract.bindContractFunction}, and

 *
have a `displayName` that is a contract function display name, which is a string that gives
 *     information for a programmer to understand which contract function this is, and

 *
if the `implementation` function has a `prototype`, have a `prototype` property,
 *

 *
that is an object,

 *
that has a `constructor` property that is the contract function, and

 *
that has `f.implementation.prototype` in its prototype chain, or is equal to it.
 *

 *

 */
AbstractContract.isAGeneralContractFunction = function (f) {
  // Apart from this, we expect f to have a name. But it is controlled by the JavaScript engine, and we cannot
  // freeze it, and not guaranteed in all engines.
  return util.typeOf(f) === 'function' &&
         util.isFrozenOwnProperty(f, 'contract') &&
         f.contract instanceof AbstractContract &&
         util.isFrozenOwnProperty(f, 'implementation') &&
         util.typeOf(f.implementation) === 'function' &&
         util.isFrozenOwnProperty(f, 'location') &&
         f.location &&
         f.displayName === AbstractContract.contractFunctionDisplayName(f) &&
         util.isFrozenOwnProperty(f, 'bind') &&
         f.bind === AbstractContract.bindContractFunction &&
         (!f.implementation.hasOwnProperty('prototype') ||
             (util.typeOf(f.prototype) === 'object' &&
                 f.prototype.constructor === f &&
                 (f.prototype === f.implementation.prototype || f.prototype instanceof f.implementation)))
}

/**
 * A Contract Function is an implementation of a Contract. This function verifies whether a function
 * given as a parameter is a Contract Function.
 *
 * To be a Contract Function, the subject must
 *

 *
be a [general contract function]{@linkplain #isAGeneralContractFunction()},

 *
have a frozen `location` property, which is a string that represents a location in source code,
 *     outside this library.

 *

 */
AbstractContract.isAContractFunction = function (f) {
  return AbstractContract.isAGeneralContractFunction(f) && util.isAStackLocation(f.location)
}

/**
 * Helper function that transforms any function given as contractFunction
 * into a [contract function]{@linkplain AbstractContract#isAContractFunction}
 * for the given parameters.
 * If {@code implFunction.prototype} exists, the {@code contractFunction.prototype} is changed to
 * an object that refers to {@code contractFunction} as {@code contractFunction.prototype.constructor},
 * is otherwise empty, and has {@code implFunction.prototype} as prototype.
 *
 * @param contractFunction {Function} the regular {Function} to be transformed into a contract function
 * @param contract {AbstractContract} the contract contractFunction is a realisation of
 * @param implFunction {Function} the function that is used in contractFunction
 *                     to realize the postconditions of contract under its preconditions
 * @param location {String} the location outside this library that the resulting
 *                          [contract function]{@linkplain AbstractContract#isAContractFunction} will carry,
 *                          that says where it is defined.
 */
AbstractContract.bless = function bless (contractFunction, contract, implFunction, location) {
  util.pre(() => util.typeOf(contractFunction) === 'function')
  // noinspection JSUnresolvedVariable
  util.pre(() => !contractFunction.contract)
  // noinspection JSUnresolvedVariable
  util.pre(() => !contractFunction.implementation)
  // noinspection JSUnresolvedVariable
  util.pre(() => !contractFunction.location)
  util.pre(() => contractFunction.bind === Function.prototype.bind)
  util.pre(() => contract instanceof AbstractContract)
  util.pre(() => util.typeOf(implFunction) === 'function')
  util.pre(() => location === AbstractContract.internalLocation || util.isAStackLocation(location))

  util.setAndFreezeProperty(contractFunction, 'contract', contract)
  util.setAndFreezeProperty(contractFunction, 'implementation', implFunction)
  util.setAndFreezeProperty(contractFunction, 'location', location)
  util.setAndFreezeProperty(contractFunction, 'bind', AbstractContract.bindContractFunction)
  if (implFunction.hasOwnProperty('prototype')) {
    contractFunction.prototype = Object.create(implFunction.prototype)
    util.setAndFreezeProperty(contractFunction.prototype, 'constructor', contractFunction)
  }
  util.defineFrozenDerivedProperty(
    contractFunction,
    'displayName',
    function () { return AbstractContract.contractFunctionDisplayName(this) }
  )
}

/**
 * Function that always returns false.
 */
AbstractContract.falseCondition = function () { return false }

/**
 * Singleton array of {@linkplain AbstractContract#falseCondition}. Can be used the clearly signal
 * that a function should never throw exceptions, or never end nominally, or should never be called,
 * because the preconditions will always fail.
 */
AbstractContract.mustNotHappen = [AbstractContract.falseCondition]

/**
 * The most general function AbstractContract. This has the most strict preconditions (nothing is allowed), which can
 * be weakened by specializations, and the most general nominal and exceptional postconditions (anything goes),
 * which can be strengthened by specializations.
 */
AbstractContract.root = new AbstractContract(
  {
    pre: AbstractContract.mustNotHappen,
    post: [],
    exception: []
  },
  AbstractContract.internalLocation
)

const message = 'an abstract function cannot be executed'

/**
 * Thrown when an abstract method is called. You shouldn't.
 *
 * @constructor
 */
function AbstractError (contract, rawStack) {
  util.pre(() => contract instanceof AbstractContract)
  util.pre(() => util.isAStack(rawStack))

  ContractError.call(this, rawStack)
  util.setAndFreezeProperty(this, 'name', AbstractError.name)
  util.setAndFreezeProperty(this, 'message', message)
  util.setAndFreezeProperty(this, 'contract', contract)
}

AbstractError.prototype = new ContractError(util.callerStack())
AbstractError.prototype.constructor = AbstractError
util.setAndFreezeProperty(AbstractError.prototype, 'name', AbstractError.name)
util.setAndFreezeProperty(AbstractError.prototype, 'message', message)
util.setAndFreezeProperty(AbstractError.prototype, 'contract', null)

AbstractError.message = message

AbstractContract.AbstractError = AbstractError

module.exports = AbstractContract
<|endoftext|>


<commit_before>
var Stock = require('./models/stocks');
var fs = require('fs');

function readLines(input, add_stock) {
  var remaining = ''	//remaining input stream

  //process and splice stock input
    remaining += input;
    var index = remaining.indexOf('\n');
    while (index > -1) {
      var line = remaining.substring(0, index);
      remaining = remaining.substring(index + 1);

	  add_stock(line);

	  index = remaining.indexOf('\n');

    }

    if (remaining.length > 0) {
      add_stock(remaining);
    }

}

function add_stock(data) {
	var id = '';			//stock id
	var name = '';			//stock name
	var abbr = '';			//stock abbr
	var first_split = 0;
	var second_split = 0;

	first_split = data.indexOf(';');
	second_split = data.substring(first_split+1).indexOf(';');
	var temp = data.substring(second_split+1);
	temp=temp.substring(temp.indexOf(';')+1);
	var split = temp.indexOf(';');

	id = data.substring(0,first_split);
	name = temp.substring(0,split);
	abbr = temp.substring(split+1);

	//console.log(id,'  ',str,'  ',abbr,'  ',name);

	var new_stock = new Stocks({
		"name" 	: name,
        "id" 	: id,
		"abbr"	: abbr
	});

	new_stock.save(function(err, new_stock) {
		if (err) return console.error(err);
		//console.dir(new_stock);
	});
}

var stock_init = false;

if (stock_init==false){
Stocks.remove({}, function(err) {
   console.log('collection removed')
});

var iconv = require('iconv-lite');
var bin = fs.readFileSync('stockList_20151217.txt');

    if (bin[0] === 0xEF && bin[1] === 0xBB && bin[2] === 0xBF) {
        bin = bin.slice(3);
    }

readLines(bin.toString('utf-8'),add_stock);
stock_init=true;
}
<commit_msg>fix tyoi<commit_after>
var Stocks = require('./models/stocks');
var fs = require('fs');

function readLines(input, add_stock) {
  var remaining = ''	//remaining input stream

  //process and splice stock input
    remaining += input;
    var index = remaining.indexOf('\n');
    while (index > -1) {
      var line = remaining.substring(0, index);
      remaining = remaining.substring(index + 1);

	  add_stock(line);

	  index = remaining.indexOf('\n');

    }

    if (remaining.length > 0) {
      add_stock(remaining);
    }

}

function add_stock(data) {
	var id = '';			//stock id
	var name = '';			//stock name
	var abbr = '';			//stock abbr
	var first_split = 0;
	var second_split = 0;

	first_split = data.indexOf(';');
	second_split = data.substring(first_split+1).indexOf(';');
	var temp = data.substring(second_split+1);
	temp=temp.substring(temp.indexOf(';')+1);
	var split = temp.indexOf(';');

	id = data.substring(0,first_split);
	name = temp.substring(0,split);
	abbr = temp.substring(split+1);

	//console.log(id,'  ',str,'  ',abbr,'  ',name);

	var new_stock = new Stocks({
		"name" 	: name,
        "id" 	: id,
		"abbr"	: abbr
	});

	new_stock.save(function(err, new_stock) {
		if (err) return console.error(err);
		//console.dir(new_stock);
	});
}

var stock_init = false;

if (stock_init==false){
Stocks.remove({}, function(err) {
   console.log('collection removed')
});

var iconv = require('iconv-lite');
var bin = fs.readFileSync('stockList_20151217.txt');

    if (bin[0] === 0xEF && bin[1] === 0xBB && bin[2] === 0xBF) {
        bin = bin.slice(3);
    }

readLines(bin.toString('utf-8'),add_stock);
stock_init=true;
}
<|endoftext|>


<commit_before>const fs = require('fs-extra');
const path = require('path');
const util = require('util');
const logger = require('winston');
const request = require('request-promise');
const tomlify = require('tomlify-j0.4');
const exec = require('sync-exec');

const fsPathCode = './citra-games-wiki/games'
const fsPathWiki = './citra-games-wiki.wiki'
const fsPathHugoContent = '../../site/content/game'
const fsPathHugoBoxart = '../../site/static/images/game/boxart'
const fsPathHugoIcon = '../../site/static/images/game/icons'
const fsPathHugoScreenshots = '../../site/static/images/screenshots0'
const fsPathHugoSavefiles = '../../site/static/savefiles/'

process.on('unhandledRejection', err => {
  logger.error('Unhandled rejection on process.');
  logger.error(err);
  process.exit(1);
});

function gitPull(directory, repository) {
  if (fs.existsSync(directory)) {
    logger.info(`Fetching latest from Github : ${directory}`);
    logger.info(`git --git-dir=${directory} pull`);
    exec(`git --git-dir=${directory} pull`);
  } else {
    logger.info(`Cloning repository from Github : ${directory}`);
    logger.info(`git clone ${repository}`);
    exec(`git clone ${repository}`);
  }
}

async function getDirectories(x) {
  return fs.readdir(x).filter(file => fs.lstatSync(path.join(x, file)).isDirectory())
}

async function run() {
  // Make sure the output directories in Hugo exist.
  [fsPathHugoContent, fsPathHugoBoxart, fsPathHugoIcon, fsPathHugoSavefiles, fsPathHugoScreenshots].forEach(function (path) {
    if (fs.existsSync(path) == false) {
      logger.info(`Creating Hugo output directory: ${path}`);
      fs.ensureDirSync(path);
    }
  });

  // Fetch game files stored in games-wiki repository.
  gitPull('./citra-games-wiki', 'https://github.com/citra-emu/citra-games-wiki.git');

  // Loop through each game and process it.
  let games = await request.get({ uri: 'https://api.citra-emu.org/gamedb/websiteFeed/', json: true })
  await Promise.all(games.map(async (x) => {
    try {
      logger.info(`Processing game: ${x.id}`);

      // Set metadata.
      x.date = `${new Date().toISOString()}`

      // In Hugo, data keys need to be strings.
      x.compatibility = x.compatibility.toString()

      // Hugo requires compatibility to be a string to link to data JSON.
      x.testcases.forEach(x => x.compatibility = x.compatibility.toString())

      x.issues = x.issues.filter(x => x.state === 'open') || []

      // Copy the boxart for the game.
      fs.copySync(`${fsPathCode}/${x.id}/boxart.png`, `${fsPathHugoBoxart}/${x.id}.png`);

      // Copy the icon for the game.
      fs.copySync(`${fsPathCode}/${x.id}/icon.png`, `${fsPathHugoIcon}/${x.id}.png`);

      // SAVEFILE BLOCK
      var fsPathCodeSavefilesGame = `${fsPathCode}/${x.id}/savefiles/`;
      var fsPathHugoSavefilesGame = `${fsPathHugoSavefiles}/${x.id}/`;
      if (fs.existsSync(fsPathCodeSavefilesGame)) {
        // Create the savefile directory for the game.
        if (fs.existsSync(fsPathHugoSavefilesGame) == false) {
          fs.mkdirSync(fsPathHugoSavefilesGame);
        }

        // Copy all savefiles into the output folder, and read their data.
        fs.readdirSync(fsPathCodeSavefilesGame).forEach(file => {
          if (path.extname(file) == '.zip') {
            fs.copySync(`${fsPathCodeSavefilesGame}/${file}`, `${fsPathHugoSavefilesGame}/${file}`);
          }
        });
        // Finished copying all savefiles into the output folder, and reading their data.
      }
      // END SAVEFILE BLOCK

      // Copy the screenshots for the game.
      let fsPathScreenshotInputGame = `${fsPathCode}/${x.id}/screenshots/`;
      let fsPathScreenshotOutputGame = `${fsPathHugoScreenshots}/${x.id}/`;
      if (fs.existsSync(fsPathScreenshotInputGame)) {
        // Create the savefile directory for each game.
        if (fs.existsSync(fsPathScreenshotOutputGame) == false) {
          fs.mkdirSync(fsPathScreenshotOutputGame);
        }

        // Copy all screenshots into the output folder.
        fs.readdirSync(fsPathScreenshotInputGame).forEach(file => {
          if (path.extname(file) == '.png') {
            fs.copySync(`${fsPathScreenshotInputGame}/${file}`, `${fsPathScreenshotOutputGame}/${file}`);
          }
        });
      }

      // Clear out the wiki markdown so it won't be stored with the metadata.
      let wikiText = x.wiki_markdown
      x.wiki_markdown = null

      let meta = tomlify(x, null, 2);
      let contentOutput = `+++\r\n${meta}\r\n+++\r\n\r\n${wikiText}\r\n`;

      await fs.writeFile(`${fsPathHugoContent}/${x.id}.md`, contentOutput);

      return x
    } catch (ex) {
      logger.warn(`${x.id} ${x.title} failed to generate: ${ex}`);
      logger.error(ex);
      throw ex
    }
  }))
}

// Script start
run()
<commit_msg>Replaced app with shared code revision. Eventually will submodule.<commit_after>require('checkenv').check();

const fs = require('fs-extra');
const path = require('path');
const util = require('util');
const logger = require('winston');
const request = require('request-promise');
const tomlify = require('tomlify-j0.4');
const exec = require('sync-exec');

const tenant = 'citra'

const fsPathCode = `./${tenant}-games-wiki/games`
const fsPathHugo = '../../../site'
const fsPathHugoContent = `${fsPathHugo}/content/game`
const fsPathHugoBoxart = `${fsPathHugo}/static/images/game/boxart`
const fsPathHugoIcon = `${fsPathHugo}/static/images/game/icons`
const fsPathHugoScreenshots = `${fsPathHugo}/static/images/screenshots0`
const fsPathHugoSavefiles = `${fsPathHugo}/static/savefiles/`

process.on('unhandledRejection', err => {
  logger.error('Unhandled rejection on process.');
  logger.error(err);
  process.exit(1);
});

function gitPull(directory, repository) {
  if (fs.existsSync(directory)) {
    logger.info(`Fetching latest from Github : ${directory}`);
    logger.info(`git --git-dir=${directory} pull`);
    exec(`git --git-dir=${directory} pull`);
  } else {
    logger.info(`Cloning repository from Github : ${directory}`);
    logger.info(`git clone ${repository}`);
    exec(`git clone ${repository}`);
  }
}

async function run() {
  // Make sure the output directories in Hugo exist.
  [fsPathHugoContent, fsPathHugoBoxart, fsPathHugoIcon, fsPathHugoSavefiles, fsPathHugoScreenshots].forEach(function (path) {
    if (fs.existsSync(path) == false) {
      logger.info(`Creating Hugo output directory: ${path}`);
      fs.ensureDirSync(path);
    }
  });

  // Fetch game files stored in games-wiki repository.
  gitPull(`./${tenant}-games-wiki`, `https://github.com/${tenant}-emu/${tenant}-games-wiki.git`);

  // Loop through each game and process it.
  let games = await request.get({ uri: `https://api.${tenant}-emu.org/gamedb/websiteFeed/`, json: true })
  await Promise.all(games.map(async (x) => {
    try {
      logger.info(`Processing game: ${x.id}`);

      // Set metadata.
      x.date = `${new Date().toISOString()}`

      // Hugo requires compatibility to be a string to link to data JSON.
      x.compatibility = x.compatibility.toString()
      x.testcases.forEach(x => x.compatibility = x.compatibility.toString())

      x.issues = x.issues || []

      // Copy the boxart for the game.
      if (fs.existsSync(`${fsPathCode}/${x.id}/boxart.png`)) {
        fs.copySync(`${fsPathCode}/${x.id}/boxart.png`, `${fsPathHugoBoxart}/${x.id}.png`);
      } else if (fs.existsSync(`${fsPathCode}/${x.id}/icon.png`)) {
        fs.copySync(`${fsPathCode}/${x.id}/icon.png`, `${fsPathHugoBoxart}/${x.id}.png`);
      }

      // Copy the icon for the game.
      // If the icon does not exist, use the boxart in place of the icon.
      if (fs.existsSync(`${fsPathCode}/${x.id}/icon.png`)) {
        fs.copySync(`${fsPathCode}/${x.id}/icon.png`, `${fsPathHugoIcon}/${x.id}.png`);
      } else if (fs.existsSync(`${fsPathCode}/${x.id}/boxart.png`)) {
        fs.copySync(`${fsPathCode}/${x.id}/boxart.png`, `${fsPathHugoIcon}/${x.id}.png`);
      }

      // SAVEFILE BLOCK
      var fsPathCodeSavefilesGame = `${fsPathCode}/${x.id}/savefiles/`;
      var fsPathHugoSavefilesGame = `${fsPathHugoSavefiles}/${x.id}/`;
      if (fs.existsSync(fsPathCodeSavefilesGame)) {
        // Create the savefile directory for the game.
        if (fs.existsSync(fsPathHugoSavefilesGame) == false) {
          fs.mkdirSync(fsPathHugoSavefilesGame);
        }

        // Copy all savefiles into the output folder, and read their data.
        fs.readdirSync(fsPathCodeSavefilesGame).forEach(file => {
          if (path.extname(file) == '.zip') {
            fs.copySync(`${fsPathCodeSavefilesGame}/${file}`, `${fsPathHugoSavefilesGame}/${file}`);
          }
        });
        // Finished copying all savefiles into the output folder, and reading their data.
      }
      // END SAVEFILE BLOCK

      // Copy the screenshots for the game.
      let fsPathScreenshotInputGame = `${fsPathCode}/${x.id}/screenshots/`;
      let fsPathScreenshotOutputGame = `${fsPathHugoScreenshots}/${x.id}/`;
      if (fs.existsSync(fsPathScreenshotInputGame)) {
        // Create the savefile directory for each game.
        if (fs.existsSync(fsPathScreenshotOutputGame) == false) {
          fs.mkdirSync(fsPathScreenshotOutputGame);
        }

        // Copy all screenshots into the output folder.
        fs.readdirSync(fsPathScreenshotInputGame).forEach(file => {
          if (path.extname(file) == '.png') {
            fs.copySync(`${fsPathScreenshotInputGame}/${file}`, `${fsPathScreenshotOutputGame}/${file}`);
          }
        });
      }

      // Clear out the wiki markdown so it won't be stored with the metadata.
      let wikiText = x.wiki_markdown || ''
      x.wiki_markdown = null

      let meta = tomlify.toToml(x, {space: 2})
      let contentOutput = `+++\r\nleft_sidebar = true\r\n${meta}\r\n+++\r\n\r\n${wikiText}\r\n`;

      await fs.writeFile(`${fsPathHugoContent}/${x.id}.md`, contentOutput);

      return x
    } catch (ex) {
      logger.warn(`${x.id} ${x.title} failed to generate: ${ex}`);
      logger.error(ex);
      throw ex
    }
  }))
}

// Script start
run()
<|endoftext|>


<commit_before>var joose = require('Joose');
var Collection = CactusJuice.Data.Collection;
var Pair = CactusJuice.Data.Pair;

joose.Class("IrcWrapper", {
  has : {
    server : {},
    irc : {
      is : "ro"
    },
    nicks : {
      init : function () { return []; }
    },
    joinChannels : {
      init : function () { return []; }
    },
    bindings : {
      init : function () { return {}; }
    },
    channels : {
      is : "ro",
      init : function () { return {}; }
    },
    people : {
      is : "ro",
      init : function () { return {}; }
    },
    me : {
      is : "ro"
    },
    admins : {
      init : function () { return []; }
    }
  },
  methods : {
    initialize : function (args) {
      this.bindings.join = this.bindings.join || [];
      this.bindings.privmsg = this.bindings.privmsg || [];
      this.bindings.part = this.bindings.part || [];
      this.bindings.quit = this.bindings.quit || [];
      this.bindings['001'] = this.bindings['001'] || [];
      this.bindings['433'] = this.bindings['433'] || [];
      this.bindings.nick = this.bindings.nick || [];
      this.bindings.clientquit = this.bindings.clientquit || [];

      this.irc = new args.IRC({
        server : this.server,
        nick : this.nicks.shift(),
        flood_protection : true
      });

      this.bindings.join.push({
        callback : function (h) {
          if (!(h.location in this.channels)) {
            this._addChannel(new Channel({
              name : h.location
            }));
          }
          var channel = this.channels[h.location];
          channel.addPerson(h.person);
          h.person.addChannel(channel);
        }.bind(this)
      });
      this.bindings['433'].push({
        callback : function (h) {
          var newNick = this.nicks.shift();
          if (newNick === undefined) {
            this.quit();
          } else {
            this.getIrc().user("js-irc", false, false, "Javascript bot");
            this.nick(newNick);
          }
        }.bind(this)
      });
      this.bindings['001'].push({
        callback : function (h) {
          this.me = this._personCreate({
            nick : h.nick
          });
          for (var i = 0; i < this.joinChannels.length; i++) {
            this.join(this.joinChannels[i]);
          }
        }.bind(this)
      });
      this.bindings.part.push({
        callback : function (h) {
          var channel = this.getChannel(h.location);
          var person = h.person;
          channel.removePerson(person);
          person.removeChannel(channel);

          // If bot parts, remove channel from memory.
          if (this.getMe() === person) {
            this._removeChannel(channel);
          }
        }.bind(this)
      });
      this.bindings.quit.push({
        callback : function (h) {
          var channel = this.getChannel(h.location);
          var person = h.person;
          channel.removePerson(person);
          person.removeChannel(channel);

          // If bot parts, remove channel from memory.
          if (this.getMe() === person) {
            this._removeChannel(channel);
          }
        }.bind(this)
      });
      this.bindings.nick.push({
        callback : function (h) {
          h.person.setNick(h.newNick);
        }
      });

      // Apply bindings.
      for (var p in this.bindings) if (this.bindings.hasOwnProperty(p)) {
        var raw = p;
        var v = this.bindings[p];
        if ("_on" + raw in this) {
          for (var i = 0; i < v.length; i++) {
            this["_on" + raw](v[i]);
          }
        } else {
          for (var i = 0; i < v.length; i++) {
            this._addListener(raw, v[i].callback);
          }
        }
      }
      this.irc.connect();
    },
    _addListener : function (raw, callback) {
      if (!(callback instanceof Function)) {
        throw new Error("_addListener: callback must be a function.");
      }
      this.irc.addListener(raw, function (e) {
        var x = this._parseE(raw, e);
        callback.call(this, x);
      }.bind(this));
    },
    _parseE : function (raw, e) {
      var h = {
        e : e
      };
      if (raw === "join" || raw === "part" || raw === "quit" || raw === "privmsg" || raw === "nick") {
        h.person = this._personCreate({
          nick : e.person.nick,
          user : e.person.user,
          host : e.person.host
        });
      }
      if (raw === "quit" && h.person === this.getMe()) {
        h.clientQuit = true;
      }
      if (raw === "nick") {
        h.oldNick = e.person.nick;
        h.newNick = e.params[0];
      }
      if (raw === "001") {
        h.nick = e.params[0];
      }
      if (raw === "join" || raw === "part" || raw === "quit" || raw === "privmsg") {
        var location = e.params[0];
        h.location = location;
        h.reply = this.privmsg.bind(this.irc, location);
      }
      if (raw === "part" || raw === "quit" || raw === "privmsg" || raw === "001") {
        h.message = e.params[1];
      }
      if (raw === "privmsg") {
        h.regExp = null;
      }
      return h;
    },
    _onprivmsg : function (options) {
      this._addListener("privmsg", function (h) {
        if ("location" in options && options.location !== h.location) {
          return;
        }
        if ("messageString" in options && options.messageString !== h.message) {
          return;
        }
        if ("messageRegExp" in options) {
          h.regExp = options.messageRegExp.exec(h.message);
          if (h.regExp === null) {
            return;
          }
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    _onjoin : function (options) {
      this._addListener("join", function (h) {
        if ("channel" in options && options.channel !== h.location) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    _onpart : function (options) {
      this._addListener("part", function (h) {
        if ("channel" in options && options.channel !== h.location) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    /**
     * Does no trigger when client itself quits.
     */
    _onquit : function (options) {
      this._addListener("quit", function (h) {
        if (h.clientQuit) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    _onclientquit : function (options) {
      this._addListener("quit", function (h) {
        if (!h.clientQuit) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    getChannel : function (name) {
      if (!(name in this.channels)) {
        throw new Error("IrcWrapper:getChannel: No channel with name: " + name);
      }
      return this._getChannel(name);
    },
    _removeChannel : function (channel) {
      delete this.channels[channel.getName()];
    },
    _addChannel : function (channel) {
      this.channels[channel.getName()] = channel;
    },
    _getChannel : function (name) {
      return this.channels[name];
    },
    getPerson : function (nick) {
      if (!(nick in this.people)) {
        throw new Error("IrcWrapper:getPerson: No user with nick: " + nick);
      }
      return this._getPerson(nick);
    },
    _getPerson : function (nick) {
      return this.people[nick];
    },
    _personCreate : function (values) {
      if (this._getPerson(values.nick)) {
        var p = this._getPerson(values.nick);
        if (values.user) {
          p.setUser(values.user);
        }
        if (values.host) {
          p.setHost(values.host);
        }
        return p;
      } else {
        var p = new Person(values);
        this.people[p.getNick()] = p;
        return p;
      }
    },
    getMe : function () {
      return this.me;
    },
    _personMatchesMask : function (person, mask) {
      /^([^!]+)!([^@]+)@(.+?)$/.test(mask);
      var ps = [
        new Pair(person.getNick(), RegExp.$1),
        new Pair(person.getUser(), RegExp.$2),
        new Pair(person.getHost(), RegExp.$3)
      ];
      for (var i = 0; i < ps.length; i++) {
        var p = ps[i];
        var reg = new RegExp("^" + p.getSecond().replace(/\*/g, ".*") + "$");
        if (!reg.test(p.getFirst())) {
          return false;
        }
      }
      return true;
    },
    isAdmin : function (person) {
      return Collection.some(this.admins, this._personMatchesMask.bind(this, person));
    },
    amsg : function (message) {
      for (var p in this.channels) if (this.channels.hasOwnProperty(p)) {
        var channel = this.channels[p];
        this.privmsg(channel.getName(), message);
      }
    },
    join : function (channel, password) {
      this.getIrc().join(channel, password);
    },
    nick : function (newNick) {
      this.getIrc().nick(newNick);
    },
    quit : function (message) {
      this.getIrc().quit(message);
    },
    privmsg : function (location, message) {
      this.getIrc().privmsg(location, message);
    }
  }
});

module.exports = IrcWrapper;
<commit_msg>Fixed bug in privmsg binding.<commit_after>var joose = require('Joose');
var Collection = CactusJuice.Data.Collection;
var Pair = CactusJuice.Data.Pair;

joose.Class("IrcWrapper", {
  has : {
    server : {},
    irc : {
      is : "ro"
    },
    nicks : {
      init : function () { return []; }
    },
    joinChannels : {
      init : function () { return []; }
    },
    bindings : {
      init : function () { return {}; }
    },
    channels : {
      is : "ro",
      init : function () { return {}; }
    },
    people : {
      is : "ro",
      init : function () { return {}; }
    },
    me : {
      is : "ro"
    },
    admins : {
      init : function () { return []; }
    }
  },
  methods : {
    initialize : function (args) {
      this.bindings.join = this.bindings.join || [];
      this.bindings.privmsg = this.bindings.privmsg || [];
      this.bindings.part = this.bindings.part || [];
      this.bindings.quit = this.bindings.quit || [];
      this.bindings['001'] = this.bindings['001'] || [];
      this.bindings['433'] = this.bindings['433'] || [];
      this.bindings.nick = this.bindings.nick || [];
      this.bindings.clientquit = this.bindings.clientquit || [];

      this.irc = new args.IRC({
        server : this.server,
        nick : this.nicks.shift(),
        flood_protection : true
      });

      this.bindings.join.push({
        callback : function (h) {
          if (!(h.location in this.channels)) {
            this._addChannel(new Channel({
              name : h.location
            }));
          }
          var channel = this.channels[h.location];
          channel.addPerson(h.person);
          h.person.addChannel(channel);
        }.bind(this)
      });
      this.bindings['433'].push({
        callback : function (h) {
          var newNick = this.nicks.shift();
          if (newNick === undefined) {
            this.quit();
          } else {
            this.getIrc().user("js-irc", false, false, "Javascript bot");
            this.nick(newNick);
          }
        }.bind(this)
      });
      this.bindings['001'].push({
        callback : function (h) {
          this.me = this._personCreate({
            nick : h.nick
          });
          for (var i = 0; i < this.joinChannels.length; i++) {
            this.join(this.joinChannels[i]);
          }
        }.bind(this)
      });
      this.bindings.part.push({
        callback : function (h) {
          var channel = this.getChannel(h.location);
          var person = h.person;
          channel.removePerson(person);
          person.removeChannel(channel);

          // If bot parts, remove channel from memory.
          if (this.getMe() === person) {
            this._removeChannel(channel);
          }
        }.bind(this)
      });
      this.bindings.quit.push({
        callback : function (h) {
          var channel = this.getChannel(h.location);
          var person = h.person;
          channel.removePerson(person);
          person.removeChannel(channel);

          // If bot parts, remove channel from memory.
          if (this.getMe() === person) {
            this._removeChannel(channel);
          }
        }.bind(this)
      });
      this.bindings.nick.push({
        callback : function (h) {
          h.person.setNick(h.newNick);
        }
      });

      // Apply bindings.
      for (var p in this.bindings) if (this.bindings.hasOwnProperty(p)) {
        var raw = p;
        var v = this.bindings[p];
        if ("_on" + raw in this) {
          for (var i = 0; i < v.length; i++) {
            this["_on" + raw](v[i]);
          }
        } else {
          for (var i = 0; i < v.length; i++) {
            this._addListener(raw, v[i].callback);
          }
        }
      }
      this.irc.connect();
    },
    _addListener : function (raw, callback) {
      if (!(callback instanceof Function)) {
        throw new Error("_addListener: callback must be a function.");
      }
      this.irc.addListener(raw, function (e) {
        var x = this._parseE(raw, e);
        callback.call(this, x);
      }.bind(this));
    },
    _parseE : function (raw, e) {
      var h = {
        e : e
      };
      if (raw === "join" || raw === "part" || raw === "quit" || raw === "privmsg" || raw === "nick") {
        h.person = this._personCreate({
          nick : e.person.nick,
          user : e.person.user,
          host : e.person.host
        });
      }
      if (raw === "quit" && h.person === this.getMe()) {
        h.clientQuit = true;
      }
      if (raw === "nick") {
        h.oldNick = e.person.nick;
        h.newNick = e.params[0];
      }
      if (raw === "001") {
        h.nick = e.params[0];
      }
      if (raw === "join" || raw === "part" || raw === "quit" || raw === "privmsg") {
        var location = e.params[0];
        h.location = location;
        h.reply = this.privmsg.bind(this, location);
      }
      if (raw === "part" || raw === "quit" || raw === "privmsg" || raw === "001") {
        h.message = e.params[1];
      }
      if (raw === "privmsg") {
        h.regExp = null;
      }
      return h;
    },
    _onprivmsg : function (options) {
      this._addListener("privmsg", function (h) {
        if ("location" in options && options.location !== h.location) {
          return;
        }
        if ("messageString" in options && options.messageString !== h.message) {
          return;
        }
        if ("messageRegExp" in options) {
          h.regExp = options.messageRegExp.exec(h.message);
          if (h.regExp === null) {
            return;
          }
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    _onjoin : function (options) {
      this._addListener("join", function (h) {
        if ("channel" in options && options.channel !== h.location) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    _onpart : function (options) {
      this._addListener("part", function (h) {
        if ("channel" in options && options.channel !== h.location) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    /**
     * Does no trigger when client itself quits.
     */
    _onquit : function (options) {
      this._addListener("quit", function (h) {
        if (h.clientQuit) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    _onclientquit : function (options) {
      this._addListener("quit", function (h) {
        if (!h.clientQuit) {
          return;
        }
        options.callback.call(this, h);
      }.bind(this));
    },
    getChannel : function (name) {
      if (!(name in this.channels)) {
        throw new Error("IrcWrapper:getChannel: No channel with name: " + name);
      }
      return this._getChannel(name);
    },
    _removeChannel : function (channel) {
      delete this.channels[channel.getName()];
    },
    _addChannel : function (channel) {
      this.channels[channel.getName()] = channel;
    },
    _getChannel : function (name) {
      return this.channels[name];
    },
    getPerson : function (nick) {
      if (!(nick in this.people)) {
        throw new Error("IrcWrapper:getPerson: No user with nick: " + nick);
      }
      return this._getPerson(nick);
    },
    _getPerson : function (nick) {
      return this.people[nick];
    },
    _personCreate : function (values) {
      if (this._getPerson(values.nick)) {
        var p = this._getPerson(values.nick);
        if (values.user) {
          p.setUser(values.user);
        }
        if (values.host) {
          p.setHost(values.host);
        }
        return p;
      } else {
        var p = new Person(values);
        this.people[p.getNick()] = p;
        return p;
      }
    },
    getMe : function () {
      return this.me;
    },
    _personMatchesMask : function (person, mask) {
      /^([^!]+)!([^@]+)@(.+?)$/.test(mask);
      var ps = [
        new Pair(person.getNick(), RegExp.$1),
        new Pair(person.getUser(), RegExp.$2),
        new Pair(person.getHost(), RegExp.$3)
      ];
      for (var i = 0; i < ps.length; i++) {
        var p = ps[i];
        var reg = new RegExp("^" + p.getSecond().replace(/\*/g, ".*") + "$");
        if (!reg.test(p.getFirst())) {
          return false;
        }
      }
      return true;
    },
    isAdmin : function (person) {
      return Collection.some(this.admins, this._personMatchesMask.bind(this, person));
    },
    amsg : function (message) {
      for (var p in this.channels) if (this.channels.hasOwnProperty(p)) {
        var channel = this.channels[p];
        this.privmsg(channel.getName(), message);
      }
    },
    join : function (channel, password) {
      this.getIrc().join(channel, password);
    },
    nick : function (newNick) {
      this.getIrc().nick(newNick);
    },
    quit : function (message) {
      this.getIrc().quit(message);
    },
    privmsg : function (location, message) {
      this.getIrc().privmsg(location, message);
    }
  }
});

module.exports = IrcWrapper;
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var Table = require('easy-table');
var questionsCollection = require('./questions');

module.exports = yeoman.Base.extend({
  constructor: function(){
    yeoman.Base.apply(this, arguments);
    this.props = {
      fields: []
    };
    this.argument('moduleName', { type: String, required: false, desc: 'Module Name', defaults: null});
    this.props.moduleName = this.moduleName;
  },
  prompting: function () {
    var done = this.async();
    var that = this;
    //shows module fields
    function listFields(){
      that.log(chalk.blue("Module " + chalk.bold(that.props.moduleName)));
      var table = new Table();
      _.forEach(that.props.fields, function(field){
        table.cell('Field name', field.name);
        table.cell('Field type', field.type);
        table.newRow();
      });
      that.log(chalk.yellow(table.toString()));
      addField();
    }
    //adds new field
    function addField(){
      that.prompt(questionsCollection.confirmAddField).then(function(answers){
        if(answers.addField){//add new field
          that.prompt(questionsCollection.getField).then(function(answers){
            that.props.fields.push(answers);
            listFields();
          });
        }else{//don't add field go to next phase
          done();
        }
      });
    }
    if(this.props.moduleName){
      listFields();
    }else{
      this.prompt(questionsCollection.moduleNameQuestion).then(function(answers){
        that.props.moduleName = answers.moduleName;
        listFields();
      });
    }
  },

  writing: function () {
  },

  install: function () {
  },

  end: function(){
  }
});<commit_msg>added a new line<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var Table = require('easy-table');
var questionsCollection = require('./questions');

module.exports = yeoman.Base.extend({
  constructor: function(){
    yeoman.Base.apply(this, arguments);
    this.props = {
      fields: []
    };
    this.argument('moduleName', { type: String, required: false, desc: 'Module Name', defaults: null});
    this.props.moduleName = this.moduleName;
  },
  prompting: function () {
    var done = this.async();
    var that = this;
    //shows module fields
    function listFields(){
      that.log("\n" + chalk.blue("Module " + chalk.bold(that.props.moduleName)));
      var table = new Table();
      _.forEach(that.props.fields, function(field){
        table.cell('Field name', field.name);
        table.cell('Field type', field.type);
        table.newRow();
      });
      that.log(chalk.yellow(table.toString()));
      addField();
    }
    //adds new field
    function addField(){
      that.prompt(questionsCollection.confirmAddField).then(function(answers){
        if(answers.addField){//add new field
          that.prompt(questionsCollection.getField).then(function(answers){
            that.props.fields.push(answers);
            listFields();
          });
        }else{//don't add field go to next phase
          done();
        }
      });
    }
    if(this.props.moduleName){
      listFields();
    }else{
      this.prompt(questionsCollection.moduleNameQuestion).then(function(answers){
        that.props.moduleName = answers.moduleName;
        listFields();
      });
    }
  },

  writing: function () {
  },

  install: function () {
  },

  end: function(){
  }
});<|endoftext|>


<commit_before>var $operators = {
    "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift",
    "**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift",
    "+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv",
    "%=":"imod","&=":"iand","|=":"ior",
    "^=":"ipow","+":"add","-":"sub","*":"mul",
    "/":"truediv","%":"mod","&":"and","|":"or",
    "^":"pow","<":"lt",">":"gt",
    "<=":"le",">=":"ge","==":"eq","!=":"ne",
    "or":"or","and":"and","in":"in","not":"not",
    "not_in":"not_in","is_not":"is_not" // fake
    }

var $first_op_letter = {}
for(op in $operators){$first_op_letter[op.charAt(0)]=0}

function $tokenize(src){
    var delimiters = [["#","\n","comment"],['"""','"""',"triple_string"],
        ["'","'","string"],['"','"',"string"],
        ["r'","'","raw_string"],['r"','"',"raw_string"]]
    var br_open = {"(":0,"[":0,"{":0}
    var br_close = {")":"(","]":"[","}":"{"}
    var br_stack = ""
    var br_pos = new Array()
    var kwdict = $List2Dict("False","class","finally","is","return",
        "None","continue","for","lambda","try","True","def","from",
        "nonlocal","while","del","global","with",
        "as","elif","if","yield","assert","else","import","pass",
        "break","except","raise")
    var unsupported = $List2Dict("class","is","from","nonlocal","with",
        "as","yield")
    // causes errors for some browsers
    // complete list at http://www.javascripter.net/faq/reserved.htm
    var forbidden = $List2Dict("item")

    var punctuation = {',':0,':':0} //,';':0}
    var int_pattern = new RegExp("^\\d+")
    var float_pattern = new RegExp("^\\d+\\.\\d*(e-?\\d+)?")
    var id_pattern = new RegExp("[\\$_a-zA-Z]\\w*")

    var stack = new Array()
    var name = ""
    var _type = null
    var pos = 0
    var indent_stack = [0]

    var pos2line = {}
    var lnum=1
    for(i=0;i<src.length;i++){
        pos2line[i]=lnum
        if(src.charAt(i)=='\n'){lnum+=1}
    }
    lnum = 0
    while(pos<src.length){
        document.line_num = pos2line[pos]
        var flag = false
        var car = src.charAt(pos)
        // check indentation
        if(stack.length==0 || $last(stack)[0]=='newline'){
            var indent = 0
            while(pos<src.length && src.charAt(pos)==" "){
                indent++;pos++
            }
            // ignore empty lines
            if(src.charAt(pos)=='\n'){pos++;lnum++;continue}
            // indentation must be equal to some value in indent_stack, or
            // greater if last line ended with :
            if(stack.length>1){
                if(indent>$last(indent_stack)){
                    if(stack[stack.length-2][0] != "delimiter" &&
                        stack[stack.length-2][1] != ":"){
                        $raise("IndentationError","unexpected indent")
                    }else{
                        indent_stack.push(indent)
                    }
                }else if(indent==$last(indent_stack)){
                    if(stack[stack.length-2][0]=="delimiter" &&
                        stack[stack.length-2][1]==":"){
                        $raise("IndentationError","expected an indented block")
                    }
                }else if(indent<$last(indent_stack)){
                    indent_stack.pop()
                    while(true){
                        if(indent_stack.length==0){
                            $raise('IndentationError','unexpected indent')
                        }
                        if(indent>$last(indent_stack)){
                            $raise('IndentationError','unexpected indent')
                        }else if(indent==$last(indent_stack)){break}
                        else{indent_stack.pop()}
                    }
                }
            }else if(indent>0){
                $raise("IndentationError","unexpected indent")
            }
            stack.push(["indent",indent,pos-indent])
            continue
        }
        // comment
        if(car=="#"){
            var end = src.substr(pos+1).search('\n')
            if(end==-1){end=src.length-1}
            stack.push(["newline",lnum,pos+1+end])
            lnum += 1
            pos += end+2;continue
        }
        // string
        if(car=='"' || car=="'"){
            var raw = false
            var end = null
            if(name.length>0 && name.toLowerCase()=="r"){
                // raw string
                raw = true;name=""
            }
            if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3}
            else{_type="string";end=pos+1}
            var escaped = false
            var zone = car
            var found = false
            while(end<src.length){
                if(escaped){zone+=src.charAt(end);escaped=false;end+=1}
                else if(src.charAt(end)=="\\"){
                    if(raw){
                        zone += '\\\\'
                        end++
                    } else {
                        if(src.charAt(end+1)=='\n'){
                            // explicit line joining inside strings
                            end += 2
                            lnum++
                        } else {
                            zone+=src.charAt(end);escaped=true;end+=1
                        }
                    }
                } else if(src.charAt(end)==car){
                    if(_type=="triple_string" && src.substr(end,3)!=car+car+car){
                        end++
                    } else {
                        found = true
                        // end of string
                        if(stack.length>0 && $last(stack)[0]=="str"){
                            // implicit string concatenation : insert a + sign
                            stack.push(['operator','+',end])
                        }
                        stack.push(["str",zone+car,pos])
                        pos = end+1
                        if(_type=="triple_string"){pos = end+3}
                        break
                    }
                } else {
                    zone += src.charAt(end)
                    if(src.charAt(end)=='\n'){lnum++}
                    end++
                }
            }
            if(!found){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"String end not found ")
            }
            continue
        }
        // identifier ?
        if(name==""){
            if(car.search(/[a-zA-Z_]/)!=-1){
                name=car // identifier start
                pos++;continue
            }
        } else {
            if(car.search(/\w/)!=-1){
                name+=car
                pos++;continue
            } else{
                if(name in kwdict){
                    if(name in unsupported){
                        document.line_num = pos2line[pos]
                        $raise('SyntaxError',"Unsupported Python keyword '"+name+"'")
                    }
                    stack.push(["keyword",name,pos-name.length])
                } else if(name in forbidden) {
                    document.line_num = pos2line[pos]
                    $raise('SyntaxError',"Forbidden name '"+name+"' : might conflict with Javascript variables")
                } else if(name in $operators) { // and, or
                    stack.push(["operator",name,pos-name.length])
                } else if(stack.length>1 && $last(stack)[0]=="point"
                    && (stack[stack.length-2][0] in $List2Dict('id','qualifier','bracket'))) {
                    stack.push(["qualifier",name,pos-name.length])
                } else {
                    stack.push(["id",name,pos-name.length])
                }
                name=""
                continue
            }
        }
        // qualified name ?
        if(car=="."){
            stack.push(["point",".",pos])
            pos++;continue
        }
        // number
        if(car.search(/\d/)>-1){
            // digit
            var res = float_pattern.exec(src.substr(pos))
            if(res){
                if(res[0].search('e')>-1){stack.push(["float",res[0],pos])}
                else{stack.push(["float",eval(res[0]),pos])}
            }else{
                res = int_pattern.exec(src.substr(pos))
                stack.push(["int",eval(res[0]),pos])
            }
            pos += res[0].length
            continue
        }
        if(car=="\n"){
            lnum++
            if(br_stack.length>0){
                // implicit line joining inside brackets
                pos++;continue
            } else {
                // ignore empty lines
                if(stack[stack.length-1][0]!="newline"){
                    stack.push(["newline",lnum,pos])
                } else {
                    stack[stack.length-1][1] = lnum // update line num
                }
                pos++;continue
            }
        }
        if(car in br_open){
            br_stack += car
            br_pos[br_stack.length-1] = pos
            stack.push(["bracket",car,pos])
            pos++;continue
        }
        if(car in br_close){
            if(br_stack==""){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unexpected closing bracket")
            } else if(br_close[car]!=$last(br_stack)){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unbalanced bracket ")
            } else {
                br_stack = br_stack.substr(0,br_stack.length-1)
                stack.push(["bracket",car,pos])
                pos++;continue
            }
        }
        if(car=="="){
            if(src.charAt(pos+1)!="="){
                // assignment if outside of brackets
                if(br_stack.length==0){
                    stack.push(["assign","=",pos])
                } else { // like in foo(bar=9)
                    stack.push(["delimiter","=",pos])
                }
                pos++;continue
            } else {
                stack.push(["operator","==",pos])
                pos+=2;continue
            }
        }
        if(car in punctuation){
            stack.push(["delimiter",car,pos])
            pos++;continue
        }
        // operators
        if(car in $first_op_letter){
            // find longest match
            var op_match = ""
            for(op_sign in $operators){
                if(op_sign==src.substr(pos,op_sign.length)
                    && op_sign.length>op_match.length){
                    op_match=op_sign
                }
            }
            if(op_match.length>0){
                stack.push(["operator",op_match,pos])
                pos += op_match.length
                continue
            }
        }
        if(car=='\\' && src.charAt(pos+1)=='\n'){
            lnum++;pos+=2;continue
        }
        if(car!=' '){$raise('SyntaxError','unknown token '+car)}
        pos += 1
    }

    if(br_stack.length!=0){
        pos = br_pos.pop()
        document.line_num = pos2line[pos]
        $raise('SyntaxError',"Unbalanced bracket "+br_stack.charAt(br_stack.length-1))
    }

    return stack

}
<commit_msg>py_tokenizer.js : add "status" to forbidden words<commit_after>var $operators = {
    "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift",
    "**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift",
    "+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv",
    "%=":"imod","&=":"iand","|=":"ior",
    "^=":"ipow","+":"add","-":"sub","*":"mul",
    "/":"truediv","%":"mod","&":"and","|":"or",
    "^":"pow","<":"lt",">":"gt",
    "<=":"le",">=":"ge","==":"eq","!=":"ne",
    "or":"or","and":"and","in":"in","not":"not",
    "not_in":"not_in","is_not":"is_not" // fake
    }

var $first_op_letter = {}
for(op in $operators){$first_op_letter[op.charAt(0)]=0}

function $tokenize(src){
    var delimiters = [["#","\n","comment"],['"""','"""',"triple_string"],
        ["'","'","string"],['"','"',"string"],
        ["r'","'","raw_string"],['r"','"',"raw_string"]]
    var br_open = {"(":0,"[":0,"{":0}
    var br_close = {")":"(","]":"[","}":"{"}
    var br_stack = ""
    var br_pos = new Array()
    var kwdict = $List2Dict("False","class","finally","is","return",
        "None","continue","for","lambda","try","True","def","from",
        "nonlocal","while","del","global","with",
        "as","elif","if","yield","assert","else","import","pass",
        "break","except","raise")
    var unsupported = $List2Dict("class","is","from","nonlocal","with",
        "as","yield")
    // causes errors for some browsers
    // complete list at http://www.javascripter.net/faq/reserved.htm
    var forbidden = $List2Dict("item","status")

    var punctuation = {',':0,':':0} //,';':0}
    var int_pattern = new RegExp("^\\d+")
    var float_pattern = new RegExp("^\\d+\\.\\d*(e-?\\d+)?")
    var id_pattern = new RegExp("[\\$_a-zA-Z]\\w*")

    var stack = new Array()
    var name = ""
    var _type = null
    var pos = 0
    var indent_stack = [0]

    var pos2line = {}
    var lnum=1
    for(i=0;i<src.length;i++){
        pos2line[i]=lnum
        if(src.charAt(i)=='\n'){lnum+=1}
    }
    lnum = 0
    while(pos<src.length){
        document.line_num = pos2line[pos]
        var flag = false
        var car = src.charAt(pos)
        // check indentation
        if(stack.length==0 || $last(stack)[0]=='newline'){
            var indent = 0
            while(pos<src.length && src.charAt(pos)==" "){
                indent++;pos++
            }
            // ignore empty lines
            if(src.charAt(pos)=='\n'){pos++;lnum++;continue}
            // indentation must be equal to some value in indent_stack, or
            // greater if last line ended with :
            if(stack.length>1){
                if(indent>$last(indent_stack)){
                    if(stack[stack.length-2][0] != "delimiter" &&
                        stack[stack.length-2][1] != ":"){
                        $raise("IndentationError","unexpected indent")
                    }else{
                        indent_stack.push(indent)
                    }
                }else if(indent==$last(indent_stack)){
                    if(stack[stack.length-2][0]=="delimiter" &&
                        stack[stack.length-2][1]==":"){
                        $raise("IndentationError","expected an indented block")
                    }
                }else if(indent<$last(indent_stack)){
                    indent_stack.pop()
                    while(true){
                        if(indent_stack.length==0){
                            $raise('IndentationError','unexpected indent')
                        }
                        if(indent>$last(indent_stack)){
                            $raise('IndentationError','unexpected indent')
                        }else if(indent==$last(indent_stack)){break}
                        else{indent_stack.pop()}
                    }
                }
            }else if(indent>0){
                $raise("IndentationError","unexpected indent")
            }
            stack.push(["indent",indent,pos-indent])
            continue
        }
        // comment
        if(car=="#"){
            var end = src.substr(pos+1).search('\n')
            if(end==-1){end=src.length-1}
            stack.push(["newline",lnum,pos+1+end])
            lnum += 1
            pos += end+2;continue
        }
        // string
        if(car=='"' || car=="'"){
            var raw = false
            var end = null
            if(name.length>0 && name.toLowerCase()=="r"){
                // raw string
                raw = true;name=""
            }
            if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3}
            else{_type="string";end=pos+1}
            var escaped = false
            var zone = car
            var found = false
            while(end<src.length){
                if(escaped){zone+=src.charAt(end);escaped=false;end+=1}
                else if(src.charAt(end)=="\\"){
                    if(raw){
                        zone += '\\\\'
                        end++
                    } else {
                        if(src.charAt(end+1)=='\n'){
                            // explicit line joining inside strings
                            end += 2
                            lnum++
                        } else {
                            zone+=src.charAt(end);escaped=true;end+=1
                        }
                    }
                } else if(src.charAt(end)==car){
                    if(_type=="triple_string" && src.substr(end,3)!=car+car+car){
                        end++
                    } else {
                        found = true
                        // end of string
                        if(stack.length>0 && $last(stack)[0]=="str"){
                            // implicit string concatenation : insert a + sign
                            stack.push(['operator','+',end])
                        }
                        stack.push(["str",zone+car,pos])
                        pos = end+1
                        if(_type=="triple_string"){pos = end+3}
                        break
                    }
                } else {
                    zone += src.charAt(end)
                    if(src.charAt(end)=='\n'){lnum++}
                    end++
                }
            }
            if(!found){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"String end not found ")
            }
            continue
        }
        // identifier ?
        if(name==""){
            if(car.search(/[a-zA-Z_]/)!=-1){
                name=car // identifier start
                pos++;continue
            }
        } else {
            if(car.search(/\w/)!=-1){
                name+=car
                pos++;continue
            } else{
                if(name in kwdict){
                    if(name in unsupported){
                        document.line_num = pos2line[pos]
                        $raise('SyntaxError',"Unsupported Python keyword '"+name+"'")
                    }
                    stack.push(["keyword",name,pos-name.length])
                } else if(name in forbidden) {
                    document.line_num = pos2line[pos]
                    $raise('SyntaxError',"Forbidden name '"+name+"' : might conflict with Javascript variables")
                } else if(name in $operators) { // and, or
                    stack.push(["operator",name,pos-name.length])
                } else if(stack.length>1 && $last(stack)[0]=="point"
                    && (stack[stack.length-2][0] in $List2Dict('id','qualifier','bracket'))) {
                    stack.push(["qualifier",name,pos-name.length])
                } else {
                    stack.push(["id",name,pos-name.length])
                }
                name=""
                continue
            }
        }
        // qualified name ?
        if(car=="."){
            stack.push(["point",".",pos])
            pos++;continue
        }
        // number
        if(car.search(/\d/)>-1){
            // digit
            var res = float_pattern.exec(src.substr(pos))
            if(res){
                if(res[0].search('e')>-1){stack.push(["float",res[0],pos])}
                else{stack.push(["float",eval(res[0]),pos])}
            }else{
                res = int_pattern.exec(src.substr(pos))
                stack.push(["int",eval(res[0]),pos])
            }
            pos += res[0].length
            continue
        }
        if(car=="\n"){
            lnum++
            if(br_stack.length>0){
                // implicit line joining inside brackets
                pos++;continue
            } else {
                // ignore empty lines
                if(stack[stack.length-1][0]!="newline"){
                    stack.push(["newline",lnum,pos])
                } else {
                    stack[stack.length-1][1] = lnum // update line num
                }
                pos++;continue
            }
        }
        if(car in br_open){
            br_stack += car
            br_pos[br_stack.length-1] = pos
            stack.push(["bracket",car,pos])
            pos++;continue
        }
        if(car in br_close){
            if(br_stack==""){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unexpected closing bracket")
            } else if(br_close[car]!=$last(br_stack)){
                document.line_num = pos2line[pos]
                $raise('SyntaxError',"Unbalanced bracket ")
            } else {
                br_stack = br_stack.substr(0,br_stack.length-1)
                stack.push(["bracket",car,pos])
                pos++;continue
            }
        }
        if(car=="="){
            if(src.charAt(pos+1)!="="){
                // assignment if outside of brackets
                if(br_stack.length==0){
                    stack.push(["assign","=",pos])
                } else { // like in foo(bar=9)
                    stack.push(["delimiter","=",pos])
                }
                pos++;continue
            } else {
                stack.push(["operator","==",pos])
                pos+=2;continue
            }
        }
        if(car in punctuation){
            stack.push(["delimiter",car,pos])
            pos++;continue
        }
        // operators
        if(car in $first_op_letter){
            // find longest match
            var op_match = ""
            for(op_sign in $operators){
                if(op_sign==src.substr(pos,op_sign.length)
                    && op_sign.length>op_match.length){
                    op_match=op_sign
                }
            }
            if(op_match.length>0){
                stack.push(["operator",op_match,pos])
                pos += op_match.length
                continue
            }
        }
        if(car=='\\' && src.charAt(pos+1)=='\n'){
            lnum++;pos+=2;continue
        }
        if(car!=' '){$raise('SyntaxError','unknown token '+car)}
        pos += 1
    }

    if(br_stack.length!=0){
        pos = br_pos.pop()
        document.line_num = pos2line[pos]
        $raise('SyntaxError',"Unbalanced bracket "+br_stack.charAt(br_stack.length-1))
    }

    return stack

}
<|endoftext|>


<commit_before>'use strict';

/**
 *
 * @param {Object} jsonData
 * @param {string} jsonData[].Product
 * @param {string} xmlData
 * @param {string} requestUrl
 */
const icecat = function (jsonData, xmlData, requestUrl) {
    this.xmlData = xmlData;
    this.jsonData = jsonData;
    this.productData = jsonData['ICECAT-interface'].Product[0];
    this.requestUrl = requestUrl;
    this.returnCode = {
        FAIL: -1,
        SUCCESS: 1
    }
};

/**
 * getJSON
 * @returns {string}
 */
icecat.prototype.getJSON = function () {
    return this.jsonData;
};

/**
 * getXML
 * @returns {string}
 */
icecat.prototype.getXML = function () {
    return this.xmlData;
};

/**
 * getReturnCode
 * Example  returns -1 || 1
 * @returns {String}
 */
icecat.prototype.getReturnCode = function () {
    return parseInt(this.productData['$'].Code, 10);
};

/**
 * getErrorMessage
 * @returns {string}
 */
icecat.prototype.getErrorMessage = function () {
    return this.productData['$'].ErrorMessage;
};

/**
 * getName
 *
 * @returns Product Name {string}
 */
icecat.prototype.getName = function () {
    return this.productData['$'].Name;
};

/**
 * getTitle
 *
 * @returns Product Title {string}
 */
icecat.prototype.getTitle = function () {
    return this.productData['$'].Title;
};

/**
 * getReleaseDate
 *
 * @returns Product Release Date YYYY-MM-DD {string}
 */
icecat.prototype.getReleaseDate = function () {
    return this.productData['$'].ReleaseDate;
};

/**
 * getLongDescription
 * @returns {string}
 */
icecat.prototype.getLongDescription = function () {
    try {
        return this.productData.ProductDescription[0]['$'].LongDesc;
    } catch (e) {
        return false;
    }
};

/**
 * getShortDescription
 * @returns {string}
 */
icecat.prototype.getShortDescription = function () {
    try {
        return this.productData.ProductDescription[0]['$'].ShortDesc;
    } catch (e) {
        return false;
    }
};

/**
 * getProductInfoPDFurl
 * @returns {string}
 */
icecat.prototype.getProductInfoPDFurl = function () {
    try {
        return this.productData.ProductDescription[0]['$'].PDFURL;
    } catch (e) {
        return false;
    }
};

/**
 * getProductManualPDFurl
 * @returns {string}
 */
icecat.prototype.getProductManualPDFurl = function () {
    try {
        return this.productData.ProductDescription[0]['$'].PDFURL;
    } catch (e) {
        return false;
    }
};

/**
 * getProductUrl
 * @returns {string}
 */
icecat.prototype.getProductUrl = function () {
    try {
        return this.productData.ProductDescription[0]['$'].URL;
    } catch (e) {
        return false;
    }
};

/**
 * getSupplier
 * @returns {string}
 */
icecat.prototype.getSupplier = function () {
    return this.productData.Supplier[0]['$'].Name;
};

/**
 * getCategory
 * @returns {string}
 */
icecat.prototype.getCategory = function () {
    return this.productData.Category[0].Name[0]['$'].Value;
};

/**
 * getFamily
 * @returns {Object}
 */
icecat.prototype.getFamily = function () {
    try {
        return {
            id: this.productData.ProductFamily[0].Name[0]['$'].ID,
            name: this.productData.ProductFamily[0].Name[0]['$'].Value
        }
    } catch (e) {
        return false;
    }
};

/**
 * getID
 * @returns {string}
 */
icecat.prototype.getId = function () {
    return this.productData['$'].ID;
};

/**
 * getEan
 * @returns {string}
 */
icecat.prototype.getEan = function () {
    return this.productData.EANCode[0]['$'].EAN;
};

/**
 * getImages
 * @returns {array}
 */
icecat.prototype.getImages = function () {
    let images = [];

    for (let img of this.productData.ProductGallery[0].ProductPicture) {
        const imageSet = {};
        imageSet.IsMain = img['$']['IsMain'];
        imageSet.HighImg = img['$']['Pic'];
        imageSet.LowImg = img['$']['LowPic'];
        imageSet.TumbImg = img['$']['ThumbPic'];

        images.push(imageSet);
    }

    return images;
};

/**
 * getSpecifications
 * @returns {array}
 */
icecat.prototype.getSpecifications = function () {
    let ProductFeatures = [];

    for (let pSpec of this.productData.ProductFeature) {
        let specSet = {};

        specSet.name = pSpec.Feature[0].Name[0]['$'].Value;
        specSet.presentationValue = pSpec['$'].Presentation_Value;
        specSet.value = pSpec['$'].Value;
        specSet.specId = pSpec['$'].CategoryFeature_ID;
        specSet.specGroupId = pSpec['$'].CategoryFeatureGroup_ID;

        ProductFeatures.push(specSet);
    }

    return ProductFeatures;
};

/**
 * getMultimediaObjects
 * @returns {Array}
 */
icecat.prototype.getMultimediaObjects = function () {
    let MultimediaObjects = [];

    try {
        for (let mObj of this.productData.ProductMultimediaObject) {
            let mObjectSet = [];

            mObjectSet.contentType = mObj.MultimediaObject[0]['$'].ContentType;
            mObjectSet.tumbUrl = mObj.MultimediaObject[0]['$'].ThumbUrl;
            mObjectSet.description = mObj.MultimediaObject[0]['$'].Description;
            mObjectSet.keepAsURL = mObj.MultimediaObject[0]['$'].KeepAsURL;
            mObjectSet.size = mObj.MultimediaObject[0]['$'].Size;
            mObjectSet.url = mObj.MultimediaObject[0]['$'].URL;

            MultimediaObjects.push(mObjectSet);
        }
    } catch (e) {
        return false;
    }

    return MultimediaObjects;
};

module.exports = icecat;<commit_msg>code review<commit_after>'use strict';

/**
 *
 * @param {Object} jsonData
 * @param {string} jsonData[].Product
 * @param {string} xmlData
 * @param {string} requestUrl
 */
const icecat = function (jsonData, xmlData, requestUrl) {
    this.xmlData = xmlData;
    this.jsonData = jsonData;
    this.productData = jsonData['ICECAT-interface'].Product[0];
    this.requestUrl = requestUrl;
    this.returnCode = {
        FAIL: -1,
        SUCCESS: 1
    }
};

/**
 * getJSON
 * @returns {string}
 */
icecat.prototype.getJSON = function () {
    return this.jsonData;
};

/**
 * getXML
 * @returns {string}
 */
icecat.prototype.getXML = function () {
    return this.xmlData;
};

/**
 * getReturnCode
 * Example  returns -1 || 1
 * @returns {String}
 */
icecat.prototype.getReturnCode = function () {
    return parseInt(this.productData['$'].Code, 10);
};

/**
 * getErrorMessage
 * @returns {string}
 */
icecat.prototype.getErrorMessage = function () {
    return this.productData['$'].ErrorMessage;
};

/**
 * getName
 *
 * @returns Product Name {string}
 */
icecat.prototype.getName = function () {
    return this.productData['$'].Name;
};

/**
 * getTitle
 *
 * @returns Product Title {string}
 */
icecat.prototype.getTitle = function () {
    return this.productData['$'].Title;
};

/**
 * getReleaseDate
 *
 * @returns Product Release Date YYYY-MM-DD {string}
 */
icecat.prototype.getReleaseDate = function () {
    return this.productData['$'].ReleaseDate;
};

/**
 * getLongDescription
 * @returns {string}
 */
icecat.prototype.getLongDescription = function () {
    try {
        return this.productData.ProductDescription[0]['$'].LongDesc;
    } catch (e) {
        return false;
    }
};

/**
 * getShortDescription
 * @returns {string}
 */
icecat.prototype.getShortDescription = function () {
    try {
        return this.productData.ProductDescription[0]['$'].ShortDesc;
    } catch (e) {
        return false;
    }
};

/**
 * getProductInfoPDFurl
 * @returns {string}
 */
icecat.prototype.getProductInfoPDFurl = function () {
    try {
        return this.productData.ProductDescription[0]['$'].PDFURL;
    } catch (e) {
        return false;
    }
};

/**
 * getProductManualPDFurl
 * @returns {string}
 */
icecat.prototype.getProductManualPDFurl = function () {
    try {
        return this.productData.ProductDescription[0]['$'].PDFURL;
    } catch (e) {
        return false;
    }
};

/**
 * getProductUrl
 * @returns {string}
 */
icecat.prototype.getProductUrl = function () {
    try {
        return this.productData.ProductDescription[0]['$'].URL;
    } catch (e) {
        return false;
    }
};

/**
 * getSupplier
 * @returns {string}
 */
icecat.prototype.getSupplier = function () {
    return this.productData.Supplier[0]['$'].Name;
};

/**
 * getCategory
 * @returns {string}
 */
icecat.prototype.getCategory = function () {
    return this.productData.Category[0].Name[0]['$'].Value;
};

/**
 * getFamily
 * @returns {Object}
 */
icecat.prototype.getFamily = function () {
    try {
        return {
            id: this.productData.ProductFamily[0].Name[0]['$'].ID,
            name: this.productData.ProductFamily[0].Name[0]['$'].Value
        }
    } catch (e) {
        return false;
    }
};

/**
 * getID
 * @returns {string}
 */
icecat.prototype.getID = function () {
    return this.productData['$'].ID;
};

/**
 * getEan
 * @returns {string}
 */
icecat.prototype.getEan = function () {
    return this.productData.EANCode[0]['$'].EAN;
};

/**
 * getImages
 * @returns {array}
 */
icecat.prototype.getImages = function () {
    let images = [];

    for (let img of this.productData.ProductGallery[0].ProductPicture) {
        const imageSet = {};
        imageSet.IsMain = img['$']['IsMain'];
        imageSet.HighImg = img['$']['Pic'];
        imageSet.LowImg = img['$']['LowPic'];
        imageSet.TumbImg = img['$']['ThumbPic'];

        images.push(imageSet);
    }

    return images;
};

/**
 * getSpecifications
 * @returns {array}
 */
icecat.prototype.getSpecifications = function () {
    let ProductFeatures = [];

    for (let pSpec of this.productData.ProductFeature) {
        let specSet = {};

        specSet.name = pSpec.Feature[0].Name[0]['$'].Value;
        specSet.presentationValue = pSpec['$'].Presentation_Value;
        specSet.value = pSpec['$'].Value;
        specSet.specId = pSpec['$'].CategoryFeature_ID;
        specSet.specGroupId = pSpec['$'].CategoryFeatureGroup_ID;

        ProductFeatures.push(specSet);
    }

    return ProductFeatures;
};

/**
 * getMultimediaObjects
 * @returns {Array}
 */
icecat.prototype.getMultimediaObjects = function () {
    let MultimediaObjects = [];

    try {
        for (let mObj of this.productData.ProductMultimediaObject) {
            let mObjectSet = [];

            mObjectSet.contentType = mObj.MultimediaObject[0]['$'].ContentType;
            mObjectSet.tumbUrl = mObj.MultimediaObject[0]['$'].ThumbUrl;
            mObjectSet.description = mObj.MultimediaObject[0]['$'].Description;
            mObjectSet.keepAsURL = mObj.MultimediaObject[0]['$'].KeepAsURL;
            mObjectSet.size = mObj.MultimediaObject[0]['$'].Size;
            mObjectSet.url = mObj.MultimediaObject[0]['$'].URL;

            MultimediaObjects.push(mObjectSet);
        }
    } catch (e) {
        return false;
    }

    return MultimediaObjects;
};

module.exports = icecat;<|endoftext|>