<commit_before>import Botkit from 'botkit'

class AsyncQueue {
  constructor ({ timeout = Infinity }) {
    this.timeout = timeout
    this.queue = []
    this.waitingForData = []
  }

  enqueue = (message) => {
    this.queue.push(message)
    if (this.waitingForData.length) {
      const resolve = this.waitingForData.shift()
      resolve(this.queue.shift())
    }
  }

  dequeue = () => {
    if (this.queue.length) {
      return Promise.resolve(this.queue.shift())
    } else {
      return new Promise((resolve, reject) => {
        this.waitingForData.push(resolve)

        if (this.timeout < Infinity) {
          const err = new Error('No message received within timeout limit')
          setTimeout(() => reject(err), this.timeout)
        }
      })
    }
  }
}

export default (configuration = {}) => {
  const { timeout = 5000, ...coreConfig } = configuration
  const testBotkit = Botkit.core(coreConfig)

  testBotkit.middleware.spawn.use((bot, next) => {
    bot.initialize()
    next()
  })

  // this needs the "function" cruft to be a "constructor function" :(
  testBotkit.defineBot(function (botkit, config) {
    const bot = {
      botkit: botkit,
      config: config || {},
      utterances: botkit.utterances
    }

    bot.initialize = () => {
      this.responses = new AsyncQueue({ timeout })
    }

    bot.createConversation = (message, cb) => {
      botkit.createConversation(this, message, cb)
    }

    bot.startConversation = (message, cb) => {
      botkit.startConversation(this, message, cb)
    }

    bot.send = (message, cb) => {
      this.responses.enqueue(message)

      console.log('BOT.send:', message.text)
      if (cb) {
        cb()
      }
    }

    bot.reply = (src, resp, cb) => {
      let msg = {}

      if (typeof (resp) === 'string') {
        msg.text = resp
      } else {
        msg = resp
      }

      msg.channel = src.channel

      bot.say(msg, cb)
    }

    bot.userSays = (text) => {
      const message = {
        text,
        user: 'user',
        channel: 'text',
        timestamp: Date.now()
      }
      testBotkit.receiveMessage(this, message)
    }

    bot.nextResponse = () => this.responses.dequeue()

    bot.findConversation = (message, cb) => {
      botkit.debug('CUSTOM FIND CONVO', message.user, message.channel)
      for (var t = 0; t < botkit.tasks.length; t++) {
        for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
          if (
              botkit.tasks[t].convos[c].isActive() &&
              botkit.tasks[t].convos[c].source_message.user == message.user
            ) {
            botkit.debug('FOUND EXISTING CONVO!')
            cb(botkit.tasks[t].convos[c])
            return
          }
        }
      }

      cb()
    }

    return bot
  })

  return testBotkit
}
<commit_msg>Clean up AsyncQueue<commit_after>import Botkit from 'botkit'

class AsyncQueue {
  constructor ({ timeout = Infinity }) {
    this.timeout = timeout
    this.queue = []
    this.waitingForData = []
  }

  enqueue = message => {
    this.queue.push(message)

    if (this.waitingForData.length) {
      const resolve = this.waitingForData.shift()
      resolve(this.queue.shift())
    }
  }

  dequeue = () => new Promise((resolve, reject) => {
    if (this.queue.length) {
      resolve(this.queue.shift())
    } else {
      this.waitingForData.push(resolve)

      if (this.timeout < Infinity) {
        const err = new Error('No message received within timeout limit')
        setTimeout(() => reject(err), this.timeout)
      }
    }
  })
}

export default (configuration = {}) => {
  const { timeout = 5000, ...coreConfig } = configuration
  const testBotkit = Botkit.core(coreConfig)

  testBotkit.middleware.spawn.use((bot, next) => {
    bot.initialize()
    next()
  })

  // this needs the "function" cruft to be a "constructor function" :(
  testBotkit.defineBot(function (botkit, config) {
    const bot = {
      botkit: botkit,
      config: config || {},
      utterances: botkit.utterances
    }

    bot.initialize = () => {
      this.responses = new AsyncQueue({ timeout })
    }

    bot.createConversation = (message, cb) => {
      botkit.createConversation(this, message, cb)
    }

    bot.startConversation = (message, cb) => {
      botkit.startConversation(this, message, cb)
    }

    bot.send = (message, cb) => {
      this.responses.enqueue(message)

      console.log('BOT.send:', message.text)
      if (cb) {
        cb()
      }
    }

    bot.reply = (src, resp, cb) => {
      let msg = {}

      if (typeof (resp) === 'string') {
        msg.text = resp
      } else {
        msg = resp
      }

      msg.channel = src.channel

      bot.say(msg, cb)
    }

    bot.userSays = (text) => {
      const message = {
        text,
        user: 'user',
        channel: 'text',
        timestamp: Date.now()
      }
      testBotkit.receiveMessage(this, message)
    }

    bot.nextResponse = () => this.responses.dequeue()

    bot.findConversation = (message, cb) => {
      botkit.debug('CUSTOM FIND CONVO', message.user, message.channel)
      for (var t = 0; t < botkit.tasks.length; t++) {
        for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
          if (
              botkit.tasks[t].convos[c].isActive() &&
              botkit.tasks[t].convos[c].source_message.user == message.user
            ) {
            botkit.debug('FOUND EXISTING CONVO!')
            cb(botkit.tasks[t].convos[c])
            return
          }
        }
      }

      cb()
    }

    return bot
  })

  return testBotkit
}
<|endoftext|>


<commit_before>'use strict'

const createServer = require('ipfsd-ctl').createServer

const server = createServer()

module.exports = {
  bundlesize: { maxSize: '240kB' },
  webpack: {
    resolve: {
      mainFields: ['browser', 'main']
    }
  },
  karma: {
    files: [{
      pattern: 'node_modules/interface-ipfs-core/test/fixtures/**/*',
      watched: false,
      served: true,
      included: false
    }],
    browserNoActivityTimeout: 210 * 1000,
    singleRun: true
  },
  hooks: {
    browser: {
      pre: () => server.start(),
      post: () => server.stop()
    }
  }
}
<commit_msg>chore: increase bundlesize<commit_after>'use strict'

const createServer = require('ipfsd-ctl').createServer

const server = createServer()

module.exports = {
  bundlesize: { maxSize: '245kB' },
  webpack: {
    resolve: {
      mainFields: ['browser', 'main']
    }
  },
  karma: {
    files: [{
      pattern: 'node_modules/interface-ipfs-core/test/fixtures/**/*',
      watched: false,
      served: true,
      included: false
    }],
    browserNoActivityTimeout: 210 * 1000,
    singleRun: true
  },
  hooks: {
    browser: {
      pre: () => server.start(),
      post: () => server.stop()
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

'use strict';

require('../../setupBabel')();

const Metro = require('metro');

const {Terminal} = require('metro-core');

const messageSocket = require('./util/messageSocket');
const morgan = require('morgan');
const path = require('path');
const webSocketProxy = require('./util/webSocketProxy');
const MiddlewareManager = require('./middleware/MiddlewareManager');

import type {ConfigT} from 'metro-config/src/configTypes.flow';

export type Args = {|
  +assetExts: $ReadOnlyArray<string>,
  +cert: string,
  +customLogReporterPath?: string,
  +host: string,
  +https: boolean,
  +maxWorkers: number,
  +key: string,
  +nonPersistent: boolean,
  +platforms: $ReadOnlyArray<string>,
  +port: number,
  +projectRoot: string,
  +providesModuleNodeModules: Array<string>,
  +resetCache: boolean,
  +sourceExts: $ReadOnlyArray<string>,
  +transformer?: string,
  +verbose: boolean,
  +watchFolders: $ReadOnlyArray<string>,
|};

async function runServer(args: Args, config: ConfigT) {
  const terminal = new Terminal(process.stdout);
  const ReporterImpl = getReporterImpl(args.customLogReporterPath || null);
  const reporter = new ReporterImpl(terminal);
  const middlewareManager = new MiddlewareManager(args);

  middlewareManager.getConnectInstance().use(morgan('combined'));

  args.watchFolders.forEach(middlewareManager.serveStatic);

  config.maxWorkers = args.maxWorkers;
  config.server.port = args.port;
  config.reporter = reporter;
  config.resetCache = args.resetCache;
  config.server.enhanceMiddleware = middleware =>
    middlewareManager.getConnectInstance().use(middleware);

  const serverInstance = await Metro.runServer(config, {
    host: args.host,
    secure: args.https,
    secureCert: args.cert,
    secureKey: args.key,
    hmrEnabled: true,
  });

  const wsProxy = webSocketProxy.attachToServer(
    serverInstance,
    '/debugger-proxy',
  );
  const ms = messageSocket.attachToServer(serverInstance, '/message');
  middlewareManager.attachDevToolsSocket(wsProxy);
  middlewareManager.attachDevToolsSocket(ms);

  // In Node 8, the default keep-alive for an HTTP connection is 5 seconds. In
  // early versions of Node 8, this was implemented in a buggy way which caused
  // some HTTP responses (like those containing large JS bundles) to be
  // terminated early.
  //
  // As a workaround, arbitrarily increase the keep-alive from 5 to 30 seconds,
  // which should be enough to send even the largest of JS bundles.
  //
  // For more info: https://github.com/nodejs/node/issues/13391
  //
  serverInstance.keepAliveTimeout = 30000;
}

function getReporterImpl(customLogReporterPath: ?string) {
  if (customLogReporterPath == null) {
    return require('metro/src/lib/TerminalReporter');
  }
  try {
    // First we let require resolve it, so we can require packages in node_modules
    // as expected. eg: require('my-package/reporter');
    /* $FlowFixMe: can't type dynamic require */
    return require(customLogReporterPath);
  } catch (e) {
    if (e.code !== 'MODULE_NOT_FOUND') {
      throw e;
    }
    // If that doesn't work, then we next try relative to the cwd, eg:
    // require('./reporter');
    /* $FlowFixMe: can't type dynamic require */
    return require(path.resolve(customLogReporterPath));
  }
}

module.exports = runServer;
<commit_msg>Fix ignored --projectRoot/watchFolders arguments (#21165)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

'use strict';

require('../../setupBabel')();

const Metro = require('metro');

const {Terminal} = require('metro-core');

const messageSocket = require('./util/messageSocket');
const morgan = require('morgan');
const path = require('path');
const webSocketProxy = require('./util/webSocketProxy');
const MiddlewareManager = require('./middleware/MiddlewareManager');

import type {ConfigT} from 'metro-config/src/configTypes.flow';

export type Args = {|
  +assetExts: $ReadOnlyArray<string>,
  +cert: string,
  +customLogReporterPath?: string,
  +host: string,
  +https: boolean,
  +maxWorkers: number,
  +key: string,
  +nonPersistent: boolean,
  +platforms: $ReadOnlyArray<string>,
  +port: number,
  +projectRoot: string,
  +providesModuleNodeModules: Array<string>,
  +resetCache: boolean,
  +sourceExts: $ReadOnlyArray<string>,
  +transformer?: string,
  +verbose: boolean,
  +watchFolders: $ReadOnlyArray<string>,
|};

async function runServer(args: Args, config: ConfigT) {
  const terminal = new Terminal(process.stdout);
  const ReporterImpl = getReporterImpl(args.customLogReporterPath || null);
  const reporter = new ReporterImpl(terminal);
  const middlewareManager = new MiddlewareManager(args);

  middlewareManager.getConnectInstance().use(morgan('combined'));

  args.watchFolders.forEach(middlewareManager.serveStatic);

  config.maxWorkers = args.maxWorkers;
  config.server.port = args.port;
  config.reporter = reporter;
  config.resetCache = args.resetCache;
  config.projectRoot = args.projectRoot;
  config.watchFolders = args.watchFolders.slice(0);
  config.server.enhanceMiddleware = middleware =>
    middlewareManager.getConnectInstance().use(middleware);

  const serverInstance = await Metro.runServer(config, {
    host: args.host,
    secure: args.https,
    secureCert: args.cert,
    secureKey: args.key,
    hmrEnabled: true,
  });

  const wsProxy = webSocketProxy.attachToServer(
    serverInstance,
    '/debugger-proxy',
  );
  const ms = messageSocket.attachToServer(serverInstance, '/message');
  middlewareManager.attachDevToolsSocket(wsProxy);
  middlewareManager.attachDevToolsSocket(ms);

  // In Node 8, the default keep-alive for an HTTP connection is 5 seconds. In
  // early versions of Node 8, this was implemented in a buggy way which caused
  // some HTTP responses (like those containing large JS bundles) to be
  // terminated early.
  //
  // As a workaround, arbitrarily increase the keep-alive from 5 to 30 seconds,
  // which should be enough to send even the largest of JS bundles.
  //
  // For more info: https://github.com/nodejs/node/issues/13391
  //
  serverInstance.keepAliveTimeout = 30000;
}

function getReporterImpl(customLogReporterPath: ?string) {
  if (customLogReporterPath == null) {
    return require('metro/src/lib/TerminalReporter');
  }
  try {
    // First we let require resolve it, so we can require packages in node_modules
    // as expected. eg: require('my-package/reporter');
    /* $FlowFixMe: can't type dynamic require */
    return require(customLogReporterPath);
  } catch (e) {
    if (e.code !== 'MODULE_NOT_FOUND') {
      throw e;
    }
    // If that doesn't work, then we next try relative to the cwd, eg:
    // require('./reporter');
    /* $FlowFixMe: can't type dynamic require */
    return require(path.resolve(customLogReporterPath));
  }
}

module.exports = runServer;
<|endoftext|>


<commit_before>import { caution } from '../images';
import { fieldGeneratorMapping } from '../shared';
import { oppositesToDropdown } from '../../utils';
import config from '../../../../common/const';
import { translate } from '../../../../../common/i18n';

export const marketDropdown = block => {
    block
        .appendDummyInput('MARKETDEFINITION')
        .appendField(`${translate('Market')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.MARKET_LIST), 'MARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SUBMARKET_LIST(block)), 'SUBMARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SYMBOL_LIST(block)), 'SYMBOL_LIST');
};

export const tradeTypeDropdown = block => {
    block
        .appendDummyInput('TRADETYPEDEFINITION')
        .appendField(`${translate('Trade Type')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPECAT_LIST(block)), 'TRADETYPECAT_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPE_LIST(block)), 'TRADETYPE_LIST');
};

export const contractTypes = block => {
    if (!block.getInput('CONTRACT_TYPE')) {
        const getContractTypes = () => {
            const tradeType = block.getFieldValue('TRADETYPE_LIST');
            if (tradeType) {
                return [[translate('Both'), 'both'], ...oppositesToDropdown(config.opposites[tradeType.toUpperCase()])];
            }
            return [['', '']];
        };
        block
            .appendDummyInput('CONTRACT_TYPE')
            .appendField(translate('Contract Type:'))
            .appendField(new Blockly.FieldDropdown(getContractTypes), 'TYPE_LIST');
    }
};

export const candleInterval = block => {
    if (!block.getInput('CANDLE_INTERVAL')) {
        block
            .appendDummyInput('CANDLE_INTERVAL')
            .appendField(translate('Default Candle Interval:'))
            .appendField(new Blockly.FieldDropdown(config.candleIntervals.slice(1)), 'CANDLEINTERVAL_LIST');
    }
};

export const duration = block => {
    if (!block.getInput('DURATION')) {
        block
            .appendValueInput('DURATION')
            .setCheck('Number')
            .appendField(translate('Duration:'))
            .appendField(new Blockly.FieldDropdown([['', '']]), 'DURATIONTYPE_LIST');
    }
};

export const payout = block => {
    if (!block.getInput('AMOUNT')) {
        block
            .appendValueInput('AMOUNT')
            .setCheck('Number')
            .appendField(`${translate('Stake')}:`)
            .appendField(new Blockly.FieldDropdown(config.lists.CURRENCY), 'CURRENCY_LIST');
    }
};

export const barrierOffset = block => {
    if (!block.getInput('BARRIEROFFSET')) {
        block
            .appendValueInput('BARRIEROFFSET')
            .setCheck('Number')
            .appendField(`${translate('Barrier Offset')} 1:`)
            .appendField(new Blockly.FieldDropdown(config.barrierTypes), 'BARRIEROFFSETTYPE_LIST');
    } else {
        const barrierOffsetList = block.getField('BARRIEROFFSETTYPE_LIST');

        if (
            !block.workspace.getBlockById('BARRIERVALUE') &&
            !block.getInput('BARRIEROFFSET').connection.isConnected()
        ) {
            const barrierValue = block.workspace.newBlock('math_number', 'BARRIERVALUE');
            barrierOffsetList.setValue('+');
            barrierValue.setFieldValue('0.274', 'NUM');
            barrierValue.setShadow(true);
            barrierValue.outputConnection.connect(block.getInput('BARRIEROFFSET').connection);
            barrierValue.initSvg();
            barrierValue.render();
        }
    }
};

export const secondBarrierOffset = block => {
    if (!block.getInput('SECONDBARRIEROFFSET')) {
        block
            .appendValueInput('SECONDBARRIEROFFSET')
            .setCheck('Number')
            .appendField(`${translate('Barrier Offset')} 2:`)
            .appendField(new Blockly.FieldDropdown(config.barrierTypes), 'SECONDBARRIEROFFSETTYPE_LIST');
    } else {
        const barrierOffsetList = block.getField('SECONDBARRIEROFFSETTYPE_LIST');

        if (
            !block.workspace.getBlockById('SECONDBARRIERVALUE') &&
            !block.getInput('BARRIEROFFSET').connection.isConnected()
        ) {
            const secondBarrierValue = block.workspace.newBlock('math_number', 'SECONDBARRIERVALUE');
            barrierOffsetList.setValue('-');
            secondBarrierValue.setFieldValue('0.274', 'NUM');
            secondBarrierValue.setShadow(true);
            secondBarrierValue.outputConnection.connect(block.getInput('SECONDBARRIEROFFSET').connection);
            secondBarrierValue.initSvg();
            secondBarrierValue.render();
        }
    }
};

export const prediction = block => {
    if (!block.getInput('PREDICTION')) {
        block
            .appendValueInput('PREDICTION')
            .setCheck('Number')
            .appendField(translate('Prediction:'));
    }
};

export const restart = block => {
    block
        .appendDummyInput()
        .appendField(`${translate('Restart buy/sell on error')}`)
        .appendField(`(${translate('disable for better performance')}):`)
        .appendField(new Blockly.FieldCheckbox('FALSE'), 'TIME_MACHINE_ENABLED');
    block
        .appendDummyInput()
        .appendField(`${translate('Restart last trade on error')}`)
        .appendField(`(${translate('bot ignores the unsuccessful trade')}):`)
        .appendField(new Blockly.FieldCheckbox('TRUE'), 'RESTARTONERROR')
        .appendField(new Blockly.FieldImage(caution, 15, 15, '!'));
};
<commit_msg>check connection before adding barrier value<commit_after>import { caution } from '../images';
import { fieldGeneratorMapping } from '../shared';
import { oppositesToDropdown } from '../../utils';
import config from '../../../../common/const';
import { translate } from '../../../../../common/i18n';

export const marketDropdown = block => {
    block
        .appendDummyInput('MARKETDEFINITION')
        .appendField(`${translate('Market')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.MARKET_LIST), 'MARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SUBMARKET_LIST(block)), 'SUBMARKET_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.SYMBOL_LIST(block)), 'SYMBOL_LIST');
};

export const tradeTypeDropdown = block => {
    block
        .appendDummyInput('TRADETYPEDEFINITION')
        .appendField(`${translate('Trade Type')}:`)
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPECAT_LIST(block)), 'TRADETYPECAT_LIST')
        .appendField('>')
        .appendField(new Blockly.FieldDropdown(fieldGeneratorMapping.TRADETYPE_LIST(block)), 'TRADETYPE_LIST');
};

export const contractTypes = block => {
    if (!block.getInput('CONTRACT_TYPE')) {
        const getContractTypes = () => {
            const tradeType = block.getFieldValue('TRADETYPE_LIST');
            if (tradeType) {
                return [[translate('Both'), 'both'], ...oppositesToDropdown(config.opposites[tradeType.toUpperCase()])];
            }
            return [['', '']];
        };
        block
            .appendDummyInput('CONTRACT_TYPE')
            .appendField(translate('Contract Type:'))
            .appendField(new Blockly.FieldDropdown(getContractTypes), 'TYPE_LIST');
    }
};

export const candleInterval = block => {
    if (!block.getInput('CANDLE_INTERVAL')) {
        block
            .appendDummyInput('CANDLE_INTERVAL')
            .appendField(translate('Default Candle Interval:'))
            .appendField(new Blockly.FieldDropdown(config.candleIntervals.slice(1)), 'CANDLEINTERVAL_LIST');
    }
};

export const duration = block => {
    if (!block.getInput('DURATION')) {
        block
            .appendValueInput('DURATION')
            .setCheck('Number')
            .appendField(translate('Duration:'))
            .appendField(new Blockly.FieldDropdown([['', '']]), 'DURATIONTYPE_LIST');
    }
};

export const payout = block => {
    if (!block.getInput('AMOUNT')) {
        block
            .appendValueInput('AMOUNT')
            .setCheck('Number')
            .appendField(`${translate('Stake')}:`)
            .appendField(new Blockly.FieldDropdown(config.lists.CURRENCY), 'CURRENCY_LIST');
    }
};

export const barrierOffset = block => {
    if (!block.getInput('BARRIEROFFSET')) {
        block
            .appendValueInput('BARRIEROFFSET')
            .setCheck('Number')
            .appendField(`${translate('Barrier Offset')} 1:`)
            .appendField(new Blockly.FieldDropdown(config.barrierTypes), 'BARRIEROFFSETTYPE_LIST');
    } else {
        const barrierOffsetList = block.getField('BARRIEROFFSETTYPE_LIST');

        if (
            !block.workspace.getBlockById('BARRIERVALUE') &&
            !block.getInput('BARRIEROFFSET').connection.isConnected()
        ) {
            const barrierValue = block.workspace.newBlock('math_number', 'BARRIERVALUE');
            barrierOffsetList.setValue('+');
            barrierValue.setFieldValue('0.274', 'NUM');
            barrierValue.setShadow(true);
            barrierValue.outputConnection.connect(block.getInput('BARRIEROFFSET').connection);
            barrierValue.initSvg();
            barrierValue.render();
        }
    }
};

export const secondBarrierOffset = block => {
    if (!block.getInput('SECONDBARRIEROFFSET')) {
        block
            .appendValueInput('SECONDBARRIEROFFSET')
            .setCheck('Number')
            .appendField(`${translate('Barrier Offset')} 2:`)
            .appendField(new Blockly.FieldDropdown(config.barrierTypes), 'SECONDBARRIEROFFSETTYPE_LIST');
    } else {
        const barrierOffsetList = block.getField('SECONDBARRIEROFFSETTYPE_LIST');

        if (
            !block.workspace.getBlockById('SECONDBARRIERVALUE') &&
            !block.getInput('SECONDBARRIEROFFSET').connection.isConnected()
        ) {
            const secondBarrierValue = block.workspace.newBlock('math_number', 'SECONDBARRIERVALUE');
            barrierOffsetList.setValue('-');
            secondBarrierValue.setFieldValue('0.274', 'NUM');
            secondBarrierValue.setShadow(true);
            secondBarrierValue.outputConnection.connect(block.getInput('SECONDBARRIEROFFSET').connection);
            secondBarrierValue.initSvg();
            secondBarrierValue.render();
        }
    }
};

export const prediction = block => {
    if (!block.getInput('PREDICTION')) {
        block
            .appendValueInput('PREDICTION')
            .setCheck('Number')
            .appendField(translate('Prediction:'));
    }
};

export const restart = block => {
    block
        .appendDummyInput()
        .appendField(`${translate('Restart buy/sell on error')}`)
        .appendField(`(${translate('disable for better performance')}):`)
        .appendField(new Blockly.FieldCheckbox('FALSE'), 'TIME_MACHINE_ENABLED');
    block
        .appendDummyInput()
        .appendField(`${translate('Restart last trade on error')}`)
        .appendField(`(${translate('bot ignores the unsuccessful trade')}):`)
        .appendField(new Blockly.FieldCheckbox('TRUE'), 'RESTARTONERROR')
        .appendField(new Blockly.FieldImage(caution, 15, 15, '!'));
};
<|endoftext|>


<commit_before>
var rewire     = require('rewire');
var proxyquire = require('proxyquire');

switch (process.argv[2]) {
	// The "start" script is run during development mode
	case 'start':
		rewireModule('react-scripts/scripts/start.js', loadCustomizer('../webpack.config.dev.extension'));
		break;

	// The "build" script is run to produce a production bundle
	case 'build':
		rewireModule('react-scripts/scripts/build.js', loadCustomizer('../webpack.config.prod.extension'));
		break;

	// The "test" script runs all the tests with Jest
	case 'test':
		let customizer = loadCustomizer('../webpack.config.testing.extension');
		proxyquire('react-scripts/scripts/test.js', {
			// When test.js asks for '../utils/createJestConfig' it will get this instead:
			'../utils/createJestConfig': (...args) => {
				// Use the existing createJestConfig function to create a config, then pass
				// it through the customizer
				var createJestConfig = require('react-scripts/utils/createJestConfig');
				return customizer(createJestConfig(...args));
			}
		});
		break;

	default:
		console.log('custom-config only supports "start", "build", and "test" options.');
		process.exit(-1);
}

// Attempt to load the given module and return null if it fails.
function loadCustomizer(module) {
	try {
		return require(module);
	} catch (e) {
		if (e.code !== "MODULE_NOT_FOUND") throw e;
	}

	// If the module doesn't exist, return a
	// noop that simply returns the config it's given.
	return config => config;
}

function rewireModule(modulePath, customizer) {
	// Load the module with `rewire`, which allows modifying the
	// script's internal variables.
	let defaults = rewire(modulePath);

	// Reach into the module, grab its global 'config' variable,
	// pass it through the customizer function, and then set it back.
	// 'config' is Create React App's built-in Webpack config.
	let config = defaults.__get__('config');
	config = customizer(Object.assign({}, config));
	defaults.__set__('config', config);
}
<commit_msg>fix indent<commit_after>var rewire     = require('rewire');
var proxyquire = require('proxyquire');

switch (process.argv[2]) {
		// The "start" script is run during development mode
    case 'start':
        rewireModule('react-scripts/scripts/start.js', loadCustomizer('../webpack.config.dev.extension'));
        break;

		// The "build" script is run to produce a production bundle
    case 'build':
        rewireModule('react-scripts/scripts/build.js', loadCustomizer('../webpack.config.prod.extension'));
        break;

		// The "test" script runs all the tests with Jest
    case 'test':
        let customizer = loadCustomizer('../webpack.config.testing.extension');
        proxyquire('react-scripts/scripts/test.js', {
            // When test.js asks for '../utils/createJestConfig' it will get this instead:
            '../utils/createJestConfig': (...args) => {
                // Use the existing createJestConfig function to create a config, then pass
                // it through the customizer
                var createJestConfig = require('react-scripts/utils/createJestConfig');
                return customizer(createJestConfig(...args));
            }
        });
        break;

	default:
        console.log('custom-config only supports "start", "build", and "test" options.');
        process.exit(-1);
}

// Attempt to load the given module and return null if it fails.
function loadCustomizer(module) {
    try {
        return require(module);
	} catch (e) {
		if (e.code !== "MODULE_NOT_FOUND")
			throw e;
    }

    // If the module doesn't exist, return a
    // noop that simply returns the config it's given.
    return config => config;
}

function rewireModule(modulePath, customizer) {
    // Load the module with `rewire`, which allows modifying the
    // script's internal variables.
    let defaults = rewire(modulePath);

    // Reach into the module, grab its global 'config' variable,
    // pass it through the customizer function, and then set it back.
    // 'config' is Create React App's built-in Webpack config.
    let config = defaults.__get__('config');
    config = customizer(Object.assign({}, config));
    defaults.__set__('config', config);
}
<|endoftext|>


<commit_before>var moment = require('moment')
var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')

chai.use(chaiAsPromised)
var assert = chai.assert

var StandingOrder = artifacts.require('StandingOrder')

let owner = web3.eth.accounts[0]
let payee = web3.eth.accounts[1]
let otherUser = web3.eth.accounts[2]
let paymentAmount = web3.toBigNumber(web3.toWei(1, 'finney'))
let fundAmount = web3.toBigNumber(web3.toWei(10, 'finney'))
let order, startBalance, newBalance, gasUsed, unclaimedFunds, gasPrice

describe('Checking collectFunds', function () {

    before('Create a standingOrder', function () {
        let interval = 120 // two minutes
        let startTime = moment() // First payment due now
        let label = 'testorder'

        return StandingOrder.new(owner, payee, interval, paymentAmount, startTime.unix(), label,
            {
                from: owner,
            })
            .then(function (instance) {
                // console.log("Created new order at " + instance.address)
                order = instance
            })
    })

    before('Fund order', function () {
        return order.send(fundAmount, {from: owner})
            .then(function (result) {
                assert.isNotNull(result.receipt.blockHash)
                assert(web3.eth.getBalance(order.address).equals(fundAmount))
            })
    })

    before('Get payees current balance', function () {
        // get current payee balance
        startBalance = web3.eth.getBalance(payee)
        newBalance = startBalance
        assert.isAbove(startBalance.toNumber(), web3.toWei(10, 'ether'))
    })

    describe('Checking access', function () {
        it('should throw when owner calls collectFunds', function () {
            return assert.isRejected(
                order.collectFunds({from: owner}),
                /invalid opcode/
            )
        })

        it('should throw when non-payee calls collectFunds', function () {
            return assert.isRejected(
                order.collectFunds({from: otherUser}),
                /invalid opcode/
            )
        })
    })

    describe('Checking collect', function () {

        it('should get correct unclaimed funds', function () {
            return order.getUnclaimedFunds.call({from: payee}).then(function (_unclaimedFunds) {
                unclaimedFunds = _unclaimedFunds
                assert(unclaimedFunds.equals(paymentAmount), 'unclaimedFunds should match paymentAmount!')
            })
        })

        it('should call collectFunds', function done() {
            return order.collectFunds({from: payee})
                .then(function (result) {
                    assert.isNotNull(result.receipt.blockHash)
                    assert.isNotNull(result.receipt.blockNumber)
                    gasUsed = result.receipt.gasUsed
                    gasPrice = web3.eth.getTransaction(result.tx).gasPrice
                    // there should be one log event named "Collect"
                    assert.equal('Collect', result.logs[0].event)
                    // the first (and only) argument is the amount collected
                    //console.log(result.logs[0].args['amount'])
                    assert(unclaimedFunds.equals(result.logs[0].args['amount']))
                })
        })

        it('should correctly increase payees balance', function () {
            newBalance = web3.eth.getBalance(payee)
            let diff = newBalance.minus(startBalance) // how much did balance increase
            diff = diff.plus(gasPrice.mul(gasUsed)) // take gas usage into account
            if (!diff.equals(unclaimedFunds)) {
                let missing = unclaimedFunds.minus(diff)
                console.log("Missing " + missing.toString() + " wei")
                console.log("Did you run testrpc with -g option? You HAVE to specify it to get correct value for web3.eth.gasPrice!")
            }
            assert(diff.equals(unclaimedFunds), "Account balance should be increased by unclaimedFunds")
        })

        it('should correctly decrease contract balance', function () {
            assert(web3.eth.getBalance(order.address).equals(fundAmount.minus(paymentAmount)))
        })

    })

})

<commit_msg>Create Event when collecting funds.<commit_after>var moment = require('moment')
var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')

chai.use(chaiAsPromised)
var assert = chai.assert

var StandingOrder = artifacts.require('StandingOrder')

let owner = web3.eth.accounts[0]
let payee = web3.eth.accounts[1]
let otherUser = web3.eth.accounts[2]
let paymentAmount = web3.toBigNumber(web3.toWei(1, 'finney'))
let fundAmount = web3.toBigNumber(web3.toWei(10, 'finney'))
let order, startBalance, newBalance, gasUsed, unclaimedFunds, gasPrice

describe('Checking collectFunds', function () {

    before('Create a standingOrder', function () {
        let interval = 120 // two minutes
        let startTime = moment() // First payment due now
        let label = 'testorder'

        return StandingOrder.new(owner, payee, interval, paymentAmount, startTime.unix(), label,
            {
                from: owner,
            })
            .then(function (instance) {
                // console.log("Created new order at " + instance.address)
                order = instance
            })
    })

    before('Fund order', function () {
        return order.send(fundAmount, {from: owner})
            .then(function (result) {
                assert.isNotNull(result.receipt.blockHash)
                assert(web3.eth.getBalance(order.address).equals(fundAmount))
            })
    })

    before('Get payees current balance', function () {
        // get current payee balance
        startBalance = web3.eth.getBalance(payee)
        newBalance = startBalance
        assert.isAbove(startBalance.toNumber(), web3.toWei(10, 'ether'))
    })

    describe('Checking access', function () {
        it('should throw when owner calls collectFunds', function () {
            return assert.isRejected(
                order.collectFunds({from: owner}),
                /invalid opcode/
            )
        })

        it('should throw when non-payee calls collectFunds', function () {
            return assert.isRejected(
                order.collectFunds({from: otherUser}),
                /invalid opcode/
            )
        })
    })

    describe('Checking collect', function () {

        it('should get correct unclaimed funds', function () {
            return order.getUnclaimedFunds.call({from: payee}).then(function (_unclaimedFunds) {
                unclaimedFunds = _unclaimedFunds
                assert(unclaimedFunds.equals(paymentAmount), 'unclaimedFunds should match paymentAmount!')
            })
        })

        it('should call collectFunds', function done() {
            return order.collectFunds({from: payee})
                .then(function (result) {
                    assert.isNotNull(result.receipt.blockHash)
                    assert.isNotNull(result.receipt.blockNumber)
                    gasUsed = result.receipt.gasUsed
                    gasPrice = web3.eth.getTransaction(result.tx).gasPrice
                    // there should be one log event named "Collect"
                    assert.equal('Collect', result.logs[0].event)
                    // the first (and only) argument is the amount collected
                    assert(unclaimedFunds.equals(result.logs[0].args['amount']))
                })
        })

        it('should correctly increase payees balance', function () {
            newBalance = web3.eth.getBalance(payee)
            let diff = newBalance.minus(startBalance) // how much did balance increase
            diff = diff.plus(gasPrice.mul(gasUsed)) // take gas usage into account
            if (!diff.equals(unclaimedFunds)) {
                let missing = unclaimedFunds.minus(diff)
                console.log("Missing " + missing.toString() + " wei")
                console.log("Did you run testrpc with -g option? You HAVE to specify it to get correct value for web3.eth.gasPrice!")
            }
            assert(diff.equals(unclaimedFunds), "Account balance should be increased by unclaimedFunds")
        })

        it('should correctly decrease contract balance', function () {
            assert(web3.eth.getBalance(order.address).equals(fundAmount.minus(paymentAmount)))
        })

    })

})

<|endoftext|>


<commit_before>var assert = require('assert')
  , WebSocket = require('../')
  , WebSocketServer = WebSocket.Server
  , fs = require('fs');
require('should');

var port = 20000;

function getArrayBuffer(buf) {
  var l = buf.length;
  var arrayBuf = new ArrayBuffer(l);
  for (var i = 0; i < l; ++i) {
    arrayBuf[i] = buf[i];
  }
  return arrayBuf;
}

function areArraysEqual(x, y) {
  if (x.length != y.length) return false;
  for (var i = 0, l = x.length; i < l; ++i) {
    if (x[i] !== y[i]) return false;
  }
  return true;
}

describe('WebSocketServer', function() {
  describe('#ctor', function() {
    it('throws an error if no option object is passed', function() {
      var gotException = false;
      try {
        var wss = new WebSocketServer();
      }
      catch (e) {
        gotException = true;
      }
      gotException.should.be.ok;
    })
    it('throws an error if no port is specified', function() {
      var gotException = false;
      try {
        var wss = new WebSocketServer({});
      }
      catch (e) {
        gotException = true;
      }
      gotException.should.be.ok;
    })
    it('emits an error if http server bind fails', function(done) {
      var wss = new WebSocketServer({port: 1});
      wss.on('error', function() { done(); })
    })
  })

  describe('#close', function() {
    it('will close all clients', function(done) {
      var wss = new WebSocketServer({port: ++port}, function() {
        var ws = new WebSocket('ws://localhost:' + port);
        ws.on('close', function() {
          if (++closes == 2) done();
        });
      });
      var closes = 0;
      wss.on('connection', function(client) {
        client.on('close', function() {
          if (++closes == 2) done();
        });
        wss.close();
      });
    })
  })

  it('starts a server at the given port', function(done) {
    var wss = new WebSocketServer({port: ++port}, function() {
      var ws = new WebSocket('ws://localhost:' + port);
    });
    wss.on('connection', function(client) {
      wss.close();
      done();
    });
  })

  it('can send data', function(done) {
    var wss = new WebSocketServer({port: ++port}, function() {
      var ws = new WebSocket('ws://localhost:' + port);
      ws.on('message', function(data, flags) {
        data.should.eql('hello!');
        wss.close();
        done();
      });
    });
    wss.on('connection', function(client) {
      client.send('hello!');
    });
  })

  describe('#clients', function() {
    it('returns a list of connected clients', function(done) {
      var wss = new WebSocketServer({port: ++port}, function() {
        wss.clients.length.should.eql(0);
        var ws = new WebSocket('ws://localhost:' + port);
      });
      wss.on('connection', function(client) {
        wss.clients.length.should.eql(1);
        wss.close();
        done();
      });
    })
    it('is updated when client terminates the connection', function(done) {
      var ws;
      var wss = new WebSocketServer({port: ++port}, function() {
        ws = new WebSocket('ws://localhost:' + port);
      });
      wss.on('connection', function(client) {
        client.on('close', function() {
          wss.clients.length.should.eql(0);
          wss.close();
          done();
        });
        ws.terminate();
      });
    })
    it('is updated when client closes the connection', function(done) {
      var ws;
      var wss = new WebSocketServer({port: ++port}, function() {
        ws = new WebSocket('ws://localhost:' + port);
      });
      wss.on('connection', function(client) {
        client.on('close', function() {
          wss.clients.length.should.eql(0);
          wss.close();
          done();
        });
        ws.close();
      });
    })
  })
})

<commit_msg>Test attaching `WebSocketServer` to a HTTP server<commit_after>var assert = require('assert')
  , http = require('http')
  , WebSocket = require('../')
  , WebSocketServer = WebSocket.Server
  , fs = require('fs');
require('should');

var port = 20000;

function getArrayBuffer(buf) {
  var l = buf.length;
  var arrayBuf = new ArrayBuffer(l);
  for (var i = 0; i < l; ++i) {
    arrayBuf[i] = buf[i];
  }
  return arrayBuf;
}

function areArraysEqual(x, y) {
  if (x.length != y.length) return false;
  for (var i = 0, l = x.length; i < l; ++i) {
    if (x[i] !== y[i]) return false;
  }
  return true;
}

describe('WebSocketServer', function() {
  describe('#ctor', function() {
    it('throws an error if no option object is passed', function() {
      var gotException = false;
      try {
        var wss = new WebSocketServer();
      }
      catch (e) {
        gotException = true;
      }
      gotException.should.be.ok;
    })
    it('throws an error if no port is specified', function() {
      var gotException = false;
      try {
        var wss = new WebSocketServer({});
      }
      catch (e) {
        gotException = true;
      }
      gotException.should.be.ok;
    })
    it('emits an error if http server bind fails', function(done) {
      var wss = new WebSocketServer({port: 1});
      wss.on('error', function() { done(); })
    })
    it('uses passed server object', function () {
      var srv = http.createServer()
        , wss = new WebSocketServer({server: srv});
      wss._server.should.equal(srv);
    });
  })

  describe('#close', function() {
    it('will close all clients', function(done) {
      var wss = new WebSocketServer({port: ++port}, function() {
        var ws = new WebSocket('ws://localhost:' + port);
        ws.on('close', function() {
          if (++closes == 2) done();
        });
      });
      var closes = 0;
      wss.on('connection', function(client) {
        client.on('close', function() {
          if (++closes == 2) done();
        });
        wss.close();
      });
    })
  })

  it('starts a server at the given port', function(done) {
    var wss = new WebSocketServer({port: ++port}, function() {
      var ws = new WebSocket('ws://localhost:' + port);
    });
    wss.on('connection', function(client) {
      wss.close();
      done();
    });
  })

  it('works with a http server', function (done) {
    var srv = http.createServer();
    srv.listen(++port, function () {
      var wss = new WebSocketServer({server: srv});
      var ws = new WebSocket('ws://localhost:' + port);

      wss.on('connection', function(client) {
        wss.close();
        done();
      });
    });
  })

  it('can send data', function(done) {
    var wss = new WebSocketServer({port: ++port}, function() {
      var ws = new WebSocket('ws://localhost:' + port);
      ws.on('message', function(data, flags) {
        data.should.eql('hello!');
        wss.close();
        done();
      });
    });
    wss.on('connection', function(client) {
      client.send('hello!');
    });
  })

  describe('#clients', function() {
    it('returns a list of connected clients', function(done) {
      var wss = new WebSocketServer({port: ++port}, function() {
        wss.clients.length.should.eql(0);
        var ws = new WebSocket('ws://localhost:' + port);
      });
      wss.on('connection', function(client) {
        wss.clients.length.should.eql(1);
        wss.close();
        done();
      });
    })
    it('is updated when client terminates the connection', function(done) {
      var ws;
      var wss = new WebSocketServer({port: ++port}, function() {
        ws = new WebSocket('ws://localhost:' + port);
      });
      wss.on('connection', function(client) {
        client.on('close', function() {
          wss.clients.length.should.eql(0);
          wss.close();
          done();
        });
        ws.terminate();
      });
    })
    it('is updated when client closes the connection', function(done) {
      var ws;
      var wss = new WebSocketServer({port: ++port}, function() {
        ws = new WebSocket('ws://localhost:' + port);
      });
      wss.on('connection', function(client) {
        client.on('close', function() {
          wss.clients.length.should.eql(0);
          wss.close();
          done();
        });
        ws.close();
      });
    })
  })
})

<|endoftext|>


<commit_before>/* RUN: LOG_LEVEL=off mocha test/18-exchange-promises.js */

var Promise = require('bluebird');

module.exports = SeeAbove;

function SeeAbove() {
}

SeeAbove.prototype.methodName1 = function (opts, callback) {

  if (opts.errorAs == 'callback') return callback(new Error('THIS IS JUST A TEST'));
  if (opts.errorAs == 'throw') throw new Error('THIS IS JUST A TEST');

  opts.number++;
  callback(null, opts);
};

SeeAbove.prototype.callCallbackTwice = function (opts, callback) {
  opts.number++;
  callback(null, opts);

  setTimeout(function () {
    callback(null, {number: opts.number + 1});
  }, 100);
};

SeeAbove.prototype.fireAndForget = function (opts) {
  //do nothing
};

SeeAbove.prototype.promiseMethod = Promise.promisify(function (opts, callback) {

  if (opts.errorAs == 'callback') return callback(new Error('THIS IS JUST A TEST WITH CALLBACK ERROR'));
  if (opts.errorAs == 'throw') throw new Error('THIS IS JUST A TEST THAT THROWS AN ERROR');

  opts.number++;
  callback(null, opts);

});

SeeAbove.prototype.promisePromiseCaller = Promise.promisify(function (opts, callback) {

  this.promiseMethod(opts)
    .then(function () {
      callback(null, opts);
    })
    .catch(callback)

});

SeeAbove.prototype.promiseCaller = function (opts, callback) {

  this.promiseMethod(opts)
    .then(function () {
      callback(null, opts);
    })
    .catch(callback)

};

SeeAbove.prototype.promiseReturner = function (opts) {
  return this.promiseMethod(opts);
};

SeeAbove.prototype.synchronousMethodHappnOrigin = function (opts, opts2, $happn, $origin) {

  if (!$happn) throw new Error('$happn is meant to exist');
  if (!$origin) throw new Error('$origin is meant to exist');

  return opts + opts2;
};

SeeAbove.prototype.synchronousMethod = function (opts, opts2) {
  return opts + opts2;
};

SeeAbove.prototype.$happner = {
  config: {
    'component': {
      schema: {
        methods: {
          'methodName1': {
            alias: 'ancientmoth'
          },
          'synchronousMethod': {
            type: 'sync-promise'//NB - this is how you can wrap a synchronous method with a promise
          },
          'synchronousMethodHappnOrigin': {
            type: 'sync-promise'//NB - this is how you can wrap a synchronous method with a promise
          },
          'fireAndForget': {
            type: 'sync'
          }
        }
      }
    }
  }
};

if (global.TESTING_18) return; // When 'requiring' the module above,
// don't run the tests below
//.............
var should = require('chai').should();

describe('a8 - exchange supports promises', function () {

  require('benchmarket').start();
  after(require('benchmarket').store());

  var Mesh = require('../');
  var mesh;

  this.timeout(120000);

  before(function (done) {

    global.TESTING_18 = true; //.............

    mesh = this.mesh = new Mesh();

    mesh.initialize({
      dataLayer: {
        setOptions: {
          timeout: 1000
        }
      },
      util: {
        //logLevel: 'trace'
      },
      modules: {
        'component': {
          path: __filename   // .............
        }
      },
      components: {
        'component': {}
      }
    }, function (err) {
      delete global.TESTING_18; //.............
      if (err) return done(err);
      done();
    });
  });

  after(function (done) {
    mesh.stop({reconnect: false}, done);
  });

  it('supports non-promises in the exchange', function (done) {

    this.mesh.exchange.component.methodName1({number: 1}, function (err, res) {

      res.should.eql({number: 2});
      done();

    });

  });

  it('supports promises in the exchange', function (done) {

    this.mesh.exchange.component.methodName1({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('the promise implementation supports .catch from callback error', function (done) {

    this.mesh.exchange.component.methodName1({errorAs: 'callback'})

      .then(function (res) {
        done(new Error('did not catch'));
      })

      .catch(function (err) {
        err.should.match(/THIS IS JUST A TEST/);
        done();
      })

  });

  it('the promise implementation supports .catch from thrown error', function (done) {

    this.mesh.exchange.component.methodName1({errorAs: 'throw'})

      .then(function (res) {
        console.log(res);
        done(new Error('did not catch'));
      })

      .catch(function (err) {
        err.should.match(/THIS IS JUST A TEST/);
        done();
      })

  });

  it('supports non-promises on the alias', function (done) {

    this.mesh.exchange.component.ancientmoth({number: 1}, function (err, res) {

      res.should.eql({number: 2});
      done();

    });

  })

  it('supports promises on the alias', function (done) {

    this.mesh.exchange.component.ancientmoth({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      });

  });

  it('supports fire and forget', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.methodName1({errorAs: 'throw'});
    done();
  });

  it('supports calling a synchronous method and getting a promise back', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.synchronousMethod(1, 2)

      .then(function (res) {
        res.should.eql(3);
        done();
      })

      .catch(function (err) {
        done(err);
      })
    ;

  });

  it('supports calling a synchronous method with $happn and $origin and getting a promise back', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.synchronousMethodHappnOrigin(1, 2)

      .then(function (res) {
        res.should.eql(3);
        done();
      })

      .catch(function (err) {
        done(err);
      })
    ;

  });

  it('supports calling a synchronous method fire and forget', function (done) {

    this.timeout(1500);
    this.mesh.exchange.component.synchronousMethod(1, 2);
    done();

  });

  it('supports exposing a promise on the exchange', function (done) {

    this.mesh.exchange.component.promiseMethod({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports calling a promise from a promise on the exchange', function (done) {

    this.timeout(1500);
    var _this = this;

    this.mesh.exchange.component.promisePromiseCaller({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      }.bind(_this))

  });

  it('supports calling a promise from a method on the exchange', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseCaller({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports returning a promise from a method on the exchange', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturner({number: 1})
      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports returning a promise from a method on the exchange that throws an error', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturner({number: 1, errorAs: 'throw'})
      .then(function () {
        done(new Error('should not get here'));
      })
      .catch(function (err) {
        err.message.should.eql('THIS IS JUST A TEST THAT THROWS AN ERROR');
        done();
      });
  });

  it('supports returning a promise from a method on the exchange that callbacks an error', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturner({number: 1, errorAs: 'callback'})
      .then(function () {
        done(new Error('should not get here'));
      })
      .catch(function (err) {
        err.message.should.eql('THIS IS JUST A TEST WITH CALLBACK ERROR');
        done();
      });
  });

  it('does not time out a sync function', function (done) {

    this.timeout(2500);

    this.mesh.exchange.component.fireAndForget({number: 1})
      .then(function (res) {
        // should never get here
        done(new Error('Should not get a result'));
      })
      .catch(function (err) {
        done(err);
      });

    setTimeout(done, 2000);

  });

  it('does not fire a callback twice', function (done) {

    this.timeout(2000);

    this.mesh.exchange.component.callCallbackTwice({number: 1}, function (err, result) {
      result.number.should.eql(2);
      setTimeout(done, 500);
    });
  });

  require('benchmarket').stop();

});

<commit_msg>1.18.0 - Restore original test<commit_after>/* RUN: LOG_LEVEL=off mocha test/18-exchange-promises.js */

var Promise = require('bluebird');

module.exports = SeeAbove;

function SeeAbove() {
}

SeeAbove.prototype.methodName1 = function (opts, callback) {

  if (opts.errorAs == 'callback') return callback(new Error('THIS IS JUST A TEST'));
  if (opts.errorAs == 'throw') throw new Error('THIS IS JUST A TEST');

  opts.number++;
  callback(null, opts);
};

SeeAbove.prototype.callCallbackTwice = function (opts, callback) {
  opts.number++;
  callback(null, opts);

  setTimeout(function () {
    callback(null, {number: opts.number + 1});
  }, 100);
};

SeeAbove.prototype.fireAndForget = function (opts) {
  //do nothing
};

SeeAbove.prototype.promiseMethod = Promise.promisify(function (opts, callback) {

  if (opts.errorAs == 'callback') return callback(new Error('THIS IS JUST A TEST WITH CALLBACK ERROR'));
  if (opts.errorAs == 'throw') throw new Error('THIS IS JUST A TEST THAT THROWS AN ERROR');

  opts.number++;
  callback(null, opts);

});

SeeAbove.prototype.promisePromiseCaller = Promise.promisify(function (opts, callback) {

  this.promiseMethod(opts)
    .then(function () {
      callback(null, opts);
    })
    .catch(callback)

});

SeeAbove.prototype.promiseCaller = function (opts, callback) {

  this.promiseMethod(opts)
    .then(function () {
      callback(null, opts);
    })
    .catch(callback)

};

SeeAbove.prototype.promiseReturnerNoCallback = function (opts) {
  return this.promiseMethod(opts);
};

SeeAbove.prototype.promiseReturner = Promise.promisify(function (opts,callback) {
  return this.promiseMethod(opts, callback);
});

SeeAbove.prototype.synchronousMethodHappnOrigin = function (opts, opts2, $happn, $origin) {

  if (!$happn) throw new Error('$happn is meant to exist');
  if (!$origin) throw new Error('$origin is meant to exist');

  return opts + opts2;
};

SeeAbove.prototype.synchronousMethod = function (opts, opts2) {
  return opts + opts2;
};

SeeAbove.prototype.$happner = {
  config: {
    'component': {
      schema: {
        methods: {
          'methodName1': {
            alias: 'ancientmoth'
          },
          'synchronousMethod': {
            type: 'sync-promise'//NB - this is how you can wrap a synchronous method with a promise
          },
          'synchronousMethodHappnOrigin': {
            type: 'sync-promise'//NB - this is how you can wrap a synchronous method with a promise
          },
          'fireAndForget': {
            type: 'sync'
          }
        }
      }
    }
  }
};

if (global.TESTING_18) return; // When 'requiring' the module above,
// don't run the tests below
//.............
var should = require('chai').should();

describe('a8 - exchange supports promises', function () {

  require('benchmarket').start();
  after(require('benchmarket').store());

  var Mesh = require('../');
  var mesh;

  this.timeout(120000);

  before(function (done) {

    global.TESTING_18 = true; //.............

    mesh = this.mesh = new Mesh();

    mesh.initialize({
      dataLayer: {
        setOptions: {
          timeout: 1000
        }
      },
      util: {
        //logLevel: 'trace'
      },
      modules: {
        'component': {
          path: __filename   // .............
        }
      },
      components: {
        'component': {}
      }
    }, function (err) {
      delete global.TESTING_18; //.............
      if (err) return done(err);
      done();
    });
  });

  after(function (done) {
    mesh.stop({reconnect: false}, done);
  });

  it('supports non-promises in the exchange', function (done) {

    this.mesh.exchange.component.methodName1({number: 1}, function (err, res) {

      res.should.eql({number: 2});
      done();

    });

  });

  it('supports promises in the exchange', function (done) {

    this.mesh.exchange.component.methodName1({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('the promise implementation supports .catch from callback error', function (done) {

    this.mesh.exchange.component.methodName1({errorAs: 'callback'})

      .then(function (res) {
        done(new Error('did not catch'));
      })

      .catch(function (err) {
        err.should.match(/THIS IS JUST A TEST/);
        done();
      })

  });

  it('the promise implementation supports .catch from thrown error', function (done) {

    this.mesh.exchange.component.methodName1({errorAs: 'throw'})

      .then(function (res) {
        console.log(res);
        done(new Error('did not catch'));
      })

      .catch(function (err) {
        err.should.match(/THIS IS JUST A TEST/);
        done();
      })

  });

  it('supports non-promises on the alias', function (done) {

    this.mesh.exchange.component.ancientmoth({number: 1}, function (err, res) {

      res.should.eql({number: 2});
      done();

    });

  })

  it('supports promises on the alias', function (done) {

    this.mesh.exchange.component.ancientmoth({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      });

  });

  it('supports fire and forget', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.methodName1({errorAs: 'throw'});
    done();
  });

  it('supports calling a synchronous method and getting a promise back', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.synchronousMethod(1, 2)

      .then(function (res) {
        res.should.eql(3);
        done();
      })

      .catch(function (err) {
        done(err);
      })
    ;

  });

  it('supports calling a synchronous method with $happn and $origin and getting a promise back', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.synchronousMethodHappnOrigin(1, 2)

      .then(function (res) {
        res.should.eql(3);
        done();
      })

      .catch(function (err) {
        done(err);
      })
    ;

  });

  it('supports calling a synchronous method fire and forget', function (done) {

    this.timeout(1500);
    this.mesh.exchange.component.synchronousMethod(1, 2);
    done();

  });

  it('supports exposing a promise on the exchange', function (done) {

    this.mesh.exchange.component.promiseMethod({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports calling a promise from a promise on the exchange', function (done) {

    this.timeout(1500);
    var _this = this;

    this.mesh.exchange.component.promisePromiseCaller({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      }.bind(_this))

  });

  it('supports calling a promise from a method on the exchange', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseCaller({number: 1})

      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports returning a promise from a method on the exchange', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturner({number: 1})
      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports returning a promise from a method on the exchange with no callback', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturnerNoCallback({number: 1})
      .then(function (res) {
        res.should.eql({number: 2});
        done();
      })

  });

  it('supports returning a promise from a method on the exchange that throws an error', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturnerNoCallback({number: 1, errorAs: 'throw'})
      .then(function () {
        done(new Error('should not get here'));
      })
      .catch(function (err) {
        err.message.should.eql('THIS IS JUST A TEST THAT THROWS AN ERROR');
        done();
      });
  });

  it('supports returning a promise from a method on the exchange that callbacks an error', function (done) {

    this.timeout(1500);

    this.mesh.exchange.component.promiseReturnerNoCallback({number: 1, errorAs: 'callback'})
      .then(function () {
        done(new Error('should not get here'));
      })
      .catch(function (err) {
        err.message.should.eql('THIS IS JUST A TEST WITH CALLBACK ERROR');
        done();
      });
  });

  it('does not time out a sync function', function (done) {

    this.timeout(2500);

    this.mesh.exchange.component.fireAndForget({number: 1})
      .then(function (res) {
        // should never get here
        done(new Error('Should not get a result'));
      })
      .catch(function (err) {
        done(err);
      });

    setTimeout(done, 2000);

  });

  it('does not fire a callback twice', function (done) {

    this.timeout(2000);

    this.mesh.exchange.component.callCallbackTwice({number: 1}, function (err, result) {
      result.number.should.eql(2);
      setTimeout(done, 500);
    });
  });

  require('benchmarket').stop();

});

<|endoftext|>


<commit_before>/**
 * Created by groupsky on 20.11.15.
 */

var _ = require('lodash');
var should = require('should');
var setup = require('../_setup');
var Promise = require('bluebird');

describe.only('Nomenclatures:', function () {

  before(function () {
    return setup.init();
  });

  after(function () {
    return setup.finish();
  });

  var testNomenclatureTypes = ['birds_name', 'birds_nest_success'];
  var testNomenclatureSlugs = ['acrocephalus-agricola', 'fledglings'];

  describe('given some types', function () {

    // Guest
    setup.describeAsGuest(function (runAction) {

      it('cannot list nomenclatures', function () {
        return runAction('nomenclature:typeList', {}).then(function (response) {
          response.should.have.property('error').and.not.empty();
        });
      });

      testNomenclatureTypes.forEach(function(type) {
        it('cannot view nomenclatures of type ' + type, function () {
          return runAction('nomenclature:typeList', {"type": type}).then(function (response) {
            response.should.have.property('error').and.not.empty();
          });
        });
      });

    }); // end Guest

    // Logged User or Admin
    setup.describeAsAuth(function (runAction) {

      testNomenclatureTypes.forEach(function(type) {
        it('can list nomenclatures of type ' + type, function () {
          return runAction('nomenclature:typeList', {"type": type}).then(function (response) {

            response.should.not.have.property('error');
            response.should.have.property('data').not.empty().instanceOf(Array);
            response.should.have.property('count').and.be.greaterThan(0);

            for (var i=0; i<response.data.length; i++) {
              //response.data[i].should.have.property('ownerId').and.be.equal(1);
              //response.data[i].should.have.property('location').not.empty();
            }

          });
        });
      });

    }); // end Logged User or Admin

  }); // given some types

  describe('given some types and slugs', function () {

    // Guest
    setup.describeAsGuest(function (runAction) {

      it('cannot list nomenclatures', function () {
        return runAction('nomenclature:view', {}).then(function (response) {
          response.should.have.property('error').and.not.empty();
        });
      });

      testNomenclatureTypes.forEach(function(type) {
        testNomenclatureSlugs.forEach(function(slug) {
          it('cannot view nomenclatures of type ' + type + ' and slug ' + slug, function () {
            return runAction('nomenclature:view', {"type": type}).then(function (response) {
              response.should.have.property('error').and.not.empty();
            });
          });
        });
      });

    }); // end Guest

    // Logged User or Admin
    setup.describeAsAuth(function (runAction) {

      var type = testNomenclatureTypes[0];
      var slug = testNomenclatureSlugs[0];

      it('can list nomenclatures of type ' + type + ' and slug ' + slug, function () {
        return runAction('nomenclature:view', {"type": type, "slug": slug}).then(function (response) {

          response.should.not.have.property('error');
          response.should.have.property('data').instanceOf(Object);
          response.data.should.have.property('slug').eq(slug);
        });
      });

    }); // end Logged User or Admin

  }); // given some types

});
<commit_msg>fix tests<commit_after>/**
 * Created by groupsky on 20.11.15.
 */

var _ = require('lodash');
var should = require('should');
var setup = require('../_setup');
var Promise = require('bluebird');

describe('Nomenclatures:', function () {

  before(function () {
    return setup.init();
  });

  after(function () {
    return setup.finish();
  });

  var testNomenclatureTypes = ['birds_name', 'birds_nest_success'];
  var testNomenclatureSlugs = ['acrocephalus-agricola', 'fledglings'];

  describe('given some types', function () {

    // Guest
    setup.describeAsGuest(function (runAction) {

      it('cannot list nomenclatures', function () {
        return runAction('nomenclature:typeList', {}).then(function (response) {
          response.should.have.property('error').and.not.empty();
        });
      });

      testNomenclatureTypes.forEach(function(type) {
        it('cannot view nomenclatures of type ' + type, function () {
          return runAction('nomenclature:typeList', {"type": type}).then(function (response) {
            response.should.have.property('error').and.not.empty();
          });
        });
      });

    }); // end Guest

    // Logged User or Admin
    setup.describeAsAuth(function (runAction) {

      testNomenclatureTypes.forEach(function(type) {
        it('can list nomenclatures of type ' + type, function () {
          return runAction('nomenclature:typeList', {"type": type}).then(function (response) {

            response.should.not.have.property('error');
            response.should.have.property('data').not.empty().instanceOf(Array);
            response.should.have.property('count').and.be.greaterThan(0);

            for (var i=0; i<response.data.length; i++) {
              //response.data[i].should.have.property('ownerId').and.be.equal(1);
              //response.data[i].should.have.property('location').not.empty();
            }

          });
        });
      });

    }); // end Logged User or Admin

  }); // given some types

  describe('given some types and slugs', function () {

    // Guest
    setup.describeAsGuest(function (runAction) {

      it('cannot list nomenclatures', function () {
        return runAction('nomenclature:view', {}).then(function (response) {
          response.should.have.property('error').and.not.empty();
        });
      });

      testNomenclatureTypes.forEach(function(type) {
        testNomenclatureSlugs.forEach(function(slug) {
          it('cannot view nomenclatures of type ' + type + ' and slug ' + slug, function () {
            return runAction('nomenclature:view', {"type": type}).then(function (response) {
              response.should.have.property('error').and.not.empty();
            });
          });
        });
      });

    }); // end Guest

    // Logged User or Admin
    setup.describeAsAuth(function (runAction) {

      var type = testNomenclatureTypes[0];
      var slug = testNomenclatureSlugs[0];

      it('can list nomenclatures of type ' + type + ' and slug ' + slug, function () {
        return runAction('nomenclature:view', {"type": type, "slug": slug}).then(function (response) {

          response.should.not.have.property('error');
          response.should.have.property('data').instanceOf(Object);
          response.data.should.have.property('slug').equal(slug);
        });
      });

    }); // end Logged User or Admin

  }); // given some types

});
<|endoftext|>


<commit_before>//The following code is from https://github.com/bgrins/devtools-snippets
(function(console){
    console.save = function(data, filename){

        if(!data) {
            console.error('Console.save: No data')
            return;
        }

        if(!filename) filename = 'console.json'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)
window.onload = function() {
  // Check for browser support
  if(!(window.performance && window.performance.timing)) {
    return;
  }
 console.log(console.save(performance.timing));
};
setTimeout(function(){window.location=window.location;},5000);
<commit_msg>Delete AutoTestingMRK1.js<commit_after><|endoftext|>


<commit_before>if (document.querySelector('audio') != null) {
	var music = document.getElementById('music'); // id for audio element
	var duration; // Duration of audio clip
	var pButton = document.getElementById('pButton'); // play button

	var playhead = document.getElementById('playhead'); // playhead

	var timeline = document.getElementById('timeline'); // timeline
	// timeline width adjusted for playhead
	var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;

	var timeholder = document.querySelector('.episode--player_time');

	// timeupdate event listener
	music.addEventListener("timeupdate", timeUpdate, false);

	//Makes timeline clickable
	timeline.addEventListener("click", function (event) {
		moveplayhead(event);
		music.currentTime = duration * clickPercent(event);
	}, false);

	// returns click as decimal (.77) of the total timelineWidth
	function clickPercent(e) {
		return (e.pageX - timeline.offsetLeft) / timelineWidth;
	}

	// Makes playhead draggable
	playhead.addEventListener('mousedown', mouseDown, false);
	window.addEventListener('mouseup', mouseUp, false);

	// Boolean value so that mouse is moved on mouseUp only when the playhead is released
	var onplayhead = false;
	// mouseDown EventListener
	function mouseDown() {
		onplayhead = true;
		window.addEventListener('mousemove', moveplayhead, true);
		music.removeEventListener('timeupdate', timeUpdate, false);
	}
	// mouseUp EventListener
	// getting input from all mouse clicks
	function mouseUp(e) {
		if (onplayhead == true) {
			moveplayhead(e);
			window.removeEventListener('mousemove', moveplayhead, true);
			// change current time
			music.currentTime = duration * clickPercent(e);
			music.addEventListener('timeupdate', timeUpdate, false);
		}
		onplayhead = false;
	}
	// mousemove EventListener
	// Moves playhead as user drags
	function moveplayhead(e) {
		var newMargLeft = e.pageX - timeline.offsetLeft;
		if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
			playhead.style.marginLeft = newMargLeft + "px";
		}
		if (newMargLeft < 0) {
			playhead.style.marginLeft = "0px";
		}
		if (newMargLeft > timelineWidth) {
			playhead.style.marginLeft = timelineWidth + "px";
		}
	}

	// timeUpdate
	// Synchronizes playhead position with current point in audio
	function timeUpdate() {
		var playPercent = timelineWidth * (music.currentTime / duration);
		playhead.style.marginLeft = playPercent + "px";
		if (music.currentTime == duration) {
			pButton.className = "";
			pButton.className = "episode--player_play episode--player_icon";
		}
		var timeString = (duration / 60) + '',
			dcml = Number('.' + timeString.split('.')[1]) * 60;
		timeholder.innerHTML = Math.floor(music.currentTime / 60) + ':' + Math.floor(music.currentTime) % 60 + ' | ' + Math.floor(duration / 60) + ':' + Math.floor(dcml);
	}

	//Play and Pause
	function play() {
		// start music
		if (music.paused) {
			music.play();
			// remove play, add pause
			pButton.className = "";
			pButton.className = "episode--player_pause episode--player_icon";
		} else { // pause music
			music.pause();
			// remove pause, add play
			pButton.className = "";
			pButton.className = "episode--player_play episode--player_icon";
		}
	}

	// Gets audio file duration
	music.addEventListener("canplaythrough", function () {
		duration = music.duration;
	}, false);
}
<commit_msg>adjusting timer so that 0 is in front of secondsif (document.querySelector('audio') != null) { 	var music = document.getElementById('music'); // id for audio element 	var duration; // Duration of audio clip 	var pButton = document.getElementById('pButton'); // play button  	var playhead = document.getElementById('playhead'); // playhead  	var timeline = document.getElementById('timeline'); // timeline 	// timeline width adjusted for playhead 	var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;  	var timeholder = document.querySelector('.episode--player_time');  	// timeupdate event listener 	music.addEventListener("timeupdate", timeUpdate, false);  	//Makes timeline clickable 	timeline.addEventListener("click", function (event) { 		moveplayhead(event); 		music.currentTime = duration * clickPercent(event); 	}, false);  	// returns click as decimal (.77) of the total timelineWidth 	function clickPercent(e) { 		return (e.pageX - timeline.offsetLeft) / timelineWidth; 	}  	// Makes playhead draggable 	playhead.addEventListener('mousedown', mouseDown, false); 	window.addEventListener('mouseup', mouseUp, false);  	// Boolean value so that mouse is moved on mouseUp only when the playhead is released 	var onplayhead = false; 	// mouseDown EventListener 	function mouseDown() { 		onplayhead = true; 		window.addEventListener('mousemove', moveplayhead, true); 		music.removeEventListener('timeupdate', timeUpdate, false); 	} 	// mouseUp EventListener 	// getting input from all mouse clicks 	function mouseUp(e) { 		if (onplayhead == true) { 			moveplayhead(e); 			window.removeEventListener('mousemove', moveplayhead, true); 			// change current time 			music.currentTime = duration * clickPercent(e); 			music.addEventListener('timeupdate', timeUpdate, false); 		} 		onplayhead = false; 	} 	// mousemove EventListener 	// Moves playhead as user drags 	function moveplayhead(e) { 		var newMargLeft = e.pageX - timeline.offsetLeft; 		if (newMargLeft >= 0 && newMargLeft <= timelineWidth) { 			playhead.style.marginLeft = newMargLeft + "px"; 		} 		if (newMargLeft < 0) { 			playhead.style.marginLeft = "0px"; 		} 		if (newMargLeft > timelineWidth) { 			playhead.style.marginLeft = timelineWidth + "px"; 		} 	}  	// timeUpdate 	// Synchronizes playhead position with current point in audio 	function timeUpdate() { 		var playPercent = timelineWidth * (music.currentTime / duration); 		playhead.style.marginLeft = playPercent + "px"; 		if (music.currentTime == duration) { 			pButton.className = ""; 			pButton.className = "episode--player_play episode--player_icon"; 		} 		var timeString = (duration / 60) + '', 			dcml = Number('.' + timeString.split('.')[1]) * 60; 		timeholder.innerHTML = Math.floor(music.currentTime / 60) + ':' + ('0' + (Math.floor(music.currentTime) % 60)).slice(-2) + ' | ' + Math.floor(duration / 60) + ':' +  ('0' + Math.floor(dcml)).slice(-2); 	}  	//Play and Pause 	function play() { 		// start music 		if (music.paused) { 			music.play(); 			// remove play, add pause 			pButton.className = ""; 			pButton.className = "episode--player_pause episode--player_icon"; 		} else { // pause music 			music.pause(); 			// remove pause, add play 			pButton.className = ""; 			pButton.className = "episode--player_play episode--player_icon"; 		} 	}  	// Gets audio file duration 	music.addEventListener("canplaythrough", function () { 		duration = music.duration; 	}, false);<commit_after>if (document.querySelector('audio') != null) {
	var music = document.getElementById('music'); // id for audio element
	var duration; // Duration of audio clip
	var pButton = document.getElementById('pButton'); // play button

	var playhead = document.getElementById('playhead'); // playhead

	var timeline = document.getElementById('timeline'); // timeline
	// timeline width adjusted for playhead
	var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;

	var timeholder = document.querySelector('.episode--player_time');

	// timeupdate event listener
	music.addEventListener("timeupdate", timeUpdate, false);

	//Makes timeline clickable
	timeline.addEventListener("click", function (event) {
		moveplayhead(event);
		music.currentTime = duration * clickPercent(event);
	}, false);

	// returns click as decimal (.77) of the total timelineWidth
	function clickPercent(e) {
		return (e.pageX - timeline.offsetLeft) / timelineWidth;
	}

	// Makes playhead draggable
	playhead.addEventListener('mousedown', mouseDown, false);
	window.addEventListener('mouseup', mouseUp, false);

	// Boolean value so that mouse is moved on mouseUp only when the playhead is released
	var onplayhead = false;
	// mouseDown EventListener
	function mouseDown() {
		onplayhead = true;
		window.addEventListener('mousemove', moveplayhead, true);
		music.removeEventListener('timeupdate', timeUpdate, false);
	}
	// mouseUp EventListener
	// getting input from all mouse clicks
	function mouseUp(e) {
		if (onplayhead == true) {
			moveplayhead(e);
			window.removeEventListener('mousemove', moveplayhead, true);
			// change current time
			music.currentTime = duration * clickPercent(e);
			music.addEventListener('timeupdate', timeUpdate, false);
		}
		onplayhead = false;
	}
	// mousemove EventListener
	// Moves playhead as user drags
	function moveplayhead(e) {
		var newMargLeft = e.pageX - timeline.offsetLeft;
		if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
			playhead.style.marginLeft = newMargLeft + "px";
		}
		if (newMargLeft < 0) {
			playhead.style.marginLeft = "0px";
		}
		if (newMargLeft > timelineWidth) {
			playhead.style.marginLeft = timelineWidth + "px";
		}
	}

	// timeUpdate
	// Synchronizes playhead position with current point in audio
	function timeUpdate() {
		var playPercent = timelineWidth * (music.currentTime / duration);
		playhead.style.marginLeft = playPercent + "px";
		if (music.currentTime == duration) {
			pButton.className = "";
			pButton.className = "episode--player_play episode--player_icon";
		}
		var timeString = (duration / 60) + '',
			dcml = Number('.' + timeString.split('.')[1]) * 60;
		timeholder.innerHTML = Math.floor(music.currentTime / 60) + ':' + ('0' + (Math.floor(music.currentTime) % 60)).slice(-2) + ' | ' + Math.floor(duration / 60) + ':' +  ('0' + Math.floor(dcml)).slice(-2);
	}

	//Play and Pause
	function play() {
		// start music
		if (music.paused) {
			music.play();
			// remove play, add pause
			pButton.className = "";
			pButton.className = "episode--player_pause episode--player_icon";
		} else { // pause music
			music.pause();
			// remove pause, add play
			pButton.className = "";
			pButton.className = "episode--player_play episode--player_icon";
		}
	}

	// Gets audio file duration
	music.addEventListener("canplaythrough", function () {
		duration = music.duration;
	}, false);
}
<|endoftext|>


<commit_before>/* globals describe, it, before */
"use strict";

var chai = require("chai"),
    assert = chai.assert,
    sinon  = require("sinon");

var utils = require("radiodan-client").utils;

describe("setup", function(){
  before(function() {
    this.Avoider = require("../../app/avoider/avoider")();
  });

  it("sets avoid type", function(){
    var subject = this.Avoider.create("testService", "avoidTest");

    assert.equal(subject.avoidTopic, "avoidTest");
  });
});

describe("on avoid", function(){
  beforeEach(function() {
    this.services    = { change: sinon.spy(), current: sinon.spy(), get: sinon.spy() };
    this.bbcServices = { once: sinon.spy() };
    function createResolvedStub() {
      return sinon.stub().returns(utils.promise.resolve());
    }
    function createMockPlayer() {
      return {
        play  : createResolvedStub(),
        stop  : createResolvedStub(),
        add   : createResolvedStub()
      };
    }
    this.players = {
      main: createMockPlayer(),
      avoider: createMockPlayer()
    };

    this.Avoider = require("../../app/avoider/avoider")(
      {},
      this.bbcServices
    );
  });

  it("starts avoiding", function(){
    var subject = this.Avoider.create("avoidStation", "testTopic"),
        emitSpy = sinon.spy(),
        avoidCallBack;

    subject.startAvoiding({}, this.players, this.services, emitSpy);

    assert.ok(emitSpy.called);
    assert.ok(emitSpy.calledWith('avoider.start'))
  });
});
<commit_msg>Fix test (for all the good it will do)<commit_after>/* globals describe, it, before */
"use strict";

var chai = require("chai"),
    assert = chai.assert,
    sinon  = require("sinon");

var utils = require("radiodan-client").utils;

describe("setup", function(){
  before(function() {
    this.Avoider = require("../../app/avoider/avoider")();
  });

  it("sets avoid type", function(){
    var subject = this.Avoider.create("testService", "avoidTest");

    assert.equal(subject.avoidTopic, "avoidTest");
  });
});

describe("on avoid", function(){
  beforeEach(function() {
    this.services    = {
      change: sinon.spy(),
      current: sinon.stub().returns("radio1"),
      get: sinon.spy()
    };
    this.bbcServices = { once: sinon.spy() };
    function createResolvedStub() {
      return sinon.stub().returns(utils.promise.resolve());
    }
    function createMockPlayer() {
      return {
        play  : createResolvedStub(),
        stop  : createResolvedStub(),
        add   : createResolvedStub()
      };
    }
    this.players = {
      main: createMockPlayer(),
      avoider: createMockPlayer()
    };

    this.Avoider = require("../../app/avoider/avoider")(
      {},
      this.bbcServices
    );
  });

  it("starts avoiding", function(){
    var subject = this.Avoider.create("avoidStation", "testTopic"),
        emitSpy = sinon.spy(),
        avoidCallBack;

    subject.startAvoiding({}, this.players, this.services, emitSpy);

    assert.ok(emitSpy.called);
    assert.ok(emitSpy.calledWith('avoider.start'))
  });
});
<|endoftext|>


<commit_before>/**!
 * cnpmjs.org - test/common/markdown.test.js
 *
 * Copyright(c) fengmk2 and other contributors.
 * MIT Licensed
 *
 * Authors:
 *   fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
 */

'use strict';

/**
 * Module dependencies.
 */

var path = require('path');
var fs = require('fs');
var markdown = require('../../common/markdown');

describe('common/markdown.test.js', function () {
  var fixtures = path.join(__dirname, '..', 'fixtures');

  it('should render sonido readme', function () {
    var readme = fs.readFileSync(path.join(fixtures, 'sonido.md'), 'utf8');
    var md = markdown.render(readme);
    md.should.equal('
Configuration Wizard: <!--- This is what the user will see during the configuration ->
\n');
  });

  it('should filter xss', function () {
    var html = markdown.render('foo/xss\n[foo](/foo) bar\n"\'');
    // console.log(html);
    html.should.equal('
foo/xss\nfoo bar\n"'
\n');
    markdown.render('[xss link](javascript:alert(2))').should.equal('
[xss link](javascript:alert(2))
\n');
  });
});
<commit_msg>fix xss tests<commit_after>/**!
 * cnpmjs.org - test/common/markdown.test.js
 *
 * Copyright(c) fengmk2 and other contributors.
 * MIT Licensed
 *
 * Authors:
 *   fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
 */

'use strict';

/**
 * Module dependencies.
 */

var path = require('path');
var fs = require('fs');
var markdown = require('../../common/markdown');

describe('common/markdown.test.js', function () {
  var fixtures = path.join(__dirname, '..', 'fixtures');

  it('should render sonido readme', function () {
    var readme = fs.readFileSync(path.join(fixtures, 'sonido.md'), 'utf8');
    var md = markdown.render(readme);
    md.should.equal('
Configuration Wizard: <!--- This is what the user will see during the configuration ->
\n');
  });

  it('should filter xss', function () {
    var html = markdown.render('foo/xss\n[foo](/foo) bar\n"\'');
    // console.log(html);
    html.should.equal('
foo<script>alert(1)</script>/xss\nfoo bar\n"\'
\n');
    markdown.render('[xss link](javascript:alert(2))').should.equal('
[xss link](javascript:alert(2))
\n');
  });
});
<|endoftext|>


<commit_before>// configured-user-test.js
//
// Test the config.users array
//
// Copyright 2018, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

"use strict";

var fs = require("fs"),
    path = require("path"),
    assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("lodash"),
    httputil = require("./lib/http"),
    gj = httputil.getJSON,
    pj = httputil.postJSON,
    oauthutil = require("./lib/oauth"),
    apputil = require("./lib/app"),
    actutil = require("./lib/activity"),
    validActivity = actutil.validActivity,
    setupApp = apputil.setupApp,
    newPair = oauthutil.newPair;

var tc = JSON.parse(fs.readFileSync(path.resolve(__dirname, "config.json")));

var suite = vows.describe("configured user and tokens");

suite.addBatch({
    "When we set up the app with a configured client": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            app.close();
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we request the user profile with the configured credentials": {
            topic: function() {
                var callback = this.callback;
                var client = tc.clients[0];
                var user = tc.users[0];
                var token = user.tokens[0];
                var nickname = user.nickname;
                var cred = {
                    consumer_key: client.client_id,
                    consumer_secret: client.client_secret,
                    token: token.token,
                    token_secret: token.token_secret
                };
                gj("http://localhost:4815/api/user/" + nickname, cred, callback);
            },
            "it works": function(err, body, resp) {
                assert.ifError(err);
                assert.isObject(body);
            }
        },
        "and we post a new activity with the configured credentials": {
            topic: function() {
                var callback = this.callback;
                var client = tc.clients[0];
                var user = tc.users[0];
                var token = user.tokens[0];
                var nickname = user.nickname;
                var cred = {
                    consumer_key: client.client_id,
                    consumer_secret: client.client_secret,
                    token: token.token,
                    token_secret: token.token_secret
                };
                var url = "http://localhost:4815/api/user/"+nickname+"/feed";
                var act = {
                        verb: "post",
                        object: {
                            objectType: "note",
                            content: "Hello, world."
                        }
                    };

                pj(url, cred, act, callback);
            },
            "it works": function(err, body) {
                assert.ifError(err);
                validActivity(body);
            }
        }
    }
});

suite["export"](module);
<commit_msg>Better description on configured-users-test<commit_after>// configured-user-test.js
//
// Test the config.users array
//
// Copyright 2018, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

"use strict";

var fs = require("fs"),
    path = require("path"),
    assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("lodash"),
    httputil = require("./lib/http"),
    gj = httputil.getJSON,
    pj = httputil.postJSON,
    oauthutil = require("./lib/oauth"),
    apputil = require("./lib/app"),
    actutil = require("./lib/activity"),
    validActivity = actutil.validActivity,
    setupApp = apputil.setupApp,
    newPair = oauthutil.newPair;

var tc = JSON.parse(fs.readFileSync(path.resolve(__dirname, "config.json")));

var suite = vows.describe("configured user and tokens");

suite.addBatch({
    "When we set up the app with configured users": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            app.close();
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we request the user profile with the configured credentials": {
            topic: function() {
                var callback = this.callback;
                var client = tc.clients[0];
                var user = tc.users[0];
                var token = user.tokens[0];
                var nickname = user.nickname;
                var cred = {
                    consumer_key: client.client_id,
                    consumer_secret: client.client_secret,
                    token: token.token,
                    token_secret: token.token_secret
                };
                gj("http://localhost:4815/api/user/" + nickname, cred, callback);
            },
            "it works": function(err, body, resp) {
                assert.ifError(err);
                assert.isObject(body);
            }
        },
        "and we post a new activity with the configured credentials": {
            topic: function() {
                var callback = this.callback;
                var client = tc.clients[0];
                var user = tc.users[0];
                var token = user.tokens[0];
                var nickname = user.nickname;
                var cred = {
                    consumer_key: client.client_id,
                    consumer_secret: client.client_secret,
                    token: token.token,
                    token_secret: token.token_secret
                };
                var url = "http://localhost:4815/api/user/"+nickname+"/feed";
                var act = {
                        verb: "post",
                        object: {
                            objectType: "note",
                            content: "Hello, world."
                        }
                    };

                pj(url, cred, act, callback);
            },
            "it works": function(err, body) {
                assert.ifError(err);
                validActivity(body);
            }
        }
    }
});

suite["export"](module);
<|endoftext|>