text:
const { browserStackErrorReporter } = requireHelper('browserstack-error-reporter');
const utils = requireHelper('e2e-utils');
const config = requireHelper('e2e-config');
requireHelper('rejection');

const axePageObjects = requireHelper('axe-page-objects');

jasmine.getEnv().addReporter(browserStackErrorReporter);

const clickOnMultiselect = async () => {
  const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).first();
  await browser.driver
    .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
  await multiselectEl.click();
};

const setTimer = () => {
  let starttime = 0;
  browser.controlFlow().execute(() => {
    starttime = Date.now();
  });
  return {
    get elapsed() {
      return browser.controlFlow().execute(() => Date.now() - starttime);
    }
  };
};

describe('Multiselect example-states tests', () => {
  beforeEach(async () => {
    await utils.setPage('/components/multiselect/example-states');
  });

  it('Should not have errors', async () => {
    await utils.checkForErrors();
  });

  it('Should open multiselect list on click', async () => {
    await clickOnMultiselect();
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(element(by.className('is-open'))), config.waitsFor);

    expect(await element(by.className('is-open')).isDisplayed()).toBe(true);
  });

  it('Should scroll down to end of list, and Vermont should be visible', async () => {
    await clickOnMultiselect();
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(element(by.className('is-open'))), config.waitsFor);

    await browser.executeScript('document.querySelector("ul[role=\'listbox\']").scrollTop = 10000');
    const multiselectElList = await element(by.css('ul[role="listbox"]'));
    const vermontOption = await element(by.css('li[data-val="VT"]'));
    const posVT = await vermontOption.getLocation();
    const multiselectElListSize = await multiselectElList.getSize();
    const posMultiselectElList = await multiselectElList.getLocation();

    expect(posVT.y > posMultiselectElList.y &&
      posVT.y < (posMultiselectElList.y + multiselectElListSize.height)).toBeTruthy();
  });

  if (!utils.isSafari()) {
    xit('Should show validation message error "Required" on tab out', async () => {
      // Disabled until dropdown fixes are in 4.9
      const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).get(2);
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
      await multiselectEl.sendKeys(protractor.Key.TAB);
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(element(by.className('message-text'))), config.waitsFor);

      expect(await element(by.css('.message-text')).getText()).toEqual('Required');
    });

    xit('Should show validation message error "Required" on click', async () => {
      // Disabled until dropdown fixes are in 4.9
      const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).get(2);
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
      await element(by.css('body')).sendKeys(protractor.Key.TAB);
      await element(by.css('body')).sendKeys(protractor.Key.TAB);
      await element(by.css('body')).sendKeys(protractor.Key.TAB);
      await multiselectEl.sendKeys(protractor.Key.ENTER);
      await multiselectEl.sendKeys(protractor.Key.ENTER);
      await multiselectEl.sendKeys(protractor.Key.ENTER);
      await element.all(by.css('.trigger')).first().click();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(element(by.className('message-text'))), config.waitsFor);

      expect(await element(by.css('.message-text')).getText()).toEqual('Required');
    });
  }

  if (!utils.isIE()) {
    xit('Should be accessible on init with no WCAG 2AA violations', async () => {
      await clickOnMultiselect();
      const res = await axePageObjects(browser.params.theme);

      expect(res.violations.length).toEqual(0);
    });
  }
});

describe('Multiselect example-index tests', () => {
  beforeEach(async () => {
    await utils.setPage('/components/multiselect/example-index');
  });

  if (!utils.isSafari()) {
    it('Should arrow down to Arizona, and focus', async () => {
      const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).first();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
      await multiselectEl.click();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(await element(by.css('ul[role="listbox"]'))), config.waitsFor);
      const multiselectSearchEl = await element(by.id('dropdown-search'));
      await multiselectSearchEl.click();
      await multiselectSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await multiselectSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(await element(by.className('is-focused'))), config.waitsFor);

      expect(await element(by.className('is-focused')).getText()).toEqual('Arizona');
    });

    it('Should tab into deselect Alaska then tab out and input should be empty', async () => {
      const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).first();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
      await element(by.css('body')).sendKeys(protractor.Key.TAB);
      await element(by.css('body')).sendKeys(protractor.Key.TAB);
      await element(by.css('body')).sendKeys(protractor.Key.TAB);
      await multiselectEl.sendKeys(protractor.Key.ENTER);
      const multiselectSearchEl = await element(by.id('dropdown-search'));
      await multiselectSearchEl.sendKeys(protractor.Key.ENTER);
      await multiselectSearchEl.sendKeys(protractor.Key.TAB);

      expect(await element.all(by.css('.dropdown span')).first().getText()).toEqual('');
    });

    it('Should arrow down to Arizona select, arrow down, and select Arkansas, and update search input', async () => {
      const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).first();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
      await multiselectEl.click();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(await element(by.css('ul[role="listbox"]'))), config.waitsFor);
      const multiselectSearchEl = await element(by.id('dropdown-search'));
      await multiselectSearchEl.click();
      await multiselectSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await multiselectSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await multiselectSearchEl.sendKeys(protractor.Key.ENTER);
      await multiselectSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await multiselectSearchEl.sendKeys(protractor.Key.ENTER);

      expect(await element(by.className('is-focused')).getText()).toEqual('Arkansas');
      const multiselectSearchElVal = element(by.id('dropdown-search')).getAttribute('value');

      expect(await multiselectSearchElVal).toEqual('Alaska, Arizona, Arkansas');
    });
  }

  if (utils.isChrome() && utils.isCI()) {
    it('Should not visual regress', async () => {
      const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).first();
      const multiselectElList = await element(by.id('dropdown-list'));
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
      await browser.driver.sleep(config.waitsFor);

      expect(await browser.protractorImageComparison.checkElement(multiselectEl, 'multiselect-init')).toEqual(0);

      await clickOnMultiselect();
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(multiselectElList), config.waitsFor);
      await browser.driver.sleep(config.waitsFor);

      expect(await browser.protractorImageComparison.checkElement(multiselectElList, 'multiselect-open')).toEqual(0);
    });
  }

  it('Should search for Colorado', async () => {
    const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).first();
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);
    await multiselectEl.click();
    await element(by.id('dropdown-search')).click();
    await browser.driver.switchTo().activeElement().clear();
    await element(by.id('dropdown-search')).sendKeys('Colorado');
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(await element(by.css('.is-focused i'))), config.waitsFor);

    expect(await element(by.className('is-focused')).getText()).toEqual('Colorado');
  });

  it('Should do nothing on disabled', async () => {
    const multiselectEl = await element.all(by.css('div[aria-controls="dropdown-list"]')).get(1);
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(multiselectEl), config.waitsFor);

    expect(await element.all(by.className('is-disabled')).first().getAttribute('disabled')).toBeTruthy();
    await multiselectEl.click();

    expect(await element.all(by.className('is-disabled')).first().getAttribute('disabled')).toBeTruthy();
  });
});

describe('Multiselect example-clear-all tests', () => {
  beforeEach(async () => {
    await utils.setPage('/components/multiselect/example-clear-all');
  });

  if (!utils.isSafari()) {
    it('Should clear all', async () => {
      const buttonEl = await element(by.id('btn-clear'));
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(buttonEl), config.waitsFor);

      expect(await element(by.css('.dropdown span')).getText()).toEqual('Orange');
      await buttonEl.click();
      await browser.driver
        .wait(protractor.ExpectedConditions.textToBePresentInElement(await element.all(by.css('.dropdown span')).first(), ''), config.waitsFor);

      expect(await element(by.css('.dropdown span')).getText()).toEqual('');
    });
  }
});

describe('Multiselect example-select-all-performance tests', () => {
  beforeEach(async () => {
    await utils.setPage('/components/multiselect/test-select-all-performance');
  });

  xit('Should select all performance test', async () => {
    const timer = setTimer();
    await clickOnMultiselect();
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(element(by.className('is-open'))), config.waitsFor);

    const all = await element.all(by.css('.dropdown-option')).count();
    const selectAll = element(by.css('li.dropdown-select-all-list-item'));
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(selectAll), config.waitsFor);

    await selectAll.click();
    const selected = await element.all(by.css('.dropdown-option.is-selected')).count();

    expect(selected).toEqual(all);
    expect(timer.elapsed).toBeLessThan(1300);
  });

  xit('Should clear all selected performance test', async () => {
    const timer = setTimer();
    await clickOnMultiselect();
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(element(by.className('is-open'))), config.waitsFor);

    const all = await element.all(by.css('.dropdown-option')).count();
    const selectAll = element(by.css('li.dropdown-select-all-list-item'));
    await browser.driver
      .wait(protractor.ExpectedConditions.presenceOf(selectAll), config.waitsFor);

    await selectAll.click();
    let selected = await element.all(by.css('.dropdown-option.is-selected')).count();

    expect(selected).toEqual(all);

    await selectAll.click();
    selected = await element.all(by.css('.dropdown-option.is-selected')).count();

    expect(selected).toEqual(0);
    expect(timer.elapsed).toBeLessThan(2200);
  });
});

describe('Multiselect typeahead-reloading tests', () => {
  beforeEach(async () => {
    await utils.setPage('/components/multiselect/test-reload-typeahead');
  });

  if (!utils.isSafari()) {
    it('Should make ajax calls properly on typeahead for multiple items', async () => {
      // Open the list
      const dropdownEl = await element(by.css('div[aria-controls="dropdown-list"]'));
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(dropdownEl), config.waitsFor);

      await dropdownEl.sendKeys(protractor.Key.ARROW_DOWN);
      await browser.driver
        .wait(protractor.ExpectedConditions.presenceOf(await element(by.css('.dropdown.is-open'))), config.waitsFor);
      const dropdownSearchEl = await element(by.id('dropdown-search'));
      await dropdownSearchEl.click();

      // Search for "new" and select "New Jersey"
      // NOTE: Sleep simulates the Multiselect's default typeahead delay (300ms)
      await dropdownSearchEl.sendKeys('New');
      await browser.driver.sleep(config.sleep);
      await dropdownSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await dropdownSearchEl.sendKeys(protractor.Key.ENTER);

      // Search for "new" and select "New York"
      await dropdownSearchEl.sendKeys('New');
      await browser.driver.sleep(config.sleep);
      await dropdownSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await dropdownSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await dropdownSearchEl.sendKeys(protractor.Key.ARROW_DOWN);
      await dropdownSearchEl.sendKeys(protractor.Key.ENTER);

      expect(await element(by.css('.dropdown span')).getText()).toEqual('New Jersey, New York');
    });
  }
});


text:
import React from "react";
import ContentType from "./ContentType";
import ActionType from "./ActionType";
import { GenerateGUID } from "../Utils";

const DefaultMessage = {
  CurrentID: undefined,
  RoomID: undefined,
  MessageContent: {
    ActionType: undefined,
    ContentType: undefined,
    ContentValue: undefined
  }
};

function GetDefaultObject() {
  return Object.assign({}, DefaultMessage);
}

const MessageBuilder = {
  AppConnected: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.APP_CONNECTED;
    returnMessage.MessageContent.ContentType = ContentType.TEXT_PLAIN;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  AppDisconected: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.APP_DISCONNECTED;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  HostConnected: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.HOST_CONNECTED;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  HostDisconnected: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.HOST_DISCONNECTED;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  AnexoPedidoMedico: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.PEDIDO_MEDICO_ANEXO;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_BASE64;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  Texto: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.ENVIAR_TEXTO_LAUDO;
    returnMessage.MessageContent.ContentType = ContentType.TEXT_PLAIN;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  Audio: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.DITADO_AUDIO;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_BASE64;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  StateChanged: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.STATE_CHANGED;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  Laudar: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.ATALHO_ACAO_LAUDAR;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  Revisar: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.ATALHO_ACAO_REVISAR;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  LaudarRevisar: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType =
      ActionType.ATALHO_ACAO_LAUDAR_REVISAR;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  ReconhecimentoSTT: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.RECONHECIMENTO_VOZ_STT;
    returnMessage.MessageContent.ContentType = ContentType.TEXT_PLAIN;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  },
  ComandoAssistente: content => {
    let returnMessage = GetDefaultObject();
    returnMessage.CurrentID = GenerateGUID();
    returnMessage.RoomID = "";
    returnMessage.MessageContent.ActionType = ActionType.COMANDO_ASSISTENTE;
    returnMessage.MessageContent.ContentType = ContentType.APPLICATION_JSON;
    returnMessage.MessageContent.ContentValue = content;
    return returnMessage;
  }
};

export { MessageBuilder, ContentType, ActionType };

domain: javascript


text:
function getText(s)
    {
    switch(s)
        {
        case "Cannot delete Asset Base Folder.":return "Impossible d'effacer le r\u00E9pertoire racine.";
        case "Delete this file ?":return "Voulez vous effacer ce fichier ?";
        case "Uploading...":return "publication en cours...";
        case "File already exists. Do you want to replace it?":return "File already exists. Do you want to replace it?"

		case "Files": return "Fichiers";
		case "del": return "Effacer";
		case "Empty...": return "Empty...";
        }
    }
function loadText()
    {
    var txtLang = document.getElementsByName("txtLang");
    txtLang[0].innerHTML = "Nouveau r\u00E9pertoire";
    txtLang[1].innerHTML = "Effacer le r\u00E9pertoire";
    txtLang[2].innerHTML = "Publier un fichier";

	var optLang = document.getElementsByName("optLang");
    optLang[0].text = "Tous les fichiers";
    optLang[1].text = "Media";
    optLang[2].text = "Images";
    optLang[3].text = "Flash";

    document.getElementById("btnOk").value = " ok ";
    document.getElementById("btnUpload").value = "publier";
    }
function writeTitle()
    {
    document.write("<title>Gestionnaire de fichiers</title>")
    }


text:
const createSubscriber = require('../../../../../../controllers/api/guilds/feeds/subscribers/createSubscriber.js')
const roleServices = require('../../../../../../services/role.js')
const userServices = require('../../../../../../services/user.js')
const subscriberServices = require('../../../../../../services/subscriber.js')
const createError = require('../../../../../../util/createError.js')
const {
  createResponse,
  createNext
} = require('../../../../../mocks/express.js')

jest.mock('../../../../../../services/role.js')
jest.mock('../../../../../../services/user.js')
jest.mock('../../../../../../services/subscriber.js')
jest.mock('../../../../../../util/createError.js')

describe('Unit::controllers/api/guilds/feeds/subscribers/createSubscriber', function () {
  afterEach(function () {
    roleServices.isRoleOfGuild.mockReset()
    userServices.getMemberOfGuild.mockReset()
    subscriberServices.createSubscriber.mockReset()
  })
  it('returns the created subscriber for user', async function () {
    const req = {
      params: {},
      body: {
        type: 'user'
      }
    }
    const json = jest.fn()
    const res = {
      status: jest.fn(() => ({ json }))
    }
    const createdSubscriber = 3245634
    userServices.getMemberOfGuild.mockResolvedValue({})
    subscriberServices.createSubscriber.mockResolvedValue(createdSubscriber)
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(next).not.toHaveBeenCalled()
    expect(res.status).toHaveBeenCalledWith(201)
    expect(json).toHaveBeenCalledWith(createdSubscriber)
  })
  it('returns the created subscriber for role', async function () {
    const req = {
      params: {},
      body: {
        type: 'role'
      }
    }
    const json = jest.fn()
    const res = {
      status: jest.fn(() => ({ json }))
    }
    const createdSubscriber = 3245634
    roleServices.isRoleOfGuild.mockResolvedValue(true)
    subscriberServices.createSubscriber.mockResolvedValue(createdSubscriber)
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(next).not.toHaveBeenCalled()
    expect(res.status).toHaveBeenCalledWith(201)
    expect(json).toHaveBeenCalledWith(createdSubscriber)
  })
  it('calls next with error if role service fails fail', async function () {
    const req = {
      params: {},
      body: {
        type: 'role'
      }
    }
    const json = jest.fn()
    const res = {
      status: jest.fn(() => ({ json }))
    }
    const error = new Error('etwsgry')
    roleServices.isRoleOfGuild.mockRejectedValue(error)
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(next).toHaveBeenCalledWith(error)
  })
  it('calls next with error if user service fails fail', async function () {
    const req = {
      params: {},
      body: {
        type: 'user'
      }
    }
    const res = createResponse()
    const error = new Error('etwsgry')
    userServices.getMemberOfGuild.mockRejectedValue(error)
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(next).toHaveBeenCalledWith(error)
  })
  it('calls next with error if subscriber service fails fail', async function () {
    const req = {
      params: {},
      body: {
        type: 'role'
      }
    }
    const res = createResponse()
    const error = new Error('etwsgry')
    roleServices.isRoleOfGuild.mockResolvedValue(true)
    subscriberServices.createSubscriber.mockRejectedValue(error)
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(next).toHaveBeenCalledWith(error)
  })
  it('calls user services with the right args', async function () {
    const req = {
      params: {
        guildID: 'w4try5',
        feedID: '32wet4ryh'
      },
      body: {
        id: '3254r',
        type: 'user',
        filters: {
          a: ['a']
        }
      }
    }
    const res = createResponse()
    userServices.getMemberOfGuild.mockResolvedValue({})
    subscriberServices.createSubscriber.mockResolvedValue()
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(userServices.getMemberOfGuild)
      .toHaveBeenCalledWith(req.body.id, req.params.guildID)
  })
  it('calls role services with the right args', async function () {
    const req = {
      params: {
        guildID: 'w4try5',
        feedID: '32wet4ryh'
      },
      body: {
        id: '3254r',
        type: 'role',
        filters: {
          a: ['a']
        }
      }
    }
    const res = createResponse()
    roleServices.isRoleOfGuild.mockResolvedValue(true)
    subscriberServices.createSubscriber.mockResolvedValue()
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(roleServices.isRoleOfGuild)
      .toHaveBeenCalledWith(req.body.id, req.params.guildID)
  })
  it('calls subscriber services with the right args', async function () {
    const req = {
      params: {
        guildID: 'w4try5',
        feedID: 'qw4etry'
      },
      body: {
        id: '3254r',
        type: 'role',
        filters: {
          a: ['a']
        }
      }
    }
    const res = createResponse()
    roleServices.isRoleOfGuild.mockResolvedValue(true)
    subscriberServices.createSubscriber.mockResolvedValue()
    const next = createNext()
    await createSubscriber(req, res, next)
    expect(subscriberServices.createSubscriber)
      .toHaveBeenCalledWith({
        ...req.body,
        feed: req.params.feedID
      })
    subscriberServices.createSubscriber.mockReset()
    // Make sure filters is turned into an empty object
    req.body.filters = null
    await createSubscriber(req, res, next)
    expect(subscriberServices.createSubscriber)
      .toHaveBeenCalledWith({
        ...req.body,
        filters: {},
        feed: req.params.feedID
      })
  })
  it('returns 403 when is not role of guild', async function () {
    const req = {
      params: {},
      body: {
        type: 'role'
      }
    }
    const json = jest.fn()
    const res = {
      status: jest.fn(() => ({ json }))
    }
    roleServices.isRoleOfGuild.mockResolvedValue(false)
    const next = createNext()
    const createdError = 34
    createError.mockReturnValue(createdError)
    await createSubscriber(req, res, next)
    expect(res.status).toHaveBeenCalledWith(403)
    expect(json).toHaveBeenCalledWith(createdError)
  })
  it('returns 403 when is not user of guild', async function () {
    const req = {
      params: {},
      body: {
        type: 'user'
      }
    }
    const json = jest.fn()
    const res = {
      status: jest.fn(() => ({ json }))
    }
    userServices.getMemberOfGuild.mockResolvedValue(null)
    const next = createNext()
    const createdError = 34
    createError.mockReturnValue(createdError)
    await createSubscriber(req, res, next)
    expect(res.status).toHaveBeenCalledWith(403)
    expect(json).toHaveBeenCalledWith(createdError)
  })
})


text:
const gulp = require('gulp')
const config = require('../config')
const browserSync = require('browser-sync')
const openBrowser = require('react-dev-utils/openBrowser')
const WebpackDevServerUtils = require('react-dev-utils/WebpackDevServerUtils')
const { prepareUrls, choosePort } = WebpackDevServerUtils

gulp.task('browser-sync', done => {
  const DEFAULT_PORT = 3000
  const HOST = '0.0.0.0'
  const protocol = 'http'
  choosePort(HOST, DEFAULT_PORT)
    .then(port => {
      if (port === null) return
      const urls = prepareUrls(protocol, HOST, port)
      browserSync.init({
        port,
        server: {
          baseDir: config.directories.dist.base,
          serveStaticOptions: {
            extensions: ['html']
          }
        },
        open: false,
        logConnections: true,
        tunnel: config.tunnel,
        files: ['**/*.css']
      })
      openBrowser(urls.localUrlForBrowser)
      done()
    })
})


text:
jQuery(document).ready(gformInitDatepicker);

function gformInitDatepicker(){
    jQuery('.datepicker').each(
        function (){
            var element = jQuery(this);
            var format = "mm/dd/yy";

            if(element.hasClass("mdy"))
                format = "mm/dd/yy";
            else if(element.hasClass("dmy"))
                format = "dd/mm/yy";
            else if(element.hasClass("dmy_dash"))
                format = "dd-mm-yy";
            else if(element.hasClass("dmy_dot"))
                format = "dd.mm.yy";
            else if(element.hasClass("ymd_slash"))
                format = "yy/mm/dd";
            else if(element.hasClass("ymd_dash"))
                format = "yy-mm-dd";
            else if(element.hasClass("ymd_dot"))
                format = "yy.mm.dd";

            var image = "";
            var showOn = "focus";
            if(element.hasClass("datepicker_with_icon")){
                showOn = "both";
                image = jQuery('#gforms_calendar_icon_' + this.id).val();
            }

            element.datepicker({ yearRange: '-100:+20', showOn: showOn, buttonImage: image, buttonImageOnly: true, dateFormat: format, changeMonth: true, changeYear: true });
        }
    );
}


text:
/*
 * Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
 *
 * Copyright (C) 2019 THL A29 Limited, a Tencent company.  All rights reserved.
 *
 * BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
 *
 * A copy of the MIT License is included in this file.
 *
 *
 * Terms of the MIT License:
 * ---------------------------------------------------
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @file main entry
 */

import Vue from 'vue'
import App from './App'
import createRouter from './router'
import store from './store'
import focus from './directives/focus/index.js'

import VeeValidate from 'vee-validate'
import validationENMessages from 'vee-validate/dist/locale/en'
import validationCNMessages from 'vee-validate/dist/locale/zh_CN'
import ExtendsCustomRules from './utils/customRules'
import validDictionary from './utils/validDictionary'
import PortalVue from 'portal-vue' // eslint-disable-line
import createLocale from '../../locale'
import '@icon-cool/bk-icon-devops/src/index'
import '@icon-cool/bk-icon-devops'

import { actionMap, resourceMap, resourceTypeMap } from '../../common-lib/permission-conf'
import bkMagic from 'bk-magic-vue'
import BkPipeline from 'bkui-pipeline'

// 全量引入 bk-magic-vue 样式
require('bk-magic-vue/dist/bk-magic-vue.min.css')

const { i18n, setLocale } = createLocale(require.context('@locale/pipeline/', false, /\.json$/))

Vue.use(focus)
Vue.use(bkMagic)
Vue.use(PortalVue)

Vue.use(VeeValidate, {
    i18nRootKey: 'validations', // customize the root path for validation messages.
    i18n,
    fieldsBagName: 'veeFields',
    dictionary: {
        'en-US': validationENMessages,
        'zh-CN': validationCNMessages
    }
})
VeeValidate.Validator.localize(validDictionary)
ExtendsCustomRules(VeeValidate.Validator.extend)
console.log(BkPipeline)
Vue.use(BkPipeline, {
    i18n
})

Vue.prototype.$setLocale = setLocale
Vue.prototype.$permissionActionMap = actionMap
Vue.prototype.$permissionResourceMap = resourceMap
Vue.prototype.$permissionResourceTypeMap = resourceTypeMap
Vue.prototype.$bkMessage = function (config) {
    config.ellipsisLine = config.ellipsisLine || 3
    bkMagic.bkMessage(config)
}
/* eslint-disable */
// 扩展字符串，判断是否为蓝盾变量格式
String.prototype.isBkVar = function () {
    return /^\${{([\w\_]+)}}$/g.test(this)
}
/* eslint-disable */

Vue.mixin({
    methods: {
        // handleError (e, permissionAction, instance, projectId, resourceMap = this.$permissionResourceMap.pipeline) {
        handleError (e, noPermissionList) {
            if (e.code === 403) { // 没有权限编辑
                // this.setPermissionConfig(resourceMap, permissionAction, instance ? [instance] : [], projectId)
                this.$showAskPermissionDialog({
                    noPermissionList
                })
            } else {
                this.$showTips({
                    message: e.message || e,
                    theme: 'error'
                })
            }
        },
        /**
         * 设置权限弹窗的参数
         */
        setPermissionConfig (resourceId, actionId, instanceId = [], projectId = this.$route.params.projectId) {
            this.$showAskPermissionDialog({
                noPermissionList: [{
                    actionId,
                    resourceId,
                    instanceId,
                    projectId
                }]
            })
        }
    }
})

if (window.top === window.self) { // 只能以iframe形式嵌入
    location.href = `${WEB_URL_PREFIX}${location.pathname}`
}

global.pipelineVue = new Vue({
    el: '#app',
    router: createRouter(store),
    i18n,
    store,
    components: {
        App
    },
    template: '<App/>'
})


text:
import React from 'react';
import { Link as RouterLink } from 'react-router-dom';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import {
  AppBar,
  Box,
  Toolbar,
  makeStyles,
  Typography
} from '@material-ui/core';
import PublicIcon from '@material-ui/icons/Public';

const useStyles = makeStyles(() => ({
  root: {},
  avatar: {
    width: 60,
    height: 60
  },
  heading: {
    color: 'white',
  }
}));

const TopBar = ({
  className,
  onMobileNavOpen,
  ...rest
}) => {
  const classes = useStyles();

  return (
    <AppBar
      className={clsx(classes.root, className)}
      elevation={0}
      {...rest}
    >
      <Toolbar>
        <RouterLink to="/">
          <Box display="flex" flexDirection="row">
            <PublicIcon className={classes.heading} />
            <Typography className={classes.heading} variant="h4">
              COVID-19 Twitter Tracker
            </Typography>
          </Box>
        </RouterLink>
        <Box flexGrow={1} />
      </Toolbar>
    </AppBar>
  );
};

TopBar.propTypes = {
  className: PropTypes.string,
  onMobileNavOpen: PropTypes.func
};

export default TopBar;


text:
'use strict';

angular.module('licenses').controller('LicenseFormController',['$scope', '$filter','$rootScope', '$reactive', 'LicensesTypes', 'LicensesGov', 'SIMPERTypes','DateSimper',
  function($scope, $filter, $rootScope, $reactive, LicensesTypes, LicensesGov, SIMPERTypes, DateSimper) {
    $reactive(this).attach($scope);

    $scope.select = {};
    $scope.detail = {};

    $scope.dateUntil = [];

    $scope.init = () => {
      $scope.select.licenseTypes = LicensesTypes;
      $scope.select.licenseGov = LicensesGov;
      $scope.select.simperTypes = SIMPERTypes;
    };

    $scope.datePlus = (d,index) => {
      var dateNow = new Date($filter('date')(d.govdetails[index].issue, 'dd-MM-yyyy'));
      dateNow = new Date(dateNow.setHours(0,0,0,0));
      var year = dateNow.getFullYear();
      var month = dateNow.getMonth();
      var day = dateNow.getDate();
      var dateUntil = new Date(year + 4, month, day);
      $scope.dateUntil[index] = dateUntil;
      DateSimper.dateUntil($scope.dateUntil);
    };

    ////////////////
    // ARRAY USER //
    ////////////////
    $scope.addNewLicense = () => {
      if(!$scope.license.details) $scope.license.details = [];
      $scope.license.details.push({

      });
    };

    $scope.deleteLicense = (index) => {
      $scope.license.details.splice(index,1);
    };

     //////////////
    // DUE DATE //
   //////////////

   $scope.dateAddYears = () => {
     var numberYearsToAdd = 4;
     $scope.license.details.simperissue = $scope.issueDate;
     $scope.license.details.simperdue = $scope.issueDate.setDate($scope.issueDate.getFullYear() + numberYearsToAdd);
     console.log($scope.issueDate);
   };
  }]);


text:
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
/* globals expect, should  */
import { DataBinder } from '../../src/data_binder/data_binder';

import {
  catchConsoleErrors
} from './catch_console_errors';

import {
  registerTestTemplates, ChildTemplate, PrimitiveChildrenTemplate, ReferenceParentTemplate, ArrayContainerTemplate,
  MapContainerTemplate, SetContainerTemplate
} from './testTemplates';

import * as _ from 'underscore';

import { PropertyElement } from '../../src/internal/property_element';
import { PropertyFactory } from '@fluid-experimental/property-properties';
import { RESOLVE_NEVER, RESOLVE_NO_LEAFS, RESOLVE_ALWAYS } from '../../src/internal/constants';
import { MockSharedPropertyTree } from './mock_shared_property_tree';

describe('Property element', function() {

  let dataBinder;
  let workspace;

  // Silence the actual console.error, so the test logs are clean
  console.error = function() {
  };

  catchConsoleErrors();

  beforeAll(function() {
    registerTestTemplates();
  });

  beforeEach(async function() {
    workspace = await MockSharedPropertyTree();
  });

  describe('hierarchy walking', function() {
    beforeEach(function() {
      dataBinder = new DataBinder();
      // Bind to the workspace
      dataBinder.attachTo(workspace);
    });

    afterEach(function() {
      // Unbind checkout view
      dataBinder.detach();
      dataBinder = null;
    });

    it('dereferencing', function() {
      workspace.root.insert('refParent', PropertyFactory.create(ReferenceParentTemplate.typeid, 'single'));
      workspace.root.insert('child', PropertyFactory.create(PrimitiveChildrenTemplate.typeid, 'single'));
      workspace.root.get(['refParent', 'single_ref'], RESOLVE_NEVER).setValue('/child');

      const rootElem = new PropertyElement(workspace.root);
      expect(rootElem.isValid()).toEqual(true);

      const refParentElem = rootElem.getChild('refParent');
      expect(refParentElem.getProperty().getId()).toEqual('refParent');

      const directToRef = ['single_ref'];
      expect(refParentElem.getChild(directToRef, RESOLVE_NEVER).getProperty().getId()).toEqual('single_ref');
      expect(refParentElem.getChild(directToRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('single_ref');
      expect(refParentElem.getChild(directToRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('child');

      const pathToRef = ['refParent', 'single_ref'];
      expect(rootElem.getChild(pathToRef, RESOLVE_NEVER).getProperty().getId()).toEqual('single_ref');
      expect(rootElem.getChild(pathToRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('single_ref');
      expect(rootElem.getChild(pathToRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('child');

      const pathThroughRef = ['refParent', 'single_ref', 'aString'];
      expect(rootElem.getChild(pathThroughRef, RESOLVE_NEVER).isValid()).toEqual(false);
      expect(rootElem.getChild(pathThroughRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('aString');
      expect(rootElem.getChild(pathThroughRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('aString');
    });

  });

  it('reference containers', function() {
    workspace.root.insert('refParent', PropertyFactory.create(ReferenceParentTemplate.typeid, 'single'));
    workspace.root.insert('child', PropertyFactory.create(PrimitiveChildrenTemplate.typeid, 'single'));
    workspace.root.get(['refParent', 'array_ref']).push('/child');
    workspace.root.get(['refParent', 'map_ref']).insert('aKey', '/child');

    const rootElem = new PropertyElement(workspace.root);
    expect(rootElem.isValid()).toEqual(true);

    const refParentElem = rootElem.getChild('refParent');
    expect(refParentElem.getProperty().getId()).toEqual('refParent');

    const pathToArrayRef = ['array_ref', 0];
    expect(refParentElem.getChild(pathToArrayRef, RESOLVE_NEVER).getProperty().getId()).toEqual('array_ref');
    expect(refParentElem.getChild(pathToArrayRef, RESOLVE_NEVER).getChildToken()).toEqual(0);
    expect(refParentElem.getChild(pathToArrayRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('array_ref');
    expect(refParentElem.getChild(pathToArrayRef, RESOLVE_NO_LEAFS).getChildToken()).toEqual(0);
    expect(refParentElem.getChild(pathToArrayRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('child');

    const pathToMapRef = ['map_ref', 'aKey'];
    expect(refParentElem.getChild(pathToMapRef, RESOLVE_NEVER).getProperty().getId()).toEqual('map_ref');
    expect(refParentElem.getChild(pathToMapRef, RESOLVE_NEVER).getChildToken()).toEqual('aKey');
    expect(refParentElem.getChild(pathToMapRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('map_ref');
    expect(refParentElem.getChild(pathToMapRef, RESOLVE_NO_LEAFS).getChildToken()).toEqual('aKey');
    expect(refParentElem.getChild(pathToMapRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('child');

    const pathThroughArrayRef = ['refParent', 'array_ref', 0, 'aString'];
    expect(rootElem.getChild(pathThroughArrayRef, RESOLVE_NEVER).isValid()).toEqual(false);
    expect(rootElem.getChild(pathThroughArrayRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('aString');
    expect(rootElem.getChild(pathThroughArrayRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('aString');

    const pathThroughMapRef = ['refParent', 'map_ref', 'aKey', 'aString'];
    expect(rootElem.getChild(pathThroughMapRef, RESOLVE_NEVER).isValid()).toEqual(false);
    expect(rootElem.getChild(pathThroughMapRef, RESOLVE_NO_LEAFS).getProperty().getId()).toEqual('aString');
    expect(rootElem.getChild(pathThroughMapRef, RESOLVE_ALWAYS).getProperty().getId()).toEqual('aString');
  });

  it('parenting', function() {
    const child = PropertyFactory.create(PrimitiveChildrenTemplate.typeid, 'single');
    const refParent = PropertyFactory.create(ReferenceParentTemplate.typeid, 'single');

    workspace.root.insert('refParent', refParent);
    workspace.root.insert('child', child);
    workspace.root.get(['refParent', 'array_ref']).push('/child');
    workspace.root.get(['refParent', 'map_ref']).insert('aKey', '/child');
    workspace.root.get(['child', 'arrayOfNumbers']).push(42);

    const rootElem = new PropertyElement(workspace.root);
    expect(rootElem.isValid()).toEqual(true);

    // Root has no parent
    expect(rootElem.getParent().isValid()).toEqual(false);

    const refParentElem = rootElem.getChild('refParent');
    expect(refParentElem.getParent().getProperty()).toEqual(workspace.root);

    const arrayEntryElem = refParentElem.getChild(['array_ref', 0], RESOLVE_NEVER);
    expect(arrayEntryElem.getChildToken()).toEqual(0);
    expect(arrayEntryElem.getParent().getProperty()).toEqual(workspace.root.get(['refParent', 'array_ref']));
    expect(arrayEntryElem.getParent().getChildToken()).toBeUndefined();

    const mapEntryElem = refParentElem.getChild(['map_ref', 'aKey'], RESOLVE_NEVER);
    expect(mapEntryElem.getChildToken()).toEqual('aKey');
    expect(mapEntryElem.getParent().getProperty()).toEqual(workspace.root.get(['refParent', 'map_ref']));
    expect(mapEntryElem.getParent().getChildToken()).toBeUndefined();

    const childElem = rootElem.getChild('child');
    const numberElem = childElem.getChild(['arrayOfNumbers', 0]);
    expect(numberElem.getChildToken()).toEqual(0);
    expect(numberElem.getValue()).toEqual(42);

    const parentElem = numberElem.getParent();
    expect(parentElem.getProperty().getId()).toEqual('arrayOfNumbers');
  });

  it('getValue', function() {
    const myData = PropertyFactory.create(PrimitiveChildrenTemplate.typeid, 'single');
    myData.get('arrayOfNumbers').setValues([1, 2, 3]);
    myData.get('arrayOfStrings').push('a');
    myData.get('arrayOfStrings').push('b');
    myData.get('arrayOfStrings').push('c');
    myData.get('mapOfNumbers').set('a', 1);
    myData.get('mapOfNumbers').set('b', 2);
    myData.get('mapOfNumbers').set('c', 3);
    myData.get('mapOfStrings').set('a', 'A');
    myData.get('mapOfStrings').set('b', 'B');
    myData.get('mapOfStrings').set('c', 'C');
    myData.get('aString').setValue('my string');
    myData.get('aNumber').setValue(42);
    myData.resolvePath('nested.aNumber').setValue(12);

    const allData = {
      thedata: myData.getValues()
    };
    // console.log('All the data:', allData);

    workspace.root.insert('thedata', myData);

    const propElem = new PropertyElement(workspace.root);

    const test = (data, child) => {
      propElem.becomeChild(child);
      // console.log('checking', propElem.toString(),':');
      const computed = propElem.getValue();
      const expected = data[child];
      // console.log(computed, ' expecting ', expected);
      expect(computed).toEqual(expected);
      if (propElem.getTypeId() !== 'String') {
        _.each(data[child], (value, key) => {
          test(data[child], key);
        });
      }
      propElem.becomeParent();
    };

    test(allData, 'thedata');
  });

  it('setValue', function() {
    const myData = PropertyFactory.create(PrimitiveChildrenTemplate.typeid, 'single');
    const propElem = new PropertyElement(myData);
    propElem.getChild('arrayOfNumbers').setValue([1, 2, 3]);
    propElem.getChild(['arrayOfNumbers', 1]).setValue(42);
    expect(propElem.getChild('arrayOfNumbers').getValue()).toEqual([1, 42, 3]);

    propElem.getChild('arrayOfStrings').setValue(['a', 'b', 'c']);
    propElem.getChild(['arrayOfStrings', 1]).setValue('INTERRUPTING COW');
    expect(propElem.getChild('arrayOfStrings').getValue()).toEqual(['a', 'INTERRUPTING COW', 'c']);

    propElem.getChild('mapOfNumbers').setValue({ a: 1, b: 2, c: 3 });
    propElem.getChild(['mapOfNumbers', 'b']).setValue(42);
    expect(propElem.getChild('mapOfNumbers').getValue()).toEqual({ a: 1, b: 42, c: 3 });

    propElem.getChild('mapOfStrings').setValue({ a: 'A', b: 'B', c: 'C' });
    propElem.getChild(['mapOfStrings', 'b']).setValue('INTERRUPTING... not funny second time');
    expect(propElem.getChild('mapOfStrings').getValue()).toEqual(
      { a: 'A', b: 'INTERRUPTING... not funny second time', c: 'C' }
    );

    propElem.getChild('nested').setValue({ aNumber: 12 });
    expect(propElem.getChild('nested').getValue()).toEqual({ aNumber: 12 });

    expect(myData.getValues()).toEqual(propElem.getValue());
  });

  it('isPrimitiveCollection basic', function() {
    const myData = PropertyFactory.create(PrimitiveChildrenTemplate.typeid, 'single');
    const propElem = new PropertyElement(myData);

    expect(propElem.isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('nested').isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('arrayOfStrings').isPrimitiveCollection()).toEqual(true);
    expect(propElem.getChild('mapOfNumbers').isPrimitiveCollection()).toEqual(true);
    expect(propElem.getChild('mapOfStrings').isPrimitiveCollection()).toEqual(true);
    expect(propElem.getChild('aString').isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('aNumber').isPrimitiveCollection()).toEqual(false);
  });

  it('isPrimitiveCollection array of prop', function() {
    const myArrayData = PropertyFactory.create(ArrayContainerTemplate.typeid, 'single');
    const propElem = new PropertyElement(myArrayData);
    expect(propElem.isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('subArray').isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('unrepresentedSubArray').isPrimitiveCollection()).toEqual(false);
  });

  it('isPrimitiveCollection set of prop', function() {
    const mySetData = PropertyFactory.create(SetContainerTemplate.typeid, 'single');
    const propElem = new PropertyElement(mySetData);
    expect(propElem.isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('subSet').isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('unrepresentedSubSet').isPrimitiveCollection()).toEqual(false);
  });

  it('isPrimitiveCollection map of prop', function() {
    const myMapData = PropertyFactory.create(MapContainerTemplate.typeid, 'single');
    const propElem = new PropertyElement(myMapData);
    expect(propElem.isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('subMap').isPrimitiveCollection()).toEqual(false);
    expect(propElem.getChild('unrepresentedSubMap').isPrimitiveCollection()).toEqual(false);
  });

  it('crazy paths for child token', function() {
    const mymap = PropertyFactory.create('Float64', 'map');
    workspace.root.insert('themap', mymap);

    mymap.insert('"my.child.path"', 42);
    const propElem = new PropertyElement(mymap);
    propElem.becomeChild('"my.child.path"');
    expect(propElem.isValid()).toEqual(true);

    expect(propElem.getValue()).toEqual(42);

    expect(propElem.getAbsolutePath()).toEqual('/themap["my.child.path"]');
  });

  it('array of properties parenting', function() {
    const array = PropertyFactory.create(ArrayContainerTemplate.typeid, 'single');
    const child0 = PropertyFactory.create(ChildTemplate.typeid, 'single');
    const child1 = PropertyFactory.create(ChildTemplate.typeid, 'single');
    child0.get('text').setValue('child0 text');
    child1.get('text').setValue('child1 text');
    array.get('subArray').push(child0);
    array.get('subArray').push(child1);
    workspace.root.insert('theArray', array);

    const rootElem = new PropertyElement(workspace.root);
    const childElem = rootElem.getChild(['theArray', 'subArray', 1, 'text']);
    expect(childElem.getValue()).toEqual('child1 text');

    expect(childElem.getParent().getParent().getProperty().getId()).toEqual('subArray');
    expect(childElem.getParent().getParent().getChildToken()).toBeUndefined();
  });

  it('map of properties parenting', function() {
    const map = PropertyFactory.create(MapContainerTemplate.typeid, 'single');
    const child0 = PropertyFactory.create(ChildTemplate.typeid, 'single');
    const child1 = PropertyFactory.create(ChildTemplate.typeid, 'single');
    child0.get('text').setValue('child0 text');
    child1.get('text').setValue('child1 text');
    map.get('subMap').insert('child0', child0);
    map.get('subMap').insert('child1', child1);
    workspace.root.insert('theMap', map);

    const rootElem = new PropertyElement(workspace.root);
    const childElem = rootElem.getChild(['theMap', 'subMap', 'child1', 'text']);
    expect(childElem.getValue()).toEqual('child1 text');

    expect(childElem.getParent().getProperty().getId()).toEqual('child1');
    expect(childElem.getParent().getChildToken()).toBeUndefined();

    expect(childElem.getParent().getParent().getProperty().getId()).toEqual('subMap');
    expect(childElem.getParent().getParent().getChildToken()).toBeUndefined();
  });

  it('double references', function() {
    const text = PropertyFactory.create('String', 'single');
    const ref1 = PropertyFactory.create('Reference', 'single');
    const ref2 = PropertyFactory.create('Reference', 'single');
    const ref3 = PropertyFactory.create('Reference', 'single');
    workspace.root.insert('text', text);
    workspace.root.insert('ref1', ref1);
    workspace.root.insert('ref2', ref2);
    workspace.root.insert('ref3', ref3);
    ref3.setValue('/ref2');
    ref2.setValue('/ref1');
    ref1.setValue('/text');
    text.setValue('theText');

    const rootElem = new PropertyElement(workspace.root);
    expect(rootElem.getChild('ref3', RESOLVE_ALWAYS).getValue()).toEqual('theText');
    expect(rootElem.getChild('ref3', RESOLVE_NEVER).getValue()).toEqual('/ref2');
  });

  it('double references array', function() {
    const text = PropertyFactory.create('String', 'single');
    const refs = PropertyFactory.create('Reference', 'array');
    workspace.root.insert('text', text);
    workspace.root.insert('refs', refs);
    refs.push('/text');
    refs.push('/refs[0]');
    refs.push('/refs[1]');
    text.setValue('theText');

    const rootElem = new PropertyElement(workspace.root);
    expect(rootElem.getChild(['refs', 2], RESOLVE_ALWAYS).getValue()).toEqual('theText');
    expect(rootElem.getChild(['refs', 2], RESOLVE_NO_LEAFS).getValue()).toEqual('/refs[1]');
    expect(rootElem.getChild(['refs', 2], RESOLVE_NEVER).getValue()).toEqual('/refs[1]');
  });

  it('tokenized path, toString, getContext', function() {
    const arrayData = PropertyFactory.create('String', 'array');
    workspace.root.insert('theArray', arrayData);
    arrayData.push('hi');

    const rootElem = new PropertyElement(workspace.root);
    expect(rootElem.getTokenizedPath().length).toEqual(0);
    expect(rootElem.getContext()).toEqual('single');
    rootElem.becomeChild('theArray');
    expect(rootElem.getContext()).toEqual('array');
    expect(rootElem.getTokenizedPath().length).toEqual(1);
    expect(rootElem.getTokenizedPath()[0]).toEqual('theArray');
    expect(rootElem.toString()).toEqual('</theArray>');

    rootElem.becomeChild(0);
    expect(rootElem.getContext()).toEqual('single');
    expect(rootElem.getTokenizedPath().length).toEqual(2);
    expect(rootElem.getTokenizedPath()[0]).toEqual('theArray');
    expect(rootElem.getTokenizedPath()[1]).toEqual('0');
    expect(rootElem.toString()).toEqual('</theArray[0]>');

    expect((new PropertyElement()).toString()).toEqual('<invalid>');
  });

  it('becoming the parent', function() {
    const arrayData = PropertyFactory.create('String', 'array');
    workspace.root.insert('theArray', arrayData);
    arrayData.push('hi');

    const rootElem = new PropertyElement(workspace.root);
    rootElem.becomeChild('theArray');
    expect(rootElem.getProperty()).toEqual(workspace.root.get('theArray'));
    rootElem.becomeChild(0);
    expect(rootElem.getProperty()).toEqual(workspace.root.get('theArray'));
    expect(rootElem.getChildToken()).toEqual(0);
    rootElem.becomeParent();
    expect(rootElem.getProperty()).toEqual(workspace.root.get('theArray'));
    expect(rootElem.getChildToken()).toBeUndefined();
    rootElem.becomeParent();
    expect(rootElem.getProperty()).toEqual(workspace.root);
    expect(rootElem.getChildToken()).toBeUndefined();
    rootElem.becomeParent();
    expect(rootElem.isValid()).toEqual(false);
  });

  it('isPrimitiveCollection', function() {
    const types = ['String', 'Float32', 'Reference'];
    const contexts = ['single', 'array', 'map'];
    types.forEach((theType) => {
      contexts.forEach((context) => {
        const prop = PropertyFactory.create(theType, context);
        expect((new PropertyElement(prop)).isPrimitiveCollection()).toEqual(context !== 'single');
      });
    });

    const nodeArray = PropertyFactory.create('NodeProperty', 'array');
    const propElem = new PropertyElement(nodeArray);
    expect(propElem.isPrimitiveCollection()).toEqual(false);

    const array = PropertyFactory.create('Float32', 'array');
    array.push(42);
    const element = new PropertyElement(array);
    expect(element.isPrimitiveCollection()).toEqual(true);
    element.becomeChild(0);
    expect(element.isPrimitiveCollection()).toEqual(false);
  });

  it('cloning', function() {
    const arrayData = PropertyFactory.create('String', 'array');
    workspace.root.insert('theArray', arrayData);
    arrayData.push('hi');

    const rootElem = new PropertyElement(workspace.root);
    rootElem.becomeChild('theArray');
    rootElem.becomeChild(0);
    const clone = rootElem.clone();
    expect(clone.getProperty()).toEqual(rootElem.getProperty());
    expect(clone.getChildToken()).toEqual(rootElem.getChildToken());
  });

  it('a reference with *', function() {
    const myData = PropertyFactory.create('Float64');
    const myReference1 = PropertyFactory.create('Reference');
    const myReference2 = PropertyFactory.create('Reference');

    workspace.root.insert('myData', myData);
    workspace.root.insert('myReference1', myReference1);
    workspace.root.insert('myReference2', myReference2);

    myData.setValue(42);
    myReference1.setValue('/myData');


text:
const { Router } = require('express');
const router = Router();

const passport = require('passport');
const { isLoggedIn, isNotloggedIn } = require('../lib/auth');

router.get('/signup', isNotloggedIn, (req, res) => {
    res.render('auth/signup');
});

router.get('/signin', isNotloggedIn, (req, res) => {
    res.render('auth/signin');
});

router.post('/signin', isNotloggedIn, (req, res, next) => {
    passport.authenticate('local.signin', {
        successRedirect: '/profile',
        failureRedirect: '/signin',
        failureFlash: true
    })(req, res, next);
});

router.post('/signup', isNotloggedIn, passport.authenticate('local.signup', {
    successRedirect: '/profile',
    failureRedirect: '/signup',
    failureFlash: true
}));

router.get('/profile', isLoggedIn, (req, res) => {
    res.render('profile');
});

router.get('/logout', isLoggedIn, (req, res) => {
    req.logOut()
    res.redirect('/signin');
});

module.exports = router;


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Styles from './ContactFormStyles.module.css';

export default class ContactForm extends Component {
  state = {
    name: '',
    number: '',
  };
  handleChangeName = event => {
    this.setState({ name: event.target.value });
  };
  handleChangeNumber = event => {
    this.setState({ number: event.target.value });
  };
  handleFormSubmit = event => {
    event.preventDefault();
    const contacts = this.props.contacts;
    // console.log('props',this.props);
    const { name } = this.state;
    if (contacts.find(el => el.name.toLowerCase() === name.toLowerCase())) {
      alert(`"${name}" is alredy in contacts `);
    } else {
      this.props.addUserContact(this.state.name, this.state.number);
    }
    this.setState({ name: '', number: '' });
  };
  render() {
    return (
      <form className={Styles.form__style}onSubmit={this.handleFormSubmit}>
        <label>
          <input
          placeholder="Name"
          className={Styles.input__style}
          type="text"
          value={this.state.name}
          onChange={this.handleChangeName}
          ></input>
        </label>
        <label>
          <input
          placeholder="Number"
          className={Styles.input__style}
            type="number"
            value={this.state.number}
            onChange={this.handleChangeNumber}
          ></input>
        </label>
        <button className={Styles.addbtn__style}type="submit" onSubmit={this.handleFormSubmit}>
          Add contact
        </button>
      </form>
    );
  }
}

ContactForm.propTypes = {
  contacts: PropTypes.arrayOf(
    PropTypes.shape({
      name:PropTypes.string,
      number:PropTypes.string,
      id:PropTypes.string

    })
  ).isRequired,
  addUserContact: PropTypes.func.isRequired,
};


text:
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import $ from 'jquery';

import catalogUtils from 'catalog/catalogUtils';
import { getOptimizer } from './optimizer/optimizer';
import { DataCatalog } from './dataCatalog';

/**
 * Helper function to reload a Optimizer multi table attribute, like topAggs or topFilters
 *
 * @param {MultiTableEntry} multiTableEntry
 * @param {Object} [options]
 * @param {boolean} [options.silenceErrors] - Default true
 * @param {string} promiseAttribute
 * @param {string} dataAttribute
 * @param {Function} apiHelperFunction
 * @return {CancellableJqPromise}
 */
const genericOptimizerReload = function (
  multiTableEntry,
  options,
  promiseAttribute,
  dataAttribute,
  apiHelperFunction
) {
  if (multiTableEntry.dataCatalog.canHaveOptimizerMeta()) {
    return multiTableEntry.trackedPromise(
      promiseAttribute,
      catalogUtils.fetchAndSave(apiHelperFunction, dataAttribute, multiTableEntry, options)
    );
  }
  multiTableEntry[promiseAttribute] = $.Deferred().reject();
  return multiTableEntry[promiseAttribute];
};

/**
 * Helper function to get a Optimizer multi table attribute, like topAggs or topFilters
 *
 * @param {MultiTableEntry} multiTableEntry
 * @param {Object} [options]
 * @param {boolean} [options.silenceErrors] - Default false
 * @param {boolean} [options.refreshCache] - Default false
 * @param {boolean} [options.cachedOnly] - Default false
 * @param {boolean} [options.cancellable] - Default false
 * @param {string} promiseAttribute
 * @param {string} dataAttribute
 * @param {Function} apiHelperFunction
 * @return {CancellableJqPromise}
 */
const genericOptimizerGet = function (
  multiTableEntry,
  options,
  promiseAttribute,
  dataAttribute,
  apiHelperFunction
) {
  if (DataCatalog.cacheEnabled() && options && options.cachedOnly) {
    return (
      catalogUtils.applyCancellable(multiTableEntry[promiseAttribute], options) ||
      $.Deferred().reject(false).promise()
    );
  }
  if (!DataCatalog.cacheEnabled() || (options && options.refreshCache)) {
    return catalogUtils.applyCancellable(
      genericOptimizerReload(
        multiTableEntry,
        options,
        promiseAttribute,
        dataAttribute,
        apiHelperFunction
      ),
      options
    );
  }
  return catalogUtils.applyCancellable(
    multiTableEntry[promiseAttribute] ||
      genericOptimizerReload(
        multiTableEntry,
        options,
        promiseAttribute,
        dataAttribute,
        apiHelperFunction
      ),
    options
  );
};

class MultiTableEntry {
  /**
   *
   * @param {Object} options
   * @param {string} options.identifier
   * @param {DataCatalog} options.dataCatalog
   * @param {string[][]} options.paths
   * @constructor
   */
  constructor(options) {
    const self = this;
    self.identifier = options.identifier;
    self.dataCatalog = options.dataCatalog;
    self.paths = options.paths;

    self.topAggs = undefined;
    self.topAggsPromise = undefined;

    self.topColumns = undefined;
    self.topColumnsPromise = undefined;

    self.topFilters = undefined;
    self.topFiltersPromise = undefined;

    self.topJoins = undefined;
    self.topJoinsPromise = undefined;
  }

  /**
   * Save the multi table entry to cache
   *
   * @return {Promise}
   */
  save() {
    const self = this;
    window.clearTimeout(self.saveTimeout);
    return self.dataCatalog.persistMultiTableEntry(self);
  }

  /**
   * Save the multi table entry at a later point of time
   */
  saveLater() {
    const self = this;
    if (CACHEABLE_TTL.default > 0) {
      window.clearTimeout(self.saveTimeout);
      self.saveTimeout = window.setTimeout(() => {
        self.save();
      }, 1000);
    }
  }
  /**
   * Helper function that ensure that cancellable promises are not tracked anymore when cancelled
   *
   * @param {string} promiseName - The attribute name to use
   * @param {CancellableJqPromise} cancellableJqPromise
   */
  trackedPromise(promiseName, cancellableJqPromise) {
    const self = this;
    self[promiseName] = cancellableJqPromise;
    return cancellableJqPromise.fail(() => {
      if (cancellableJqPromise.cancelled) {
        delete self[promiseName];
      }
    });
  }

  /**
   * Returns the dialect of this entry.
   *
   * @return {string} - 'impala', 'hive', 'solr', etc.
   */
  getDialect() {
    return this.getConnector().dialect || this.getConnector().id; // .id for editor v1
  }

  /**
   * Returns the connector for this entry
   *
   * @return {Connector}
   */
  getConnector() {
    return this.dataCatalog.connector;
  }

  /**
   * Gets the top aggregate UDFs for the entry. It will fetch it if not cached or if the refresh option is set.
   *
   * @param {Object} [options]
   * @param {boolean} [options.silenceErrors] - Default false
   * @param {boolean} [options.cachedOnly] - Default false
   * @param {boolean} [options.refreshCache] - Default false
   * @param {boolean} [options.cancellable] - Default false
   *
   * @return {CancellableJqPromise}
   */
  getTopAggs(options) {
    const optimizer = getOptimizer(this.dataCatalog.connector);
    return genericOptimizerGet(
      this,
      options,
      'topAggsPromise',
      'topAggs',
      optimizer.fetchTopAggs.bind(optimizer)
    );
  }

  /**
   * Gets the top columns for the entry. It will fetch it if not cached or if the refresh option is set.
   *
   * @param {Object} [options]
   * @param {boolean} [options.silenceErrors] - Default false
   * @param {boolean} [options.cachedOnly] - Default false
   * @param {boolean} [options.refreshCache] - Default false
   * @param {boolean} [options.cancellable] - Default false
   *
   * @return {CancellableJqPromise}
   */
  getTopColumns(options) {
    const optimizer = getOptimizer(this.dataCatalog.connector);
    return genericOptimizerGet(
      this,
      options,
      'topColumnsPromise',
      'topColumns',
      optimizer.fetchTopColumns.bind(optimizer)
    );
  }

  /**
   * Gets the top filters for the entry. It will fetch it if not cached or if the refresh option is set.
   *
   * @param {Object} [options]
   * @param {boolean} [options.silenceErrors] - Default false
   * @param {boolean} [options.cachedOnly] - Default false
   * @param {boolean} [options.refreshCache] - Default false
   * @param {boolean} [options.cancellable] - Default false
   *
   * @return {CancellableJqPromise}
   */
  getTopFilters(options) {
    const optimizer = getOptimizer(this.dataCatalog.connector);
    return genericOptimizerGet(
      this,
      options,
      'topFiltersPromise',
      'topFilters',
      optimizer.fetchTopFilters.bind(optimizer)
    );
  }

  /**
   * Gets the top joins for the entry. It will fetch it if not cached or if the refresh option is set.
   *
   * @param {Object} [options]
   * @param {boolean} [options.silenceErrors] - Default false
   * @param {boolean} [options.cachedOnly] - Default false
   * @param {boolean} [options.refreshCache] - Default false
   * @param {boolean} [options.cancellable] - Default false
   *
   * @return {CancellableJqPromise}
   */
  getTopJoins(options) {
    const optimizer = getOptimizer(this.dataCatalog.connector);
    return genericOptimizerGet(
      this,
      options,
      'topJoinsPromise',
      'topJoins',
      optimizer.fetchTopJoins.bind(optimizer)
    );
  }
}

export default MultiTableEntry;


text:
import * as openpgp from 'openpgp'

openpgp.config.aead_protect = false
openpgp.config.prefer_hash_algorithm = 2 // SHA1
var hkp = new openpgp.HKP('https://pgp.mit.edu')
var hkp2 = new openpgp.HKP('http://keys.gnupg.net')
var keyring = new openpgp.Keyring()

// Print a key
function printKey () {
  let keyid = printKeyid(this.primaryKey.getKeyId())
  let userid = printUser(this.getPrimaryUser().user)
  return keyid + ' ' + userid
}
// openpgp.key.toString = printKey

function printKeyid (keyid) {
  return keyid.toHex()
}
// openpgp.Keyid.prototype.toString = openpgp.Keyid.prototype.toHex

function printUser (user) {
  return user.userId.userid
}

function getFullSignature (signature) {
  let key = keyring.getKeysForId(printKeyid(signature.keyid))[0]
  let user = key.getPrimaryUser().user
  signature.user = user
  signature.email = printUser(user).match(/<(.*)>/)[1]
  return signature
}

// Find the public key(s) for `email` on the local browser keyring.
function locallookup (email) {
  let keys = keyring.publicKeys.getForAddress(email)
  if (keys.length === 0) {
    return null
  }
  // keys[0].toString = printKey
  return keys[0]
}

export class PGP {
  // Find the public key(s) for `email` on a server (note - how can you trust the PGP server?) add them to the browser keyring.
  static async lookup (email) {
    // Has no option to do an exact email search for some reason.
    // william@example.net instead returns results for "william example net"
    // so we must work around this stupidity
    try {
      let keys = await hkp.lookup({ query: email })
      if (typeof keys === 'undefined') return null
      keys = openpgp.key.readArmored(keys).keys
      // Find keys with an exact match for the email address given
      let results = []
      for (let k of keys) {
        for (let u of k.users) {
          if (u.userId.userid.includes(`<${email}>`)) {
            results.push(k.primaryKey.keyid.toHex())
            keyring.publicKeys.push(k)
          }
        }
      }
      results = results.length > 0 ? results : null
      return results
    } catch (err) {
      console.log('err =', err)
      return null
    }
  }

  // Generate a key pair in the browser and add it to the browser keyring.
  static async keygen (name, email) {
    const { privateKeyArmored, publicKeyArmored } = await openpgp.generateKey({
      userIds: [
        {
          name: name,
          email: email
        }
      ]
    })
    keyring.publicKeys.importKey(publicKeyArmored)
    keyring.privateKeys.importKey(privateKeyArmored)
    // let key = openpgp.key.readArmored(privateKeyArmored).keys[0]
    // key.toString = printKey
    // We need to manually call this to save the keypair to localstorage
    keyring.store()
  }

  // Returns a human-readable list of all the public keys in the browser's keyring.
  static async list () {
    let print = []
    for (let key of keyring.publicKeys.keys) {
      print.push(printKey.apply(key))
    }
    return print
  }

  // Encrypt `msg` using the public key for `email`
  static async encrypt (email, msg) {
    // Load Alice's keypair from localstorage
    // let privateKey = keyring.privateKeys.keys[0]
    let publicKey = locallookup(email)
    const encrypted = await openpgp.encrypt({
      publicKeys: publicKey, // NOTE: it's plural...
      data: msg
    })
    return encrypted.data
  }

  // Decrypt `msg` using the private key for `email`
  // msg should be the full encrypted message including the -----BEGIN PGP MESSAGE----- and -----END PGP MESSAGE----- lines.
  static async decrypt (email, msg) {
    let privateKey = PGP.lookupPrivateKey(email)
    const decrypted = openpgp.decrypt({
      privateKey: privateKey,
      message: openpgp.message.readArmored(msg)
    })
    return decrypted.data
  }

  // Sign `msg` using the private key for `email'
  static async sign (email, msg) {
    // Load keypair from localstorage
    let privateKey = PGP.lookupPrivateKey(email)
    if (privateKey) {
      const signed = await openpgp.sign({
        privateKeys: privateKey,
        data: msg
      })
      return signed.data
    } else {
      throw new Error(
        'No PrivateKey in the OpenPGP keyring for the email address: ' + email
      )
    }
  }

  // Verify a signed `msg` using the public key for `email`
  static async verify (email, msg) {
    let publicKeys = locallookup(email)
    const verified = await openpgp.verify({
      publicKeys: publicKeys,
      message: openpgp.cleartext.readArmored(msg)
    })
    let signature = verified.signatures.map(getFullSignature)
    signature = signature.filter(x => x.email === email)
    if (signature.length !== 1) {
      return false
    } else {
      return signature[0].valid
    }
  }

  // Sign `plaintext` using the private key for `email'
  static async createBinaryDetachedSignature (email, plaintext) {
    // Load keypair from localstorage
    let privateKey = PGP.lookupPrivateKey(email)
    if (privateKey) {
      // Is the only difference between cleartext signatures and detached binary the text normalization?
      // If so, I could probably add that functionality to openpgpjs - I'd just need a little guidance
      // on how to encode the PacketType and add the functionality to export to armor.js
      let bytes = openpgp.util.str2Uint8Array(plaintext)
      let message = openpgp.message.fromBinary(bytes)
      let signedMessage = message.sign([privateKey])
      let signature = signedMessage.packets.filterByTag(
        openpgp.enums.packet.signature
      )
      let armoredMessage = openpgp.armor.encode(
        openpgp.enums.armor.message,
        signature.write()
      )
      // Github won't recognize the signature unless we rename the headers (Tested 2017-01-04)
      armoredMessage = armoredMessage.replace(
        '-----BEGIN PGP MESSAGE-----\r\n',
        '-----BEGIN PGP SIGNATURE-----\r\n'
      )
      armoredMessage = armoredMessage.replace(
        '-----END PGP MESSAGE-----\r\n',
        '-----END PGP SIGNATURE-----\r\n'
      )
      return armoredMessage
    } else {
      throw new Error(
        'No PrivateKey in the OpenPGP keyring for the email address: ' + email
      )
    }
  }

  // Verify `message` with detached `signature` using the public key for `email`
  static async verifyDetachedSignature (email, message, signature) {
    locallookup(email)
    console.log('email, message, signature =', email, message, signature)
    let msg = openpgp.message.readSignedContent(message, signature)
    console.log('msg =', msg)
    var result = msg.verify(keyring.publicKeys.keys)
    console.log('result[0] =', result[0])
    console.log('keyid =', printKeyid(result[0].keyid))
    return result[0].valid
  }

  // Returns true if the keyring has a private key for `email`.
  static hasPrivateKey (email) {
    let keys = keyring.privateKeys.getForAddress(email)
    return keys.length > 0
  }

  // Export public signing key
  static exportPublicKey (email) {
    return PGP.lookupPrivateKey(email)
      .toPublic()
      .armor()
      .trim()
      .replace(/\r/g, '')
  }

  // Upload the public signing key to the MIT key server
  static async publish (email) {
    let key = PGP.exportPublicKey(email)
    return Promise.all([hkp.upload(key), hkp2.upload(key)])
  }

  static lookupPrivateKey (email) {
    let keys = keyring.privateKeys.getForAddress(email)
    if (keys.length === 0) {
      return null
    }
    // keys[0].toString = printKey
    return keys[0]
  }
}


text:
export default class Counter {
  constructor() {
    this.count = 0;
    this.$value = document.querySelector("#value");
    this.initEventListeners();
  }

  increase() {
    if (this.count >= 10) {
      return;
    }
    this.count += 1;
    this.$value.innerText = this.count;
  }

  decrease() {
    if (this.count <= 0) {
      return;
    }
    this.count -= 1;
    this.$value.innerText = this.count;
  }

  reset() {
    this.count = 0;
    this.$value.innerText = this.count;
  }

  initEventListeners() {
    document
      .querySelector(".increase-btn")
      .addEventListener("click", this.increase.bind(this));

    document
      .querySelector(".decrease-btn")
      .addEventListener("click", this.decrease.bind(this));

    document
      .querySelector(".reset-btn")
      .addEventListener("click", this.reset.bind(this));
  }
}


text:
import {
  refreshLinks,
  setMenuItems,
  toggleAutoRefresh,
  toggleDisplayFolderLinks,
  toggleRepeatFolders,
  allFoldersHandler,
  folderPicked,
  generateLinks,
  processRemoveFolder,
  resetCustomFolders,
  showPicker,
  showPrompt,
  showRemoveFolderPrompt
} from './core';
import { getOAuthToken } from './utils';

global.refreshLinks = refreshLinks;

/**
 * Simple trigger that runs on sheet open.
 */
global.onOpen = event => {
  try {
    setMenuItems(event);
  } catch (e) {
    Logger.log(e);
  }
};

/**
 * Simple trigger that runs upon addon installation.
 */
global.onInstall = e => {
  global.onOpen(e);
};

global.toggleAutoRefresh = toggleAutoRefresh;
global.toggleDisplayFolderLinks = toggleDisplayFolderLinks;
global.toggleRepeatFolders = toggleRepeatFolders;

global.getOAuthToken = getOAuthToken;

global.allFoldersHandler = allFoldersHandler;
global.folderPicked = folderPicked;
global.generateLinks = generateLinks;
global.processRemoveFolder = processRemoveFolder;
global.resetCustomFolders = resetCustomFolders;
global.showPicker = showPicker;
global.showPrompt = showPrompt;
global.showRemoveFolderPrompt = showRemoveFolderPrompt;


text:
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Mutator for object expressions.
 */

'use strict';

const babelTypes = require('@babel/types');

const common = require('./common.js');
const mutator = require('./mutator.js');
const random = require('../random.js');

const MAX_PROPERTIES = 50;

/**
 * Turn the key of an object property into a string literal.
 */
function keyToString(key) {
  if (babelTypes.isNumericLiteral(key)) {
    return babelTypes.stringLiteral(key.value.toString());
  }
  if (babelTypes.isIdentifier(key)) {
    return babelTypes.stringLiteral(key.name);
  }
  // Already a string literal.
  return key;
}

class ObjectMutator extends mutator.Mutator {
  constructor(settings) {
    super();
    this.settings = settings;
  }

  get visitor() {
    const thisMutator = this;

    return {
      ObjectExpression(path) {
        const properties = path.node.properties;
        if (!random.choose(thisMutator.settings.MUTATE_OBJECTS) ||
            properties.length > MAX_PROPERTIES) {
          return;
        }

        // Use the indices of object properties for mutations. We ignore
        // getters and setters.
        const propertyIndicies = [];
        for (const [index, property] of properties.entries()) {
          if (babelTypes.isObjectProperty(property)) {
            propertyIndicies.push(index);
          }
        }

        // The mutations below require at least one property.
        if (!propertyIndicies.length) {
          return;
        }

        // Annotate object expression with the action taken.
        function annotate(message) {
          thisMutator.annotate(path.node, message);
        }

        function getOneRandomProperty() {
          return properties[random.single(propertyIndicies)];
        }

        function getTwoRandomProperties() {
          const [a, b] = random.sample(propertyIndicies, 2);
          return [properties[a], properties[b]];
        }

        function swapPropertyValues() {
          if (propertyIndicies.length > 1) {
            annotate('Swap properties');
            const [a, b] = getTwoRandomProperties();
            [a.value, b.value] = [b.value, a.value];
          }
        }

        function duplicatePropertyValue() {
          if (propertyIndicies.length > 1) {
            const [a, b] = random.shuffle(getTwoRandomProperties());
            if (common.isLargeNode(b.value)) {
              return;
            }
            annotate('Duplicate a property value');
            a.value = babelTypes.cloneDeep(b.value);
          }
        }

        function insertRandomValue() {
          annotate('Insert a random value');
          const property = getOneRandomProperty();
          property.value = common.randomValue(path);
        }

        function stringifyKey() {
          annotate('Stringify a property key');
          const property = getOneRandomProperty();
          property.key = keyToString(property.key);
        }

        function removeProperty() {
          annotate('Remove a property');
          properties.splice(random.single(propertyIndicies), 1);
        }

        // Mutation options. Repeated mutations have a higher probability.
        const mutations = [
          swapPropertyValues,
          swapPropertyValues,
          duplicatePropertyValue,
          duplicatePropertyValue,
          insertRandomValue,
          insertRandomValue,
          removeProperty,
          stringifyKey,
        ];

        // Perform mutation.
        random.single(mutations)();
      },
    }
  }
}

module.exports = {
  ObjectMutator: ObjectMutator,
};


text:
/*
 * File: app.js
 *
 * This file was generated by Sencha Architect version 3.0.4.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Sencha Touch 2.3.x library, under independent license.
 * License of Sencha Architect does not include license for Sencha Touch 2.3.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

// @require @packageOverrides
Ext.Loader.setConfig({

});

Ext.application({

    requires: [
        'Ext.MessageBox'
    ],
    models: [
        'Employee'
    ],
    stores: [
        'EmployeeJsonPStore'
    ],
    views: [
        'MainView',
        'EmployeeNavigationView',
        'EmployeeList',
        'EmployeeFormPanel'
    ],
    controllers: [
        'EmployeeController'
    ],
    name: 'SenchaCrud',

    getGenericServerMessage: function() {
        return "Connectivity Error, try again later.";
    },

    launch: function() {

        Ext.create('SenchaCrud.view.MainView', {fullscreen: true});
    }

});


text: var __awaiter=this&&this.__awaiter||function(t,e,r,n){function i(t){return t instanceof r?t:new r((function(e){e(t)}))}return new(r||(r=Promise))((function(r,o){function a(t){try{u(n.next(t))}catch(t){o(t)}}function s(t){try{u(n["throw"](t))}catch(t){o(t)}}function u(t){t.done?r(t.value):i(t.value).then(a,s)}u((n=n.apply(t,e||[])).next())}))};var __generator=this&&this.__generator||function(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,a;return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(t){return function(e){return u([t,e])}}function u(a){if(n)throw new TypeError("Generator is already executing.");while(r)try{if(n=1,i&&(o=a[0]&2?i["return"]:a[0]?i["throw"]||((o=i["return"])&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;if(i=0,o)a=[a[0]&2,o.value];switch(a[0]){case 0:case 1:o=a;break;case 4:r.label++;return{value:a[1],done:false};case 5:r.label++;i=a[1];a=[0];continue;case 7:a=r.ops.pop();r.trys.pop();continue;default:if(!(o=r.trys,o=o.length>0&&o[o.length-1])&&(a[0]===6||a[0]===2)){r=0;continue}if(a[0]===3&&(!o||a[1]>o[0]&&a[1]<o[3])){r.label=a[1];break}if(a[0]===6&&r.label<o[1]){r.label=o[1];o=a;break}if(o&&r.label<o[2]){r.label=o[2];r.ops.push(a);break}if(o[2])r.ops.pop();r.trys.pop();continue}a=e.call(t,r)}catch(t){a=[6,t];i=0}finally{n=o=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:true}}};System.register(["./p-92f7c087.system.js","./p-d2d3f0b5.system.js","./p-7660814d.system.js","./p-0b5de7fa.system.js","./p-af5365d2.system.js","./p-956bb589.system.js","./p-5fcc633d.system.js","./p-576893c9.system.js","./p-4c5bd054.system.js"],(function(t){"use strict";var e,r,n,i,o,a,s,u,l,c,d,f,h,p,b,m,v,g;return{setters:[function(t){e=t.r;r=t.e;n=t.h;i=t.H;o=t.g},function(t){a=t.e},function(t){s=t.c},function(t){u=t.g},function(){},function(t){l=t.createGesture},function(t){c=t.s},function(t){d=t.i;f=t.b;h=t.c;p=t.g;b=t.e;m=t.f},function(t){v=t.g;g=t.s}],execute:function(){var w=this;var x=function(t,e,r){if(r===void 0){r=400}var n=s();var i=t.host||t;var o=t.querySelector(".toast-wrapper");var a="calc(-12px - var(--safe-area-bottom, 0px))";var u="calc(12px + var(--safe-area-top, 0px))";n.addElement(o);switch(e){case"bottom":n.fromTo("transform","translate3d(0, 200%, 0)","translate3d(0, "+a+", 0)");break;case"middle":var l="50%";o.style.top=""+l;n.fromTo("opacity",.01,1);break;default:n.fromTo("transform","translate3d(0, -200%, 0)","translate3d(0, "+u+", 0)");break}var c=s().addElement(i).easing("cubic-bezier(.155,1.105,.295,1.12)").duration(r).addAnimation(n);var d=s().beforeStyles({transform:"translateY(0)","transform-origin":"top center",overflow:"hidden"});c.addAnimation(d);return c};var y=function(t,e,r){if(r===void 0){r=300}var n=s();var i=t.host||t;var o=t.querySelector(".toast-wrapper");var a="calc(-12px - var(--safe-area-bottom, 0px))";var u="calc(12px + var(--safe-area-top, 0px))";n.addElement(o);switch(e){case"bottom":n.fromTo("transform","translate3d(0, "+a+", 0)","translate3d(0, 200%, 0)");break;case"middle":n.fromTo("opacity",.99,0);break;default:n.fromTo("transform","translate3d(0, "+u+", 0)","translate3d(0, -200%, 0)");break}var l=s().addElement(i).easing("cubic-bezier(.36,.66,.04,1)").duration(r).addAnimation(n);var c=s().beforeClearStyles(["transform"]).afterClearStyles(["transform"]).onFinish((function(t){if(t!==1){return}}));l.addAnimation(c);return l};var k=function(t,e,r,n){var i=t.querySelector(".toast-wrapper");var o=i.clientHeight;console.log(o);var s=false;var c=r==="top"?-.9999:1e-4;var d=r==="top"?1e-4:.9999;var f=function(t){return __awaiter(w,void 0,void 0,(function(){var e;return __generator(this,(function(r){e=t.event.target;if(e){return[2,true]}return[2,false]}))}))};var h=function(){e.progressStart(true,s?1:0)};var p=function(t){var r=a(c,t.deltaY/(o*2),d);e.progressStep(r)};var b=function(t){var r=t.velocityY;var i=a(c,t.deltaY/(o*2),d);var l=(t.deltaY+r*1e3)/o;var f=l>=.5;var h=f?-.001:.001;if(!f){e.easing("cubic-bezier(1, 0, 0.68, 0.28)");h+=u([0,0],[1,0],[.68,.28],[1,1],i)[0]}else{e.easing("cubic-bezier(0.32, 0.72, 0, 1)");h+=u([0,0],[.32,.72],[0,1],[1,1],i)[0]}var p=f?_(i*o,r):_((1-i)*o,r);s=f;m.enable(false);e.onFinish((function(){if(!f){m.enable(true)}})).progressEnd(f?1:0,h,p);if(f){n()}};var m=l({el:t,gestureName:"toastSwipeToClose",gesturePriority:40,direction:"y",threshold:10,canStart:f,onStart:h,onMove:p,onEnd:b});return m};var _=function(t,e){return a(400,t/Math.abs(e*1.1),500)};var T=":host{--border-width:0;--border-style:none;--border-color:initial;--box-shadow:0 15px 25px 0 rgba(var(--box-shadow-color, var(--bkkr-text-color-rgb, 0, 0, 0)), 0.1), 0 6px 20px 0 rgba(var(--box-shadow-color, var(--bkkr-text-color-rgb, 0, 0, 0)), 0.12), 0 13.2px 40px 0 rgba(var(--box-shadow-color, var(--bkkr-text-color-rgb, 0, 0, 0)), 0.08);--min-width:auto;--width:auto;--min-height:auto;--height:auto;--max-height:auto;--white-space:pre-wrap;--background:var(--bkkr-background-color, #fff);--border-radius:2em;--button-color:color-get(primary, base);--color:var(--bkkr-color-step-850, #262626);--max-width:700px;--start:calc(var(--bkkr-spacer, 16px) / 2);--end:var(--start);top:0;left:0;display:block;position:absolute;width:100%;height:100%;outline:none;color:var(--color);font-family:var(--default-font-sans-serif);font-size:14px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;contain:strict;z-index:1001;pointer-events:none}:host(.overlay-hidden){display:none}.toast-wrapper{border-radius:var(--border-radius);right:var(--end);left:var(--start);margin-left:auto;margin-right:auto;margin-top:auto;margin-bottom:auto;display:block;position:absolute;width:var(--width);min-width:var(--min-width);max-width:var(--max-width);height:var(--height);min-height:var(--min-height);max-height:var(--max-height);border-width:var(--border-width);border-style:var(--border-style);border-color:var(--border-color);background:var(--background);-webkit-box-shadow:var(--box-shadow);box-shadow:var(--box-shadow)}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.toast-wrapper{margin-left:unset;margin-right:unset;-webkit-margin-start:auto;margin-inline-start:auto;-webkit-margin-end:auto;margin-inline-end:auto}}.toast-container{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;height:inherit;min-height:inherit;max-height:inherit;pointer-events:auto;contain:content}.toast-content{padding-left:15px;padding-right:15px;padding-top:15px;padding-bottom:15px;display:-ms-flexbox;display:flex;-ms-flex:1;flex:1;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;text-align:center}@supports ((-webkit-margin-start: 0) or (margin-inline-start: 0)) or (-webkit-margin-start: 0){.toast-content{padding-left:unset;padding-right:unset;-webkit-padding-start:15px;padding-inline-start:15px;-webkit-padding-end:15px;padding-inline-end:15px}}.toast-header{margin-bottom:2px;font-weight:700}.toast-message{-ms-flex:1;flex:1;white-space:var(--white-space)}.toast-button-group{display:-ms-flexbox;display:flex}.toast-button{border:0;outline:none;color:var(--button-color);z-index:0}.toast-icon{font-size:1.4em}.toast-button-inner{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.toast-wrapper.toast-top{top:0;-webkit-transform:translate3d(0, -200%, 0);transform:translate3d(0, -200%, 0)}.toast-wrapper.toast-middle{opacity:0.01}.toast-wrapper.toast-bottom{bottom:0;-webkit-transform:translate3d(0, 200%, 0);transform:translate3d(0, 200%, 0)}:host(.bkkr-color){--button-color:inherit;color:current-color(contrast)}:host(.bkkr-color) .toast-button-cancel{color:inherit}:host(.bkkr-color) .toast-wrapper{background:current-color(base)}";var C=t("bkkr_toast",function(){function t(t){var n=this;e(this,t);this.didPresent=r(this,"toastDidPresent",7);this.willPresent=r(this,"toastWillPresent",7);this.willDismiss=r(this,"toastWillDismiss",7);this.didDismiss=r(this,"toastDidDismiss",7);this.gestureAnimationDismissing=false;this.presented=false;this.duration=0;this.keyboardClose=false;this.position="top";this.swipeToClose=true;this.animated=true;this.dispatchCancelHandler=function(t){var e=t.detail.role;if(d(e)){var r=n.getButtons().find((function(t){return t.role==="cancel"}));n.callButtonHandler(r)}}}t.prototype.swipeToCloseChanged=function(t){if(this.gesture){this.gesture.enable(t)}else if(t){this.initSwipeToClose()}};t.prototype.connectedCallback=function(){f(this.el)};t.prototype.present=function(){return __awaiter(this,void 0,void 0,(function(){var t=this;return __generator(this,(function(e){switch(e.label){case 0:return[4,h(this,x,this.position)];case 1:e.sent();if(this.swipeToClose){this.initSwipeToClose()}if(this.duration>0){this.durationTimeout=setTimeout((function(){return t.dismiss(undefined,"timeout")}),this.duration)}return[2]}}))}))};t.prototype.initSwipeToClose=function(){var t=this;var e=this.leaveAnimation||y;var r=this.animation=e(this.el.shadowRoot,this.position);this.gesture=k(this.el.shadowRoot,r,this.position,(function(){t.gestureAnimationDismissing=true;t.animation.onFinish((function(){return __awaiter(t,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this.dismiss(undefined,"gesture")];case 1:t.sent();this.gestureAnimationDismissing=false;return[2]}}))}))}))}));this.gesture.enable(true)};t.prototype.dismiss=function(t,e){return __awaiter(this,void 0,void 0,(function(){var r,n;return __generator(this,(function(i){switch(i.label){case 0:if(this.gestureAnimationDismissing&&e!=="gesture"){return[2,false]}if(this.durationTimeout){clearTimeout(this.durationTimeout)}r=p.get(this)||[];return[4,b(this,t,e,y,this.position)];case 1:n=i.sent();if(n){if(this.animation){this.animation.destroy()}r.forEach((function(t){return t.destroy()}))}this.animation=undefined;return[2,n]}}))}))};t.prototype.onDidDismiss=function(){return m(this.el,"toastDidDismiss")};t.prototype.onWillDismiss=function(){return m(this.el,"toastWillDismiss")};t.prototype.getButtons=function(){var t=this.buttons?this.buttons.map((function(t){return typeof t==="string"?{text:t}:t})):[];return t};t.prototype.buttonClick=function(t){return __awaiter(this,void 0,void 0,(function(){var e,r;return __generator(this,(function(n){switch(n.label){case 0:e=t.role;if(d(e)){return[2,this.dismiss(undefined,e)]}return[4,this.callButtonHandler(t)];case 1:r=n.sent();if(r){return[2,this.dismiss(undefined,e)]}return[2,Promise.resolve()]}}))}))};t.prototype.callButtonHandler=function(t){return __awaiter(this,void 0,void 0,(function(){var e,r;return __generator(this,(function(n){switch(n.label){case 0:if(!(t&&t.handler))return[3,4];n.label=1;case 1:n.trys.push([1,3,,4]);return[4,t.handler()];case 2:e=n.sent();if(e===false){return[2,false]}return[3,4];case 3:r=n.sent();console.error(r);return[3,4];case 4:return[2,true]}}))}))};t.prototype.renderButtons=function(t,e){var r;var i=this;if(t.length===0){return}var o=(r={"toast-button-group":true},r["toast-button-group-"+e]=true,r);return n("div",{class:o},t.map((function(t){return n("button",{type:"button",class:D(t),tabIndex:0,onClick:function(){return i.buttonClick(t)},part:"button"},n("div",{class:"toast-button-inner"},t.icon&&n("BKKR-icon",{icon:t.icon,slot:t.text===undefined?"icon-only":undefined,class:"toast-icon"}),t.text))})))};t.prototype.render=function(){var t;var e=this.getButtons();var r=e.filter((function(t){return t.side==="start"}));var o=e.filter((function(t){return t.side!=="start"}));var a=(t={"toast-wrapper":true},t["toast-"+this.position]=true,t);return n(i,{style:{zIndex:""+(6e4+this.overlayIndex)},class:g(this.color,Object.assign({},v(this.cssClass))),tabindex:"-1",onBkkrToastWillDismiss:this.dispatchCancelHandler},n("div",{class:a},n("div",{class:"toast-container",part:"container"},this.renderButtons(r,"start"),n("div",{class:"toast-content"},this.header!==undefined&&n("div",{class:"toast-header",part:"header"},this.header),this.message!==undefined&&n("div",{class:"toast-message",part:"message",innerHTML:c(this.message)})),this.renderButtons(o,"end"))))};Object.defineProperty(t.prototype,"el",{get:function(){return o(this)},enumerable:false,configurable:true});Object.defineProperty(t,"watchers",{get:function(){return{swipeToClose:["swipeToCloseChanged"]}},enumerable:false,configurable:true});return t}());var D=function(t){var e;return Object.assign((e={"toast-button":true,"toast-button-icon-only":t.icon!==undefined&&t.text===undefined},e["toast-button-"+t.role]=t.role!==undefined,e["state-focusable"]=true,e["state-activatable"]=true,e),v(t.cssClass))};C.style=T}}}));


text:
import { APP_URL, gen, password, website } from '../../../../helpers'

context('Login Flow Success', () => {
  const email = gen.email()
  const password = gen.password()

  before(() => {
    cy.registerApi({ email, password, fields: { 'traits.website': website } })
  })

  beforeEach(() => {
    cy.clearCookies()
    cy.visit(APP_URL + '/auth/login')
  })

  it('should sign up and be logged in', () => {
    cy.get('input[name="identifier"]').type(email)
    cy.get('input[name="password"]').type(password)
    cy.get('button[type="submit"]').click()

    cy.session().should((session) => {
      const { identity } = session
      expect(identity.id).to.not.be.empty
      expect(identity.schema_id).to.equal('default')
      expect(identity.schema_url).to.equal(`${APP_URL}/schemas/default`)
      expect(identity.traits.website).to.equal(website)
      expect(identity.traits.email).to.equal(email)
    })
  })

  it('should sign in with case insensitive identifier', () => {
    cy.get('input[name="identifier"]').type(email.toUpperCase())
    cy.get('input[name="password"]').type(password)
    cy.get('button[type="submit"]').click()

    cy.session().should((session) => {
      const { identity } = session
      expect(identity.id).to.not.be.empty
      expect(identity.schema_id).to.equal('default')
      expect(identity.schema_url).to.equal(`${APP_URL}/schemas/default`)
      expect(identity.traits.website).to.equal(website)
      expect(identity.traits.email).to.equal(email)
    })
  })
})


text:
// eslint-disable-next-line ember/no-classic-components
import Component from '@ember/component';
import { action } from '@ember/object';
import { reads } from '@ember/object/computed';
import { inject } from '@ember/service';
import { tagName } from '@ember-decorators/component';
// eslint-disable-next-line ember/no-mixins
import Sortable from 'api-umbrella-admin-ui/mixins/sortable';
import bootbox from 'bootbox';
import classic from 'ember-classic-decorator';

@classic
@tagName("")
export default class RewriteTable extends Component.extend(Sortable) {
  @inject()
  store;

  openModal = false;

  @reads('model.rewrites')
  sortableCollection;

  @action
  add() {
    this.set('rewriteModel', this.store.createRecord('api/rewrite'));
    this.set('openModal', true);
  }

  @action
  edit(rewrite) {
    this.set('rewriteModel', rewrite);
    this.set('openModal', true);
  }

  @action
  remove(rewrite) {
    bootbox.confirm('Are you sure you want to remove this rewrite?', function(response) {
      if(response) {
        this.model.rewrites.removeObject(rewrite);
      }
    }.bind(this));
  }
}


text: module.exports={A:{A:{"2":"H D G E A B IB"},B:{"2":"0 C p J L N I"},C:{"1":"1 4 6 7 8 9 v w x y z AB BB CB","2":"0 2 3 cB F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u aB UB"},D:{"1":"1 4 6 7 8 9 s t u v w x y z AB BB CB OB GB JB HB eB KB LB MB","2":"0 2 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r"},E:{"1":"B C TB b VB","2":"F K H D G E A NB FB PB QB RB SB"},F:{"1":"f g h i j k l m n o M q r s t u v w x y z","2":"2 E B C J L N I O P Q R S T U V W X Y Z a c d e WB XB YB ZB b DB bB EB"},G:{"1":"C mB nB oB","2":"5 G FB dB fB gB hB iB jB kB lB"},H:{"2":"pB"},I:{"1":"GB","2":"3 5 F qB rB sB tB uB vB"},J:{"2":"D A"},K:{"1":"M","2":"A B C b DB EB"},L:{"1":"HB"},M:{"1":"1"},N:{"2":"A B"},O:{"1":"wB"},P:{"1":"K xB yB","2":"F"},Q:{"1":"zB"},R:{"1":"0B"}},B:1,C:"rel=noopener"};


text:
var express = require("express")
var pokemon = require("../models/pokemon")
var router = express.Router(); //create router here

router.get("/", function(req, res){
    pokemon.all(function(data){
        var pokemonObj = {
            pokemons: data
        };
        console.log(pokemonObj);
        res.render("index", pokemonObj)
    });
});

router.post("/api/pokemons", function(req, res) {
    pokemon.add([
        "pokemon_name"
      ], [
        req.body.pokemon_name
      ], function(result) {
        // Send back the ID of the new quote
        res.json({ id: result.insertId });
      });
    });

router.put("/api/pokemons/:id", function(req, res) {
        var condition = "id = " + req.params.id;

        console.log("condition", condition);

        pokemon.update({
          caught: true
        }, condition, function(result) {
          if (result.changedRows == 0) {
            // If no rows were changed, then the ID must not exist, so 404
            return res.status(404).end();
          } else {
            res.status(200).end();
          }
        });
      });

module.exports = router;