<commit_before>var request = require('request'),
    _ = require('lodash'),
    Q = require('q');

function Client(settings) {
    var defaults = {
        version: 'v1',
        url: 'https://api.lifx.com/',
        bearerToken: null
    };
    settings = settings || {};

    if(!settings.hasOwnProperty('bearerToken') || !settings.bearerToken.length) {
        throw new Error('Authentication token is required to use the API.');
    }

    this.settings = _.merge(defaults, settings);

    return this;
}

var checkForErrors = function(response, body) {
    var responseCodes = [
        { codes: 400, message: 'Request was invalid.' },
        { codes: 401, message: 'Bad access token.' },
        { codes: 403, message: 'Bad OAuth scope.' },
        { codes: 404, message: 'Selector did not match any lights.' },
        { codes: 422, message: 'Missing or malformed parameters' },
        { codes: 426, message: 'HTTP was used to make the request instead of HTTPS. Repeat the request using HTTPS instead.' },
        { codes: 429, message: 'The request exceeded a rate limit.' },
        { codes: [ 500, 502, 503, 523 ], message: 'Something went wrong on Lif\'s end.' }
    ];

    var error = '';
    responseCodes.every(function(responseCode) {
        if(_.isArray(responseCode.codes)) {
            responseCode.codes.forEach(function(code) {
                if (code === response.statusCode) {
                    error = responseCode.message;
                    return false;
                }

                return true;
            });
        }
    });

    // Special case HTTP code 422 Unprocessable Entity
    if(response.statusCode === 422) {
        error = body.error;
    }

    return error;
};

var verifySelector = function(selector) {
    var validSelectors = [
        'all',
        'label:',
        'id:',
        'group_id:',
        'group:',
        'location_id:',
        'location:',
        'scene_id:'
    ], isValid = false;

    if(!selector || !selector.length) {
        return false;
    }

    validSelectors.every(function(sel) {
        if(selector.startsWith(sel)) {
            isValid = true;

            return false;
        }

        return true;
    });

    return isValid;
};

Client.prototype.getVersion = function() {
    return this.settings.version;
};

Client.prototype.setVersion = function(version) {
    if(!version || !version.length) {
        return false;
    }

    this.settings.version = version;

    return true;
};

Client.prototype.getUrl = function() {
    return this.settings.url;
};

Client.prototype.setUrl = function(url) {
    if(!url || !url.length) {
        return false;
    }
    this.settings.url = url;

    return true;
};

Client.prototype.getApiUrl = function() {
    return [ this.settings.url, this.settings.version ].join('');
};

Client.prototype.getBearerToken = function() {
    return this.settings.bearerToken;
};

Client.prototype.setBearerToken = function(token) {
    if(!token || !token.length) {
        return false;
    }
    this.settings.token = token;

    return true;
};

Client.prototype.getSettings = function() {
    return this.settings;
};

Client.prototype.send = function(settings, cb) {
    var defaults = {
        qs: {},
        json: true,
        method: 'GET',
        baseUrl: this.getApiUrl(),
        headers: {
            Authorization: [ 'Bearer', this.getBearerToken() ].join(' ')
        }
    };

    settings = settings || {};
    settings = _.merge(defaults, settings);

    request(settings, function(err, response, body) {
        var errors = checkForErrors(response, body);
        if(err || errors.length) {
            cb(err || errors, null);
            return;
        }
        cb(null, body);
    });
};

Client.prototype.listLights = function(selector, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    this.send({ url: 'lights/' + selector }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.listScenes = function(cb) {
    var deferred = Q.defer();

    this.send({ url: 'scenes' }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.setState = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    this.send({
        url: 'lights/' + selector + '/state',
        body: settings,
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.setStates = function(settings, cb) {
    var deferred = Q.defer();

    settings = settings || {};
    if(!settings.hasOwnProperty('states')) {
        throw new Error('"states" is required.')
    }

    this.send({
        url: 'lights/states',
        body: settings,
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.togglePower = function(selector, duration, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    duration = duration || 0;
    this.send({
        url: 'lights/' + selector + '/toggle',
        body: { duration: duration },
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.breathe = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    if(!settings.hasOwnProperty('color')) {
        throw new Error('"color" is required.');
    }

    this.send({
        url: 'lights/' + selector + '/effects/breathe',
        body: settings,
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.pulse = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    if(!settings.hasOwnProperty('color')) {
        throw new Error('"color" is required.');
    }

    this.send({
        url: 'lights/' + selector + '/effects/pulse',
        body: settings,
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.cycle = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    if(!settings.hasOwnProperty('states')) {
        throw new Error('"states" is required.');
    }

    this.send({
        url: 'lights/' + selector + '/cycle',
        body: settings,
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.activateScene = function(selector, duration, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    duration = duration || 0;
    this.send({
        url: 'lights/' + selector + '/cycle',
        body: { duration: duration },
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.validateColor = function(color, cb) {
    var deferred = Q.defer();

    color = color || '';
    if(!color.length) {
        throw new Error('"color" is required.');
    }

    this.send({
        url: 'color',
        qs: { color: color },
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

module.exports = Client;<commit_msg>Add inline documentation<commit_after>var request = require('request'),
    _ = require('lodash'),
    Q = require('q');

/**
 *
 * Sets up the lifx http api client.
 *
 * @param settings
 * @returns {Client}
 * @constructor
 */
function Client(settings) {
    var defaults = {
        version: 'v1',
        url: 'https://api.lifx.com/',
        bearerToken: null
    };
    settings = settings || {};

    if(!settings.hasOwnProperty('bearerToken') || !settings.bearerToken.length) {
        throw new Error('Authentication token is required to use the API.');
    }

    this.settings = _.merge(defaults, settings);

    return this;
}

/**
 * Checks the HTTP response code and returns the according error message.
 *
 * See: <http://api.developer.lifx.com/docs/errors>
 *
 * @param {object} response
 * @param {string} body
 * @returns {string}
 */
var checkForErrors = function(response, body) {
    var responseCodes = [
        { codes: 400, message: 'Request was invalid.' },
        { codes: 401, message: 'Bad access token.' },
        { codes: 403, message: 'Bad OAuth scope.' },
        { codes: 404, message: 'Selector did not match any lights.' },
        { codes: 422, message: 'Missing or malformed parameters' },
        { codes: 426, message: 'HTTP was used to make the request instead of HTTPS. Repeat the request using HTTPS instead.' },
        { codes: 429, message: 'The request exceeded a rate limit.' },
        { codes: [ 500, 502, 503, 523 ], message: 'Something went wrong on Lif\'s end.' }
    ];

    var error = '';
    responseCodes.every(function(responseCode) {
        if(_.isArray(responseCode.codes)) {
            responseCode.codes.forEach(function(code) {
                if (code === response.statusCode) {
                    error = responseCode.message;
                    return false;
                }

                return true;
            });
        }
    });

    // Special case HTTP code 422 Unprocessable Entity
    if(response.statusCode === 422) {
        error = body.error;
    }

    return error;
};

/**
 * Checks the light selector if it's valid.
 *
 * See: <http://api.developer.lifx.com/docs/selectors>
 *
 * @param {string} selector
 * @returns {boolean}
 */
var verifySelector = function(selector) {
    var validSelectors = [
        'all',
        'label:',
        'id:',
        'group_id:',
        'group:',
        'location_id:',
        'location:',
        'scene_id:'
    ], isValid = false;

    if(!selector || !selector.length) {
        return false;
    }

    validSelectors.every(function(sel) {
        if(selector.startsWith(sel)) {
            isValid = true;

            return false;
        }

        return true;
    });

    return isValid;
};

/**
 * Returns the api version.
 *
 * @returns {string}
 */
Client.prototype.getVersion = function() {
    return this.settings.version;
};

/**
 * Sets the api version.
 *
 * @param {string} version
 * @returns {boolean}
 */
Client.prototype.setVersion = function(version) {
    if(!version || !version.length) {
        return false;
    }

    this.settings.version = version;

    return true;
};

/**
 * Returns the api url.
 *
 * @returns {string}
 */
Client.prototype.getUrl = function() {
    return this.settings.url;
};

/**
 * Sets the api url.
 *
 * @param {string} url
 * @returns {boolean}
 */
Client.prototype.setUrl = function(url) {
    if(!url || !url.length) {
        return false;
    }
    this.settings.url = url;

    return true;
};

/**
 * Returns the full api url
 * @returns {string}
 */
Client.prototype.getApiUrl = function() {
    return [ this.settings.url, this.settings.version ].join('');
};

/**
 * Returns the bearer token which is used to authenticate against the api.
 * @returns {null|string}
 */
Client.prototype.getBearerToken = function() {
    return this.settings.bearerToken;
};

/**
 * Sets the bearer token
 *
 * @param {string} token
 * @returns {boolean}
 */
Client.prototype.setBearerToken = function(token) {
    if(!token || !token.length) {
        return false;
    }
    this.settings.token = token;

    return true;
};

/**
 * Returns the client configuration
 *
 * @returns {object}
 */
Client.prototype.getSettings = function() {
    return this.settings;
};

/**
 * Sends the actual request to the lifx api end point.
 *
 * @param {object} settings
 * @param {function} cb
 */
Client.prototype.send = function(settings, cb) {
    var defaults = {
        qs: {},
        json: true,
        method: 'GET',
        baseUrl: this.getApiUrl(),
        headers: {
            Authorization: [ 'Bearer', this.getBearerToken() ].join(' ')
        }
    };

    settings = settings || {};
    settings = _.merge(defaults, settings);

    request(settings, function(err, response, body) {
        var errors = checkForErrors(response, body);
        if(err || errors.length) {
            cb(err || errors, null);
            return;
        }
        cb(null, body);
    });
};

/**
 * Lists all lights or specific lights depending on the selector.
 *
 * @param {string} selector
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.listLights = function(selector, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    this.send({ url: 'lights/' + selector }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Lists all available scenes
 *
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.listScenes = function(cb) {
    var deferred = Q.defer();

    this.send({ url: 'scenes' }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Sets a sets to all or a specific light.
 *
 * @param {string} selector
 * @param {object} settings
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.setState = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    this.send({
        url: 'lights/' + selector + '/state',
        body: settings,
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Sets multiple states at once.
 *
 * @param {object} settings
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.setStates = function(settings, cb) {
    var deferred = Q.defer();

    settings = settings || {};
    if(!settings.hasOwnProperty('states')) {
        throw new Error('"states" is required.')
    }

    this.send({
        url: 'lights/states',
        body: settings,
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Toggles the power status of the light.
 *
 * @param {string} selector
 * @param {string} duration
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.togglePower = function(selector, duration, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    duration = duration || 0;
    this.send({
        url: 'lights/' + selector + '/toggle',
        body: { duration: duration },
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Creates a breathe effect with the matching light bulbs.
 *
 * @param {string} selector
 * @param {object} settings
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.breathe = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    if(!settings.hasOwnProperty('color')) {
        throw new Error('"color" is required.');
    }

    this.send({
        url: 'lights/' + selector + '/effects/breathe',
        body: settings,
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Creates a pulse effect with the matching light bulbs.
 *
 * @param {string} selector
 * @param {object} settings
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.pulse = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    if(!settings.hasOwnProperty('color')) {
        throw new Error('"color" is required.');
    }

    this.send({
        url: 'lights/' + selector + '/effects/pulse',
        body: settings,
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Cycles through different defined states.
 *
 * @param {string} selector
 * @param {object} settings
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.cycle = function(selector, settings, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    settings = settings || {};
    if(!settings.hasOwnProperty('states')) {
        throw new Error('"states" is required.');
    }

    this.send({
        url: 'lights/' + selector + '/cycle',
        body: settings,
        method: 'POST'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

/**
 * Activates the specific scene to the specific light bulbs.
 *
 * @param {string} selector
 * @param {string} duration
 * @param {function} cb
 * @returns {*} either the promise or nothing
 */
Client.prototype.activateScene = function(selector, duration, cb) {
    var deferred = Q.defer();

    selector = selector || 'all';
    if(!verifySelector(selector)) {
        throw new Error('Selector is not valid.');
    }

    duration = duration || 0;
    this.send({
        url: 'lights/' + selector + '/cycle',
        body: { duration: duration },
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

Client.prototype.validateColor = function(color, cb) {
    var deferred = Q.defer();

    color = color || '';
    if(!color.length) {
        throw new Error('"color" is required.');
    }

    this.send({
        url: 'color',
        qs: { color: color },
        method: 'PUT'
    }, function(err, data) {
        if (err) deferred.reject(err);
        else deferred.resolve(data);
    });

    return deferred.promise.nodeify(cb);
};

module.exports = Client;<|endoftext|>


<commit_before>import toRomaji from '../../src/toRomaji';
import { JA_PUNC, EN_PUNC } from '../helpers/conversionTables';

describe('toRomaji()', () => {
  it('sane defaults', () => {
    expect(toRomaji()).toBe('');
    expect(toRomaji('')).toBe('');
  });

  it('Convert katakana to romaji', () =>
    expect(toRomaji('ワニカニ　ガ　スゴイ　ダ')).toBe('wanikani ga sugoi da'));

  it('Convert hiragana to romaji', () =>
    expect(toRomaji('わにかに　が　すごい　だ')).toBe('wanikani ga sugoi da'));

  it('Convert mixed kana to romaji', () =>
    expect(toRomaji('ワニカニ　が　すごい　だ')).toBe('wanikani ga sugoi da'));

  it('Will convert punctuation and full-width spaces', () =>
    expect(toRomaji(JA_PUNC.join(''))).toBe(EN_PUNC.join('')));

  it('Use the upcaseKatakana flag to preserve casing. Works for katakana.', () =>
    expect(toRomaji('ワニカニ', { upcaseKatakana: true })).toBe('WANIKANI'));

  it('Use the upcaseKatakana flag to preserve casing. Works for mixed kana.', () =>
    expect(toRomaji('ワニカニ　が　すごい　だ', { upcaseKatakana: true })).toBe(
      'WANIKANI ga sugoi da'
    ));

  it("Doesn't mangle the long dash 'ー' or slashdot '・'", () =>
    expect(toRomaji('罰ゲーム・ばつげーむ')).toBe('罰geemu/batsuge-mu'));

  it("Doesn't mangle the long dash 'ー' or slashdot '・'", () =>
    expect(toRomaji('罰ゲーム・ばつげーむ')).toBe('罰geemu/batsuge-mu'));

  it('Spaces must be manually entered', () =>
    expect(toRomaji('わにかにがすごいだ')).not.toBe('wanikani ga sugoi da'));

  describe("double n's and double consonants", () => {
    it('Double and single n', () => expect(toRomaji('きんにくまん')).toBe('kinnikuman'));
    it('N extravaganza', () => expect(toRomaji('んんにんにんにゃんやん')).toBe("nnninninnyan'yan"));
    it('Double consonants', () =>
      expect(toRomaji('かっぱ　たった　しゅっしゅ ちゃっちゃ　やっつ')).toBe(
        'kappa tatta shusshu chatcha yattsu'
      ));
  });

  describe('Small kana', () => {
    it("Small tsu doesn't transliterate", () => expect(toRomaji('っ')).toBe(''));
    it('Small ya', () => expect(toRomaji('ゃ')).toBe('ya'));
    it('Small yu', () => expect(toRomaji('ゅ')).toBe('yu'));
    it('Small yo', () => expect(toRomaji('ょ')).toBe('yo'));
    it('Small a', () => expect(toRomaji('ぁ')).toBe('a'));
    it('Small i', () => expect(toRomaji('ぃ')).toBe('i'));
    it('Small u', () => expect(toRomaji('ぅ')).toBe('u'));
    it('Small e', () => expect(toRomaji('ぇ')).toBe('e'));
    it('Small o', () => expect(toRomaji('ぉ')).toBe('o'));
  });

  describe('Apostrophes in ambiguous consonant vowel combos', () => {
    it('おんよみ', () => expect(toRomaji('おんよみ')).toBe("on'yomi"));
    it('んよ んあ んゆ', () => expect(toRomaji('んよ んあ んゆ')).toBe("n'yo n'a n'yu"));
  });
});
<commit_msg>test: buff toRomaji cases<commit_after>import toRomaji from '../../src/toRomaji';
import { JA_PUNC, EN_PUNC } from '../helpers/conversionTables';

describe('toRomaji()', () => {
  it('sane defaults', () => {
    expect(toRomaji()).toBe('');
    expect(toRomaji('')).toBe('');
  });

  it('Convert katakana to romaji', () =>
    expect(toRomaji('ワニカニ　ガ　スゴイ　ダ')).toBe('wanikani ga sugoi da'));

  it('Convert hiragana to romaji', () =>
    expect(toRomaji('わにかに　が　すごい　だ')).toBe('wanikani ga sugoi da'));

  it('Convert mixed kana to romaji', () =>
    expect(toRomaji('ワニカニ　が　すごい　だ')).toBe('wanikani ga sugoi da'));

  it('Will convert punctuation and full-width spaces', () =>
    expect(toRomaji(JA_PUNC.join(''))).toBe(EN_PUNC.join('')));

  it('Use the upcaseKatakana flag to preserve casing. Works for katakana.', () =>
    expect(toRomaji('ワニカニ', { upcaseKatakana: true })).toBe('WANIKANI'));

  it('Use the upcaseKatakana flag to preserve casing. Works for mixed kana.', () =>
    expect(toRomaji('ワニカニ　が　すごい　だ', { upcaseKatakana: true })).toBe('WANIKANI ga sugoi da'));

  it("Converts long dash 'ー' in hiragana to hyphen", () =>
    expect(toRomaji('ばつげーむ')).toBe('batsuge-mu'));

  it("Doesn't confuse '一' (one kanji) for long dash 'ー'", () =>
    expect(toRomaji('一抹げーむ')).toBe('一抹ge-mu'));

  it("Converts long dash 'ー' (chōonpu) in katakana to long vowel", () =>
    expect(toRomaji('スーパー')).toBe('suupaa'));

  it('Spaces must be manually entered', () =>
    expect(toRomaji('わにかにがすごいだ')).not.toBe('wanikani ga sugoi da'));

  describe("double n's and double consonants", () => {
    it('Double and single n', () => expect(toRomaji('きんにくまん')).toBe('kinnikuman'));
    it('N extravaganza', () => expect(toRomaji('んんにんにんにゃんやん')).toBe("nnninninnyan'yan"));
    it('Double consonants', () =>
      expect(toRomaji('かっぱ　たった　しゅっしゅ ちゃっちゃ　やっつ')).toBe('kappa tatta shusshu chatcha yattsu'));
  });

  describe('Small kana', () => {
    it("Small tsu doesn't transliterate", () => expect(toRomaji('っ')).toBe(''));
    it("Small kata ke doesn't transliterate", () => expect(toRomaji('ヶ')).toBe('ヶ'));
    it("Small kata ka doesn't transliterate", () => expect(toRomaji('ヵ')).toBe('ヵ'));
    it('Small ya', () => expect(toRomaji('ゃ')).toBe('ya'));
    it('Small yu', () => expect(toRomaji('ゅ')).toBe('yu'));
    it('Small yo', () => expect(toRomaji('ょ')).toBe('yo'));
    it('Small a', () => expect(toRomaji('ぁ')).toBe('a'));
    it('Small i', () => expect(toRomaji('ぃ')).toBe('i'));
    it('Small u', () => expect(toRomaji('ぅ')).toBe('u'));
    it('Small e', () => expect(toRomaji('ぇ')).toBe('e'));
    it('Small o', () => expect(toRomaji('ぉ')).toBe('o'));
  });

  describe('Apostrophes in ambiguous consonant vowel combos', () => {
    it('おんよみ', () => expect(toRomaji('おんよみ')).toBe("on'yomi"));
    it('んよ んあ んゆ', () => expect(toRomaji('んよ んあ んゆ')).toBe("n'yo n'a n'yu"));
    it('シンヨ', () => expect(toRomaji('シンヨ')).toBe("shin'yo"));
  });
});
<|endoftext|>


<commit_before>/*jshint node: true */
/*globals describe, it, beforeEach */
'use strict';
var expect = require('expect.js');
var Database = require('../');
var db = new Database();

var testDbName = 'test__database_0';

describe('database', function () {
  describe('createDatabase', function () {
    beforeEach(function (done) {
      db.dropDatabase(testDbName, function () {
        done();
      });
    });
    it('returns a new database object with the given name', function (done) {
      db.createDatabase(testDbName, function (err, database) {
        expect(err).to.eql(null);
        expect(database).to.be.a(Database);
        expect(database.name).to.equal(testDbName);
        done();
      });
    });
    it('creates a new database with the given name', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).to.eql(null);
        db.database(testDbName, false, function (err2, database) {
          expect(err2).to.eql(null);
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
  });
  describe('database', function () {
    it('is missing tests');
  });
  describe('databases', function () {
    it('is missing tests');
  });
  describe('dropDatabase', function () {
    it('is missing tests');
  });
});<commit_msg>Test basic database CRUD.<commit_after>/*jshint node: true */
/*globals describe, it, beforeEach */
'use strict';
var expect = require('expect.js');
var Database = require('../');
var ArangoError = require('../lib/error');
var db = new Database();

var testDbName = 'test__database_0';

describe('database', function () {
  beforeEach(function (done) {
    db.dropDatabase(testDbName, function () {
      done();
    });
  });
  describe('createDatabase', function () {
    it('returns a new database object with the given name', function (done) {
      db.createDatabase(testDbName, function (err, database) {
        expect(err).not.to.be.ok();
        expect(database).to.be.a(Database);
        expect(database.name).to.equal(testDbName);
        done();
      });
    });
    it('creates a new database with the given name', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.database(testDbName, false, function (err2, database) {
          expect(err2).not.to.be.ok();
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
    it('returns an ArangoError if the db already exists', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.createDatabase(testDbName, function (err2, database) {
          expect(err2).to.be.an(ArangoError);
          expect(database).not.to.be.ok();
          done();
        });
      });
    });
  });
  describe('database', function () {
    describe('with autoCreate:false', function () {
      it('returns the database if it exists', function (done) {
        db.createDatabase(testDbName, function (err) {
          expect(err).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).not.to.be.ok();
            expect(database.name).to.equal(testDbName);
            done();
          });
        });
      });
      it('returns an ArangoError if the db does not exist', function (done) {
        db.database('this_db_does_not_exist', false, function (err, database) {
          expect(err).to.be.an(ArangoError);
          expect(database).not.to.be.ok();
          done();
        });
      });
    });
    describe('with autoCreate:true', function () {
      it('returns the database if it exists', function (done) {
        db.createDatabase(testDbName, function (err) {
          expect(err).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).not.to.be.ok();
            expect(database.name).to.equal(testDbName);
            done();
          });
        });
      });
      it('creates the database if it does not exist', function (done) {
        db.database(testDbName, true, function (err, database) {
          expect(err).not.to.be.ok();
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
  });
  describe('databases', function () {
    it('returns all the databases', function (done) {
      db.databases(function (err, dbs) {
        expect(err).not.to.be.ok();
        expect(dbs).to.be.an(Array);
        expect(dbs).to.have.property('length', 1);
        expect(dbs[0]).to.be.a(Database);
        expect(dbs[0].name).to.equal('_system');
        db.createDatabase(testDbName, function (err2) {
          expect(err2).not.to.be.ok();
          db.databases(function (err3, dbs2) {
            expect(err3).not.to.be.ok();
            var dbNames = dbs2.map(function (db) {
              return db.name;
            });
            expect(dbNames.sort()).to.eql(['_system', testDbName]);
            done();
          });
        })
      })
    });
  });
  describe('dropDatabase', function () {
    it('drops the database if it exists', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.dropDatabase(testDbName, function (err1) {
          expect(err1).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).to.be.an(ArangoError);
            expect(database).not.to.be.ok();
            done();
          });
        });
      });
    });
    it('returns an ArangoError if the db does not exist', function (done) {
      db.dropDatabase('this_db_does_not_exist', function (err) {
        expect(err).to.be.an(ArangoError);
        done();
      });
    });
  });
});<|endoftext|>


<commit_before>var assert = require('assert');
var request = require('request');
// var http = require('http');
var https = require('https');
var path = require('path');

var Proxy = require('../../src/server');
var testServer = require('../testServer');

describe('#https server', function () {
  var proxyServer;
  before(function () {
    testServer.listen(61234);

    proxyServer = new Proxy(8850, 10011);
    proxyServer.addRewriteFile(path.join(__dirname, 'conf', 'rewrite'));
    proxyServer.start();
    // proxyServer.openBrowser('chrome', '127.0.0.1:8850', true);
  });

  after(function () {
    testServer.close();
    proxyServer.stop();
  });

  describe('#api', function () {
    it('#start()', function (done) {
      var server = new Proxy(8848, 10012);
      server.start().then(function () {
        if (server.httpsServer instanceof https.Server) {
          done();
        } else {
          done(new Error('server.httpsServer is not an instance of https.Server'));
        }
        server.stop();
      });
    });
  });

  describe('#server response', function () {
    it('request /', function (done) {
      request({
        url: 'https://127.0.0.1:10011/',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          done(err || new Error('Body not match'));
        } else if (body.indexOf('the man in the middle page: /') !== -1) {
          done();
        }
      });
    });
  });

  describe('# proxy', function () {
    it('request t.ttt.com/', function (done) {
      request({
        uri: 'https://t.ttt.com/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false,
        json: true,
        gzip: true
      }, function (err, response, body) {
        if (body && body.url === '/' && body.method === 'GET') {
          done();
        } else {
          done(err || new Error('Body not match'));
        }
      });
    });

    it('request t.ttt.com/t/ proxy ok', function (done) {
      request({
        uri: 'https://t.ttt.com/t/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false,
        gzip: true,
        json: true
      }, function (err, response, body) {
        console.log(body);
        if (body.url === '/test/') {
          done();
        } else {
          done(err || new Error('Body not match'));
        }
      });
    });

    it('request t.ttt.com/t/ header ok', function (done) {
      request({
        uri: 'https://t.ttt.com/t/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false,
        gzip: true,
        json: true
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var reqHeaders = body.headers;
        var resHeaders = response.headers;

        assert.equal('t.ttt.com', reqHeaders.host);
        assert.equal('hiproxy', reqHeaders.proxy_app);

        assert.equal('1', resHeaders.set_header_field_1);
        assert.deepEqual(['cookie1=c1', 'cookie2=c2'].sort(), resHeaders['set-cookie'].sort());

        done();
      });
    });

    it('request t.ttt.com/source/ (alias, root)', function (done) {
      request({
        uri: 'https://t.ttt.com/source/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var headers = response.headers;

        assert.equal('
hello, hiproxy
', body);
        assert.equal('text/html', headers['content-type']);

        done();
      });
    });

    it('request t.ttt.com/source/a.json', function (done) {
      request({
        uri: 'https://t.ttt.com/source/a.json',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var headers = response.headers;

        assert.equal('{"ret": true}', body);
        assert.equal('application/json', headers['content-type']);

        done();
      });
    });

    it('should return remote content when request https://www.example.com/', function (done) {
      request({
        uri: 'https://www.example.com/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var statusCode = response.statusCode;

        assert.equal(statusCode, 200);

        done();
      });
    });

    it('should return error content when request https://www.example-domain-not-exists.com/', function (done) {
      request({
        uri: 'https://www.example-domain-not-exists.com/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        assert.notEqual(err, null);

        done();
      });
    });
  });
});
<commit_msg>delete console log<commit_after>var assert = require('assert');
var request = require('request');
// var http = require('http');
var https = require('https');
var path = require('path');

var Proxy = require('../../src/server');
var testServer = require('../testServer');

describe('#https server', function () {
  var proxyServer;
  before(function () {
    testServer.listen(61234);

    proxyServer = new Proxy(8850, 10011);
    proxyServer.addRewriteFile(path.join(__dirname, 'conf', 'rewrite'));
    proxyServer.start();
    // proxyServer.openBrowser('chrome', '127.0.0.1:8850', true);
  });

  after(function () {
    testServer.close();
    proxyServer.stop();
  });

  describe('#api', function () {
    it('#start()', function (done) {
      var server = new Proxy(8848, 10012);
      server.start().then(function () {
        if (server.httpsServer instanceof https.Server) {
          done();
        } else {
          done(new Error('server.httpsServer is not an instance of https.Server'));
        }
        server.stop();
      });
    });
  });

  describe('#server response', function () {
    it('request /', function (done) {
      request({
        url: 'https://127.0.0.1:10011/',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          done(err || new Error('Body not match'));
        } else if (body.indexOf('the man in the middle page: /') !== -1) {
          done();
        }
      });
    });
  });

  describe('# proxy', function () {
    it('request t.ttt.com/', function (done) {
      request({
        uri: 'https://t.ttt.com/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false,
        json: true,
        gzip: true
      }, function (err, response, body) {
        if (body && body.url === '/' && body.method === 'GET') {
          done();
        } else {
          done(err || new Error('Body not match'));
        }
      });
    });

    it('request t.ttt.com/t/ proxy ok', function (done) {
      request({
        uri: 'https://t.ttt.com/t/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false,
        gzip: true,
        json: true
      }, function (err, response, body) {
        if (body.url === '/test/') {
          done();
        } else {
          done(err || new Error('Body not match'));
        }
      });
    });

    it('request t.ttt.com/t/ header ok', function (done) {
      request({
        uri: 'https://t.ttt.com/t/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false,
        gzip: true,
        json: true
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var reqHeaders = body.headers;
        var resHeaders = response.headers;

        assert.equal('t.ttt.com', reqHeaders.host);
        assert.equal('hiproxy', reqHeaders.proxy_app);

        assert.equal('1', resHeaders.set_header_field_1);
        assert.deepEqual(['cookie1=c1', 'cookie2=c2'].sort(), resHeaders['set-cookie'].sort());

        done();
      });
    });

    it('request t.ttt.com/source/ (alias, root)', function (done) {
      request({
        uri: 'https://t.ttt.com/source/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var headers = response.headers;

        assert.equal('
hello, hiproxy
', body);
        assert.equal('text/html', headers['content-type']);

        done();
      });
    });

    it('request t.ttt.com/source/a.json', function (done) {
      request({
        uri: 'https://t.ttt.com/source/a.json',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var headers = response.headers;

        assert.equal('{"ret": true}', body);
        assert.equal('application/json', headers['content-type']);

        done();
      });
    });

    it('should return remote content when request https://www.example.com/', function (done) {
      request({
        uri: 'https://www.example.com/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        if (err) {
          return done(err);
        }

        var statusCode = response.statusCode;

        assert.equal(statusCode, 200);

        done();
      });
    });

    it('should return error content when request https://www.example-domain-not-exists.com/', function (done) {
      request({
        uri: 'https://www.example-domain-not-exists.com/',
        proxy: 'http://127.0.0.1:8850',
        rejectUnauthorized: false
      }, function (err, response, body) {
        assert.notEqual(err, null);

        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert')
  , Fellowship = require('../')

describe('#removePermission', function () {

  it('should throw an error if group does not have permission', function () {
    var fellowship = new Fellowship()

    fellowship.addResource('test', [ 'hello', 'world' ])
    fellowship.addGroup('test', { test: 2 })

    assert.throws(fellowship.removePermission.bind(fellowship, 'test', 'test', 'a'), /Permission a does not exist in test/)
  })

  it('should successfully remove a permission', function () {
    var fellowship = new Fellowship()

    fellowship.addResource('test', [ 'hello', 'world' ])
    fellowship.addGroup('test', { test: 2 })
    fellowship.addPermission('test', 'test', 'hello')

    assert.equal(fellowship.getGroup('test').test, 3)

    fellowship.removePermission('test', 'test', 'hello')

    assert.equal(fellowship.getGroup('test').test, 2)
  })

})
<commit_msg>Improve coverage<commit_after>var assert = require('assert')
  , Fellowship = require('../')

describe('#removePermission', function () {

  it('should throw an error if resource does not have permission', function () {
    var fellowship = new Fellowship()

    fellowship.addResource('test', [ 'hello', 'world' ])
    fellowship.addGroup('test', { test: 2 })

    assert.throws(fellowship.removePermission.bind(fellowship, 'test', 'test', 'a'), /Permission a does not exist in test/)
  })

  it('should throw an error if group does not have permission', function () {
    var fellowship = new Fellowship()

    fellowship.addResource('test', [ 'hello', 'world' ])
    fellowship.addGroup('test', { test: 2 })

    assert.throws(fellowship.removePermission.bind(fellowship, 'test', 'test', 'hello'), /Permission hello not defined within test/)
  })

  it('should successfully remove a permission', function () {
    var fellowship = new Fellowship()

    fellowship.addResource('test', [ 'hello', 'world' ])
    fellowship.addGroup('test', { test: 2 })
    fellowship.addPermission('test', 'test', 'hello')

    assert.equal(fellowship.getGroup('test').test, 3)

    fellowship.removePermission('test', 'test', 'hello')

    assert.equal(fellowship.getGroup('test').test, 2)
  })

})
<|endoftext|>


<commit_before>var NL_GENERA  = ['Agaricus*','Chlorophyllum*','Imageless*','Lepiota*','Macrocybe*','Peltigera*','Psalliota*','Suillus*','Tremella*'];
var NL_SPECIES = ['Abortiporus biennis*','Agaricus campestras*','Agaricus campestris*','Agaricus campestros*','Agaricus campestrus*','Amanita baccata|sensu Arora*','Amanita baccata|sensu Borealis*','Amanita boudieri var. beillei*','Boletus edulis*','Chlorophyllum rachodes*','Chlorophyllum rhacodes*','Conocybe filaris*','Coprinellus micaceus*','Coprinellus micaceus|(Bull.) Vilgalys, Hopple & Jacq. Johnson*','Coprinus comatus*','Hygrocybe russocoriacea|(Berk. & Jos.K. Mill.) P.D. Orton & Watling*','Hygrocybe russocoriacea|(Berk. & T.K. Mill.) P.D. Orton & Watling*','Lactarius alpigenes','= Lactarius alpinus','Lactarius alpinus*','Lactarius kuehneri','= Lactarius alpinus','Lactarius subalpinus','= Lactarius alpinus','Lentinellus ursinus|Kühner*','Lentinellus ursinus|Kuhner*','Lepiota rachodes*','Lepiota rhacodes*','Macrolepiota rachodes*','Macrolepiota rhacodes*','Pluteus petasatus|(Fr.) Gillet*','Pluteus petasatus|(Fries) Gillet','Russula brevipes*','Russula brevipes|Peck*','Russula cremoricolor*','Russula cremoricolor|Earle*','Strobilurus diminutivus*','Tremella justpublished*','Tremella mesenterica*','Warnerbros bugs-bunny|One*','Warnerbros bugs-bunny|Two*'];
var NL_NAMES   = [];
<commit_msg>Fix expectation which broke upon adding a new genus.<commit_after>var NL_GENERA  = ['Agaricus*','Chlorophyllum*','Imageless*','Lepiota*','Macrocybe*','Peltigera*','Psalliota*','Suillus*','Tremella*','Verpaa*'];
var NL_SPECIES = ['Abortiporus biennis*','Agaricus campestras*','Agaricus campestris*','Agaricus campestros*','Agaricus campestrus*','Amanita baccata|sensu Arora*','Amanita baccata|sensu Borealis*','Amanita boudieri var. beillei*','Boletus edulis*','Chlorophyllum rachodes*','Chlorophyllum rhacodes*','Conocybe filaris*','Coprinellus micaceus*','Coprinellus micaceus|(Bull.) Vilgalys, Hopple & Jacq. Johnson*','Coprinus comatus*','Hygrocybe russocoriacea|(Berk. & Jos.K. Mill.) P.D. Orton & Watling*','Hygrocybe russocoriacea|(Berk. & T.K. Mill.) P.D. Orton & Watling*','Lactarius alpigenes','= Lactarius alpinus','Lactarius alpinus*','Lactarius kuehneri','= Lactarius alpinus','Lactarius subalpinus','= Lactarius alpinus','Lentinellus ursinus|Kühner*','Lentinellus ursinus|Kuhner*','Lepiota rachodes*','Lepiota rhacodes*','Macrolepiota rachodes*','Macrolepiota rhacodes*','Pluteus petasatus|(Fr.) Gillet*','Pluteus petasatus|(Fries) Gillet','Russula brevipes*','Russula brevipes|Peck*','Russula cremoricolor*','Russula cremoricolor|Earle*','Strobilurus diminutivus*','Tremella justpublished*','Tremella mesenterica*','Warnerbros bugs-bunny|One*','Warnerbros bugs-bunny|Two*'];
var NL_NAMES   = [];
<|endoftext|>


<commit_before>angular.module('CarreEntrySystem').service('Risk_elements', function($http, CARRE, CONFIG, QUERY) {

  this.exports = {
    'get': getRisk_elements,
    'save': saveRisk_element,
    'associations' : RiskElementAssociations
  };

  function getRisk_elements(ArrayOfIDs) {
    return CARRE.instances('risk_element', ArrayOfIDs);
  }

  function saveRisk_element(oldElem, newElem, user) {
    user = user || CONFIG.currentUser.graphName;
    var updateQuery = "",
      insertQuery = "";
    var newObj = {};
    if (newElem.name.length > 0) newObj.has_risk_element_name = {
      pre: 'risk',
      value: newElem.name.toString(),
      type: "string"
    };
    if (newElem.identifier.length > 0) newObj.has_risk_element_identifier = {
      pre: 'risk',
      value: "http://umls.nlm.nih.gov/sab/mth/cui/" + newElem.identifier.toString(),
      type: "node"
    };
    if (newElem.type.length > 0) newObj.has_risk_element_type = {
      pre: 'risk',
      value: newElem.type.toString(),
      type: "node"
    };
    if (newElem.modifiable_status.length > 0) newObj.has_risk_element_modifiable_status = {
      pre: 'risk',
      value: newElem.modifiable_status.toString(),
      type: "string"
    };
    if (newElem.observables.length > 0) newObj.has_risk_element_observable = {
      pre: 'risk',
      value: newElem.observables,
      type: "node"
    };
    if (newElem.risk_elements.length > 0) newObj.includes_risk_element = {
      pre: 'risk',
      value: newElem.risk_elements,
      type: "node"
    };

    console.log('Old: ', oldElem);
    console.log('New: ', newElem);
    console.log('Mapped: ', newObj);

    if (oldElem.id) {
      /*Update query*/
      updateQuery = QUERY.update(oldElem, newObj);
      console.log('----Update Query----');
      return CARRE.query(updateQuery, 'no prefix');
    }
    else {
      /*Insert query*/
      insertQuery = QUERY.insert(newObj, "risk_element", "RL", user);
      console.info('-----insertQuery------');
      return CARRE.query(insertQuery, 'no prefix');
    }

  }

  function RiskElementAssociations(id) {

    //accept only risk element ids
    if (id.indexOf("RL_") === -1) return false;

    //id fix
    var prefix = "";
    if (id.indexOf("http") === -1) {
      prefix = id.split("_")[0];
      id = prefix + ":" + id;
    }
    else {
      id = "<" + id + ">";
    }

    var query = "SELECT * FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " \n\
                  WHERE { \n\
                    ?subject a risk:risk_factor; ?predicate ?object. \n\
                    ?subject  risk:has_risk_factor_association_type ?has_risk_factor_association_type.  \n\
                    {?subject risk:has_risk_factor_source " + id + "} UNION { ?subject risk:has_risk_factor_target " + id + " }. \n\
                    OPTIONAL {    \n\
                     ?object a risk:risk_element. \n\
                     ?object risk:has_risk_element_name ?has_risk_element_name  \n\
                    } \n\
                  }";

    return CARRE.selectQuery(query).then(function(res) {

      var array = [];
      // { {this} , {links to} , {that} }
      res.data.forEach(function(rf) {

        var source = {
          label: rf.has_risk_factor_source_label,
          id: rf.has_risk_factor_source[0]
        };

        var target = {
          label: rf.has_risk_factor_target_label,
          id: rf.has_risk_factor_target[0]
        };

        var relation = {
          label: rf.has_risk_factor_association_type_label,
          id: rf.id
        };

        array.push({ source, relation, target });

      });

      return array;

    });

  }

  return this.exports;

});<commit_msg>fix risk element associations method<commit_after>angular.module('CarreEntrySystem').service('Risk_elements', function($http, CARRE, CONFIG, QUERY) {

  this.exports = {
    'get': getRisk_elements,
    'save': saveRisk_element,
    'associations': RiskElementAssociations
  };

  function getRisk_elements(ArrayOfIDs) {
    return CARRE.instances('risk_element', ArrayOfIDs);
  }

  function saveRisk_element(oldElem, newElem, user) {
    user = user || CONFIG.currentUser.graphName;
    var updateQuery = "",
      insertQuery = "";
    var newObj = {};
    if (newElem.name.length > 0) newObj.has_risk_element_name = {
      pre: 'risk',
      value: newElem.name.toString(),
      type: "string"
    };
    if (newElem.identifier.length > 0) newObj.has_risk_element_identifier = {
      pre: 'risk',
      value: "http://umls.nlm.nih.gov/sab/mth/cui/" + newElem.identifier.toString(),
      type: "node"
    };
    if (newElem.type.length > 0) newObj.has_risk_element_type = {
      pre: 'risk',
      value: newElem.type.toString(),
      type: "node"
    };
    if (newElem.modifiable_status.length > 0) newObj.has_risk_element_modifiable_status = {
      pre: 'risk',
      value: newElem.modifiable_status.toString(),
      type: "string"
    };
    if (newElem.observables.length > 0) newObj.has_risk_element_observable = {
      pre: 'risk',
      value: newElem.observables,
      type: "node"
    };
    if (newElem.risk_elements.length > 0) newObj.includes_risk_element = {
      pre: 'risk',
      value: newElem.risk_elements,
      type: "node"
    };

    console.log('Old: ', oldElem);
    console.log('New: ', newElem);
    console.log('Mapped: ', newObj);

    if (oldElem.id) {
      /*Update query*/
      updateQuery = QUERY.update(oldElem, newObj);
      console.log('----Update Query----');
      return CARRE.query(updateQuery, 'no prefix');
    }
    else {
      /*Insert query*/
      insertQuery = QUERY.insert(newObj, "risk_element", "RL", user);
      console.info('-----insertQuery------');
      return CARRE.query(insertQuery, 'no prefix');
    }

  }

  function RiskElementAssociations(id) {

    //accept only risk element ids
    if (id.indexOf("RL_") === -1) return false;

    //id fix
    var prefix = "";
    if (id.indexOf("http") === -1) {
      prefix = id.split("_")[0];
      id = prefix + ":" + id;
    }
    else {
      id = "<" + id + ">";
    }

    var query = "SELECT * FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " \n\
                WHERE { \n\
                    ?subject a risk:risk_factor; ?predicate ?object. \n\
                    ?subject  risk:has_risk_factor_association_type ?has_risk_factor_association_type.  \n\
                    {?subject risk:has_risk_factor_source " + id + "} UNION { ?subject risk:has_risk_factor_target " + id + " }. \n\
                    OPTIONAL {    \n\
                     ?object a risk:risk_element. \n\
                     ?object risk:has_risk_element_name ?has_risk_element_name  \n\
                    } \n\
                  }";

    return CARRE.selectQuery(query).then(function(res) {

      var array = [];
      // { {this} , {links to} , {that} }
      res.data.forEach(function(rf) {

        var source = {
          label: rf.has_risk_factor_source_label,
          id: rf.has_risk_factor_source[0]
        };

        var target = {
          label: rf.has_risk_factor_target_label,
          id: rf.has_risk_factor_target[0]
        };

        var relation = {
          label: rf.has_risk_factor_association_type_label,
          id: rf.id
        };

        array.push({source:source, relation:relation, target:target});

      });

      return array;

    });

  }

  return this.exports;

});<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.add.evidence')
    .directive('addEvidenceBasic', addEvidenceBasicDirective)
    .controller('AddEvidenceBasicController', AddEvidenceBasicController);

  // @ngInject
  function addEvidenceBasicDirective() {
    return {
      restrict: 'E',
      scope: {},
      templateUrl: 'app/views/add/evidence/addEvidenceBasic.tpl.html',
      controller: 'AddEvidenceBasicController'
    }
  }

  // @ngInject
  function AddEvidenceBasicController($scope,
                                      Security,
                                      Evidence,
                                      AddEvidenceViewOptions,
                                      formConfig) {
    var vm = $scope.vm = {};

    vm.evidenceModel = Evidence;
    vm.evidenceOptions = AddEvidenceViewOptions;

    vm.isAdmin = Security.isAdmin();
    vm.isAuthenticated = Security.isAuthenticated();

    vm.newEvidence = {
      entrez_id: '',
      variant_name: '',
      description: '',
      disease: '',
      doid: '',
      pubmed_id: '',
      pubchem_id: '',
      drugs: [],
      rating: Number(),
      evidence_level: '',
      evidence_type: '',
      evidence_direction: '',
      clinical_significance: '',
      variant_origin: ''
    };

    //vm.newEvidence = {
    //  entrez_id: '673',
    //  variant_name: 'V600E',
    //  description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut vehicula sed lorem et cursus. In hac habitasse platea dictumst. Sed rhoncus, enim iaculis malesuada scelerisque, quam tortor porttitor tortor, id blandit tellus libero et lectus. Vestibulum nec purus eget purus suscipit ultricies non in dui.',
    //  disease: 'Breast Cancer',
    //  doid: '3908',
    //  pubmed_id: '20979473',
    //  pubchem_id: '33042',
    //  drugs: {
    //    collection: []
    //  },
    //  rating: 4,
    //  evidence_level: 'C',
    //  evidence_type: 'Predictive',
    //  evidence_direction: 'Supports',
    //  clinical_significance: 'Positive',
    //  variant_origin: 'Somatic'
    //};

    vm.newEvidence.comment = { title: '', text:'' };

    vm.formErrors = {};
    vm.formMessages = {};
    vm.errorMessages = formConfig.errorMessages;
    vm.errorPrompts = formConfig.errorPrompts;

    function evidenceLevelChange(value, field, scope) {
      console.log('***** evidenceLevelChanged.');
    }

    vm.formSelects = {
      evidence_levels: [
        { value: 'A', label: 'A - Validated'},
        { value: 'B', label: 'B - Clinical'},
        { value: 'C', label: 'C - Preclinical'},
        { value: 'D', label: 'D - Inferential'},
        { value: 'E', label: 'E - n of 1'}
      ],
      evidence_ratings: [
        { value: 1, label: '1 - Poor' },
        { value: 2, label: '2 - Adequate' },
        { value: 3, label: '3 - Average' },
        { value: 4, label: '4 - Good' },
        { value: 5, label: '5 - Excellent'}
      ],
      clinical_significance: [
        { value: 'Positive', label: 'Positive' },
        { value: 'Better Outcome', label: 'Better Outcome' },
        { value: 'Sensitivity', label: 'Sensitivity' },
        { value: 'Resistance or Non-Response', label: 'Resistance or Non-Response' },
        { value: 'Poor Outcome', label: 'Poor Outcome' },
        { value: 'Negative', label: 'Negative' },
        { value: 'N/A', label: 'N/A' }
      ],

      evidence_directions: [
        { value: 'Supports', label: 'Supports'},
        { value: 'Does Not Support', label: 'Does Not Support' }
      ],
      variant_origins: [
        { value: 'Somatic', label: 'Somatic'},
        { value: 'Germline', label: 'Germline' }
      ]
    };

    vm.evidenceFields = [
      {
        key: 'evidence_type',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Evidence Type',
          value: 'vm.newEvidence.evidence_type',
          options: [
            { value: 'Predictive', label: 'Predictive' },
            { value: 'Diagnostic', label: 'Diagnostic' },
            { value: 'Prognostic', label: 'Prognostic' }
          ],
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Type of clinical outcome associated with the evidence statement.',
          onChange: evidenceLevelChange
        }
      },
      {
        key: 'entrez_id',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Gene Entrez ID',
          value: 'vm.newEvidence.entrez_id',
          minLength: 32,
          helpText: 'Entrez Gene ID (e.g., 673 for BRAF)'
        }
      },
      {
        key: 'variant_name',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Variant Name',
          value: 'vm.newEvidence.variant_name',
          minLength: 32,
          helpText: 'Description of the type of variant (e.g., V600E, BCR-ABL fusion, Loss-of-function, exon 12 mutations). Should be as specific as possible (i.e., specific amino acid changes).'
        }
      },
      {
        key: 'variant_origin',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Variant Origin',
          value: 'vm.newEvidence.variant_origin',
          options: vm.formSelects.variant_origins,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Origin of variant'
        }
      },
      {
        key: 'disease',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Disease',
          value: 'vm.newEvidence.disease',
          minLength: 32,
          helpText: 'Enter the disease or subtype that is associated with this evidence statement. This should be a disease in the disease-ontology that carries a DOID (e.g., 1909 for melanoma). If the disease to be entered is not in the disease ontology, enter it as free text. '
        }
      },
      {
        key: 'doid',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'DOID',
          value: 'vm.newEvidence.doid',
          minLength: 8,
          length: 8,
          helpText: 'Disease Ontology ID of the specific disease or disease subtype associated with the evidence statement (e.g., 1909 for melanoma).'
        }
      },
      {
        key: 'description',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 5,
          label: 'Description',
          value: 'vm.newEvidence.description',
          minLength: 32,
          helpText: 'Description of evidence from published medical literature detailing the association of or lack of association of a variant with diagnostic, prognostic or predictive value in relation to a specific disease (and treatment for predictive evidence). Data constituting protected health information (PHI) should not be entered. Please familiarize yourself with your jurisdiction\'s definition of PHI before contributing.'
        }
      },
      {
        key: 'pubmed_id',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Pubmed Id',
          value: 'vm.newEvidence.pubmed_id',
          minLength: 8,
          length: 8,
          helpText: 'PubMed ID for the publication associated with the evidence statement (e.g. 23463675)'
        }
      },
      {
        key: 'pubchem_id',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Pubchem Id',
          value: 'vm.newEvidence.pubchem_id',
          helpText: 'For predictive evidence, the PubChem ID for relevant drug (e.g., 44462760 for Dabrafenib).'
        }
      },
      {
        template: '
'
      },
      {
        key: 'evidence_level',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Evidence Level',
          value: 'vm.newEvidence.rating',
          options: vm.formSelects.evidence_levels,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Description of the study performed to produce the evidence statement'
        }
      },
      {
        key: 'rating',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Rating',
          options: vm.formSelects.evidence_ratings,
          valueProp: 'value',
          labelProp: 'label',
          helpText: [
                   '
Please rate your evidence according to the following scale, basing your subjective evaluation on the following guidelines:
',
                   '
',
                   '
One Star: Claim is not supported well by experimental evidence. Results are not reproducible, or have very small sample size. No follow-up is done to validate novel claims.
',
                   '
Two Stars: Evidence is not well supported by experimental data, and little follow-up data is available. Publication is from a journal with low academic impact. Experiments may lack proper controls, have small sample size, or are not statistically convincing.
',
                   '
Three Stars: Evidence is convincing, but not supported by a breadth of experiments. May be smaller scale projects, or novel results without many follow-up experiments. Discrepancies from expected results are explained and not concerning.
',
                   '
Four Stars: Strong, well supported evidence. Experiments are well controlled, and results are convincing. Any discrepancies from expected results are well-explained and not concerning.
',
                   '
Five Stars: Strong, well supported evidence from a lab or journal with respected academic standing. Experiments are well controlled, and results are clean and reproducible across multiple replicates. Evidence confirmed using separate methods.
'].join(" ")
        }
      },
      {
        key: 'evidence_direction',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Evidence Direction',
          value: 'vm.newEvidence.evidence_direction',
          options: vm.formSelects.evidence_directions,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'A indicator of whether the evidence statement supports or refutes the clinical significance of an event.'
        }
      },
      {
        key: 'clinical_significance',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Clinical Significance',
          value: 'vm.newEvidence.clinical_significance',
          options: vm.formSelects.clinical_significance,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Positive or negative association of the Variant with predictive, prognostic, or diagnostic evidence types. If the variant was not associated with a positive or negative outcome, Not Applicable should be selected.'
        },
        data: {
          predictiveOpts: [ 'Sensitivity', 'Resistance or Non-Resistance'],
          prognosticOpts: ['Better Outcome', 'Poor Outcome'],
          diagnosticOpts: ['Positive', 'Negative']
        }
      },
      { template: '
'},
      {
        type: 'horizontalInputHelp',
        key: 'title',
        model: vm.newEvidence.comment,
        templateOptions: {
          label: 'Comment Title',
          value: 'title',
          helpText: 'First Comment Title'
        }
      },
      {
        key: 'text',
        type: 'horizontalTextareaHelp',
        model: vm.newEvidence.comment,
        templateOptions: {
          rows: 5,
          label: 'Comment',
          value: 'text',
          helpText: 'First Comment Text'
        }
      }
    ];

    vm.submit = function(newEvidence, options) {
      newEvidence.evidenceId = newEvidence.id;
      vm.formErrors = {};
      vm.formMessages = {};
      Evidence.add(newEvidence)
        .then(function(response) {
          console.log('add evidence success!');
          vm.formMessages['submitSuccess'] = true;
          // options.resetModel();
        })
        .catch(function(error) {
          console.error('add evidence error!');
          vm.formErrors[error.status] = true;
        })
        .finally(function(){
          console.log('add evidence done!');
        });
    };
  }

})();
<commit_msg>commented out pubchem ID field from add evidence form<commit_after>(function() {
  'use strict';
  angular.module('civic.add.evidence')
    .directive('addEvidenceBasic', addEvidenceBasicDirective)
    .controller('AddEvidenceBasicController', AddEvidenceBasicController);

  // @ngInject
  function addEvidenceBasicDirective() {
    return {
      restrict: 'E',
      scope: {},
      templateUrl: 'app/views/add/evidence/addEvidenceBasic.tpl.html',
      controller: 'AddEvidenceBasicController'
    }
  }

  // @ngInject
  function AddEvidenceBasicController($scope,
                                      Security,
                                      Evidence,
                                      AddEvidenceViewOptions,
                                      formConfig) {
    var vm = $scope.vm = {};

    vm.evidenceModel = Evidence;
    vm.evidenceOptions = AddEvidenceViewOptions;

    vm.isAdmin = Security.isAdmin();
    vm.isAuthenticated = Security.isAuthenticated();

    vm.newEvidence = {
      entrez_id: '',
      variant_name: '',
      description: '',
      disease: '',
      doid: '',
      pubmed_id: '',
      //pubchem_id: '',
      drugs: [],
      rating: Number(),
      evidence_level: '',
      evidence_type: '',
      evidence_direction: '',
      clinical_significance: '',
      variant_origin: ''
    };

    //vm.newEvidence = {
    //  entrez_id: '673',
    //  variant_name: 'V600E',
    //  description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut vehicula sed lorem et cursus. In hac habitasse platea dictumst. Sed rhoncus, enim iaculis malesuada scelerisque, quam tortor porttitor tortor, id blandit tellus libero et lectus. Vestibulum nec purus eget purus suscipit ultricies non in dui.',
    //  disease: 'Breast Cancer',
    //  doid: '3908',
    //  pubmed_id: '20979473',
    //  pubchem_id: '33042',
    //  drugs: {
    //    collection: []
    //  },
    //  rating: 4,
    //  evidence_level: 'C',
    //  evidence_type: 'Predictive',
    //  evidence_direction: 'Supports',
    //  clinical_significance: 'Positive',
    //  variant_origin: 'Somatic'
    //};

    vm.newEvidence.comment = { title: '', text:'' };

    vm.formErrors = {};
    vm.formMessages = {};
    vm.errorMessages = formConfig.errorMessages;
    vm.errorPrompts = formConfig.errorPrompts;

    function evidenceLevelChange(value, field, scope) {
      console.log('***** evidenceLevelChanged.');
    }

    vm.formSelects = {
      evidence_levels: [
        { value: 'A', label: 'A - Validated'},
        { value: 'B', label: 'B - Clinical'},
        { value: 'C', label: 'C - Preclinical'},
        { value: 'D', label: 'D - Inferential'},
        { value: 'E', label: 'E - n of 1'}
      ],
      evidence_ratings: [
        { value: 1, label: '1 - Poor' },
        { value: 2, label: '2 - Adequate' },
        { value: 3, label: '3 - Average' },
        { value: 4, label: '4 - Good' },
        { value: 5, label: '5 - Excellent'}
      ],
      clinical_significance: [
        { value: 'Positive', label: 'Positive' },
        { value: 'Better Outcome', label: 'Better Outcome' },
        { value: 'Sensitivity', label: 'Sensitivity' },
        { value: 'Resistance or Non-Response', label: 'Resistance or Non-Response' },
        { value: 'Poor Outcome', label: 'Poor Outcome' },
        { value: 'Negative', label: 'Negative' },
        { value: 'N/A', label: 'N/A' }
      ],

      evidence_directions: [
        { value: 'Supports', label: 'Supports'},
        { value: 'Does Not Support', label: 'Does Not Support' }
      ],
      variant_origins: [
        { value: 'Somatic', label: 'Somatic'},
        { value: 'Germline', label: 'Germline' }
      ]
    };

    vm.evidenceFields = [
      {
        key: 'evidence_type',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Evidence Type',
          value: 'vm.newEvidence.evidence_type',
          options: [
            { value: 'Predictive', label: 'Predictive' },
            { value: 'Diagnostic', label: 'Diagnostic' },
            { value: 'Prognostic', label: 'Prognostic' }
          ],
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Type of clinical outcome associated with the evidence statement.',
          onChange: evidenceLevelChange
        }
      },
      {
        key: 'entrez_id',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Gene Entrez ID',
          value: 'vm.newEvidence.entrez_id',
          minLength: 32,
          helpText: 'Entrez Gene ID (e.g., 673 for BRAF)'
        }
      },
      {
        key: 'variant_name',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Variant Name',
          value: 'vm.newEvidence.variant_name',
          minLength: 32,
          helpText: 'Description of the type of variant (e.g., V600E, BCR-ABL fusion, Loss-of-function, exon 12 mutations). Should be as specific as possible (i.e., specific amino acid changes).'
        }
      },
      {
        key: 'variant_origin',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Variant Origin',
          value: 'vm.newEvidence.variant_origin',
          options: vm.formSelects.variant_origins,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Origin of variant'
        }
      },
      {
        key: 'disease',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Disease',
          value: 'vm.newEvidence.disease',
          minLength: 32,
          helpText: 'Enter the disease or subtype that is associated with this evidence statement. This should be a disease in the disease-ontology that carries a DOID (e.g., 1909 for melanoma). If the disease to be entered is not in the disease ontology, enter it as free text. '
        }
      },
      {
        key: 'doid',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'DOID',
          value: 'vm.newEvidence.doid',
          minLength: 8,
          length: 8,
          helpText: 'Disease Ontology ID of the specific disease or disease subtype associated with the evidence statement (e.g., 1909 for melanoma).'
        }
      },
      {
        key: 'description',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 5,
          label: 'Description',
          value: 'vm.newEvidence.description',
          minLength: 32,
          helpText: 'Description of evidence from published medical literature detailing the association of or lack of association of a variant with diagnostic, prognostic or predictive value in relation to a specific disease (and treatment for predictive evidence). Data constituting protected health information (PHI) should not be entered. Please familiarize yourself with your jurisdiction\'s definition of PHI before contributing.'
        }
      },
      {
        key: 'pubmed_id',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Pubmed Id',
          value: 'vm.newEvidence.pubmed_id',
          minLength: 8,
          length: 8,
          helpText: 'PubMed ID for the publication associated with the evidence statement (e.g. 23463675)'
        }
      },
      //{
      //  key: 'pubchem_id',
      //  type: 'horizontalInputHelp',
      //  templateOptions: {
      //    label: 'Pubchem Id',
      //    value: 'vm.newEvidence.pubchem_id',
      //    helpText: 'For predictive evidence, the PubChem ID for relevant drug (e.g., 44462760 for Dabrafenib).'
      //  }
      //},
      {
        template: '
'
      },
      {
        key: 'evidence_level',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Evidence Level',
          value: 'vm.newEvidence.rating',
          options: vm.formSelects.evidence_levels,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Description of the study performed to produce the evidence statement'
        }
      },
      {
        key: 'rating',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Rating',
          options: vm.formSelects.evidence_ratings,
          valueProp: 'value',
          labelProp: 'label',
          helpText: [
                   '
Please rate your evidence according to the following scale, basing your subjective evaluation on the following guidelines:
',
                   '
',
                   '
One Star: Claim is not supported well by experimental evidence. Results are not reproducible, or have very small sample size. No follow-up is done to validate novel claims.
',
                   '
Two Stars: Evidence is not well supported by experimental data, and little follow-up data is available. Publication is from a journal with low academic impact. Experiments may lack proper controls, have small sample size, or are not statistically convincing.
',
                   '
Three Stars: Evidence is convincing, but not supported by a breadth of experiments. May be smaller scale projects, or novel results without many follow-up experiments. Discrepancies from expected results are explained and not concerning.
',
                   '
Four Stars: Strong, well supported evidence. Experiments are well controlled, and results are convincing. Any discrepancies from expected results are well-explained and not concerning.
',
                   '
Five Stars: Strong, well supported evidence from a lab or journal with respected academic standing. Experiments are well controlled, and results are clean and reproducible across multiple replicates. Evidence confirmed using separate methods.
'].join(" ")
        }
      },
      {
        key: 'evidence_direction',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Evidence Direction',
          value: 'vm.newEvidence.evidence_direction',
          options: vm.formSelects.evidence_directions,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'A indicator of whether the evidence statement supports or refutes the clinical significance of an event.'
        }
      },
      {
        key: 'clinical_significance',
        type: 'horizontalSelectHelp',
        templateOptions: {
          label: 'Clinical Significance',
          value: 'vm.newEvidence.clinical_significance',
          options: vm.formSelects.clinical_significance,
          valueProp: 'value',
          labelProp: 'label',
          helpText: 'Positive or negative association of the Variant with predictive, prognostic, or diagnostic evidence types. If the variant was not associated with a positive or negative outcome, Not Applicable should be selected.'
        },
        data: {
          predictiveOpts: [ 'Sensitivity', 'Resistance or Non-Resistance'],
          prognosticOpts: ['Better Outcome', 'Poor Outcome'],
          diagnosticOpts: ['Positive', 'Negative']
        }
      },
      { template: '
'},
      {
        type: 'horizontalInputHelp',
        key: 'title',
        model: vm.newEvidence.comment,
        templateOptions: {
          label: 'Comment Title',
          value: 'title',
          helpText: 'First Comment Title'
        }
      },
      {
        key: 'text',
        type: 'horizontalTextareaHelp',
        model: vm.newEvidence.comment,
        templateOptions: {
          rows: 5,
          label: 'Comment',
          value: 'text',
          helpText: 'First Comment Text'
        }
      }
    ];

    vm.submit = function(newEvidence, options) {
      newEvidence.evidenceId = newEvidence.id;
      vm.formErrors = {};
      vm.formMessages = {};
      Evidence.add(newEvidence)
        .then(function(response) {
          console.log('add evidence success!');
          vm.formMessages['submitSuccess'] = true;
          // options.resetModel();
        })
        .catch(function(error) {
          console.error('add evidence error!');
          vm.formErrors[error.status] = true;
        })
        .finally(function(){
          console.log('add evidence done!');
        });
    };
  }

})();
<|endoftext|>


<commit_before>describe('Smooth Scroll', function () {

	//
	// Helper Methods
	//

	/**
	* Create a link element, add it to the body.
	* @public
	* @param {String} the href attribute of the new link
	* @param {Boolean} whether to add data-scroll to the link or not
	* @returns {Element}
	*/
	var injectElem = function (href, smooth) {
		var elt = document.createElement('a');
		elt.href = href;
		if (smooth) {
			elt.setAttribute('data-scroll', true);
		}
		document.body.appendChild(elt);
		return elt;
	};

	/**
	* Simulate a click event.
	* @public
	* @param {Element} the element to simulate a click on
	*/
	var simulateClick = function (elt) {
		var click = document.createEvent('MouseEvents');
		click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		elt.dispatchEvent(click);
	};

	// A pattern for settings to validate their format.
	var settingsStub = {
		speed: jasmine.any(Number),
		easing: jasmine.any(String),
		offset: jasmine.any(Number),
		updateURL: jasmine.any(Boolean),
		callback: jasmine.any(Function)
	};

	//
	// Init
	//

	describe('Should initialize plugin', function () {
		it('Should export the smoothScroll module', function () {
			expect(smoothScroll).toBeDefined();
		});

		it('Should expose public functions', function () {
			expect(smoothScroll.init).toEqual(jasmine.any(Function));
			expect(smoothScroll.destroy).toEqual(jasmine.any(Function));
			expect(smoothScroll.animateScroll).toEqual(jasmine.any(Function));
		});

		it('Should add event listeners', function () {
			spyOn(document, 'addEventListener');
			smoothScroll.init();
			expect(document.addEventListener).toHaveBeenCalledWith('click', jasmine.any(Function), false);

			spyOn(document, 'removeEventListener');
			smoothScroll.destroy();
			expect(document.removeEventListener).toHaveBeenCalledWith('click', jasmine.any(Function), false);
		});
	});

	describe('Should merge user options into defaults', function () {

		var elt = injectElem('#anchor', true);

		beforeEach(function () {
			smoothScroll.init({
				callback: function () { document.documentElement.classList.add('callback'); }
			});
		});

		it('User options should be merged into defaults', function () {
			simulateClick(elt);
			setTimeout(function() {
				expect(document.documentElement.classList.contains('callback')).toBe(true);
			}, 200);
		});

	});

	//
	// Events
	//

	describe('Should animate scroll when anchor clicked', function () {
		var elt = injectElem('#anchor', true);
		document.body.id = 'anchor';

		beforeEach(function() {
			spyOn(smoothScroll, 'animateScroll');
		});

		afterEach(function () {
			smoothScroll.destroy();
		});

		it('Should trigger smooth scrolling on click', function () {
			smoothScroll.init();
			simulateClick(elt);
			setTimeout(function() {
				expect(smoothScroll.animateScroll).toHaveBeenCalledWith(elt, '#anchor', jasmine.objectContaining(settingsStub));
			}, 200);
		});

		it('Should do nothing if not initialized', function () {
			simulateClick(elt);
			expect(smoothScroll.animateScroll).not.toHaveBeenCalled();
		});

		it('Should do nothing if destroyed', function () {
			smoothScroll.init();
			smoothScroll.destroy();
			simulateClick(elt);
			setTimeout(function() {
				expect(smoothScroll.animateScroll).not.toHaveBeenCalled();
			}, 200);
		});
	});
});<commit_msg>Fix tests<commit_after>describe('Smooth Scroll', function () {

	//
	// Helper Methods
	//
	var removeElements = function() {
		var p = document.querySelector('p');
		if (p && p.remove) {
			p.remove();
		}
		var a = document.querySelector('a');
		if (a && a.remove) {
			a.remove();
		}
		var target = document.querySelector('div');
		if (target && target.remove) {
			target.remove();
		}
	};
	/**
	 * Create a link element, add it to the body.
	 * @public
	 * @param {String} the href attribute of the new link
	 * @param {Boolean} whether to add data-scroll to the link or not
	 * @returns {Element}
	 */
	var injectElem = function (href, smooth) {
		removeElements();

		var elt = document.createElement('a');
		elt.href = href;
		elt.style.background = '#f0f';
		elt.textContent="newtext";
		if (smooth) {
			elt.setAttribute('data-scroll', true);
		}
		document.body.appendChild(elt);

		var p = document.createElement('p');
		p.style.height = '20000px';
		p.style.background = '#f00';
		document.body.appendChild(p);

		var target = document.createElement('div');
		target.id = 'target';
		target.style.height = '200px';
		target.style.background = '#0ff';
		document.body.appendChild(target);
		window.top.callPhantom({type: 'render', fname: './myscreen.png'});
		return elt;
	};

	/**
	 * Simulate a click event.
	 * @public
	 * @param {Element} the element to simulate a click on
	 */
	var simulateClick = function (elt) {
		var click = document.createEvent('MouseEvents');
		click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		elt.dispatchEvent(click);
	};

	// A pattern for settings to validate their format.
	var settingsStub = {
		speed: jasmine.any(Number),
		easing: jasmine.any(String),
		offset: jasmine.any(Number),
		updateURL: jasmine.any(Boolean),
		callback: jasmine.any(Function)
	};

	//
	// Init
	//

	describe('Should initialize plugin', function () {
		it('Should export the smoothScroll module', function () {
			expect(smoothScroll).toBeDefined();
		});

		it('Should expose public functions', function () {
			expect(smoothScroll.init).toEqual(jasmine.any(Function));
			expect(smoothScroll.destroy).toEqual(jasmine.any(Function));
			expect(smoothScroll.animateScroll).toEqual(jasmine.any(Function));
		});

		it('Should add event listeners', function () {
			spyOn(document, 'addEventListener');
			smoothScroll.init();
			expect(document.addEventListener).toHaveBeenCalledWith('click', jasmine.any(Function), false);

			spyOn(document, 'removeEventListener');
			smoothScroll.destroy();
			expect(document.removeEventListener).toHaveBeenCalledWith('click', jasmine.any(Function), false);
		});
	});

	describe('Should merge user options into defaults', function () {

		var elt = injectElem('#target', true);

		beforeEach(function () {
			smoothScroll.init({
				callback: function () { document.documentElement.classList.add('callback'); }
			});
		});

		it('User options should be merged into defaults', function (done) {
			simulateClick(elt);
			setTimeout(function() {
				expect(document.documentElement.classList.contains('callback')).toBe(true);
				done();
			}, 200);
		});

	});

	//
	// Events
	//

	describe('Should animate scroll when anchor clicked', function () {
		var elt = injectElem('#target', true);
		// document.body.id = 'anchor';

		beforeEach(function() {
			spyOn(smoothScroll, 'animateScroll');
		});

		afterEach(function () {
			smoothScroll.destroy();
		});

		it('Should trigger smooth scrolling on click', function (done) {
			smoothScroll.init();
			simulateClick(elt);
			setTimeout(function() {
				expect(smoothScroll.animateScroll).toHaveBeenCalledWith('#target', elt, jasmine.objectContaining(settingsStub));
				done();
			}, 200);
		});

		it('Should do nothing if not initialized', function () {
			simulateClick(elt);
			expect(smoothScroll.animateScroll).not.toHaveBeenCalled();
		});

		it('Should do nothing if destroyed', function (done) {
			smoothScroll.init();
			smoothScroll.destroy();
			simulateClick(elt);
			setTimeout(function() {
				expect(smoothScroll.animateScroll).not.toHaveBeenCalled();
				done();
			}, 200);
		});
	});
});
<|endoftext|>