<commit_before>import { get, computed } from '@ember/object';
import { A, isArray } from '@ember/array';
import Component from '@ember/component';
import InputDefaultsMixin from "ember-form-builder/mixins/input-defaults";
import { reads } from '@ember/object/computed';
import ObjectProxy from '@ember/object/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
import { next, cancel } from '@ember/runloop';
import { resolve } from 'rsvp';

export default Component.extend(InputDefaultsMixin, {
  tagName: "select",
  attributeBindings: ["isMultiple:multiple", "name"],
  collection: null,
  optionValuePath: "content",
  optionStringValuePath: "value.id",
  optionLabelPath: "content.name",
  modelValue: null,
  optionComponentName: "inputs/select-option",

  collectionPromise: computed('collection', function() {
    return ObjectProxy.extend(PromiseProxyMixin).create({
      promise: resolve(this.get('collection'))
    });
  }),

  resolvedCollection: reads('collectionPromise.content'),

  didInsertElement: function() {
    this._super(...arguments);
    // set default value in model
    this.get('collectionPromise').then(
      () => this.nextRun = next(this, this.change)
    );
  },

  willDestroyElement() {
    this._super(...arguments);
    cancel(this.nextRun);
  },

  change: function() {
    let selected = Array.prototype.slice.call(this.element.querySelectorAll('option:checked'));
    this._setSelection(selected.map((el) => el.index));
  },

  _setSelection: function(indicies) {
    var selection = A(this.get("resolvedCollection")).objectsAt(indicies);
    var valuePath = this.get("optionValuePath");
    var newValues = A(selection.map(function(item) {
      if (typeof item === "string" || valuePath === "content") {
        return item;
      } else {
        return get(item, valuePath.replace(/^content\./, ""));
      }
    }));

    if (isArray(this.get("value"))) {
      A(this.get("value")).replace(0, this.get("value.length"), newValues);
    } else {
      this.set("value", newValues.get("firstObject"));
    }
  },

  isMultiple: computed('modelValue', function() {
    return isArray(this.get('modelValue'));
  })
});
<commit_msg>collection input - always wait for promise<commit_after>import { get, computed } from '@ember/object';
import { A, isArray } from '@ember/array';
import Component from '@ember/component';
import InputDefaultsMixin from "ember-form-builder/mixins/input-defaults";
import { reads } from '@ember/object/computed';
import ObjectProxy from '@ember/object/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
import { next, cancel } from '@ember/runloop';
import { resolve } from 'rsvp';

export default Component.extend(InputDefaultsMixin, {
  tagName: "select",
  attributeBindings: ["isMultiple:multiple", "name"],
  collection: null,
  optionValuePath: "content",
  optionStringValuePath: "value.id",
  optionLabelPath: "content.name",
  modelValue: null,
  optionComponentName: "inputs/select-option",

  collectionPromise: computed('collection', function() {
    return ObjectProxy.extend(PromiseProxyMixin).create({
      promise: resolve(this.get('collection'))
    });
  }),

  resolvedCollection: reads('collectionPromise.content'),

  didInsertElement: function() {
    this._super(...arguments);
    // set default value in model
    this.nextRun = next(this, this.change);
  },

  willDestroyElement() {
    this._super(...arguments);
    cancel(this.nextRun);
  },

  change: function() {
    let selected = Array.prototype.slice.call(this.element.querySelectorAll('option:checked'));
    this._setSelection(selected.map((el) => el.index));
  },

  _setSelection: function(indicies) {
    this.get('collectionPromise').then((collection) => {
      var selection = A(collection).objectsAt(indicies);
      var valuePath = this.get("optionValuePath");
      var newValues = A(selection.map(function(item) {
        if (typeof item === "string" || valuePath === "content") {
          return item;
        } else if (item) {
          return get(item, valuePath.replace(/^content\./, ""));
        } else {
          return item;
        }
      }));

      if (isArray(this.get("value"))) {
        A(this.get("value")).replace(0, this.get("value.length"), newValues);
      } else {
        this.set("value", newValues.get("firstObject"));
      }
    });
  },

  isMultiple: computed('modelValue', function() {
    return isArray(this.get('modelValue'));
  })
});
<|endoftext|>


<commit_before>
'use strict';

describe('Search View', function() {

  var page, filterKey;

  beforeEach(function() {
    browser.get('/');
    page = require('./search.po');
    filterKey = 'ocean'; // should filter results down to two pages
  });

  it('elasticsearch should be up and running', function() {
    httpGet('http://localhost:9200').then(function(result) {
      expect(result.statusCode).toBe(200);
    });
  });

  it('should default to list view', function() {
    browser.getLocationAbsUrl().then(function(result) {
      expect(result).toBe('/list');
    });
  });

  it('should not have first accordion visible initially', function() {
    expect(page.firstAccordionCollapseDiv.isDisplayed()).toBe(false);
    expect(page.firstDetailsBtn.isDisplayed()).toBe(false);
  });

  it('should hide thumbnails on default', function() {
    page.firstAccordionLink.click().then(function() {
      expect(hasClass(page.firstAccordionThumbnail, 'ng-hide')).toBe(true);
    });
  });

  it('should open accordion and make appropriate elements visible', function() {
    page.firstAccordionLink.click();

    waitsFor(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    runs(function() {
      expect(page.firstDetailsBtn.isDisplayed()).toBe(true);
      expect(page.firstAccordionCollapseDiv.isDisplayed()).toBe(true);
      expect(hasClass(page.firstAccordionCollapseDiv, 'in')).toBe(true);
    });

  });

  it('should show thumbnails on checkbox click', function() {
    page.imageCheckbox.click();
    page.firstAccordionLink.click();

    browser.wait(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    expect(hasClass(page.firstAccordionThumbnail, 'ng-hide')).toBe(false);
  });

  it('should open accordion and go to details view', function() {
    page.firstAccordionLink.click();

    browser.wait(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    page.firstDetailsBtn.click();

    waitsFor(function() {
      return element(by.buttonText('Back To List')).isDisplayed();
    }, 1000);

    runs(function() {
      expect(browser.getLocationAbsUrl()).toBe('/list/details');
    });
  });

  it('should return to list view from details page', function() {
    page.firstAccordionLink.click();

    browser.wait(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    page.firstDetailsBtn.click();

    browser.wait(function() {
      return element(by.buttonText('Back To List')).isDisplayed();
    }, 1000);

    element(by.buttonText('Back To List')).click();

    waitsFor(function() {
      return page.titleInput.isDisplayed();
    }, 1000);

    runs(function() {
      expect(browser.getLocationAbsUrl()).toBe('/list');
    });

  });

  it('should include pagination defaulting to 12', function() {
    expect(element.all(by.css('.pagination-sm li')).count()).toBe(12);
  });

  it('should include pagination with filtered data', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      waitsFor(function() {
        return element.all(by.css('.pagination-sm li')).count().then(function(value) {
          return value < 12;
        });
      }, 1000);

      // With the selected filter, two pages are expected, so there will be
      // four pagination elements total -- [Previous, 1, 2, Next]
      runs(function() {
        expect(element.all(by.css('.pagination-sm li')).count()).toBe(4);
      });
    });
  });

  it('ensure direct page links in pagination work as expected', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      expect(hasClass(page.pgOneElem, 'active')).toBe(true);
      expect(hasClass(page.pgTwoElem, 'active')).toBe(false);

      page.pgTwoLink.click().then(function() {
        expect(hasClass(page.pgOneElem, 'active')).toBe(false);
        expect(hasClass(page.pgTwoElem, 'active')).toBe(true);
      });

      page.pgOneLink.click().then(function() {
        expect(hasClass(page.pgOneElem, 'active')).toBe(true);
        expect(hasClass(page.pgTwoElem, 'active')).toBe(false);
      });

    });
  });

  it('ensure next button in pagination is enabled and disabled accordingly', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      expect(hasClass(page.nextElem, 'disabled')).toBe(false);

      page.nextLink.click().then(function() {
        expect(hasClass(page.nextElem, 'disabled')).toBe(true);
      });

    });
  });

  it('ensure previous button in pagination is disabled and enabled accordingly', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      expect(hasClass(page.prevElem, 'disabled')).toBe(true);

      page.nextLink.click().then(function() {
        expect(hasClass(page.prevElem, 'disabled')).toBe(false);
      });

    });
  });

  // Helper functions
  var hasClass = function (element, cls) {
    return element.getAttribute('class').then(function (classes) {
      return classes.split(' ').indexOf(cls) !== -1;
    });
  };

  var httpGet = function (siteUrl) {
    var http = require('http');
    var defer = protractor.promise.defer();

    http.get(siteUrl, function(response) {
      var bodyString = '';

      response.setEncoding('utf8');

      response.on("data", function(chunk) {
        bodyString += chunk;
      });

      response.on('end', function() {
        defer.fulfill({
          statusCode: response.statusCode,
          bodyString: bodyString
        });
      });

    }).on('error', function(e) {
      defer.reject("Got http.get error when connecting to " + siteUrl + ": " + e.message);
    });

    return defer.promise;
  }

});<commit_msg>Removing waitsFor/runs from e2e test.<commit_after>
'use strict';

describe('Search View', function() {

  var page, filterKey;

  beforeEach(function() {
    browser.get('/');
    page = require('./search.po');
    filterKey = 'ocean'; // should filter results down to two pages
  });

  it('elasticsearch should be up and running', function() {
    httpGet('http://localhost:9200').then(function(result) {
      expect(result.statusCode).toBe(200);
    });
  });

  it('should default to list view', function() {
    browser.getLocationAbsUrl().then(function(result) {
      expect(result).toBe('/list');
    });
  });

  it('should not have first accordion visible initially', function() {
    expect(page.firstAccordionCollapseDiv.isDisplayed()).toBe(false);
    expect(page.firstDetailsBtn.isDisplayed()).toBe(false);
  });

  it('should hide thumbnails on default', function() {
    page.firstAccordionLink.click().then(function() {
      expect(hasClass(page.firstAccordionThumbnail, 'ng-hide')).toBe(true);
    });
  });

  it('should include pagination defaulting to 12', function() {
    expect(element.all(by.css('.pagination-sm li')).count()).toBe(12);
  });

  it('should open accordion and make appropriate elements visible', function() {
    page.firstAccordionLink.click().then(function() {
      browser.wait(function() {
        return page.firstDetailsBtn.isDisplayed();
      }, 1000);

      expect(page.firstDetailsBtn.isDisplayed()).toBe(true);
      expect(page.firstAccordionCollapseDiv.isDisplayed()).toBe(true);
      expect(hasClass(page.firstAccordionCollapseDiv, 'in')).toBe(true);
    });
  });

  it('should show thumbnails on checkbox click', function() {
    page.imageCheckbox.click();
    page.firstAccordionLink.click();

    browser.wait(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    expect(hasClass(page.firstAccordionThumbnail, 'ng-hide')).toBe(false);
  });

  it('should open accordion and go to details view', function() {
    page.firstAccordionLink.click();

    browser.wait(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    page.firstDetailsBtn.click();

    browser.wait(function() {
      return element(by.buttonText('Back To List')).isDisplayed();
    }, 1000);

    expect(browser.getLocationAbsUrl()).toBe('/list/details');
  });

  it('should return to list view from details page', function() {
    page.firstAccordionLink.click();

    browser.wait(function() {
      return page.firstDetailsBtn.isDisplayed();
    }, 1000);

    page.firstDetailsBtn.click();

    browser.wait(function() {
      return element(by.buttonText('Back To List')).isDisplayed();
    }, 1000);

    element(by.buttonText('Back To List')).click();

    browser.wait(function() {
      return page.titleInput.isDisplayed();
    }, 1000);

    expect(browser.getLocationAbsUrl()).toBe('/list');
  });

  it('should include pagination with filtered data', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      browser.wait(function() {
        return element.all(by.css('.pagination-sm li')).count().then(function(value) {
          return value < 12;
        });
      }, 1000);

      // With the selected filter, two pages are expected, so there will be
      // four pagination elements total -- [Previous, 1, 2, Next]
      expect(element.all(by.css('.pagination-sm li')).count()).toBe(4);
    });
  });

  it('ensure direct page links in pagination work as expected', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      expect(hasClass(page.pgOneElem, 'active')).toBe(true);
      expect(hasClass(page.pgTwoElem, 'active')).toBe(false);

      page.pgTwoLink.click().then(function() {
        expect(hasClass(page.pgOneElem, 'active')).toBe(false);
        expect(hasClass(page.pgTwoElem, 'active')).toBe(true);
      });

      page.pgOneLink.click().then(function() {
        expect(hasClass(page.pgOneElem, 'active')).toBe(true);
        expect(hasClass(page.pgTwoElem, 'active')).toBe(false);
      });

    });
  });

  it('ensure next button in pagination is enabled and disabled accordingly', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      expect(hasClass(page.nextElem, 'disabled')).toBe(false);

      page.nextLink.click().then(function() {
        expect(hasClass(page.nextElem, 'disabled')).toBe(true);
      });

    });
  });

  it('ensure previous button in pagination is disabled and enabled accordingly', function() {
    page.titleInput.sendKeys(filterKey).then(function() {

      expect(hasClass(page.prevElem, 'disabled')).toBe(true);

      page.nextLink.click().then(function() {
        expect(hasClass(page.prevElem, 'disabled')).toBe(false);
      });

    });
  });

  // Helper functions
  var hasClass = function (element, cls) {
    return element.getAttribute('class').then(function (classes) {
      return classes.split(' ').indexOf(cls) !== -1;
    });
  };

  var httpGet = function (siteUrl) {
    var http = require('http');
    var defer = protractor.promise.defer();

    http.get(siteUrl, function(response) {
      var bodyString = '';

      response.setEncoding('utf8');

      response.on("data", function(chunk) {
        bodyString += chunk;
      });

      response.on('end', function() {
        defer.fulfill({
          statusCode: response.statusCode,
          bodyString: bodyString
        });
      });

    }).on('error', function(e) {
      defer.reject("Got http.get error when connecting to " + siteUrl + ": " + e.message);
    });

    return defer.promise;
  }

});<|endoftext|>


<commit_before>const Crypto = require('crypto');
const OS = require('os');
const SteamID = require('steamid');

const EOSType = require('../enums/EOSType.js');
const EResult = require('../enums/EResult.js');

const FRIEND_CODE_REPLACEMENTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 't', 'v', 'w'];

/**
 * If the input isn't already a SteamID object, converts it into one and returns it
 * @param input
 * @returns {SteamID}
 */
exports.steamID = function(input) {
	if (!input) {
		return;
	}

	if (typeof input !== 'string') {
		if (input instanceof SteamID) {
			return input; // Looks like it's already a SteamID
		}

		input = input.toString();
	}

	return new SteamID(input);
};

/**
 * @param {SteamID} steamID
 * @returns {string}
 */
exports.createFriendCode = function(steamID) {
	let acctIdHex = steamID.accountid.toString(16);
	let friendCode = '';

	for (let i = 0; i < acctIdHex.length; i++) {
		let char = parseInt(acctIdHex[i], 16);
		friendCode += FRIEND_CODE_REPLACEMENTS[char];
	}

	let dashPos = Math.floor(friendCode.length / 2);
	return friendCode.substring(0, dashPos) + '-' + friendCode.substring(dashPos);
};

/**
 * @param {string} friendCode
 * @returns {SteamID}
 */
exports.parseFriendCode = function(friendCode) {
	friendCode = friendCode.replace(/-/g, '');
	let acctIdHex = '';

	for (let i = 0; i < friendCode.length; i++) {
		let char = friendCode[i];
		acctIdHex += FRIEND_CODE_REPLACEMENTS.indexOf(char).toString(16);
	}

	return new SteamID(`[U:1:${parseInt(acctIdHex, 16)}]`);
};

/**
 * Get an machine ID for internal use (not sent to Steam)
 * @returns {string}
 */
exports.getInternalMachineID = function() {
	// Build our machine ID off of hostname, memory, and CPU data
	let cpus = OS.cpus().map(function(cpu) {
		return cpu.model;
	});

	cpus.sort();

	let id = OS.hostname() + OS.totalmem() + cpus.join('');
	let hash = Crypto.createHash('md5');
	hash.update(id);
	return hash.digest('hex');
};

/**
 * Get an Error object for a particular EResult
 * @param {int|EResult|object} eresult - Either an EResult value, or an object that contains an eresult property. If undefined or is an object without an eresult property, will assume "Fail".
 * @returns {null|Error}
 */
exports.eresultError = function(eresult) {
	if (typeof eresult == 'undefined') {
		eresult = EResult.Fail;
	} else if (typeof eresult == 'object') {
		eresult = eresult.eresult || EResult.Fail;
	}

	if (eresult == EResult.OK) {
		// no error
		return null;
	}

	let err = new Error(EResult[eresult] || ("Error " + eresult));
	err.eresult = eresult;
	return err;
};

/**
 * @return {EOSType}
 */
exports.getOsType = function() {
	switch (OS.platform()) {
		case 'darwin':
			let match = OS.release().match(/Darwin Kernel Version (\d+)\.(\d+)\.(\d+)/);
			if (!match) {
				return EOSType.MacOSUnknown;
			}

			if (match[1] == 10 && match[2] == 0 && match[3] == 0) {
				return EOSType.MacOS106; // Snow Leopard
			}

			if (match[1] == 11 && match[2] == 3) {
				return EOSType.MacOS107; // Lion
			}

			if (match[1] == 12 && match[2] == 2) {
				return EOSType.MacOS108; // Mountain Lion
			}

			if (match[1] == 13 && match[2] == 0) {
				return EOSType.MacOS109; // Mavericks
			}

			if (match[1] == 14 && match[2] == 0) {
				return EOSType.MacOS1010; // Yosemite
			}

			return EOSType.MacOSUnknown;

		case 'win32':
			// http://prajwaldesai.com/windows-operating-system-version-numbers/
			let verParts = OS.release().split('.');
			if (verParts.length < 3) {
				return EOSType.WinUnknown;
			}

			if (verParts[0] == 3) {
				return EOSType.Win311; // yeah right
			}

			if (verParts[0] == 4 && parseInt(verParts[1], 10) <= 3) {
				return EOSType.Win95;
			}

			if (verParts[0] == 4 && verParts[1] == 10) {
				return EOSType.Win98;
			}

			if (verParts[0] == 4 && verParts[1] == 90) {
				return EOSType.WinME;
			}

			if (verParts[0] == 5 && verParts[1] == "00" && verParts[2] == 1515) {
				return EOSType.WinNT;
			}

			if (verParts[0] == 5 && parseInt(verParts[1], 10) < 1) {
				return EOSType.Win200;
			}

			if (verParts[0] == 5 && verParts[1] == 1) {
				return EOSType.WinXP;
			}

			if (verParts[0] == 5 && verParts[1] == 2) {
				return EOSType.Win2003;
			}

			if (verParts[0] == 6 && verParts[1] == 0 && verParts[2] == 6001) {
				return EOSType.Win2008;
			}

			if (verParts[0] == 6 && verParts[1] == 0) {
				return EOSType.WinVista;
			}

			if (verParts[0] == 6 && verParts[1] == 1) {
				return EOSType.Win7;
			}

			if (verParts[0] == 6 && verParts[1] == 2) {
				return EOSType.Win8;
			}

			if (verParts[0] == 6 && verParts[1] == 3) {
				return EOSType.Win81;
			}

			if (verParts[0] == 10) {
				return EOSType.Win10;
			}

			return EOSType.WinUnknown;

		default:
			return EOSType.LinuxUnknown;
	}
};

exports.fixVdfArray = function(arr) {
	arr.length = Object.keys(arr).length;
	return Array.prototype.slice.call(arr);
};

exports.onceTimeout = function(timeoutMilliseconds, emitter, event, handler) {
	let timeout;
	let internalHandler = function() {
		clearTimeout(timeout);
		handler.apply(emitter, [null].concat(Array.prototype.slice.call(arguments)));
	};

	timeout = setTimeout(() => {
		emitter.removeListener(event, internalHandler);
		handler.call(emitter, new Error('Request timed out'));
	}, timeoutMilliseconds);

	emitter.once(event, internalHandler);
};
<commit_msg>This is better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof<commit_after>const Crypto = require('crypto');
const OS = require('os');
const SteamID = require('steamid');

const EOSType = require('../enums/EOSType.js');
const EResult = require('../enums/EResult.js');

const FRIEND_CODE_REPLACEMENTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 't', 'v', 'w'];

/**
 * If the input isn't already a SteamID object, converts it into one and returns it
 * @param input
 * @returns {SteamID}
 */
exports.steamID = function(input) {
	if (!input) {
		return;
	}

	if (typeof input !== 'string') {
		let keys = Object.keys(input);
		if (keys.every(key => ['universe', 'type', 'instance', 'accountid'].includes(key))) {
			return input; // Looks like it's already a SteamID
		}

		input = input.toString();
	}

	return new SteamID(input);
};

/**
 * @param {SteamID} steamID
 * @returns {string}
 */
exports.createFriendCode = function(steamID) {
	let acctIdHex = steamID.accountid.toString(16);
	let friendCode = '';

	for (let i = 0; i < acctIdHex.length; i++) {
		let char = parseInt(acctIdHex[i], 16);
		friendCode += FRIEND_CODE_REPLACEMENTS[char];
	}

	let dashPos = Math.floor(friendCode.length / 2);
	return friendCode.substring(0, dashPos) + '-' + friendCode.substring(dashPos);
};

/**
 * @param {string} friendCode
 * @returns {SteamID}
 */
exports.parseFriendCode = function(friendCode) {
	friendCode = friendCode.replace(/-/g, '');
	let acctIdHex = '';

	for (let i = 0; i < friendCode.length; i++) {
		let char = friendCode[i];
		acctIdHex += FRIEND_CODE_REPLACEMENTS.indexOf(char).toString(16);
	}

	return new SteamID(`[U:1:${parseInt(acctIdHex, 16)}]`);
};

/**
 * Get an machine ID for internal use (not sent to Steam)
 * @returns {string}
 */
exports.getInternalMachineID = function() {
	// Build our machine ID off of hostname, memory, and CPU data
	let cpus = OS.cpus().map(function(cpu) {
		return cpu.model;
	});

	cpus.sort();

	let id = OS.hostname() + OS.totalmem() + cpus.join('');
	let hash = Crypto.createHash('md5');
	hash.update(id);
	return hash.digest('hex');
};

/**
 * Get an Error object for a particular EResult
 * @param {int|EResult|object} eresult - Either an EResult value, or an object that contains an eresult property. If undefined or is an object without an eresult property, will assume "Fail".
 * @returns {null|Error}
 */
exports.eresultError = function(eresult) {
	if (typeof eresult == 'undefined') {
		eresult = EResult.Fail;
	} else if (typeof eresult == 'object') {
		eresult = eresult.eresult || EResult.Fail;
	}

	if (eresult == EResult.OK) {
		// no error
		return null;
	}

	let err = new Error(EResult[eresult] || ("Error " + eresult));
	err.eresult = eresult;
	return err;
};

/**
 * @return {EOSType}
 */
exports.getOsType = function() {
	switch (OS.platform()) {
		case 'darwin':
			let match = OS.release().match(/Darwin Kernel Version (\d+)\.(\d+)\.(\d+)/);
			if (!match) {
				return EOSType.MacOSUnknown;
			}

			if (match[1] == 10 && match[2] == 0 && match[3] == 0) {
				return EOSType.MacOS106; // Snow Leopard
			}

			if (match[1] == 11 && match[2] == 3) {
				return EOSType.MacOS107; // Lion
			}

			if (match[1] == 12 && match[2] == 2) {
				return EOSType.MacOS108; // Mountain Lion
			}

			if (match[1] == 13 && match[2] == 0) {
				return EOSType.MacOS109; // Mavericks
			}

			if (match[1] == 14 && match[2] == 0) {
				return EOSType.MacOS1010; // Yosemite
			}

			return EOSType.MacOSUnknown;

		case 'win32':
			// http://prajwaldesai.com/windows-operating-system-version-numbers/
			let verParts = OS.release().split('.');
			if (verParts.length < 3) {
				return EOSType.WinUnknown;
			}

			if (verParts[0] == 3) {
				return EOSType.Win311; // yeah right
			}

			if (verParts[0] == 4 && parseInt(verParts[1], 10) <= 3) {
				return EOSType.Win95;
			}

			if (verParts[0] == 4 && verParts[1] == 10) {
				return EOSType.Win98;
			}

			if (verParts[0] == 4 && verParts[1] == 90) {
				return EOSType.WinME;
			}

			if (verParts[0] == 5 && verParts[1] == "00" && verParts[2] == 1515) {
				return EOSType.WinNT;
			}

			if (verParts[0] == 5 && parseInt(verParts[1], 10) < 1) {
				return EOSType.Win200;
			}

			if (verParts[0] == 5 && verParts[1] == 1) {
				return EOSType.WinXP;
			}

			if (verParts[0] == 5 && verParts[1] == 2) {
				return EOSType.Win2003;
			}

			if (verParts[0] == 6 && verParts[1] == 0 && verParts[2] == 6001) {
				return EOSType.Win2008;
			}

			if (verParts[0] == 6 && verParts[1] == 0) {
				return EOSType.WinVista;
			}

			if (verParts[0] == 6 && verParts[1] == 1) {
				return EOSType.Win7;
			}

			if (verParts[0] == 6 && verParts[1] == 2) {
				return EOSType.Win8;
			}

			if (verParts[0] == 6 && verParts[1] == 3) {
				return EOSType.Win81;
			}

			if (verParts[0] == 10) {
				return EOSType.Win10;
			}

			return EOSType.WinUnknown;

		default:
			return EOSType.LinuxUnknown;
	}
};

exports.fixVdfArray = function(arr) {
	arr.length = Object.keys(arr).length;
	return Array.prototype.slice.call(arr);
};

exports.onceTimeout = function(timeoutMilliseconds, emitter, event, handler) {
	let timeout;
	let internalHandler = function() {
		clearTimeout(timeout);
		handler.apply(emitter, [null].concat(Array.prototype.slice.call(arguments)));
	};

	timeout = setTimeout(() => {
		emitter.removeListener(event, internalHandler);
		handler.call(emitter, new Error('Request timed out'));
	}, timeoutMilliseconds);

	emitter.once(event, internalHandler);
};
<|endoftext|>


<commit_before>"use strict";

(function()
 {
     var request = require('request');

     /*~
      * A single one action.
      */
     class Action
     {
         constructor(url, data, msg)
         {
             this.url  = url;
             this.data = data;
             this.msg  = msg;
         }

         display()
         {
             console.log(this.msg);
         }

         execute(env, verbose, error, success)
         {
             console.warn(green('post') + '  ' + this.msg);
             var url = 'http://' + env.backstage.host + ':8002/manage/v2' + this.url;
             if ( verbose ) {
                 console.warn('[' + bold('verbose') + '] POST to ' + url);
                 console.warn('[' + bold('verbose') + '] Body:');
                 console.warn(this.data);
             }
             request.post(
                 {
                     url:  url,
                     json: this.data,
                     auth: {
                         user: env.backstage.admin.user,
                         pass: env.backstage.admin.password,
                         sendImmediately: false
                     }
                 },
                 (err, http, body) => {
                     if ( err ) {
                         error('Error creating a database: ' + err);
                     }
                     else if ( http.statusCode !== 201 ) {
                         error('Entity not created: ' + body.errorResponse.message);
                     }
                     else {
                         success();
                     }
                 });
         }
     }

     /*~
      * A list of actions.
      */
     class ActionList
     {
         constructor(v)
         {
             this.verbose = v;
             this.todo    = [];
             this.done    = [];
             this.error   = null;
         }

         add(a)
         {
             this.todo.push(a);
         }

         execute(env)
         {
             if ( ! this.todo.length ) {
                 // nothing left to do
                 this.display();
             }
             else {
                 var action = this.todo.shift();
                 action.execute(env, this.verbose, msg => {
                     this.error = { action: action, message: msg };
                     // stop processing
                     this.display();
                 }, () => {
                     this.done.push(action);
                     // TODO: Keep the idea of an event log?
                     // events.push('Database created: ' + db.name);
                     this.execute(env);
                 });
             }
         }

         display()
         {
             if ( this.done.length ) {
                 console.log(green('Done') + ':');
                 this.done.forEach(a => a.display());
             }
             if ( this.error ) {
                 console.log(red('Error') + ': ' + this.error.message);
                 this.error.action.display();
             }
             if ( this.todo.length ) {
                 console.log(yellow('Not done') + ':');
                 this.todo.forEach(a => a.display());
             }
         }
     }

     /*~~~~~
      * Functions to turn a string into bold, green, yellow or red resp. (for
      * the interactive console).
      */

     function bold(s)
     {
         return '\u001b[1m' + s + '\u001b[22m'
     }

     function green(s)
     {
         return '\u001b[32m' + s + '\u001b[39m'
     }

     function yellow(s)
     {
         return '\u001b[33m' + s + '\u001b[39m'
     }

     function red(s)
     {
         return '\u001b[35m' + s + '\u001b[39m'
     }

     module.exports = {
         Action     : Action,
         ActionList : ActionList,
         red        : red
     };
 }
)();
<commit_msg>Remove old file.<commit_after><|endoftext|>


<commit_before>/*
---
description: Provides methods to reveal, dissolve, nix, and toggle using Fx.Reveal.
provides: [Delegator.FxReveal, Delegator.Reveal, Delegator.ToggleReveal, Delegator.Dissolve, Delegator.Nix]
requires: [Behavior/Delegator, More/Fx.Reveal]
script: Delegator.FxReveal.js
name: Delegator.FxReveal

...
*/
(function(){

	var triggers = {};

	['reveal', 'toggleReveal', 'dissolve', 'nix'].each(function(action){

		triggers[action] = {
			handler: function(event, link, api){
				var targets;
				if (api.get('target')){
					targets = new Elements([link.getElement(api.get('target'))]);
					if (!targets) api.fail('could not locate target element to ' + action, link);
				} else if (api.get('targets')){
					targets = link.getElements(api.get('targets'));
					if (!targets.length) api.fail('could not locate target elements to ' + action, link);
				} else {
					targets = new Elements([link]);
				}

				var fxOptions = api.get('fxOptions');
				if (fxOptions) targets.set('reveal', fxOptions);
				targets.get('reveal');
				if (action == 'toggleReveal') targets.get('reveal').invoke('toggle');
				else targets[action]();
				if (!api.getAs(Boolean, 'allowEvent')) event.preventDefault();
			}
		};

	});

	Delegator.register('click', triggers);

})();<commit_msg>not using the element setter for Fx.Reveal so that it doesn't reset the state of the class.<commit_after>/*
---
description: Provides methods to reveal, dissolve, nix, and toggle using Fx.Reveal.
provides: [Delegator.FxReveal, Delegator.Reveal, Delegator.ToggleReveal, Delegator.Dissolve, Delegator.Nix]
requires: [Behavior/Delegator, More/Fx.Reveal]
script: Delegator.FxReveal.js
name: Delegator.FxReveal

...
*/
(function(){

	var triggers = {};

	['reveal', 'toggleReveal', 'dissolve', 'nix'].each(function(action){

		triggers[action] = {
			handler: function(event, link, api){
				var targets;
				if (api.get('target')){
					targets = new Elements([link.getElement(api.get('target'))]);
					if (!targets) api.fail('could not locate target element to ' + action, link);
				} else if (api.get('targets')){
					targets = link.getElements(api.get('targets'));
					if (!targets.length) api.fail('could not locate target elements to ' + action, link);
				} else {
					targets = new Elements([link]);
				}

				var fxOptions = api.getAs(Object, 'fxOptions');
				if (fxOptions){
					targets.each(function(target){
						target.get('reveal').setOptions(fxOptions);
					});
				}
				if (action == 'toggleReveal') targets.get('reveal').invoke('toggle');
				else targets[action]();
				if (!api.getAs(Boolean, 'allowEvent')) event.preventDefault();
			}
		};

	});

	Delegator.register('click', triggers);

})();<|endoftext|>


<commit_before>/* @flow */
/**
 * renderString.js
 * Written by: Connor Taylor
 */
import mustache from '../../mustache';

import loadCytoConfig from '../../../configs/loadCytoConfig';
import generateTemplate from '../../../template/generateTemplate';
import types from '../../types';
import errors from '../../errors';

/**
 * Description of renderString
 *
 */
export default function renderString(str, args) {
  mustache.escape = (text) => text; // Don't escape html

  const renderPartial = async (partialString, context) => {
    const tokens = partialString.split(' ').filter((s) => s.trim());
    if (!tokens.length || tokens.length > 2) {
      errors.invalidPartial(partialString, '');
    } else if (tokens.length === 1) {
      if (context.id) {
        tokens.push(context.id);
      } else {
        errors.invalidPartial(partialString);
      }
    }

    const [templateId, id] = tokens;
    const cytoConfig = loadCytoConfig(templateId);

    if (!types.isPartial(cytoConfig)) {
      errors.invalidPartial(partialString, `${templateId} is not a partial!`);
    }

    const generatedPartial = await generateTemplate({
      templateId,
      args: { ...context, id },
      outputRoot: '',
    });

    return Object.keys(generatedPartial).reduce((s, k) => {
      return `${s}${generatedPartial[k]}`;
    }, '');
  };

  return mustache.render(str, args, renderPartial);
}
<commit_msg>pass author arg to partial templates<commit_after>/* @flow */
/**
 * renderString.js
 * Written by: Connor Taylor
 */
import mustache from '../../mustache';

import loadCytoConfig from '../../../configs/loadCytoConfig';
import generateTemplate from '../../../template/generateTemplate';
import types from '../../types';
import errors from '../../errors';

/**
 * Description of renderString
 *
 */
export default function renderString(str, args) {
  mustache.escape = (text) => text; // Don't escape html

  const renderPartial = async (partialString, context) => {
    const tokens = partialString.split(' ').filter((s) => s.trim());
    if (!tokens.length || tokens.length > 2) {
      errors.invalidPartial(partialString, '');
    } else if (tokens.length === 1) {
      if (context.id) {
        tokens.push(context.id);
      } else {
        errors.invalidPartial(partialString);
      }
    }

    const [templateId, id] = tokens;
    const cytoConfig = loadCytoConfig(templateId);

    if (!types.isPartial(cytoConfig)) {
      errors.invalidPartial(partialString, `${templateId} is not a partial!`);
    }

    const generatedPartial = await generateTemplate({
      templateId,
      args: { ...context, id, author: args.author },
      outputRoot: '',
    });

    return Object.keys(generatedPartial).reduce((s, k) => {
      return `${s}${generatedPartial[k]}`;
    }, '');
  };

  return mustache.render(str, args, renderPartial);
}
<|endoftext|>


<commit_before>window.InfernoShoutMod = {};

require.config({
	baseUrl : 'http://nikkii.us/sbmod/dev/',
	paths: {
		jquery : 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
		minivents : 'lib/minivents',
		htmlparser : 'lib/htmlparser',
		soupselect : 'lib/soupselect'
	}
});

function loadCss(url) {
	var link = document.createElement("link");
	link.type = "text/css";
	link.rel = "stylesheet";
	link.href = url;
	document.getElementsByTagName("head")[0].appendChild(link);
}

var deps = [
	'jquery',
	'modules/mod',
	'modules/commands',
	'modules/tabs'
];

var plugins = [
	'plugins/settings',
	'plugins/groupchanger',
	'plugins/quoting',
	'plugins/youtube',
	'plugins/noshadow',
	'plugins/userhistory'
];

require(deps, function($, InfernoShoutMod) {
	var mod = new InfernoShoutMod();
	mod.init();

	console.log('[InfernoShoutMod] Initial loading done.');

	loadCss('//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css');

	console.log('[InfernoShoutMod] Initializing modules');

	var args = Array.apply([], arguments);
	args = args.slice(2);

	var i;
	for (i = 0; i < args.length; i++) {
		if (typeof args[i] !== 'undefined' && typeof args[i]['init'] !== 'undefined') {
			args[i].init(mod);
		}
	}

	require(plugins, function() {
		var i;
		mod.plugins = [];
		for(i = 0; i < arguments.length; i++) {
			arguments[i].init(mod);
			mod.plugins.push(plugins[i]);
		}
		console.log('[InfernoShoutMod] ' + arguments.length + ' plugins loaded.');
	});
});<commit_msg>Revert url to non-dev<commit_after>window.InfernoShoutMod = {};

require.config({
	baseUrl : 'http://nikkii.us/sbmod/',
	paths: {
		jquery : 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
		minivents : 'lib/minivents',
		htmlparser : 'lib/htmlparser',
		soupselect : 'lib/soupselect'
	}
});

function loadCss(url) {
	var link = document.createElement("link");
	link.type = "text/css";
	link.rel = "stylesheet";
	link.href = url;
	document.getElementsByTagName("head")[0].appendChild(link);
}

var deps = [
	'jquery',
	'modules/mod',
	'modules/commands',
	'modules/tabs'
];

var plugins = [
	'plugins/settings',
	'plugins/groupchanger',
	'plugins/quoting',
	'plugins/youtube',
	'plugins/noshadow',
	'plugins/userhistory'
];

require(deps, function($, InfernoShoutMod) {
	var mod = new InfernoShoutMod();
	mod.init();

	console.log('[InfernoShoutMod] Initial loading done.');

	loadCss('//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css');

	console.log('[InfernoShoutMod] Initializing modules');

	var args = Array.apply([], arguments);
	args = args.slice(2);

	var i;
	for (i = 0; i < args.length; i++) {
		if (typeof args[i] !== 'undefined' && typeof args[i]['init'] !== 'undefined') {
			args[i].init(mod);
		}
	}

	require(plugins, function() {
		var i;
		mod.plugins = [];
		for(i = 0; i < arguments.length; i++) {
			arguments[i].init(mod);
			mod.plugins.push(plugins[i]);
		}
		console.log('[InfernoShoutMod] ' + arguments.length + ' plugins loaded.');
	});
});<|endoftext|>


<commit_before>var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./../specUtils').waitForOncoprint;
var setOncoprintMutationsMenuOpen = require('./../specUtils').setOncoprintMutationsMenuOpen;
var goToUrlAndSetLocalStorage = require('./../specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./../specUtils').waitForNetworkQuiet;
var sessionServiceIsEnabled = require('./../specUtils').sessionServiceIsEnabled;
var assertScreenShotMatch = require('../../lib/testUtils').assertScreenShotMatch;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");

function waitForAndCheckPlotsTab() {
    browser.waitForVisible('div[data-test="PlotsTabPlotDiv"]', 10000);
    var res = browser.checkElement('div[data-test="PlotsTabEntireDiv"]', { hide:['.qtip'] });
    assertScreenShotMatch(res);
}

function runResultsTestSuite(prefix){

    it(`${prefix} render the oncoprint`, function(){
        waitForOncoprint(10000);
        var res = browser.checkElement('.oncoprintContainer', { hide:['.oncoprint__controls']}); // just hide the controls bc for some reason they keep showing up transparent in this test only
        assertScreenShotMatch(res);
    });

    // can't get it to pass reliably
    it.skip(`${prefix} igv_tab tab`, function(){
        browser.click("a.tabAnchor_cnSegments");
        browser.waitForExist('#cnSegmentsFrame', 20000);
        var res = browser.checkElement('.cnSegmentsMSKTabs',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} cancer type summary`, function(){
        browser.click("a.tabAnchor_cancerTypesSummary");
        browser.waitForVisible('[data-test="cancerTypeSummaryChart"]',10000);
        browser.waitForExist('[data-test="cancerTypeSummaryWrapper"]', 5000);
        var res = browser.checkElement('[data-test="cancerTypeSummaryWrapper"]', { hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} mutex tab`, function(){
        browser.click("a.tabAnchor_mutualExclusivity");
        var res = browser.checkElement('[data-test="mutualExclusivityTabDiv"]',{ hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} plots tab`, function(){
        browser.click("a.tabAnchor_plots");
        waitForAndCheckPlotsTab();
    });

    it.skip(`${prefix} mutation tab`, function(){
        browser.click("a.tabAnchor_mutations");
        browser.waitForVisible('.borderedChart svg',20000);
        var res = browser.checkElement('[data-test="mutationsTabDiv"]',{hide:['.qtip', '[data-test=view3DStructure]', '[data-test=GeneSummaryUniProt]'], viewportChangePause:4000}); // hide these things because the timing of data loading makes this test so flaky
        assertScreenShotMatch(res);
    });

    it(`${prefix} coexpression tab`, function(){
        browser.click("a.tabAnchor_coexpression");
        browser.waitForVisible('div[data-test="CoExpressionPlot"]',10000);
        var res = browser.checkElement('[data-test="coExpressionTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} enrichments tab`, function(){
        browser.click("a.tabAnchor_enrichments");
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.click('b=CDK14');
        browser.waitForExist('[data-test="enrichmentsTabDiv"]', 10000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} survival tab`, function(){
        browser.click("a.tabAnchor_survival");
        browser.waitForVisible('[data-test=SurvivalChart] svg',10000);
        var res = browser.checkElement('[data-test="survivalTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} network tab`, function(){
        // TODO: unskip this when bug is fixed

        browser.click("a.tabAnchor_network");

        browser.waitForExist('iframe#networkFrame', 10000);

        browser.frame('networkFrame', function(err, result) {
                if (err) console.log(err);
            });
        browser.waitForVisible('#cytoscapeweb canvas',60000);
        browser.execute(function(){
            $("<style>canvas { visibility: hidden} </style>").appendTo("body");
        });
        browser.frame(null);
        var res = browser.checkElement("#networkFrame",{hide:['.qtip','canvas'] });

        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} data_download tab`, function(){
        browser.click("a.tabAnchor_download");
        //  browser.pause(1000);
        browser.waitForExist("#text_area_gene_alteration_freq",20000);
        browser.waitUntil(function(){ return browser.getValue("#text_area_gene_alteration_freq").length > 0 },20000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
}

describe('result page screenshot tests', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/index.do?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit&show_samples=false&`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('no session')

});

describe('expression tab', function() {
    it("expression tab with complex oql", ()=>{
        goToUrlAndSetLocalStorage(`${CBIOPORTAL_URL}/results/expression?cancer_study_id=all&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=all&gene_list=TP53%3AMUT%3B&geneset_list=%20&tab_index=tab_visualize&Action=Submit&cancer_study_list=acc_tcga%2Cchol_tcga%2Cesca_tcga&show_samples=false`);
        browser.waitForExist(".borderedChart svg", 60000);
        var res = browser.checkElement('[data-test="expressionTabDiv"]');
        assertScreenShotMatch(res);
    });
});

describe("download tab screenshot tests", function() {
    it("download tab - msk_impact_2017 with ALK and SOS1 - SOS1 should be not sequenced", function() {
        var url = `${CBIOPORTAL_URL}/index.do?cancer_study_id=msk_impact_2017&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=msk_impact_2017_all&gene_list=ALK%2520SOS1&geneset_list=+&tab_index=tab_visualize&Action=Submit&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=msk_impact_2017_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=msk_impact_2017_cna`;
        goToUrlAndSetLocalStorage(url);
        browser.waitForExist("a.tabAnchor_download", 10000);
        browser.click("a.tabAnchor_download");
        browser.waitForExist('[data-test="dataDownloadGeneAlterationTable"] tr > td > svg', 20000);
        browser.waitForExist('[data-test="downloadTabDiv"]', 5000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe.skip('patient view page screenshot test', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/patient?studyId=lgg_ucsf_2014&caseId=P04`;
        goToUrlAndSetLocalStorage(url);
    });

    it('patient view lgg_ucsf_2014 P04', function() {
        // find oncokb image
        var oncokbIndicator = $('[data-test="oncogenic-icon-image"]');
        oncokbIndicator.waitForExist(30000);
        // find vaf plot
        var vafPlot = $('.vafPlot');
        vafPlot.waitForExist(30000);

        var res = browser.checkElement('#mainColumn', {hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe("enrichments tab screenshot tests", function() {
    before(function() {
        var url = `${CBIOPORTAL_URL}/results/enrichments?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit`;
        goToUrlAndSetLocalStorage(url);
    });
    it('enrichments tab coadread_tcga_pub mRNA profile', function(){
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.waitForVisible('a=mRNA', 10000);
        browser.click('a=mRNA');
        browser.waitForVisible('div[data-test="MRNAEnrichmentsTab"]',20000);
        browser.waitForVisible('b=MERTK', 10000);
        browser.click('b=MERTK');
        browser.waitForVisible('div[data-test="MiniBoxPlot"]', 20000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });
});

describe('result page tabs, loading from session id', function(){
    before(function(){
        // only run these tests if session service is enabled
        if (sessionServiceIsEnabled() === false) {
            this.skip();
        }

        var url = `${CBIOPORTAL_URL}/results?session_id=5bbe8197498eb8b3d5684271`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('session');
});
<commit_msg>Re-enable civic e2e tests (#2261)<commit_after>var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./../specUtils').waitForOncoprint;
var setOncoprintMutationsMenuOpen = require('./../specUtils').setOncoprintMutationsMenuOpen;
var goToUrlAndSetLocalStorage = require('./../specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./../specUtils').waitForNetworkQuiet;
var sessionServiceIsEnabled = require('./../specUtils').sessionServiceIsEnabled;
var assertScreenShotMatch = require('../../lib/testUtils').assertScreenShotMatch;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");

function waitForAndCheckPlotsTab() {
    browser.waitForVisible('div[data-test="PlotsTabPlotDiv"]', 10000);
    var res = browser.checkElement('div[data-test="PlotsTabEntireDiv"]', { hide:['.qtip'] });
    assertScreenShotMatch(res);
}

function runResultsTestSuite(prefix){

    it(`${prefix} render the oncoprint`, function(){
        waitForOncoprint(10000);
        var res = browser.checkElement('.oncoprintContainer', { hide:['.oncoprint__controls']}); // just hide the controls bc for some reason they keep showing up transparent in this test only
        assertScreenShotMatch(res);
    });

    // can't get it to pass reliably
    it.skip(`${prefix} igv_tab tab`, function(){
        browser.click("a.tabAnchor_cnSegments");
        browser.waitForExist('#cnSegmentsFrame', 20000);
        var res = browser.checkElement('.cnSegmentsMSKTabs',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} cancer type summary`, function(){
        browser.click("a.tabAnchor_cancerTypesSummary");
        browser.waitForVisible('[data-test="cancerTypeSummaryChart"]',10000);
        browser.waitForExist('[data-test="cancerTypeSummaryWrapper"]', 5000);
        var res = browser.checkElement('[data-test="cancerTypeSummaryWrapper"]', { hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} mutex tab`, function(){
        browser.click("a.tabAnchor_mutualExclusivity");
        var res = browser.checkElement('[data-test="mutualExclusivityTabDiv"]',{ hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} plots tab`, function(){
        browser.click("a.tabAnchor_plots");
        waitForAndCheckPlotsTab();
    });

    it(`${prefix} mutation tab`, function(){
        browser.click("a.tabAnchor_mutations");
        browser.waitForVisible('.borderedChart svg',20000);
        var res = browser.checkElement('[data-test="mutationsTabDiv"]',{hide:['.qtip', '[data-test=view3DStructure]', '[data-test=GeneSummaryUniProt]'], viewportChangePause:4000}); // hide these things because the timing of data loading makes this test so flaky
        assertScreenShotMatch(res);
    });

    it(`${prefix} coexpression tab`, function(){
        browser.click("a.tabAnchor_coexpression");
        browser.waitForVisible('div[data-test="CoExpressionPlot"]',10000);
        var res = browser.checkElement('[data-test="coExpressionTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} enrichments tab`, function(){
        browser.click("a.tabAnchor_enrichments");
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.click('b=CDK14');
        browser.waitForExist('[data-test="enrichmentsTabDiv"]', 10000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} survival tab`, function(){
        browser.click("a.tabAnchor_survival");
        browser.waitForVisible('[data-test=SurvivalChart] svg',10000);
        var res = browser.checkElement('[data-test="survivalTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} network tab`, function(){
        // TODO: unskip this when bug is fixed

        browser.click("a.tabAnchor_network");

        browser.waitForExist('iframe#networkFrame', 10000);

        browser.frame('networkFrame', function(err, result) {
                if (err) console.log(err);
            });
        browser.waitForVisible('#cytoscapeweb canvas',60000);
        browser.execute(function(){
            $("<style>canvas { visibility: hidden} </style>").appendTo("body");
        });
        browser.frame(null);
        var res = browser.checkElement("#networkFrame",{hide:['.qtip','canvas'] });

        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} data_download tab`, function(){
        browser.click("a.tabAnchor_download");
        //  browser.pause(1000);
        browser.waitForExist("#text_area_gene_alteration_freq",20000);
        browser.waitUntil(function(){ return browser.getValue("#text_area_gene_alteration_freq").length > 0 },20000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
}

describe('result page screenshot tests', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/index.do?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit&show_samples=false&`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('no session')

});

describe('expression tab', function() {
    it("expression tab with complex oql", ()=>{
        goToUrlAndSetLocalStorage(`${CBIOPORTAL_URL}/results/expression?cancer_study_id=all&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=all&gene_list=TP53%3AMUT%3B&geneset_list=%20&tab_index=tab_visualize&Action=Submit&cancer_study_list=acc_tcga%2Cchol_tcga%2Cesca_tcga&show_samples=false`);
        browser.waitForExist(".borderedChart svg", 60000);
        var res = browser.checkElement('[data-test="expressionTabDiv"]');
        assertScreenShotMatch(res);
    });
});

describe("download tab screenshot tests", function() {
    it("download tab - msk_impact_2017 with ALK and SOS1 - SOS1 should be not sequenced", function() {
        var url = `${CBIOPORTAL_URL}/index.do?cancer_study_id=msk_impact_2017&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=msk_impact_2017_all&gene_list=ALK%2520SOS1&geneset_list=+&tab_index=tab_visualize&Action=Submit&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=msk_impact_2017_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=msk_impact_2017_cna`;
        goToUrlAndSetLocalStorage(url);
        browser.waitForExist("a.tabAnchor_download", 10000);
        browser.click("a.tabAnchor_download");
        browser.waitForExist('[data-test="dataDownloadGeneAlterationTable"] tr > td > svg', 20000);
        browser.waitForExist('[data-test="downloadTabDiv"]', 5000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe('patient view page screenshot test', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/patient?studyId=lgg_ucsf_2014&caseId=P04`;
        goToUrlAndSetLocalStorage(url);
    });

    it('patient view lgg_ucsf_2014 P04', function() {
        // find oncokb image
        var oncokbIndicator = $('[data-test="oncogenic-icon-image"]');
        oncokbIndicator.waitForExist(30000);
        // find vaf plot
        var vafPlot = $('.vafPlot');
        vafPlot.waitForExist(30000);

        var res = browser.checkElement('#mainColumn', {hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe("enrichments tab screenshot tests", function() {
    before(function() {
        var url = `${CBIOPORTAL_URL}/results/enrichments?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit`;
        goToUrlAndSetLocalStorage(url);
    });
    it('enrichments tab coadread_tcga_pub mRNA profile', function(){
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.waitForVisible('a=mRNA', 10000);
        browser.click('a=mRNA');
        browser.waitForVisible('div[data-test="MRNAEnrichmentsTab"]',20000);
        browser.waitForVisible('b=MERTK', 10000);
        browser.click('b=MERTK');
        browser.waitForVisible('div[data-test="MiniBoxPlot"]', 20000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });
});

describe('result page tabs, loading from session id', function(){
    before(function(){
        // only run these tests if session service is enabled
        if (sessionServiceIsEnabled() === false) {
            this.skip();
        }

        var url = `${CBIOPORTAL_URL}/results?session_id=5bbe8197498eb8b3d5684271`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('session');
});
<|endoftext|>


<commit_before>redirecter = require('./lib/redirecter/http.js');

redirecter({
  before: function(request, response){
    return true;
  }
}).listen();
<commit_msg>Apply lint to app.js<commit_after>var proxy = require('./lib/redirecter/http.js');

proxy({
  before: function(){
    return true;
  }
}).listen();
<|endoftext|>


<commit_before>import fs from 'fs'
import { parse } from './parser'

export function extractIntl(files) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(files)) {
      files = [files]
    }

    return Promise.all(files.map(readFile))
      .then(fileContents => {
        return resolve(
          fileContents.map(parse).reduce(
            (accumulator, { messages, duplicates }) => ({
              messages: {
                ...accumulator.messages,
                ...messages
              },
              duplicates: [...accumulator.duplicates, ...duplicates]
            }),
            {
              messages: {},
              duplicates: []
            }
          )
        )
      })
      .catch(err => {
        return reject(err)
      })
  })
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) {
        return reject(err)
      }

      return resolve(data)
    })
  })
}
<commit_msg>Ensure parse options are passed in<commit_after>import fs from 'fs'
import { parse } from './parser'

export function extractIntl(files, parserOptions) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(files)) {
      files = [files]
    }

    return Promise.all(files.map(readFile))
      .then(fileContents => {
        return resolve(
          fileContents.map(contents => parse(contents, parserOptions)).reduce(
            (accumulator, { messages, duplicates }) => ({
              messages: {
                ...accumulator.messages,
                ...messages
              },
              duplicates: [...accumulator.duplicates, ...duplicates]
            }),
            {
              messages: {},
              duplicates: []
            }
          )
        )
      })
      .catch(err => {
        return reject(err)
      })
  })
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) {
        return reject(err)
      }

      return resolve(data)
    })
  })
}
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace rules
*/
var rules = {};

/**
* @name empty-line-before-comment
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/empty-line-before-comment}
*/
setReadOnly( rules, 'empty-line-before-comment', require( '@stdlib/_tools/eslint/rules/empty-line-before-comment' ) );

/**
* @name jsdoc-blockquote-indentation
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-blockquote-indentation}
*/
setReadOnly( rules, 'jsdoc-blockquote-indentation', require( '@stdlib/_tools/eslint/rules/jsdoc-blockquote-indentation' ) );

/**
* @name jsdoc-checkbox-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-checkbox-content-indent}
*/
setReadOnly( rules, 'jsdoc-checkbox-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-checkbox-content-indent' ) );

/**
* @name jsdoc-code-block-style
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-code-block-style}
*/
setReadOnly( rules, 'jsdoc-code-block-style', require( '@stdlib/_tools/eslint/rules/jsdoc-code-block-style' ) );

/**
* @name jsdoc-definition-case
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-definition-case}
*/
setReadOnly( rules, 'jsdoc-definition-case', require( '@stdlib/_tools/eslint/rules/jsdoc-definition-case' ) );

/**
* @name jsdoc-definition-spacing
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-definition-spacing}
*/
setReadOnly( rules, 'jsdoc-definition-spacing', require( '@stdlib/_tools/eslint/rules/jsdoc-definition-spacing' ) );

/**
* @name jsdoc-emphasis-marker
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-emphasis-marker}
*/
setReadOnly( rules, 'jsdoc-emphasis-marker', require( '@stdlib/_tools/eslint/rules/jsdoc-emphasis-marker' ) );

/**
* @name jsdoc-fenced-code-marker
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-fenced-code-marker}
*/
setReadOnly( rules, 'jsdoc-fenced-code-marker', require( '@stdlib/_tools/eslint/rules/jsdoc-fenced-code-marker' ) );

/**
* @name jsdoc-final-definition
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-final-definition}
*/
setReadOnly( rules, 'jsdoc-final-definition', require( '@stdlib/_tools/eslint/rules/jsdoc-final-definition' ) );

/**
* @name jsdoc-hard-break-spaces
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-hard-break-spaces}
*/
setReadOnly( rules, 'jsdoc-hard-break-spaces', require( '@stdlib/_tools/eslint/rules/jsdoc-hard-break-spaces' ) );

/**
* @name jsdoc-leading-description-sentence
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-leading-description-sentence}
*/
setReadOnly( rules, 'jsdoc-leading-description-sentence', require( '@stdlib/_tools/eslint/rules/jsdoc-leading-description-sentence' ) );

/**
* @name jsdoc-list-item-bullet-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-list-item-bullet-indent}
*/
setReadOnly( rules, 'jsdoc-list-item-bullet-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-list-item-bullet-indent' ) );

/**
* @name jsdoc-list-item-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-list-item-content-indent}
*/
setReadOnly( rules, 'jsdoc-list-item-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-list-item-content-indent' ) );

/**
* @name jsdoc-markdown-remark
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-markdown-remark}
*/
setReadOnly( rules, 'jsdoc-markdown-remark', require( '@stdlib/_tools/eslint/rules/jsdoc-markdown-remark' ) );

/**
* @name jsdoc-no-auto-link-without-protocol
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-auto-link-without-protocol}
*/
setReadOnly( rules, 'jsdoc-no-auto-link-without-protocol', require( '@stdlib/_tools/eslint/rules/jsdoc-no-auto-link-without-protocol' ) );

/**
* @name jsdoc-no-blockquote-without-marker
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-blockquote-without-marker}
*/
setReadOnly( rules, 'jsdoc-no-blockquote-without-marker', require( '@stdlib/_tools/eslint/rules/jsdoc-no-blockquote-without-marker' ) );

/**
* @name jsdoc-no-duplicate-definitions
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-definitions}
*/
setReadOnly( rules, 'jsdoc-no-duplicate-definitions', require( '@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-definitions' ) );

/**
* @name jsdoc-no-duplicate-headings
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings}
*/
setReadOnly( rules, 'jsdoc-no-duplicate-headings', require( '@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings' ) );

/**
* @name jsdoc-no-duplicate-headings-in-section
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings-in-section}
*/
setReadOnly( rules, 'jsdoc-no-duplicate-headings-in-section', require( '@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings-in-section' ) );

/**
* @name jsdoc-no-emphasis-as-heading
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-emphasis-as-heading}
*/
setReadOnly( rules, 'jsdoc-no-emphasis-as-heading', require( '@stdlib/_tools/eslint/rules/jsdoc-no-emphasis-as-heading' ) );

/**
* @name jsdoc-no-heading-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-heading-content-indent}
*/
setReadOnly( rules, 'jsdoc-no-heading-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-no-heading-content-indent' ) );

/**
* @name jsdoc-no-heading-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-heading-indent}
*/
setReadOnly( rules, 'jsdoc-no-heading-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-no-heading-indent' ) );

/**
* @name jsdoc-no-table-indentation
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-table-indentation}
*/
setReadOnly( rules, 'jsdoc-no-table-indentation', require( '@stdlib/_tools/eslint/rules/jsdoc-no-table-indentation' ) );

/**
* @name jsdoc-no-tabs
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-tabs}
*/
setReadOnly( rules, 'jsdoc-no-tabs', require( '@stdlib/_tools/eslint/rules/jsdoc-no-tabs' ) );

/**
* @name jsdoc-table-pipe-alignment
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-table-pipe-alignment}
*/
setReadOnly( rules, 'jsdoc-table-pipe-alignment', require( '@stdlib/_tools/eslint/rules/jsdoc-table-pipe-alignment' ) );

/**
* @name jsdoc-table-pipes
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-table-pipes}
*/
setReadOnly( rules, 'jsdoc-table-pipes', require( '@stdlib/_tools/eslint/rules/jsdoc-table-pipes' ) );

/**
* @name jsdoc-tag-names
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-tag-names}
*/
setReadOnly( rules, 'jsdoc-tag-names', require( '@stdlib/_tools/eslint/rules/jsdoc-tag-names' ) );

/**
* @name new-cap-array
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/new-cap-array}
*/
setReadOnly( rules, 'new-cap-array', require( '@stdlib/_tools/eslint/rules/new-cap-array' ) );

/**
* @name new-cap-error
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/new-cap-error}
*/
setReadOnly( rules, 'new-cap-error', require( '@stdlib/_tools/eslint/rules/new-cap-error' ) );

/**
* @name new-cap-regexp
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/new-cap-regexp}
*/
setReadOnly( rules, 'new-cap-regexp', require( '@stdlib/_tools/eslint/rules/new-cap-regexp' ) );

/**
* @name no-dynamic-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-dynamic-require}
*/
setReadOnly( rules, 'no-dynamic-require', require( '@stdlib/_tools/eslint/rules/no-dynamic-require' ) );

/**
* @name no-immediate-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-immediate-require}
*/
setReadOnly( rules, 'no-immediate-require', require( '@stdlib/_tools/eslint/rules/no-immediate-require' ) );

/**
* @name no-internal-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-internal-require}
*/
setReadOnly( rules, 'no-internal-require', require( '@stdlib/_tools/eslint/rules/no-internal-require' ) );

/**
* @name no-nested-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-nested-require}
*/
setReadOnly( rules, 'no-nested-require', require( '@stdlib/_tools/eslint/rules/no-nested-require' ) );

/**
* @name no-redeclare
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-redeclare}
*/
setReadOnly( rules, 'no-redeclare', require( '@stdlib/_tools/eslint/rules/no-redeclare' ) );

/**
* @name require-file-extensions
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/require-file-extensions}
*/
setReadOnly( rules, 'require-file-extensions', require( '@stdlib/_tools/eslint/rules/require-file-extensions' ) );

/**
* @name require-globals
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/require-globals}
*/
setReadOnly( rules, 'require-globals', require( '@stdlib/_tools/eslint/rules/require-globals' ) );

/**
* @name section-headers
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/section-headers}
*/
setReadOnly( rules, 'section-headers', require( '@stdlib/_tools/eslint/rules/section-headers' ) );

// EXPORTS //

module.exports = rules;
<commit_msg>Add rule to namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace rules
*/
var rules = {};

/**
* @name empty-line-before-comment
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/empty-line-before-comment}
*/
setReadOnly( rules, 'empty-line-before-comment', require( '@stdlib/_tools/eslint/rules/empty-line-before-comment' ) );

/**
* @name jsdoc-blockquote-indentation
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-blockquote-indentation}
*/
setReadOnly( rules, 'jsdoc-blockquote-indentation', require( '@stdlib/_tools/eslint/rules/jsdoc-blockquote-indentation' ) );

/**
* @name jsdoc-checkbox-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-checkbox-content-indent}
*/
setReadOnly( rules, 'jsdoc-checkbox-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-checkbox-content-indent' ) );

/**
* @name jsdoc-code-block-style
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-code-block-style}
*/
setReadOnly( rules, 'jsdoc-code-block-style', require( '@stdlib/_tools/eslint/rules/jsdoc-code-block-style' ) );

/**
* @name jsdoc-definition-case
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-definition-case}
*/
setReadOnly( rules, 'jsdoc-definition-case', require( '@stdlib/_tools/eslint/rules/jsdoc-definition-case' ) );

/**
* @name jsdoc-definition-spacing
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-definition-spacing}
*/
setReadOnly( rules, 'jsdoc-definition-spacing', require( '@stdlib/_tools/eslint/rules/jsdoc-definition-spacing' ) );

/**
* @name jsdoc-emphasis-marker
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-emphasis-marker}
*/
setReadOnly( rules, 'jsdoc-emphasis-marker', require( '@stdlib/_tools/eslint/rules/jsdoc-emphasis-marker' ) );

/**
* @name jsdoc-fenced-code-marker
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-fenced-code-marker}
*/
setReadOnly( rules, 'jsdoc-fenced-code-marker', require( '@stdlib/_tools/eslint/rules/jsdoc-fenced-code-marker' ) );

/**
* @name jsdoc-final-definition
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-final-definition}
*/
setReadOnly( rules, 'jsdoc-final-definition', require( '@stdlib/_tools/eslint/rules/jsdoc-final-definition' ) );

/**
* @name jsdoc-hard-break-spaces
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-hard-break-spaces}
*/
setReadOnly( rules, 'jsdoc-hard-break-spaces', require( '@stdlib/_tools/eslint/rules/jsdoc-hard-break-spaces' ) );

/**
* @name jsdoc-leading-description-sentence
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-leading-description-sentence}
*/
setReadOnly( rules, 'jsdoc-leading-description-sentence', require( '@stdlib/_tools/eslint/rules/jsdoc-leading-description-sentence' ) );

/**
* @name jsdoc-list-item-bullet-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-list-item-bullet-indent}
*/
setReadOnly( rules, 'jsdoc-list-item-bullet-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-list-item-bullet-indent' ) );

/**
* @name jsdoc-list-item-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-list-item-content-indent}
*/
setReadOnly( rules, 'jsdoc-list-item-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-list-item-content-indent' ) );

/**
* @name jsdoc-markdown-remark
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-markdown-remark}
*/
setReadOnly( rules, 'jsdoc-markdown-remark', require( '@stdlib/_tools/eslint/rules/jsdoc-markdown-remark' ) );

/**
* @name jsdoc-no-auto-link-without-protocol
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-auto-link-without-protocol}
*/
setReadOnly( rules, 'jsdoc-no-auto-link-without-protocol', require( '@stdlib/_tools/eslint/rules/jsdoc-no-auto-link-without-protocol' ) );

/**
* @name jsdoc-no-blockquote-without-marker
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-blockquote-without-marker}
*/
setReadOnly( rules, 'jsdoc-no-blockquote-without-marker', require( '@stdlib/_tools/eslint/rules/jsdoc-no-blockquote-without-marker' ) );

/**
* @name jsdoc-no-duplicate-definitions
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-definitions}
*/
setReadOnly( rules, 'jsdoc-no-duplicate-definitions', require( '@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-definitions' ) );

/**
* @name jsdoc-no-duplicate-headings
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings}
*/
setReadOnly( rules, 'jsdoc-no-duplicate-headings', require( '@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings' ) );

/**
* @name jsdoc-no-duplicate-headings-in-section
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings-in-section}
*/
setReadOnly( rules, 'jsdoc-no-duplicate-headings-in-section', require( '@stdlib/_tools/eslint/rules/jsdoc-no-duplicate-headings-in-section' ) );

/**
* @name jsdoc-no-emphasis-as-heading
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-emphasis-as-heading}
*/
setReadOnly( rules, 'jsdoc-no-emphasis-as-heading', require( '@stdlib/_tools/eslint/rules/jsdoc-no-emphasis-as-heading' ) );

/**
* @name jsdoc-no-heading-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-heading-content-indent}
*/
setReadOnly( rules, 'jsdoc-no-heading-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-no-heading-content-indent' ) );

/**
* @name jsdoc-no-heading-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-heading-indent}
*/
setReadOnly( rules, 'jsdoc-no-heading-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-no-heading-indent' ) );

/**
* @name jsdoc-no-paragraph-content-indent
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-paragraph-content-indent}
*/
setReadOnly( rules, 'jsdoc-no-paragraph-content-indent', require( '@stdlib/_tools/eslint/rules/jsdoc-no-paragraph-content-indent' ) );

/**
* @name jsdoc-no-table-indentation
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-table-indentation}
*/
setReadOnly( rules, 'jsdoc-no-table-indentation', require( '@stdlib/_tools/eslint/rules/jsdoc-no-table-indentation' ) );

/**
* @name jsdoc-no-tabs
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-no-tabs}
*/
setReadOnly( rules, 'jsdoc-no-tabs', require( '@stdlib/_tools/eslint/rules/jsdoc-no-tabs' ) );

/**
* @name jsdoc-table-pipe-alignment
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-table-pipe-alignment}
*/
setReadOnly( rules, 'jsdoc-table-pipe-alignment', require( '@stdlib/_tools/eslint/rules/jsdoc-table-pipe-alignment' ) );

/**
* @name jsdoc-table-pipes
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-table-pipes}
*/
setReadOnly( rules, 'jsdoc-table-pipes', require( '@stdlib/_tools/eslint/rules/jsdoc-table-pipes' ) );

/**
* @name jsdoc-tag-names
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/jsdoc-tag-names}
*/
setReadOnly( rules, 'jsdoc-tag-names', require( '@stdlib/_tools/eslint/rules/jsdoc-tag-names' ) );

/**
* @name new-cap-array
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/new-cap-array}
*/
setReadOnly( rules, 'new-cap-array', require( '@stdlib/_tools/eslint/rules/new-cap-array' ) );

/**
* @name new-cap-error
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/new-cap-error}
*/
setReadOnly( rules, 'new-cap-error', require( '@stdlib/_tools/eslint/rules/new-cap-error' ) );

/**
* @name new-cap-regexp
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/new-cap-regexp}
*/
setReadOnly( rules, 'new-cap-regexp', require( '@stdlib/_tools/eslint/rules/new-cap-regexp' ) );

/**
* @name no-dynamic-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-dynamic-require}
*/
setReadOnly( rules, 'no-dynamic-require', require( '@stdlib/_tools/eslint/rules/no-dynamic-require' ) );

/**
* @name no-immediate-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-immediate-require}
*/
setReadOnly( rules, 'no-immediate-require', require( '@stdlib/_tools/eslint/rules/no-immediate-require' ) );

/**
* @name no-internal-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-internal-require}
*/
setReadOnly( rules, 'no-internal-require', require( '@stdlib/_tools/eslint/rules/no-internal-require' ) );

/**
* @name no-nested-require
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-nested-require}
*/
setReadOnly( rules, 'no-nested-require', require( '@stdlib/_tools/eslint/rules/no-nested-require' ) );

/**
* @name no-redeclare
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/no-redeclare}
*/
setReadOnly( rules, 'no-redeclare', require( '@stdlib/_tools/eslint/rules/no-redeclare' ) );

/**
* @name require-file-extensions
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/require-file-extensions}
*/
setReadOnly( rules, 'require-file-extensions', require( '@stdlib/_tools/eslint/rules/require-file-extensions' ) );

/**
* @name require-globals
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/require-globals}
*/
setReadOnly( rules, 'require-globals', require( '@stdlib/_tools/eslint/rules/require-globals' ) );

/**
* @name section-headers
* @memberof rules
* @readonly
* @type {Function}
* @see {@link module:@stdlib/_tools/eslint/rules/section-headers}
*/
setReadOnly( rules, 'section-headers', require( '@stdlib/_tools/eslint/rules/section-headers' ) );

// EXPORTS //

module.exports = rules;
<|endoftext|>


<commit_before>Components.utils.import("resource://gre/modules/Task.jsm");

var busy = false;
var nextQuery = "";
var observer = null;

tbSync.eas.onInjectIntoContactPanel = function (window) {
    // target for the MutationObserver
    let target = window.document.getElementById("sidebar");
    // configuration for the MutationObserver
    let config = { attributes: true, childList: false, characterData: false };

    // inject into already open window (will do nothing, if not open)
    tbSync.eas.onInjectIntoAddressbook(target.contentWindow.wrappedJSObject, true);

    // create the MutationObserver: try to inject after the src attribute has been changed, thus the URL has been loaded
    observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
          tbSync.eas.abUItimer = window.setInterval(function(){
                let targetWindow = window.document.getElementById("sidebar").contentWindow.wrappedJSObject;
                if (targetWindow) {
                    window.clearInterval(tbSync.eas.abUItimer);
                    tbSync.eas.onInjectIntoAddressbook(targetWindow, true);
                }
            }, 1000);
      });
    });

    observer.observe(target, config);
}

tbSync.eas.onRemoveFromContactPanel = function (window) {
    let targetWindow = window.document.getElementById("sidebar").contentWindow.wrappedJSObject;
    if (targetWindow) tbSync.eas.onRemoveFromAddressbook(targetWindow, true);
    observer.disconnect();
}

// functions called by addressbookoverlay.xul (indirect also by abContactPanelOverlay.xul)
tbSync.eas.onBeforeInjectIntoAddressbook = function (window) {
    return true;
}

tbSync.eas.onInjectIntoAddressbook = function (target, sidebar = false) {
	if (target.document.getElementById("peopleSearchInput")) target.document.getElementById("peopleSearchInput").addEventListener("input", tbSync.eas.onSearchInputChanged, false);
    if (!sidebar) {
        if (target.document.getElementById("abResultsTree")) target.document.getElementById("abResultsTree").addEventListener("select", tbSync.eas.onResultsPaneSelectionChanged, false);
        tbSync.eas.onResultsPaneSelectionChanged();
    }
}

tbSync.eas.onRemoveFromAddressbook = function (target, sidebar = false) {
    if (target.document.getElementById("peopleSearchInput")) target.document.getElementById("peopleSearchInput").removeEventListener("input", tbSync.eas.onSearchInputChanged, false);
    if (!sidebar) {
        if (target.document.getElementById("abResultsTree")) target.document.getElementById("abResultsTree").removeEventListener("select", tbSync.eas.onResultsPaneSelectionChanged, false);
    }
}

tbSync.eas.onResultsPaneSelectionChanged = function () {
    let cards = window.GetSelectedAbCards();
    let email3Box = window.document.getElementById("cvEmail3Box");
    let email3Element = window.document.getElementById("cvEmail3");
    if (email3Box && cards.length == 1) {
        //is this an EAS card?
        let aParentDirURI = tbSync.getUriFromPrefId(cards[0].directoryId.split("&")[0]);
        if (aParentDirURI) { //could be undefined
            let folders = tbSync.db.findFoldersWithSetting("target", aParentDirURI);
            if (folders.length > 0) {
                email3Box.hidden = false;
                let email3Value = cards[0].getProperty("Email3Address","");
                window.HandleLink(email3Element, window.zSecondaryEmail, email3Value, email3Box, "mailto:" + email3Value);
                return;
            }
        }
    }
    email3Box.hidden = true;
}

tbSync.eas.onSearchInputChanged = Task.async (function* () {
    let targetWindow = window.document.getElementById("sidebar") ? window.document.getElementById("sidebar").contentWindow.wrappedJSObject : window;

    let target = targetWindow.GetSelectedDirectory();
    let query = targetWindow.document.getElementById("peopleSearchInput").value;
    let folders = tbSync.db.findFoldersWithSetting("target", target);
    if (folders.length>0) {
        let account = folders[0].account;
        if (tbSync.db.getAccountSetting(account, "allowedEasCommands").split(",").includes("Search")) {

            if (query == "") {
                //remove all gal entries from addressbooks
            } else if (query.length>2) {
                nextQuery = query;
                if (!busy) {
                    busy = true;
                    while (busy) {
                        yield tbSync.sleep(1000);
                        let currentQuery = nextQuery;
                        nextQuery = "";

        /*
gal:DisplayName
gal:Phone
gal:Office
gal:Title
gal:Company
gal:Alias
gal:FirstName
gal:LastName
gal:HomePhone
gal:MobilePhone
gal:EmailAddress
gal:Picture
gal:Data
        */
                        //let newItem = eas.sync[syncdata.type].createItem();

                        let results = yield tbSync.eas.searchGAL (account, currentQuery);
                        tbSync.window.console.log('***************************************************************');
                        for (let count = 0; count < results.length; count++) {
                            if (results[count].Properties) {
                                //add[count].ClientId
                                tbSync.window.console.log('Found contact:' + results[count].Properties.DisplayName);
                            }
                        }
                        if (nextQuery == "") busy = false;
                    }
                }
            }
        }
    }
})
<commit_msg>work on GAL search<commit_after>Components.utils.import("resource://gre/modules/Task.jsm");

var busy = false;
var nextQuery = "";
var observer = null;

tbSync.eas.onInjectIntoContactPanel = function (window) {
    // target for the MutationObserver
    let target = window.document.getElementById("sidebar");
    // configuration for the MutationObserver
    let config = { attributes: true, childList: false, characterData: false };

    // inject into already open window (will do nothing, if not open)
    tbSync.eas.onInjectIntoAddressbook(target.contentWindow.wrappedJSObject, true);

    // create the MutationObserver: try to inject after the src attribute has been changed, thus the URL has been loaded
    observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
          tbSync.eas.abUItimer = window.setInterval(function(){
                let targetWindow = window.document.getElementById("sidebar").contentWindow.wrappedJSObject;
                if (targetWindow) {
                    window.clearInterval(tbSync.eas.abUItimer);
                    tbSync.eas.onInjectIntoAddressbook(targetWindow, true);
                }
            }, 1000);
      });
    });

    observer.observe(target, config);
}

tbSync.eas.onRemoveFromContactPanel = function (window) {
    let targetWindow = window.document.getElementById("sidebar").contentWindow.wrappedJSObject;
    if (targetWindow) tbSync.eas.onRemoveFromAddressbook(targetWindow, true);
    observer.disconnect();
}

// functions called by addressbookoverlay.xul (indirect also by abContactPanelOverlay.xul)
tbSync.eas.onBeforeInjectIntoAddressbook = function (window) {
    return true;
}

tbSync.eas.onInjectIntoAddressbook = function (target, sidebar = false) {
	if (target.document.getElementById("peopleSearchInput")) {
        target.document.getElementById("peopleSearchInput").addEventListener("input", tbSync.eas.onSearchInputChanged, false);
        target.document.getElementById("peopleSearchInput").addEventListener("blur", tbSync.eas.onSearchInputChanged, false);
    }
    if (!sidebar) {
        if (target.document.getElementById("abResultsTree")) target.document.getElementById("abResultsTree").addEventListener("select", tbSync.eas.onResultsPaneSelectionChanged, false);
        tbSync.eas.onResultsPaneSelectionChanged();
    }
}

tbSync.eas.onRemoveFromAddressbook = function (target, sidebar = false) {
    if (target.document.getElementById("peopleSearchInput")) {
        target.document.getElementById("peopleSearchInput").removeEventListener("input", tbSync.eas.onSearchInputChanged, false);
        target.document.getElementById("peopleSearchInput").removeEventListener("blur", tbSync.eas.onSearchInputChanged, false);
    }
    if (!sidebar) {
        if (target.document.getElementById("abResultsTree")) target.document.getElementById("abResultsTree").removeEventListener("select", tbSync.eas.onResultsPaneSelectionChanged, false);
    }
}

tbSync.eas.onResultsPaneSelectionChanged = function () {
    let cards = window.GetSelectedAbCards();
    let email3Box = window.document.getElementById("cvEmail3Box");
    let email3Element = window.document.getElementById("cvEmail3");
    if (email3Box && cards.length == 1) {
        //is this an EAS card?
        let aParentDirURI = tbSync.getUriFromPrefId(cards[0].directoryId.split("&")[0]);
        if (aParentDirURI) { //could be undefined
            let folders = tbSync.db.findFoldersWithSetting("target", aParentDirURI);
            if (folders.length > 0) {
                email3Box.hidden = false;
                let email3Value = cards[0].getProperty("Email3Address","");
                window.HandleLink(email3Element, window.zSecondaryEmail, email3Value, email3Box, "mailto:" + email3Value);
                return;
            }
        }
    }
    email3Box.hidden = true;
}

tbSync.eas.onSearchInputChanged = Task.async (function* () {
    let targetWindow = window.document.getElementById("sidebar") ? window.document.getElementById("sidebar").contentWindow.wrappedJSObject : window;

    let target = targetWindow.GetSelectedDirectory();
    let addressbook = tbSync.getAddressBookObject(target);
    let query = targetWindow.document.getElementById("peopleSearchInput").value;

    let folders = tbSync.db.findFoldersWithSetting("target", target);
    if (folders.length>0) {
        let account = folders[0].account;
        if (tbSync.db.getAccountSetting(account, "allowedEasCommands").split(",").includes("Search")) {

            if (query.length<3) {
                tbSync.window.console.log('* CLEAR **************************************************************');
                //delete all old results
                let oldresults = addressbook.getCardsFromProperty("X-Server-Searchresult", "EAS", true);
                let cardsToDelete = Components.classes["@mozilla.org/array;1"].createInstance(Components.interfaces.nsIMutableArray);
                while (oldresults.hasMoreElements()) {
                    cardsToDelete.appendElement(oldresults.getNext(), "");
                }
                addressbook.deleteCards(cardsToDelete);
                targetWindow.onEnterInSearchBar();
            } else {
                nextQuery = query;
                if (!busy) {
                    busy = true;
                    while (busy) {

                        yield tbSync.sleep(1000);
                        let currentQuery = nextQuery;
                        nextQuery = "";
                        let results = yield tbSync.eas.searchGAL (account, currentQuery);

                        tbSync.window.console.log('* CLEAR **************************************************************');
                        //delete all old results
                        let oldresults = addressbook.getCardsFromProperty("X-Server-Searchresult", "EAS", true);
                        let cardsToDelete = Components.classes["@mozilla.org/array;1"].createInstance(Components.interfaces.nsIMutableArray);
                        while (oldresults.hasMoreElements()) {
                            cardsToDelete.appendElement(oldresults.getNext(), "");
                        }
                        addressbook.deleteCards(cardsToDelete);

                        tbSync.window.console.log('* ADD **************************************************************');
                        for (let count = 0; count < results.length; count++) {
                            if (results[count].Properties) {
                                tbSync.window.console.log('Found contact:' + results[count].Properties.DisplayName);
                                let newItem = Components.classes["@mozilla.org/addressbook/cardproperty;1"].createInstance(Components.interfaces.nsIAbCard);
                                newItem.setProperty("X-Server-Searchresult", "EAS");
                                newItem.setProperty("FirstName", results[count].Properties.FirstName);
                                newItem.setProperty("LastName", results[count].Properties.LastName);
                                newItem.setProperty("DisplayName", results[count].Properties.DisplayName + " (Result)");
                                newItem.setProperty("PrimaryEmail", results[count].Properties.EmailAddress);

                                newItem.setProperty("CellularNumber", results[count].Properties.MobilePhone);
                                newItem.setProperty("HomePhone", results[count].Properties.HomePhone);
                                newItem.setProperty("WorkPhone", results[count].Properties.Phone);
                                newItem.setProperty("Company", results[count].Properties.Company);
                                newItem.setProperty("Department", results[count].Properties.Title);
                                newItem.setProperty("JobTitle", results[count].Properties.Office);

                                /* unmapped:
                                                        gal:
                                                        gal:Office
                                                        gal:Title
                                                        gal:Company
                                                        gal:Picture
                                                        gal:Data
                                            */

                                addressbook.addCard(newItem);
                            }
                        }
                        targetWindow.onEnterInSearchBar();
                        if (nextQuery == "") busy = false;
                    }
                }
            }
        }
    }
})
<|endoftext|>