<commit_before><<<<<<< HEAD
import * as util from '../../flows/utils'

/* eslint-disable no-await-in-loop */
/* eslint-disable no-unused-vars */

const clickSaveContinue = async () => {
  console.log('here')
  await util.clickButton('Save and continue')
}

const createBrief = async () => {
  await util.clickLink('/2/outcome-choice', true)
  await util.clickLink('/2/buyer-rfx/create', true)
  await util.clickLink('Create and publish request')
  await util.clickButton('Start now')
}

const selectDropBox = async () => {
  const rfxPanelCategory = process.env.RFX_PANEL_CATEGORY
  await page.select(`#seller-search-category-select`, rfxPanelCategory)

  const rfxSellerName = process.env.RFX_SELLER_NAME
  await util.sleep(100)
  await util.typeInReactInput('seller-search', { value: rfxSellerName })
  let searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[1]/a`)
  let sr = searchResult[0]
  sr.click()

  await util.typeInReactInput('seller-search', { value: '%%%' })
  searchResult = await util.getElementHandles('//input[@id="seller-search"]/../../ul/li')
  const resultCount = searchResult.length
  for (let i = 1; i <= resultCount; i += 1) {
    if (i > 1) {
      await util.sleep(100)
      await util.typeInReactInput('seller-search', { value: '%%%' })
=======
import { sleep } from "../utils";

export const create = async (params) => {
    console.log('Starting to create outcome RXF brief');
    await createBrief();
    await fillWhoCanRespond();
    await fillAbout(params.title, params.locations);
    await fillResponseFormats();
    await fillRequirements();
    await fillTimeframesAndBudget();
    await fillEvaluationCriteria();
    await fillClosingDate();
    await fillPublishBrief();
}

const createBrief = async () => {
    await clickLink('/2/outcome-choice', true);
    await clickLink('/2/buyer-rfx/create', true);
    await clickLink('Create and publish request');
    await clickButton('Start now');
}

const fillWhoCanRespond = async () => {
    await clickSaveContinue();
    await matchText('li', 'You must select at least one panel category');
    await selectDropBox();
}

const selectDropBox = async () => {
    const rfxPanelCategory = process.env.RFX_PANEL_CATEGORY;
    await page.select(`#seller-search-category-select`, rfxPanelCategory);

    const rfxSellerName = process.env.RFX_SELLER_NAME;
    await sleep(100);
    await typeInReactInput('seller-search', { value: rfxSellerName });
    let searchResult = await getElementHandles(`//input[@id="seller-search"]/../../ul/li[1]/a`);
    let sr = searchResult[0];
    sr.click();

    await typeInReactInput('seller-search', { value: '%%%' });
    searchResult = await getElementHandles('//input[@id="seller-search"]/../../ul/li');
    let resultCount = searchResult.length;
    for (let i=1; i<=resultCount; i++) {
        if (i>1) {
            await sleep(100);
            await typeInReactInput('seller-search', { value: '%%%' });
        }
        searchResult = await getElementHandles(`//input[@id="seller-search"]/../../ul/li[${i}]/a`);
        sr = searchResult[0];
        sr.click();
>>>>>>> 00ec2611b054c474573a7c9305988ef011c85ef5
    }
    searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[${i}]/a`)
    sr = searchResult[0]
    sr.click()
  }
  await clickSaveContinue()
}

<<<<<<< HEAD
const fillWhoCanRespond = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one panel category')
  await selectDropBox()
}

const fillAbout = async (role, locations) => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a title')
  await util.matchText('li', 'You must add the name of your department, agency or organisation')
  await util.matchText('li', 'You must add a summary of work to be done')
  await util.matchText('li', 'You must add the working arrangements')
  await util.matchText('li', 'You must select a location of where the work can be done')
  await util.typeInReactInput('title', { value: role })
  await util.typeInReactInput('organisation', { numberOfCharacters: 100 })
  await util.typeInReactInput('summary', { numberOfWords: 150 })

  /*
  for (let i; i < locations.length; i+=1) {
    const location = locations[i]
    await util.selectCheck(location)
  }

  */

  locations.forEach(async location => {
    await util.selectCheck(location)
  })

  await util.typeInReactInput('working_arrangements', { numberOfCharacters: 150 })
  await util.typeInReactInput('clearance', { numberOfCharacters: 100 })
  await clickSaveContinue()
=======
const fillAbout = async (role, locations) => {
    await clickSaveContinue();
    await matchText('li', 'You must add a title');
    await matchText('li', 'You must add the name of your department, agency or organisation');
    await matchText('li', 'You must add a summary of work to be done');
    await matchText('li', 'You must add the working arrangements');
    await matchText('li', 'You must select a location of where the work can be done');
    await typeInReactInput('title', { value: role });
    await typeInReactInput('organisation', { numberOfCharacters: 100 });
    await typeInReactInput('summary', { numberOfWords: 150 });

    for (let i in locations) {
        let location = locations[i];
        await selectCheck(location);
    }
    await typeInReactInput('working_arrangements', {numberOfCharacters: 150});
    await typeInReactInput('clearance', {numberOfCharacters: 100});
    await clickSaveContinue();
>>>>>>> 00ec2611b054c474573a7c9305988ef011c85ef5
}

const fillResponseFormats = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must choose what you would like sellers to provide through the Marketplace')
  await util.selectCheck('Written proposal')
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one proposal type.')
  await util.selectCheck('Breakdown of costs')
  await util.selectCheck('Case study')
  await util.selectCheck('References')
  await util.selectCheck('Résumés')
  await util.selectCheck('Response template')
  await util.selectCheck('Presentation')
  await clickSaveContinue()
}

const fillRequirements = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must upload a requirements document')
  await util.upload('file_0', 'document.pdf', 'Requirements document')
  await util.upload('file_0', 'document.pdf', 'Response template')
  await util.upload('file_0', 'document.pdf', 'Additional documents (optional)')
  await util.typeInReactInput('industryBriefing', { numberOfWords: 150 })
  await clickSaveContinue()
}
const fillTimeframesAndBudget = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add an estimated start date')
  await util.matchText('li', 'You must add a contract length')
  await util.typeInReactInput('start_date', { numberOfCharacters: 150 })
  await util.typeInReactInput('contract_length-label', { numberOfCharacters: 50 })
  await util.typeInReactInput('contract_extensions', { numberOfCharacters: 50 })
  await util.typeInReactInput('budget_range', { numberOfWords: 150 })
  await clickSaveContinue()
}

const fillEvaluationCriteria = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.matchText('li', 'Weightings must be greater than 0.')
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.clickLink('Add another criteria')
  await util.typeInReactInput('criteria_0', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_0', { value: '50' })
  await util.typeInReactInput('criteria_1', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_1', { value: '50' })
  await clickSaveContinue()
}

const fillClosingDate = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a closing date at least 2 days from now')
  await util.matchText('li', 'You must add a contact number')
  const now = new Date()
  const future = new Date(now.setDate(now.getDate() + 14))
  await util.typeInReactInput('day', { value: `${future.getDate()}` })
  await util.typeInReactInput('month', { value: `${future.getMonth() + 1}` })
  await util.typeInReactInput('year', { value: `${future.getFullYear()}` })
  await util.typeInReactInput('contact', { value: '0123456789' })
  await clickSaveContinue()
}

const fillPublishBrief = async () => {
  await util.clickButton('Publish')
  await util.matchText('h1', 'Your opportunity is now live, and the invited sellers have been notified.')
}

const create = async params => {
  console.log('Starting to create outcome RXF brief')
  await createBrief()
  await fillWhoCanRespond()
  await fillAbout(params.title, params.locations)
  await fillResponseFormats()
  await fillRequirements()
  await fillTimeframesAndBudget()
  await fillEvaluationCriteria()
  await fillClosingDate()
  await fillPublishBrief()
}

<<<<<<< HEAD
export default create
=======

>>>>>>> 00ec2611b054c474573a7c9305988ef011c85ef5
<commit_msg>Update rfx.js<commit_after>import * as util from '../../flows/utils'

/* eslint-disable no-await-in-loop */
/* eslint-disable no-unused-vars */

const clickSaveContinue = async () => {
  console.log('here')
  await util.clickButton('Save and continue')
}

const createBrief = async () => {
  await util.clickLink('/2/outcome-choice', true)
  await util.clickLink('/2/buyer-rfx/create', true)
  await util.clickLink('Create and publish request')
  await util.clickButton('Start now')
}

const selectDropBox = async () => {
  const rfxPanelCategory = process.env.RFX_PANEL_CATEGORY
  await page.select(`#seller-search-category-select`, rfxPanelCategory)

  const rfxSellerName = process.env.RFX_SELLER_NAME
  await util.sleep(100)
  await util.typeInReactInput('seller-search', { value: rfxSellerName })
  let searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[1]/a`)
  let sr = searchResult[0]
  sr.click()

  await util.typeInReactInput('seller-search', { value: '%%%' })
  searchResult = await util.getElementHandles('//input[@id="seller-search"]/../../ul/li')
  const resultCount = searchResult.length
  for (let i = 1; i <= resultCount; i += 1) {
    if (i > 1) {
      await util.sleep(100)
      await util.typeInReactInput('seller-search', { value: '%%%' })
    }
    searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[${i}]/a`)
    sr = searchResult[0]
    sr.click()
  }
  await clickSaveContinue()
}

const fillWhoCanRespond = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one panel category')
  await selectDropBox()
}

const fillAbout = async (role, locations) => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a title')
  await util.matchText('li', 'You must add the name of your department, agency or organisation')
  await util.matchText('li', 'You must add a summary of work to be done')
  await util.matchText('li', 'You must add the working arrangements')
  await util.matchText('li', 'You must select a location of where the work can be done')
  await util.typeInReactInput('title', { value: role })
  await util.typeInReactInput('organisation', { numberOfCharacters: 100 })
  await util.typeInReactInput('summary', { numberOfWords: 150 })

  /*
  for (let i; i < locations.length; i+=1) {
    const location = locations[i]
    await util.selectCheck(location)
  }

  */

  locations.forEach(async location => {
    await util.selectCheck(location)
  })

  await util.typeInReactInput('working_arrangements', { numberOfCharacters: 150 })
  await util.typeInReactInput('clearance', { numberOfCharacters: 100 })
  await clickSaveContinue()
}

const fillResponseFormats = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must choose what you would like sellers to provide through the Marketplace')
  await util.selectCheck('Written proposal')
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one proposal type.')
  await util.selectCheck('Breakdown of costs')
  await util.selectCheck('Case study')
  await util.selectCheck('References')
  await util.selectCheck('Résumés')
  await util.selectCheck('Response template')
  await util.selectCheck('Presentation')
  await clickSaveContinue()
}

const fillRequirements = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must upload a requirements document')
  await util.upload('file_0', 'document.pdf', 'Requirements document')
  await util.upload('file_0', 'document.pdf', 'Response template')
  await util.upload('file_0', 'document.pdf', 'Additional documents (optional)')
  await util.typeInReactInput('industryBriefing', { numberOfWords: 150 })
  await clickSaveContinue()
}
const fillTimeframesAndBudget = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add an estimated start date')
  await util.matchText('li', 'You must add a contract length')
  await util.typeInReactInput('start_date', { numberOfCharacters: 150 })
  await util.typeInReactInput('contract_length-label', { numberOfCharacters: 50 })
  await util.typeInReactInput('contract_extensions', { numberOfCharacters: 50 })
  await util.typeInReactInput('budget_range', { numberOfWords: 150 })
  await clickSaveContinue()
}

const fillEvaluationCriteria = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.matchText('li', 'Weightings must be greater than 0.')
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.clickLink('Add another criteria')
  await util.typeInReactInput('criteria_0', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_0', { value: '50' })
  await util.typeInReactInput('criteria_1', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_1', { value: '50' })
  await clickSaveContinue()
}

const fillClosingDate = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a closing date at least 2 days from now')
  await util.matchText('li', 'You must add a contact number')
  const now = new Date()
  const future = new Date(now.setDate(now.getDate() + 14))
  await util.typeInReactInput('day', { value: `${future.getDate()}` })
  await util.typeInReactInput('month', { value: `${future.getMonth() + 1}` })
  await util.typeInReactInput('year', { value: `${future.getFullYear()}` })
  await util.typeInReactInput('contact', { value: '0123456789' })
  await clickSaveContinue()
}

const fillPublishBrief = async () => {
  await util.clickButton('Publish')
  await util.matchText('h1', 'Your opportunity is now live, and the invited sellers have been notified.')
}

const create = async params => {
  console.log('Starting to create outcome RXF brief')
  await createBrief()
  await fillWhoCanRespond()
  await fillAbout(params.title, params.locations)
  await fillResponseFormats()
  await fillRequirements()
  await fillTimeframesAndBudget()
  await fillEvaluationCriteria()
  await fillClosingDate()
  await fillPublishBrief()
}

export default create

<|endoftext|>


<commit_before>

module.exports = {

  getdefs: function(chords) {

    defs = [];

    for (i = 0; i < chords.length; i++) {
      for (j = 0; j < alldefs.length; j++) {
        if (chords[i] == alldefs[j].chord && alldefs[j].rank == 0) {
          defs.push(alldefs[j]);
        }
      }
    }

    return defs;
  },

  toString: function(defs) {
    string = "";

    for (i = 0; i < defs.length; i++) {
      string += defs[i].define + "\n";
    }

    return string;
  }
};

var alldefs = [
  { rank:0, chord:"Am", define:"{define: Am base-fret 0 frets x 0 2 2 1 0}" },
  { rank:0, chord:"G", define:"{define: G base-fret 0 frets 3 2 0 0 0 3}" }
]
<commit_msg>added chord definitions<commit_after>

module.exports = {

  getdefs: function(chords) {

    defs = [];

    for (i = 0; i < chords.length; i++) {
      for (j = 0; j < alldefs.length; j++) {
        if (chords[i] == alldefs[j].name && alldefs[j].rank == 0) {
          defs.push(alldefs[j]);
        }
      }
    }

    return defs;
  },

  toString: function(defs) {
    string = "";

    for (i = 0; i < defs.length; i++) {
      string += defs[i].define + "\n";
    }

    return string;
  }
};

var alldefs = [
  { rank:0, name:"Am", define:"{define: Am base-fret 0 frets x 0 2 2 1 0}" },
  { rank:0, name:"G", define:"{define: G base-fret 0 frets 3 2 0 0 0 3}" },
  { rank:0, name:"Gbsus4", define:"{define: Gbsus4 base-fret 0 frets x x 4 4 2 2}" },
  { rank:0, name:"Bbm9", define:"{define: Bbm9 base-fret 6 frets x x x 1 1 3}" },
  { rank:0, name:"Abm7", define:"{define: Abm7 base-fret 4 frets x x 1 1 1 1}" },
  { rank:0, name:"Ab4", define:"{define: Ab4 base-fret 0 frets x x 1 1 2 4}" },
  { rank:0, name:"F#", define:"{define: F# base-fret 0 frets 2 4 4 3 2 2}" },
  { rank:0, name:"Ab7", define:"{define: Ab7 base-fret 0 frets x x 1 1 1 2}" },
  { rank:0, name:"E5", define:"{define: E5 base-fret 7 frets 0 1 3 3 0 0}" },
  { rank:0, name:"E6", define:"{define: E6 base-fret 9 frets x x 3 3 3 3}" },
  { rank:0, name:"E7", define:"{define: E7 base-fret 0 frets 0 2 2 1 3 0}" },
  { rank:0, name:"A#4", define:"{define: A#4 base-fret 0 frets x x 3 3 4 1}" },
  { rank:0, name:"A/F#", define:"{define: A/F# base-fret 0 frets 2 0 2 2 2 0}" },
  { rank:0, name:"Am/F#", define:"{define: Am/F# base-fret 0 frets 2 0 3 3 2 0}" },
  { rank:0, name:"E9", define:"{define: E9 base-fret 0 frets 1 3 1 2 1 3}" },
  { rank:0, name:"A#7", define:"{define: A#7 base-fret 3 frets x x 1 1 1 2}" },
  { rank:0, name:"F#m7", define:"{define: F#m7 base-fret 0 frets 2 4 2 2 2 2}" },
  { rank:0, name:"F#m6", define:"{define: F#m6 base-fret 0 frets x x 1 2 2 2}" },
  { rank:0, name:"Emadd9", define:"{define: Emadd9 base-fret 0 frets 0 2 4 0 0 0}" },
  { rank:0, name:"Cm", define:"{define: Cm base-fret 3 frets x 1 3 3 2 1}" },
  { rank:0, name:"C#m7", define:"{define: C#m7 base-fret 4 frets x 1 3 1 2 1}" },
  { rank:0, name:"F11", define:"{define: F11 base-fret 0 frets 1 3 1 3 1 1}" },
  { rank:0, name:"Emsus4", define:"{define: Emsus4 base-fret 0 frets 0 0 2 0 0 0}" },
  { rank:0, name:"Gbm7", define:"{define: Gbm7 base-fret 0 frets x x 4 3 3 2}" },
  { rank:0, name:"Bmaj", define:"{define: Bmaj base-fret 0 frets x 2 4 3 4 x}" },
  { rank:0, name:"Ebadd9", define:"{define: Ebadd9 base-fret 0 frets x 1 1 3 4 1}" },
  { rank:0, name:"G#", define:"{define: G# base-fret 4 frets 1 3 3 2 1 1}" },
  { rank:0, name:"GD11", define:"{define: D11 base-fret 5 frets x 1 1 1 1 1}" },
  { rank:0, name:"F9", define:"{define: F9 base-fret 0 frets 2 4 2 3 2 4}" },
  { rank:0, name:"F6", define:"{define: F6 base-fret 0 frets x 3 3 2 3 x}" },
  { rank:0, name:"F7", define:"{define: F7 base-fret 0 frets 1 3 1 2 1 1}" },
  { rank:0, name:"Fadd9", define:"{define: Fadd9 base-fret 0 frets 3 0 3 2 1 1}" },
  { rank:0, name:"Abmaj7", define:"{define: Abmaj7 base-fret 0 frets x x 1 1 1 3}" },
  { rank:0, name:"Emaj7", define:"{define: Emaj7 base-fret 0 frets 0 2 1 1 0 x}" },
  { rank:0, name:"Dm", define:"{define: Dm base-fret 0 frets x 0 0 2 3 1}" },
  { rank:0, name:"Fmaj7", define:"{define: Fmaj7 base-fret 0 frets x 3 3 2 1 0}" },
  { rank:0, name:"F4", define:"{define: F4 base-fret 0 frets x x 3 3 1 1}" },
  { rank:0, name:"G6sus4", define:"{define: G6sus4 base-fret 0 frets 0 2 0 0 1 0}" },
  { rank:0, name:"Gbmaj7", define:"{define: Gbmaj7 base-fret 0 frets x x 4 3 2 1}" },
  { rank:0, name:"Dm13", define:"{define: Dm13 base-fret 0 frets x 3 3 2 0 0}" },
  { rank:0, name:"Dm11", define:"{define: Dm11 base-fret 0 frets x 0 0 0 1 1}" },
  { rank:0, name:"C#m", define:"{define: C#m base-fret 4 frets x 1 3 3 2 1}" },
  { rank:0, name:"Fmaj7/A", define:"{define: Fmaj7/A base-fret 0 frets x 0 3 2 1 0}" },
  { rank:0, name:"D", define:"{define: D base-fret 0 frets x 0 0 2 3 2}" },
  { rank:0, name:"E", define:"{define: E base-fret 0 frets 0 2 2 1 0 0}" },
  { rank:0, name:"F", define:"{define: F base-fret 0 frets 1 3 3 2 1 1}" },
  { rank:0, name:"A", define:"{define: A base-fret 0 frets x 0 2 2 2 0}" },
  { rank:0, name:"Csus9", define:"{define: Csus9 base-fret 7 frets x x 4 1 2 4}" },
  { rank:0, name:"Em9", define:"{define: Em9 base-fret 0 frets 0 2 0 0 0 2}" },
  { rank:0, name:"B", define:"{define: B base-fret 0 frets x 2 4 4 4 2}" },
  { rank:0, name:"C", define:"{define: C base-fret 0 frets x 3 2 0 1 0}" },
  { rank:0, name:"Am/G", define:"{define: Am/G base-fret 0 frets 3 0 2 2 1 0}" },
  { rank:0, name:"Csus2", define:"{define: Csus2 base-fret 0 frets x 3 0 0 1 x}" },
  { rank:0, name:"G7sus4", define:"{define: G7sus4 base-fret 0 frets 3 3 0 0 1 1}" },
  { rank:0, name:"G/D", define:"{define: G/D base-fret 4 frets x 2 2 1 0 0}" },
  { rank:0, name:"Fm7", define:"{define: Fm7 base-fret 0 frets 1 3 1 1 1 1}" },
  { rank:0, name:"G7", define:"{define: G7 base-fret 0 frets 3 2 0 0 0 1}" },
  { rank:0, name:"Gm/Bb", define:"{define: Gm/Bb base-fret 4 frets 3 2 2 1 0 0}" },
  { rank:0, name:"G/B", define:"{define: G/B base-fret 0 frets x 2 0 0 0 3}" },
  { rank:0, name:"G9", define:"{define: G9 base-fret 0 frets 3 x 0 2 0 1}" },
  { rank:0, name:"G/A", define:"{define: G/A base-fret 0 frets x 0 0 0 0 3}" },
  { rank:0, name:"G6", define:"{define: G6 base-fret 0 frets 3 2 0 0 0 0}" },
  { rank:0, name:"F#maj7", define:"{define: F#maj7 base-fret 0 frets x x 4 3 2 1}" },
  { rank:0, name:"Esus", define:"{define: Esus base-fret 0 frets 0 2 2 2 0 0}" },
  { rank:0, name:"Fm6", define:"{define: Fm6 base-fret 0 frets x x 0 1 1 1}" },
  { rank:0, name:"Em", define:"{define: Em base-fret 0 frets 0 2 2 0 0 0}" },
  { rank:0, name:"Em6", define:"{define: Em6 base-fret 0 frets 0 2 2 0 2 0}" },
  { rank:0, name:"Abm", define:"{define: Abm base-fret 4 frets 1 3 3 1 1 1}" },
  { rank:0, name:"Em7", define:"{define: Em7 base-fret 0 frets 0 2 0 0 0 0}" },
  { rank:0, name:"F#11", define:"{define: F#11 base-fret 0 frets 2 4 2 4 2 2}" },
  { rank:0, name:"Fmmaj7", define:"{define: Fmmaj7 base-fret 0 frets x 3 3 1 1 0}" },
  { rank:0, name:"Adim", define:"{define: Adim base-fret 0 frets x x 1 2 1 2}" },
  { rank:0, name:"Bm6", define:"{define: Bm6 base-fret 0 frets x x 4 4 3 4}" },
  { rank:0, name:"Cm7", define:"{define: Cm7 base-fret 3 frets x 1 3 1 2 1}" },
  { rank:0, name:"Gbdim", define:"{define: Gbdim base-fret 0 frets x x 1 2 1 2}" },
  { rank:0, name:"Gb", define:"{define: Gb base-fret 0 frets 2 4 4 3 2 2}" },
  { rank:0, name:"F7/A", define:"{define: F7/A base-fret 0 frets x 0 1 2 1 1}" },
  { rank:0, name:"Bm7", define:"{define: Bm7 base-fret 2 frets x 1 3 1 2 1}" },
  { rank:0, name:"A#dim", define:"{define: A#dim base-fret 0 frets x x 2 3 2 3}" },
  { rank:0, name:"Cm11", define:"{define: Cm11 base-fret 3 frets x 1 3 1 4 x}" },
  { rank:0, name:"Am9", define:"{define: Am9 base-fret 5 frets x 0 1 1 1 3}" },
  { rank:0, name:"Cmaj7", define:"{define: Cmaj7 base-fret 0 frets x 3 2 0 0 0}" },
  { rank:0, name:"A/G#", define:"{define: A/G# base-fret 0 frets 4 0 2 2 2 0}" },
  { rank:0, name:"Dm7", define:"{define: Dm7 base-fret 0 frets x 0 0 2 1 1}" },
  { rank:0, name:"Am7", define:"{define: Am7 base-fret 0 frets x 0 2 0 1 0}" },
  { rank:0, name:"Am6", define:"{define: Am6 base-fret 0 frets x 0 2 2 1 2}" },
  { rank:0, name:"Dm6", define:"{define: Dm6 base-fret 0 frets x 0 0 2 0 1}" },
  { rank:0, name:"C/B", define:"{define: C/B base-fret 0 frets x 2 2 0 1 0}" },
  { rank:0, name:"F#/E", define:"{define: F#/E base-fret 0 frets 0 4 4 3 2 2}" },
  { rank:0, name:"Dm9", define:"{define: Dm9 base-fret 3 frets x 3 1 3 3 3}" },
  { rank:0, name:"Fm", define:"{define: Fm base-fret 0 frets 1 3 3 1 1 1}" },
  { rank:0, name:"F/C", define:"{define: F/C base-fret 0 frets x x 3 2 1 1}" },
  { rank:0, name:"A13", define:"{define: A13 base-fret 5 frets x 0 1 2 3 1}" },
  { rank:0, name:"F/A", define:"{define: F/A base-fret 0 frets x 0 3 2 1 1}" },
  { rank:0, name:"F/G", define:"{define: F/G base-fret 0 frets 3 3 3 2 1 1}" },
  { rank:0, name:"Gbm", define:"{define: Gbm base-fret 0 frets 2 4 4 2 2 2}" },
  { rank:0, name:"A4", define:"{define: A4 base-fret 0 frets 0 0 2 2 0 0}" },
  { rank:0, name:"F#4", define:"{define: F#4 base-fret 0 frets x x 4 4 2 2}" },
  { rank:0, name:"A6", define:"{define: A6 base-fret 0 frets x x 2 2 2 2}" },
  { rank:0, name:"Gm", define:"{define: Gm base-fret 3 frets 1 3 3 1 1 1}" },
  { rank:0, name:"A7", define:"{define: A7 base-fret 0 frets x 0 2 0 2 0}" },
  { rank:0, name:"Dsus2", define:"{define: Dsus2 base-fret 0 frets x x 0 2 3 0}" },
  { rank:0, name:"F#9", define:"{define: F#9 base-fret 0 frets x 1 2 1 2 2}" },
  { rank:0, name:"A9", define:"{define: A9 base-fret 0 frets x 0 2 1 0 0}" },
  { rank:0, name:"F#7", define:"{define: F#7 base-fret 0 frets x x 4 3 2 0}" },
  { rank:0, name:"A#", define:"{define: A# base-fret 0 frets x 1 3 3 3 1}" },
  { rank:0, name:"A/D", define:"{define: A/D base-fret 0 frets x x 0 0 2 2}" },
  { rank:0, name:"B/F#", define:"{define: B/F# base-fret 0 frets 0 4 4 4 0 0}" },
  { rank:0, name:"Abdim", define:"{define: Abdim base-fret 0 frets x x 0 1 0 1}" },
  { rank:0, name:"G11", define:"{define: G11 base-fret 0 frets 3 x 0 2 1 1}" },
  { rank:0, name:"Cadd9", define:"{define: Cadd9 base-fret 0 frets x 3 2 0 3 0}" },
  { rank:0, name:"G7b9", define:"{define: G7b9 base-fret 0 frets x x 0 1 0 1}" },
  { rank:0, name:"Em/B", define:"{define: Em/B base-fret 0 frets x 2 2 0 0 0}" },
  { rank:0, name:"Amaj7", define:"{define: Amaj7 base-fret 0 frets x 0 2 1 2 0}" },
  { rank:0, name:"B4", define:"{define: B4 base-fret 2 frets x x 3 3 4 1}" },
  { rank:0, name:"B9", define:"{define: B9 base-fret 7 frets 1 3 1 2 1 3}" },
  { rank:0, name:"Em/D", define:"{define: Em/D base-fret 0 frets x x 0 0 0 0}" },
  { rank:0, name:"B7", define:"{define: B7 base-fret 0 frets x 2 1 2 0 2}" },
  { rank:0, name:"Asus", define:"{define: Asus base-fret 0 frets x x 2 2 3 0}" },
  { rank:0, name:"C11", define:"{define: C11 base-fret 3 frets x 1 3 1 4 1}" },
  { rank:0, name:"Gm6", define:"{define: Gm6 base-fret 0 frets x x 2 3 3 3}" },
  { rank:0, name:"Gm7", define:"{define: Gm7 base-fret 3 frets 1 3 1 1 1 1}" },
  { rank:0, name:"Fsus2/C", define:"{define: Fsus2/C base-fret 0 frets x 3 3 0 1 1}" },
  { rank:0, name:"E11", define:"{define: E11 base-fret 7 frets 1 1 1 1 2 2}" },
  { rank:0, name:"F#m", define:"{define: F#m base-fret 0 frets 2 4 4 2 2 2}" },
  { rank:0, name:"C7", define:"{define: C7 base-fret 0 frets x 3 2 0 3 0}" },
  { rank:0, name:"C9", define:"{define: C9 base-fret 8 frets 1 3 1 2 1 3}" },
  { rank:0, name:"E7#9", define:"{define: E7#9 base-fret 0 frets 0 2 2 1 3 3}" },
  { rank:0, name:"C4", define:"{define: C4 base-fret 0 frets x x 3 0 1 3}" },
  { rank:0, name:"Gb7", define:"{define: Gb7 base-fret 0 frets x x 4 3 2 0}" },
  { rank:0, name:"D#", define:"{define: D# base-fret 6 frets x 1 3 3 3 1}" },
  { rank:0, name:"Gb9", define:"{define: Gb9 base-fret 0 frets x 1 2 1 2 2}" },
  { rank:0, name:"B13", define:"{define: B13 base-fret 0 frets x 2 1 2 0 4}" },
  { rank:0, name:"G#m7", define:"{define: G#m7 base-fret 4 frets 1 3 1 1 1 1}" },
  { rank:0, name:"C#", define:"{define: C# base-fret 4 frets x 1 3 3 3 1}" },
  { rank:0, name:"Gbmin", define:"{define: Gbmin base-fret 0 frets 2 4 4 2 2 2}" },
  { rank:0, name:"Ab", define:"{define: Ab base-fret 4 frets 1 3 3 2 1 1}" },
  { rank:0, name:"Gsus4", define:"{define: Gsus4 base-fret 0 frets x x 0 0 1 1}" },
  { rank:0, name:"A#m", define:"{define: A#m base-fret 0 frets x 1 3 3 2 1}" },
  { rank:0, name:"Gdim", define:"{define: Gdim base-fret 0 frets x x 2 3 2 3}" },
  { rank:0, name:"D9", define:"{define: D9 base-fret 4 frets x 2 1 2 2 2}" },
  { rank:0, name:"D6", define:"{define: D6 base-fret 0 frets x 0 0 2 0 2}" },
  { rank:0, name:"A#maj7", define:"{define: A#maj7 base-fret 0 frets x 1 3 2 3 x}" },
  { rank:0, name:"C#add9", define:"{define: C#add9 base-fret 4 frets x 1 3 3 1 1}" },
  { rank:0, name:"A#m7", define:"{define: A#m7 base-fret 0 frets x 1 3 1 2 1}" },
  { rank:0, name:"Fsus2", define:"{define: Fsus2 base-fret 0 frets x 3 3 0 1 1}" },
  { rank:0, name:"Bb9", define:"{define: Bb9 base-fret 6 frets 1 3 1 2 1 3}" },
  { rank:0, name:"Bb", define:"{define: Bb base-fret 0 frets 1 1 3 3 3 1}" },
  { rank:0, name:"Esus4", define:"{define: Esus4 base-fret 0 frets 0 2 2 2 0 0}" },
  { rank:0, name:"C#7", define:"{define: C#7 base-fret 0 frets x x 3 4 2 4}" },
  { rank:0, name:"C#4", define:"{define: C#4 base-fret 4 frets x x 3 3 4 1}" },
  { rank:0, name:"Bb6", define:"{define: Bb6 base-fret 0 frets x x 3 3 3 3}" },
  { rank:0, name:"Bm", define:"{define: Bm base-fret 0 frets x 2 4 4 3 2}" },
  { rank:0, name:"E7b9", define:"{define: E7b9 base-fret 0 frets 0 2 0 1 3 2}" },
  { rank:0, name:"Fsus4", define:"{define: Fsus4 base-fret 0 frets 1 3 3 3 1 1}" }
]
<|endoftext|>


<commit_before>var File = java.io.File,
  FileReader = java.io.FileReader,
  FileInputStream = java.io.FileInputStream,
  out = java.lang.System.out,
  err = java.lang.System.err,
  Modifier = java.lang.reflect.Modifier,
  ZipInputStream = java.util.zip.ZipInputStream,
  zis = new ZipInputStream(new FileInputStream('./target/minecraft/craftbukkit.jar')),
  entry = null;
var content = [
  '/*********************',
  '## Events Helper Module',
  'The Events helper module provides a suite of functions - one for each possible event.',
  'For example, the events.blockBreak() function is just a wrapper function which calls events.on(org.bukkit.event.block.BlockBreakEvent, callback, priority)',
  'This module is a convenience wrapper for easily adding new event handling functions in Javascript. ',
  'At the in-game or server-console prompt, players/admins can type `events.` and use TAB completion ',
  'to choose from any of the approx. 160 different event types to listen to.',
  '',
  '### Usage',
  '',
  '    events.blockBreak(function(evt){ ',
  '      evt.player.sendMessage("You broke a block!"); ',
  '    });',
  '',
  '... which is just a shorter and less error-prone way of writing ...',
  '',
  '    events.on("block.BlockBreakEvent",function(evt){ ',
  '      evt.player.sendMessage("You broke a block!");',
  '    });',
  '',
  'The crucial difference is that the events module now has functions for each ',
  'of the built-in events. The functions are accessible via tab-completion so will help ',
  'beginning programmers to explore the events at the server console window.',
  '',
  '***/'
];
for (var i = 0; i< content.length; i++){
  out.println(content[i]);
}
while ( ( entry = zis.nextEntry) != null) {
  var name = '' + entry.name;
  if (name.match(/org\/bukkit\/event\/.+Event\.class$/)){
    name = name.replace(/\//g,'.').replace('.class','');
    var clz = java.lang.Class.forName(name);
    var isAbstract = Modifier.isAbstract(clz.getModifiers());
    if ( isAbstract ) {
      continue;
    }
    var parts = name.split('.');
    var shortName = name.replace('org.bukkit.event.','');
    var fname = parts.reverse().shift().replace(/^(.)/,function(a){ return a.toLowerCase()}).replace(/Event$/,'');

    var comment = [
      '/*********************',
      '### events.' + fname + '()',
      '',
      '#### Parameters ',
      '',
      ' * callback - A function which is called whenever the ' + shortName + ' event is fired',
      '',
      ' * priority - optional - see events.on() for more information.',
      '',
      '***/'
    ];
    for (var i = 0; i < comment.length; i++){
      out.println(comment[i]);
    }
    out.println('exports.' + fname + ' = function(callback,priority){ ');
    out.println('  return events.on(' + name + ',callback,priority);');
    out.println('};');
  }
}

<commit_msg>fixes issue #140<commit_after>var File = java.io.File,
  FileReader = java.io.FileReader,
  FileInputStream = java.io.FileInputStream,
  out = java.lang.System.out,
  err = java.lang.System.err,
  Modifier = java.lang.reflect.Modifier,
  clz,
  ZipInputStream = java.util.zip.ZipInputStream,
  zis = new ZipInputStream(new FileInputStream('./target/minecraft/craftbukkit.jar')),
  entry = null;
var content = [
  '/*********************',
  '## Events Helper Module',
  'The Events helper module provides a suite of functions - one for each possible event.',
  'For example, the events.blockBreak() function is just a wrapper function which calls events.on(org.bukkit.event.block.BlockBreakEvent, callback, priority)',
  'This module is a convenience wrapper for easily adding new event handling functions in Javascript. ',
  'At the in-game or server-console prompt, players/admins can type `events.` and use TAB completion ',
  'to choose from any of the approx. 160 different event types to listen to.',
  '',
  '### Usage',
  '',
  '    events.blockBreak( function( event ) { ',
  '      event.player.sendMessage(\'You broke a block!\'); ',
  '    });',
  '',
  '... which is just a shorter and less error-prone way of writing ...',
  '',
  '    events.on(\'block.BlockBreakEvent\',function( event ) { ',
  '      event.player.sendMessage(\'You broke a block!\');',
  '    });',
  '',
  'The crucial difference is that the events module now has functions for each of the built-in events. The functions are accessible via TAB-completion so will help beginning programmers to explore the events at the server console window.',
  '',
  '***/'
];
for (var i = 0; i< content.length; i++){
  out.println(content[i]);
}
while ( ( entry = zis.nextEntry) != null) {
  var name = '' + entry.name;
  if (name.match(/org\/bukkit\/event\/.+Event\.class$/)){
    name = name.replace(/\//g,'.').replace('.class','');
    try {
      clz = java.lang.Class.forName(name);
    }catch ( e) {
      clz = engine.eval(name);
    }
    var isAbstract = Modifier.isAbstract(clz.getModifiers());
    if ( isAbstract ) {
      continue;
    }
    var parts = name.split('.');
    var shortName = name.replace('org.bukkit.event.','');
    var fname = parts.reverse().shift().replace(/^(.)/,function(a){ return a.toLowerCase();}).replace(/Event$/,'');

    var comment = [
      '/*********************',
      '### events.' + fname + '()',
      '',
      '#### Parameters ',
      '',
      ' * callback - A function which is called whenever the ' + shortName + ' event is fired',
      '',
      ' * priority - optional - see events.on() for more information.',
      '',
      '***/'
    ];
    for (var i = 0; i < comment.length; i++){
      out.println(comment[i]);
    }
    out.println('exports.' + fname + ' = function(callback,priority){ ');
    out.println('  return events.on(' + name + ',callback,priority);');
    out.println('};');
  }
}

<|endoftext|>


<commit_before>import Vue from 'vue';
import querystring from 'querystring';
import _ from 'lodash';
import { format as formatDate, subYears } from 'date-fns';
import config from '../../config.js';
import { setPackages } from '../packages/packages.js';
import getPackagesDownloads from '../../server/utils/stats/getPackagesDownloads';
import { startOfDay } from 'date-fns';

const palette = config.palette;

function processPackageStats(npmModuleData) {
  const downloads = npmModuleData.downloads.map(entry => ({
    day: startOfDay(entry.day),
    count: entry.downloads,
  }));
  return {
    name: npmModuleData.package,
    // if most recent day has no download count, remove it
    downloads: _.last(downloads).count === 0 ? _.initial(downloads) : downloads,
  };
}

var {
  default: packageInput,
  emitter: packageEvents,
  packages,
} = require('../packages/packages.js');

export default Vue.extend({
  route: {
    waitForData: true,
    canReuse(...args) {
      // hack to solve https://github.com/cheapsteak/npmcharts.com/issues/23
      // > Dots on graph don't update when a package is added/removed
      return false;
    },
    data({ to, next, redirect }) {
      const packageNames =
        to.path === '/' || !to.params.packages
          ? _.sample(this.presetPackages)
          : to.params.packages
              .split(',')
              .map(packageName => window.decodeURIComponent(packageName));

      if (to.path === '/' || !to.params.packages) {
        document.title = 'Compare download stats for npm packages - npmcharts';
        this.isUsingPresetPackages = true;
      } else {
        document.title =
          'Compare npm downloads for ' +
          to.params.packages.split(',').join(', ') +
          ' - npmcharts';
      }

      setTimeout(() => ga('send', 'pageview'));

      const isMinimalMode = to.query.minimal === 'false';
      const periodLength = Number(to.query.periodLength || 7);

      if (!packageNames) {
        next({
          isMinimalMode,
          periodLength,
          moduleNames: null,
          moduleData: null,
          samplePreset: _.sample(this.presetPackages),
        });
        return;
      }

      // set notify to false to prevent triggering route change
      setPackages(packageNames, false);

      const DATE_FORMAT = 'YYYY-MM-DD';
      const endDate = formatDate(new Date(), DATE_FORMAT);
      const startDate = formatDate(subYears(new Date(), 1), DATE_FORMAT);

      // can't use 'await' here or will trigger vue router error
      getPackagesDownloads(packageNames, {
        startDate,
        endDate,
      }).then(packagesDownloads => {
        const processedPackagesStats = _.compact(packagesDownloads).map(
          processPackageStats,
        );

        next({
          isMinimalMode,
          periodLength,
          moduleNames: packageNames,
          moduleData: processedPackagesStats,
          isUsingPresetPackages: !to.params.packages,
        });
      });
    },
  },
  template: require('./home.html'),
  data() {
    return {
      presetPackages: config.presetPackages,
      samplePreset: [],
      moduleNames: null,
      moduleData: null,
      palette,
      showWeekends: true,
      periodLength: 7,
      isMinimalMode: false,
      isUsingPresetPackages: undefined,
      hoverCount: 0,
      twitterIcon: require('../assets/images/icon-twitter.svg'),
      shouldShowComments:
        window.innerWidth >= 1000 &&
        !JSON.parse(!!window.localStorage.getItem('shouldShowComments')),
    };
  },
  computed: {
    shareUrl() {
      return (
        this.moduleNames &&
        `http://npmcharts.com/compare/${this.moduleNames.join(',')}`
      );
    },
    twitterShareUrl() {
      return (
        this.shareUrl &&
        `https://twitter.com/intent/tweet?url=${window.encodeURIComponent(
          this.shareUrl,
        )}`
      );
    },
    isEmbedded() {
      return this.isMinimalMode;
    },
    queryString() {
      return querystring.stringify(this.$route.query);
    },
  },
  watch: {
    shouldShowComments() {
      this.$refs.graph.render();
    },
    isMinimalMode(isMinimalMode) {
      if (isMinimalMode) {
        document.body.classList.add('minimal');
      } else {
        document.body.classList.remove('minimal');
      }
      this.$refs.graph.render();
    },
  },
  ready() {
    packageEvents.on('change', () => {
      const nextRouteSansQuery = `/compare/${packages.join(',')}`;
      if (this.$route.router.app.$route.path !== nextRouteSansQuery) {
        this.$route.router.go(`${nextRouteSansQuery}?${this.queryString}`);
      }
    });
    // expose router so puppeteer can trigger route changes
    window.router = this.$route.router;
  },
  methods: {
    track(eventName, value) {
      ga('send', 'event', eventName, value);
    },
    getMergedQueryParams(params) {
      return { ...this.$route.query, ...params };
    },
    addPackage(packageName) {
      ga(
        'send',
        'event',
        'packageInput',
        'add',
        `${packageName} existing:${this.moduleNames}`,
      );
      if (this.$route.params && this.$route.params.packages) {
        this.$route.router.go(
          '/compare/' + this.$route.params.packages + ',' + packageName,
        );
      } else {
        this.$route.router.go('/compare/' + packageName);
      }
    },
    clearPackages() {
      this.$route.router.go('/compare');
    },
    handleClickTwitter() {
      ga('send', 'event', 'share', 'twitter', this.twitterShareUrl);
      window.open(this.twitterShareUrl);
    },
    handleHoverTwitter() {
      this.hoverCount++;
      ga(
        'send',
        'event',
        'hoverShare',
        'twitter',
        this.twitterShareUrl,
        this.hoverCount,
      );
    },
    handleMouseEnterTwitter() {
      this.twitterEventTimeout = setTimeout(this.handleHoverTwitter, 500);
    },
    handleMouseLeaveTwitter() {
      clearTimeout(this.twitterEventTimeout);
    },
    shuffle: _.shuffle,
  },
  components: {
    'package-input': packageInput,
    graph: require('../graph/graph.js'),
  },
});
<commit_msg>Fix minimal mode breaking<commit_after>import Vue from 'vue';
import querystring from 'querystring';
import _ from 'lodash';
import { format as formatDate, subYears } from 'date-fns';
import config from '../../config.js';
import { setPackages } from '../packages/packages.js';
import getPackagesDownloads from '../../server/utils/stats/getPackagesDownloads';
import { startOfDay } from 'date-fns';

const palette = config.palette;

function processPackageStats(npmModuleData) {
  const downloads = npmModuleData.downloads.map(entry => ({
    day: startOfDay(entry.day),
    count: entry.downloads,
  }));
  return {
    name: npmModuleData.package,
    // if most recent day has no download count, remove it
    downloads: _.last(downloads).count === 0 ? _.initial(downloads) : downloads,
  };
}

var {
  default: packageInput,
  emitter: packageEvents,
  packages,
} = require('../packages/packages.js');

export default Vue.extend({
  route: {
    waitForData: true,
    canReuse(...args) {
      // hack to solve https://github.com/cheapsteak/npmcharts.com/issues/23
      // > Dots on graph don't update when a package is added/removed
      return false;
    },
    data({ to, next, redirect }) {
      const packageNames =
        to.path === '/' || !to.params.packages
          ? _.sample(this.presetPackages)
          : to.params.packages
              .split(',')
              .map(packageName => window.decodeURIComponent(packageName));

      if (to.path === '/' || !to.params.packages) {
        document.title = 'Compare download stats for npm packages - npmcharts';
        this.isUsingPresetPackages = true;
      } else {
        document.title =
          'Compare npm downloads for ' +
          to.params.packages.split(',').join(', ') +
          ' - npmcharts';
      }

      setTimeout(() => ga('send', 'pageview'));

      const isMinimalMode = to.query.minimal === 'true';
      const periodLength = Number(to.query.periodLength || 7);

      if (!packageNames) {
        next({
          isMinimalMode,
          periodLength,
          moduleNames: null,
          moduleData: null,
          samplePreset: _.sample(this.presetPackages),
        });
        return;
      }

      // set notify to false to prevent triggering route change
      setPackages(packageNames, false);

      const DATE_FORMAT = 'YYYY-MM-DD';
      const endDate = formatDate(new Date(), DATE_FORMAT);
      const startDate = formatDate(subYears(new Date(), 1), DATE_FORMAT);

      // can't use 'await' here or will trigger vue router error
      getPackagesDownloads(packageNames, {
        startDate,
        endDate,
      }).then(packagesDownloads => {
        const processedPackagesStats = _.compact(packagesDownloads).map(
          processPackageStats,
        );

        next({
          isMinimalMode,
          periodLength,
          moduleNames: packageNames,
          moduleData: processedPackagesStats,
          isUsingPresetPackages: !to.params.packages,
        });
      });
    },
  },
  template: require('./home.html'),
  data() {
    return {
      presetPackages: config.presetPackages,
      samplePreset: [],
      moduleNames: null,
      moduleData: null,
      palette,
      showWeekends: true,
      periodLength: 7,
      isMinimalMode: false,
      isUsingPresetPackages: undefined,
      hoverCount: 0,
      twitterIcon: require('../assets/images/icon-twitter.svg'),
      shouldShowComments:
        window.innerWidth >= 1000 &&
        !JSON.parse(!!window.localStorage.getItem('shouldShowComments')),
    };
  },
  computed: {
    shareUrl() {
      return (
        this.moduleNames &&
        `http://npmcharts.com/compare/${this.moduleNames.join(',')}`
      );
    },
    twitterShareUrl() {
      return (
        this.shareUrl &&
        `https://twitter.com/intent/tweet?url=${window.encodeURIComponent(
          this.shareUrl,
        )}`
      );
    },
    isEmbedded() {
      return this.isMinimalMode;
    },
    queryString() {
      return querystring.stringify(this.$route.query);
    },
  },
  watch: {
    shouldShowComments() {
      this.$refs.graph.render();
    },
    isMinimalMode(isMinimalMode) {
      if (isMinimalMode) {
        document.body.classList.add('minimal');
      } else {
        document.body.classList.remove('minimal');
      }
      this.$refs.graph.render();
    },
  },
  ready() {
    packageEvents.on('change', () => {
      const nextRouteSansQuery = `/compare/${packages.join(',')}`;
      if (this.$route.router.app.$route.path !== nextRouteSansQuery) {
        this.$route.router.go(`${nextRouteSansQuery}?${this.queryString}`);
      }
    });
    // expose router so puppeteer can trigger route changes
    window.router = this.$route.router;
  },
  methods: {
    track(eventName, value) {
      ga('send', 'event', eventName, value);
    },
    getMergedQueryParams(params) {
      return { ...this.$route.query, ...params };
    },
    addPackage(packageName) {
      ga(
        'send',
        'event',
        'packageInput',
        'add',
        `${packageName} existing:${this.moduleNames}`,
      );
      if (this.$route.params && this.$route.params.packages) {
        this.$route.router.go(
          '/compare/' + this.$route.params.packages + ',' + packageName,
        );
      } else {
        this.$route.router.go('/compare/' + packageName);
      }
    },
    clearPackages() {
      this.$route.router.go('/compare');
    },
    handleClickTwitter() {
      ga('send', 'event', 'share', 'twitter', this.twitterShareUrl);
      window.open(this.twitterShareUrl);
    },
    handleHoverTwitter() {
      this.hoverCount++;
      ga(
        'send',
        'event',
        'hoverShare',
        'twitter',
        this.twitterShareUrl,
        this.hoverCount,
      );
    },
    handleMouseEnterTwitter() {
      this.twitterEventTimeout = setTimeout(this.handleHoverTwitter, 500);
    },
    handleMouseLeaveTwitter() {
      clearTimeout(this.twitterEventTimeout);
    },
    shuffle: _.shuffle,
  },
  components: {
    'package-input': packageInput,
    graph: require('../graph/graph.js'),
  },
});
<|endoftext|>


<commit_before>(function (Q, $, window, undefined) {

    /**
     * Streams/webrtc/preview tool.
     * Renders a tool to preview Streams/webrtc
     * @class Streams/webrtc/preview
     * @constructor
     * @param {Object} [options] options to pass besides the ones to Streams/preview tool
     */
    Q.Tool.define("Streams/webrtc/preview", ["Streams/preview"], function _Streams_webrtc_preview (options, preview) {
            var tool = this;
            var state = this.state;
            tool.preview = preview;

			preview.state.editable = false;

            //preview.state.creatable.preprocess = tool.composer.bind(this);

            //Q.addStylesheet('{{Streams}}/css/tools/webrtcPreview.css', { slotName: 'Streams' });

            Q.Text.get('Streams/content', function (err, text) {
                var msg = Q.firstErrorMessage(err);
                if (msg) {
                    return console.warn(msg);
                }

                tool.text = text;
                preview.state.onRefresh.add(tool.refresh.bind(tool));
            });
        },

        {
			templates: {
				view: {
					name: 'Streams/webrtc/preview/view',
					fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
				}
			}
        },

{
        refresh: function (stream) {
            var tool = this;
            var state = this.state;
            var $toolElement = $(tool.element);

            if (!Q.Streams.isStream(stream)) {
                return;
            }

            tool.stream = stream;

            // retain with stream
            Q.Streams.retainWith(tool).get(stream.fields.publisherId, stream.fields.name);

			var fields = Q.extend({}, state.templates.view.fields, {
				alt: 'icon',
				title: stream.fields.title,
				preamble: Q.getObject('webtc.preview.preamble', tool.text) || 'Meeting'
			});
			Q.Template.render(
				'Streams/webrtc/preview/view',
				fields,
				function (err, html) {
					if (err) return;
					tool.element.innerHTML = html;
					Q.activate(tool, function () {
						// load the icon
						// TODO: make this use flexbox instead
						var jq = tool.$('img.Streams_preview_icon');
						tool.preview.icon(jq[0], p.fill('icon'));
						var $pc = tool.$('.Streams_preview_contents');
						if ($pc.parent().is(":visible")) {
							$pc.width(0).width($pc[0].remainingWidth());
						}
						Q.onLayout(tool.element).set(function () {
							var $pc = tool.$('.Streams_preview_contents');
							if ($pc.parent().is(':visible')) {
								$pc.width(0).width($pc[0].remainingWidth());
							}
						}, tool);
						Q.handle(state.onRender, tool);
					});
				},
				state.templates[tpl]
			);

            setTimeout(function () {
                $toolElement.tool("Streams/preview", {
                    publisherId: state.publisherId,
                    streamName: state.streamName
                }).tool("Streams/default/preview").activate();
            }, 0);

            $toolElement.on(Q.Pointer.fastclick, function () {
                var WebConference = Q.Streams.WebRTC();
                WebConference.start({
                    element: document.body,
                    roomId: stream.fields.name.split('/').pop(),
                    roomPublisherId: stream.fields.publisherId,
                    mode: 'node',
                    startWith: {video: false, audio: true},
                    onWebRTCRoomCreated: function() {
                        console.log('onWebRTCRoomCreated', this);
                    },
                    onWebrtcControlsCreated: function() {
                        console.log('onWebrtcControlsCreated', this);
                    }
                });
            });
        }
    });

Q.Template.set('Streams/webrtc/preview/view',
	'
'
	+ ''
	+ '
'
	+ '<{{titleTag}} class="Streams_preview_preamble">{{preamble}}</{{titleTag}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '
{{size}}
'
	+ '

'
);

})(Q, Q.$, window);<commit_msg>Fixing small errors in previous commit<commit_after>(function (Q, $, window, undefined) {

    /**
     * Streams/webrtc/preview tool.
     * Renders a tool to preview Streams/webrtc
     * @class Streams/webrtc/preview
     * @constructor
     * @param {Object} [options] options to pass besides the ones to Streams/preview tool
     */
    Q.Tool.define("Streams/webrtc/preview", ["Streams/preview"], function _Streams_webrtc_preview (options, preview) {
            var tool = this;
            var state = this.state;
            tool.preview = preview;

			preview.state.editable = false;

            //preview.state.creatable.preprocess = tool.composer.bind(this);

            //Q.addStylesheet('{{Streams}}/css/tools/webrtcPreview.css', { slotName: 'Streams' });

            Q.Text.get('Streams/content', function (err, text) {
                var msg = Q.firstErrorMessage(err);
                if (msg) {
                    return console.warn(msg);
                }

                tool.text = text;
                preview.state.onRefresh.add(tool.refresh.bind(tool));
            });
        },

        {
			templates: {
				view: {
					name: 'Streams/webrtc/preview/view',
					fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
				}
			}
        },

{
        refresh: function (stream) {
            var tool = this;
            var state = this.state;
            var $toolElement = $(tool.element);

            if (!Q.Streams.isStream(stream)) {
                return;
            }

            tool.stream = stream;

            // retain with stream
            Q.Streams.retainWith(tool).get(stream.fields.publisherId, stream.fields.name);

			var fields = Q.extend({}, state.templates.view.fields, {
				alt: 'icon',
				title: stream.fields.title,
				preamble: Q.getObject('webtc.preview.preamble', tool.text) || 'Meeting'
			});
			Q.Template.render(
				'Streams/webrtc/preview/view',
				fields,
				function (err, html) {
					if (err) return;
					tool.element.innerHTML = html;
					Q.activate(tool, function () {
						// load the icon
						// TODO: make this use flexbox instead
						var jq = tool.$('img.Streams_preview_icon');
						tool.preview.icon(jq[0], p.fill('icon'));
						var $pc = tool.$('.Streams_preview_contents');
						if ($pc.parent().is(":visible")) {
							$pc.width(0).width($pc[0].remainingWidth());
						}
						Q.onLayout(tool.element).set(function () {
							var $pc = tool.$('.Streams_preview_contents');
							if ($pc.parent().is(':visible')) {
								$pc.width(0).width($pc[0].remainingWidth());
							}
						}, tool);
						Q.handle(state.onRender, tool);
					});
				},
				state.templates.view
			);

            setTimeout(function () {
                $toolElement.tool("Streams/preview", {
                    publisherId: state.publisherId,
                    streamName: state.streamName
                }).tool("Streams/default/preview").activate();
            }, 0);

            $toolElement.on(Q.Pointer.fastclick, function () {
                var WebConference = Q.Streams.WebRTC();
                WebConference.start({
                    element: document.body,
                    roomId: stream.fields.name.split('/').pop(),
                    roomPublisherId: stream.fields.publisherId,
                    mode: 'node',
                    startWith: {video: false, audio: true},
                    onWebRTCRoomCreated: function() {
                        console.log('onWebRTCRoomCreated', this);
                    },
                    onWebrtcControlsCreated: function() {
                        console.log('onWebrtcControlsCreated', this);
                    }
                });
            });
        }
    });

Q.Template.set('Streams/webrtc/preview/view',
	'
'
	+ ''
	+ '
'
	+ '<{{titleTag}} class="Streams_preview_preamble">{{preamble}}</{{titleTag}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '
{{size}}
'
	+ '

'
);

})(Q, Q.$, window);<|endoftext|>


<commit_before>/*
 * markdown_highlight_rules.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define("mode/markdown_highlight_rules", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = require("ace/mode/javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("ace/mode/xml_highlight_rules").XmlHighlightRules;
var HtmlHighlightRules = require("ace/mode/html_highlight_rules").HtmlHighlightRules;
var CssHighlightRules = require("ace/mode/css_highlight_rules").CssHighlightRules;

var escaped = function(ch) {
    return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*";
}

function github_embed(tag, prefix) {
    return { // Github style block
        token : "support.function",
        regex : "^\\s*```(?:" + "\\{" + tag + "[^\\}]*\\}" + "|" + tag + ")\\s*$",
        push  : prefix + "start"
    };
}

var MarkdownHighlightRules = function() {

    var slideFields = lang.arrayToMap(
        ("title|author|date|rtl|depends|autosize|width|height|transition|transition-speed|font-family|css|class|navigation|incremental|left|right|id|audio|video|type|at|help-doc|help-topic|source|console|console-input|execute|pause")
            .split("|")
    );

    // regexp must not have capturing parentheses
    // regexps are ordered -> the first match is used

    this.$rules = {

        "basic" : [{
            token : "constant.language.escape",
            regex : /\\[\\`*_{}\[\]()#+\-.!]/
        }, { // code span `
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)(.*?[^`])(\\1)"
        }, { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)(" + escaped("]") + ")(\\]\s*\\[)("+ escaped("]") + ")(\\])"
        }, { // link by url
            token : ["text", "keyword", "text", "markup.underline", "string", "text"],
            regex : "(\\[)(" +                                    // [
                escaped("]") +                                    // link text
                ")(\\]\\()"+                                      // ](
                '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' +        // href
                '(\\s*"' +  escaped('"') + '"\\s*)?' +            // "title"
                "(\\))"                                           // )
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { //
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }],

        start: [{
           token : "empty_line",
           regex : '^$',
           next: "allowBlock"
        }, { // code span
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)([^\\r]*?[^`])(\\1)"
        }, { // h1 with equals
            token: "markup.heading.1",
            regex: "^\\={3,}\\s*$",
            next: "fieldblock"
        }, { // h1
            token: "markup.heading.1",
            regex: "^={3,}(?=\\s*$)"
        }, { // h2
            token: "markup.heading.2",
            regex: "^\\-{3,}(?=\\s*$)"
        }, {
            token : function(value) {
                return "markup.heading." + value.length;
            },
            regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/,
            next : "header"
        },

        github_embed("(?:javascript|js)", "jscode-"),
        github_embed("xml", "xmlcode-"),
        github_embed("html", "htmlcode-"),
        github_embed("css", "csscode-"),

        { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        },
        { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"
        }, { // HR *
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"
        }, { // HR -
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"
        }, { // HR _
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"
        }, { // MathJax native display \[ ... \]
            token : "markup.list",
            regex : "\\\\\\[",
            next  : "mathjaxnativedisplay"
        }, { // MathJax native inline \( ... \)
            token : "markup.list",
            regex : "\\\\\\(",
            next  : "mathjaxnativeinline"
        }, { // $ escape
            token : "text",
            regex : "\\\\\\$"
        }, { // MathJax $$
            token : "markup.list",
            regex : "\\${2}",
            next  : "mathjaxdisplay"
        }, { // MathJax $...$ (org-mode style)
            token : ["markup.list","support.function","markup.list"],
            regex : "(\\$)((?:(?:\\\\.)|(?:[^\\$\\\\]))*?)(\\$)"
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // simple links <url>
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }, {
            // embedded latex command
            token : "keyword",
            regex : "\\\\(?:[a-zA-z0-9]+|[^a-zA-z0-9])"
        }, {
            // embedded latex arg
            token : ["paren.keyword.operator", "text", "paren.keyword.operator"],
            regex : "(\\{)([^\\}]*)(\\})"
        }, {
            // pandoc citation
            token : "markup.list",
            regex : "-?\\@[\\w\\d-]+"
        }, {
            token : "text",
            regex : "[^\\*_%$`\\[#<>\\\\@]+"
        }, {
            token : "text",
            regex : "\\\\"
        }, { // HR * - _
            token : "constant",
            regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$",
            next: "allowBlock"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock"
        }, { // html comment
            token : "comment",
            regex : "<\\!--",
            next  : "html-comment"
        }, {
            include : "basic"
        }],

        "html-comment" : [{
           token: "comment",
           regex: "-->",
           next: "start"
        }, {
           defaultToken: "comment"
        }],

        // code block
        "allowBlock": [{
           token : "support.function",
           regex : "^ {4}.+",
           next : "allowBlock"
        }, {
           token : "empty",
           regex : "",
           next : "start"
        }],

        "header" : [{
            regex: "$",
            next : "start"
        }, {
            include: "basic"
        }, {
            defaultToken : "heading"
        }],

        "listblock" : [ { // Lists only escape on completely blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock"
        }, {
            include : "basic", noEscape: true
        }, { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, {
            defaultToken : "text" //do not use markup.list to allow stling leading `*` differntly
        }],

        "blockquote" : [ { // Blockquotes only escape on blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        }, {
            include : "basic", noEscape: true
        }, {
            defaultToken : "string.blockquote"
        }],

        "githubblock" : [ {
            token : "support.function",
            regex : "^\\s*```",
            next  : "start"
        }, {
            token : "support.function",
            regex : ".+"
        }],

         "fieldblock" : [{
            token : function(value) {
                var field = value.slice(0,-1);
                if (slideFields[field])
                    return "comment.doc.tag";
                else
                    return "text";
            },
            regex : "^" +"[\\w-]+\\:",
            next  : "fieldblockvalue"
        }, {
            token : "text",
            regex : "(?=.+)",
            next  : "start"
        }],

        "fieldblockvalue" : [{
            token : "text",
            regex : "$",
            next  : "fieldblock"
        }, {
            token : "text",
            regex : ".+"
        }],

        "mathjaxdisplay" : [{
            token : "markup.list",
            regex : "\\${2}",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[^\\$]+"
        }],

        "mathjaxnativedisplay" : [{
            token : "markup.list",
            regex : "\\\\\\]",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }],

        "mathjaxnativeinline" : [{
            token : "markup.list",
            regex : "\\\\\\)",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }]

    };

    this.embedRules(JavaScriptHighlightRules, "jscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(HtmlHighlightRules, "htmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(CssHighlightRules, "csscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(XmlHighlightRules, "xmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.normalizeRules();
};
oop.inherits(MarkdownHighlightRules, TextHighlightRules);

exports.MarkdownHighlightRules = MarkdownHighlightRules;
});
<commit_msg>add markdown embedded syntax highlighting modes for perl, python, ruby, and scala<commit_after>/*
 * markdown_highlight_rules.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define("mode/markdown_highlight_rules", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = require("ace/mode/javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("ace/mode/xml_highlight_rules").XmlHighlightRules;
var HtmlHighlightRules = require("ace/mode/html_highlight_rules").HtmlHighlightRules;
var CssHighlightRules = require("ace/mode/css_highlight_rules").CssHighlightRules;
var PerlHighlightRules = require("ace/mode/perl_highlight_rules").PerlHighlightRules;
var PythonHighlightRules = require("ace/mode/python_highlight_rules").PythonHighlightRules;
var RubyHighlightRules = require("ace/mode/ruby_highlight_rules").RubyHighlightRules;
var ScalaHighlightRules = require("ace/mode/scala_highlight_rules").ScalaHighlightRules;

var escaped = function(ch) {
    return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*";
}

function github_embed(tag, prefix) {
    return { // Github style block
        token : "support.function",
        regex : "^\\s*```(?:" + "\\{" + tag + "[^\\}]*\\}" + "|" + tag + ")\\s*$",
        push  : prefix + "start"
    };
}

var MarkdownHighlightRules = function() {

    var slideFields = lang.arrayToMap(
        ("title|author|date|rtl|depends|autosize|width|height|transition|transition-speed|font-family|css|class|navigation|incremental|left|right|id|audio|video|type|at|help-doc|help-topic|source|console|console-input|execute|pause")
            .split("|")
    );

    // regexp must not have capturing parentheses
    // regexps are ordered -> the first match is used

    this.$rules = {

        "basic" : [{
            token : "constant.language.escape",
            regex : /\\[\\`*_{}\[\]()#+\-.!]/
        }, { // code span `
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)(.*?[^`])(\\1)"
        }, { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)(" + escaped("]") + ")(\\]\s*\\[)("+ escaped("]") + ")(\\])"
        }, { // link by url
            token : ["text", "keyword", "text", "markup.underline", "string", "text"],
            regex : "(\\[)(" +                                    // [
                escaped("]") +                                    // link text
                ")(\\]\\()"+                                      // ](
                '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' +        // href
                '(\\s*"' +  escaped('"') + '"\\s*)?' +            // "title"
                "(\\))"                                           // )
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)"
        }, { //
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }],

        start: [{
           token : "empty_line",
           regex : '^$',
           next: "allowBlock"
        }, { // code span
            token : ["support.function", "support.function", "support.function"],
            regex : "(`+)([^\\r]*?[^`])(\\1)"
        }, { // h1 with equals
            token: "markup.heading.1",
            regex: "^\\={3,}\\s*$",
            next: "fieldblock"
        }, { // h1
            token: "markup.heading.1",
            regex: "^={3,}(?=\\s*$)"
        }, { // h2
            token: "markup.heading.2",
            regex: "^\\-{3,}(?=\\s*$)"
        }, {
            token : function(value) {
                return "markup.heading." + value.length;
            },
            regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/,
            next : "header"
        },

        github_embed("(?:javascript|js)", "jscode-"),
        github_embed("xml", "xmlcode-"),
        github_embed("html", "htmlcode-"),
        github_embed("css", "csscode-"),
        github_embed("perl", "perlcode-"),
        github_embed("python", "pythoncode-"),
        github_embed("ruby", "rubycode-"),
        github_embed("scala", "scalacode-"),

        { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        },
        { // reference
            token : ["text", "constant", "text", "url", "string", "text"],
            regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
        }, { // link by reference
            token : ["text", "keyword", "text", "constant", "text"],
            regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"
        }, { // HR *
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"
        }, { // HR -
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"
        }, { // HR _
            token : "constant",
            regex : "^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"
        }, { // MathJax native display \[ ... \]
            token : "markup.list",
            regex : "\\\\\\[",
            next  : "mathjaxnativedisplay"
        }, { // MathJax native inline \( ... \)
            token : "markup.list",
            regex : "\\\\\\(",
            next  : "mathjaxnativeinline"
        }, { // $ escape
            token : "text",
            regex : "\\\\\\$"
        }, { // MathJax $$
            token : "markup.list",
            regex : "\\${2}",
            next  : "mathjaxdisplay"
        }, { // MathJax $...$ (org-mode style)
            token : ["markup.list","support.function","markup.list"],
            regex : "(\\$)((?:(?:\\\\.)|(?:[^\\$\\\\]))*?)(\\$)"
        }, { // strong ** __
            token : ["constant.numeric", "constant.numeric", "constant.numeric"],
            regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // emphasis * _
            token : ["constant.language.boolean", "constant.language.boolean", "constant.language.boolean"],
            regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
        }, { // simple links <url>
            token : ["text", "keyword", "text"],
            regex : "(<)("+
                "(?:https?|ftp|dict):[^'\">\\s]+"+
                "|"+
                "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
                ")(>)"
        }, {
            // embedded latex command
            token : "keyword",
            regex : "\\\\(?:[a-zA-z0-9]+|[^a-zA-z0-9])"
        }, {
            // embedded latex arg
            token : ["paren.keyword.operator", "text", "paren.keyword.operator"],
            regex : "(\\{)([^\\}]*)(\\})"
        }, {
            // pandoc citation
            token : "markup.list",
            regex : "-?\\@[\\w\\d-]+"
        }, {
            token : "text",
            regex : "[^\\*_%$`\\[#<>\\\\@]+"
        }, {
            token : "text",
            regex : "\\\\"
        }, { // HR * - _
            token : "constant",
            regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$",
            next: "allowBlock"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock"
        }, { // html comment
            token : "comment",
            regex : "<\\!--",
            next  : "html-comment"
        }, {
            include : "basic"
        }],

        "html-comment" : [{
           token: "comment",
           regex: "-->",
           next: "start"
        }, {
           defaultToken: "comment"
        }],

        // code block
        "allowBlock": [{
           token : "support.function",
           regex : "^ {4}.+",
           next : "allowBlock"
        }, {
           token : "empty",
           regex : "",
           next : "start"
        }],

        "header" : [{
            regex: "$",
            next : "start"
        }, {
            include: "basic"
        }, {
            defaultToken : "heading"
        }],

        "listblock" : [ { // Lists only escape on completely blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // list
            token : "text",
            regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
            next  : "listblock"
        }, {
            include : "basic", noEscape: true
        }, { // Github style block
            token : "support.function",
            regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$",
            next  : "githubblock"
        }, {
            defaultToken : "text" //do not use markup.list to allow stling leading `*` differntly
        }],

        "blockquote" : [ { // Blockquotes only escape on blank lines.
            token : "empty_line",
            regex : "^\\s*$",
            next  : "start"
        }, { // block quote
            token : "string.blockquote",
            regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+",
            next  : "blockquote"
        }, {
            include : "basic", noEscape: true
        }, {
            defaultToken : "string.blockquote"
        }],

        "githubblock" : [ {
            token : "support.function",
            regex : "^\\s*```",
            next  : "start"
        }, {
            token : "support.function",
            regex : ".+"
        }],

         "fieldblock" : [{
            token : function(value) {
                var field = value.slice(0,-1);
                if (slideFields[field])
                    return "comment.doc.tag";
                else
                    return "text";
            },
            regex : "^" +"[\\w-]+\\:",
            next  : "fieldblockvalue"
        }, {
            token : "text",
            regex : "(?=.+)",
            next  : "start"
        }],

        "fieldblockvalue" : [{
            token : "text",
            regex : "$",
            next  : "fieldblock"
        }, {
            token : "text",
            regex : ".+"
        }],

        "mathjaxdisplay" : [{
            token : "markup.list",
            regex : "\\${2}",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[^\\$]+"
        }],

        "mathjaxnativedisplay" : [{
            token : "markup.list",
            regex : "\\\\\\]",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }],

        "mathjaxnativeinline" : [{
            token : "markup.list",
            regex : "\\\\\\)",
            next  : "start"
        }, {
            token : "support.function",
            regex : "[\\s\\S]+?"
        }]

    };

    this.embedRules(JavaScriptHighlightRules, "jscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(HtmlHighlightRules, "htmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(CssHighlightRules, "csscode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(XmlHighlightRules, "xmlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(PerlHighlightRules, "perlcode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(PythonHighlightRules, "pythoncode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(RubyHighlightRules, "rubycode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.embedRules(ScalaHighlightRules, "scalacode-", [{
        token : "support.function",
        regex : "^\\s*```",
        next  : "pop"
    }]);

    this.normalizeRules();
};
oop.inherits(MarkdownHighlightRules, TextHighlightRules);

exports.MarkdownHighlightRules = MarkdownHighlightRules;
});
<|endoftext|>


<commit_before>'use strict';

angular.module('esn.profile', ['restangular', 'xeditable', 'angularSpinner', 'esn.user'])
  .directive('profileDisplay', function() {
    return {
      restrict: 'E',
      scope: {
        user: '='
      },
      templateUrl: '/views/modules/profile/profile.html'
    };
  })

  .directive('profileMinicard', function() {
    return {
      restrict: 'E',
      scope: {
        user: '=',
        label: '@',
        labelclass: '@'
      },
      templateUrl: '/views/modules/profile/minicard.html'
    };
  })

  .controller('profileEditionController', ['$scope', 'profileAPI', 'editableOptions', function($scope, profileAPI, editableOptions) {
    //theming for yes/no buttons in field modification confirmation
    editableOptions.theme = 'bs3';
    var maxNameLength = 100;

    $scope.running = {
      name: false,
      job: false,
      service: false,
      building_location: false,
      office_location: false,
      phone: false
    };

    $scope.initFullName = function(firstname, lastname) {
      if (firstname && lastname) {
        $scope.fullName = firstname + ' ' + lastname;
      }
      return $scope.fullName;
    };

    var updateField = function(data, runningMarker, fieldName) {
      runningMarker = true;

      return profileAPI.updateProfileField(fieldName, data).then(
        function(data) {
          runningMarker = false;
          return true;
        },
        function(error) {
          runningMarker = false;
          return error.statusText;
        }
      );
    };

    $scope.updateName = function(data) {
      var nameParts = data.split(' ');
      if (nameParts.length < 2) {
        return 'Incorrect Name';
      }
      var firstName = nameParts.shift();
      var lastName = nameParts.join(' ');
      if (firstName.length > maxNameLength) {
        return 'First name is too long';
      }
      if (lastName.length > maxNameLength) {
        return 'Last name is too long';
      }

      $scope.running.name = true;
      return profileAPI.updateProfileField('firstname', firstName).then(
        function(data) {
          $scope.running.name = false;
          return updateField(lastName, $scope.running.name, 'lastname');
        },
        function(error) {
          $scope.running.name = false;
          return error.statusText;
        }
      );
    };

    $scope.updateJob = function(data) {
      return updateField(data, $scope.running.job, 'job_title');
    };

    $scope.updateService = function(data) {
      return updateField(data, $scope.running.service, 'service');
    };

    $scope.updateBuildingLocation = function(data) {
      return updateField(data, $scope.running.building_location, 'building_location');
    };

    $scope.updateOfficeLocation = function(data) {
      return updateField(data, $scope.running.office_location, 'office_location');
    };

    $scope.updatePhone = function(data) {
      return updateField(data, $scope.running.phone, 'main_phone');
    };

  }])

  .factory('profileAPI', ['Restangular', function(Restangular) {
    function updateProfileField(fieldName, fieldValue) {
      var payload = {
        value: fieldValue
      };
      return Restangular.one('user/profile', fieldName).customPUT(payload);
    }

    return {
      updateProfileField: updateProfileField
    };
  }])

  .controller('profilecontroller', ['$scope', 'userAPI', function($scope, userAPI) {
    userAPI.currentUser().then(function(response) {
      $scope.user = response.data;
    });
  }])
  .controller('avatarController', ['$rootScope', '$scope', '$timeout', function($rootScope, $scope, $timeout) {

    $scope.getURL = function() {
      return '/api/user/profile/avatar?cb=' + Date.now();
    };

    $scope.avatarURL = $scope.getURL();
    $rootScope.$on('avatar:updated', function() {
      $timeout(function() {
        $scope.avatarURL = $scope.getURL();
        $scope.$apply();
      });
    });
  }]);
<commit_msg>OR-633 Fix spinner not visible on profile properties update<commit_after>'use strict';

angular.module('esn.profile', ['restangular', 'xeditable', 'angularSpinner', 'esn.user'])
  .directive('profileDisplay', function() {
    return {
      restrict: 'E',
      scope: {
        user: '='
      },
      templateUrl: '/views/modules/profile/profile.html'
    };
  })

  .directive('profileMinicard', function() {
    return {
      restrict: 'E',
      scope: {
        user: '=',
        label: '@',
        labelclass: '@'
      },
      templateUrl: '/views/modules/profile/minicard.html'
    };
  })

  .controller('profileEditionController', ['$scope', 'profileAPI', 'editableOptions', function($scope, profileAPI, editableOptions) {
    //theming for yes/no buttons in field modification confirmation
    editableOptions.theme = 'bs3';
    var maxNameLength = 100;

    $scope.running = {
      name: false,
      job: false,
      service: false,
      building_location: false,
      office_location: false,
      phone: false
    };

    $scope.initFullName = function(firstname, lastname) {
      if (firstname && lastname) {
        $scope.fullName = firstname + ' ' + lastname;
      }
      return $scope.fullName;
    };

    var updateField = function(data, runningMarker, fieldName) {
      $scope.running[runningMarker] = true;

      return profileAPI.updateProfileField(fieldName, data).then(
        function(data) {
          $scope.running[runningMarker] = false;
          return true;
        },
        function(error) {
          $scope.running[runningMarker] = false;
          return error.statusText;
        }
      ).finally (function() {
        $scope.running[runningMarker] = false;
      });
    };

    $scope.updateName = function(data) {
      var nameParts = data.split(' ');
      if (nameParts.length < 2) {
        return 'Incorrect Name';
      }
      var firstName = nameParts.shift();
      var lastName = nameParts.join(' ');
      if (firstName.length > maxNameLength) {
        return 'First name is too long';
      }
      if (lastName.length > maxNameLength) {
        return 'Last name is too long';
      }

      $scope.running.name = true;
      return profileAPI.updateProfileField('firstname', firstName).then(
        function(data) {
          $scope.running.name = false;
          return updateField(lastName, $scope.running.name, 'lastname');
        },
        function(error) {
          $scope.running.name = false;
          return error.statusText;
        }
      );
    };

    $scope.updateJob = function(data) {
      return updateField(data, 'job', 'job_title');
    };

    $scope.updateService = function(data) {
      return updateField(data, 'service', 'service');
    };

    $scope.updateBuildingLocation = function(data) {
      return updateField(data, 'building_location', 'building_location');
    };

    $scope.updateOfficeLocation = function(data) {
      return updateField(data, 'office_location', 'office_location');
    };

    $scope.updatePhone = function(data) {
      return updateField(data, 'phone', 'main_phone');
    };

  }])

  .factory('profileAPI', ['Restangular', function(Restangular) {
    function updateProfileField(fieldName, fieldValue) {
      var payload = {
        value: fieldValue
      };
      return Restangular.one('user/profile', fieldName).customPUT(payload);
    }

    return {
      updateProfileField: updateProfileField
    };
  }])

  .controller('profilecontroller', ['$scope', 'userAPI', function($scope, userAPI) {
    userAPI.currentUser().then(function(response) {
      $scope.user = response.data;
    });
  }])
  .controller('avatarController', ['$rootScope', '$scope', '$timeout', function($rootScope, $scope, $timeout) {

    $scope.getURL = function() {
      return '/api/user/profile/avatar?cb=' + Date.now();
    };

    $scope.avatarURL = $scope.getURL();
    $rootScope.$on('avatar:updated', function() {
      $timeout(function() {
        $scope.avatarURL = $scope.getURL();
        $scope.$apply();
      });
    });
  }]);
<|endoftext|>