<commit_before>/* jslint node: true */
'use strict';

var Config					= require('./config.js').config;
var Log						= require('./logger.js').log;
var getMessageAreaByName	= require('./message_area.js').getMessageAreaByName;
var clientConnections		= require('./client_connections.js');
var sysProp					= require('./system_property.js');

var packageJson 			= require('../package.json');
var assert					= require('assert');
var os						= require('os');
var _						= require('lodash');
var moment					= require('moment');

exports.getPredefinedMCIValue	= getPredefinedMCIValue;

function getPredefinedMCIValue(client, code) {

	if(!client || !code) {
		return;
	}

	try {
		return {
			//
			//	Board
			//
			BN	: function boardName() { return Config.general.boardName; },

			//	ENiGMA
			VL	: function versionLabel() { return 'ENiGMA½ v' + packageJson.version; },
			VN	: function version() { return packageJson.version; },

			//	:TODO: SysOp username
			//	:TODO: SysOp real name

			//
			//	Current user / session
			//
			UN	: function userName() { return client.user.username; },
			UI	: function userId() { return client.user.userId.toString(); },
			UG	: function groups() { return _.values(client.user.groups).join(', '); },
			UR	: function realName() { return client.user.properties.real_name; },
			LO	: function location() { return client.user.properties.location; },
			UA	: function age() { return client.user.getAge().toString(); },
			UB	: function birthdate() { return moment(client.user.properties.birthdate).format(client.currentTheme.helpers.getDateFormat()); },
			US	: function sex() { return client.user.properties.sex; },
			UE	: function emailAddres() { return client.user.properties.email_address; },
			UW	: function webAddress() { return client.user.properties.web_address; },
			UF	: function affils() { return client.user.properties.affiliation; },
			UT	: function themeId() { return client.user.properties.theme_id; },
			UC	: function loginCount() { return client.user.properties.login_count.toString(); },
			ND	: function connectedNode() { return client.node.toString(); },
			IP	: function clientIpAddress() { return client.address().address; },
			ST	: function serverName() { return client.session.serverName; },

			MS	: function accountCreated() { return moment(client.user.properties.account_created).format(client.currentTheme.helpers.getDateFormat()); },
			CS	: function currentStatus() { return client.currentStatus; },

			MD	: function currentMenuDescription() {
				return _.has(client, 'currentMenuModule.menuConfig.desc') ? client.currentMenuModule.menuConfig.desc : '';
			},

			MA	: function messageAreaDescription() {
				var area = getMessageAreaByName(client.user.properties.message_area_name);
				return area ? area.desc : '';
			},

			SH	: function termHeight() { return client.term.termHeight.toString(); },
			SW	: function termWidth() { return client.term.termWidth.toString(); },

			//
			//	Date/Time
			//
			//	:TODO: change to CD for 'Current Date'
			DT	: function date() { return moment().format(client.currentTheme.helpers.getDateFormat()); },
			CT	: function time() { return moment().format(client.currentTheme.helpers.getTimeFormat()) ;},

			//
			//	OS/System Info
			//
			OS	: function operatingSystem() {
				return {
					linux	: 'Linux',
					darwin	: 'Mac OS X',
					win32	: 'Windows',
					sunos	: 'SunOS',
					freebsd	: 'FreeBSD',
				}[os.platform()] || os.type();
			},

			OA	: function systemArchitecture() { return os.arch(); },
			SC		: function systemCpuModel() {
				//
				//	Clean up CPU strings a bit for better display
				//
				return os.cpus()[0].model.replace(/\(R\)|\(TM\)|processor|CPU/g, '')
					.replace(/\s+(?= )/g, '');
			},

			//	:TODO: MCI for core count, e.g. os.cpus().length

			//	:TODO: cpu load average (over N seconds): http://stackoverflow.com/questions/9565912/convert-the-output-of-os-cpus-in-node-js-to-percentage
			//	:TODO: Node version/info

			AN	: function activeNodes() { return clientConnections.getActiveConnections().length.toString(); },

			TC	: function totalCalls() { return sysProp.getSystemProperty('login_count').toString(); },

		}[code]();

	} catch(e) {
		//	Don't use client.log here as we may not have a client logger established yet!!
		Log.warn( { code : code, exception : e.message }, 'Exception caught attempting to construct predefined MCI value');
	}
}
<commit_msg>Notes<commit_after>/* jslint node: true */
'use strict';

var Config					= require('./config.js').config;
var Log						= require('./logger.js').log;
var getMessageAreaByName	= require('./message_area.js').getMessageAreaByName;
var clientConnections		= require('./client_connections.js');
var sysProp					= require('./system_property.js');

var packageJson 			= require('../package.json');
var assert					= require('assert');
var os						= require('os');
var _						= require('lodash');
var moment					= require('moment');

exports.getPredefinedMCIValue	= getPredefinedMCIValue;

function getPredefinedMCIValue(client, code) {

	if(!client || !code) {
		return;
	}

	try {
		return {
			//
			//	Board
			//
			BN	: function boardName() { return Config.general.boardName; },

			//	ENiGMA
			VL	: function versionLabel() { return 'ENiGMA½ v' + packageJson.version; },
			VN	: function version() { return packageJson.version; },

			//	:TODO: SysOp username
			//	:TODO: SysOp real name

			//
			//	Current user / session
			//
			UN	: function userName() { return client.user.username; },
			UI	: function userId() { return client.user.userId.toString(); },
			UG	: function groups() { return _.values(client.user.groups).join(', '); },
			UR	: function realName() { return client.user.properties.real_name; },
			LO	: function location() { return client.user.properties.location; },
			UA	: function age() { return client.user.getAge().toString(); },
			UB	: function birthdate() { return moment(client.user.properties.birthdate).format(client.currentTheme.helpers.getDateFormat()); },
			US	: function sex() { return client.user.properties.sex; },
			UE	: function emailAddres() { return client.user.properties.email_address; },
			UW	: function webAddress() { return client.user.properties.web_address; },
			UF	: function affils() { return client.user.properties.affiliation; },
			UT	: function themeId() { return client.user.properties.theme_id; },
			UC	: function loginCount() { return client.user.properties.login_count.toString(); },
			ND	: function connectedNode() { return client.node.toString(); },
			IP	: function clientIpAddress() { return client.address().address; },
			ST	: function serverName() { return client.session.serverName; },

			MS	: function accountCreated() { return moment(client.user.properties.account_created).format(client.currentTheme.helpers.getDateFormat()); },
			CS	: function currentStatus() { return client.currentStatus; },

			MD	: function currentMenuDescription() {
				return _.has(client, 'currentMenuModule.menuConfig.desc') ? client.currentMenuModule.menuConfig.desc : '';
			},

			MA	: function messageAreaDescription() {
				var area = getMessageAreaByName(client.user.properties.message_area_name);
				return area ? area.desc : '';
			},

			SH	: function termHeight() { return client.term.termHeight.toString(); },
			SW	: function termWidth() { return client.term.termWidth.toString(); },

			//
			//	Date/Time
			//
			//	:TODO: change to CD for 'Current Date'
			DT	: function date() { return moment().format(client.currentTheme.helpers.getDateFormat()); },
			CT	: function time() { return moment().format(client.currentTheme.helpers.getTimeFormat()) ;},

			//
			//	OS/System Info
			//
			OS	: function operatingSystem() {
				return {
					linux	: 'Linux',
					darwin	: 'Mac OS X',
					win32	: 'Windows',
					sunos	: 'SunOS',
					freebsd	: 'FreeBSD',
				}[os.platform()] || os.type();
			},

			OA	: function systemArchitecture() { return os.arch(); },
			SC		: function systemCpuModel() {
				//
				//	Clean up CPU strings a bit for better display
				//
				return os.cpus()[0].model.replace(/\(R\)|\(TM\)|processor|CPU/g, '')
					.replace(/\s+(?= )/g, '');
			},

			//	:TODO: MCI for core count, e.g. os.cpus().length

			//	:TODO: cpu load average (over N seconds): http://stackoverflow.com/questions/9565912/convert-the-output-of-os-cpus-in-node-js-to-percentage
			//	:TODO: Node version/info

			AN	: function activeNodes() { return clientConnections.getActiveConnections().length.toString(); },

			TC	: function totalCalls() { return sysProp.getSystemProperty('login_count').toString(); },

		}[code]();	//	:TODO: Just call toString() here and remove above - DRY

	} catch(e) {
		//	Don't use client.log here as we may not have a client logger established yet!!
		Log.warn( { code : code, exception : e.message }, 'Exception caught attempting to construct predefined MCI value');
	}
}
<|endoftext|>


<commit_before>'use strict'
var yo = require('yo-yo')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var remix = require('ethereum-remix')
var styleGuide = remix.ui.styleGuide
var styles = styleGuide()

var EventManager = remix.lib.EventManager
var helper = require('../../lib/helper')
var ethJSUtil = require('ethereumjs-util')
var BN = ethJSUtil.BN
var executionContext = require('../../execution-context')

var css = csjs`
  .log {
    display: flex;
    align-items: baseline;
  }
  .txTable, .tr, .td {
    border: 1px solid ${styles.colors.orange};
    background-color: ${styles.colors.veryLightGrey};
    border-collapse: collapse;
    font-size: 10px;
    color: ${styles.colors.grey};
  }
  #txTable {
    width: 450px;
    margin-top: 10px;
    align-self: center;
  }
  .tr, .td {
    padding: 4px;
  }
  .buttons {
    display: flex;
  }
  .debug, .details {
    ${styles.button}
    min-height: 18px;
    max-height: 18px;
    width: 45px;
    min-width: 45px;
    font-size: 10px;
    margin-left: 5px;
  }
  .debug {
    background-color: ${styles.colors.lightOrange};
  }
  .details {
    background-color: ${styles.colors.lightGrey};
  }
`
/**
  * This just export a function that register to `newTransaction` and forward them to the logger.
  * Emit debugRequested
  *
  */
class TxLogger {
  constructor (opts = {}) {
    this.event = new EventManager()
    this.opts = opts
    this.logKnownTX = opts.api.editorpanel.registerCommand('knownTransaction', (args, cmds, append) => {
      var data = args[0]
      var el = renderKnownTransaction(this, data)
      append(el)
    })
    this.logUnknownTX = opts.api.editorpanel.registerCommand('unknownTransaction', (args, cmds, append) => {
      var data = args[0]
      var el = renderUnknownTransaction(this, data)
      append(el)
    })
    this.logEmptyBlock = opts.api.editorpanel.registerCommand('emptyBlock', (args, cmds, append) => {
      var data = args[0]
      var el = renderEmptyBlock(this, data)
      append(el)
    })

    opts.events.txListener.register('newBlock', (block) => {
      if (!block.transactions.length) {
        this.logEmptyBlock({ block: block })
      }
    })

    opts.events.txListener.register('newTransaction', (tx) => {
      log(this, tx, opts.api)
    })
  }
}

function log (self, tx, api) {
  var resolvedTransaction = api.resolvedTransaction(tx.hash)
  if (resolvedTransaction) {
    api.parseLogs(tx, resolvedTransaction.contractName, api.compiledContracts(), (error, logs) => {
      if (!error) {
        self.logKnownTX({ tx: tx, resolvedData: resolvedTransaction, logs: logs })
      }
    })
  } else {
    // contract unknown - just displaying raw tx.
    self.logUnknownTX({ tx: tx })
  }
}

function renderKnownTransaction (self, data) {
  var from = helper.shortenAddress(data.tx.from)
  var to = ''

  if (data.tx.blockHash) {
    to = helper.shortenAddress(data.tx.to)
  } else if (data.tx.hash) {  // call (constructor of function call)
    var name = data.resolvedData.contractName + '.' + data.resolvedData.fn
    var logs = ',' + ' 0 logs'
    if (data.resolvedData.fn === '(constructor)') {
      to = name + logs
      from = from + ' ' + name + logs
    } else {
      var toHash = helper.shortenAddress(data.resolvedData.to)
      to = name + ' ' + toHash + logs
      from = from + ' ' + name + logs
    }
  }

  function debug () {
    self.event.trigger('debugRequested', [data.tx.hash])
  }
  var tx = yo`

        ${context(self, data.tx)}, ${data.resolvedData.contractName}.${data.resolvedData.fn}, ${data.logs.length} logs

          <button class=${css.details} onclick=${detail}>Details</button>
          <button class=${css.debug} onclick=${debug}>Debug</button>

  `
  function detail () {
    var table = yo`

          from
          ${from}

          to:
          ${to}

          value:
          ${value(data.tx.value)} wei

          data:
          ${helper.shortenHexData(data.tx.input)}

          hash:
          ${helper.shortenHexData((data.tx.hash))}

    `
    tx.appendChild(table)
  }
  return tx
}

function renderUnknownTransaction (self, data) {
  var from = helper.shortenAddress(data.tx.from)
  var to = data.tx.to
  if (to) to = helper.shortenAddress(data.tx.to)
  function debug () {
    self.event.trigger('debugRequested', [data.tx.hash])
  }
  var tx = yo`

        ${context(self, data.tx)}

          <button class=${css.details} onclick=${detail}>Details</button>
          <button class=${css.debug} onclick=${debug}>Debug</button>

  `
  function detail () {
    var table = yo`

          from
          ${from}

          to:
          ${to}

          value:
          ${value(data.tx.value)} wei

          data:
          ${helper.shortenHexData(data.tx.input)}

          hash:
          ${helper.shortenHexData((data.tx.hash))}

    `
    tx.appendChild(table)
  }
  return tx
}

function renderEmptyBlock (self, data) {
  return yo`<span>block ${data.block.number} - O transactions</span>`
}

function context (self, tx) {
  if (executionContext.getProvider() === 'vm') {
    return yo`<span>(vm)</span>`
  } else {
    return yo`<span>block:${tx.blockNumber}, txIndex:${tx.transactionIndex}</span>`
  }
}

function value (v) {
  try {
    if (v.indexOf && v.indexOf('0x') === 0) {
      return (new BN(v.replace('0x', ''), 16)).toString(10)
    } else {
      return v.toString(10)
    }
  } catch (e) {
    console.log(e)
    return v
  }
}

module.exports = TxLogger
<commit_msg>Fix show/hide<commit_after>'use strict'
var yo = require('yo-yo')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var remix = require('ethereum-remix')
var styleGuide = remix.ui.styleGuide
var styles = styleGuide()

var EventManager = remix.lib.EventManager
var helper = require('../../lib/helper')
var ethJSUtil = require('ethereumjs-util')
var BN = ethJSUtil.BN
var executionContext = require('../../execution-context')

var css = csjs`
  .log {
    display: flex;
    align-items: baseline;
  }
  .txTable, .tr, .td {
    border: 1px solid ${styles.colors.orange};
    border-collapse: collapse;
    font-size: 10px;
    color: ${styles.colors.grey};
  }
  #txTable {
    width: 450px;
    margin-top: 10px;
    align-self: center;
  }
  .tr, .td {
    padding: 4px;
  }
  .buttons {
    display: flex;
  }
  .debug, .details {
    ${styles.button}
    min-height: 18px;
    max-height: 18px;
    width: 45px;
    min-width: 45px;
    font-size: 10px;
    margin-left: 5px;
  }
  .debug {
    background-color: ${styles.colors.lightOrange};
  }
  .details {
    background-color: ${styles.colors.lightGrey};
  }
`
/**
  * This just export a function that register to `newTransaction` and forward them to the logger.
  * Emit debugRequested
  *
  */
class TxLogger {
  constructor (opts = {}) {
    this.event = new EventManager()
    this.opts = opts
    this.logKnownTX = opts.api.editorpanel.registerCommand('knownTransaction', (args, cmds, append) => {
      var data = args[0]
      var el = renderKnownTransaction(this, data)
      append(el)
    })
    this.logUnknownTX = opts.api.editorpanel.registerCommand('unknownTransaction', (args, cmds, append) => {
      var data = args[0]
      var el = renderUnknownTransaction(this, data)
      append(el)
    })
    this.logEmptyBlock = opts.api.editorpanel.registerCommand('emptyBlock', (args, cmds, append) => {
      var data = args[0]
      var el = renderEmptyBlock(this, data)
      append(el)
    })

    opts.events.txListener.register('newBlock', (block) => {
      if (!block.transactions.length) {
        this.logEmptyBlock({ block: block })
      }
    })

    opts.events.txListener.register('newTransaction', (tx) => {
      log(this, tx, opts.api)
    })
  }
}

function log (self, tx, api) {
  var resolvedTransaction = api.resolvedTransaction(tx.hash)
  if (resolvedTransaction) {
    api.parseLogs(tx, resolvedTransaction.contractName, api.compiledContracts(), (error, logs) => {
      if (!error) {
        self.logKnownTX({ tx: tx, resolvedData: resolvedTransaction, logs: logs })
      }
    })
  } else {
    // contract unknown - just displaying raw tx.
    self.logUnknownTX({ tx: tx })
  }
}

function renderKnownTransaction (self, data) {
  var from = helper.shortenAddress(data.tx.from)
  var to = ''

  if (data.tx.blockHash) {
    to = helper.shortenAddress(data.tx.to)
  } else if (data.tx.hash) {  // call (constructor of function call)
    var name = data.resolvedData.contractName + '.' + data.resolvedData.fn
    var logs = ',' + ' 0 logs'
    if (data.resolvedData.fn === '(constructor)') {
      to = name + logs
      from = from + ' ' + name + logs
    } else {
      var toHash = helper.shortenAddress(data.resolvedData.to)
      to = name + ' ' + toHash + logs
      from = from + ' ' + name + logs
    }
  }

  function debug () {
    self.event.trigger('debugRequested', [data.tx.hash])
  }
  var tx = yo`

        ${context(self, data.tx)}, ${data.resolvedData.contractName}.${data.resolvedData.fn}, ${data.logs.length} logs

        <button class=${css.details} onclick=${txDetails}>Details</button>
        <button class=${css.debug} onclick=${debug}>Debug</button>

  `

  var table
  function txDetails () {
    if (table && table.parentNode) {
      tx.removeChild(table)
    } else {
      table = createTable({
        from, to, val: data.tx.value, input: data.tx.input, hash: data.tx.hash
      })
      tx.appendChild(table)
    }
  }

  return tx
}

function renderUnknownTransaction (self, data) {
  var from = helper.shortenAddress(data.tx.from)
  var to = data.tx.to
  if (to) to = helper.shortenAddress(data.tx.to)
  function debug () {
    self.event.trigger('debugRequested', [data.tx.hash])
  }
  var tx = yo`

        ${context(self, data.tx)}

          <button class=${css.details} onclick=${txDetails}>Details</button>
          <button class=${css.debug} onclick=${debug}>Debug</button>

  `
  var table
  function txDetails () {
    if (table && table.parentNode) {
      tx.removeChild(table)
    } else {
      table = createTable({
        from, to, val: data.tx.value, input: data.tx.input, hash: data.tx.hash
      })
      tx.appendChild(table)
    }
  }
  return tx
}

function renderEmptyBlock (self, data) {
  return yo`<span>block ${data.block.number} - O transactions</span>`
}

function context (self, tx) {
  if (executionContext.getProvider() === 'vm') {
    return yo`<span>(vm)</span>`
  } else {
    return yo`<span>block:${tx.blockNumber}, txIndex:${tx.transactionIndex}</span>`
  }
}

function value (v) {
  try {
    if (v.indexOf && v.indexOf('0x') === 0) {
      return (new BN(v.replace('0x', ''), 16)).toString(10)
    } else {
      return v.toString(10)
    }
  } catch (e) {
    console.log(e)
    return v
  }
}

module.exports = TxLogger

// helpers

function createTable (opts) {
  var from = opts.from
  var to = opts.to
  var val = opts.val
  var input = opts.input
  var hash = opts.hash
  return yo`

      from
      ${from}

      to:
      ${to}

      value:
      ${value(val)} wei

      data:
      ${helper.shortenHexData(input)}

      hash:
      ${helper.shortenHexData((hash))}

  `
}
<|endoftext|>


<commit_before>/* global bard, sinon */
describe('Service: Series', function () {
	beforeEach(function () {
		bard.appModule('plugins.series');

		/* global $httpBackend, seriesService, exception, CacheFactory, $q */
		bard.inject('$httpBackend', 'seriesService', 'exception', 'CacheFactory', '$q');

		sinon.stub(exception, 'catcher').returns($q.reject({ message: 'Request failed' }));

		//Clear all caches before the tests to prevent cross test caching
		CacheFactory.clearAll();
	});

	it('should exist', function () {
		expect(seriesService).to.exist;
	});

	describe('getShows()', function () {
		it('should issue a GET /api/series/ request', function () {
			$httpBackend.expect('GET', '/api/series/').respond(200, {});
			seriesService.getShows().then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/').respond(500);
			seriesService.getShows().catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});

		//TODO: Figure out how to test the caching system

		/*	it("should only call the API only once because of caching", function () {
				$httpBackend.expect('GET', '/api/series/').respond(200, JSON.stringify({}));
				seriesService.getShows().then(function (data) {
					console.log(data);
					expect(data).to.exist;
				});
				$httpBackend.flush();

				//CacheFactory.clearAll();

				$httpBackend.resetExpectations();

				$httpBackend.expect('GET', '/api/series/').respond(200, JSON.stringify({}));

				seriesService.getShows().then(function (data) {
					console.log(data);
					expect(data).to.exist;
					//expect(true).to.be.false;
				});
				$httpBackend.flush();
			});*/
	});

	describe('getShowMetadata()', function () {
		it('should issue a GET /api/tvdb/series/:name/ request', function () {
			$httpBackend.expect('GET', '/api/tvdb/series/iZombie/').respond(200, {});
			seriesService.getShowMetadata({ 'show_name': 'iZombie' }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/tvdb/series/iZombie/').respond(500);
			seriesService.getShowMetadata({ 'show_name': 'iZombie' }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('deleteShow()', function () {
		it('should issue a DELETE /api/series/:id/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/').respond(200, {});
			seriesService.deleteShow({ 'show_id': 1 }).then(function (data) {
				expect(data).not.to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/').respond(500);
			seriesService.deleteShow({ 'show_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('searchShows()', function () {
		it('should issue a GET /api/series/search/:term/ request', function () {
			$httpBackend.expect('GET', '/api/series/search/iZombie/').respond(200, {});
			seriesService.searchShows('iZombie').then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/search/iZombie/').respond(500);
			seriesService.searchShows('iZombie').catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});

		//TODO: Test search result

	});

	describe('getEpisodes()', function () {
		it('should issue a GET /api/series/:id/episodes/ request', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/').respond(200, {});
			seriesService.getEpisodes({ 'show_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/').respond(500);
			seriesService.getEpisodes({ 'show_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('deleteEpisode()', function () {
		it('should issue a DELETE /api/series/:sid/episodes/:eid/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/').respond(200, {});
			seriesService.deleteEpisode({ 'show_id': 1 }, { 'episode_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/').respond(500);
			seriesService.deleteEpisode({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('resetReleases()', function () {
		it('should issue a PUT /api/series/:sid/episodes/:eid/releases/ request', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/').respond(200, {});
			seriesService.resetReleases({ 'show_id': 1 }, { 'episode_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/').respond(500);
			seriesService.resetReleases({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('forgetRelease()', function () {
		it('should issue a DELETE /api/series/:sid/episodes/:eid/releases/:rid/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/1/').respond(200, {});
			seriesService.forgetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { release_id: 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/1/').respond(500);
			seriesService.forgetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { release_id: 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('resetRelease()', function () {
		it('should issue a PUT /api/series/:sid/episodes/:eid/releases/:rid/ request', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/1/').respond(200, {});
			seriesService.resetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { release_id: 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/1/').respond(500);
			seriesService.resetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { release_id: 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('deleteReleases()', function () {
		it('should issue a DELETE /api/series/:sid/episodes/:eid/releases/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/').respond(200, {});
			seriesService.deleteReleases({ 'show_id': 1 }, { 'episode_id': 1 }).then(function () {
				expect(true).to.be.true;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/').respond(500);
			seriesService.deleteReleases({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('loadReleases()', function () {
		it('should issue a GET /api/series/:sid/episodes/:eid/releases/ request', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/1/releases/').respond(200, {});
			seriesService.loadReleases({ 'show_id': 1 }, { 'episode_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/1/releases/').respond(500);
			seriesService.loadReleases({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});
});
<commit_msg>Leftover camelcase code quality issues in UI<commit_after>/* global bard, sinon */
describe('Service: Series', function () {
	beforeEach(function () {
		bard.appModule('plugins.series');

		/* global $httpBackend, seriesService, exception, CacheFactory, $q */
		bard.inject('$httpBackend', 'seriesService', 'exception', 'CacheFactory', '$q');

		sinon.stub(exception, 'catcher').returns($q.reject({ message: 'Request failed' }));

		//Clear all caches before the tests to prevent cross test caching
		CacheFactory.clearAll();
	});

	it('should exist', function () {
		expect(seriesService).to.exist;
	});

	describe('getShows()', function () {
		it('should issue a GET /api/series/ request', function () {
			$httpBackend.expect('GET', '/api/series/').respond(200, {});
			seriesService.getShows().then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/').respond(500);
			seriesService.getShows().catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});

		//TODO: Figure out how to test the caching system

		/*	it("should only call the API only once because of caching", function () {
				$httpBackend.expect('GET', '/api/series/').respond(200, JSON.stringify({}));
				seriesService.getShows().then(function (data) {
					console.log(data);
					expect(data).to.exist;
				});
				$httpBackend.flush();

				//CacheFactory.clearAll();

				$httpBackend.resetExpectations();

				$httpBackend.expect('GET', '/api/series/').respond(200, JSON.stringify({}));

				seriesService.getShows().then(function (data) {
					console.log(data);
					expect(data).to.exist;
					//expect(true).to.be.false;
				});
				$httpBackend.flush();
			});*/
	});

	describe('getShowMetadata()', function () {
		it('should issue a GET /api/tvdb/series/:name/ request', function () {
			$httpBackend.expect('GET', '/api/tvdb/series/iZombie/').respond(200, {});
			seriesService.getShowMetadata({ 'show_name': 'iZombie' }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/tvdb/series/iZombie/').respond(500);
			seriesService.getShowMetadata({ 'show_name': 'iZombie' }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('deleteShow()', function () {
		it('should issue a DELETE /api/series/:id/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/').respond(200, {});
			seriesService.deleteShow({ 'show_id': 1 }).then(function (data) {
				expect(data).not.to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/').respond(500);
			seriesService.deleteShow({ 'show_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('searchShows()', function () {
		it('should issue a GET /api/series/search/:term/ request', function () {
			$httpBackend.expect('GET', '/api/series/search/iZombie/').respond(200, {});
			seriesService.searchShows('iZombie').then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/search/iZombie/').respond(500);
			seriesService.searchShows('iZombie').catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});

		//TODO: Test search result

	});

	describe('getEpisodes()', function () {
		it('should issue a GET /api/series/:id/episodes/ request', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/').respond(200, {});
			seriesService.getEpisodes({ 'show_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/').respond(500);
			seriesService.getEpisodes({ 'show_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('deleteEpisode()', function () {
		it('should issue a DELETE /api/series/:sid/episodes/:eid/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/').respond(200, {});
			seriesService.deleteEpisode({ 'show_id': 1 }, { 'episode_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/').respond(500);
			seriesService.deleteEpisode({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('resetReleases()', function () {
		it('should issue a PUT /api/series/:sid/episodes/:eid/releases/ request', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/').respond(200, {});
			seriesService.resetReleases({ 'show_id': 1 }, { 'episode_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/').respond(500);
			seriesService.resetReleases({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('forgetRelease()', function () {
		it('should issue a DELETE /api/series/:sid/episodes/:eid/releases/:rid/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/1/').respond(200, {});
			seriesService.forgetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { 'release_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/1/').respond(500);
			seriesService.forgetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { 'release_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('resetRelease()', function () {
		it('should issue a PUT /api/series/:sid/episodes/:eid/releases/:rid/ request', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/1/').respond(200, {});
			seriesService.resetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { 'release_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('PUT', '/api/series/1/episodes/1/releases/1/').respond(500);
			seriesService.resetRelease({ 'show_id': 1 }, { 'episode_id': 1 }, { 'release_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('deleteReleases()', function () {
		it('should issue a DELETE /api/series/:sid/episodes/:eid/releases/ request', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/').respond(200, {});
			seriesService.deleteReleases({ 'show_id': 1 }, { 'episode_id': 1 }).then(function () {
				expect(true).to.be.true;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('DELETE', '/api/series/1/episodes/1/releases/').respond(500);
			seriesService.deleteReleases({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});

	describe('loadReleases()', function () {
		it('should issue a GET /api/series/:sid/episodes/:eid/releases/ request', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/1/releases/').respond(200, {});
			seriesService.loadReleases({ 'show_id': 1 }, { 'episode_id': 1 }).then(function (data) {
				expect(data).to.exist;
			});
			$httpBackend.flush();
		});

		it('should report an error if request fails', function () {
			$httpBackend.expect('GET', '/api/series/1/episodes/1/releases/').respond(500);
			seriesService.loadReleases({ 'show_id': 1 }, { 'episode_id': 1 }).catch(function (error) {
				expect(error.message).to.equal('Request failed');
				expect(exception.catcher).to.have.been.calledOnce;
			});
			$httpBackend.flush();
		});
	});
});
<|endoftext|>


<commit_before>/**
 * Created by xubt on 4/20/16.
 */
var boardsLink = "http://localhost:8080/boards";

kanbanApp.controller('boardController', ['$scope', '$location', '$q', 'boardsService', 'localStorageService',
    function ($scope, $location, $q, boardsService, localStorageService) {
        var boardPromise = boardsService.load(boardsLink);
        boardsService.boardsLink = boardsLink;
        boardPromise.then(function (data) {
            $scope.boards = data;
        });

        $scope.toEntries = function (_boardId, _boardLink) {
            localStorageService.set("boardLink", _boardLink);
            $location.path('/boards/' + _boardId);
        };
        $scope.displayBoardCreationForm = true;
        $scope.displayForm = false;
        $scope.createBoard = function () {
            if ($scope.name === undefined || $scope.name === "") {
                $scope.isShowNameError = true;
                return;
            }
            var name = $scope.name;
            var board = {name: name};
            var entriesPromise = boardsService.create(board);
            entriesPromise.then(function (data) {
                if ($scope.boards === null) {
                    $scope.boards = [];
                }
                $scope.boards.push(data);
                $scope.cancelCreateBoard();
                $scope.name = "";
            });
        };
        $scope.keyPress = function ($event) {
            if ($event.keyCode == 13) {
                $scope.createBoard();
            }
            if ($event.keyCode == 27) {
                $scope.cancelCreateBoard();
            }
        };
        $scope.showBoardCreationForm = function () {
            $scope.displayBoardCreationForm = false;
            $scope.displayForm = true;
        };
        $scope.cancelCreateBoard = function () {
            $scope.displayBoardCreationForm = true;
            $scope.displayForm = false;
        };
    }]);
<commit_msg>Load boardsLink from local storage.<commit_after>/**
 * Created by xubt on 4/20/16.
 */

kanbanApp.controller('boardController', ['$scope', '$location', '$q', 'boardsService', 'localStorageService',
    function ($scope, $location, $q, boardsService, localStorageService) {
        var boardsLink = localStorageService.get("user.links").boards.href;
        var boardPromise = boardsService.load(boardsLink);
        boardsService.boardsLink = boardsLink;
        boardPromise.then(function (data) {
            $scope.boards = data;
        });

        $scope.toEntries = function (_boardId, _boardLink) {
            localStorageService.set("boardLink", _boardLink);
            $location.path('/boards/' + _boardId);
        };
        $scope.displayBoardCreationForm = true;
        $scope.displayForm = false;
        $scope.createBoard = function () {
            if ($scope.name === undefined || $scope.name === "") {
                $scope.isShowNameError = true;
                return;
            }
            var name = $scope.name;
            var board = {name: name};
            var entriesPromise = boardsService.create(board);
            entriesPromise.then(function (data) {
                if ($scope.boards === null) {
                    $scope.boards = [];
                }
                $scope.boards.push(data);
                $scope.cancelCreateBoard();
                $scope.name = "";
            });
        };
        $scope.keyPress = function ($event) {
            if ($event.keyCode == 13) {
                $scope.createBoard();
            }
            if ($event.keyCode == 27) {
                $scope.cancelCreateBoard();
            }
        };
        $scope.showBoardCreationForm = function () {
            $scope.displayBoardCreationForm = false;
            $scope.displayForm = true;
        };
        $scope.cancelCreateBoard = function () {
            $scope.displayBoardCreationForm = true;
            $scope.displayForm = false;
        };
    }]);
<|endoftext|>


<commit_before>angular.module( 'moviematch.match', ['moviematch.services'] )

.controller( 'MatchController', function( $scope, Match, Auth, Session, FetchMovies, Socket ) {
  $scope.session = {};
  $scope.user = {};
  $scope.imgPath = 'http://image.tmdb.org/t/p/w500';

  $scope.user.name = Auth.getUserName();
  //$scope.user.id = 1;

  $scope.session.name = Session.getSession();
  //$scope.session.id = 1;

  var currMovieIndex = 0;
  var currMoviePackage = 0;

  var fetchNextMovies = function( packageNumber, callback ){
    FetchMovies.getNext10Movies( packageNumber )
      .then(function( data ){
        console.log(data);
        $scope.moviePackage = data;
        callback();
      })
  };

  var loadNextMovie = function(){
    if( currMovieIndex === 9 ) {
      currMoviePackage++;
      fetchNextMovies( currMoviePackage, function() {
        $scope.currMovie = $scope.moviePackage[0];
        });
      currMovieIndex = 0;
    }
    else {
      currMovieIndex++;
      $scope.currMovie = $scope.moviePackage[currMovieIndex];
    }

  };

  $scope.init = function() {        //as soon as the view is loaded request the first movie-package here
    fetchNextMovies( 0 , function() {
        $scope.currMovie = $scope.moviePackage[0];
      })
  }
  $scope.init();

  // Listen for the signal to redirect to a 'match found' page.
  Socket.on( 'matchRedirect', function( data ) {
    Match.matchRedirect();
  });

  $scope.yes = function() {
    Match.sendVote( $scope.session.name, $scope.user.name, $scope.currMovie.id, true )
    // For every 'yes' we want to double check to see if we have a match. If we do,
    // we want to send a socket event out to inform the server.
    .then( function() {
      Match.checkMatch( $scope.session, $scope.currMovie )
      .then( function( result ) {
        if( result === true ) {
          Socket.emit( 'foundMatch', { sessionName: $scope.session.name, movie: $scope.currMovie } );
        }
      });
    });
    loadNextMovie();
  }
  $scope.no = function() {
    Match.sendVote( $scope.session.name, $scope.user.name, $scope.currMovie.id, false );
    loadNextMovie();
  }
} );
<commit_msg>Refactor for truthiness rather than deep truth<commit_after>angular.module( 'moviematch.match', ['moviematch.services'] )

.controller( 'MatchController', function( $scope, Match, Auth, Session, FetchMovies, Socket ) {
  $scope.session = {};
  $scope.user = {};
  $scope.imgPath = 'http://image.tmdb.org/t/p/w500';

  $scope.user.name = Auth.getUserName();
  //$scope.user.id = 1;

  $scope.session.name = Session.getSession();
  //$scope.session.id = 1;

  var currMovieIndex = 0;
  var currMoviePackage = 0;

  var fetchNextMovies = function( packageNumber, callback ){
    FetchMovies.getNext10Movies( packageNumber )
      .then(function( data ){
        console.log(data);
        $scope.moviePackage = data;
        callback();
      })
  };

  var loadNextMovie = function(){
    if( currMovieIndex === 9 ) {
      currMoviePackage++;
      fetchNextMovies( currMoviePackage, function() {
        $scope.currMovie = $scope.moviePackage[0];
        });
      currMovieIndex = 0;
    }
    else {
      currMovieIndex++;
      $scope.currMovie = $scope.moviePackage[currMovieIndex];
    }

  };

  $scope.init = function() {        //as soon as the view is loaded request the first movie-package here
    fetchNextMovies( 0 , function() {
        $scope.currMovie = $scope.moviePackage[0];
      })
  }
  $scope.init();

  // Listen for the signal to redirect to a 'match found' page.
  Socket.on( 'matchRedirect', function( data ) {
    Match.matchRedirect();
  });

  $scope.yes = function() {
    Match.sendVote( $scope.session.name, $scope.user.name, $scope.currMovie.id, true )
    // For every 'yes' we want to double check to see if we have a match. If we do,
    // we want to send a socket event out to inform the server.
    .then( function() {
      Match.checkMatch( $scope.session, $scope.currMovie )
      .then( function( result ) {
        if( result == true ) {
          Socket.emit( 'foundMatch', { sessionName: $scope.session.name, movie: $scope.currMovie } );
        }
      });
    });
    loadNextMovie();
  }
  $scope.no = function() {
    Match.sendVote( $scope.session.name, $scope.user.name, $scope.currMovie.id, false );
    loadNextMovie();
  }
} );
<|endoftext|>


<commit_before>import * as Collections from './../../lib/collections';
import {Meteor} from 'meteor/meteor';
import {Match} from 'meteor/check';
import {FlowRouter} from 'meteor/kadira:flow-router';
import {ReactiveDict} from 'meteor/reactive-dict';
import {Tracker} from 'meteor/tracker';
import $ from 'jquery';
import 'magnific-popup';
import {_} from 'meteor/underscore';
import {TAPi18n} from 'meteor/tap:i18n';
import {NotificationManager} from 'react-notifications';
import {moment} from 'meteor/momentjs:moment';
import { reducer as formReducer } from 'redux-form';
import {
  createStore,
  applyMiddleware,
  combineReducers
} from 'redux';
import createLogger from 'redux-logger';
import undoable from 'redux-undo';

import Helpers from './../lib/helpers';
import SelectedCtrl from './../lib/controllers/selected_nodes';
import ReferencesCtrl from './../lib/controllers/references';
import ShowMoreCtrl from './../lib/controllers/show_more';
import TagsCtrl from './../lib/controllers/tags';

const LocalState = new ReactiveDict();

// // Init local state
// // TODO: remove this
// LocalState.set('CURRENT_DOCUMENT', 'pXK96LKA7h8Ekggim');

export default function ({ reducers }) {

  const reducer = combineReducers({
    ...reducers,
    form: undoable(formReducer)
  });

  const middlewares = [
    createLogger()
  ];

  const Store = createStore(reducer, applyMiddleware(...middlewares));

  return {
    NotificationManager,
    moment,
    Match,
    SelectedCtrl,
    ReferencesCtrl,
    ShowMoreCtrl,
    TagsCtrl,
    TAPi18n,
    Meteor,
    FlowRouter,
    Collections,
    LocalState,
    Tracker,
    Helpers,
    $,
    _,
    Store,
    dispatch: Store.dispatch
  };
}
<commit_msg>Turn off redux logging.<commit_after>import * as Collections from './../../lib/collections';
import {Meteor} from 'meteor/meteor';
import {Match} from 'meteor/check';
import {FlowRouter} from 'meteor/kadira:flow-router';
import {ReactiveDict} from 'meteor/reactive-dict';
import {Tracker} from 'meteor/tracker';
import $ from 'jquery';
import 'magnific-popup';
import {_} from 'meteor/underscore';
import {TAPi18n} from 'meteor/tap:i18n';
import {NotificationManager} from 'react-notifications';
import {moment} from 'meteor/momentjs:moment';
import { reducer as formReducer } from 'redux-form';
import {
  createStore,
  applyMiddleware,
  combineReducers
} from 'redux';
import createLogger from 'redux-logger';
import undoable from 'redux-undo';

import Helpers from './../lib/helpers';
import SelectedCtrl from './../lib/controllers/selected_nodes';
import ReferencesCtrl from './../lib/controllers/references';
import ShowMoreCtrl from './../lib/controllers/show_more';
import TagsCtrl from './../lib/controllers/tags';

const LocalState = new ReactiveDict();

// // Init local state
// // TODO: remove this
// LocalState.set('CURRENT_DOCUMENT', 'pXK96LKA7h8Ekggim');

export default function ({ reducers }) {

  const reducer = combineReducers({
    ...reducers,
    form: undoable(formReducer)
  });

  const middlewares = [
    // createLogger()
  ];

  const Store = createStore(reducer, applyMiddleware(...middlewares));

  return {
    NotificationManager,
    moment,
    Match,
    SelectedCtrl,
    ReferencesCtrl,
    ShowMoreCtrl,
    TagsCtrl,
    TAPi18n,
    Meteor,
    FlowRouter,
    Collections,
    LocalState,
    Tracker,
    Helpers,
    $,
    _,
    Store,
    dispatch: Store.dispatch
  };
}
<|endoftext|>


<commit_before>// unauthenticated requests are rate-limited to 6/min
var githubSearchURL = 'https://api.github.com/search/repositories';
var sort = 'sort=stars&order=desc';
var githubOrg = '+org:Esri';

function assembleSearchUrl(keywords) {
    var query = '?q=';

    if (keywords) {
        keywords = keywords.trim();
        query += 'topic:' + keywords.replace(/ +/g, '+topic:');
    }

    query += '+NOT+deprecated';
    query += githubOrg;
    return githubSearchURL + query + '&' + sort;
}

function showQueryResults(tags, response) {
    if (!response.message) {
        var items = response.items,
        i,
        dateUpdated,
        html,
        project;

        if (Array.isArray(items) /*&& items.length > 0*/) {
            html = '';
            //$('#content').html('
' + items.length + '
');
            $('#numReposFound').html('
'+items.length+'
');
            // for (i = 0; i < items.length; i ++) {
            //     project = items[i];
            //     dateUpdated = new Date(project.updated_at).toLocaleDateString();
            //     html += '

' + project.name + '

' + (project.language || '') + '' + dateUpdated + '

' + (project.description || '') + '

 ' + project.forks_count + '  ' + project.stargazers_count + '
View it on github

';
            // }
            // $('#content').html('
' + html + '
');
        } else {
            //$('#content').html('
No projects found with tags ' + tags + '
');
            //$('#numReposFound').html("0");
            $('#numReposFound').html('
'+items.length+'
');
        }
    } else if (response.message && response.message.indexOf('API rate limit exceeded') > -1) {
        //$('#content').html('
Hold your horses. GitHub only allows six searches per minute.
');
        console.log("GitHub API rate limit exceeded...");
    }
}

function showQueryError(tags, error) {
    $('#numReposFound').html('
Error ' + error.message + ' searching for ' + tags + '
');
}

function redirectIfQuery() {
    var pageName = window.location.toString(),
        delimiterPosition,
        redirectURL = 'https://github.com/Esri?q=',
        topicList = document.getElementById('esri-topic-list').childNodes,
        redirected = false;

    delimiterPosition = pageName.indexOf('#');

    // if a hashed query is passed and cant be matched with our list of valid topics, redirect a canned github search
    if (delimiterPosition >= 0 && pageName.length - 1 > delimiterPosition) {
        for (var i=1; i < topicList.length; i++) {
            if (pageName.substr(delimiterPosition + 1) === topicList[i].innerHTML) {
                return redirected;
            }
        }

        pageName = redirectURL + pageName.substr(delimiterPosition + 1);
        redirected = true;
        window.location = pageName;
    }

    return redirected;
}

$(function() {
    var inlineLinks = document.getElementsByClassName("subdued-links");
    for (var i = 0; i < inlineLinks.length; ++i) {
        inlineLinks[i].addEventListener("click", function(){
        window.location.hash = this.id;
        });
    }

    if (redirectIfQuery()) {
        return;
    }
    $(".chosen-select").chosen({width: "100%", max_selected_options: 3});
    $(".chosen-container .search-field .chosen-search-input").attr("spellcheck", false);
    // $(".repo-language").click(function() {
    //     var e = this.innerHTML.replace(/ /g, "");
    //     return $("select").val(e).trigger("liszt:updated").change(),
    //         window.location.hash = e,
    //         !1
    // }),
    $("select").change(function() {
        var selectedOptions,
            selectedTags = [];
        selectedOptions = $("select option:selected"),

        selectedOptions.each(function() {
            selectedTags.push($(this).data("filter"));
        });

        if (selectedTags.length > 0) {
            var tags = selectedTags.join(" ");
            var searchURL = assembleSearchUrl(tags);
            //$('#content').html('
Looking for projects matching ' + tags + '
');
            fetch(searchURL).then(function (response) {
               response.json().then(function(json) {
                   showQueryResults(tags, json)
               }, function (error) {
                   showQueryError(tags, error);
               });
            },
            function (error) {
                showQueryError(tags, error);
            });
        } else {
            $('#numReposFound').html(' ');
        }
        window.location.hash = selectedTags.join(",");
    }),
    $(document).ready(function() {
        var e = window.location.hash;
        null !== e && "" != e && ($("select").val(e.replace(/#/, "").split(",")),
            $("select").trigger("liszt:updated").change())
    }),
    $(document).ready(function() {

        var n, i = !1, o = 3e3, a = 0; //c = ["JavaScript", "ActionScript", "Objective-C", "Java", "Python", "DotNet", "iOS", "C-Sharp", "Android", "QuickStart", "Local-Government", "Bootstrap", "Mapping", "GeoJSON", "Mobile", "Code-Challenge", "Utility", "Storytelling", "Geocoding", "ArcGIS", "Hadoop", "Web", "Social", "Analysis", "Offline", "Runtime", "Dashboard", "Public", ""];
        function e(e) {
            window.clearInterval(n),
            e && (n = setInterval(t, o))
        }
        function t() {
            $("select").val(c[a]),
                $("select").trigger("liszt:updated").change(),
                a < c.length - 1 ? a++ : a = 0
        }
        $(document).keydown(function(t) {
            38 === t.which && t.shiftKey && i ? o > 1e3 && (o -= 1e3) : 40 === t.which && t.shiftKey && i && 5e3 > o && (o += 1e3),
            i && e(i)
        })
        $("#btnViewRepos").on("click", function(e){
            e.preventDefault();
            var selectedOptions,
                selectedTags = [],
                urlEsriBase = "https://github.com/Esri",
                urlEsriRepos;

            selectedOptions = $("select option:selected"),
            selectedOptions.each(function() {
                selectedTags.push($(this).data("filter"));
            });
            if (selectedTags.length > 0) {
                var tags = selectedTags.join("+topic:");
                window.location.href = urlEsriBase + '?q=topic:' + tags;
            } else {
                window.location.href = urlEsriBase;
            }
        })
    })
});
<commit_msg>Major cleanup, simplified, removed hash behavior<commit_after>// unauthenticated requests are rate-limited to 6/min
var githubSearchURL = 'https://api.github.com/search/repositories';
var sort = 'sort=stars&order=desc';
var githubOrg = '+org:Esri';

function assembleSearchUrl(keywords) {
    var query = '?q=';

    if (keywords) {
        keywords = keywords.trim();
        query += 'topic:' + keywords.replace(/ +/g, '+topic:');
    }

    query += '+NOT+deprecated';
    query += githubOrg;
    return githubSearchURL + query + '&' + sort;
}

function showQueryResults(tags, response) {
    showElement($(".spinner"), false);
    if (!response.message) {
        var items = response.items || [];
        $('#numReposFound').html(items.length);
    } else if (response.message && response.message.indexOf('API rate limit exceeded') > -1) {
        console.log("GitHub API rate limit exceeded...");
    } else {
        $('#numReposFound').html("0");
    }
}

function showQueryError(tags, error) {
    showElement($(".spinner"), false);
    console.error(error.message);
}

function showElement(ele, show) {
    if (show) {
        ele.removeClass("hide");
    } else {
        ele.addClass("hide")
    }
}

function clearResults() {
    $("#numReposFound").empty();
}

function redirectIfQuery() {
    var pageName = window.location.toString(),
        delimiterPosition,
        redirectURL = 'https://github.com/Esri?q=',
        topicList = document.getElementById('esri-topic-list').childNodes,
        redirected = false;

    delimiterPosition = pageName.indexOf('#');

    // if a hashed query is passed and cant be matched with our list of valid topics, redirect a canned github search
    if (delimiterPosition >= 0 && pageName.length - 1 > delimiterPosition) {
        for (var i=1; i < topicList.length; i++) {
            if (pageName.substr(delimiterPosition + 1) === topicList[i].innerHTML) {
                return redirected;
            }
        }
        pageName = redirectURL + pageName.substr(delimiterPosition + 1);
        redirected = true;
        window.location = pageName;
    }
    return redirected;
}

function getSelectedTags() {
    var selectedOptions,
        selectedTags = [];
    selectedOptions = $("select option:selected"),
    selectedOptions.each(function() {
        selectedTags.push($(this).data("filter"));
    });
    return selectedTags;
}

$(function() {
    // Backwards compatibility - Redirect if query doesn't match a topic e.g. esri.github.io/#bootstrap-map-js
    if (redirectIfQuery()) {
        return;
    }

    // Show control after select is loaded
    $(".chzn-select").removeClass("hidden");

    // Initialize chosen
    $(".chosen-select").chosen({width: "100%", max_selected_options: 3});

    // Provide spell check search
    $(".chosen-container .search-field .chosen-search-input").attr("spellcheck", false);

    // Fetch number of repos that match query
    $("select").change(function() {
        // UI
        clearResults();
        showElement($(".spinner"), true);
        // Get tags
        var selectedTags = getSelectedTags();
        // Fetch repos
        if (selectedTags.length > 0) {
            var tags = selectedTags.join(" ");
            var searchURL = assembleSearchUrl(tags);
            fetch(searchURL).then(function (response) {
               response.json().then(function(json) {
                   showQueryResults(tags, json)
               }, function (error) {
                   showQueryError(tags, error);
               });
            },
            function (error) {
                showQueryError(tags, error);
            });
        } else {
            showElement($(".spinner"), false);
        }
    });

    $(document).ready(function() {
        // Go to GitHub
        $("#btnViewRepos").on("click", function(e){
            e.preventDefault();
            var urlEsriBase = "https://github.com/Esri";

            // Get tags
            var selectedTags = getSelectedTags();
            if (selectedTags.length > 0) {
                var tags = selectedTags.join("+topic:");
                window.location.href = urlEsriBase + '?q=topic:' + tags;
            } else {
                window.location.href = urlEsriBase;
            }
        })
    })
});
<|endoftext|>


<commit_before>ScriptRunner.require("cluster/HttpCluster.js");
ScriptRunner.require("cluster/ZookeeperCluster.js");
ScriptRunner.require("cluster/KafkaCluster.js");
ScriptRunner.require("cluster/SparknginCluster.js");
ScriptRunner.require("cluster/DemandSpikeCluster.js");

var appDir = java.lang.System.getProperty("app.dir") ;

this.HTTP_CONFIG = {
  listenPort: 8080,
  webappDir: appDir + "/webapp",
  serverRole: "generic",
  servers: ["generic"]
};

this.KAFKA_CONFIG = {
  port: 9092,
  zookeeperConnect: "127.0.0.1:2181",
  serverRole: "kafka",
  servers: ["kafka1", "kafka2", "kafka3"],
  kafkaConnect: "127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094"
};

this.SPARKNGIN_CONFIG = {
  serverRole: "sparkngin",
  servers: ["sparkngin1"],
  httpListenPort: 7080,
  forwarderClass: "com.neverwinterdp.sparkngin.http.NullDevMessageForwarder",
  sparknginConnect: "127.0.0.1:7070"
};

var ClusterEnv = {
  httpCluster: new HttpCluster(HTTP_CONFIG) ,
  zkCluster: new ZookeeperCluster() ,
  kafkaCluster: new KafkaCluster(KAFKA_CONFIG),
  sparknginCluster: new SparknginCluster(SPARKNGIN_CONFIG),
  demandspikeCluster: new DemandSpikeCluster(),

  install: function() {
    this.httpCluster.installByServer() ;
    this.zkCluster.installByServer() ;
    this.kafkaCluster.installByServer() ;
    this.sparknginCluster.installByServer() ;
    this.demandspikeCluster.installByServer() ;
    ClusterShell.module.list() ;
  },

  uninstall: function() {
    this.demandspikeCluster.uninstall() ;
    this.sparknginCluster.uninstall() ;
    this.kafkaCluster.uninstall() ;
    this.zkCluster.uninstall() ;
    //this.httpCluster.uninstall() ;
  }
}

function runAll() {
  var demandSpikeJobParams = [
    {
      //test kafka with 1k message size
      "driver": "kafka", "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
      "num-of-task": 2,  "num-of-thread": 2, "message-size": 1024,
      "member-role": "demandspike", "max-duration": 15000, "max-num-of-message": 3000000
    },
    {
      //test kafka with 2k message size
      "driver": "kafka", "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
      "num-of-task": 2,  "num-of-thread": 2, "message-size": 2048,
      "member-role": "demandspike", "max-duration": 15000, "max-num-of-message": 3000000
    },
    {
      //test sparkngin with 1k message size, forward to device null
      "driver": "sparkngin", "broker-connect": SPARKNGIN_CONFIG.sparknginConnect, "topic": "metrics.consumer",
      "num-of-task": 2,  "num-of-thread": 2, "message-size": 1024,
      "member-role": "demandspike", "max-duration": 15000, "max-num-of-message": 3000000
    }
  ]

  for(var i = 0; i < demandSpikeJobParams.length; i++) {
    var jobParams = demandSpikeJobParams[i] ;
    ClusterEnv.install() ;
    ClusterEnv.demandspikeCluster.submitDemandSpikeJob(jobParams, true) ;
    ClusterShell.server.metric({}) ;
    ClusterShell.server.clearMetric({"expression": "*"}) ;
    ClusterEnv.uninstall() ;
  }
}

function runSingle() {
  var jobParams = {
    //test kafka with 1k message size
    "driver": "kafka", "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
    "num-of-task": 2,  "num-of-thread": 2, "message-size": 1024,
    "member-role": "demandspike", "max-duration": 60000, "max-num-of-message": 3000000
  }

  ClusterEnv.install() ;
  ClusterEnv.demandspikeCluster.submitDemandSpikeJob(jobParams, true) ;
  ClusterShell.server.metric({}) ;
  ClusterShell.server.clearMetric({"expression": "*"}) ;
  ClusterEnv.uninstall() ;
}

function runKafkaRandomFailure() {
  var jobParams = {
    //test kafka with 1k message size
    "driver": "kafka", "driver:request.required.acks": "1",
    "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
    "num-of-task": 2, "num-of-thread": 2, "message-size": 1024,
    "member-role": "demandspike", "max-duration": 60000, "max-num-of-message": 3000000,

    "problem:kafka.problem": "service-failure",
    "problem:kafka.member-role": "kafka",
    "problem:kafka.module": "Kafka",
    "problem:kafka.service-id": "KafkaClusterService",
    "problem:kafka.period": "15000",
    "problem:kafka.failure-time": "1000"
  }

  ClusterEnv.install() ;
  ClusterEnv.demandspikeCluster.submitDemandSpikeJob(jobParams, true) ;
  ClusterShell.server.metric({}) ;
  ClusterShell.server.clearMetric({"expression": "*"}) ;
  ClusterEnv.uninstall() ;
}

runSingle() ;
ClusterShell.server.clearMetric({"expression": "*"}) ;
runKafkaRandomFailure() ;
//runAll() ;

<commit_msg>add request ack parameter<commit_after>ScriptRunner.require("cluster/HttpCluster.js");
ScriptRunner.require("cluster/ZookeeperCluster.js");
ScriptRunner.require("cluster/KafkaCluster.js");
ScriptRunner.require("cluster/SparknginCluster.js");
ScriptRunner.require("cluster/DemandSpikeCluster.js");

var appDir = java.lang.System.getProperty("app.dir") ;

this.HTTP_CONFIG = {
  listenPort: 8080,
  webappDir: appDir + "/webapp",
  serverRole: "generic",
  servers: ["generic"]
};

this.KAFKA_CONFIG = {
  port: 9092,
  zookeeperConnect: "127.0.0.1:2181",
  serverRole: "kafka",
  servers: ["kafka1", "kafka2", "kafka3"],
  kafkaConnect: "127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094"
};

this.SPARKNGIN_CONFIG = {
  serverRole: "sparkngin",
  servers: ["sparkngin1"],
  httpListenPort: 7080,
  forwarderClass: "com.neverwinterdp.sparkngin.http.NullDevMessageForwarder",
  sparknginConnect: "127.0.0.1:7070"
};

var ClusterEnv = {
  httpCluster: new HttpCluster(HTTP_CONFIG) ,
  zkCluster: new ZookeeperCluster() ,
  kafkaCluster: new KafkaCluster(KAFKA_CONFIG),
  sparknginCluster: new SparknginCluster(SPARKNGIN_CONFIG),
  demandspikeCluster: new DemandSpikeCluster(),

  install: function() {
    this.httpCluster.installByServer() ;
    this.zkCluster.installByServer() ;
    this.kafkaCluster.installByServer() ;
    this.sparknginCluster.installByServer() ;
    this.demandspikeCluster.installByServer() ;
    ClusterShell.module.list() ;
  },

  uninstall: function() {
    this.demandspikeCluster.uninstall() ;
    this.sparknginCluster.uninstall() ;
    this.kafkaCluster.uninstall() ;
    this.zkCluster.uninstall() ;
    //this.httpCluster.uninstall() ;
  }
}

function runAll() {
  var demandSpikeJobParams = [
    {
      //test kafka with 1k message size
      "driver": "kafka", "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
      "num-of-task": 2,  "num-of-thread": 2, "message-size": 1024,
      "member-role": "demandspike", "max-duration": 15000, "max-num-of-message": 3000000
    },
    {
      //test kafka with 2k message size
      "driver": "kafka", "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
      "num-of-task": 2,  "num-of-thread": 2, "message-size": 2048,
      "member-role": "demandspike", "max-duration": 15000, "max-num-of-message": 3000000
    },
    {
      //test sparkngin with 1k message size, forward to device null
      "driver": "sparkngin", "broker-connect": SPARKNGIN_CONFIG.sparknginConnect, "topic": "metrics.consumer",
      "num-of-task": 2,  "num-of-thread": 2, "message-size": 1024,
      "member-role": "demandspike", "max-duration": 15000, "max-num-of-message": 3000000
    }
  ]

  for(var i = 0; i < demandSpikeJobParams.length; i++) {
    var jobParams = demandSpikeJobParams[i] ;
    ClusterEnv.install() ;
    ClusterEnv.demandspikeCluster.submitDemandSpikeJob(jobParams, true) ;
    ClusterShell.server.metric({}) ;
    ClusterShell.server.clearMetric({"expression": "*"}) ;
    ClusterEnv.uninstall() ;
  }
}

function runSingle() {
  var jobParams = {
    //test kafka with 1k message size
    "driver": "kafka", "driver:request.required.acks": "1",
    "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
    "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
    "num-of-task": 2,  "num-of-thread": 2, "message-size": 1024,
    "member-role": "demandspike", "max-duration": 60000, "max-num-of-message": 3000000
  }

  ClusterEnv.install() ;
  ClusterEnv.demandspikeCluster.submitDemandSpikeJob(jobParams, true) ;
  ClusterShell.server.metric({}) ;
  ClusterShell.server.clearMetric({"expression": "*"}) ;
  ClusterEnv.uninstall() ;
}

function runKafkaRandomFailure() {
  var jobParams = {
    //test kafka with 1k message size
    "driver": "kafka", "driver:request.required.acks": "1",
    "broker-connect": KAFKA_CONFIG.kafkaConnect, "topic": "metrics.consumer",
    "num-of-task": 2, "num-of-thread": 2, "message-size": 1024,
    "member-role": "demandspike", "max-duration": 60000, "max-num-of-message": 3000000,

    "problem:kafka.problem": "service-failure",
    "problem:kafka.member-role": "kafka",
    "problem:kafka.module": "Kafka",
    "problem:kafka.service-id": "KafkaClusterService",
    "problem:kafka.period": "15000",
    "problem:kafka.failure-time": "1000"
  }

  ClusterEnv.install() ;
  ClusterEnv.demandspikeCluster.submitDemandSpikeJob(jobParams, true) ;
  ClusterShell.server.metric({}) ;
  ClusterShell.server.clearMetric({"expression": "*"}) ;
  ClusterEnv.uninstall() ;
}

runSingle() ;
ClusterShell.server.clearMetric({"expression": "*"}) ;
runKafkaRandomFailure() ;
//runAll() ;

<|endoftext|>


<commit_before>class Picker {
	constructor(opts) {
		this.parent = opts.parent;
		this.width = opts.width;
		this.height = opts.height;
		this.country = opts.country;
		opts.country && this.set_country(opts.country);
		this.countries = opts.countries;
		this.setup_picker();
	}

	refresh() {
		this.update_icon_selected(true);
	}

	setup_picker() {
		this.icon_picker_wrapper = $(`

					<input type="search" placeholder="Search for countries.." class="form-control">
					${frappe.utils.icon('search', "sm")}

		`);
		this.parent.append(this.icon_picker_wrapper);
		this.icon_wrapper = this.icon_picker_wrapper.find('.phones');
		this.search_input = this.icon_picker_wrapper.find('.search-phones > input');
		this.refresh();
		this.setup_icons();
	}

	setup_icons() {

		Object.entries(this.countries).forEach(([country, info]) => {
		let $country = $(`<div id="${country}" class="phone-wrapper">${frappe.utils.flag(info.code, "md")}<span class="country">${country}</span></div>`);
		this.icon_wrapper.append($country);
		const set_values = () => {
			this.set_country(country);
			this.update_icon_selected();
		};
		$country.on('click', () => {
			set_values();
		});
		$country.hover(() => {
			$country.toggleClass("bg-gray-100");
		 });
		this.search_input.keydown((e) => {
			const key_code = e.keyCode;
			if ([13, 32].includes(key_code)) {
				e.preventDefault();
				set_values();
			}
		});
		this.search_input.keyup((e) => {
			e.preventDefault();
			this.filter_icons();
		});

		this.search_input.on('search', () => {
			this.filter_icons();
		});
	});
	}

	filter_icons() {
		let value = this.search_input.val();
		if (!value) {
			this.icon_wrapper.find(".phone-wrapper").removeClass('hidden');
		} else {
			this.icon_wrapper.find(".phone-wrapper").addClass('hidden');
			this.icon_wrapper.find(`.phone-wrapper[id*='${value}']`).removeClass('hidden');
		}
	}

	update_icon_selected(silent) {
		!silent && this.on_change && this.on_change(this.get_country());
	}

	set_country(country) {
		this.country = country || '';
	}

	get_country() {
		if (!this.country) return frappe.utils.icon("down", "sm")
		return this.country;
	}
}

export default Picker;
<commit_msg>fix: made the search for country case insensitive<commit_after>class Picker {
	constructor(opts) {
		this.parent = opts.parent;
		this.width = opts.width;
		this.height = opts.height;
		this.country = opts.country;
		opts.country && this.set_country(opts.country);
		this.countries = opts.countries;
		this.setup_picker();
	}

	refresh() {
		this.update_icon_selected(true);
	}

	setup_picker() {
		this.icon_picker_wrapper = $(`

					<input type="search" placeholder="Search for countries.." class="form-control">
					${frappe.utils.icon('search', "sm")}

		`);
		this.parent.append(this.icon_picker_wrapper);
		this.icon_wrapper = this.icon_picker_wrapper.find('.phones');
		this.search_input = this.icon_picker_wrapper.find('.search-phones > input');
		this.refresh();
		this.setup_icons();
	}

	setup_icons() {

		Object.entries(this.countries).forEach(([country, info]) => {
		let $country = $(`<div id="${country.toLowerCase()}" class="phone-wrapper">${frappe.utils.flag(info.code, "md")}<span class="country">${country}</span></div>`);
		this.icon_wrapper.append($country);
		const set_values = () => {
			this.set_country(country);
			this.update_icon_selected();
		};
		$country.on('click', () => {
			set_values();
		});
		$country.hover(() => {
			$country.toggleClass("bg-gray-100");
		 });
		this.search_input.keydown((e) => {
			const key_code = e.keyCode;
			if ([13].includes(key_code)) {
				e.preventDefault();
				set_values();
			}
		});
		this.search_input.keyup((e) => {
			e.preventDefault();
			this.filter_icons();
		});

		this.search_input.on('search', () => {
			this.filter_icons();
		});
	});
	}

	filter_icons() {
		let value = this.search_input.val();
		if (!value) {
			this.icon_wrapper.find(".phone-wrapper").removeClass('hidden');
		} else {
			this.icon_wrapper.find(".phone-wrapper").addClass('hidden');
			this.icon_wrapper.find(`.phone-wrapper[id*='${value.toLowerCase()}']`).removeClass('hidden');
		}
	}

	update_icon_selected(silent) {
		!silent && this.on_change && this.on_change(this.get_country());
	}

	set_country(country) {
		this.country = country || '';
	}

	get_country() {
		if (!this.country) return frappe.utils.icon("down", "sm")
		return this.country;
	}
}

export default Picker;
<|endoftext|>


<commit_before>// initialize with ID (string) of field that should act like a shell,
//  i.e., command history, taking input and replacing it with output from server
var shellObject = function(shellArea, historyArea, shellFunctions) {
    var keys = {
        arrowUp: 38,
        arrowDown: 40,
        arrowLeft: 37,
        arrowRight: 39,
        cKey: 67,
        ctrlKeyCode: 17,
        metaKeyCodes: [224, 17, 91, 93],
        backspace: 8,
        tab: 9,
        enter: 13
    };

    var unicodeBell = '\u0007';
    var setCaretPosition = shellFunctions['setCaretPosition'];
    var postMessage = shellFunctions['postMessage'];
    var scrollDown = shellFunctions['scrollDown'];
    var interrupt = shellFunctions['interrupt'];
    var tabPress = shellFunctions['tabPress'];
    var mathProgramOutput = "";
    var shell = shellArea;
    var history = historyArea;
    var cmdHistory = []; // History of M2 commands for shell-like arrow navigation
    cmdHistory.index = 0;

    shell.on("track", function(e, msg) { // add command to history
        //console.log("Tracking message: " + msg);
        if (typeof msg != 'undefined') {
            var input = msg.split("\n");
            for (var line in input) {
                if (input[line].length > 0) {
                    // console.log("Line: " + input[line]);
                    cmdHistory.index = cmdHistory.push(input[line]);
                }
            }
        }
    });

    function stripInputPrompt(lastLine) {
        return lastLine.replace(/^i\d+\s*:/, "");
    }

    function stripSpacesAtBeginningOfLine(lastLine) {
        return lastLine.replace(/^\s*/, "");
    }

    function stripPrompt(lastLine) {
        return lastLine.replace(/^> /, "");
    }

    var getCurrentCommand = function(){
        var completeText = shell.val().split("\n");
        var lastLine = completeText[completeText.length-2];
        // Need to set prompt symbol somewhere else.
        lastLine = stripInputPrompt(lastLine);
        lastLine = stripSpacesAtBeginningOfLine(lastLine);
        lastLine = stripPrompt(lastLine);
        return lastLine;
    };

    // On pressing return send last part of M2Out to M2 and remove it.
    shell.keyup(function(e) {
        if (e.keyCode == keys.enter) { // Return
            // We trigger the track manually, since we might have used tab.
            shell.trigger('track',getCurrentCommand());
            // Disable traking of posted message.
            packageAndSendMessage('', true);
        }
    });

    var packageAndSendMessage = function(tail, notrack){
        setCaretPosition(shell, shell.val().length);
        if (shell.val().length >= mathProgramOutput.length) {
            l = shell.val().length;
            msg = shell.val().substring(mathProgramOutput.length, l) + tail;
            if(history != undefined){
               history.val(history.val() + msg);
               scrollDown(history);
            }
            postMessage(msg, notrack);
        } else {
            console.log("There must be an error.");
            // We don't want empty lines send to M2 at pressing return twice.
            //e.preventDefault();
        }
    };

    var upDownArrowKeyHandling = function(e){
        e.preventDefault();
        if (cmdHistory.length == 0){
            // Maybe we did nothing so far.
            return;
        }
        if ((e.keyCode == keys.arrowDown) && (cmdHistory.index < cmdHistory.length)) { // DOWN
            cmdHistory.index = cmdHistory.index + 1;
        }
        if ((e.keyCode == keys.arrowUp) && (cmdHistory.index > 0)) { // UP
            if (cmdHistory.index == cmdHistory.length) {
                cmdHistory.current = shell.val().substring(mathProgramOutput.length, shell.val().length);
            }
            cmdHistory.index = cmdHistory.index - 1;
        }
        if (cmdHistory.index == cmdHistory.length) {
            shell.val(shell.val().substring(0, mathProgramOutput.length) + cmdHistory.current);
        } else {
            shell.val(shell.val().substring(0, mathProgramOutput.length) + cmdHistory[cmdHistory.index]);
        }
        scrollDown(shell);
    };

    // If something is entered, change to end of textarea, if at wrong position.
    shell.keydown(function(e) {
        // console.log("Got keydown: " + e.keyCode);
        // The keys 37, 38, 39 and 40 are the arrow keys.
        if (e.keyCode == keys.enter){
            setCaretPosition(shell, shell.val().length);
        }

        if ((e.keyCode == keys.arrowUp) || (e.keyCode == keys.arrowDown)) {
            upDownArrowKeyHandling(e);
        }
        if (e.keyCode == keys.ctrlKeyCode) { // do not jump to bottom on Ctrl+C or on Ctrl
            return;
        }
        if (e.ctrlKey && e.keyCode == keys.cKey){
            interrupt();
        }
        // for MAC OS
        if ((e.metaKey && e.keyCode == keys.cKey) || (keys.metaKeyCodes.indexOf(e.keyCode) > -
            1)) { // do not jump to bottom on Command+C or on Command
            return;
        }
        var pos = shell[0].selectionStart;
        if (pos < mathProgramOutput.length) {
            setCaretPosition(shell, shell.val().length);
        }
        // This deals with backspace.
        // We may not shorten the string entered by M2.
        if (e.keyCode == keys.backspace) {
            if (shell.val().length == mathProgramOutput.length) {
                e.preventDefault();
            }
        }
        // Forward key for tab completion, but do not track it.
        if(e.keyCode == keys.tab){
            packageAndSendMessage("\t", true);
            e.preventDefault();
        }
    });

    shell.on("onmessage", function(e, msgDirty) {
        // console.log("Dirty JSON message: " + JSON.stringify(msgDirty));
        if(msgDirty == unicodeBell){
            return;
        }
        var msg = msgDirty.replace(/\u0007/,"");
        msg = msg.replace(/\r\n/g,"\n");
        msg = msg.replace(/\r/g,"\n");
        var completeText = shell.val();
        mathProgramOutput += msg;
        var after = completeText.substring(mathProgramOutput.length, completeText.length);
        var commonIndex = 0;
        while((after[commonIndex] == msg[commonIndex]) && (commonIndex < after.length) && (commonIndex < msg.length)){
            commonIndex++;
        }
        var nonReturnedInput = after.substring(commonIndex, after.length);
        shell.val(mathProgramOutput + nonReturnedInput);
        scrollDown(shell);
    });

    shell.on("reset", function(){
       //console.log("Received reset event.");
       shell.val(mathProgramOutput);
    });
};

<commit_msg>Formatting<commit_after>// initialize with ID (string) of field that should act like a shell,
//  i.e., command history, taking input and replacing it with output from server
var shellObject = function (shellArea, historyArea, shellFunctions) {
    var keys = {
        arrowUp: 38,
        arrowDown: 40,
        arrowLeft: 37,
        arrowRight: 39,
        cKey: 67,
        ctrlKeyCode: 17,
        metaKeyCodes: [224, 17, 91, 93],
        backspace: 8,
        tab: 9,
        enter: 13
    };

    var unicodeBell = '\u0007';
    var setCaretPosition = shellFunctions['setCaretPosition'];
    var postMessage = shellFunctions['postMessage'];
    var scrollDown = shellFunctions['scrollDown'];
    var interrupt = shellFunctions['interrupt'];
    var tabPress = shellFunctions['tabPress'];
    var mathProgramOutput = "";
    var shell = shellArea;
    var history = historyArea;
    var cmdHistory = []; // History of M2 commands for shell-like arrow navigation
    cmdHistory.index = 0;

    shell.on("track", function (e, msg) { // add command to history
        //console.log("Tracking message: " + msg);
        if (typeof msg != 'undefined') {
            var input = msg.split("\n");
            for (var line in input) {
                if (input[line].length > 0) {
                    // console.log("Line: " + input[line]);
                    cmdHistory.index = cmdHistory.push(input[line]);
                }
            }
        }
    });

    function stripInputPrompt(lastLine) {
        return lastLine.replace(/^i\d+\s*:/, "");
    }

    function stripSpacesAtBeginningOfLine(lastLine) {
        return lastLine.replace(/^\s*/, "");
    }

    function stripPrompt(lastLine) {
        return lastLine.replace(/^> /, "");
    }

    var getCurrentCommand = function () {
        var completeText = shell.val().split("\n");
        var lastLine = completeText[completeText.length - 2];
        // Need to set prompt symbol somewhere else.
        lastLine = stripInputPrompt(lastLine);
        lastLine = stripSpacesAtBeginningOfLine(lastLine);
        lastLine = stripPrompt(lastLine);
        return lastLine;
    };

    // On pressing return send last part of M2Out to M2 and remove it.
    shell.keyup(function (e) {
        if (e.keyCode == keys.enter) { // Return
            // We trigger the track manually, since we might have used tab.
            shell.trigger('track', getCurrentCommand());
            // Disable traking of posted message.
            packageAndSendMessage('', true);
        }
    });

    var packageAndSendMessage = function (tail, notrack) {
        setCaretPosition(shell, shell.val().length);
        if (shell.val().length >= mathProgramOutput.length) {
            l = shell.val().length;
            msg = shell.val().substring(mathProgramOutput.length, l) + tail;
            if (history != undefined) {
                history.val(history.val() + msg);
                scrollDown(history);
            }
            postMessage(msg, notrack);
        } else {
            console.log("There must be an error.");
            // We don't want empty lines send to M2 at pressing return twice.
            //e.preventDefault();
        }
    };

    var upDownArrowKeyHandling = function (e) {
        e.preventDefault();
        if (cmdHistory.length == 0) {
            // Maybe we did nothing so far.
            return;
        }
        if ((e.keyCode == keys.arrowDown) && (cmdHistory.index < cmdHistory.length)) { // DOWN
            cmdHistory.index = cmdHistory.index + 1;
        }
        if ((e.keyCode == keys.arrowUp) && (cmdHistory.index > 0)) { // UP
            if (cmdHistory.index == cmdHistory.length) {
                cmdHistory.current = shell.val().substring(mathProgramOutput.length, shell.val().length);
            }
            cmdHistory.index = cmdHistory.index - 1;
        }
        if (cmdHistory.index == cmdHistory.length) {
            shell.val(shell.val().substring(0, mathProgramOutput.length) + cmdHistory.current);
        } else {
            shell.val(shell.val().substring(0, mathProgramOutput.length) + cmdHistory[cmdHistory.index]);
        }
        scrollDown(shell);
    };

    // If something is entered, change to end of textarea, if at wrong position.
    shell.keydown(function (e) {
        // console.log("Got keydown: " + e.keyCode);
        // The keys 37, 38, 39 and 40 are the arrow keys.
        if (e.keyCode == keys.enter) {
            setCaretPosition(shell, shell.val().length);
        }

        if ((e.keyCode == keys.arrowUp) || (e.keyCode == keys.arrowDown)) {
            upDownArrowKeyHandling(e);
        }
        if (e.keyCode == keys.ctrlKeyCode) { // do not jump to bottom on Ctrl+C or on Ctrl
            return;
        }
        if (e.ctrlKey && e.keyCode == keys.cKey) {
            interrupt();
        }
        // for MAC OS
        if ((e.metaKey && e.keyCode == keys.cKey) || (keys.metaKeyCodes.indexOf(e.keyCode) > -
                1)) { // do not jump to bottom on Command+C or on Command
            return;
        }
        var pos = shell[0].selectionStart;
        if (pos < mathProgramOutput.length) {
            setCaretPosition(shell, shell.val().length);
        }
        // This deals with backspace.
        // We may not shorten the string entered by M2.
        if (e.keyCode == keys.backspace) {
            if (shell.val().length == mathProgramOutput.length) {
                e.preventDefault();
            }
        }
        // Forward key for tab completion, but do not track it.
        if (e.keyCode == keys.tab) {
            packageAndSendMessage("\t", true);
            e.preventDefault();
        }
    });

    shell.on("onmessage", function (e, msgDirty) {
        // console.log("Dirty JSON message: " + JSON.stringify(msgDirty));
        if (msgDirty == unicodeBell) {
            return;
        }
        var msg = msgDirty.replace(/\u0007/, "");
        msg = msg.replace(/\r\n/g, "\n");
        msg = msg.replace(/\r/g, "\n");
        var completeText = shell.val();
        mathProgramOutput += msg;
        var after = completeText.substring(mathProgramOutput.length, completeText.length);
        var commonIndex = 0;
        while ((after[commonIndex] == msg[commonIndex]) && (commonIndex < after.length) && (commonIndex < msg.length)) {
            commonIndex++;
        }
        var nonReturnedInput = after.substring(commonIndex, after.length);
        shell.val(mathProgramOutput + nonReturnedInput);
        scrollDown(shell);
    });

    shell.on("reset", function () {
        //console.log("Received reset event.");
        shell.val(mathProgramOutput);
    });
};

<|endoftext|>


<commit_before>(function() {
  function initNgModules(element) {
      var elements = [element],
          moduleElements = [],
          modules = [],
          names = ['ng:module', 'ng-module', 'x-ng-module', 'data-ng-module', 'ng:modules', 'ng-modules', 'x-ng-modules', 'data-ng-modules'],
          NG_MODULE_CLASS_REGEXP = /\sng[:\-]module[s](:\s*([\w\d_]+);?)?\s/;

      function append(element) {
          element && elements.push(element);
      }

      for(var i = 0; i < names.length; i++) {
          var name = names[i];
          names[i] = true;
          append(document.getElementById(name));
          name = name.replace(':', '\\:');
          if (element.querySelectorAll) {
              var elements2;
              elements2 = element.querySelectorAll('.' + name);
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('.' + name + '\\:');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('[' + name + ']');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);
          }
      }

      for(var i = 0; i < elements.length; i++) {
          var element = elements[i];

          var className = ' ' + element.className + ' ';
          var match = NG_MODULE_CLASS_REGEXP.exec(className);
          if (match) {
              moduleElements.push(element);
              modules.push((match[2] || '').replace(/\s+/g, ','));
          } else {
              if(element.attributes) {
                  for (var attrName in element.attributes) {
                      if(attrName == "length") continue;
                      var attr = { name: attrName, value: element.attributes[attrName].nodeValue };

                      if (names[attr.name]) {
                          moduleElements.push(element);
                          modules.push(attr.value);
                      }
                  }
              }
          }
      }

      for(var i = 0; i < moduleElements.length; i++) {
          var moduleElement = moduleElements[i];
          var module = modules[i].replace(/ /g,'').split(",");
          angular.bootstrap(moduleElement, module);
      }
  }

  angular.element(document).ready(function() {
        initNgModules(document);
  });
})();<commit_msg>added check to avoid error in firefox<commit_after>(function() {
  function initNgModules(element) {
      var elements = [element],
          moduleElements = [],
          modules = [],
          names = ['ng:module', 'ng-module', 'x-ng-module', 'data-ng-module', 'ng:modules', 'ng-modules', 'x-ng-modules', 'data-ng-modules'],
          NG_MODULE_CLASS_REGEXP = /\sng[:\-]module[s](:\s*([\w\d_]+);?)?\s/;

      function append(element) {
          element && elements.push(element);
      }

      for(var i = 0; i < names.length; i++) {
          var name = names[i];
          names[i] = true;
          append(document.getElementById(name));
          name = name.replace(':', '\\:');
          if (element.querySelectorAll) {
              var elements2;
              elements2 = element.querySelectorAll('.' + name);
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('.' + name + '\\:');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);

              elements2 = element.querySelectorAll('[' + name + ']');
              for(var j = 0; j < elements2.length; j++) append(elements2[j]);
          }
      }

      for(var i = 0; i < elements.length; i++) {
          var element = elements[i];

          var className = ' ' + element.className + ' ';
          var match = NG_MODULE_CLASS_REGEXP.exec(className);
          if (match) {
              moduleElements.push(element);
              modules.push((match[2] || '').replace(/\s+/g, ','));
          } else {
              if(element.attributes) {
                  for (var attrName in element.attributes) {
                      if(attrName == "length") continue;
                      var attr = { name: attrName, value: element.attributes[attrName].nodeValue };

                      if (names[attr.name]) {
                          moduleElements.push(element);
                          modules.push(attr.value);
                      }
                  }
              }
          }
      }

      for(var i = 0; i < moduleElements.length; i++) {
          var moduleElement = moduleElements[i];
          if (typeof(modules[i]) != 'undefined') {
            var module = modules[i].replace(/ /g,'').split(",");
            angular.bootstrap(moduleElement, module);
          }
      }
  }

  angular.element(document).ready(function() {
        initNgModules(document);
  });
})();
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {Provider} from 'react-redux';
import {Router, IndexRoute, Route, browserHistory} from 'react-router';
import App from '../components/App';
import About from '../components/About';
import Playlists from './Playlists';
import Home from './Home';
import jwtDecode from 'jwt-decode';
import {AFTER_CHOOSE_AUTH_NAME, BEFORE_CHOOSE_NAME} from '../constants/chooseName';
import * as Actions from '../actions/index';

class Root extends Component {
  componentDidMount() {
    const actions = bindActionCreators(Actions, this.props.store.dispatch);

    socket.on('chat message', (msg) => actions.addMessage(msg));
    socket.on('update messages', (msgs) => actions.updateMessages(msgs));
    socket.on('update userlist', (users) => actions.updateUserList(users));
    socket.on('update playlists', (playlists) => actions.setPlaylists(playlists || {}));
    socket.on('next video', (video) => {
      const {videoId, host, start} = video;
      actions.startNextVideo(videoId, host, start);
    });
    socket.on('error token', () => {
      localStorage.removeItem('token');
      actions.setChooseName(BEFORE_CHOOSE_NAME);
      actions.setUsername('');
    });

    const token = localStorage.getItem('token');
    if (token) {
      const decoded = jwtDecode(token);
      actions.setChooseName(AFTER_CHOOSE_AUTH_NAME);
      actions.setUsername(decoded.username);
      socket.emit('add user', {name: decoded.username, token});
    }

    socket.emit('initial load');
  }

  render() {
    return (
      <Provider store={this.props.store}>
        <Router history={browserHistory}>
          <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="about" component={About} />
            <Route path="playlists" component={Playlists} />
          </Route>
        </Router>
      </Provider>
    );
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired
};

export default Root;
<commit_msg>Add Welcome Message<commit_after>import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {Provider} from 'react-redux';
import {Router, IndexRoute, Route, browserHistory} from 'react-router';
import App from '../components/App';
import About from '../components/About';
import Playlists from './Playlists';
import Home from './Home';
import jwtDecode from 'jwt-decode';
import {AFTER_CHOOSE_AUTH_NAME, BEFORE_CHOOSE_NAME} from '../constants/chooseName';
import * as Actions from '../actions/index';

class Root extends Component {
  componentDidMount() {
    const actions = bindActionCreators(Actions, this.props.store.dispatch);

    socket.on('chat message', (msg) => actions.addMessage(msg));
    socket.on('update messages', (msgs) => {
      actions.updateMessages(msgs);
      actions.addMessage({
        text: `

Welcome to gryph!

A video sharing chat application. (Plug.dj clone)

              Update: Playlists are added! - CreaturePhil

        `,
        html: true
      });
    });
    socket.on('update userlist', (users) => actions.updateUserList(users));
    socket.on('update playlists', (playlists) => actions.setPlaylists(playlists || {}));
    socket.on('next video', (video) => {
      const {videoId, host, start} = video;
      actions.startNextVideo(videoId, host, start);
    });
    socket.on('error token', () => {
      localStorage.removeItem('token');
      actions.setChooseName(BEFORE_CHOOSE_NAME);
      actions.setUsername('');
    });

    const token = localStorage.getItem('token');
    if (token) {
      const decoded = jwtDecode(token);
      actions.setChooseName(AFTER_CHOOSE_AUTH_NAME);
      actions.setUsername(decoded.username);
      socket.emit('add user', {name: decoded.username, token});
    }

    socket.emit('initial load');
  }

  render() {
    return (
      <Provider store={this.props.store}>
        <Router history={browserHistory}>
          <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="about" component={About} />
            <Route path="playlists" component={Playlists} />
          </Route>
        </Router>
      </Provider>
    );
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired
};

export default Root;
<|endoftext|>


<commit_before>import Widget from "./base_widget.js";

export default class OnboardingWidget extends Widget {
	constructor(opts) {
		super(opts);
		window.onb = this;
	}

	refresh() { }

	customize() { }

	make_body() {
		this.steps.forEach(step => {
			this.add_step(step);
		})
	}

	add_step(step) {
		let $step = $(`

				${step.label}

`)

		$step.appendTo(this.body)
		return $step
	}

	set_body() {
		this.widget.addClass('onboarding-widget-box')
		this.make_body();
	}

	set_title() {
		super.set_title();
		let subtitle = $(`<div class="widget-subtitle">${this.subtitle}</div>`)
		subtitle.appendTo(this.head);
	}

	setup_events() { }

	setup_customize_actions() { }

	set_actions() { }
}<commit_msg>chore: cleanup<commit_after>import Widget from "./base_widget.js";

export default class OnboardingWidget extends Widget {
	constructor(opts) {
		super(opts);
	}

	refresh() { }

	customize() { }

	make_body() {
		this.steps.forEach(step => {
			this.add_step(step);
		})
	}

	add_step(step) {
		let $step = $(`

				${step.label}

`)

		$step.appendTo(this.body)
		return $step
	}

	set_body() {
		this.widget.addClass('onboarding-widget-box')
		this.make_body();
	}

	set_title() {
		super.set_title();
		let subtitle = $(`<div class="widget-subtitle">${this.subtitle}</div>`)
		subtitle.appendTo(this.head);
	}

	setup_events() { }

	setup_customize_actions() { }

	set_actions() { }
}<|endoftext|>