<commit_before>import { observer } from 'binary-common-utils/lib/observer'
import CustomApi from 'binary-common-utils/lib/customApi'
import { getToken } from 'binary-common-utils/lib/storageManager'
import _ from 'underscore'
import config from '../../common/const'
import PurchaseCtrl from './purchaseCtrl'
import _Symbol from './symbol'
import { number as expectNumber, barrierOffset as expectBarrierOffset } from '../../common/expect'

const decorateTradeOptions = (tradeOption, otherOptions = {}) => {
  const option = {
    duration_unit: tradeOption.duration_unit,
    basis: tradeOption.basis,
    currency: tradeOption.currency,
    symbol: tradeOption.symbol,
    ...otherOptions,
  }
  option.duration = expectNumber('duration', tradeOption.duration)
  option.amount = expectNumber('amount', tradeOption.amount).toFixed(2)
  if ('prediction' in tradeOption) {
    option.barrier = expectNumber('prediction', tradeOption.prediction)
  }
  if ('barrierOffset' in tradeOption) {
    option.barrier = expectBarrierOffset(tradeOption.barrierOffset)
  }
  if ('secondBarrierOffset' in tradeOption) {
    option.barrier2 = expectBarrierOffset(tradeOption.secondBarrierOffset)
  }
  return option
}

export default class Bot {
  constructor(api = null) {
    this.ticks = []
    this.candles = []
    this.candleInterval = 60
    this.running = false
    this.currentToken = ''
    this.balanceStr = ''
    this.currentSymbol = ''
    this.unregisterOnFinish = []
    this.totalProfit = 0
    this.totalRuns = 0
    this.totalWins = 0
    this.totalLosses = 0
    this.totalStake = 0
    this.totalPayout = 0
    this.balance = 0
    this.api = (api === null) ? new CustomApi() : api
    this.symbol = new _Symbol(this.api)
    this.initPromise = this.symbol.initPromise
  }
  start(token, tradeOption, beforePurchase, duringPurchase, afterPurchase, sameTrade) {
    if (!this.running || sameTrade) {
      this.running = true
      if (this.purchaseCtrl) {
        this.purchaseCtrl.destroy()
      }
      this.purchaseCtrl = new PurchaseCtrl(this.api, beforePurchase, duringPurchase, afterPurchase)
      this.tradeOption = tradeOption
      observer.emit('log.bot.start', {
        again: !!sameTrade,
      })
      const accountName = getToken(token).account_name
      if (typeof amplitude !== 'undefined') {
        amplitude.getInstance().setUserId(accountName)
      }
      if (typeof trackJs !== 'undefined') {
        trackJs.configure({
          userId: accountName,
        })
      }
      if (sameTrade) {
        this.startTrading()
      } else {
        const promises = []
        if (this.currentToken !== token) {
          promises.push(this.login(token))
        }
        if (!_.isEmpty(this.tradeOption)) {
          if (this.tradeOption.symbol !== this.currentSymbol) {
            observer.unregisterAll('api.ohlc')
            observer.unregisterAll('api.tick')
            promises.push(this.subscribeToTickHistory())
            promises.push(this.subscribeToCandles())
          } else if (this.tradeOption.candleInterval !== this.candleInterval) {
            observer.unregisterAll('api.ohlc')
            this.candleInterval = this.tradeOption.candleInterval
            promises.push(this.subscribeToCandles())
          }
        }
        Promise.all(promises).then(() => {
          this.startTrading()
        }).catch((error) => {
          if (error.name === 'BlocklyError') {
            // pass
          } else {
            throw error
          }
        })
      }
    }
  }
  login(token) {
    return new Promise((resolve) => {
      const apiAuthorize = () => {
        observer.emit('log.bot.login', {
          lastToken: this.currentToken,
          token,
        })
        this.currentToken = token
        this.subscribeToBalance()
        this.observeStreams()
        resolve()
      }
      observer.register('api.authorize', apiAuthorize, true, {
        type: 'authorize',
        unregister: [['api.authorize', apiAuthorize]],
      }, true)
      this.api.authorize(token)
    })
  }
  setTradeOptions() {
    if (!_.isEmpty(this.tradeOption)) {
      this.pip = this.symbol.activeSymbols.getSymbols()[this.tradeOption.symbol.toLowerCase()].pip
      const opposites = config.opposites[this.tradeOption.condition]
      this.candleInterval = this.tradeOption.candleInterval
      this.tradeOptions = []
      for (const key of Object.keys(opposites)) {
        this.tradeOptions.push(decorateTradeOptions(this.tradeOption, {
          contract_type: Object.keys(opposites[key])[0],
        }))
      }
    } else {
      this.tradeOptions = []
    }
  }
  subscribeToBalance() {
    const apiBalance = (balance) => {
      this.balance = balance.balance
      this.balanceStr = `${Number(balance.balance).toFixed(2)} ${balance.currency}`
      observer.emit('bot.tradeInfo', {
        balance: this.balanceStr,
      })
    }
    observer.register('api.balance', apiBalance, false, {
      type: 'balance',
      unregister: [['api.balance', apiBalance]],
    })
    this.api.balance()
  }
  subscribeToCandles() {
    return new Promise((resolve) => {
      const apiCandles = (candles) => {
        this.observeOhlc()
        this.candles = candles
        resolve()
      }
      observer.register('api.candles', apiCandles, true, {
        type: 'candles',
        unregister: ['api.ohlc', 'api.candles', 'api.tick', 'bot.tickUpdate'],
      })
      this.api.originalApi.unsubscribeFromAllCandles().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 600,
        granularity: this.candleInterval,
        style: 'candles',
        subscribe: 1,
      })
    })
  }
  subscribeToTickHistory() {
    return new Promise((resolve) => {
      const apiHistory = (history) => {
        this.observeTicks()
        this.currentSymbol = this.tradeOption.symbol
        this.ticks = history
        resolve()
      }
      observer.register('api.history', apiHistory, true, {
        type: 'history',
        unregister: [['api.history', apiHistory], 'api.tick',
          'bot.tickUpdate', 'api.ohlc', 'api.candles'],
      }, true)
      this.api.originalApi.unsubscribeFromAllTicks().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 600,
        subscribe: 1,
      })
    })
  }
  observeTicks() {
    if (!observer.isRegistered('api.tick')) {
      const apiTick = (tick) => {
        this.ticks = [...this.ticks, tick]
        this.ticks.splice(0, 1)
        if (this.running) {
          this.purchaseCtrl.updateTicks({
            ticks: this.ticks,
            candles: this.candles,
          })
        }
        observer.emit('bot.tickUpdate', {
          ticks: this.ticks,
          candles: this.candles,
          pip: this.pip,
        })
      }
      observer.register('api.tick', apiTick)
    }
  }
  observeOhlc() {
    if (!observer.isRegistered('api.ohlc')) {
      const apiOHLC = (candle) => {
        if (this.candles.length && this.candles.slice(-1)[0].epoch === candle.epoch) {
          this.candles = [...this.candles.slice(0, -1), candle]
        } else {
          this.candles = [...this.candles, candle]
          this.candles.splice(0, 1)
        }
      }
      observer.register('api.ohlc', apiOHLC)
    }
  }
  observeBeforePurchase() {
    if (!observer.isRegistered('beforePurchase.ready')) {
      const beforePurchaseReady = () => {
        if (this.running) {
          observer.emit('bot.waiting_for_purchase')
        }
      }
      observer.register('beforePurchase.ready', beforePurchaseReady)
    }
  }
  observeTradeUpdate() {
    if (!observer.isRegistered('beforePurchase.tradeUpdate')) {
      const beforePurchaseTradeUpdate = (contract) => {
        if (this.running) {
          observer.emit('bot.tradeUpdate', contract)
        }
      }
      observer.register('beforePurchase.tradeUpdate', beforePurchaseTradeUpdate)
    }
  }
  observeStreams() {
    this.observeTradeUpdate()
    this.observeBeforePurchase()
    this.observeTicks()
    this.observeOhlc()
  }
  subscribeProposal(tradeOption) {
    const apiProposal = (proposal) => {
      if (this.running) {
        observer.emit('log.bot.proposal', proposal)
        this.purchaseCtrl.updateProposal(proposal)
      }
    }
    observer.register('api.proposal', apiProposal, false, {
      type: 'proposal',
      unregister: [
        ['api.proposal', apiProposal],
        'beforePurchase.ready',
        'bot.waiting_for_purchase',
      ],
    })
    this.unregisterOnFinish.push(['api.proposal', apiProposal])
    this.api.proposal(tradeOption)
  }
  subscribeProposals() {
    this.setTradeOptions()
    observer.unregisterAll('api.proposal')
    this.api.originalApi.unsubscribeFromAllProposals().then(() => {
      for (const to of this.tradeOptions) {
        this.subscribeProposal(to)
      }
    }, () => 0)
  }
  waitForBeforePurchaseFinish() {
    const beforePurchaseFinish = (contract) => {
      this.botFinish(contract)
    }
    observer.register('beforePurchase.finish', beforePurchaseFinish, true, null, true)
    this.unregisterOnFinish.push(['beforePurchase.finish', beforePurchaseFinish])
  }
  waitForTradePurchase() {
    const tradePurchase = () => {
      this.totalRuns += 1
      observer.emit('bot.tradeInfo', {
        totalRuns: this.totalRuns,
      })
    }
    observer.register('trade.purchase', tradePurchase, true, null, true)
    this.unregisterOnFinish.push(['trade.purchase', tradePurchase])
  }
  startTrading() {
    this.waitForBeforePurchaseFinish()
    this.waitForTradePurchase()
    this.subscribeProposals()
  }
  updateTotals(contract) {
    const profit = +(Number(contract.sell_price) - Number(contract.buy_price)).toFixed(2)
    const user = getToken(this.currentToken)
    observer.emit('log.revenue', {
      user,
      profit,
      contract,
    })

    if (+profit > 0) {
      this.totalWins += 1
    } else if (+profit < 0) {
      this.totalLosses += 1
    }
    this.totalProfit = +(this.totalProfit + profit).toFixed(2)
    this.totalStake = +(this.totalStake + Number(contract.buy_price)).toFixed(2)
    this.totalPayout = +(this.totalPayout + Number(contract.sell_price)).toFixed(2)

    observer.emit('bot.tradeInfo', {
      totalProfit: this.totalProfit,
      totalWins: this.totalWins,
      totalLosses: this.totalLosses,
      totalStake: this.totalStake,
      totalPayout: this.totalPayout,
    })
  }
  botFinish(contract) {
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    this.updateTotals(contract)
    observer.emit('bot.finish', contract)
    // order matters
    this.running = false
    this.purchaseCtrl.destroy()
    this.purchaseCtrl = null
  //
  }
  stop(contract) {
    if (!this.running) {
      observer.emit('bot.stop', contract)
      return
    }
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    // order matters
    this.running = false
    if (this.purchaseCtrl) {
      this.purchaseCtrl.destroy()
      this.purchaseCtrl = null
    }
    //
    this.api.originalApi.unsubscribeFromAllProposals().then(() => 0, () => 0)
    if (contract) {
      observer.emit('log.bot.stop', contract)
    }
    observer.emit('bot.stop', contract)
  }
}

export const bot = process.browser ? new Bot() : null
<commit_msg>Fixed candle interval initialization problem<commit_after>import { observer } from 'binary-common-utils/lib/observer'
import CustomApi from 'binary-common-utils/lib/customApi'
import { getToken } from 'binary-common-utils/lib/storageManager'
import _ from 'underscore'
import config from '../../common/const'
import PurchaseCtrl from './purchaseCtrl'
import _Symbol from './symbol'
import { number as expectNumber, barrierOffset as expectBarrierOffset } from '../../common/expect'

const decorateTradeOptions = (tradeOption, otherOptions = {}) => {
  const option = {
    duration_unit: tradeOption.duration_unit,
    basis: tradeOption.basis,
    currency: tradeOption.currency,
    symbol: tradeOption.symbol,
    ...otherOptions,
  }
  option.duration = expectNumber('duration', tradeOption.duration)
  option.amount = expectNumber('amount', tradeOption.amount).toFixed(2)
  if ('prediction' in tradeOption) {
    option.barrier = expectNumber('prediction', tradeOption.prediction)
  }
  if ('barrierOffset' in tradeOption) {
    option.barrier = expectBarrierOffset(tradeOption.barrierOffset)
  }
  if ('secondBarrierOffset' in tradeOption) {
    option.barrier2 = expectBarrierOffset(tradeOption.secondBarrierOffset)
  }
  return option
}

export default class Bot {
  constructor(api = null) {
    this.ticks = []
    this.candles = []
    this.currentCandleInterval = 0
    this.running = false
    this.currentToken = ''
    this.balanceStr = ''
    this.currentSymbol = ''
    this.unregisterOnFinish = []
    this.totalProfit = 0
    this.totalRuns = 0
    this.totalWins = 0
    this.totalLosses = 0
    this.totalStake = 0
    this.totalPayout = 0
    this.balance = 0
    this.api = (api === null) ? new CustomApi() : api
    this.symbol = new _Symbol(this.api)
    this.initPromise = this.symbol.initPromise
  }
  start(token, tradeOption, beforePurchase, duringPurchase, afterPurchase, sameTrade) {
    if (!this.running || sameTrade) {
      this.running = true
      if (this.purchaseCtrl) {
        this.purchaseCtrl.destroy()
      }
      this.purchaseCtrl = new PurchaseCtrl(this.api, beforePurchase, duringPurchase, afterPurchase)
      this.tradeOption = tradeOption
      observer.emit('log.bot.start', {
        again: !!sameTrade,
      })
      const accountName = getToken(token).account_name
      if (typeof amplitude !== 'undefined') {
        amplitude.getInstance().setUserId(accountName)
      }
      if (typeof trackJs !== 'undefined') {
        trackJs.configure({
          userId: accountName,
        })
      }
      if (sameTrade) {
        this.startTrading()
      } else {
        const promises = []
        if (this.currentToken !== token) {
          promises.push(this.login(token))
        }
        if (!_.isEmpty(this.tradeOption)) {
          if (this.tradeOption.symbol !== this.currentSymbol) {
            observer.unregisterAll('api.ohlc')
            observer.unregisterAll('api.tick')
            promises.push(this.subscribeToTickHistory())
            promises.push(this.subscribeToCandles())
          } else if (this.tradeOption.candleInterval !== this.currentCandleInterval) {
            observer.unregisterAll('api.ohlc')
            promises.push(this.subscribeToCandles())
          }
        }
        Promise.all(promises).then(() => {
          this.startTrading()
        }).catch((error) => {
          if (error.name === 'BlocklyError') {
            // pass
          } else {
            throw error
          }
        })
      }
    }
  }
  login(token) {
    return new Promise((resolve) => {
      const apiAuthorize = () => {
        observer.emit('log.bot.login', {
          lastToken: this.currentToken,
          token,
        })
        this.currentToken = token
        this.subscribeToBalance()
        this.observeStreams()
        resolve()
      }
      observer.register('api.authorize', apiAuthorize, true, {
        type: 'authorize',
        unregister: [['api.authorize', apiAuthorize]],
      }, true)
      this.api.authorize(token)
    })
  }
  setTradeOptions() {
    if (!_.isEmpty(this.tradeOption)) {
      this.pip = this.symbol.activeSymbols.getSymbols()[this.tradeOption.symbol.toLowerCase()].pip
      const opposites = config.opposites[this.tradeOption.condition]
      this.currentCandleInterval = this.tradeOption.candleInterval
      this.tradeOptions = []
      for (const key of Object.keys(opposites)) {
        this.tradeOptions.push(decorateTradeOptions(this.tradeOption, {
          contract_type: Object.keys(opposites[key])[0],
        }))
      }
    } else {
      this.tradeOptions = []
    }
  }
  subscribeToBalance() {
    const apiBalance = (balance) => {
      this.balance = balance.balance
      this.balanceStr = `${Number(balance.balance).toFixed(2)} ${balance.currency}`
      observer.emit('bot.tradeInfo', {
        balance: this.balanceStr,
      })
    }
    observer.register('api.balance', apiBalance, false, {
      type: 'balance',
      unregister: [['api.balance', apiBalance]],
    })
    this.api.balance()
  }
  subscribeToCandles() {
    return new Promise((resolve) => {
      const apiCandles = (candles) => {
        this.observeOhlc()
        this.currentCandleInterval = this.tradeOption.candleInterval
        this.candles = candles
        resolve()
      }
      observer.register('api.candles', apiCandles, true, {
        type: 'candles',
        unregister: ['api.ohlc', 'api.candles', 'api.tick', 'bot.tickUpdate'],
      })
      this.api.originalApi.unsubscribeFromAllCandles().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 600,
        granularity: this.tradeOption.candleInterval,
        style: 'candles',
        subscribe: 1,
      })
    })
  }
  subscribeToTickHistory() {
    return new Promise((resolve) => {
      const apiHistory = (history) => {
        this.observeTicks()
        this.currentSymbol = this.tradeOption.symbol
        this.ticks = history
        resolve()
      }
      observer.register('api.history', apiHistory, true, {
        type: 'history',
        unregister: [['api.history', apiHistory], 'api.tick',
          'bot.tickUpdate', 'api.ohlc', 'api.candles'],
      }, true)
      this.api.originalApi.unsubscribeFromAllTicks().then(() => 0, () => 0)
      this.api.history(this.tradeOption.symbol, {
        end: 'latest',
        count: 600,
        subscribe: 1,
      })
    })
  }
  observeTicks() {
    if (!observer.isRegistered('api.tick')) {
      const apiTick = (tick) => {
        this.ticks = [...this.ticks, tick]
        this.ticks.splice(0, 1)
        if (this.running) {
          this.purchaseCtrl.updateTicks({
            ticks: this.ticks,
            candles: this.candles,
          })
        }
        observer.emit('bot.tickUpdate', {
          ticks: this.ticks,
          candles: this.candles,
          pip: this.pip,
        })
      }
      observer.register('api.tick', apiTick)
    }
  }
  observeOhlc() {
    if (!observer.isRegistered('api.ohlc')) {
      const apiOHLC = (candle) => {
        if (this.candles.length && this.candles.slice(-1)[0].epoch === candle.epoch) {
          this.candles = [...this.candles.slice(0, -1), candle]
        } else {
          this.candles = [...this.candles, candle]
          this.candles.splice(0, 1)
        }
      }
      observer.register('api.ohlc', apiOHLC)
    }
  }
  observeBeforePurchase() {
    if (!observer.isRegistered('beforePurchase.ready')) {
      const beforePurchaseReady = () => {
        if (this.running) {
          observer.emit('bot.waiting_for_purchase')
        }
      }
      observer.register('beforePurchase.ready', beforePurchaseReady)
    }
  }
  observeTradeUpdate() {
    if (!observer.isRegistered('beforePurchase.tradeUpdate')) {
      const beforePurchaseTradeUpdate = (contract) => {
        if (this.running) {
          observer.emit('bot.tradeUpdate', contract)
        }
      }
      observer.register('beforePurchase.tradeUpdate', beforePurchaseTradeUpdate)
    }
  }
  observeStreams() {
    this.observeTradeUpdate()
    this.observeBeforePurchase()
    this.observeTicks()
    this.observeOhlc()
  }
  subscribeProposal(tradeOption) {
    const apiProposal = (proposal) => {
      if (this.running) {
        observer.emit('log.bot.proposal', proposal)
        this.purchaseCtrl.updateProposal(proposal)
      }
    }
    observer.register('api.proposal', apiProposal, false, {
      type: 'proposal',
      unregister: [
        ['api.proposal', apiProposal],
        'beforePurchase.ready',
        'bot.waiting_for_purchase',
      ],
    })
    this.unregisterOnFinish.push(['api.proposal', apiProposal])
    this.api.proposal(tradeOption)
  }
  subscribeProposals() {
    this.setTradeOptions()
    observer.unregisterAll('api.proposal')
    this.api.originalApi.unsubscribeFromAllProposals().then(() => {
      for (const to of this.tradeOptions) {
        this.subscribeProposal(to)
      }
    }, () => 0)
  }
  waitForBeforePurchaseFinish() {
    const beforePurchaseFinish = (contract) => {
      this.botFinish(contract)
    }
    observer.register('beforePurchase.finish', beforePurchaseFinish, true, null, true)
    this.unregisterOnFinish.push(['beforePurchase.finish', beforePurchaseFinish])
  }
  waitForTradePurchase() {
    const tradePurchase = () => {
      this.totalRuns += 1
      observer.emit('bot.tradeInfo', {
        totalRuns: this.totalRuns,
      })
    }
    observer.register('trade.purchase', tradePurchase, true, null, true)
    this.unregisterOnFinish.push(['trade.purchase', tradePurchase])
  }
  startTrading() {
    this.waitForBeforePurchaseFinish()
    this.waitForTradePurchase()
    this.subscribeProposals()
  }
  updateTotals(contract) {
    const profit = +(Number(contract.sell_price) - Number(contract.buy_price)).toFixed(2)
    const user = getToken(this.currentToken)
    observer.emit('log.revenue', {
      user,
      profit,
      contract,
    })

    if (+profit > 0) {
      this.totalWins += 1
    } else if (+profit < 0) {
      this.totalLosses += 1
    }
    this.totalProfit = +(this.totalProfit + profit).toFixed(2)
    this.totalStake = +(this.totalStake + Number(contract.buy_price)).toFixed(2)
    this.totalPayout = +(this.totalPayout + Number(contract.sell_price)).toFixed(2)

    observer.emit('bot.tradeInfo', {
      totalProfit: this.totalProfit,
      totalWins: this.totalWins,
      totalLosses: this.totalLosses,
      totalStake: this.totalStake,
      totalPayout: this.totalPayout,
    })
  }
  botFinish(contract) {
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    this.updateTotals(contract)
    observer.emit('bot.finish', contract)
    // order matters
    this.running = false
    this.purchaseCtrl.destroy()
    this.purchaseCtrl = null
  //
  }
  stop(contract) {
    if (!this.running) {
      observer.emit('bot.stop', contract)
      return
    }
    for (const obs of this.unregisterOnFinish) {
      observer.unregisterAll(...obs)
    }
    this.unregisterOnFinish = []
    // order matters
    this.running = false
    if (this.purchaseCtrl) {
      this.purchaseCtrl.destroy()
      this.purchaseCtrl = null
    }
    //
    this.api.originalApi.unsubscribeFromAllProposals().then(() => 0, () => 0)
    if (contract) {
      observer.emit('log.bot.stop', contract)
    }
    observer.emit('bot.stop', contract)
  }
}

export const bot = process.browser ? new Bot() : null
<|endoftext|>


<commit_before>var q = require('bluebird');
var registry = require("npm-registry");
var _ = require('underscore');

var database = require("./lib/database.js");

// crawlers
var keywords = require("npm-keywords");
var ghClient = require("./lib/github.js");
var npmClient = require("./lib/npm.js");
var npmHistory = require("./lib/npmHistory.js");

// helpers
var postProcessor = require("./lib/util/postProcessor.js");

var workflow = function(opts) {
  this.keys = opts.keys || [];
  this.refreshTime = opts.refreshTime || 3600;
  this.updateInterval = opts.updateInterval || 60;
  this.db = new database();
  this.dbLoad = this.db.load();
  this.pkgs = [];
  this.npm = new registry({
    registry: opts.registryURL
  });
};

workflow.prototype.start = function() {
  return this.run().then(function() {
    this.reloadCron = setInterval(this.run.bind(this), this.refreshTime * 1000);
    this.updateCron = setInterval(this.updateCronJob.bind(this), this.updateInterval * 1000);
  }.bind(this));
};

// 1) download package list
workflow.prototype.run = function run() {
  var self = this;
  return keywords(this.keys, this.npm).map(this.downloadPkg.bind(this)).then(function(pkgs) {
    // on succes:  save to DB
    console.log("workflow: trying to save into DB.");
    self.pkgs = pkgs.map(function(el) {
      return {
        name: el.name,
        version: el.version
      };
    });
    self.dbLoad
      .then(self.db.loadCache.bind(self.db))
      .then(function() {
        return self.db.save(pkgs);
      });
  }).then(function() {
    console.log("workflow: load complete.");
  });
};

// 2) crawl the package from NPM
workflow.prototype.downloadPkg = function(name) {
  // also support pkg object with name attribute
  if (name.name !== undefined) {
    name = name.name;
  }
  return new npmClient(name, this.npm).then(this.postDownload.bind(this));
};

// 3) other info
workflow.prototype.postDownload = function(pkg) {
  var postOpts = {
    keys: this.keys
  };
  var ps = [];
  ps.push(new ghClient(pkg));
  ps.push(new npmHistory(pkg));
  return q.all(ps).then(function() {
    return postProcessor(pkg, postOpts);
  }).catch(function(err) {
    if (err != undefined && err.name !== "queryEvents") {
      // event errors can happen - ignore them
      console.log("downloaderr", err);
    } else {
      console.log(arguments);
    }
    return pkg;
  });
};

// update a single pkg
workflow.prototype.updatePkg = function(pkg) {
  return this.downloadPkg(pkg).then(function(newPkg) {
    var index = _.indexOf(_.pluck(this.pkgs, "name"), newPkg.name);
    this.pkgs[index] = newPkg;
    this.db.updatePkg(newPkg);
    console.log("package update saved: ", newPkg.name);
  }.bind(this)).catch(function(err) {
    console.log("err during package update: ", pkg.name);
    console.log(err);
  });
};

// crons the npm registry manually and checks for package updates
workflow.prototype.updateCronJob = function updateCronJob() {
  var self = this;
  this.pkgs.forEach(function(oldPkg) {
    return new npmClient(oldPkg.name + "@latest", this.npm).then(function(newPkg) {
      // we have only the latest version -> download entire package
      if (oldPkg.version !== newPkg.version && newPkg.name !== undefined) {
        console.log("new package uploaded: ", newPkg.name);
        self.updatePkg(newPkg.name);
      }
    }.bind(this));
  });
};

workflow.prototype.stop = function() {
  clearInterval(this.updateCron);
  clearInterval(this.reloadCron);
};

module.exports = workflow;
<commit_msg>fix in auto refreshing (wrong npm repo)<commit_after>var q = require('bluebird');
var registry = require("npm-registry");
var _ = require('underscore');

var database = require("./lib/database.js");

// crawlers
var keywords = require("npm-keywords");
var ghClient = require("./lib/github.js");
var npmClient = require("./lib/npm.js");
var npmHistory = require("./lib/npmHistory.js");

// helpers
var postProcessor = require("./lib/util/postProcessor.js");

var workflow = function(opts) {
  this.keys = opts.keys || [];
  this.refreshTime = opts.refreshTime || 3600;
  this.updateInterval = opts.updateInterval || 60;
  this.db = new database();
  this.dbLoad = this.db.load();
  this.pkgs = [];
  this.npm = new registry({
    registry: opts.registryURL
  });
};

workflow.prototype.start = function() {
  return this.run().then(function() {
    this.reloadCron = setInterval(this.run.bind(this), this.refreshTime * 1000);
    this.updateCron = setInterval(this.updateCronJob.bind(this), this.updateInterval * 1000);
  }.bind(this));
};

// 1) download package list
workflow.prototype.run = function run() {
  var self = this;
  return keywords(this.keys, this.npm).map(this.downloadPkg.bind(this)).then(function(pkgs) {
    // on succes:  save to DB
    console.log("workflow: trying to save into DB.");
    self.pkgs = pkgs.map(function(el) {
      return {
        name: el.name,
        version: el.version
      };
    });
    self.dbLoad
      .then(self.db.loadCache.bind(self.db))
      .then(function() {
        return self.db.save(pkgs);
      });
  }).then(function() {
    console.log("workflow: load complete.");
  });
};

// 2) crawl the package from NPM
workflow.prototype.downloadPkg = function(name) {
  // also support pkg object with name attribute
  if (name.name !== undefined) {
    name = name.name;
  }
  return new npmClient(name, this.npm).then(this.postDownload.bind(this));
};

// 3) other info
workflow.prototype.postDownload = function(pkg) {
  var postOpts = {
    keys: this.keys
  };
  var ps = [];
  ps.push(new ghClient(pkg));
  ps.push(new npmHistory(pkg));
  return q.all(ps).then(function() {
    return postProcessor(pkg, postOpts);
  }).catch(function(err) {
    if (err != undefined && err.name !== "queryEvents") {
      // event errors can happen - ignore them
      console.log("downloaderr", err);
    } else {
      console.log(arguments);
    }
    return pkg;
  });
};

// update a single pkg
workflow.prototype.updatePkg = function(pkg) {
  return this.downloadPkg(pkg).then(function(newPkg) {
    var index = _.indexOf(_.pluck(this.pkgs, "name"), newPkg.name);
    this.pkgs[index] = newPkg;
    this.db.updatePkg(newPkg);
    console.log("package update saved: ", newPkg.name);
  }.bind(this)).catch(function(err) {
    console.log("err during package update: ", pkg.name);
    console.log(err);
  });
};

// crons the npm registry manually and checks for package updates
workflow.prototype.updateCronJob = function updateCronJob() {
  var self = this;
  this.pkgs.forEach(function(oldPkg) {
    return new npmClient(oldPkg.name + "@latest", self.npm).then(function(newPkg) {
      // we have only the latest version -> download entire package
      if (oldPkg.version != newPkg.version && newPkg.name != undefined) {
        console.log("new package uploaded: ", newPkg.name, newPkg.version, oldPkg.version);
        self.updatePkg(newPkg.name);
      }
    }.bind(this));
  });
};

workflow.prototype.stop = function() {
  clearInterval(this.updateCron);
  clearInterval(this.reloadCron);
};

module.exports = workflow;
<|endoftext|>


<commit_before>import Company from '../Company/company'

/**
 * Class representing a Broker
 * @memberof module:parties
 * @extends module:parties.Company
 */
class Broker extends Company {
  /**
   * Construct a new Broker instance
   * @param {object} params - Broker creation options:
   * @param {number} params.assetManagerId - Asset Manager ID of the Broker __(required)__
   * @param {string} params.partyId - Party ID of the Broker __(required)__
   * @param {string} [params.partyStatus=Active] - Status of the Broker
   * @param {string} [params.baseCurrency] - Base Currency of the Broker (e.g. SGD, USD)
   * @param {string} [params.description] - Description of the Broker
   * @param {string} [params.licenseNumber] - Company license number (if applicable)
   * @param {string} [params.licenseType] - Company license type
   * @param {string} [params.assetsUnderManagement] - Value of assets under management
   * @param {string} [params.registrationNumber] - Business registration number (if applicable)
   * @param {string} [params.yearOfIncorporation] - Year of incorporation
   * @param {string} [params.contactNumber] - Contact number
   * @param {object} [params.addresses] - Object of Addresses associated with the Broker
   * @param {object} [params.emails] - Object of Emails associated with the Broker
   * @param {object} [params.references] - Object of References associated with the Broker
   * @param {object} [params.comments] - Object of Comments associated with the Broker
   * @param {object} [params.links] - Object of Links associated with the Broker
   * @param {string} [params.legalName]- Legal name of the Asset Manager associated with this party
   * @param {string} [params.displayName] - Display name of the Asset Manager associated with this party
   * @param {string} [params.url] - Url of this Party
   * @param {string} [params.createdBy] - ID of the user that created the Broker
   * @param {string} [params.updatedBy] - ID of the user that updated the Broker
   * @param {date} [params.createdTime] - Time that the Broker was created
   * @param {date} [params.updatedTime] - Time that the Broker was updated
   * @param {number} [params.version] - Version number of the Broker
   */
  constructor({
    assetManagerId,
    partyId,
    partyStatus='Active',
    baseCurrency,
    description='',
    yearOfIncorporation,
    contactNumber,
    addresses={},
    emails={},
    references={},
    comments={},
    links={},
    legalName,
    displayName,
    url,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version
  }) {
    super({
      assetManagerId,
      partyId,
      partyStatus,
      baseCurrency,
      description,
      yearOfIncorporation,
      contactNumber,
      addresses,
      emails,
      references,
      comments,
      links,
      legalName,
      displayName,
      url,
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
  }
}

export default Broker
<commit_msg>Update broker.js<commit_after>import Company from '../Company/company'

/**
 * Class representing a Broker
 * @memberof module:parties
 * @extends module:parties.Company
 */
class Broker extends Company {
  /**
   * Construct a new Broker instance
   * @param {object} params - Broker creation options:
   * @param {number} params.assetManagerId - Asset Manager ID of the Broker __(required)__
   * @param {string} params.partyId - Party ID of the Broker __(required)__
   * @param {string} [params.partyStatus=Active] - Status of the Broker
   * @param {string} [params.baseCurrency] - Base Currency of the Broker (e.g. SGD, USD)
   * @param {string} [params.description] - Description of the Broker
   * @param {string} [params.licenseNumber] - Company license number (if applicable)
   * @param {string} [params.licenseType] - Company license type
   * @param {string} [params.assetsUnderManagement] - Value of assets under management
   * @param {string} [params.registrationNumber] - Business registration number (if applicable)
   * @param {string} [params.yearOfIncorporation] - Year of incorporation
   * @param {object} [params.addresses] - Object of Addresses associated with the Broker
   * @param {object} [params.emails] - Object of Emails associated with the Broker
   * @param {object} [params.references] - Object of References associated with the Broker
   * @param {object} [params.comments] - Object of Comments associated with the Broker
   * @param {object} [params.links] - Object of Links associated with the Broker
   * @param {string} [params.legalName]- Legal name of the Asset Manager associated with this party
   * @param {string} [params.displayName] - Display name of the Asset Manager associated with this party
   * @param {string} [params.url] - Url of this Party
   * @param {string} [params.createdBy] - ID of the user that created the Broker
   * @param {string} [params.updatedBy] - ID of the user that updated the Broker
   * @param {date} [params.createdTime] - Time that the Broker was created
   * @param {date} [params.updatedTime] - Time that the Broker was updated
   * @param {number} [params.version] - Version number of the Broker
   */
  constructor({
    assetManagerId,
    partyId,
    partyStatus='Active',
    baseCurrency,
    description='',
    yearOfIncorporation,
    addresses={},
    emails={},
    references={},
    comments={},
    links={},
    legalName,
    displayName,
    url,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version
  }) {
    super({
      assetManagerId,
      partyId,
      partyStatus,
      baseCurrency,
      description,
      yearOfIncorporation,
      addresses,
      emails,
      references,
      comments,
      links,
      legalName,
      displayName,
      url,
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
  }
}

export default Broker
<|endoftext|>


<commit_before>define(['pex/sys/Platform', 'pex/sys/EjectaPolyfills'], function(Platform, EjectaPolyfills) {
  var requestAnimFrameFps = 60;

  if (Platform.isBrowser) {
    window.requestAnimFrame = (function() {
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / requestAnimFrameFps);
              };
    })();
  }

  var eventListeners = [];

  function fireEvent(eventType, event) {
    for(var i=0; i<eventListeners.length; i++) {
      if (eventListeners[i].eventType == eventType) {
        eventListeners[i].handler(event);
      }
    }
  }

  function registerEvents(canvas) {
    makeMouseDownHandler(canvas);
    makeMouseUpHandler(canvas);
    makeMouseDraggedHandler(canvas);
    makeMouseMovedHandler(canvas);
    makeScrollWheelHandler(canvas);
    makeTouchDownHandler(canvas);
    makeTouchUpHandler(canvas);
    makeTouchMoveHandler(canvas);
    makeKeyDownHandler(canvas);
  }

  function makeMouseDownHandler(canvas) {
    canvas.addEventListener('mousedown', function(e) {
      fireEvent('leftMouseDown', {
        x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    })
  }

  function makeMouseUpHandler(canvas) {
    canvas.addEventListener('mouseup', function(e) {
      fireEvent('leftMouseUp', {
        x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      })
    })
  }

  function makeMouseDraggedHandler(canvas) {
    var down = false;
    var px = 0;
    var py = 0;
    canvas.addEventListener('mousedown', function(e) {
      down = true;
      px = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio;
      py = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio;
    });
    canvas.addEventListener('mouseup', function(e) {
      down = false;
    });
    canvas.addEventListener('mousemove', function(e) {
      if (down) {
        var x = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio;
        var y = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio;
        fireEvent('mouseDragged', {
          x: x,
          y: y,
          dx: x - px,
          dy: y - py,
          option: e.altKey,
          shift: e.shiftKey,
          control: e.ctrlKey
        });
        px = x;
        py = y;
      }
    })
  }

  function makeMouseMovedHandler(canvas) {
    canvas.addEventListener('mousemove', function(e) {
      fireEvent('mouseMoved', {
        x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    })
  }

  function makeScrollWheelHandler(canvas) {
    var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel'
    document.addEventListener(mousewheelevt, function(e) {
      fireEvent('scrollWheel', {
        x: (e.offsetX || e.layerX) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY) * window.devicePixelRatio,
        dy: e.wheelDelta/10 || -e.detail/10,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    });
  }

  var lastTouch = null;
  function makeTouchDownHandler(canvas) {
    canvas.addEventListener('touchstart', function(e) {
      lastTouch = {
        clientX : (e.touches[0].clientX) * window.devicePixelRatio,
        clientY : (e.touches[0].clientY) * window.devicePixelRatio
      };
      fireEvent('leftMouseDown', {
        x: (e.touches[0].clientX) * window.devicePixelRatio,
        y: (e.touches[0].clientY) * window.devicePixelRatio,
        option: false,
        shift: false,
        control: false
      });
    })
  }

  function makeTouchUpHandler(canvas) {
    canvas.addEventListener('touchend', function(e) {
      fireEvent('leftMouseUp', {
        x: lastTouch ? lastTouch.clientX : 0,
        y: lastTouch ? lastTouch.clientY : 0,
        option: false,
        shift: false,
        control: false
      });
      lastTouch = null;
    })
  }

   function makeTouchMoveHandler(canvas) {
    canvas.addEventListener('touchmove', function(e) {
      lastTouch = {
        clientX : (e.touches[0].clientX) * window.devicePixelRatio,
        clientY : (e.touches[0].clientY) * window.devicePixelRatio
      };
      fireEvent('mouseDragged', {
        x: (e.touches[0].clientX) * window.devicePixelRatio,
        y: (e.touches[0].clientY) * window.devicePixelRatio,
        option: false,
        shift: false,
        control: false
      });
    })
  }

  function makeKeyDownHandler(canvas) {
    var timeout = 0;
    window.addEventListener('keydown', function(e) {
      timeout = setTimeout(function() {
        fireEvent('keyDown', {
          str: '',
          keyCode: e.keyCode,
          option: e.altKey,
          shift: e.shiftKey,
          control: e.ctrlKey
        }, 1);
      })
    })
    window.addEventListener('keypress', function(e) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = 0;
      }
      fireEvent('keyDown', {
        str: String.fromCharCode(e.charCode),
        keyCode: e.keyCode,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    })
  }

  function simpleWindow(obj) {
    var canvas = obj.settings.canvas;

    if (obj.settings.fullscreen) {
       obj.settings.width = window.innerWidth;
       obj.settings.height = window.innerHeight;
    }

    if (!canvas) {
      canvas = document.getElementById('canvas');
    }
    else if (obj.settings.width && obj.setttings.height) {
      canvas.width = obj.settings.width;
      canvas.height = obj.settings.height;
    }
    else {
      obj.settings.width = canvas.width;
      obj.settings.height = canvas.height;
    }

    if (!canvas) {
      canvas = document.createElement('canvas');
      canvas.width = obj.settings.width;
      canvas.height = obj.settings.height;
    }

    if (Platform.isEjecta && (window.devicePixelRatio == 2)) {
      canvas.width = obj.settings.width * 2;
      canvas.height = obj.settings.height * 2;
      canvas.style.width = obj.settings.width;
      canvas.style.height = obj.settings.height;
      obj.settings.width *= 2;
      obj.settings.height *= 2;
    }

    obj.width = obj.settings.width;
    obj.height = obj.settings.height;
    obj.canvas = canvas;

    canvas.style.backgroundColor = '#000000';

    function go() {
      if (obj.stencil === undefined) obj.stencil = false;
      if (obj.settings.fullscreen) {
        document.body.style.margin = '0';
        document.body.style.padding = '0';
        document.body.style.overflow = 'hidden';
      }

      var gl = null;
      var ctx = null;

      if (obj.settings.type == '3d') {
        try {
          gl = canvas.getContext('experimental-webgl'); //, {antialias: true, premultipliedAlpha : true, stencil: obj.settings.stencil}
        }
        catch(err){
          console.error(err.message);
          return;
        }
      }
      else if (obj.settings.type == '2d') {
        ctx = canvas.getContext('2d');
      }

      obj.framerate = function(fps) {
        requestAnimFrameFps = fps;
      }

      obj.on = function(eventType, handler) {
        eventListeners.push({eventType:eventType, handler:handler});
      }

      registerEvents(canvas);

      obj.dispose = function() {
        obj.__disposed = true;
      }

      obj.gl = gl;
      obj.ctx = ctx;
      obj.init();

      function drawloop() {
        if (!obj.__disposed) {
          obj.draw();
          requestAnimFrame(drawloop);
        }
      }

      requestAnimFrame(drawloop);
    }

    if (!canvas.parentNode) {
      if (document.body) {
        document.body.appendChild(canvas);
        go();
      }
      else {
        window.addEventListener('load', function() {
          document.body.appendChild(canvas);
          go();
        }, false);
      }
    }
    else {
      go();
    }

    return obj;
  }

  var BrowserWindow = {
    simpleWindow : simpleWindow
  }

  return BrowserWindow;
});<commit_msg>Enabled antialiasing in BrowserWindow by default<commit_after>define(['pex/sys/Platform', 'pex/sys/EjectaPolyfills'], function(Platform, EjectaPolyfills) {
  var requestAnimFrameFps = 60;

  if (Platform.isBrowser) {
    window.requestAnimFrame = (function() {
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / requestAnimFrameFps);
              };
    })();
  }

  var eventListeners = [];

  function fireEvent(eventType, event) {
    for(var i=0; i<eventListeners.length; i++) {
      if (eventListeners[i].eventType == eventType) {
        eventListeners[i].handler(event);
      }
    }
  }

  function registerEvents(canvas) {
    makeMouseDownHandler(canvas);
    makeMouseUpHandler(canvas);
    makeMouseDraggedHandler(canvas);
    makeMouseMovedHandler(canvas);
    makeScrollWheelHandler(canvas);
    makeTouchDownHandler(canvas);
    makeTouchUpHandler(canvas);
    makeTouchMoveHandler(canvas);
    makeKeyDownHandler(canvas);
  }

  function makeMouseDownHandler(canvas) {
    canvas.addEventListener('mousedown', function(e) {
      fireEvent('leftMouseDown', {
        x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    })
  }

  function makeMouseUpHandler(canvas) {
    canvas.addEventListener('mouseup', function(e) {
      fireEvent('leftMouseUp', {
        x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      })
    })
  }

  function makeMouseDraggedHandler(canvas) {
    var down = false;
    var px = 0;
    var py = 0;
    canvas.addEventListener('mousedown', function(e) {
      down = true;
      px = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio;
      py = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio;
    });
    canvas.addEventListener('mouseup', function(e) {
      down = false;
    });
    canvas.addEventListener('mousemove', function(e) {
      if (down) {
        var x = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio;
        var y = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio;
        fireEvent('mouseDragged', {
          x: x,
          y: y,
          dx: x - px,
          dy: y - py,
          option: e.altKey,
          shift: e.shiftKey,
          control: e.ctrlKey
        });
        px = x;
        py = y;
      }
    })
  }

  function makeMouseMovedHandler(canvas) {
    canvas.addEventListener('mousemove', function(e) {
      fireEvent('mouseMoved', {
        x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    })
  }

  function makeScrollWheelHandler(canvas) {
    var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel'
    document.addEventListener(mousewheelevt, function(e) {
      fireEvent('scrollWheel', {
        x: (e.offsetX || e.layerX) * window.devicePixelRatio,
        y: (e.offsetY || e.layerY) * window.devicePixelRatio,
        dy: e.wheelDelta/10 || -e.detail/10,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    });
  }

  var lastTouch = null;
  function makeTouchDownHandler(canvas) {
    canvas.addEventListener('touchstart', function(e) {
      lastTouch = {
        clientX : (e.touches[0].clientX) * window.devicePixelRatio,
        clientY : (e.touches[0].clientY) * window.devicePixelRatio
      };
      fireEvent('leftMouseDown', {
        x: (e.touches[0].clientX) * window.devicePixelRatio,
        y: (e.touches[0].clientY) * window.devicePixelRatio,
        option: false,
        shift: false,
        control: false
      });
    })
  }

  function makeTouchUpHandler(canvas) {
    canvas.addEventListener('touchend', function(e) {
      fireEvent('leftMouseUp', {
        x: lastTouch ? lastTouch.clientX : 0,
        y: lastTouch ? lastTouch.clientY : 0,
        option: false,
        shift: false,
        control: false
      });
      lastTouch = null;
    })
  }

   function makeTouchMoveHandler(canvas) {
    canvas.addEventListener('touchmove', function(e) {
      lastTouch = {
        clientX : (e.touches[0].clientX) * window.devicePixelRatio,
        clientY : (e.touches[0].clientY) * window.devicePixelRatio
      };
      fireEvent('mouseDragged', {
        x: (e.touches[0].clientX) * window.devicePixelRatio,
        y: (e.touches[0].clientY) * window.devicePixelRatio,
        option: false,
        shift: false,
        control: false
      });
    })
  }

  function makeKeyDownHandler(canvas) {
    var timeout = 0;
    window.addEventListener('keydown', function(e) {
      timeout = setTimeout(function() {
        fireEvent('keyDown', {
          str: '',
          keyCode: e.keyCode,
          option: e.altKey,
          shift: e.shiftKey,
          control: e.ctrlKey
        }, 1);
      })
    })
    window.addEventListener('keypress', function(e) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = 0;
      }
      fireEvent('keyDown', {
        str: String.fromCharCode(e.charCode),
        keyCode: e.keyCode,
        option: e.altKey,
        shift: e.shiftKey,
        control: e.ctrlKey
      });
    })
  }

  function simpleWindow(obj) {
    var canvas = obj.settings.canvas;

    if (obj.settings.fullscreen) {
       obj.settings.width = window.innerWidth;
       obj.settings.height = window.innerHeight;
    }

    if (!canvas) {
      canvas = document.getElementById('canvas');
    }
    else if (obj.settings.width && obj.setttings.height) {
      canvas.width = obj.settings.width;
      canvas.height = obj.settings.height;
    }
    else {
      obj.settings.width = canvas.width;
      obj.settings.height = canvas.height;
    }

    if (!canvas) {
      canvas = document.createElement('canvas');
      canvas.width = obj.settings.width;
      canvas.height = obj.settings.height;
    }

    if (Platform.isEjecta && (window.devicePixelRatio == 2)) {
      canvas.width = obj.settings.width * 2;
      canvas.height = obj.settings.height * 2;
      canvas.style.width = obj.settings.width;
      canvas.style.height = obj.settings.height;
      obj.settings.width *= 2;
      obj.settings.height *= 2;
    }

    obj.width = obj.settings.width;
    obj.height = obj.settings.height;
    obj.canvas = canvas;

    canvas.style.backgroundColor = '#000000';

    function go() {
      if (obj.stencil === undefined) obj.stencil = false;
      if (obj.settings.fullscreen) {
        document.body.style.margin = '0';
        document.body.style.padding = '0';
        document.body.style.overflow = 'hidden';
      }

      var gl = null;
      var ctx = null;

      if (obj.settings.type == '3d') {
        try {
          gl = canvas.getContext('experimental-webgl', {antialias: true}); //, {antialias: true, premultipliedAlpha : true, stencil: obj.settings.stencil}
        }
        catch(err){
          console.error(err.message);
          return;
        }
        if (gl == null) {
          throw 'No WebGL context is available.'
        }
      }
      else if (obj.settings.type == '2d') {
        ctx = canvas.getContext('2d');
      }

      obj.framerate = function(fps) {
        requestAnimFrameFps = fps;
      }

      obj.on = function(eventType, handler) {
        eventListeners.push({eventType:eventType, handler:handler});
      }

      registerEvents(canvas);

      obj.dispose = function() {
        obj.__disposed = true;
      }

      obj.gl = gl;
      obj.ctx = ctx;
      obj.init();

      function drawloop() {
        if (!obj.__disposed) {
          obj.draw();
          requestAnimFrame(drawloop);
        }
      }

      requestAnimFrame(drawloop);
    }

    if (!canvas.parentNode) {
      if (document.body) {
        document.body.appendChild(canvas);
        go();
      }
      else {
        window.addEventListener('load', function() {
          document.body.appendChild(canvas);
          go();
        }, false);
      }
    }
    else {
      go();
    }

    return obj;
  }

  var BrowserWindow = {
    simpleWindow : simpleWindow
  }

  return BrowserWindow;
});<|endoftext|>


<commit_before>'use strict';

// Production specific configuration
// ==================================
var production = {
    server: {
        staticDir : '/../../dist'
    },

    // MongoDB connection options
    mongodb: {
        uri: 'mongodb://localhost/devnews-dev'
    },

    seedDB: false
};

// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.MONGOLAB_URI) {
    production.mongodb.uri = process.env.MONGOLAB_URI;
} else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
    production.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}

module.exports = production;
<commit_msg>Initialize database on startup<commit_after>'use strict';

// Production specific configuration
// ==================================
var production = {
    server: {
        staticDir : '/../../dist'
    },

    // MongoDB connection options
    mongodb: {
        uri: 'mongodb://localhost/devnews-dev'
    },

    seedDB: true
};

// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.MONGOLAB_URI) {
    production.mongodb.uri = process.env.MONGOLAB_URI;
} else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
    production.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}

module.exports = production;
<|endoftext|>


<commit_before>exports.myFirstProject =
{
  "connections":[
    {
      "kind":"addConnection",
      "startNodeId":398809118,
      "startPortIndex":0,
      "endNodeId":23624844,
      "endPortIndex":0,
      "_id":964734507,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":604762864,
      "startPortIndex":0,
      "endNodeId":398809118,
      "endPortIndex":0,
      "_id":647386019,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":598617458,
      "startPortIndex":0,
      "endNodeId":23624844,
      "endPortIndex":1,
      "_id":564971549,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":3271050,
      "startPortIndex":0,
      "endNodeId":598617458,
      "endPortIndex":2,
      "_id":742143501,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":440238000,
      "startPortIndex":0,
      "endNodeId":42665510,
      "endPortIndex":0,
      "_id":661808583,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":42665510,
      "startPortIndex":0,
      "endNodeId":945248858,
      "endPortIndex":0,
      "_id":359041827,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":604762864,
      "startPortIndex":0,
      "endNodeId":398809118,
      "endPortIndex":1,
      "_id":899758279,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":823934643,
      "startPortIndex":0,
      "endNodeId":42665510,
      "endPortIndex":1,
      "_id":764520692,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":794491759,
      "endPortIndex":1,
      "endNodeId":440238000,
      "startPortIndex":0,
      "startNodeId":282252545,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":965267809,
      "endPortIndex":2,
      "endNodeId":440238000,
      "startPortIndex":0,
      "startNodeId":498266200,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":267211310,
      "endPortIndex":0,
      "endNodeId":317753978,
      "startPortIndex":0,
      "startNodeId":440238000,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":573083411,
      "endPortIndex":2,
      "endNodeId":42665510,
      "startPortIndex":0,
      "startNodeId":317753978,
      "kind":"addConnection"
    }
  ],
  "nodes":[
    {
      "name":"DefaultNodeName",
      "position":[
        596,
        119
      ],
      "typeName":"SolidExtrusion",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        true,
        false
      ],
      "_id":23624844,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        350,
        67
      ],
      "typeName":"RegularPolygon",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":398809118,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        62,
        85
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":604762864,
      "replication":"applyLongest",
      "extra":{
        "value":8,
        "min":0,
        "step":0.1,
        "max":20
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        351,
        181
      ],
      "typeName":"Vector",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":598617458,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        63,
        230
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":3271050,
      "replication":"applyLongest",
      "extra":{
        "max":40,
        "step":0.1,
        "min":-40,
        "value":15
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        346,
        449
      ],
      "typeName":"Range",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":440238000,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        859,
        452
      ],
      "typeName":"Vector",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":42665510,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        1006,
        451
      ],
      "typeName":"Point",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false
      ],
      "_id":945248858,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        47,
        442
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":282252545,
      "replication":"applyLongest",
      "extra":{
        "max":100,
        "step":0.1,
        "min":0,
        "value":20
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        534,
        486
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":823934643,
      "replication":"applyLongest",
      "extra":{
        "max":150,
        "step":0.1,
        "min":-150,
        "value":30
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        50,
        532
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":498266200,
      "replication":"applyLongest",
      "extra":{
        "max":150,
        "step":0.1,
        "min":0,
        "value":150
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        501,
        561
      ],
      "typeName":"Script",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false
      ],
      "_id":317753978,
      "replication":"applyLongest",
      "extra":{
        "script":"10 * Sin(A);"
      }
    }
  ],
  "name":"My First Project",
};

exports.myFirstCustomNode =
{
  "connections":[
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":137881318,
      "endPortIndex":0,
      "endNodeId":263728761,
      "startPortIndex":0,
      "startNodeId":253762878,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":525878839,
      "endPortIndex":1,
      "endNodeId":263728761,
      "startPortIndex":0,
      "startNodeId":253762878,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":144876797,
      "endPortIndex":0,
      "endNodeId":892555475,
      "startPortIndex":0,
      "startNodeId":263728761,
      "kind":"addConnection"
    }
  ],
  "nodes":[
    {
      "name":"DefaultNodeName",
      "position":[
        107,
        161
      ],
      "typeName":"Input",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":253762878,
      "replication":"applyLongest",
      "extra":{
        "name":"X"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        548,
        156
      ],
      "typeName":"Output",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        true
      ],
      "_id":892555475,
      "replication":"applyLongest",
      "extra":{
        "name":"X * X"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        359,
        152
      ],
      "typeName":"Multiply",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false
      ],
      "_id":263728761,
      "replication":"applyLongest",
      "extra":{

      }
    }
  ],
  "name":"My First Custom Node",
  "isCustomNode": true
};<commit_msg>Account for new workspace offset<commit_after>exports.myFirstProject =
{
  "connections":[
    {
      "kind":"addConnection",
      "startNodeId":398809118,
      "startPortIndex":0,
      "endNodeId":23624844,
      "endPortIndex":0,
      "_id":964734507,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":604762864,
      "startPortIndex":0,
      "endNodeId":398809118,
      "endPortIndex":0,
      "_id":647386019,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":598617458,
      "startPortIndex":0,
      "endNodeId":23624844,
      "endPortIndex":1,
      "_id":564971549,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":3271050,
      "startPortIndex":0,
      "endNodeId":598617458,
      "endPortIndex":2,
      "_id":742143501,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":440238000,
      "startPortIndex":0,
      "endNodeId":42665510,
      "endPortIndex":0,
      "_id":661808583,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":42665510,
      "startPortIndex":0,
      "endNodeId":945248858,
      "endPortIndex":0,
      "_id":359041827,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":604762864,
      "startPortIndex":0,
      "endNodeId":398809118,
      "endPortIndex":1,
      "_id":899758279,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "kind":"addConnection",
      "startNodeId":823934643,
      "startPortIndex":0,
      "endNodeId":42665510,
      "endPortIndex":1,
      "_id":764520692,
      "startProxy":false,
      "endProxy":false,
      "startProxyPosition":[
        0,
        0
      ],
      "endProxyPosition":[
        0,
        0
      ],
      "hidden":false
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":794491759,
      "endPortIndex":1,
      "endNodeId":440238000,
      "startPortIndex":0,
      "startNodeId":282252545,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":965267809,
      "endPortIndex":2,
      "endNodeId":440238000,
      "startPortIndex":0,
      "startNodeId":498266200,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":267211310,
      "endPortIndex":0,
      "endNodeId":317753978,
      "startPortIndex":0,
      "startNodeId":440238000,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":573083411,
      "endPortIndex":2,
      "endNodeId":42665510,
      "startPortIndex":0,
      "startNodeId":317753978,
      "kind":"addConnection"
    }
  ],
  "nodes":[
    {
      "name":"DefaultNodeName",
      "position":[
        4596,
        4119
      ],
      "typeName":"SolidExtrusion",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        true,
        false
      ],
      "_id":23624844,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4350,
        467
      ],
      "typeName":"RegularPolygon",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":398809118,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4062,
        4085
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":604762864,
      "replication":"applyLongest",
      "extra":{
        "value":8,
        "min":0,
        "step":0.1,
        "max":20
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4351,
        4181
      ],
      "typeName":"Vector",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":598617458,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4063,
        4230
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":3271050,
      "replication":"applyLongest",
      "extra":{
        "max":40,
        "step":0.1,
        "min":-40,
        "value":15
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4346,
        4449
      ],
      "typeName":"Range",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":440238000,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4859,
        4452
      ],
      "typeName":"Vector",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false,
        false
      ],
      "_id":42665510,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        5006,
        4451
      ],
      "typeName":"Point",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false
      ],
      "_id":945248858,
      "replication":"applyLongest",
      "extra":{
        "script":"A;"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4047,
        4442
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":282252545,
      "replication":"applyLongest",
      "extra":{
        "max":100,
        "step":0.1,
        "min":0,
        "value":20
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4534,
        4486
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":823934643,
      "replication":"applyLongest",
      "extra":{
        "max":150,
        "step":0.1,
        "min":-150,
        "value":30
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4050,
        4532
      ],
      "typeName":"Number",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":498266200,
      "replication":"applyLongest",
      "extra":{
        "max":150,
        "step":0.1,
        "min":0,
        "value":150
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4501,
        4561
      ],
      "typeName":"Script",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false
      ],
      "_id":317753978,
      "replication":"applyLongest",
      "extra":{
        "script":"10 * Sin(A);"
      }
    }
  ],
  "name":"My First Project",
};

exports.myFirstCustomNode =
{
  "connections":[
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":137881318,
      "endPortIndex":0,
      "endNodeId":263728761,
      "startPortIndex":0,
      "startNodeId":253762878,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":525878839,
      "endPortIndex":1,
      "endNodeId":263728761,
      "startPortIndex":0,
      "startNodeId":253762878,
      "kind":"addConnection"
    },
    {
      "hidden":false,
      "endProxyPosition":[
        0,
        0
      ],
      "startProxyPosition":[
        0,
        0
      ],
      "endProxy":false,
      "startProxy":false,
      "_id":144876797,
      "endPortIndex":0,
      "endNodeId":892555475,
      "startPortIndex":0,
      "startNodeId":263728761,
      "kind":"addConnection"
    }
  ],
  "nodes":[
    {
      "name":"DefaultNodeName",
      "position":[
        4107,
        4161
      ],
      "typeName":"Input",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[

      ],
      "_id":253762878,
      "replication":"applyLongest",
      "extra":{
        "name":"X"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4548,
        4156
      ],
      "typeName":"Output",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        true
      ],
      "_id":892555475,
      "replication":"applyLongest",
      "extra":{
        "name":"X * X"
      }
    },
    {
      "name":"DefaultNodeName",
      "position":[
        4359,
        4152
      ],
      "typeName":"Multiply",
      "selected":false,
      "visible":true,
      "ignoreDefaults":[
        false,
        false
      ],
      "_id":263728761,
      "replication":"applyLongest",
      "extra":{

      }
    }
  ],
  "name":"My First Custom Node",
  "isCustomNode": true
};<|endoftext|>


<commit_before>var debug = require('debug')('keystone:core:list:ensureTextIndex');

// A basic string hashing function
function hashString (string) {
	var char;
	var hash = 0;
	if (string.length === 0) return hash;
	for (var i = 0; i < string.length; i++) {
		char = string.charCodeAt(i);
		hash = ((hash << 5) - hash) + char;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
}

/**
 * Does what it can to ensure the collection has an appropriate text index.
 *
 * Works around unreliable behaviour with the Mongo drivers ensureIndex()
 * Specifically, when the following are true..
 *   - Relying on collection.ensureIndexes() to create text indexes
 *   - A text index already exists on the collection
 *   - The existing index has a different definition but the same name
 * The index is not created/updated and no error is returned, either by the
 * ensureIndexes() call or the connection error listener.
 * Or at least that's what was happening for me (mongoose v3.8.40, mongodb v1.4.38)..
 */
function ensureTextIndex (callback) {
	var list = this;
	var collection = list.model.collection;

	var textIndex = list.buildSearchTextIndex();
	var fieldsHash = Math.abs(hashString(Object.keys(textIndex).sort().join(';')));
	var indexNamePrefix = 'keystone_searchFields_textIndex_';
	var newIndexName = indexNamePrefix + fieldsHash;

	// We use this later to create a new index if needed
	var createNewIndex = function () {
		collection.createIndex(textIndex, { name: newIndexName }, function (result) {
			debug('collection.createIndex() result for \'' + list.key + '\:', result);
			return callback();
		});
	};

	collection.getIndexes(function (err, indexes) {
		if (err) throw err;  // Not sure what else to do here..
		var indexNames = Object.keys(indexes);
		// debug('indexes', indexes);
		// debug('indexNames', indexNames);

		// Search though the
		for (var i = 0; i < indexNames.length; i++) {
			var existingIndexName = indexNames[i];
			var isText = false;

			// Check we're dealing with a text index
			for (var h = 0; h < indexes[existingIndexName].length; h++) {
				var column = indexes[existingIndexName][h];
				if (column[1] === 'text') isText = isText || true;
			}

			// Skip non-text indexes
			if (!isText) continue;

			// Already exists with correct def
			if (existingIndexName === newIndexName) {
				debug('Existing text index \'' + existingIndexName + '\' already matches the searchFields for \'' + list.key + '\'');
				return;
			}

			// Exists but hash (def) doesn't match
			// Check for 'searchFields_text_index' for backwards compatibility
			if (existingIndexName.slice(0, indexNamePrefix.length) === indexNamePrefix || existingIndexName === 'searchFields_text_index') {
				debug('Existing text index \'' + existingIndexName + '\' doesn\'t match the searchFields for \'' + list.key + '\' and will be recreated as \'' + newIndexName + '\'');

				collection.dropIndex(existingIndexName, function (result) {
					debug('collection.dropIndex() result for \'' + list.key + '\:', result);
					createNewIndex();
				});
				return;
			}

			// It's a text index but not one of ours; nothing we can do
			debug('Existing text index \'' + existingIndexName + '\' in \'' + list.key + '\' not recognised; no action taken');
			return;
		}

		// No text indexes found at all; create ours now
		debug('No existing text index found in \'' + list.key + '\'; Creating ours now');
		createNewIndex();
	});
}

module.exports = ensureTextIndex;
<commit_msg>Handle mongo error in ensureTextIndex<commit_after>var debug = require('debug')('keystone:core:list:ensureTextIndex');

// A basic string hashing function
function hashString (string) {
	var char;
	var hash = 0;
	if (string.length === 0) return hash;
	for (var i = 0; i < string.length; i++) {
		char = string.charCodeAt(i);
		hash = ((hash << 5) - hash) + char;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
}

/**
 * Does what it can to ensure the collection has an appropriate text index.
 *
 * Works around unreliable behaviour with the Mongo drivers ensureIndex()
 * Specifically, when the following are true..
 *   - Relying on collection.ensureIndexes() to create text indexes
 *   - A text index already exists on the collection
 *   - The existing index has a different definition but the same name
 * The index is not created/updated and no error is returned, either by the
 * ensureIndexes() call or the connection error listener.
 * Or at least that's what was happening for me (mongoose v3.8.40, mongodb v1.4.38)..
 */
function ensureTextIndex (callback) {
	var list = this;
	var collection = list.model.collection;

	var textIndex = list.buildSearchTextIndex();
	var fieldsHash = Math.abs(hashString(Object.keys(textIndex).sort().join(';')));
	var indexNamePrefix = 'keystone_searchFields_textIndex_';
	var newIndexName = indexNamePrefix + fieldsHash;

	// We use this later to create a new index if needed
	var createNewIndex = function () {
		collection.createIndex(textIndex, { name: newIndexName }, function (result) {
			debug('collection.createIndex() result for \'' + list.key + '\:', result);
			return callback();
		});
	};

	collection.getIndexes(function (err, indexes) {
		if (err) {
			if (err.code === 26) {
				// if the database doesn't exist, we'll get error code 26 "no database" here
				// that's fine, we just default the indexes object so the new text index
				// gets created when the database is connected.
				indexes = {};
			} else {
				// otherwise, we've had an unexpected error, so we throw it
				throw err;
			}
		}
		var indexNames = Object.keys(indexes);

		// Search though the
		for (var i = 0; i < indexNames.length; i++) {
			var existingIndexName = indexNames[i];
			var isText = false;

			// Check we're dealing with a text index
			for (var h = 0; h < indexes[existingIndexName].length; h++) {
				var column = indexes[existingIndexName][h];
				if (column[1] === 'text') isText = isText || true;
			}

			// Skip non-text indexes
			if (!isText) continue;

			// Already exists with correct def
			if (existingIndexName === newIndexName) {
				debug('Existing text index \'' + existingIndexName + '\' already matches the searchFields for \'' + list.key + '\'');
				return;
			}

			// Exists but hash (def) doesn't match
			// Check for 'searchFields_text_index' for backwards compatibility
			if (existingIndexName.slice(0, indexNamePrefix.length) === indexNamePrefix || existingIndexName === 'searchFields_text_index') {
				debug('Existing text index \'' + existingIndexName + '\' doesn\'t match the searchFields for \'' + list.key + '\' and will be recreated as \'' + newIndexName + '\'');

				collection.dropIndex(existingIndexName, function (result) {
					debug('collection.dropIndex() result for \'' + list.key + '\:', result);
					createNewIndex();
				});
				return;
			}

			// It's a text index but not one of ours; nothing we can do
			debug('Existing text index \'' + existingIndexName + '\' in \'' + list.key + '\' not recognised; no action taken');
			return;
		}

		// No text indexes found at all; create ours now
		debug('No existing text index found in \'' + list.key + '\'; Creating ours now');
		createNewIndex();
	});
}

module.exports = ensureTextIndex;
<|endoftext|>


<commit_before>/** internal
 *  mixin Paths
 *
 *  An internal mixin whose public methods are exposed on the [[Environment]]
 *  and [[Index]] classes.
 *
 *  Provides helpers to work with `Hike.Trail` instance.
 **/

// REQUIRED PROPERTIES /////////////////////////////////////////////////////////
//
// - `__trail__` (Hike.Trail)
//
////////////////////////////////////////////////////////////////////////////////

'use strict';

// internal
var getter = require('../common').getter;

////////////////////////////////////////////////////////////////////////////////

/**
 *  Paths#root -> String
 *
 *  Returns [[Environment]] root.
 *
 *  All relative paths are expanded with root as its base.
 *  To be useful set this to your applications root directory.
 **/
getter(module.exports, 'root', function () {
  return this.__trail__.root;
});

/**
 *  Paths#paths -> Array
 *
 *  Returns an `Array` of path `String`s.
 *
 *  These paths will be used for asset logical path lookups.
 *
 *  Note that a copy of the `Array` is returned so mutating will
 *  have no affect on the environment. See [[Paths#appendPath]],
 *  [[Paths#prependPath]], and [[Paths#clearPaths]].
 **/
getter(module.exports, 'paths', function () {
  return this.__trail__.paths.toArray();
});

/**
 *  Paths#prependPath(path) -> Void
 *
 *  Prepend a `path` to the `paths` list.
 *  Paths at the end have the least priority.
 **/
module.exports.prependPath = function (path) {
  this.__trail__.paths.prepend(path);
};

/**
 *  Paths#appendPath(path) -> Void
 *
 *  Append a `path` to the `paths` list.
 *  Paths at the beginning have a higher priority.
 **/
module.exports.appendPath = function (path) {
  this.__trail__.paths.append(path);
};

/**
 *  Paths#clearPaths() -> Void
 *
 *  Clear all paths and start fresh.
 *
 *  There is no mechanism for reordering paths, so its best to
 *  completely wipe the paths list and reappend them in the order
 *  you want.
 **/
module.exports.clearPaths = function () {
  var trail = this.__trail__;

  this.paths.forEach(function (path) {
    trail.remove(path);
  });
};

/**
 *  Paths#extensions -> Array
 *
 *  Returns an `Array` of extensions.
 *
 *  These extensions maybe omitted from logical path searches.
 *
 *      [".js", ".css", ".coffee", ".sass", ...]
 **/
getter(module.exports, 'extensions', function () {
  return this.__trail__.extensions.toArray();
});
<commit_msg>Fix #clearPaths mixin<commit_after>/** internal
 *  mixin Paths
 *
 *  An internal mixin whose public methods are exposed on the [[Environment]]
 *  and [[Index]] classes.
 *
 *  Provides helpers to work with `Hike.Trail` instance.
 **/

// REQUIRED PROPERTIES /////////////////////////////////////////////////////////
//
// - `__trail__` (Hike.Trail)
//
////////////////////////////////////////////////////////////////////////////////

'use strict';

// internal
var getter = require('../common').getter;

////////////////////////////////////////////////////////////////////////////////

/**
 *  Paths#root -> String
 *
 *  Returns [[Environment]] root.
 *
 *  All relative paths are expanded with root as its base.
 *  To be useful set this to your applications root directory.
 **/
getter(module.exports, 'root', function () {
  return this.__trail__.root;
});

/**
 *  Paths#paths -> Array
 *
 *  Returns an `Array` of path `String`s.
 *
 *  These paths will be used for asset logical path lookups.
 *
 *  Note that a copy of the `Array` is returned so mutating will
 *  have no affect on the environment. See [[Paths#appendPath]],
 *  [[Paths#prependPath]], and [[Paths#clearPaths]].
 **/
getter(module.exports, 'paths', function () {
  return this.__trail__.paths.toArray();
});

/**
 *  Paths#prependPath(path) -> Void
 *
 *  Prepend a `path` to the `paths` list.
 *  Paths at the end have the least priority.
 **/
module.exports.prependPath = function (path) {
  this.__trail__.paths.prepend(path);
};

/**
 *  Paths#appendPath(path) -> Void
 *
 *  Append a `path` to the `paths` list.
 *  Paths at the beginning have a higher priority.
 **/
module.exports.appendPath = function (path) {
  this.__trail__.paths.append(path);
};

/**
 *  Paths#clearPaths() -> Void
 *
 *  Clear all paths and start fresh.
 *
 *  There is no mechanism for reordering paths, so its best to
 *  completely wipe the paths list and reappend them in the order
 *  you want.
 **/
module.exports.clearPaths = function () {
  var trail = this.__trail__;

  this.paths.forEach(function (path) {
    trail.paths.remove(path);
  });
};

/**
 *  Paths#extensions -> Array
 *
 *  Returns an `Array` of extensions.
 *
 *  These extensions maybe omitted from logical path searches.
 *
 *      [".js", ".css", ".coffee", ".sass", ...]
 **/
getter(module.exports, 'extensions', function () {
  return this.__trail__.extensions.toArray();
});
<|endoftext|>


<commit_before>'use strict'
'use babel'

const {Emitter} = require('atom')

class CallStackModel {
  constructor (service) {
    this.service = service
    this.emitter = new Emitter()

    this.selectedIndex = 0

    this.service.onPaused(this._pausedHandler.bind(this))
  }

  getCallStack () {
    return this.callstack
  }

  getSelectedIndex () {
    return this.selectedIndex
  }

  onChange (handler) {
    return this.emitter.on('changed', handler)
  }

  _pausedHandler (payload) {
    if (payload.command === 'UPDATE_CALLSTACK') {
      this.callstack = payload.callFrames
      this.callstack.forEach((ele, index) => {
        if (ele.callFrameId === payload.currentCallFrameId) {
          this.selectedIndex = index
        }
      }, this)

      this.emitter.emit('changed', this)
    }
  }

  destroy () {
    this.emitter.dispose()
  }
}

module.exports = CallStackModel
<commit_msg>use last call stack when payload is undefined<commit_after>'use strict'
'use babel'

const {Emitter} = require('atom')

class CallStackModel {
  constructor (service) {
    this.service = service
    this.emitter = new Emitter()

    this.selectedIndex = 0

    this.service.onPaused(this._pausedHandler.bind(this))
  }

  getCallStack () {
    return this.callstack
  }

  getSelectedIndex () {
    return this.selectedIndex
  }

  onChange (handler) {
    return this.emitter.on('changed', handler)
  }

  _pausedHandler (payload) {
    if (payload.command === 'UPDATE_CALLSTACK') {
      this.callstack = payload.callFrames || this.callstack
      this.callstack.forEach((ele, index) => {
        if (ele.callFrameId === payload.currentCallFrameId) {
          this.selectedIndex = index
        }
      }, this)

      this.emitter.emit('changed', this)
    }
  }

  destroy () {
    this.emitter.dispose()
  }
}

module.exports = CallStackModel
<|endoftext|>


<commit_before>
"use strict";

const
  moment = require('moment'),
  Promise= require('bluebird'),
  Joi    = require('joi');

const

  schema_user = Joi
    .object()
    .required(),
//    .options({ allowUnknown : true })
//    .keys({
//      promise_total_number_of_days_in_allowance : Joi.func().required(),
//    }),

  schema_year = Joi
    .object()
    .type(moment)
    .default(() => moment.utc(), 'Default year is current one'),

  schema_promise_allowance = Joi.object().required().keys({
    year : schema_year,
    user : schema_user,
  }),

  scheme_constructor = Joi.object().required().keys({
    year : schema_year,
    user : schema_user,
    total_number_of_days_in_allowance     : Joi.number().required(),
    number_of_days_taken_from_allowance   : Joi.number().required(),
  });

class UserAllowance {

  constructor(args) {

    args = Joi.attempt(
      args,
      scheme_constructor,
      'Failed parameters validation for UserAllowance constructor'
    );

    let self = this;

    self._user = args.user;
    self._total_number_of_days_in_allowance     = args.total_number_of_days_in_allowance;
    self._number_of_days_taken_from_allowance   = args.number_of_days_taken_from_allowance;

    Object.defineProperty(self, 'total_number_of_days_in_allowance', {
      get : () => self._total_number_of_days_in_allowance,
    });

    Object.defineProperty(self, 'number_of_days_taken_from_allowance', {
      get : () => self._number_of_days_taken_from_allowance,
    });

    Object.defineProperty(self, 'number_of_days_available_in_allowance', {
      get : () => self.total_number_of_days_in_allowance - self.number_of_days_taken_from_allowance,
    });

  }

  /*
   *  The idea of this static method is to be constructor for UserAllowance class.
   *  It takes parameters and perform all necessary (and costly) actions to fetch
   *  all info required for allowance calculation for given user and year.
   * */
  static promise_allowance(args) {

    args = Joi.attempt(
      args,
      schema_promise_allowance,
      'Failed to validate parameters for promise_allowance'
    );

    let
      user = args.user,
      year = args.year,
      number_of_days_taken_from_allowance,
      total_number_of_days_in_allowance;

    return Promise

      // We code below relies on user to have my_leaves fetched onto it, so do it if needed
      .resolve(
        user.my_leaves === undefined
        ? user.reload_with_leave_details({ year : year })
        : 1
      )

      // Fetch total number of days in employees allowance
      .then(() => promise_total_number_of_days_in_allowance.call(user, year))
      .then(num => Promise.resolve( total_number_of_days_in_allowance = num))

      .then(() => Promise.resolve( number_of_days_taken_from_allowance = user.calculate_number_of_days_taken_from_allowance({ year : year.format('YYYY') }) ))

      // Got all necessary data for UserAllowance object so build it!
      .then(() => {

        return new UserAllowance({
          user : user,
          year : year,

          total_number_of_days_in_allowance     : total_number_of_days_in_allowance,
          number_of_days_taken_from_allowance   : number_of_days_taken_from_allowance,
        });
      });

  }

}

/*
 * THis function used to be a method on user object.
 *
 * */

function promise_total_number_of_days_in_allowance(year){
  let self = this;

  return Promise

    // First ensure that all necessary properties are available
    .try(() => {
      if ( ! self.department) {
        return self.getDepartment()
          .then(department => {
            self.department = department;
            return Promise.resolve();
          })
      }

      return Promise.resolve();
    })

    // Fetch Adjustment and Carried over allowance for current year
    .then(() => self.promise_adjustment_and_carry_over_for_year(year))

    .then(adjustment_and_coa => Promise.resolve(
      self._calculate_total_number_of_days_n_allowance({
        year       : year,
        adjustment : adjustment_and_coa.adjustment,
        carried_over_allowance : adjustment_and_coa.carried_over_allowance,
      })
    ));
};

module.exports = UserAllowance;
<commit_msg>Reduce allwance specific user methods<commit_after>
"use strict";

const
  moment = require('moment'),
  Promise= require('bluebird'),
  Joi    = require('joi');

const

  schema_user = Joi
    .object()
    .required(),
//    .options({ allowUnknown : true })
//    .keys({
//      promise_total_number_of_days_in_allowance : Joi.func().required(),
//    }),

  schema_year = Joi
    .object()
    .type(moment)
    .default(() => moment.utc(), 'Default year is current one'),

  schema_promise_allowance = Joi.object().required().keys({
    year : schema_year,
    user : schema_user,
  }),

  scheme_constructor = Joi.object().required().keys({
    year : schema_year,
    user : schema_user,
    total_number_of_days_in_allowance     : Joi.number().required(),
    number_of_days_taken_from_allowance   : Joi.number().required(),
  });

class UserAllowance {

  constructor(args) {

    args = Joi.attempt(
      args,
      scheme_constructor,
      'Failed parameters validation for UserAllowance constructor'
    );

    let self = this;

    self._user = args.user;
    self._total_number_of_days_in_allowance     = args.total_number_of_days_in_allowance;
    self._number_of_days_taken_from_allowance   = args.number_of_days_taken_from_allowance;

    Object.defineProperty(self, 'total_number_of_days_in_allowance', {
      get : () => self._total_number_of_days_in_allowance,
    });

    Object.defineProperty(self, 'number_of_days_taken_from_allowance', {
      get : () => self._number_of_days_taken_from_allowance,
    });

    Object.defineProperty(self, 'number_of_days_available_in_allowance', {
      get : () => self.total_number_of_days_in_allowance - self.number_of_days_taken_from_allowance,
    });

  }

  /*
   *  The idea of this static method is to be constructor for UserAllowance class.
   *  It takes parameters and perform all necessary (and costly) actions to fetch
   *  all info required for allowance calculation for given user and year.
   * */
  static promise_allowance(args) {

    args = Joi.attempt(
      args,
      schema_promise_allowance,
      'Failed to validate parameters for promise_allowance'
    );

    let
      user = args.user,
      year = args.year,
      number_of_days_taken_from_allowance,
      manual_adjustment,
      carried_over_allowance,
      total_number_of_days_in_allowance;

    return Promise

      .join(
        // We code below relies on user to have my_leaves fetched onto it, so do it if needed
        Promise.resolve(
          user.my_leaves === undefined
          ? user.reload_with_leave_details({ year : year })
          : 1
        ),
        // Ensure that all necessary properties are available
        Promise.resolve(
          user.department === undefined
            ? user.getDepartment().then(dep => Promise.resolve(user.department = dep))
            : 1
        ),
        () => {
          return Promise.resolve();
      })

      // Fetch adjustment and Carry over allowance
      .then(() => user.promise_adjustment_and_carry_over_for_year(year))
      .then(adjustment_and_coa => {
        manual_adjustment      = adjustment_and_coa.adjustment;
        carried_over_allowance = adjustment_and_coa.carried_over_allowance;
        return Promise.resolve();
      })

      // Fetch total number of days in employees allowance
      .then(() => Promise.resolve(
        user._calculate_total_number_of_days_n_allowance({
          year       : year,
          adjustment : manual_adjustment,
          carried_over_allowance : carried_over_allowance,
        })
      ))
      .then(num => Promise.resolve( total_number_of_days_in_allowance = num))

      .then(() => Promise.resolve( number_of_days_taken_from_allowance = user.calculate_number_of_days_taken_from_allowance({ year : year.format('YYYY') }) ))

      // Got all necessary data for UserAllowance object so build it!
      .then(() => {

        return new UserAllowance({
          user : user,
          year : year,

          total_number_of_days_in_allowance     : total_number_of_days_in_allowance,
          number_of_days_taken_from_allowance   : number_of_days_taken_from_allowance,
        });
      });

  }

}

module.exports = UserAllowance;
<|endoftext|>