<commit_before>
import { expect } from 'chai';

const {Quest, QuestGen, QuestPopulate}
    = require('../../../client/src/quest-gen');
const FactoryWorld = require('../../../client/src/factory.world');
const RGTest = require('../../roguetest');

const questGram1 = '<QUEST> ::= "goto" "kill";';

const questGram2 =
`<QUEST> ::= <goto> "kill";
<goto> ::= <subquest> "goto" | "goto";
<subquest> ::= "goto" | "goto" <QUEST>;`;

const questGram3 =
`<QUEST> ::= <goto> <get> <learn>;
<goto> ::= <learn> "goto_there";
<get> ::= <goto> "get_it";
<learn> ::= "learn_it";`;

describe('QuestGen', () => {
    let questGen = null;

    beforeEach(() => {
        questGen = new QuestGen();
    });

    it('can create simple quests', () => {
        const rules = QuestGen.parse(questGram1);
        const conf = {rules};

        const quest = questGen.genQuestWithConf(conf);
        expect(quest).to.be.instanceof(Quest);
        expect(quest.numQuests()).to.equal(1);
        expect(quest.numTasks()).to.equal(2);
        console.log(JSON.stringify(quest));
    });

    it('can create quests with sub-quests', () => {
        const rules = QuestGen.parse(questGram2);
        const conf = {rules, minQuests: 2};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numQuests()).to.be.above(1);
    });

    it('creates a single task from each term', () => {
        const rules = QuestGen.parse(questGram3);
        const conf = {debug: true, rules};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numTasks()).to.equal(6);
    });
});

describe('QuestPopulate', () => {
    let questPopul = null;

    beforeEach(() => {
        questPopul = new QuestPopulate();
    });

    it('is used to map quests to resources', () => {
        const factWorld = new FactoryWorld();
        const city = factWorld.createCity({
            name: 'QuestCity', nQuarters: 1,
            quarter: [
                {name: 'QuestQuarter', nLevels: 1}
            ]
        });
        const taskList = ['<goto>already_there', '<kill>kill'];
        const quest = new Quest('Kill an actor', taskList);
        questPopul.mapQuestToResources(quest, city, null);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const actors = level.getActors();

        let hasGiver = false;
        let hasTarget = false;
        actors.forEach(actor => {
            console.log('Checking actor', actor.getName());
            if (actor.has('QuestTarget')) {hasTarget = true;}
            if (actor.has('QuestGiver')) {hasGiver = true;}
        });

        expect(hasGiver).to.equal(true);
        expect(hasTarget).to.equal(true);
    });

    it('can map learn/goto/get/give task', () => {
        const area = RGTest.createTestArea();
        const taskList = [
            '<goto>already_there',
            'listen',
            '<goto>goto',
            '<get>gather',
            '<goto>goto',
            'give'
        ];
        const quest = new Quest('Learn item loc and give it', taskList);
        const areaTile = area.getTileXY(0, 0);
        const city = areaTile.getZones('City')[0];
        const ok = questPopul.mapQuestToResources(quest, city, areaTile);
        expect(ok, 'Quest mapped OK').to.equal(true);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const giver = level.getActors().find(a => a.has('QuestGiver'));
        expect(giver).to.not.be.empty;
        const giverComp = giver.get('QuestGiver');
        const questTargets = giverComp.getQuestTargets();
        expect(questTargets.length).to.equal(6);

    });

    it('can map any arbitrary quest without sub-quests to resources', () => {
        for (let i = 0; i < 5; i++) {
            const player = RGTest.createPlayer(['Potion of power']);
            const area = RGTest.createTestArea();
            const city = area.getTileXY(0, 0).getZones('City')[0];
            const level0 = city.getLevels()[0];
            level0.addActor(player, 10, 10);
            const numCreated = questPopul.createQuests({}, area, 0, 0);
            expect(numCreated).to.equal(1);
        }
    });

    it('can map any arbitrary quest to resources/tasks/subquests', () => {
        // const area = RGTest.createTestArea();
    });
});
<commit_msg>Added call to createTestWorld().<commit_after>
import { expect } from 'chai';

const {Quest, QuestGen, QuestPopulate}
    = require('../../../client/src/quest-gen');
const FactoryWorld = require('../../../client/src/factory.world');
const RGTest = require('../../roguetest');

const questGram1 = '<QUEST> ::= "goto" "kill";';

const questGram2 =
`<QUEST> ::= <goto> "kill";
<goto> ::= <subquest> "goto" | "goto";
<subquest> ::= "goto" | "goto" <QUEST>;`;

const questGram3 =
`<QUEST> ::= <goto> <get> <learn>;
<goto> ::= <learn> "goto_there";
<get> ::= <goto> "get_it";
<learn> ::= "learn_it";`;

describe('QuestGen', () => {
    let questGen = null;

    beforeEach(() => {
        questGen = new QuestGen();
    });

    it('can create simple quests', () => {
        const rules = QuestGen.parse(questGram1);
        const conf = {rules};

        const quest = questGen.genQuestWithConf(conf);
        expect(quest).to.be.instanceof(Quest);
        expect(quest.numQuests()).to.equal(1);
        expect(quest.numTasks()).to.equal(2);
        console.log(JSON.stringify(quest));
    });

    it('can create quests with sub-quests', () => {
        const rules = QuestGen.parse(questGram2);
        const conf = {rules, minQuests: 2};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numQuests()).to.be.above(1);
    });

    it('creates a single task from each term', () => {
        const rules = QuestGen.parse(questGram3);
        const conf = {debug: true, rules};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numTasks()).to.equal(6);
    });
});

describe('QuestPopulate', () => {
    let questPopul = null;

    beforeEach(() => {
        questPopul = new QuestPopulate();
    });

    it('is used to map quests to resources', () => {
        const factWorld = new FactoryWorld();
        const city = factWorld.createCity({
            name: 'QuestCity', nQuarters: 1,
            quarter: [
                {name: 'QuestQuarter', nLevels: 1}
            ]
        });
        const taskList = ['<goto>already_there', '<kill>kill'];
        const quest = new Quest('Kill an actor', taskList);
        questPopul.mapQuestToResources(quest, city, null);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const actors = level.getActors();

        let hasGiver = false;
        let hasTarget = false;
        actors.forEach(actor => {
            console.log('Checking actor', actor.getName());
            if (actor.has('QuestTarget')) {hasTarget = true;}
            if (actor.has('QuestGiver')) {hasGiver = true;}
        });

        expect(hasGiver).to.equal(true);
        expect(hasTarget).to.equal(true);
    });

    it('can map learn/goto/get/give task', () => {
        const area = RGTest.createTestArea();
        const taskList = [
            '<goto>already_there',
            'listen',
            '<goto>goto',
            '<get>gather',
            '<goto>goto',
            'give'
        ];
        const quest = new Quest('Learn item loc and give it', taskList);
        const areaTile = area.getTileXY(0, 0);
        const city = areaTile.getZones('City')[0];
        const ok = questPopul.mapQuestToResources(quest, city, areaTile);
        expect(ok, 'Quest mapped OK').to.equal(true);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const giver = level.getActors().find(a => a.has('QuestGiver'));
        expect(giver).to.not.be.empty;
        const giverComp = giver.get('QuestGiver');
        const questTargets = giverComp.getQuestTargets();
        expect(questTargets.length).to.equal(6);

    });

    it('can map any arbitrary quest without sub-quests to resources', () => {
        for (let i = 0; i < 5; i++) {
            const player = RGTest.createPlayer(['Potion of power']);
            const world = RGTest.createTestWorld();
            const area = world.getCurrentArea();
            const game = RGTest.createGame({place: world, player});
            expect(game).to.not.be.empty;
            const city = area.getTileXY(0, 0).getZones('City')[0];
            const level0 = city.getLevels()[0];
            level0.addActor(player, 10, 10);
            const numCreated = questPopul.createQuests({}, area, 0, 0);
            expect(numCreated).to.equal(1);
        }
    });

    it('can map any arbitrary quest to resources/tasks/subquests', () => {
        // const area = RGTest.createTestArea();
    });
});
<|endoftext|>


<commit_before>import chai from 'chai'
import { Text, TextAssembler, ElementAssembler } from '../lib'

const { assert } = chai

const serializer = new XMLSerializer

describe('TextAssembler', () => {
    describe('new TextAssembler', () => {
        const text = new TextAssembler
        const node = text.node
        it('instanceof Text', () => {
            assert.instanceOf(node, Text)
        })
        it('node.data', () => {
            assert.propertyVal(node, 'data', '')
        })
    })
    describe('new TextAssembler(new String)', () => {
        const text = new TextAssembler('foobar')
        it('node.data', () => {
            assert.propertyVal(text.node, 'data', 'foobar')
        })
    })
    describe('new TextAssembler({ data })', () => {
        const text = new TextAssembler({ data : 'foobar' })
        it('node.data', () => {
            assert.propertyVal(text.node, 'data', 'foobar')
        })
    })
    describe('new TextAssembler({ node })', () => {
        const node = document.createTextNode('foobar')
        const text = new TextAssembler({ node })
        it('nodes equal', () => {
            assert.equal(text.node, node)
        })
    })
    describe('data = new String', () => {
        const text = new TextAssembler
        text.data = 'foobar'
        it('node.data', () => {
            assert.propertyVal(text.node, 'data', 'foobar')
        })
        it('data', () => {
            assert.propertyVal(text, 'data', 'foobar')
        })
    })
})
<commit_msg>TextAssembler: improve specs<commit_after>import chai from 'chai'
import { Text, TextAssembler, ElementAssembler } from '../lib'

const { assert } = chai

const serializer = new XMLSerializer

describe('TextAssembler', () => {
    describe('new TextAssembler', () => {
        const text = new TextAssembler
        const node = text.node
        it('instanceof Text', () => {
            assert.instanceOf(node, Text)
        })
        it('node.data', () => {
            assert.propertyVal(node, 'data', '')
        })
        it('serializeToString(node)', () => {
            assert.equal(serializer.serializeToString(node), '')
        })
    })
    describe('new TextAssembler(new String)', () => {
        const text = new TextAssembler('foobar')
        const node = text.node
        it('node.data', () => {
            assert.propertyVal(node, 'data', 'foobar')
        })
        it('serializeToString(node)', () => {
            assert.equal(serializer.serializeToString(node), 'foobar')
        })
    })
    describe('new TextAssembler({ data })', () => {
        const text = new TextAssembler({ data : 'foobar' })
        const node = text.node
        it('node.data', () => {
            assert.propertyVal(node, 'data', 'foobar')
        })
        it('serializeToString(node)', () => {
            assert.equal(serializer.serializeToString(node), 'foobar')
        })
    })
    describe('new TextAssembler({ node })', () => {
        const node = document.createTextNode('foobar')
        const text = new TextAssembler({ node })
        it('nodes equal', () => {
            assert.equal(text.node, node)
        })
    })
    describe('data = new String', () => {
        const text = new TextAssembler
        const node = text.node
        text.data = 'foobar'
        it('node.data', () => {
            assert.propertyVal(node, 'data', 'foobar')
        })
        it('data', () => {
            assert.propertyVal(text, 'data', 'foobar')
        })
        it('serializeToString(node)', () => {
            assert.equal(serializer.serializeToString(node), 'foobar')
        })
    })
    describe('new TextAssembler({ data, parentNode })', () => {
        const element = new ElementAssembler
        const text = new TextAssembler({
            data : 'foobar',
            parentNode : element
        })
        const node = text.node
        it('node.parentNode', () => {
            assert.propertyVal(node, 'parentNode', element.node)
        })
        it('parentNode', () => {
            assert.propertyVal(text, 'parentNode', element)
        })
        it('serializeToString(element.node)', () => {
            const xml = serializer.serializeToString(element.node)
            assert.equal(xml, '<element>foobar</element>')
        })
    })
})
<|endoftext|>


<commit_before>import moment from 'moment'
import {sortBy} from 'lodash'
import {isPast} from '<utils>/utils'

const sponsors = {
  premierSponsors: [
    {
      imgSrc: '/sponsors/eggheadio.png',
      name: 'Egghead.io',
      link: 'http://jsair.io/eggheadio',
      tagline: 'Bite-sized web development video training',
      startDate: '2015-12-08',
      endDate: '2016-06-08',
    },
  ],
  goldSponsors: [
    {
      imgSrc: '/sponsors/frontendmasters.png',
      name: 'Frontend Masters',
      link: 'http://jsair.io/frontendmasters',
      tagline: 'Expert front-end training',
      startDate: '2015-12-08',
      endDate: '2016-06-08',
    },
    {
      imgSrc: '/sponsors/trackjs.png',
      name: '{Track:js}',
      link: 'http://jsair.io/trackjs',
      tagline: 'JavaScript Error Monitoring',
      startDate: '2015-12-08',
      endDate: '2016-06-08',
    },
    {
      imgSrc: '/sponsors/wallabyjs.png',
      name: 'Wallaby.js',
      link: 'http://jsair.io/wallabyjs',
      tagline: 'Realtime code coverage',
      startDate: '2016-01-15',
      endDate: '2016-04-18',
    },
    {
      imgSrc: '/sponsors/codecov.png',
      name: 'Codecov.io',
      link: 'http://jsair.io/codecov',
      tagline: 'Code coverage done right',
      startDate: '2016-01-15',
      endDate: '2016-04-19',
    },
    {
      imgSrc: '/sponsors/sparkpost.png',
      name: 'SparkPost',
      link: 'http://jsair.io/sparkpost',
      tagline: `Email. We've Got It Down.`,
      startDate: '2016-04-19',
      endDate: '2016-07-05',
    },
    {
      imgSrc: '/sponsors/webstorm.png',
      name: 'WebStorm',
      link: 'http://jsair.io/webstorm',
      tagline: 'Smart JavaScript IDE',
      startDate: '2016-04-20',
      endDate: '2016-07-20',
    },
  ],
  silverSponsors: [
    {
      imgSrc: '/sponsors/fluent.png',
      name: 'Fluent',
      link: 'http://jsair.io/fluent',
      tagline: 'Web development training',
      startDate: '2016-02-02',
      endDate: '2016-05-02',
    },
    {
      imgSrc: '/sponsors/auth0.png',
      name: 'Auth0',
      link: 'http://jsair.io/auth0',
      tagline: 'Authentication Made Simple',
      startDate: '2016-02-17',
      endDate: '2016-05-17',
    },
    {
      imgSrc: '/sponsors/trading-tech.png',
      name: 'Trading Technologies',
      link: 'http://jsair.io/trading-technologies',
      tagline: `Building For What's Next`,
      startDate: '2016-03-22',
      endDate: '2016-06-22',
    },
    {
      imgSrc: '/sponsors/sparkpost.png',
      name: 'SparkPost',
      link: 'http://jsair.io/sparkpost',
      tagline: `Email. We've Got It Down.`,
      startDate: '2016-04-05',
      endDate: '2016-04-19',
    },
  ],
  appreciationSponsors: [
    {
      twitter: '_jwngr',
      name: 'Jacob Wenger',
      startDate: '2016-03-11',
      endDate: '2016-06-11',
    },
    {
      twitter: 'nyrosmith',
      name: 'Martin Schmid',
      startDate: '2016-03-11',
      endDate: '2016-06-11',
    },
  ].map(s => {
    return {
      imgSrc: `/sponsors/appreciation/${s.twitter}.png`,
      link: `https://twitter.com/${s.twitter}`,
      squareImage: false,
      ...s,
    }
  }),
}

function getSponsorsForDate(date) {
  const filterSponsor = getSponsorFilter(date)
  const sponsorsForDate = Object.keys(sponsors).reduce((current, key) => {
    const sponsorGroup = sponsors[key]
    const filteredSponsors = sponsorGroup.filter(filterSponsor)
    const sortedSponsors = sortBy(filteredSponsors, 'date')
    if (key === 'premierSponsors') {
      current.premierSponsor = sortedSponsors[0]
    } else {
      current[key] = sortedSponsors
    }
    return current
  }, {})
  return sponsorsForDate
}

function getSponsorFilter(date) {
  const momentDate = moment(date)
  return function filter(sponsor) {
    const {startDate, endDate} = sponsor
    const sponsorshipHasBegun = isPast(startDate, momentDate)
    const sponsorshipHasEnded = endDate && isPast(endDate, momentDate)
    return sponsorshipHasBegun && !sponsorshipHasEnded
  }
}

const currentSponsors = getSponsorsForDate(new Date())

export default sponsors

export {currentSponsors, getSponsorsForDate}
<commit_msg>Update end date for Egghead.io sponsorship<commit_after>import moment from 'moment'
import {sortBy} from 'lodash'
import {isPast} from '<utils>/utils'

const sponsors = {
  premierSponsors: [
    {
      imgSrc: '/sponsors/eggheadio.png',
      name: 'Egghead.io',
      link: 'http://jsair.io/eggheadio',
      tagline: 'Bite-sized web development video training',
      startDate: '2015-12-08',
      endDate: '2016-09-08',
    },
  ],
  goldSponsors: [
    {
      imgSrc: '/sponsors/frontendmasters.png',
      name: 'Frontend Masters',
      link: 'http://jsair.io/frontendmasters',
      tagline: 'Expert front-end training',
      startDate: '2015-12-08',
      endDate: '2016-06-08',
    },
    {
      imgSrc: '/sponsors/trackjs.png',
      name: '{Track:js}',
      link: 'http://jsair.io/trackjs',
      tagline: 'JavaScript Error Monitoring',
      startDate: '2015-12-08',
      endDate: '2016-06-08',
    },
    {
      imgSrc: '/sponsors/wallabyjs.png',
      name: 'Wallaby.js',
      link: 'http://jsair.io/wallabyjs',
      tagline: 'Realtime code coverage',
      startDate: '2016-01-15',
      endDate: '2016-04-18',
    },
    {
      imgSrc: '/sponsors/codecov.png',
      name: 'Codecov.io',
      link: 'http://jsair.io/codecov',
      tagline: 'Code coverage done right',
      startDate: '2016-01-15',
      endDate: '2016-04-19',
    },
    {
      imgSrc: '/sponsors/sparkpost.png',
      name: 'SparkPost',
      link: 'http://jsair.io/sparkpost',
      tagline: `Email. We've Got It Down.`,
      startDate: '2016-04-19',
      endDate: '2016-07-05',
    },
    {
      imgSrc: '/sponsors/webstorm.png',
      name: 'WebStorm',
      link: 'http://jsair.io/webstorm',
      tagline: 'Smart JavaScript IDE',
      startDate: '2016-04-20',
      endDate: '2016-07-20',
    },
  ],
  silverSponsors: [
    {
      imgSrc: '/sponsors/fluent.png',
      name: 'Fluent',
      link: 'http://jsair.io/fluent',
      tagline: 'Web development training',
      startDate: '2016-02-02',
      endDate: '2016-05-02',
    },
    {
      imgSrc: '/sponsors/auth0.png',
      name: 'Auth0',
      link: 'http://jsair.io/auth0',
      tagline: 'Authentication Made Simple',
      startDate: '2016-02-17',
      endDate: '2016-05-17',
    },
    {
      imgSrc: '/sponsors/trading-tech.png',
      name: 'Trading Technologies',
      link: 'http://jsair.io/trading-technologies',
      tagline: `Building For What's Next`,
      startDate: '2016-03-22',
      endDate: '2016-06-22',
    },
    {
      imgSrc: '/sponsors/sparkpost.png',
      name: 'SparkPost',
      link: 'http://jsair.io/sparkpost',
      tagline: `Email. We've Got It Down.`,
      startDate: '2016-04-05',
      endDate: '2016-04-19',
    },
  ],
  appreciationSponsors: [
    {
      twitter: '_jwngr',
      name: 'Jacob Wenger',
      startDate: '2016-03-11',
      endDate: '2016-06-11',
    },
    {
      twitter: 'nyrosmith',
      name: 'Martin Schmid',
      startDate: '2016-03-11',
      endDate: '2016-06-11',
    },
  ].map(s => {
    return {
      imgSrc: `/sponsors/appreciation/${s.twitter}.png`,
      link: `https://twitter.com/${s.twitter}`,
      squareImage: false,
      ...s,
    }
  }),
}

function getSponsorsForDate(date) {
  const filterSponsor = getSponsorFilter(date)
  const sponsorsForDate = Object.keys(sponsors).reduce((current, key) => {
    const sponsorGroup = sponsors[key]
    const filteredSponsors = sponsorGroup.filter(filterSponsor)
    const sortedSponsors = sortBy(filteredSponsors, 'date')
    if (key === 'premierSponsors') {
      current.premierSponsor = sortedSponsors[0]
    } else {
      current[key] = sortedSponsors
    }
    return current
  }, {})
  return sponsorsForDate
}

function getSponsorFilter(date) {
  const momentDate = moment(date)
  return function filter(sponsor) {
    const {startDate, endDate} = sponsor
    const sponsorshipHasBegun = isPast(startDate, momentDate)
    const sponsorshipHasEnded = endDate && isPast(endDate, momentDate)
    return sponsorshipHasBegun && !sponsorshipHasEnded
  }
}

const currentSponsors = getSponsorsForDate(new Date())

export default sponsors

export {currentSponsors, getSponsorsForDate}
<|endoftext|>


<commit_before>function Template(template) {
	this.template = template;
	this.index = 0;
	this.length = template.length;
}

Template.prototype = {
	next: function () {
		this.index++;
		return this;
	},
	skipWhitespace: function () {
		//regexpNoWhitespace.lastIndex = this.index;
		//var result = regexpNoWhitespace.exec(this.template);
		//if (result){
		//    this.index = result.index;
		//}
		//return this;

		var template = this.template,
			index = this.index,
			length = this.length;

		for (; index < length; index++) {
			if (template.charCodeAt(index) !== 32 /*' '*/) {
				break;
			}
		}

		this.index = index;

		return this;
	},

	skipToChar: function (c) {
		var template = this.template,
			index;

		do {
			index = template.indexOf(c, this.index);
		}
		while (~index && template.charCodeAt(index - 1) !== 92 /*'\\'*/);

		this.index = index;

		return this;
	},

//	skipToAny: function (chars) {
//		var r = regexp[chars];
//		if (r == null) {
//			console.error('Unknown regexp %s: Create', chars);
//			r = (regexp[chars] = new RegExp('[' + chars + ']', 'g'));
//		}
//
//		r.lastIndex = this.index;
//		var result = r.exec(this.template);
//		if (result != null) {
//			this.index = result.index;
//		}
//		return this;
//	},

	skipToAttributeBreak: function () {

//		regexpAttrEnd.lastIndex = ++this.index;
//		var result;
//		do {
//			result = regexpAttrEnd.exec(this.template);
//			if (result != null) {
//				if (result[0] == '#' && this.template.charCodeAt(this.index + 1) === 123) {
//					regexpAttrEnd.lastIndex += 2;
//					continue;
//				}
//				this.index = result.index;
//				break;
//			}
//		} while (result != null)
//		return this;

		var template = this.template,
			index = this.index,
			length = this.length,
			c;
		do {
			c = template.charCodeAt(++index);
			// if c == # && next() == { - continue */
			if (c === 35 && template.charCodeAt(index + 1) === 123) {
				index++;
				c = null;
			}
		}
		while (c !== 46 && c !== 35 && c !== 62 && c !== 123 && c !== 32 && c !== 59 && index < length);
		//while(!== ".#>{ ;");

		this.index = index;

		return this;
	},

	sliceToChar: function (c) {
		var template = this.template,
			index = this.index,
			start = index,
			isEscaped = false,
			value;

		while (true) {
			index = template.indexOf(c, index);
			if (!~index || template.charCodeAt(index - 1) !== 92 /*'\\'*/) {
				break;
			}
			isEscaped = true;
			index++;
		}

		value = template.substring(start, index);

		this.index = index;

		return isEscaped ? value.replace(regexpEscapedChar[c], c) : value;

		//-return this.skipToChar(c).template.substring(start, this.index);
	}

//	,
//	sliceToAny: function (chars) {
//		var start = this.index;
//		return this.skipToAny(chars).template.substring(start, this.index);
//	}
};
<commit_msg>[fix] prevent this.index from -1 if char no found<commit_after>function Template(template) {
	this.template = template;
	this.index = 0;
	this.length = template.length;
}

Template.prototype = {
	next: function () {
		this.index++;
		return this;
	},
	skipWhitespace: function () {
		//regexpNoWhitespace.lastIndex = this.index;
		//var result = regexpNoWhitespace.exec(this.template);
		//if (result){
		//    this.index = result.index;
		//}
		//return this;

		var template = this.template,
			index = this.index,
			length = this.length;

		for (; index < length; index++) {
			if (template.charCodeAt(index) !== 32 /*' '*/) {
				break;
			}
		}

		this.index = index;

		return this;
	},

	skipToChar: function (c) {
		var template = this.template,
			index;

		do {
			index = template.indexOf(c, this.index);
		}
		while (~index && template.charCodeAt(index - 1) !== 92 /*'\\'*/);

		this.index = index;

		return this;
	},

//	skipToAny: function (chars) {
//		var r = regexp[chars];
//		if (r == null) {
//			console.error('Unknown regexp %s: Create', chars);
//			r = (regexp[chars] = new RegExp('[' + chars + ']', 'g'));
//		}
//
//		r.lastIndex = this.index;
//		var result = r.exec(this.template);
//		if (result != null) {
//			this.index = result.index;
//		}
//		return this;
//	},

	skipToAttributeBreak: function () {

//		regexpAttrEnd.lastIndex = ++this.index;
//		var result;
//		do {
//			result = regexpAttrEnd.exec(this.template);
//			if (result != null) {
//				if (result[0] == '#' && this.template.charCodeAt(this.index + 1) === 123) {
//					regexpAttrEnd.lastIndex += 2;
//					continue;
//				}
//				this.index = result.index;
//				break;
//			}
//		} while (result != null)
//		return this;

		var template = this.template,
			index = this.index,
			length = this.length,
			c;
		do {
			c = template.charCodeAt(++index);
			// if c == # && next() == { - continue */
			if (c === 35 && template.charCodeAt(index + 1) === 123) {
				index++;
				c = null;
			}
		}
		while (c !== 46 && c !== 35 && c !== 62 && c !== 123 && c !== 32 && c !== 59 && index < length);
		//while(!== ".#>{ ;");

		this.index = index;

		return this;
	},

	sliceToChar: function (c) {
		var template = this.template,
			index = this.index,
			start = index,
			isEscaped = false,
			value, nindex;

		while ((nindex = template.indexOf(c, index)) > -1) {
			index = nindex;
			if (template.charCodeAt(index - 1) !== 92 /*'\\'*/) {
				break;
			}
			isEscaped = true;
			index++;
		}

		value = template.substring(start, index);

		this.index = index;

		return isEscaped ? value.replace(regexpEscapedChar[c], c) : value;

		//-return this.skipToChar(c).template.substring(start, this.index);
	}

//	,
//	sliceToAny: function (chars) {
//		var start = this.index;
//		return this.skipToAny(chars).template.substring(start, this.index);
//	}
};
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.6.3
var MainCtrl, app;

app = angular.module('app', ['ngSanitize']);

app.factory('questions', function($http) {
  return {
    newQuestion: function(cb) {
      var doRequest;
      doRequest = function() {
        return $http.get('/new-question/').success(function(data) {
          return cb(data);
        }).error(function() {
          return doRequest();
        });
      };
      return doRequest();
    }
  };
});

MainCtrl = function($scope, questions) {
  $scope.numQuestions = 2;
  $scope.currentQuestionNum = 0;
  $scope.numCorrect = 0;
  $scope.percentCorrect = 0;
  $scope.getNextQuestion = function() {
    if ($scope.currentQuestionNum === $scope.numQuestions) {
      $scope.gameOver = true;
      $scope.calculateGrade();
      return;
    }
    $scope.busy = true;
    return questions.newQuestion(function(data) {
      $scope.currentQuestion = data;
      $scope.currentQuestionNum++;
      return $scope.busy = false;
    });
  };
  $scope.getNextQuestion();
  $scope.setChoice = function(i) {
    return $scope.choice = i;
  };
  $scope.submitChoice = function() {
    $scope.currentQuestion.graded = true;
    $scope.currentQuestion.correct = $scope.choice === $scope.currentQuestion.answer;
    if ($scope.currentQuestion.correct) {
      $scope.numCorrect++;
      return $scope.percentCorrect = 100 * $scope.numCorrect / $scope.numQuestions;
    }
  };
  $scope.getProgressBarStyle = function() {
    var color;
    color = "green";
    if ($scope.percentCorrect < 50) {
      color = "red";
    } else if ($scope.percentCorrect < 70) {
      color = "yellow";
    } else if ($scope.percentCorrect < 90) {
      color = "orange";
    }
    return {
      width: "" + $scope.percentCorrect + "%",
      'background-color': color
    };
  };
  return $scope.calculateGrade = function() {
    var pc;
    pc = $scope.percentCorrect;
    if (pc < 60) {
      $scope.letterGrade = "F";
      return $scope.doctorLevel = "Bro, do you even healthcare?";
    } else if (pc < 70) {
      $scope.letterGrade = "D";
      return $scope.doctorLevel = "Nurse Assistant";
    } else if (pc < 80) {
      $scope.letterGrade = "C";
      return $scope.doctorLevel = "Nurse";
    } else if (pc < 90) {
      $scope.letterGrade = "B";
      return $scope.doctorLevel = "Physician";
    } else {
      $scope.letterGrade = "A";
      return $scope.doctorLevel = "Dr. House";
    }
  };
};
<commit_msg>Recompile main.js<commit_after>// Generated by CoffeeScript 1.6.3
var MainCtrl, app;

app = angular.module('app', ['ngSanitize']);

app.factory('questions', function($http) {
  return {
    newQuestion: function(cb) {
      var doRequest;
      doRequest = function() {
        return $http.get('/new-question/').success(function(data) {
          return cb(data);
        }).error(function() {
          return doRequest();
        });
      };
      return doRequest();
    }
  };
});

MainCtrl = function($scope, questions) {
  $scope.numQuestions = 10;
  $scope.currentQuestionNum = 0;
  $scope.numCorrect = 0;
  $scope.percentCorrect = 0;
  $scope.getNextQuestion = function() {
    if ($scope.currentQuestionNum === $scope.numQuestions) {
      $scope.gameOver = true;
      $scope.calculateGrade();
      return;
    }
    $scope.busy = true;
    return questions.newQuestion(function(data) {
      $scope.currentQuestion = data;
      $scope.currentQuestionNum++;
      return $scope.busy = false;
    });
  };
  $scope.getNextQuestion();
  $scope.setChoice = function(i) {
    return $scope.choice = i;
  };
  $scope.submitChoice = function() {
    $scope.currentQuestion.graded = true;
    $scope.currentQuestion.correct = $scope.choice === $scope.currentQuestion.answer;
    if ($scope.currentQuestion.correct) {
      $scope.numCorrect++;
      return $scope.percentCorrect = 100 * $scope.numCorrect / $scope.numQuestions;
    }
  };
  $scope.getProgressBarStyle = function() {
    var color;
    color = "green";
    if ($scope.percentCorrect < 50) {
      color = "red";
    } else if ($scope.percentCorrect < 70) {
      color = "yellow";
    } else if ($scope.percentCorrect < 90) {
      color = "orange";
    }
    return {
      width: "" + $scope.percentCorrect + "%",
      'background-color': color
    };
  };
  return $scope.calculateGrade = function() {
    var pc;
    pc = $scope.percentCorrect;
    if (pc < 60) {
      $scope.letterGrade = "F";
      return $scope.doctorLevel = "Bro, do you even healthcare?";
    } else if (pc < 70) {
      $scope.letterGrade = "D";
      return $scope.doctorLevel = "Nurse Assistant";
    } else if (pc < 80) {
      $scope.letterGrade = "C";
      return $scope.doctorLevel = "Nurse";
    } else if (pc < 90) {
      $scope.letterGrade = "B";
      return $scope.doctorLevel = "Physician";
    } else {
      $scope.letterGrade = "A";
      return $scope.doctorLevel = "Dr. House";
    }
  };
};
<|endoftext|>


<commit_before>/**
* Created by Mauriel on 3/9/2017.
*/
$(document).ready(function () {
    var json_response_file_types = {};
    var json_response_multiple_file = {};
    var selected_file = undefined;
    var myDropzone;
    var fileIcons = getFileIcons();

    if (sessionStorage.signininfo) {
        $("#sign-in-info").text(sessionStorage.signininfo);
        $("#btn-select-irods-file").show();
        $("#irods-sel-file").text("No file selected.");
    }

    Dropzone.options.hsDropzone = {
        previewTemplate: document.getElementById('preview-template').innerHTML,
        clickable: "#dz-container",
        previewsContainer: "#dz-container:not(.dz-details)",
        paramName: "files", // The name that will be used to transfer the file
        maxFilesize: 1024, // MB
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 99, // arbitrary large number for parallel uploads

        success: function (file, response) {
            if (response.status == "success") {
                window.location = response['resource_url'];
            }
            else {
                console.log(response);
            }
        },
        error: function (file, response) {
            console.log(response);
        },

        init: function () {
            myDropzone = this;

            $(".btn-create-resource").click(function () {
                $("html, #dz-container").css("cursor", "progress");

                // Delete invalid files from queue before uploading
                $(".dz-error .btn-remove").trigger("click");

                var title = $("#txtTitle").val().trim();
                if (!title) {
                    title = $("#txtTitle").attr("placeholder");
                }

                $("#form-title").val(title);

                if (myDropzone.files.length > 0) {
                    myDropzone.processQueue();
                }
                else {
                    var url = $("#hsDropzone").attr("action");
                    var datastring = $("#hsDropzone").serialize();
                    $.ajax({
                        type: "POST",
                        data: datastring,
                        url: url,
                        success: function (response) {
                            if (response.status == "success") {
                                window.location = response['resource_url'];
                            }
                        },
                        error: function (response) {
                            console.log(response);
                        }
                    });
                }
            });

            // The user dragged a file onto the Dropzone
            this.on("dragenter", function (file) {
                $("#hsDropzone").toggleClass("hs-dropzone-highlight", true);
            });

            // The user dragged a file out of the Dropzone
            this.on("dragleave", function (event) {
                $("#hsDropzone").toggleClass("hs-dropzone-highlight", false);
            });

            this.on("addedfile", function (file) {
                // Initialize tooltips
                var template = $(file.previewElement);
                template.find(".dz-filename").attr("title", template.find("span[data-dz-name]").text());

                // Set file type icon
                var fileName = template.find(".dz-filename").text();
                var fileTypeExt = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length).toUpperCase();
                if (fileIcons[fileTypeExt]) {
                    template.find(".file-type-icon").append(fileIcons[fileTypeExt]);
                }
                else {
                    template.find(".file-type-icon").append(fileIcons.DEFAULT);
                }

                template.find("[data-toggle='tooltip']").tooltip();

                if (!myDropzone.options.uploadMultiple && myDropzone.files[1] != null) {
                    this.removeFile(this.files[0]);
                }
                $("#hsDropzone").toggleClass("hs-dropzone-highlight", false);

                $(".hs-upload-indicator").hide();
            });

            this.on("removedfile", function (file) {
                $('#hsDropzone .tooltip').remove();
                if (myDropzone.files.length == 0) {
                    $(".hs-upload-indicator").show();
                }
            });

            this.on("error", function (file, error) {
                var template = $(file.previewElement);
                $(template).addClass("dz-error");
                $(template).attr("data-toggle", "tooltip");
                $(template).attr("data-placement", "top");
                $(template).attr("title", error);
                template.tooltip();
            });

            this.on('sendingmultiple', function (data, xhr, formData) {
                $("#upload-content").find("input[name]").each(function () {
                    formData.append($(this).attr("name"), $(this).val());
                });
            });
        }
    };

    $('input:radio[name="copy-move"]').change(function () {
        if ($(this).val() == 'move') {
            $("#copy-or-move").val('move');
            $("#file-move-warning").show();
        }
        else {
            $("#copy-or-move").val('copy');
            $("#file-move-warning").hide();
        }
    });

    $('#dropdown-resource-type li a').click(function () {
        // Removed all previously queued files when the resource type changes.
        Dropzone.forElement("#hsDropzone").removeAllFiles(true);
        $('#irods-sel-file').text("No file selected.");
        $('#irods_file_names').val("");

        if (selected_file != undefined) {
            selected_file.value = '';
        }

        $("#form-resource-type").val($(this).attr("data-value"));

        var template = this.innerHTML;
        $("#select-resource-type")[0].innerHTML = template;
        $("#select-resource-type").find(".resource-type-name").append(" ")

        // Get supported file types
        $.ajax({
            type: "GET",
            url: "/hsapi/_internal/" + $(this).attr("data-value") + "/supported-file-types/",
            success: function (result) {
                json_response_file_types = JSON.parse(result);

                if (JSON.parse(json_response_file_types.file_types).length == 0) {
                    $("#upload-content").hide();    // No files needed
                }
                else {
                    $("#upload-content").show();

                    var supported_file_types = JSON.parse(json_response_file_types.file_types);

                    $("#file-types").empty();

                    if (supported_file_types != ".*") {
                        // Append message
                        $("#file-types").append("" +
                                "Only the following file types can be uploaded:
");

                        // Render badge for each file type
                        for (var i = 0; i < supported_file_types.length; i++) {
                            $("#file-types").append('' + supported_file_types[i] + '');
                        }

                        // Set controls
                        if (myDropzone) {
                            myDropzone.options.acceptedFiles = supported_file_types.toString();
                            $(myDropzone.hiddenFileInput).attr("accept", supported_file_types.toString());
                        }

                    }
                    else {
                        // Append message
                        $("#file-types").append("" +
                                "Any file type can be uploaded.");

                        // Set controls
                        if (myDropzone) {
                            myDropzone.options.acceptedFiles = "";
                            $(myDropzone.hiddenFileInput).removeAttr("accept");
                        }

                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#file-types").empty();

                // Append message
                $("#file-types").append("" +
                                "Error in determining supported file types
");

                // Set controls
                if (myDropzone) {
                    myDropzone.options.acceptedFiles = "";
                    $(myDropzone.hiddenFileInput).removeAttr("accept");
                }
            }
        });

        // Get multiple files flag value
        $.ajax({
            type: "GET",
            url: "/hsapi/_internal/" + $(this).attr("data-value") + "/allow-multiple-file/",
            success: function (result) {
                json_response_multiple_file = JSON.parse(result);

                $("#file-multiple").empty();
                if (json_response_multiple_file.allow_multiple_file == true) {
                    // Append message
                    $("#file-multiple").append("");
                    $("#file-multiple").append("Multiple file upload is allowed.");

                    // Set controls
                    if (myDropzone) {
                        myDropzone.options.uploadMultiple = true;
                        $(myDropzone.hiddenFileInput).attr("multiple", 'multiple');
                    }
                }
                else {
                    // Append message
                    $("#file-multiple").append("");
                    $("#file-multiple").append("Only one file can be uploaded.");

                    // Set controls
                    if (myDropzone) {
                        myDropzone.options.uploadMultiple = false;
                        $(myDropzone.hiddenFileInput).removeAttr('multiple');
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#file-multiple").empty();

                // Append message
                $("#file-multiple").append("");
                $("#file-multiple").append("Error in determining if multiple file upload is allowed for this resource type.");

                // Set controls
                if (myDropzone) {
                    myDropzone.options.uploadMultiple = true;
                    $(myDropzone.hiddenFileInput).attr("multiple", 'multiple');
                }
            }
        })
    });

    $("#btn-remove-all-files").click(function () {
        Dropzone.forElement("#hsDropzone").removeAllFiles(true);
        $(".hs-upload-indicator").show();
    });
});<commit_msg>Undoing merge<commit_after>/**
* Created by Mauriel on 3/9/2017.
*/
$(document).ready(function () {
    var json_response_file_types = {};
    var json_response_multiple_file = {};
    var selected_file = undefined;
    var myDropzone;
    var fileIcons = getFileIcons();

    if (sessionStorage.signininfo) {
        $("#sign-in-info").text(sessionStorage.signininfo);
        $("#btn-select-irods-file").show();
        $("#irods-sel-file").text("No file selected.");
    }

    Dropzone.options.hsDropzone = {
        previewTemplate: document.getElementById('preview-template').innerHTML,
        clickable: "#dz-container",
        previewsContainer: "#dz-container:not(.dz-details)",
        paramName: "files", // The name that will be used to transfer the file
        maxFilesize: 1024, // MB
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 99, // arbitrary large number for parallel uploads

        success: function (file, response) {
            if (response.status == "success") {
                window.location = response['resource_url'];
            }
            else {
                console.log(response);
            }
        },
        error: function (file, response) {
            console.log(response);
        },

        init: function () {
            myDropzone = this;

            $(".btn-create-resource").click(function () {
                $("html, #dz-container").css("cursor", "progress");

                // Delete invalid files from queue before uploading
                $(".dz-error .btn-remove").trigger("click");

                var title = $("#txtTitle").val().trim();
                if (!title) {
                    title = $("#txtTitle").attr("placeholder");
                }

                $("#form-title").val(title);

                if (myDropzone.files.length > 0) {
                    myDropzone.processQueue();
                }
                else {
                    var url = $("#hsDropzone").attr("action");
                    var datastring = $("#hsDropzone").serialize();
                    $.ajax({
                        type: "POST",
                        data: datastring,
                        url: url,
                        success: function (response) {
                            if (response.status == "success") {
                                window.location = response['resource_url'];
                            }
                        },
                        error: function (response) {
                            console.log(response);
                        }
                    });
                }
            });

            // The user dragged a file onto the Dropzone
            this.on("dragenter", function (file) {
                $("#hsDropzone").toggleClass("hs-dropzone-highlight", true);
            });

            // The user dragged a file out of the Dropzone
            this.on("dragleave", function (event) {
                $("#hsDropzone").toggleClass("hs-dropzone-highlight", false);
            });

            this.on("addedfile", function (file) {
                // Initialize tooltips
                var template = $(file.previewElement);
                template.find(".dz-filename").attr("title", template.find("span[data-dz-name]").text());

                // Set file type icon
                var fileName = template.find(".dz-filename").text();
                var fileTypeExt = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length).toUpperCase();
                if (fileIcons[fileTypeExt]) {
                    template.find(".file-type-icon").append(fileIcons[fileTypeExt]);
                }
                else {
                    template.find(".file-type-icon").append(fileIcons.DEFAULT);
                }

                template.find("[data-toggle='tooltip']").tooltip();

                if (!myDropzone.options.uploadMultiple && myDropzone.files[1] != null) {
                    this.removeFile(this.files[0]);
                }
                $("#hsDropzone").toggleClass("hs-dropzone-highlight", false);

                $(".hs-upload-indicator").hide();
            });

            this.on("removedfile", function (file) {
                $('#hsDropzone .tooltip').remove();
                if (myDropzone.files.length == 0) {
                    $(".hs-upload-indicator").show();
                }
            });

            this.on("error", function (file, error) {
                var template = $(file.previewElement);
                $(template).addClass("dz-error");
                $(template).attr("data-toggle", "tooltip");
                $(template).attr("data-placement", "top");
                $(template).attr("title", error);
                template.tooltip();
            });

            this.on('sendingmultiple', function (data, xhr, formData) {
                $("#upload-content").find("input[name]").each(function () {
                    formData.append($(this).attr("name"), $(this).val());
                });
            });
        }
    };

    $('input:radio[name="copy-move"]').change(function () {
        if ($(this).val() == 'move') {
            $("#copy-or-move").val('move');
            $("#file-move-warning").show();
        }
        else {
            $("#copy-or-move").val('copy');
            $("#file-move-warning").hide();
        }
    });

    $('#dropdown-resource-type li a').click(function () {
        // Remove all previously queued files when the resource type changes.
        Dropzone.forElement("#hsDropzone").removeAllFiles(true);
        $('#irods-sel-file').text("No file selected.");
        $('#irods_file_names').val("");

        if (selected_file != undefined) {
            selected_file.value = '';
        }

        $("#form-resource-type").val($(this).attr("data-value"));

        var template = this.innerHTML;
        $("#select-resource-type")[0].innerHTML = template;
        $("#select-resource-type").find(".resource-type-name").append(" ")

        // Get supported file types
        $.ajax({
            type: "GET",
            url: "/hsapi/_internal/" + $(this).attr("data-value") + "/supported-file-types/",
            success: function (result) {
                json_response_file_types = JSON.parse(result);

                if (JSON.parse(json_response_file_types.file_types).length == 0) {
                    $("#upload-content").hide();    // No files needed
                }
                else {
                    $("#upload-content").show();

                    var supported_file_types = JSON.parse(json_response_file_types.file_types);

                    $("#file-types").empty();

                    if (supported_file_types != ".*") {
                        // Append message
                        $("#file-types").append("" +
                                "Only the following file types can be uploaded:
");

                        // Render badge for each file type
                        for (var i = 0; i < supported_file_types.length; i++) {
                            $("#file-types").append('' + supported_file_types[i] + '');
                        }

                        // Set controls
                        if (myDropzone) {
                            myDropzone.options.acceptedFiles = supported_file_types.toString();
                            $(myDropzone.hiddenFileInput).attr("accept", supported_file_types.toString());
                        }

                    }
                    else {
                        // Append message
                        $("#file-types").append("" +
                                "Any file type can be uploaded.");

                        // Set controls
                        if (myDropzone) {
                            myDropzone.options.acceptedFiles = "";
                            $(myDropzone.hiddenFileInput).removeAttr("accept");
                        }

                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#file-types").empty();

                // Append message
                $("#file-types").append("" +
                                "Error in determining supported file types
");

                // Set controls
                if (myDropzone) {
                    myDropzone.options.acceptedFiles = "";
                    $(myDropzone.hiddenFileInput).removeAttr("accept");
                }
            }
        });

        // Get multiple files flag value
        $.ajax({
            type: "GET",
            url: "/hsapi/_internal/" + $(this).attr("data-value") + "/allow-multiple-file/",
            success: function (result) {
                json_response_multiple_file = JSON.parse(result);

                $("#file-multiple").empty();
                if (json_response_multiple_file.allow_multiple_file == true) {
                    // Append message
                    $("#file-multiple").append("");
                    $("#file-multiple").append("Multiple file upload is allowed.");

                    // Set controls
                    if (myDropzone) {
                        myDropzone.options.uploadMultiple = true;
                        $(myDropzone.hiddenFileInput).attr("multiple", 'multiple');
                    }
                }
                else {
                    // Append message
                    $("#file-multiple").append("");
                    $("#file-multiple").append("Only one file can be uploaded.");

                    // Set controls
                    if (myDropzone) {
                        myDropzone.options.uploadMultiple = false;
                        $(myDropzone.hiddenFileInput).removeAttr('multiple');
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#file-multiple").empty();

                // Append message
                $("#file-multiple").append("");
                $("#file-multiple").append("Error in determining if multiple file upload is allowed for this resource type.");

                // Set controls
                if (myDropzone) {
                    myDropzone.options.uploadMultiple = true;
                    $(myDropzone.hiddenFileInput).attr("multiple", 'multiple');
                }
            }
        })
    });

    $("#btn-remove-all-files").click(function () {
        Dropzone.forElement("#hsDropzone").removeAllFiles(true);
        $(".hs-upload-indicator").show();
    });
});<|endoftext|>


<commit_before>$(window).on('load', documentReady);
var thePath;

function documentReady() {
  thePath = window.location.pathname;
  setSideMenu();

  // Top menu color change
  $(window).on("scroll", function () {
    setColorMenu();
  });

  setColorMenu();
  function setColorMenu() {
    if ($(window).scrollTop() > 0 || thePath !== '/') {
      $("#header").addClass("active");
    } else {
      //remove the background property so it comes transparent again (defined in your css)
      $("#header").removeClass("active");
    }
  }

  // Set mobile menu
  $('#menu-toggle').on('click', function (e) {
    $('.top-menu-items').toggleClass('open');
  });

  $('top-menu-item').on('click', function(e) {
    $('.top-menu-items').removeClass('open');
  });

  $('pre code').each(function(i, block) {
    var codeText = $(this).text();
    hljs.highlightBlock(block);

    $(this).append('<button class="copy-button" data-clipboard-text=\''+codeText+'\'>
  Copy

  Copied to clipboard
</button>');
  });

  var client = new ZeroClipboard( $('.copy-button') );

  $('.copy-button').click(function() {
    var self = this;
    $(self).addClass('clicked');

    window.setTimeout(function () {
      $(self).removeClass('clicked');
    }, 5000);

  });

  //unsticky menu
  $(window).scroll(function () {
    var offsetTop = $('.footer').offset().top;
    var scrollBottom = $(window).scrollTop() + $(window).height();

    if(scrollBottom >= offsetTop) {
      $('#side-menu').css('position', 'absolute');
      $('#side-menu').css('bottom', '0');

    } else {
      $('#side-menu').css('position', 'fixed');
      $('#side-menu').css('bottom', '');
    }
  });

  // Set target="_blank" on external links
  $(document.links).filter(function() {
    return this.hostname != window.location.hostname;
  }).attr('target', '_blank');

  //check if emails are correct
  var inputfields = $('#mc-embedded-subscribe-form input');

  $('#mc-embedded-subscribe-form input').on('change paste keyup', function () {
    var emailValue = $(this).val();

    //
    if(isEmail(emailValue) && (emailValue !== '')) {
      $(this).parent().find('.button').removeClass('not-active');
    } else {
      $(this).parent().find('.button').addClass('not-active');
    }

  });

  function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
  }

  buildSearch();

}

// Set side menu
function setSideMenu() {
  var firstPartUrl = thePath.split('/')[1];
  $('.side-menu-list').each(function () {
    var parentUrl = $(this).data('parenturl');
    var firstPartUrlMenu = parentUrl.split('/')[1];
    if (firstPartUrl === firstPartUrlMenu) {
      $(this).css('display', 'block');
    }
  });

  $('.top-menu-item').each(function () {
    var parentUrl = $(this).data('parenturl');
    var firstPartUrlMenu = parentUrl.split('/')[1];
    $(this).removeClass('active');
    if (firstPartUrl === firstPartUrlMenu) {
      $(this).addClass('active');
    }
  });

  var urlInfo = getInfoFromUrl(window.location.pathname);

  if (urlInfo) {
    $('.side-menu__sub__item__text').each(function (element) {
      var elementUrlInfo = getInfoFromUrl($(this).data('url'));
      var isCurrent = '';

      if (elementUrlInfo.version === urlInfo.version) {
        isCurrent = 'selected';
        $(this).css('display', 'block');
      }

      if (elementUrlInfo.pageName === urlInfo.pageName) {
        $('#versions-dropdown').append('<option value="' + $(this).attr('href') + '"'+isCurrent+'>' + elementUrlInfo.version + '</option>')
      }
    });

    $('#versions-dropdown').css('display', 'block');
  } else {
    $('.side-menu__sub__item__text').each(function () {
      $(this).css('display', 'block');
    });
  }

  function getInfoFromUrl(url) {
    var splittedUrl = url.split('/').slice(1,-1);
    var urlInfo =  {
      pageName: splittedUrl[splittedUrl.length-1],
      version: splittedUrl[splittedUrl.length-2]
    }

    return urlInfo && urlInfo.version &&  urlInfo.version.substring(0,1) === 'v' && !isNaN(urlInfo.version.substring(1,2)) ? urlInfo : false;
  }

}

// Search function
function buildSearch() {
  var self = this;
  self.theIndex = {};

  $.getJSON(theBaseUrl + 'pages.json', function (data) {
    self.pages = data;
    $.getJSON(theBaseUrl + 'searchIndex.json', function (indexData) {
      self.theIndex = lunr.Index.load(indexData);
    }, function(error){
      console.log(error);
    });
  }, function(error) {
    console.log(error);
  });

  $('.search-bar__input').keydown($.debounce(250, function( event ) {
    if ( event.which == 13 ) {
      event.preventDefault();
    }
    console.log();
    var searchResults = self.theIndex.search($(this).val());
    console.log(searchResults);
    $('.search-results ul').empty();

    for (var sri = 0; sri < searchResults.length; sri++) {
      if(searchResults[sri]) {
        var parsedResult = self.pages[searchResults[sri].ref];
        var goToUrl = theBaseUrl + ((parsedResult.path.split(' ').join('-')).substring(1, parsedResult.path.length));
        $('.search-results ul').append('

' + parsedResult.title + '

' + parsedResult.path.split(' ').join('-') + '

' + parsedResult.content + '

');
      }
    }

  }));

  $('.search-button').click(function(event) {
    $('#search').toggleClass('active');
    $('.search-bar__input').focus();
    event.preventDefault();
    event.stopPropagation();
  });

  $('.search-bar__back').click(function(event) {
    event.preventDefault();
    event.stopPropagation();
    exitSearch(event);
  });

  //escape key
  $('.search-bar__input').keyup(function(e) {
    //escape key
    if (e.keyCode == 27) {
      exitSearch(e);
    }
    //enter key
    if (e.keyCode == 13) {

    }

  });

  function exitSearch(event) {
    event && event.preventDefault();
    event && event.stopPropagation();
    $('.search-bar__input').val('');
    $('.search-bar__input').focusout();
    $('#search').toggleClass('active');

  }
}

<commit_msg>Speed improvement. Code loads when DOM is loaded and not when the whole page is loaded"<commit_after>// $(window).on('load', documentReady);
$(document).ready(function() {
  documentReady();
});

var thePath;

function documentReady() {
  thePath = window.location.pathname;
  setSideMenu();

  // Top menu color change
  $(window).on("scroll", function () {
    setColorMenu();
  });

  setColorMenu();
  function setColorMenu() {
    if ($(window).scrollTop() > 0 || thePath !== '/') {
      $("#header").addClass("active");
    } else {
      //remove the background property so it comes transparent again (defined in your css)
      $("#header").removeClass("active");
    }
  }

  // Set mobile menu
  $('#menu-toggle').on('click', function (e) {
    $('.top-menu-items').toggleClass('open');
  });

  $('top-menu-item').on('click', function(e) {
    $('.top-menu-items').removeClass('open');
  });

  $('pre code').each(function(i, block) {
    var codeText = $(this).text();
    hljs.highlightBlock(block);

    $(this).append('<button class="copy-button" data-clipboard-text=\''+codeText+'\'>
  Copy

  Copied to clipboard
</button>');
  });

  var client = new ZeroClipboard( $('.copy-button') );

  $('.copy-button').click(function() {
    var self = this;
    $(self).addClass('clicked');

    window.setTimeout(function () {
      $(self).removeClass('clicked');
    }, 5000);

  });

  //unsticky menu
  $(window).scroll(function () {
    var offsetTop = $('.footer').offset().top;
    var scrollBottom = $(window).scrollTop() + $(window).height();

    if(scrollBottom >= offsetTop) {
      $('#side-menu').css('position', 'absolute');
      $('#side-menu').css('bottom', '0');

    } else {
      $('#side-menu').css('position', 'fixed');
      $('#side-menu').css('bottom', '');
    }
  });

  // Set target="_blank" on external links
  $(document.links).filter(function() {
    return this.hostname != window.location.hostname;
  }).attr('target', '_blank');

  //check if emails are correct
  var inputfields = $('#mc-embedded-subscribe-form input');

  $('#mc-embedded-subscribe-form input').on('change paste keyup', function () {
    var emailValue = $(this).val();

    //
    if(isEmail(emailValue) && (emailValue !== '')) {
      $(this).parent().find('.button').removeClass('not-active');
    } else {
      $(this).parent().find('.button').addClass('not-active');
    }

  });

  function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
  }

  buildSearch();

}

// Set side menu
function setSideMenu() {
  var firstPartUrl = thePath.split('/')[1];
  $('.side-menu-list').each(function () {
    var parentUrl = $(this).data('parenturl');
    var firstPartUrlMenu = parentUrl.split('/')[1];
    if (firstPartUrl === firstPartUrlMenu) {
      $(this).css('display', 'block');
    }
  });

  $('.top-menu-item').each(function () {
    var parentUrl = $(this).data('parenturl');
    var firstPartUrlMenu = parentUrl.split('/')[1];
    $(this).removeClass('active');
    if (firstPartUrl === firstPartUrlMenu) {
      $(this).addClass('active');
    }
  });

  var urlInfo = getInfoFromUrl(window.location.pathname);

  if (urlInfo) {
    $('.side-menu__sub__item__text').each(function (element) {
      var elementUrlInfo = getInfoFromUrl($(this).data('url'));
      var isCurrent = '';

      if (elementUrlInfo.version === urlInfo.version) {
        isCurrent = 'selected';
        $(this).css('display', 'block');
      }

      if (elementUrlInfo.pageName === urlInfo.pageName) {
        $('#versions-dropdown').append('<option value="' + $(this).attr('href') + '"'+isCurrent+'>' + elementUrlInfo.version + '</option>')
      }
    });

    $('#versions-dropdown').css('display', 'block');
  } else {
    $('.side-menu__sub__item__text').each(function () {
      $(this).css('display', 'block');
    });
  }

  function getInfoFromUrl(url) {
    var splittedUrl = url.split('/').slice(1,-1);
    var urlInfo =  {
      pageName: splittedUrl[splittedUrl.length-1],
      version: splittedUrl[splittedUrl.length-2]
    }

    return urlInfo && urlInfo.version &&  urlInfo.version.substring(0,1) === 'v' && !isNaN(urlInfo.version.substring(1,2)) ? urlInfo : false;
  }

}

// Search function
function buildSearch() {
  var self = this;
  self.theIndex = {};

  $.getJSON(theBaseUrl + 'pages.json', function (data) {
    self.pages = data;
    $.getJSON(theBaseUrl + 'searchIndex.json', function (indexData) {
      self.theIndex = lunr.Index.load(indexData);
    }, function(error){
      console.log(error);
    });
  }, function(error) {
    console.log(error);
  });

  $('.search-bar__input').keydown($.debounce(250, function( event ) {
    if ( event.which == 13 ) {
      event.preventDefault();
    }
    console.log();
    var searchResults = self.theIndex.search($(this).val());
    console.log(searchResults);
    $('.search-results ul').empty();

    for (var sri = 0; sri < searchResults.length; sri++) {
      if(searchResults[sri]) {
        var parsedResult = self.pages[searchResults[sri].ref];
        var goToUrl = theBaseUrl + ((parsedResult.path.split(' ').join('-')).substring(1, parsedResult.path.length));
        $('.search-results ul').append('

' + parsedResult.title + '

' + parsedResult.path.split(' ').join('-') + '

' + parsedResult.content + '

');
      }
    }

  }));

  $('.search-button').click(function(event) {
    $('#search').toggleClass('active');
    $('.search-bar__input').focus();
    event.preventDefault();
    event.stopPropagation();
  });

  $('.search-bar__back').click(function(event) {
    event.preventDefault();
    event.stopPropagation();
    exitSearch(event);
  });

  //escape key
  $('.search-bar__input').keyup(function(e) {
    //escape key
    if (e.keyCode == 27) {
      exitSearch(e);
    }
    //enter key
    if (e.keyCode == 13) {

    }

  });

  function exitSearch(event) {
    event && event.preventDefault();
    event && event.stopPropagation();
    $('.search-bar__input').val('');
    $('.search-bar__input').focusout();
    $('#search').toggleClass('active');

  }
}

<|endoftext|>


<commit_before>define(["Element"], function(DOMElement, _map, _forEach, _slice, _forIn, _makeError, _some, _every, _filter, _foldl) {
    "use strict";

    // DOM COLLECTION
    // --------------

    /**
     * Read-only array-like collection of elements
     * @name DOMCollection
     * @constructor
     * @private
     */
    function DOMCollection(elements) {
        Array.prototype.push.apply(this, _map(elements, DOMElement));
    }

    DOMCollection.prototype = {
        constructor: DOMCollection,

        /**
         * Executes callback on each element in the collection
         * @memberOf DOMCollection.prototype
         * @param  {Function} callback callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {DOMCollection}
         */
        each: function(callback, thisArg) {
            _forEach(this, callback, thisArg);

            return this;
        },

        /**
         * Checks if the callback returns true for any element in the collection
         * @memberOf DOMCollection.prototype
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {Boolean} true, if any element in the collection return true
         */
        some: function(callback, thisArg) {
            return _some(this, callback, thisArg);
        },

        /**
         * Checks if the callback returns true for all elements in the collection
         * @memberOf DOMCollection.prototype
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {Boolean} true, if all elements in the collection returns true
         */
        every: function(callback, thisArg) {
            return _every(this, callback, thisArg);
        },

        /**
         * Creates an array of values by running each element in the collection through the callback
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {Array} new array of the results of each callback execution
         */
        map: function(callback, thisArg) {
            return _map(this, callback, thisArg);
        },

        /**
         * Examines each element in a collection, returning an array of all elements the callback returns truthy for
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {DOMCollection} new DOMCollection of elements that passed the callback check
         */
        filter: function(callback, thisArg) {
            return new DOMCollection(_filter(this, callback, thisArg));
        },

        /**
         * Boils down a list of values into a single value
         * @param  {Function} callback callback function
         * @param  {Object}   memo     initial value of the accumulator
         * @return {Object} the accumulated value
         */
        reduce: function(callback, memo) {
            return _foldl(this, callback, memo);
        }
    };

    // shortcuts
    _forIn(DOMElement.prototype, function(value, key) {
        if (~("" + value).indexOf("return this;")) {
            var args = [key];

            DOMCollection.prototype[key] = function() {
                return this.invoke.apply(this, args.concat(_slice(arguments)));
            };
        }
    });
});
<commit_msg>fix issue wil collection shortcuts<commit_after>define(["Element"], function(DOMElement, _map, _forEach, _slice, _forIn, _makeError, _some, _every, _filter, _foldl) {
    "use strict";

    // DOM COLLECTION
    // --------------

    /**
     * Read-only array-like collection of elements
     * @name DOMCollection
     * @constructor
     * @private
     */
    function DOMCollection(elements) {
        Array.prototype.push.apply(this, _map(elements, DOMElement));
    }

    DOMCollection.prototype = {
        constructor: DOMCollection,

        /**
         * Executes callback on each element in the collection
         * @memberOf DOMCollection.prototype
         * @param  {Function} callback callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {DOMCollection}
         */
        each: function(callback, thisArg) {
            _forEach(this, callback, thisArg);

            return this;
        },

        /**
         * Checks if the callback returns true for any element in the collection
         * @memberOf DOMCollection.prototype
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {Boolean} true, if any element in the collection return true
         */
        some: function(callback, thisArg) {
            return _some(this, callback, thisArg);
        },

        /**
         * Checks if the callback returns true for all elements in the collection
         * @memberOf DOMCollection.prototype
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {Boolean} true, if all elements in the collection returns true
         */
        every: function(callback, thisArg) {
            return _every(this, callback, thisArg);
        },

        /**
         * Creates an array of values by running each element in the collection through the callback
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {Array} new array of the results of each callback execution
         */
        map: function(callback, thisArg) {
            return _map(this, callback, thisArg);
        },

        /**
         * Examines each element in a collection, returning an array of all elements the callback returns truthy for
         * @param  {Function} callback   callback function
         * @param  {Object}   [thisArg]  callback context
         * @return {DOMCollection} new DOMCollection of elements that passed the callback check
         */
        filter: function(callback, thisArg) {
            return new DOMCollection(_filter(this, callback, thisArg));
        },

        /**
         * Boils down a list of values into a single value
         * @param  {Function} callback callback function
         * @param  {Object}   memo     initial value of the accumulator
         * @return {Object} the accumulated value
         */
        reduce: function(callback, memo) {
            return _foldl(this, callback, memo);
        }
    };

    // shortcuts
    _forIn(DOMElement.prototype, function(value, key) {
        if (~("" + value).indexOf("return this;")) {
            var functor = function(el) { el[key].apply(el, this); };

            DOMCollection.prototype[key] = function() {
                return this.each(functor, arguments);
            };
        }
    });
});
<|endoftext|>